Skip to content

Recompute flat entity maps before skipping a stored formula backfill - #32449

Merged
charlesBochet merged 4 commits into
mainfrom
charles/formula-backfill-cache-miss
Dec 5, 2026
Merged

charlesBochet merged 4 commits into
mainfrom
charles/formula-backfill-cache-miss

Conversation

@charlesBochet

@charlesBochet charlesBochet commented Dec 4, 2026 •

Copy link
Copy Markdown
Member

Why

A stored formula field created within about 10 seconds of another metadata change ends up with no values. Its compute_storedFormulaFields operation completes in a few milliseconds, the row is deleted, and nothing is backfilled. There is no error and no FAILED row.

Seen during 2.68 QA on twenty-main: three formula fields created back to back had their operation complete in 6 to 9 ms with every record left empty.

Two things combine:

  • WorkspaceCacheService memoizes each read for 10 seconds per process. An invalidation only clears that memo in the process that invalidates. The worker keeps serving the maps it read for the previous job, without checking the Redis hash.
  • The formula handler treated "formula not in the maps" as "formula gone" and returned completed.

The row is also committed before the migration invalidates the cache, but that window is a few milliseconds. The memo is what makes this happen in practice.

Reproduced locally on main with a server and a worker: 6 of 8 isolated creations, and 15 of 30 parallel ones, were left with no value. A later backfill on the same object hides it, because the dirty pass recomputes every formula of the records it touches.

This is the same failure as #32290 (build_index, validate_foreignKey, build_recordPermissionIndexes, rebuild_object). The formula handler was not converted then.

Fix

  1. The job run marks the worker's local cache stale before loading the maps (markWorkspaceLocalCacheStale, as the access group jobs do since Mark the workspace cache stale instead of evicting it in access-group jobs #31703). The next read compares hashes with Redis and refetches only what changed. Nothing is written to Redis and other pods are not affected. This covers every deferred operation, not only formulas.
  2. The formula handler returns retryWithFreshMetadata when a formula field of its payload is not in the workspace context. The runner then recomputes the maps once from the database and runs the operation again. If the field is still missing it was really deleted and the operation is skipped, as before.
  3. payloadEntityNotFound is renamed retryWithFreshMetadata, which says what the runner does with it.
flowchart TD
  A[Job reads<br/>PENDING rows] --> B[Mark local<br/>cache stale]:::new
  B --> C[Load maps,<br/>hash checked]
  C --> D[Run handler]
  D -->|completed| E[Delete row]
  D -->|retryWithFresh<br/>Metadata| F[Recompute maps<br/>from DB, once]
  F --> G[Run handler<br/>again]
  G -->|completed| E
  G -->|still missing| H[Skip: entity<br/>deleted]
  H --> E
  classDef new fill:#d4f7d4,stroke:#2a7a2a
Loading
Local run, 12 isolated + 36 parallel creations Fields left empty Redis-wide recomputes
main (earlier run: 8 isolated + 30 parallel) 21 of 38 0
Handler change only 0 23
Handler change + stale mark 0 0

The recompute stays as a fallback for a row committed before its migration has invalidated the cache, and for entities that were really deleted.

Not covered

A formula switched from computed on read to stored inside the commit window is in the cache with its old evaluation, so it is still skipped. That needs a different signal than "not in the maps".

Screenshots

No UI change.

Test

Typecheck and lint. QA on a local server and worker, scratch database, final code:

Case Result
12 isolated and 36 parallel stored formula creations All backfilled, 0 Redis-wide recomputes
Same build, stale mark disabled All backfilled, 22 Redis-wide recomputes
Same build, stale mark and retry disabled (main behavior) 26 of 48 fields left empty
Formula expression updated Every record recomputed
Field deleted before its job runs One recompute, operation skipped, row removed
Redis still holding the maps from before the creation One recompute, every record backfilled

Redis cache traffic for the same 48 creations, server and worker together:

Variant Hash reads Data reads Writes Data written
main 1,192 96 1,855 ~4.0 GB
Handler change only 1,375 139 2,532 ~4.7 GB
This PR 1,143 100 1,746 ~3.6 GB

The stale mark costs at most a few hash reads per job run and no write. Each recompute it avoids is about 33 MB written on this workspace.

View guided diff

Copilot AI balanced review requested due to automatic review settings December 4, 2026 20:53
@twenty-ci-bot-public

twenty-ci-bot-public Bot commented Dec 4, 2026 •

Copy link
Copy Markdown

🚀 Preview Environment Ready!

Your preview environment is available at: https://precision-steel-jackson-possible.trycloudflare.com

This environment will automatically shut down after 5 hours.

@twenty-ci-bot-public

twenty-ci-bot-public Bot commented Dec 4, 2026 •

Copy link
Copy Markdown

🤖 PR Review

Check Result
🔍 Build safety ⏭️ skipped — external-only
🧭 Triage ⏭️ skipped — external-only
📐 Quality ✅ passed
🛡️ Security ✅ passed
🚦 Auto-approve 👀 needs review — Complexity is medium
🔐 Permissions ⏭️ skipped: no endpoint permission change

🛡️ Security Review

✅ No high-severity vulnerabilities detected.


🚦 Auto-approve

🙋 Manual review recommended for the following reason(s):

  • Complexity is medium

  • 🧠 Complexity: medium

  • 📏 Size: +52 / -6 lines across 8 file(s)


View details

Automated pre-review — human approval still required.

@twenty-ci-bot-public

twenty-ci-bot-public Bot commented Dec 4, 2026 •

Copy link
Copy Markdown

✅ Quality review · no findings

Safe to merge — no high-level findings

High-level — The outcome rename to retryWithFreshMetadata, the formula-field check against the cached object's fieldIds, and marking the workspace local cache stale before persisted runs all reuse the refresh-then-retry path that already exists in DeferredWorkspaceOperationRunnerService; the earlier ORM-context finding was answered by the author, so it isn't raised again.
Low-level — No rule violations found — 424 rule questions over 8 piece(s) of 8 file(s)


Reviewed against the pr-review standard — high-level then low-level. Advisory; human review still required. Run details.

}: DeferredWorkspaceOperationExecutionArgs<
DeferredWorkspaceOperationPayload<'compute_storedFormulaFields'>
>): Promise<DeferredWorkspaceOperationOutcome> {
const hasEveryFormulaField =

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Nit · High-level · extend existing seams

The payloadEntityNotFound check reads the ORM workspace context instead of the runner-provided allFlatEntityMaps, so the runner's refresh-and-retry never covers it

The sibling handlers (e.g. rebuild-object-deferred-operation-handler.service.ts:31) look up the entity in allFlatEntityMaps for keys declared in metadataNamesToLoad, and DeferredWorkspaceOperationRunnerService (deferred-workspace-operation-runner.service.ts:427-441) invalidates and reloads only those keys before the second attempt. Here the field lookup goes through getWorkspaceContext() while metadataNamesToLoad lists only objectMetadata, so if the field map is stale the retry hits the same stale map, logs "metadata no longer exists" and drops the backfill. Fix: add 'fieldMetadata' to metadataNamesToLoad and check allFlatEntityMaps.flatFieldMetadataMaps in the handler, then delete hasEveryFormulaField.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changed. The runner expands metadataNamesToLoad through getMetadataNamesToLoadForWorkspaceMigration, so objectMetadata already loads fieldMetadata, and invalidateFlatEntityMaps goes through withDerivedFieldMetadataMaps, so the retry refreshes flatFieldMetadataMapsOrm too. The check reads the ORM context on purpose: it is the snapshot the computation itself uses, and its freshness is tracked separately from allFlatEntityMaps.

CoreTeamTwenty
CoreTeamTwenty previously approved these changes Dec 4, 2026

@CoreTeamTwenty CoreTeamTwenty left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Auto-approved — cleared automated quality and security review and is low-complexity.

  • Quality: passed — 1 nit(s)
  • Security: passed
  • Auto-approve: passed — complexity low

Automated approval — a human still merges, and this is re-evaluated on every push.

@greptile-apps

greptile-apps Bot commented Dec 4, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5RetriggerView in Greptile

[Medium impact] The PR appears safe to merge.

Summary

The handler now returns payloadEntityNotFound when a requested formula field is missing from the ORM workspace context.

  • Stored formula backfills check for every field before they start.

Known limitation acknowledged by charlesBochet: switching an existing formula from computed-on-read to stored can still be skipped when cached settings are stale. The PR explicitly defers that case.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Check requested formula fields] --> B{All fields found?}
  B -->|Yes| C[Backfill records]
  B -->|No| D{Maps already refreshed?}
  D -->|No| E[Refresh maps including ORM field maps]
  E --> A
  D -->|Yes| F[Skip deleted field operation]
Loading

Reviews (1) · Last reviewed commit: "Recompute flat entity maps before skippi..." · Reviewed by Greptile

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The cache consistency check can accept a new formula missing from its cached object's fieldIds, silently leaving it uncomputed instead of triggering recomputation.

1 open issue
What changed in this PR

Extends the deferred-operation retry mechanism from #32290 to stored-formula backfills, addressing silent skips caused by stale metadata.

Changes:

  • Adds a formula-field existence check using the ORM workspace context.
  • Returns payloadEntityNotFound when fields are missing, triggering the runner’s existing refresh-and-retry flow.
File Description
packages/​twenty-server/​src/​engine/​core-modules/​stored-formula-field/​services/​stored-formula-field-computation.service.ts Adds the formula-field existence check.
packages/​twenty-server/​src/​engine/​core-modules/​stored-formula-field/​deferred-operation-handlers/​compute-stored-formula-fields-deferred-operation-handler.service.ts Signals missing metadata before starting backfill.

Review effort: Balanced

@CoreTeamTwenty
CoreTeamTwenty dismissed their stale review December 4, 2026 21:03

Superseded — re-approving the latest commit.

CoreTeamTwenty
CoreTeamTwenty previously approved these changes Dec 4, 2026

@CoreTeamTwenty CoreTeamTwenty left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Auto-approved — cleared automated quality and security review and is low-complexity.

  • Quality: passed
  • Security: passed
  • Auto-approve: passed — complexity low

Automated approval — a human still merges, and this is re-evaluated on every push.

The worker memoizes workspace cache reads for 10 seconds, so a job starting right after a metadata change read maps without the new entity. Marking the local cache stale forces a hash check against Redis without invalidating it for other pods.

Rename the payloadEntityNotFound outcome to retryWithFreshMetadata.
@CoreTeamTwenty
CoreTeamTwenty dismissed their stale review December 5, 2026 10:28

Auto-approval withdrawn — this PR no longer meets the auto-approve criteria.

@charlesBochet
charlesBochet merged commit e497cc2 into main Dec 5, 2026
280 of 284 checks passed
@charlesBochet
charlesBochet deleted the charles/formula-backfill-cache-miss branch December 5, 2026 11:16
charlesBochet added a commit that referenced this pull request Dec 5, 2026
Backport to `v2.68` for a v2.68.1 patch.

## Why

`twenty/v2.68.0` was tagged at `7feaaa1` (#32441) and is on staging, not
prod. Fixes merged on main since then need to ship with 2.68, but main
is already on 2.69.0 (#32446) and release tags are immutable, so they go
out as v2.68.1 from this branch.

## Changes

Clean cherry-picks (`-x`), no conflicts:

- #32450 Keep SDK client type declarations in the server image (AI
component preview fails in Docker images)
- #32449 Recompute flat entity maps before skipping a stored formula
backfill (formula fields left empty, found in 2.68 QA)
- #32452 Answer not found for a deleted chat channel while its cleanup
holds the lock (integration shard 14 failure)
- #32372 Build the RLS workspace member predicates once per request
(prod p99 latency)

`.github/workflows` is unchanged on main since the tag, so the tag
workflow should not 403.

No UI change, no screenshots.


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/twentyhq/twenty/pull/32471?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="View guided diff"
src="https://www.cubic.dev/buttons/review-in-cubic-light.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants