Repository navigation
[v2.68] Backport fixes for v2.68.1 - #32471
Conversation
## Why In Docker images, the AI component preview fails for any generated component that imports the client SDK: ``` component.tsx:2:35 TS2307: Cannot find module 'twenty-client-sdk/metadata' or its corresponding type declarations. ``` The preview typecheck (#29412) reads the SDK types from the generated client archive, which is built from the template copied to `dist/assets/twenty-client-sdk`. The image cleanup step deletes every `.d.ts` under the server `dist`, template included, so every archive built from an image has no declarations. On twenty-main the template holds 13 files: `package.json` and the JS bundles, nothing under `dist/core` or `dist/metadata`. Local dev is not affected, since the template is resolved from the workspace package there. ## How the declarations reach the preview build The preview runs in Lambda, but both Lambdas get the SDK types from the server image. ```mermaid flowchart TD sdk["Image build:<br/>client SDK<br/>JS + .d.ts"] copy["Image build:<br/>copied to<br/>dist/assets"] clean["Image build:<br/>cleanup deletes<br/>every .d.ts"] template["SDK template<br/>in the image"] pack["Server:<br/>packs template<br/>into generator"] generator["Lambda:<br/>template +<br/>core client"] archive["SDK archive<br/>in file<br/>storage"] read["Server:<br/>reads .ts and<br/>package.json"] builder["Lambda:<br/>typechecks<br/>component"] schema["Workspace<br/>GraphQL<br/>schema"] source["AI component<br/>source"] entry{"Entry .d.ts<br/>in archive?"} failure["TS2307<br/>module<br/>not found"] success["Preview<br/>built"] sdk --> copy --> clean --> template --> pack --> generator --> archive --> read --> builder --> entry schema --> generator source --> builder entry -- no --> failure entry -- yes --> success classDef changed fill:#fde68a,stroke:#b45309,color:#111827 class clean changed ``` The highlighted step is the one this PR changes: the cleanup now skips the template. `package.json` in the archive maps `./core` and `./metadata` to `dist/<name>/index.d.ts`. The core client generated from the workspace schema is reached through `dist/core/index.d.ts`, so without that file the per-workspace types are in the archive but cannot be resolved either. | | Template in the image | Archive | Preview of a component importing the SDK | | --- | --- | --- | --- | | Before | 13 files, no `.d.ts` | generated core sources, no entry declarations | TS2307 on `twenty-client-sdk/core` and `/metadata` | | After | 82 files, 69 `.d.ts` | entry declarations and metadata types included | typechecked against the workspace schema | ## Fix The cleanup skips `dist/assets/twenty-client-sdk`. The server's own declarations are still removed. ## Follow-up Archives already stored were built without declarations. If they are not regenerated on their own, bumping `SDK_CLIENT_GENERATION_KEY` forces it, at the cost of rebuilding every SDK layer on first use. Left out of this PR on purpose. ## Screenshots No UI change. ## Test The `find` expression was checked on a scratch tree: declarations under the template are kept, the others are deleted. No full image build. <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/twentyhq/twenty/pull/32450?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. --> (cherry picked from commit 88967d4)
…32449) ## 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 #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. ```mermaid 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 ``` | 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. <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/twentyhq/twenty/pull/32449?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. --> (cherry picked from commit e497cc2)
…he lock (#32452) ## Why Integration shard 14 keeps failing on `chat-channel-deletion-and-summaries.integration-spec.ts`, test "keeps chats out of a deleted destination that a stale cache still lists": it expects `CHAT_CHANNEL_NOT_FOUND` and gets `CHAT_CHANNEL_BUSY`. It failed three times in a row on the 2.69.0 version bump PR (#32446) and on unrelated PRs the same day. Since #32294, deleting a channel queues `MoveDeletedAgentChatChannelThreadsJob`, which takes the channel's deletion advisory lock while it moves leftover threads to General. A request that files or moves a thread into that channel right after the deletion goes through `lockAgentChatChannelForThreadWriteOrThrow`, which tried the shared lock first and threw busy before it ever checked that the channel still exists. So a channel that is already gone answered "busy" for as long as its cleanup job ran, in tests (jobs run in-process) and in production. ## What `lockAgentChatChannelForThreadWriteOrThrow` still tries the lock first, then checks the channel row, and only then decides: - channel gone: `CHAT_CHANNEL_NOT_FOUND`, whether or not the lock was free - channel still there and lock held by a deletion: `CHAT_CHANNEL_BUSY`, as before A deletion in progress keeps its channel row until the end, so writes during a user-triggered deletion still get busy. The existing util spec is updated for the new order, with one case for a missing channel whose lock is held. ## Screenshots No UI change. <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/twentyhq/twenty/pull/32452?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. --> (cherry picked from commit 7906669)
## Why Prod-eu p99 request latency roughly doubled after channel visibility gave each workspace member an individual role (Nov 25-26). Reproduced locally on seed data with a per-request probe (CPU, pg time, query count, event-loop delay) and CDP profiles: the extra time is Node CPU in the permission read path, not the database. #32029 removed the per-request recomputation of the principal's own permissions. The heaviest scans left are `findWorkspaceMemberBoundPredicates` and `findWorkspaceMemberRelationPredicates`: they walk every role × every object of the workspace (42,546 object entries per call in a 1,012-role workspace). Their cost grows with the number of members. They ran twice in `PermissionsMetadataMapsService.load`, and up to 4 more times per message read through `AccessGroupReadService.findPrincipalWorkspaceMember`. ## What ```mermaid flowchart LR A[roles<br/>permissions] --> B[build once<br/>per request] B --> M[metadata<br/>maps] M --> C[bound<br/>predicates] M --> D[relation<br/>predicates] style B fill:#d4f7d4 ``` - New pure util `buildRlsWorkspaceMemberPredicates(rolesPermissions)` walks the roles once. It returns `{ bound, relation }`: the predicates bound to a workspace member, and the workspace member relation predicates deduplicated by member field. `withRlsWorkspaceMemberPredicates(maps)` attaches them to a metadata maps object. - `PermissionsMetadataMaps` now carries `rlsWorkspaceMemberPredicates`. `PermissionsMetadataMapsService.load` builds it, once per principals through its existing per-principals cache. - `findWorkspaceMemberBoundPredicates` and `findWorkspaceMemberRelationPredicates` are removed. `load` and `AccessGroupReadService` read the built lists from the metadata maps. The access-group sync listener and the RLS relation value cache build them once where they already load `rolesPermissions`. - `isWorkspaceMemberUpdateAffectingAccessGroups` and `findWorkspaceMemberRelationFieldNamesOfObject` take `rlsWorkspaceMemberPredicates` instead of `rolesPermissions`. - Related record path narrowing (`omitPermissionsUnableToReadField`) is unchanged and carries `rlsWorkspaceMemberPredicates` over as is. Nothing reads the predicates from narrowed maps; only `load` and `AccessGroupReadService` read them, both from the request's unnarrowed maps. No cache, no `WeakMap`, no behaviour change, migration, flag or API change. Unit spec fixtures that build a full `PermissionsMetadataMaps` go through `withRlsWorkspaceMemberPredicates`. One integration helper now gets the lists from `PermissionsMetadataMapsService.load`. ## Work per request Counted on a 1,012-role workspace by instrumenting the scans: | Full role × object scans per request | main | This PR | |---|---|---| | Message or calendar read | 6 | 1 | | Other reads | 2 | 1 | Timings from my local runs are not reliable enough to quote: the machine was at a load of ~13 on 10 cores during the last benchmark. On v2.66.3 at 1,012 roles, local CDP profiles put these two scans at about a fifth of busy CPU. At prod sizes (≤123 roles) one scan is about 5k entries. ## Not in this PR - `isObjectRestrictedByRlsRule`: one pass over the roles per related record path. It is cheap per call and correct on narrowed maps as is. - The per-path clone in `omitPermissionsUnableToReadField`, which matters at 1,000+ roles - The access group compact id lookup that runs on the writer for each read of an access-group object - The extra source-record queries #31708 added to timeline activity reads (cherry picked from commit e2d5d5e)
Confidence Score: 5/5
[High impact] The backport appears safe to merge. SummaryBackports four fixes for v2.68.1:
No actionable issues found. Tests and image builds were not run. Acknowledged deferrals by charlesBochet in the backported commit descriptions: rebuilding previously stored SDK archives was intentionally excluded; formula changes from computed-on-read to stored during the commit window remain outside this fix. Diagram%%{init: {'theme': 'neutral', 'htmlLabels': false}}%%
flowchart TD
A[Worker finds pending operations] --> B[Mark local cache stale]
B --> C[Load metadata]
C --> D[Run handler]
D -->|Completed| E[Remove operation]
D -->|Metadata missing| F[Recompute metadata once]
F --> G[Run handler again]
G -->|Completed| E
G -->|Still missing| H[Skip deleted entity]
H --> E
Reviews (1) · Last reviewed commit: "Build the RLS workspace member predicate..." · Reviewed by Greptile |
🤖 PR Review
🛡️ Security Review✅ No high-severity vulnerabilities detected. 🚦 Auto-approve🙋 Manual review recommended for the following reason(s):
Automated pre-review — human approval still required. |
🟡 Quality review · 1 finding
High-level — No PR description was available to check the diff against, and the diff bundles four unrelated server and Docker fixes that should be separate PRs; architecture and rollout look fine (predicates are now derived once into PermissionsMetadataMaps, retries reuse the runner's existing cache-invalidation seam, and there are no migrations or breaking schema changes). 💬 1 inline comment on the diff. Reviewed against the |
| # Clean server build output (type declarations and compiled tests are not needed at runtime; | ||
| # source maps are kept because twenty-infra extracts them from the image for Sentry uploads) | ||
| RUN find /app/packages/twenty-server/dist -name '*.d.ts' -delete \ | ||
| RUN find /app/packages/twenty-server/dist -name '*.d.ts' -not -path '/app/packages/twenty-server/dist/assets/twenty-client-sdk/*' -delete \ |
There was a problem hiding this comment.
🟡 Nit · High-level · build strategy
PR bundles at least four unrelated changes: Docker client-sdk .d.ts retention, AI chat channel lock ordering, deferred-operation stale-metadata retry, and the RLS workspace-member predicate memoization
Each touches a different area (docker image, ai-chat, workspace-migration runner and stored formulas, permissions), so one PR can't be reviewed, reverted or bisected cleanly, and there's no description to reconcile them against. Split them into one PR per logical change, or at least list each change and why it's here in the description.
Backport to
v2.68for a v2.68.1 patch.Why
twenty/v2.68.0was tagged at7feaaa1(#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:.github/workflowsis unchanged on main since the tag, so the tag workflow should not 403.No UI change, no screenshots.