Repository navigation
fix(platform): harden erasure, legal-hold and audit-log paths - #3246
Merged
Merged
Conversation
core/audit_logs/helpers.ts (843 lines) was the 0.4 audit writer/readers
over `ctx.db.query('auditLogs')`: nothing dispatched it (no
handler_names entry, both ctx-shim tables import createAuditLog from
domains/audit_logs/service.ts), its only importer was its own test, and
it dragged the frozen v1 legacy hash (used nowhere else — the live
writer states "no v1 fallback here") and a second, divergent copy of the
audit vocabulary in core/audit_logs/types.ts along with it.
Delete the module, its test, computeAuditHashV1Legacy/canonicalizeV1Legacy
and the core types copy; the four remaining importers (emit.ts,
build_audit_context.ts, knowledge/index-health.ts, the app's audit-log
queries hook) now read the one vocabulary in domains/audit_logs.
Finding: compliance-1.
Retry of a receipt blocked AT FILING (effective_at_ms still NULL — the hold gate answered before the policy branch ever ran) went straight to 'pending' + an immediate processor job, skipping the dual approval and cooling-off window requestErasure enforces; a single admin could file against a held subject and Retry once the hold lifted with no second admin and no cancel window. The re-arm UPDATE also had no status predicate, so two Retries racing, or a Retry racing a finishing cascade, could flip a settled receipt back to pending and run the cascade twice. - retryErasure re-arms with a status compare-and-set (409 NOT_RETRIABLE on zero rows, nothing enqueued) and routes a filing-time block through the request-time policy: dual approval parks it via the shared parkForDualApproval (the approvals row + bell requestErasure writes), otherwise it schedules behind the cooling-off window. Partial/failed receipts and execution-time blocks keep the immediate re-run. - processErasure's execution-time hold block is audited (gdpr_erasure_blocked_by_hold, atExecution: true), emits the gdpr_erasure hint and clears the started_at_ms stamp the claim set, so the receipt timeline explains why a scheduled erasure stopped. - requestErasure only records 'rate_limited' for RateLimitExceededError; a limiter outage is logged and rethrown instead of being written into the hash chain as a denial. - New agentRuns pass: project_agent_runs the subject started are pseudonymised (started_by → erased-user, feedback cleared), the table the retention hold already treats as the starter's data. Findings: compliance-3, compliance-v1, compliance-7, compliance-10, compliance-4.
The one-live-request-per-subject index (0031) covered only pending/running while requestErasure's duplicate handler and the Retry door treat blocked and partial receipts as live. A second filing against a subject whose receipt sat blocked under a hold minted a twin; once the hold lifted both could run the cascade — two receipts and two gdpr_erasure_executed rows for one erasure. Migration 0081 settles existing duplicates (the furthest-along receipt per subject survives, the rest become 'cancelled' with a system reason) and recreates the index over pending/running/blocked/partial. The ALREADY_PENDING copy in en/de/fr names the open states, the docs page describes the re-filing refusal and the policy a filing-time-blocked Retry now honours, and the integration check files against a blocked receipt (409 ALREADY_PENDING with its id) and zeroes the cooling-off window before the retry it drives to done. Finding: compliance-2 (docs also cover compliance-3).
GET /api/app/legal-holds returned every hold — reason, matter name, who placed it, why it was released — to any org member, while the sibling /by-target strips exactly those fields for non-admins and every other admin surface in the router gates inline. Members keep /targets (the badge read) and the stripped /by-target view; a route test pins member → 403 on the list and 200 on /targets. Finding: compliance-5.
sweepAuditLogs stopped its prefix walk only at a row the held custodian ACTED in (actor_id); rows ABOUT them (resource_type 'user', resource_id = held — role changes, erasure denials, the hold placement itself) were reaped, while the erasure scrub and the docs' "a hold blocks every retention pass for the target" define those rows as the subject's. The walk now stops on either side of the row, same prefix-only semantics. Finding: compliance-6.
GET /audit-logs/errors passed an unclamped limit to SQL (`?limit=-5` reached `LIMIT -4`, a Postgres 500); listAuditLogs now clamps to 1..200 for every caller and the route validates through the same zod shape as the sibling list (400 on an invalid limit). The CSV export quoted only commas, quotes and newlines: a member-titled document `=HYPERLINK(...)` executed in the admin's spreadsheet on open. csvCell prefixes cells starting with = + - @ tab or CR with an apostrophe before the ordinary quoting runs. Findings: compliance-8, compliance-9.
…y lane checkErasure zeroes coolingOffHours so the Retry of the hold-blocked receipt (which now honours the filing policy) finishes inside the lane, but left 0 on disk; the governance-tail lanes downstream cancel inside a real window and read the policy back expecting 1, as main's lane left it. Restore 1 once the retried receipt is done.
A SERIALIZABLE snapshot is fixed at the transaction's first statement, so a retry that lost on a hot row (the audit chain head, bumped by every audited write of an org) re-collides whenever another writer commits before the retry reaches the row: an advisory lock taken inside the transaction is acquired after the snapshot and protects nothing. Under a burst all five attempts lose and the caller sees the 40001 (compliance-x1). A callback that knows which resource it lost on now marks the failure with a retry-queue key. The next attempt reserves one connection, takes a session-level advisory lock on the key BEFORE opening the transaction, runs the callback, commits and unlocks on that same connection: its snapshot post-dates the writer it lost to, and writers that take the transaction-level lock on the same key inside their own transaction queue behind it instead of bumping the row underneath it. Runners without `reserve` keep the plain retry. The queued transaction gets postgres.js-shaped savepoints; a COMMIT the server answers with ROLLBACK is surfaced, never reported as success.
`lockChainHead` locked the per-org chain head with SELECT ... FOR UPDATE inside the caller's SERIALIZABLE transaction. Any appender whose head was bumped between its snapshot and that lock aborted with 40001, and under a burst of audited writes for one org (the task-agent settle jobs behind POST /api/app/tasks in the integration proof) every retry lost again: the route answered 500 and the proof truncated at the tasks/collab lanes (compliance-x1). The head statements now run behind a transaction-level advisory lock on the org's queue key, and a 40001/40P01 they raise is marked with that key so the caller's next attempt takes the session lock before BEGIN (see `transactSerializable`). Concurrent appenders queue; each wastes at most one attempt. Unit tests pin the lock order and the marking; the integration proof gains a lane where eight overlapping serializable appenders for one org all commit with a valid, linear chain.
A duplicate live receipt that 0081 moves to `cancelled` could still own a pending approvals-inbox card from dual-approval parking; the card stayed decidable although `confirmAndScheduleErasure` no-ops on a non-pending receipt. The settle step now closes those rows the way `cancelErasure` does (status rejected, reviewed_at_ms, and a supersededBy marker naming the surviving receipt, the 0074 shape). Proved on a real Postgres with migrations 0001-0080 applied and seeded twins: the loser's pending card is rejected, the survivor's and every other card stay untouched.
The alreadyPending copy and the DSAR docs said an open receipt could be retried or cancelled; `cancelErasure` only accepts a pending receipt, so a blocked or partial one can only be retried and a running one neither. The sentence now promises Retry and qualifies Cancel with the pending window, in all three locales and the three docs pages.
oxlint (unbound-method, no-shadow) in the shared workspace's own lint task; behaviour unchanged.
This was referenced Sep 6, 2026
larryro
added a commit
that referenced
this pull request
Sep 6, 2026
A retry queued on one key drops the others: a task comment that lost at the org's audit chain head was re-marked with the task key by its outer queue, so its retry took the task's session lock alone, met the other tasks' commenters at the chain head again and lost there — the storm #3246 removed came back for cross-task bursts. Marks now nest. `markRetryQueueKey` prepends an outer key to the keys an inner callback already put on the error (never twice), so the list reads in the callback's own acquisition order; `beginQueued` takes the session locks in that order before BEGIN and unlocks in reverse; the retry loop adopts the whole list whenever a marked failure arrives. Every first attempt takes its transaction-level locks in the same order, so a queued retry and a first attempt never hold two keys in opposite orders. `retryQueueKeysOf` exposes the list; `retryQueueKeyOf` keeps answering the outermost key.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Hardens the compliance slice — the erasure receipt lifecycle, the legal-hold register, audit-log retention and the audit-log read/export surface — deletes the dead Convex-era audit writer, and (repair round) stops the audit chain-head 40001 storm at the root: concurrent audited writes for one org now queue instead of exhausting their retries and answering 500. One concept per commit.
Findings fixed
lockChainHeadlocked the per-org head withSELECT … FOR UPDATEinside the caller's SERIALIZABLE transaction; any appender whose head was bumped between its snapshot and that lock aborted with 40001, and under a burst every plain retry lost again (the snapshot is fixed at the transaction's first statement, so no lock taken inside the transaction can help). Root fix in two parts: (1)@tale/shared/db/serializable— a serialization failure can carry a retry-queue key (markRetryQueueKey); the next attempt reserves one connection, takes a SESSION advisory lock on the key BEFOREBEGIN, runs the callback, commits and unlocks on that connection, so its snapshot post-dates the writer it lost to. (2)audit_logs/service.ts— the head statements run behindpg_advisory_xact_lockon the org's queue key (a first attempt queues behind a queued retry instead of bumping the head underneath it) and a 40001/40P01 they raise is marked with the key. Each appender wastes at most one attempt. Tests:serializable.test.ts(queued protocol, plain retry stays plain, rollback/unlock/release, COMMIT-answered-ROLLBACK, savepoints),audit_logs/service.test.ts(lock order; 40001 marked, 23505 not), and a new itest lane (eight overlapping serializable appenders for one org).core/audit_logs/helpers.ts(843-line Convex-era writer/readers), its test,computeAuditHashV1Legacy/canonicalizeV1Legacyand the divergentcore/audit_logs/types.tscopy deleted; the four surviving importers readdomains/audit_logs/types.ts/service.ts.0081_gdpr_erasure_live_index_covers_blocked_partial.sql: settles duplicate live receipts, recreatesgdpr_erasure_one_live_per_subjectoverpending/running/blocked/partial(the set the 23505 handler and Retry already treat as live). Repair round: a cancelled loser's pending approvals-inbox card is settled as rejected (0074 shape,supersededBy= the survivor).alreadyPendingcopy (en/de/fr) and the DSAR docs page (en/de/fr) updated; itest files a second request against a blocked receipt → 409ALREADY_PENDINGwith its id.retryErasureroutes a receipt blocked AT filing (effective_at_ms IS NULL) through the request-time policy: dual approval parks it via the sharedparkForDualApproval(the approvals row + bellrequestErasurewrites), otherwise it schedules behind the cooling-off window; partial/failed and execution-time blocks keep the immediate re-run.… AND status IN ('blocked','partial','failed') RETURNING id); zero rows → 409NOT_RETRIABLE, nothing enqueued/audited.agentRunscascade pass pseudonymisesproject_agent_runsthe subject started (started_by → erased-user,feedback = NULL), counted on the receipt.GET /api/app/legal-holdsis admin-gated like every other register surface;/targetsand the stripped/by-targetstay member-readable. Newlegal_holds/routes.test.ts.sweepAuditLogsalso stops the prefix walk at a row ABOUT the held custodian (resource_type = 'user' AND resource_idheld), matching the erasure scrub's two-sided definition.processErasureis audited (gdpr_erasure_blocked_by_hold,atExecution: true), emits thegdpr_erasurehint and clearsstarted_at_ms.listAuditLogsclampslimitto 1..200 for every caller;/audit-logs/errorsvalidateslimitthrough the sibling zod shape (400 on invalid).csvCellprefixes= + - @ \t \rcells with'before quoting (OWASP CSV-injection mitigation).rate_limitedforRateLimitExceededError; anything else is logged and rethrown.Skipped
None.
Review round 1 — what changed
fix(shared): queue a serializable retry on the row it lost to+fix(platform): queue audit chain appenders instead of storming 40001).8b4a5e33a): NOT reworded — the repair brief forbids force-pushing or rewriting the branch history, and this PR squash-merges under its own ≤72-char title, so that header never reachesmain.csvCellstill neutralises a leading-in id columns (nanoid ids can start with-; OWASP-complete neutralisation of every cell is the safer default for an export whose reader is the org's most privileged one — restrict to free-text columns in a follow-up if id fidelity in spreadsheets ever matters); theagentRunslabel and the un-metered Retry stay as noted.Tests & gates observed
bunx tsc --noEmit→ exit 0;bunx oxlint --type-aware→ exit 0 (services/platform, on the fixed tree);bun run lint+bun run testin packages/shared → exit 0,Test Files 22 passed (22)/Tests 214 passed (214).audit_logs/service.test.ts+organizations/service.test.ts→Test Files 2 passed (2)/Tests 18 passed (18)(the organizations recording tx now answers the queue-lock SELECT).bun run check(repair round) →Tasks: 39 successful, 40 total;@tale/platform:test→Test Files 529 passed (529); shared/docs/web/ui suites green; the one red task was@tale/platform#test:ui(Test Files 5 failed | 451 passed (456)/Tests 9 failed | 3503 passed (3512): chat-surface, connectors-settings, data-residency-settings, enterprise-sso-form, providers-settings — none touched by this branch, run under itest load); rerun of those five alone →Test Files 5 passed (5)/Tests 136 passed (136).bun run knip:check→ exit 0 (one pre-existing configuration hint:cron-parserinservices/platform/knip.config.ts).run-itest.sh, real Postgres + MinIO), two stacks running concurrently on the fixed tree (compliance-fix-itest-a/b.log): a →[itest] 476/477 checks passed across 134/134 lanes(onlywebdav re-home, pre-existing red); b →[itest] 475/477 checks passed across 134/134 lanes(webdav re-home+messages: concurrent appends each take their own slot — appends=12, failed=2, the conversations lane overchat/store.ts appendMessageRow, a plainINSERT … ON CONFLICT DO NOTHINGslot loop with no transaction and no audit write — passed in stack a and in both pre-fix runs; load flake, not touched here). A third run after the 0081 approvals settle (compliance-fix-itest-c.log, concurrent withbun run check) →[itest] 475/477 checks passed across 134/134 lanes(same two lanes). New lane in every run:PASS audit chain: a burst of serializable appenders for one org all commit — committed=8/8 rejected=0 chainValid=true headNamesLatest=true attempts=15. NoRUN TRUNCATEDanywhere.compliance-prefix-lane.log):FAIL audit chain: a burst of serializable appenders for one org all commit — committed=6/8 rejected=2 (PostgresError: could not serialize access due to concurrent update; …) attempts=30.tale-dbwith 0001–0080 applied via psql and seeded twins (running survivor + blocked loser with a pending card; blocked/partial pair; unrelated org/subject rows): loser →cancelled/system, its card →rejectedwithsupersededBy= survivor, every other receipt and card untouched, index recreated over the four live statuses.Notes for the reviewer
committed=6/8 rejected=2 (PostgresError: could not serialize access due to concurrent update; …) attempts=30, logcompliance-prefix-lane.log); after it, both concurrent stacks reportcommitted=8/8 rejected=0 chainValid=true headNamesLatest=true attempts=15(2N−1: every loser wastes exactly one attempt). All 134 lanes ran in both concurrent stacks — noRUN TRUNCATED, everytasks/collablane green. The pre-fix two-stack repro on this branch (compliance-prefix-itest-{a,b}.log) did NOT truncate — the storm on main is machine-load dependent; the lane is the reliable reproduction.sql.reserve(postgres.js); runners without it (test stubs) keep the plain retry. The queued transaction is opened by hand (BEGIN ISOLATION LEVEL SERIALIZABLE…COMMIT) because postgres.js cannotbeginon a reserved connection;savepointfollows postgres.js's shape,prepareis refused. ACOMMITthe server answers withROLLBACK(aborted transaction) is surfaced, never reported as success. The advisory-lock class72_085_002is the only two-argument advisory lock in the codebase (migration runner and sandbox/skill locks use the one-argument bigint form), so it conflicts with nothing else.retryErasuredoes NOT charge thegovernance:dsar_requestlimiter (a Retry re-arms an existing receipt; the limiter meters filings).dataSubjectRequests.categories.<key>with a raw-key fallback; every 0.5 pass name already falls back —agentRunsjoins that pre-existing gap; a 16-key × 3-locale label sweep is its own small PR.cancelledwithcancelled_by = 'system'(the drawer shows the id verbatim when no user name resolves).checkErasurelane zeroescoolingOffHoursbefore the retry of the hold-blocked receipt and spends all 5 of the admin's daily DSAR filings; the existing end-of-lane limiter reset covers downstream lanes.