Skip to content

fix(platform): harden erasure, legal-hold and audit-log paths - #3246

Merged
larryro merged 12 commits into
mainfrom
fix/compliance-hold-retention-erasure
Sep 6, 2026
Merged

larryro merged 12 commits into
mainfrom
fix/compliance-hold-retention-erasure

Conversation

@larryro

@larryro larryro commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

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

  • compliance-x1 — audit chain-head 40001 storm. lockChainHead locked the per-org 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 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 BEFORE BEGIN, 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 behind pg_advisory_xact_lock on 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).
  • compliance-1 — core/audit_logs/helpers.ts (843-line Convex-era writer/readers), its test, computeAuditHashV1Legacy/canonicalizeV1Legacy and the divergent core/audit_logs/types.ts copy deleted; the four surviving importers read domains/audit_logs/types.ts / service.ts.
  • compliance-2 — migration 0081_gdpr_erasure_live_index_covers_blocked_partial.sql: settles duplicate live receipts, recreates gdpr_erasure_one_live_per_subject over pending/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). alreadyPending copy (en/de/fr) and the DSAR docs page (en/de/fr) updated; itest files a second request against a blocked receipt → 409 ALREADY_PENDING with its id.
  • compliance-3 — retryErasure routes a receipt blocked AT filing (effective_at_ms IS NULL) 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 and execution-time blocks keep the immediate re-run.
  • compliance-v1 — the re-arm is a status compare-and-set (… AND status IN ('blocked','partial','failed') RETURNING id); zero rows → 409 NOT_RETRIABLE, nothing enqueued/audited.
  • compliance-4 — new agentRuns cascade pass pseudonymises project_agent_runs the subject started (started_by → erased-user, feedback = NULL), counted on the receipt.
  • compliance-5 — GET /api/app/legal-holds is admin-gated like every other register surface; /targets and the stripped /by-target stay member-readable. New legal_holds/routes.test.ts.
  • compliance-6 — sweepAuditLogs also stops the prefix walk at a row ABOUT the held custodian (resource_type = 'user' AND resource_id held), matching the erasure scrub's two-sided definition.
  • compliance-7 — the execution-time hold block in processErasure is audited (gdpr_erasure_blocked_by_hold, atExecution: true), emits the gdpr_erasure hint and clears started_at_ms.
  • compliance-8 — listAuditLogs clamps limit to 1..200 for every caller; /audit-logs/errors validates limit through the sibling zod shape (400 on invalid).
  • compliance-9 — csvCell prefixes = + - @ \t \r cells with ' before quoting (OWASP CSV-injection mitigation).
  • compliance-10 — the limiter catch only records rate_limited for RateLimitExceededError; anything else is logged and rethrown.

Skipped

None.

Review round 1 — what changed

  • Blocking 1 (compliance-x1): fixed at the root as described above (commits fix(shared): queue a serializable retry on the row it lost to + fix(platform): queue audit chain appenders instead of storming 40001).
  • Blocking 2 (75-char header on 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 reaches main.
  • Non-blocking: approvals of 0081 losers settled (above); copy/docs no longer promise Cancel for a non-pending receipt ("Retry it (or cancel it while it is still pending)", en/de/fr + docs en/de/fr). Kept as-is with reason: csvCell still 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); the agentRuns label 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 test in packages/shared → exit 0, Test Files 22 passed (22) / Tests 214 passed (214).
  • Targeted server suites after the repair: 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-parser in services/platform/knip.config.ts).
  • Integration proof (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 (only webdav 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 over chat/store.ts appendMessageRow, a plain INSERT … ON CONFLICT DO NOTHING slot 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 with bun 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. No RUN TRUNCATED anywhere.
  • Pre-fix control on the same tree (fix files reverted, lane kept; 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.
  • Migration 0081 settle step proved on a throwaway tale-db with 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 → rejected with supersededBy = survivor, every other receipt and card untouched, index recreated over the four live statuses.

Notes for the reviewer

  • Concurrency proof for compliance-x1. Before the fix the new lane fails deterministically on the same tree (committed=6/8 rejected=2 (PostgresError: could not serialize access due to concurrent update; …) attempts=30, log compliance-prefix-lane.log); after it, both concurrent stacks report committed=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 — no RUN TRUNCATED, every tasks/collab lane 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.
  • The queued retry needs 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 cannot begin on a reserved connection; savepoint follows postgres.js's shape, prepare is refused. A COMMIT the server answers with ROLLBACK (aborted transaction) is surfaced, never reported as success. The advisory-lock class 72_085_002 is 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.
  • Migration numbered 0081 (generator produced 0078, which the brief assigns to the files theme; renumbered before the first commit and claimed in the campaign state). Re-check at merge time that 0081 is still free and that 0078–0080 land.
  • retryErasure does NOT charge the governance:dsar_request limiter (a Retry re-arms an existing receipt; the limiter meters filings).
  • The receipt drawer labels cascade passes via dataSubjectRequests.categories.<key> with a raw-key fallback; every 0.5 pass name already falls back — agentRuns joins that pre-existing gap; a 16-key × 3-locale label sweep is its own small PR.
  • Migration 0081's duplicate settlement marks the losers cancelled with cancelled_by = 'system' (the drawer shows the id verbatim when no user name resolves).
  • The itest checkErasure lane zeroes coolingOffHours before 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.

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.
@larryro
larryro merged commit 5127ecd into main Sep 6, 2026
48 checks passed
@larryro
larryro deleted the fix/compliance-hold-retention-erasure branch September 6, 2026 02:14
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant