Skip to content

fix(platform): retire unheld chat and mail blobs - #4270

Closed
yannickmonney wants to merge 3 commits into
mainfrom
fix/chat-holder-retirement-clean
Closed

yannickmonney wants to merge 3 commits into
mainfrom
fix/chat-holder-retirement-clean

Conversation

@yannickmonney

@yannickmonney yannickmonney commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

Draft — TALE-549 / #4208 remains incomplete

Current immutable repair: d24091c

Clean replacement#4270 preserves original draft#4238/history and LOW/INFO/API semantics. Current repairs forward resolver-selected source through happy and refused production inserts; historical missing document proof is explicitly ambiguous, never inferred from file.document_id. Migration0150 now has transactional table locks plus enduring message/file capture and affected-ref ledger triggers. Independently owned duplicates take precedence over weaker retired bindings; message file locks NOWAIT rather than deadlock. This SQL has not been executed during light-only admission.

Current light proof:337tests/14suites,7selected TS files/zero diagnostics, focused format/type-aware lint/diff pass; full replacement branch-range commitlint passes. Scoped SAST zero findings with3exclusions/1partial parse. Real resolver/runTurn/PG-store functions are tested through a fake SQL port, not physical persisted ownership. Distinct source review is not whole-task acceptance.

Release blockers: native PostgreSQL/S3 migration/old-writer/affected-ref matrix; actual same-ref multi-team purge/copy proof; C2 near-expiry full-caller concurrency; preexisting rowless adjudication; explicit root disposition of historical ambiguous replay withholding and old-reader stop/drain barrier. SQLSTATE55P03 conflicting old writes fail atomically and are not automatically retried. Keep this PR draft. Original red logs remain preserved; original400test evidence below is historical, not proof of this repair.

Prior continuation evidence (historical)

Do not merge, deploy, close #4208 or infer whole-task acceptance. Root's existing retention policy is unchanged. This extends the preserved LOW/INFO work on the same branch.

Prospective source changes

  • Durable organization/ref reclaim ledger, transactional pg-boss enqueue, bounded retries and recovery. The strict conservative deletion seam preserves restorable rows, pending intents, applicable holds and genuine holders; it observes store failures.
  • Mail settlement (including Message-ID conflict), failed discard, bounded 15-minute owned undo handoff, conversation deletion, API acknowledgement/receipt-owned reconciliation removal and chat-lineage purge capture affected refs transactionally. Observed successful transport is settled by recovery rather than resurrected as retryable failed mail.
  • Chat ownership is classified from server-side locked file provenance before carrying rows disappear, persisted and copied through branch/arena copies. Readable borrowed document/file attachments confer no independent retention ownership; replay is filtered after the authorized source disappears.
  • Retention audit distinguishes document record removal and confirmed deleted, retained or unknown bytes. Additive migration 0150 and a registered native schema probe; no historical backfill or bucket scan.
  • Original bounded upload-intent scans, failure rotation, canonical ownership lock order and corrected scan-cost documentation remain.

Observed proof

  • 29 focused suites / 400 tests pass with private PostgreSQL 18.4 and moto S3, including actual pg-boss enqueue/rollback, store HEAD/delete, send/undo/discard/conversation/purge/API matrix, borrowed deletion/destruction, legal holds/restorable rows, concurrent append/delete, recovery fairness and observed-send failures.
  • 32 selected-file TypeScript diagnostics: zero; focused type-aware lint, format and diff checks pass. Scoped pinned SAST: zero findings, with test/config exclusions and one partial parse reported by the engine.
  • Previous-code MEDIUM control: three actual PostgreSQL/S3 regressions fail at 795ec00 (executed after draft implementation, not represented as test-first). Separate previous-image upgrade control remains deliberately red.
  • Local probes are not the full hosted/native integration-check harness; pg_search/vector substrate was unavailable locally. No whole-workspace test/typecheck was run.

Blocking disposition

Distinct immutable-head review requests changes: C1: same-blob multi-team source proof selects file_metadata.document_id, not necessarily the visible authorizing document; C2: legacy NULL-owner undo can obtain the handoff proof lock before the ledger. Both require fixes and actual native adversarial proof. The review receipt is retained in the task delivery box; no whole-task acceptance is given.
R3: legacy genuine owned chat attachment already rowless before migration. Trusted provenance is absent; the upgrade control reports hold true before / false after, replay unavailable, bytes still present. No author/readability/client-parts inference or broad legacy exception was introduced. A trusted provenance source or explicit audited rollout disposition and passing transition proof are required before release.

The continuation commit was published with invalid scope files instead of allowed platform; local commitlint reports this. Shared history is not rewritten in this lane. This is another explicit pre-merge repair gate, not a claimed passing check.

Distinct immutable-head whole-task review and complete hosted gates remain required. CI is observed passively; no rerun/cancellation/native slot is claimed. API source closure intentionally preserves existing queued/failed replies; later acknowledgement or actual removal ends those holders. No production operation, deployment or cleanup occurred. Pending-held deliverable is a read-only design only.

@yannickmonney

Copy link
Copy Markdown
Contributor Author

PR4270 independent source review — request changes

Exact head 08f613c, tree cc37ffe5bd7799048df4f0c5a30765c18d25a211. Actual parent/merge base d4c519f; GitHub targets a9a19af. The36-path PR delta is retained in changes.patch and source-manifest.json. A read-only merge-tree with a9 succeeds as 0ef59c93089095b931170e689a190cff5f6d4160; no source integration was done. #4238 and its rejection/red evidence are unchanged.

This is a bounded adversarial read of C1/C2/R3 and their regression coverage, not whole-PR acceptance. No installs, tests, DB/S3/container/browser, native task/review mutation, new permission or production operation. The PR reports92 focused tests; I have not independently executed or verified their runtime receipt. The actual PG/S3, same-blob ACL, near-expiry lock and rolling transition proofs remain outstanding as the author states.

Blocking findings

C1a — The ordinary turn still drops the authorized document binding (P2)

backend/domains/chat/store.ts:509–519 builds the user-message object for appendMessageRow without setup.attachmentProvenance.

The new resolver in chat/shim.ts:578–620 selects a readable document. core/chat/turn_action.ts:1041–1058,1143–1146,1337 puts that map onto the TurnRequest, and lib/chat/turn.ts:1311–1312 puts it onto beginTurn setup. But the production Postgres store omits it at the last hop. The classifier therefore receives its default empty map (files/chat-ownership.ts:49), falls back to file.document_id at61, and can stamp a different same-blob document than the one that authorized access.

The prior supported case survives unchanged: D-A and D-B share a blob, file row points at D-B, reader can access only D-A. After D-A is destroyed while D-B retains bytes, replay trusts D-B and remains available to that chat; the converse order can hide a still-authorized attachment. This is source control-flow evidence, not a new runtime reproduction.

Repair: preserve trusted server provenance through the actual pgTurnStore.beginTurn user insert and audit other supported turn entry points/copies for the same loss; do not trust a client-supplied map. Regression: run the resolver → executeTurn/runTurn → real store.beginTurn → persisted ownership chain, not only the low-level SQL builder. Native same-ref/two-team case must test both purge orders and copied/arena history. The new append-message.test.ts:282–294 only calls attachmentOwnershipForParts directly with a hand-supplied map and checks a SQL fragment plus JSON-input count; it never exercises the omitted hop and cannot detect this defect.

C1b — Legacy lazy classification still invents the file pointer as the authorized source (P2)

Independently of C1a, files/chat-ownership.ts:22–39 still stamps file.document_id on every unclassified attachment. It selects a same-ref file row by ownership/order, never the document that actually authorized that historical message. knowledge/release.ts:161–162 invokes this before document purge; files/service.ts:686–691 invokes it before ordinary file deletion. Branch/arena copies correctly preserve whatever map exists, including NULL or an incorrectly derived map; copying is not provenance reconstruction.

A pre-upgrade chat message with NULL ownership, live D-A/D-B and file pointer D-B passes migration0150 because its file row exists. Purging readable D-A in the new image lazily stamps D-B, then replay accepts D-B at chat-replay.ts:18–22. Wiring C1a alone does not repair these existing messages or old replicas' newly written unclassified messages.

Repair: define a conservative transition for source-ambiguous historical document attachments and keep it distinct from proven owned uploads. Do not silently substitute an unreadable twin, current author identity or current readability for historical source proof. Root must retain any policy/adjudication decision; this review does not authorize one. Regression: a legacy NULL-proof row with a real authorized D-A history and unreadable pointer D-B must not become a D-B proof during lazy preservation. Test independent surviving twins and both purge orders, alongside known-valid owned upload and non-document binding controls. Current native tests create fresh rows through appendMessageRow; the document test at retirement.postgres.test.ts:517 has only one document. They do not cover this transition.

R3 — The migration's one-time refusal is not a rolling transition barrier (blocking)

db/migrations/0150_blob_reclaims.sql:10–27 checks for rowless user attachments once, before adding nullable ownership. db/migrate.ts:268–283 records the migration and skips it on subsequent boots. It adds no continuing constraint/trigger/writer fence that prevents the previous image from creating another ambiguous row after the check.

Concrete allowed rolling schedule:

  1. A previous-image user message references a genuine owned upload, with its file row still present. The gate passes; migration commits and is recorded. Ownership for that old row is NULL.
  2. While the old replica is still serving, its ordinary files/service.ts:649–696 deletes the metadata row. The old code has no preservation call; its blob-holders.ts:110–117 treats that chat reference as a holder, so the bytes are deliberately kept.
  3. The new image reads the now-rowless message. chat-replay.ts:24–32 has neither provenance nor a file row and substitutes attachment unavailable. New blob-holders.ts:112–132 no longer counts the chat as a holder. A subsequently eligible new-code reclaim can therefore regard the ref as unheld. The migration is already in the ledger; a later boot does not re-run its check.

The same gap exists if an old writer appends unclassified history after migration and later retires its file row. The migration advisory lock serializes migrators, not old request/worker traffic. Its transactional rollback protects against a detected pre-existing rowless case; it does not make a successful rollout safe against the subsequent schedule. “Old image remains serving” is not itself a guarantee supplied by an SQL transaction and requires deployment-level evidence.

Repair: a genuinely phased provenance-writer/read-retirement transition or another explicitly accepted, enforced rollout barrier is required before merge/release acceptance. Do not convert unknown historical refs to ownership based on the user or loosen the holder policy indiscriminately. The current draft already acknowledges adjudication is outstanding; the new point is that even a clean preflight snapshot is insufficient under continuing old-image writes.

Required causal proof: previous-release schema/data with file-present owned history → apply migration successfully → execute the previous image's actual deletion/write path against the migrated schema → verify the final new-image hold/replay and bytes. Also retain original pre-existing-rowless red evidence and prove the intended gate failure rolls back its DDL/ledger. Current retirement.postgres.test.ts:183–212 runs boot migrations on the synthetic substrate then reapplies the SQL before fixtures; it is not this rolling schedule. The new normal integration probe (retirement.integration.ts:18–80) checks schema, ledger/hand-off scope and rollback, not transition semantics. No committed test specifically exercises the migration's rowless refusal or old-writer-after-success case.

C2: source correction is present; exact concurrency proof is still needed

conversations/send.ts:886–898 now calls ownsUploadedBlob(..., {stamp:false}) before handoffComposerBlobs. The helper's false branch performs SELECTs on both upload intents and composer handoffs (upload-intents.ts:224–252), so the reported early handoff UPDATE lock is gone. The later renewal still takes the reclaim ledger first (retirement.ts:80–99), matching the worker's ledger→expired-handoff order at118–129. I found no remaining instance of the original inverse-lock mechanism in this actual undo path.

The focused unit test at send.test.ts:795–839 asserts the actual undo caller uses stamp:false, with ownsUploadedBlob mocked. The existing real-PG test at retirement.postgres.test.ts:819–845 calls handoffComposerBlobs directly; it does not exercise legacy NULL-owner undo with a trusted near-expiry handoff. Author should run the prior requested full-call-chain schedule and verify returned composer custody and actual byte retention/reclamation after expiry. Do not describe the reported92 pure/focused tests or the direct helper lock test as this native proof.

Before H1 admission

Route C1a/C1b and R3 to the current TALE-549 author; keep clean PR4270 draft and old4238 history. A light source/regression repair can precede expensive proof. H1 should use the corrected immutable head and explicitly include real authorized multi-team C1, legacy-transition cases and actual legacy undo C2, with the existing synthetic PG/S3/cleanup constraints. Retain head, checkout, exact command/runtime, actual counts/failures and source-bound limitations; no retry-to-green claim or baseline omission. Fresh hosted normal gates and distinct whole-task review remain required.

@yannickmonney

Copy link
Copy Markdown
Contributor Author

Independent source disposition for exact head d24091c797a217848a3f2d0f10edb7b50b104512 (tree 0e2579ced5d634ab919181c3f6f0e7153d4d1393). This follows the earlier review of 08f613cc; the branch normally integrated ffa15e019 before the repair. No tests, database, storage or production operation was run in this review.

The prior C1a source defect is closed: chat/store.ts:514 now carries trusted provenance through the actual beginTurn insert, and lib/chat/turn.ts:1268 carries it through refused-turn user insertion. The new normal/refused tests call the real resolver, runTurn and PG-store functions, but use a fake SQL port and assert JSON binding. They do not prove a persisted native row, both purge orders, or copied history.

The prior C1b guessing defect is closed in source: lazy/default classification now records sourceAmbiguous:true instead of inventing a document identity from file.document_id; the legacy replay fallback excludes document-bound rows. Historical document replay withholding remains an explicitly unaccepted availability/policy effect, not proof that historical authorization was reconstructed. Valid owned/thread and non-document binding controls still need the native matrix.

C2's source correction remains present: actual legacy undo retains stamp:false before the ledger-first handoff. The complete NULL-owner, near-expiry undo-versus-retirement caller/storage schedule remains unproven.

R3 is materially improved, but remains an acceptance blocker. Migration0150 now takes write-conflicting table locks before preflight, installs enduring message/file capture triggers, preserves existing proof, prefers genuine independent-owned duplicate bindings, and records affected refs transactionally. This addresses reliance on a one-time scan in the inspected source. Its four new migration tests are SQL-text contracts; no current-head SQL compilation, trigger execution, install race, rollback or previous-image post-migration write/delete proof is supplied. NOWAIT deliberately exposes55P03 whole-request refusal; the transaction wrapper does not automatically retry it. A rowless old copy without proof fails23514. These are disclosed availability costs, not seamless rolling compatibility.

Before acceptance, retain the full synthetic PostgreSQL/S3 gates: fresh/previous-schema boot; original rowless refusal with DDL/ledger rollback; concurrent install/write and old-image writer/delete schedules; actual authorized D-A/unreadable D-B same-ref rows with both purge orders and branch/arena copies; legacy ambiguity and owned/non-document controls; full C2 callers; physical retained/reclaimed bytes. Supplied337 tests/14 suites are scoped proof only. An already-applied0150 would require a later numbered migration; no production application of this draft is asserted here.

Old readers ignore the new column. The proposed stop-ingress/claims, drain/terminate old readers/model/destructive workers, and zero-old-worker/lease/connection readback barrier remains a separate unaccepted rollout requirement. Historical ambiguity and rowless adjudication remain unresolved. A successful migration does not approve that policy or authorize mixed-generation destructive workers.

One evidence wording correction: branch/arena code copies raw parts plus ownership JSON; the later history read applies replay filtering. The copies are not themselves filtered as the provenance audit says. This is a documentation precision point, not an additional established copy defect.

No additional concrete source blocker was found in this bounded reread. The corrected immutable source can proceed to controlled synthetic proof through ordinary manager admission for its existing author. This is not a GitHub approval, native acceptance, merge approval, rollout approval or permission to change historical policy. Keep the draft and prior failed evidence. Fresh normal hosted/native gates and distinct whole-task review remain required.

@yannickmonney

yannickmonney commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor Author

TALE-549 exact-head H1 proof — run884ac008

Source and disposition

Product head remains d24091c, tree0e2579ced5d634ab919181c3f6f0e7153d4d1393, draft #4270. No product-source edits, new source commit, history rewrite or gate bypass. Actual previous image is preserved795ec00c07d5235b65ad0194a2a2efa7f66fc69c in a second detached task-owned worktree. Root abd5df04 and manager919cf04a explicitly admitted H1 for this head only.

Partial, not accepted/mergeable/deployable. Existing native suites are red:53pass/5fail across58tests. Separate synthetic real-schema scripts report24passing named cases. These counts are separate and do not cancel the five failures or constitute a green hosted/native full integration harness. Historical withholding and old-reader stop/drain/zero-old-worker barriers remain unaccepted design/policy limits. No real-data adjudication, historical/bucket sweep or production action was run.

Observed matrix

Evidence Observed result and scope
native-d240-retirement.log Actual application migrations boot twice concurrently on fresh PostgreSQL18.4; pg-boss real transaction enqueue, moto HEAD/deletion, existing send/undo/discard/conversation/API/thread/retention/recovery lanes. 22/25pass,3fail. Connector, corpus/config/fault boundaries are synthetic, as recorded by the committed suite.
native-low-info.log Actual PostgreSQL substrate,1000-row expired backlog/EXPLAIN bounded25 and reversed-ref ownership transactions. 31/33pass,2fail; schema is the committed minimal substrate, not full app boot. Store-delete seam intentionally refuses.
native-matrix.log + native-matrix.ts 11/11named cases pass on actual previous-image app schema then current boot: rowless preflight refusal with added DDL/filename-ledger rollback; two concurrent new boots; actual old deleteFile and old appendMessageRow after install; owned proof/hold/replay/moto bytes+ledger; duplicate-binding both orders; ambiguity;23514copy rejection;55P03 full transaction rollback with no partial proof/sentinel ledger; file-delete rollback; transactional rerun.
native-barrier.log + native-barrier.ts 1case pass: real old-image transaction owns message-table DML lock; actual migrator observed blocked on relation lock; actual old append observed queued behind migration; committed earlier NULL proof remains NULL until affected delete, queued old append receives installed owned proof. This tests writer/install ordering, not a production deployment barrier.
native-c1.log + native-c1.ts 4cases pass: actual SQL member/team ACL resolver returns authorized D-A despite unreadable D-B file pointer; normal/refused runTurn→real pgTurnStore→persisted ownership; real branchThread and ensureArenaPair copy raw parts+ownership; real history-reader replay filtering; both purge orders, twin byte retention then moto deletion, source-specific replay. Synthetic minimal auth-table fixtures, model/budget/corpus boundaries; not complete auth/provider/RAG harness.
native-controls.log + native-controls.ts 7cases pass: historical NULL-proof D-A description/D-B pointer both purge orders, surviving-twin bytes and withheld replay; owned/thread/non-document controls; concurrent duplicate deletion; same-ref other-tenant owned row cannot grant custody. Historical D-A authorization is deliberately not reconstructed; ambiguity cost remains explicit.
native-c2.log + native-c2.ts 1case pass: real NULL-owner queued undo caller obtains non-mutating trusted handoff proof then waits on externally held ledger; actual retire caller participates; original handoff expires and can be deleted under500ms timeout without inverse lock; full undo renews owned composer custody; real retirement retains live handoff bytes, then physically reclaims after forced expiry. Worker SKIP LOCKED is allowed, so this proves this controlled schedule, not all interleavings. Real audit/pg-boss/storage functions, synthetic config.

Red suite mechanisms — not silently waived

  1. Retirement enqueue-rollback test expects zero ledger rows after an enqueue failure. A prior committed file-delete trigger has already durably listed the ref before that failed holder transition, so one row remains. The earlier recorded ref must not be erased merely to make the test green. Enqueue failure rollback needs a source-aware oracle isolating prior ledger state before any acceptance claim.
  2. Legal-custodian test creates both files with synthetic-user as uploader, deletes them, then labels one ref as belonging only to other. New capture retains the actual deleted uploader as a legal custodian; under that user's hold the ref stays. The failing physical-delete assertion is preserved. Owner/custody semantics need explicit source-aware review; this receipt does not permit deleting legal-held bytes or assume test staleness resolves compliance acceptance.
  3. Mixed-author test creates files under synthetic-user, changes mail authors, then expects ledger arrays containing only mail authors. File-delete capture adds the actual uploader, yielding an extra legitimate provenance identity. Retain the failure; distinct review must decide the proper custody oracle and verify no unrelated batch author contaminates another ref.
    4–5. Upload-intent substrate's two document cases expect pointer-derived documentId. Current accepted source repair deliberately emits sourceAmbiguous instead. The red assertions are preserved; no weakened rerun/oracle edit was made. New physical ambiguity controls are separate evidence, not replacement for fixing the committed suite under approved policy.

Proof chronology and limits

native-startup-attempt.log records a missing-database setup attempt, not a product red. native-c1-initial.log/native-c1-rawpool.log record an initial raw postgres pool double-encoding pg-boss JSON; the final script uses the real application createSql JSON-passthrough pool and passes. These logs are retained; no product code changed to resolve harness setup.

Bounded native proof used one Vitest worker and small application pools, with real owned services. It is not the complete Backend integration harness (knowledge vector/search image and full auth/provider/corpus stack were not run). No hosted check rerun/cancel or approval occurred. Distinct review is proof inspection, not independent runtime execution or whole-task acceptance.

Scripts are synthetic probe deliverables, not committed production tests. Reproduce in an owned fresh runtime: restore both immutable source worktrees/dependencies, initialize PostgreSQL user tale549 on55495, start moto55595, create itest_blob_retirement_d240 and itest_upload_intents_d240. Run existing retirement suite first to create the synthetic bucket; native-matrix.ts creates its own gate/prior databases; then run native-c1.ts/native-controls.ts/native-c2.ts against that prior database and native-barrier.ts against its own fresh database. Fixed IDs require fresh owned databases before a repeated run. Never target deployed/real data.

Resources

Capacity at11:34:28Z:154917318656freebytes, load3.00, CPU PSI9.83%,memory0.66%,IO4.06%/full2.68%. Combined admitted H2 growth<=3GiB plus this hardcap3GiB leaves well above20GiB. IO later reached41.03%/full18.19%; results were not inferred from queue delay.

Private cluster tale549-native-d240:PostgreSQL18.4, loopback55495, task-box pg-data/pg-socket, PID550. Moto5.1.14:loopback55595, PID563, bucket tale549-synthetic-retirement. Observed task footprint peaked at approximately1.596GB apparent bytes (includes both worktrees, dependency symlink overlay, runtimes and databases), below3GiB cap; free-byte deltas include concurrent H2/other shared activity and are not attributed entirely to this task. Heavy start/service capacity receipt is native-heavy-start.txt; final owned stop/readback is native-heavy-stop.txt.

Both services stopped11:57:11Z: PostgreSQL via owned pg_ctl, moto TERM. Both PIDsabsent and portsclosed;149681856512freebytes at stop. Exact sampled task footprint1596565768bytes. H1 release posted on TALE549 as1ecf4f1c-9a19-4d05-8e05-e1ff04efb03a. Passive hosted snapshot includes six successful source-resolution jobs but downstream Detect changes/Format are queued and draft gates skipped: no green hosted full-check result claimed. No queued checks were rerun/cancelled.

Owned stopped runtime/data/dependency overlay and both detached worktrees were removed after preservation at12:01:14Z; standing clone is clean and retains the published branch/head. Post-cleanup151797268480freebytes;52artifacts/~884KiB before final receipt edits. Original prior task evidence remains attached; no shared retained state was deleted. GitHub receipt #4270 (comment); TALE359 receipt38e0ae56-b389-4c9c-aa6f-8d924447fe7a.

Additional acceptance precision: current probes exercise actual purgeDocument byte outcomes and replay/store state, not a full destructive-retention sweep through persisted destruction audit and all governed-record lanes. The latter remains part of the complete native/hosted acceptance gate. Actual old function code was executed from pinned795ec00c with the task dependency overlay; a complete old deployment container/auth/model/worker stack was not launched. This is selected old-source function/transaction compatibility, not production rolling-image/read-barrier proof.

@yannickmonney

Copy link
Copy Markdown
Contributor Author

TALE-801 publication: TALE-549 diagnosis plan — part 1/3

Verbatim source text from author run 39c53c3f-528f-4708-891d-4915577328d9, published by the same author under TALE-801 run f55a4901-f7d2-4400-8d9a-ab7d8f7bcf5a. This is a diagnosis handoff, not new proof or independent acceptance. No code push to this PR.


TALE-549 — bounded diagnosis and repair design

Date:2026-10-05. Author run39c53c3f-528f-4708-891d-4915577328d9. Binding root handoff8226a693; LIGHT continuation, no native runtime, install, push or product edits.

Evidence identity and conclusion

Inspected committed objects at d24091c, tree0e2579ced5d634ab919181c3f6f0e7153d4d1393, against retained native-d240-retirement.log, native-low-info.log, native-independent-review.md and native-proof-receipt.md. These are two failing suites with five failing test cases, not five suites. Existing native result remains 53/58, five failures;24 standalone passing probes remain separate. No new test execution or independent acceptance occurs here.

Source control flow explains each observed failure. That establishes a diagnosis, not proof that all five are harmless stale tests: custody union changes retention behavior, retries are skipped after the first failure, and historical ambiguity intentionally withholds access. The repair should strengthen fixtures and transaction-specific assertions, not erase already committed affected-ref evidence or downgrade policy gates. Keep#4270/#4238draft and#4208open.

F1 — transaction rollback versus a previously committed candidate

Location:services/platform/backend/domains/files/retirement.postgres.test.ts:540, assertion550. The fixture creates a file, then performs an autocommit DELETE. Migration0150's BEFORE DELETE trigger inserts app.blob_reclaims inside that committed DELETE. Only subsequently does the test enter another transaction, call queueBlobRetirement, and explicitly throw synthetic rollback. It therefore cannot expect the earlier ledger row to disappear. The log observes one row, exactly consistent with this chronology.

Precision: despite the test title mentioning enqueue, this first failure is a deliberate throw after the enqueue helper; it does not itself inject a pg-boss send failure. Assertions exercising store refusal, last_outcome='failed', recovery and eventual physical deletion are never reached. Their correctness cannot be inferred from this red run.

Bounded repair (test scope first; no proposed product deletion):

  1. Split into three independently seeded cases. New candidate created in rolled-back holder transaction: compare ledger, holder and queued job identity before/after, and require no new row/job. Existing candidate from committed file deletion: snapshot all mutable ledger fields/custodians and actual job rows, attempt a holder upsert/enqueue then roll back; require the original candidate unchanged, holder unchanged, no additional committed job.
  2. Inject actual enqueue failure through the existing fixture seam; require holder CAS transition and ledger changes to roll back together. Never TRUNCATE an already pending candidate to fake atomicity.
  3. Run the separate retry case from the committed file-delete candidate: store refuses, bytes HEAD200, candidate records failure; reopen due timestamp only in synthetic fixture, execute recovery/worker, observe HEAD404 and candidate removal. Verify recovery through existing pg-boss/outbox seam rather than substituting releaseRefs.

Product-change contingency: only change queueBlobRetirement/worker if these stronger invariants fail. No evidence currently justifies deleting the preexisting row. Heavy proof:real PostgreSQL application schema, pg-boss transaction rollback and synthetic S3 failures; exact source and original red control retained.

F2 — an allegedly free ref has the held uploader

Location:retirement.postgres.test.ts:768, assertion789. Both held and free files use file(), whose uploaded_by is synthetic-user. The test DELETE commits both refs' original uploader into their own reclaim rows. It then holds synthetic-user and adds other as the free candidate's listed custodian. queueBlobRetirement unions custodians; it does not replace synthetic-user. retireBlobBatch sees that held uploader and retains the free ref. The failed HEAD assertion is consistent with actual same-uploader provenance, not demonstrated cross-ref contamination.

Bounded repair: add a trusted fixture uploader parameter and create genuinely distinct uploaders before deletion, not by relabeling a candidate later. Seed held uploader U-H, free uploader U-F, independently queue correct per-ref identities, install hold only U-H, assert exact per-ref sets/no U-H on free, execute actual worker and require held HEAD200/free HEAD404. Keep a separate same-uploader control: adding a different holder author must not erase real uploader custody. Verify hold removal then due/retry reclaims, without removing a live legal hold for convenience.

Policy boundary: whether historical uploader identity remains a legal custodian after every live row/holder ends is not decided by this diagnosis. Current source retains it; deleting under that hold would be a new compliance decision. Review the authorized legal-hold contract before changing that rule. Until disposition, preserve real holds and report the reason, do not silently replace the union with the final message author.

@yannickmonney

Copy link
Copy Markdown
Contributor Author

TALE-801 publication: TALE-549 diagnosis plan — part 2/3

Verbatim source text from author run 39c53c3f-528f-4708-891d-4915577328d9, published by the same author under TALE-801 run f55a4901-f7d2-4400-8d9a-ab7d8f7bcf5a. This is a diagnosis handoff, not new proof or independent acceptance. No code push to this PR.


F3 — mixed message authors do not replace original uploaders

Location:retirement.postgres.test.ts:792, first failed equality810. Both uploaded files again belong to synthetic-user; the test rewrites mail owner stamps to held-author/free-author. File deletion captures actual uploader; retireConversationAttachments adds each pending mail's author per ref through queueHolderBlobRetirement. The observed held row is therefore the union synthetic-user+held-author. Membership order is not the issue; the extra identity causes failure.

Bounded repair: build held/free uploads and queued messages under internally consistent distinct owners from the start. Assert sets per ref (sorted for stable presentation) and absence of the other ref's authors, not a union across the batch. Run actual conversation deletion and worker; held ref stays, free ref is deleted. Add a separate legitimate uploader≠message-author fixture if server-side admission can actually produce it; otherwise do not manufacture that path by client-like stamping. For that control preserve any authorized union and verify per-ref isolation.

Remaining native proof: the red case aborts before free-row equality and both physical worker assertions. Neither later outcome was proved. A reviewed union explanation must not substitute for those checks. Run unknown-owner/custody_unknown controls, repeated enqueue idempotence and two-org same-ref isolation. Unknown custody is currently sticky OR on the ledger and can conservatively pin a ref under any user hold; report this distinctly rather than calling it known held-author provenance.

F4 and F5 — borrowed and author document fixtures still expect a guessed pointer

Location:services/platform/backend/domains/files/upload-intents.postgres.test.ts:245, cases borrowed document attachment and author document attachment. Both expect {documentId:'document'} from preserveChatAttachmentOwnership. Current source deliberately returns {sourceAmbiguous:true} when no trusted admission map exists and a file is document-bound. Even if uploader/thread matches author, a document binding does not become an independently owned upload. The actual JSON mismatch directly explains both failures.

Bounded repair: change only these legacy missing-proof oracle branches to explicit ambiguity, retain owned/thread/non-document expected forms and held=false for document cases, and add replay-unavailable checks while the file and unrelated document twin survive. Preserve a different new-admission regression requiring resolver-authorized D-A documentId through real runTurn/beginTurn/refused append and persisted SQL; no arbitrary ambiguity acceptance there. Keep original failed logs and run actual deletion, then verify no ownership/replay resurrection. The current red cases fail before DELETE and final held assertion; rerun those actual outcomes.

This repairs the source/test contract for C1b, not policy acceptance of historical withholding. It must not weaken the original rowless-owned upgrade oracle: unknown historical own use still needs trusted reconstruction or explicit phased disposition. No author-ID, pointer or present ACL can supply missing history.

Remaining MEDIUM1 lifecycle design

Reuse app.blob_reclaims, existing pg-boss transactional enqueue/recovery, and strict deleteUnheldOrgBlobRefs. Do not introduce a second release seam or bucket scanner. Keep captures deduplicated by organization/ref with CAS transition identity and trusted per-ref custody before carrying rows disappear.

Transition Invariant and bounded proof
Mail successful send, Message-ID conflict, observed-success watchdog Pending metadata refs captured in successful settlement transaction only; old claim cannot retire/revive newer state. Delete file during undo window; bytes stay before settlement, queue survives commit/crash and S3 refusal, then delete after no holder/row/intent. Exercise both success branches and recovery, not only sent-before-delete control.
Failed discard and conversation deletion Failed mail holds until real end. Snapshot only refs/custodians of removed pending rows; release neither a concurrent pending reply nor another org. Prove mixed-author corrected fixtures plus rollback and idempotent duplicate delivery.
API acknowledgement and receipt-owned actual source removal Acknowledgement/snapshot reconciliation ends the holder; deleted:true teardown intentionally preserves transcript queued/failed replies until acknowledgement/discard/removal. Retain this accepted distinction and test stale receipt/CAS source identity.
Chat lineage purge Persisted own proof survives rowless file deletion; refs collected before message deletion. Purge root+branches/arena lineage transactionally, preserve unrelated thread/valid independent refs; after commit/recovery bytes are reclaimed.
Undo handoff stamp:false proof must not lock handoff before ledger. Transfer only trusted actor-owned refs into bounded15-minute handoff, not another actor or borrowed document. Actual NULL-owner near-expiry caller schedule, composer return, worker contention, expiry and S3 reclamation. Retained native-c2 proves one external-lock/SKIP-LOCKED schedule, not every interleaving.

Cross-cutting cases:restorable trashed file remains live; unexpired/bound intents retain; valid legal holds win; consumed intent is not the sole durable closure record. After store deletion but before ledger commit failure, idempotent retry must safely converge. Candidate/job retry exhaustion must leave recovery-visible state. Observe real failed deletion (not swallowed success), bound recovery25 and no prefix starvation. Tenant and per-ref custody assertions are mandatory.

@yannickmonney

Copy link
Copy Markdown
Contributor Author

TALE-801 publication: TALE-549 diagnosis plan — part 3/3

Verbatim source text from author run 39c53c3f-528f-4708-891d-4915577328d9, published by the same author under TALE-801 run f55a4901-f7d2-4400-8d9a-ab7d8f7bcf5a. This is a diagnosis handoff, not new proof or independent acceptance. No code push to this PR.


LOW and INFO — preserve already delivered fixes

LOW:both expensive expired-intent arms materialize at most25candidates ordered expiry/id; consumed-intent housekeeping is still unbounded but does not evaluate intentBlobHeld. Do not describe the entire mint as constant-time: each candidate can still scan many org chat/task rows. Failure rotation shifts expired expiry to inside the one-minute grace; it must remain nonbindable and eventually revisit after grace. Docstring now correctly says each repeated per-ref evaluation pays scan cost.

Plan:retain source unless profiling/proof finds a regression. Correct the two provenance expectations without changing batching. Under later H1, rerun1000-row EXPLAIN ANALYZE loop-count<=25 per expensive arm, persistent refusal rotation/held-tail advancement, both ledger variants, org scoping and repeated-sweep eligibility. The retained31passing substrate cases are evidence, not green suite acceptance. Index changes need separate measured necessity, migration skill and admission, not a speculative global scanner.

INFO:firstForeignUpload deduplicates/sorts refs before ownership locks. Preserve READ COMMITTED transaction-bound proof and stamp:false preflight. Bounded proof:reversed/repeated ref arrays in two transactions, deterministic barrier, both finish with no deadlock; foreign ref rejection rolls back message/stamps. Existing reversed-ref substrate tests do not exercise the entire transport send route; keep that distinction. Failed mail intentionally remains a holder until retry/discard/end; no automatic failed-message expiry introduced. NOWAIT55P03 introduced by rolling message trigger is a separate explicit refusal, not fixed by ref sorting or automatically retried by current40001/40P01 wrapper.

MEDIUM2 — options recorded, no new decision

Binding root policy remains:read access is not independent document retention ownership; preserve real legal holds, restorable rows and genuine own/thread-bound uploads. C1 new admission provenance is resolved server-side. Native normal/refused D-A/D-B/copied history controls passed in the prior phase; full destruction audit/governed-record sweep remains open.

Historical unresolved options to present for explicit disposition, not implement here:

  • Reconstruct provenance from trustworthy retained evidence, limited authorized tuple set; audit the source and ambiguity rather than infer from author/current pointer/current visibility. Irrecoverable tuples remain unresolved.
  • Explicitly accept conservative sourceAmbiguous withholding with scoped historical availability effects and rowless preflight blocking. This is not yet approved and does not confer borrowed custody.
  • Separately authorize a stop/drain/zero-old-reader-and-destructive-worker rollout barrier and measure installation/capture cost. Database triggers address writer capture, not old model-reader policy. No successful synthetic migration can prove production worker drain.

A destruction audit must distinguish physical deleted/retained/unknown refs and record removal; a row removed is not necessarily destroyed bytes. Exercise actual retention sweep and persisted audit with store refusal, surviving authorized twin, real hold, independent owned upload and governed record. No destruction-lane override of valid holders is authorized by this note.

Ordered continuation and done gates

  1. Distinct source-aware review of this diagnosis and custody/oracle boundaries before changing tests. No new root policy question is requested; existing unresolved dispositions are preserved.
  2. Bounded local fixture/oracle repair:retirement.postgres.test.ts three split/strengthened cases and upload-intents.postgres.test.ts two legacy assertions; retain original logs, zero product changes by default. Unit guards for per-ref union/unknown/idempotence as needed. Do not count runtime-skipped native cases as passing locally.
  3. Review immutable repaired source; scoped type/lint/format/SAST and valid branch-range commitlint. No shared history rewrite; publish only under a later admission permitting push.
  4. New H1 permit required, not carried over:private PG18.4+synthetic S3, estimated2GiB/30–45min subject to current manager occupancy/PSI/free-disk checks and explicit cap. Execute all58committed cases with zero failures, complete split rollback/retry and custody physical outcomes, then native24probe controls and full audit cells. Full hosted/backend integration and real-image rolling proof need their own admitted resources/dependencies; cannot promise complete coverage within that estimate.
  5. Explicit historical/reader-barrier disposition, measured forward/rolling compatibility and distinct whole-task acceptance. If still partial, remain draft/open. No production opt-in, report, cleanup, bucket/history scan, deployment or task move is authorized here.

This run's receipt

Read-only source-object/evidence analysis; no source branch/worktree edits, installs, test runs, service starts, new commit, push or CI action. Standing clone's unrelated checkout left intact; fetched origin for orientation but did not merge into pinned evidence. No H1 used/requested as a current lease. Native original red logs remain staged/attached unchanged. Produced this diagnosis/plan and checkpoint references only. This is not independent review or task completion.

@yannickmonney

Copy link
Copy Markdown
Contributor Author

TALE-812 / TALE-549 — distinct source-aware verdict: ACCEPT the plan

Reviewer C10, agent a0f9fd03-7af6-4c69-b602-755201d86f89, run 4190b293-3192-4a60-a573-a30bf26f2323; distinct from C5 and author/publication runs 39c53c3f / f55a4901.

I reviewed the three numbered diagnosis comments beginning 5989927013, against immutable PR head d24091c797a217848a3f2d0f10edb7b50b104512, tree 0e2579ced5d634ab919181c3f6f0e7153d4d1393, and fetched main 4653d3e3ba2fc224aaf3a437c1b8d853fe096a4a. Evidence scope is source inspection plus the retained native summary 5979691405 and prior exact-head source disposition 5978881765. I did not independently execute the native runs or obtain their raw attached logs.

ACCEPT the diagnosis and bounded repair plan only. This is not PR approval, whole-task acceptance, policy approval, a native review decision, merge/deployment permission, or a heavy permit. No substantive gap in the proposed repair design was established by this review. The original two red suites, 53/58 passing cases with five failures, and 24 separate probes remain separate, unwaived evidence.

Five failures: supported, not excused

  • F1: retirement.postgres.test.ts:541 commits the file DELETE before starting the transaction that queues and deliberately throws. Migration 0150_blob_reclaims.sql:135 captures the OLD uploader/ref inside that earlier DELETE, and its BEFORE DELETE trigger is installed at :176. The later rollback cannot erase that committed candidate. C5 correctly corrects the older receipt's “enqueue failure” shorthand: this failing assertion is reached after a deliberate throw, not an injected pg-boss send failure. Split new-candidate rollback, preexisting-candidate rollback with exact ledger/job snapshots, actual enqueue refusal, and recovery/store-refusal proof; do not truncate committed evidence to obtain zero rows.
  • F2: retirement.postgres.test.ts:135 always seeds uploaded_by = synthetic-user. The held/free test at :770 deletes both before adding other custody to the free candidate. retirement.ts:28 unions identities rather than replacing the captured uploader, and :129 checks those custodians against active holds. Distinct trusted fixture uploaders and a separate same-uploader union control are the right repair; deleting under the existing uploader hold is not authorized.
  • F3: At retirement.postgres.test.ts:792, file uploaders are again synthetic-user, while message-owner stamps are rewritten to held/free authors. message-corpus.ts:37 and queueHolderBlobRetirement add custody per ref; they do not remove the already captured uploader. The unexpected extra identity, not array order, explains the failure. Require exact per-ref sets/no cross-ref contamination and both actual byte outcomes. Any uploader-versus-message-author control must be producible through trusted admission, not client-like relabeling.
  • F4/F5: The borrowed/author document cases at upload-intents.postgres.test.ts:245 expect a guessed documentId. chat-ownership.ts:9 excludes document-bound files from independent upload ownership and :28 explicitly emits sourceAmbiguous:true without a trusted admission map. Both mismatches are explained. Repair only the missing-proof legacy oracle; retain no-hold/no-replay assertions, final DELETE outcomes, independent-owned controls, and a separate authorized D-A normal/refused production-chain regression. Do not relax the original rowless upgrade oracle or call historical withholding approved.

Assertions after each first failure remain unproved until rerun. Sticky custody_unknown OR and conservative hold retention must remain visible, not be relabeled as known custody or erased for a green test.

MEDIUM 1 and native proof

The intended closure is correct: collect trusted organization/ref/custody evidence while carrying rows exist; commit holder transition plus ledger/job together; let a later worker recheck all live holders and delete through deleteUnheldOrgBlobRefs(..., { strict: true }), not knowledge.release_refs. jobs/enqueue.ts:79 binds pg-boss SQL to the holder transaction; the worker cannot see it before commit. retirement.ts:144 uses the strict seam, which propagates storage failures and checks both unexpired intent ledgers (files/service.ts:755). blob-holders.ts:36 retains all file rows, including trashed-but-restorable rows, documents/history, listed holders and live composer handoffs. The release predicate instead excludes non-active file rows and is the wrong seam for this holder-end closure.

The proposed matrix is sufficient as the next bounded proof plan: delete during undo window then settle; ordinary and Message-ID-conflict settlement; observed-success watchdog recovery without resend; failed discard/conversation deletion; API acknowledgement and receipt-owned source removal, with teardown preserving unacknowledged queued/failed replies; root/branch/arena purge; and rollback, crash, duplicate delivery, stale claim/receipt, store refusal, retry exhaustion/recovery, surviving holder/row/intent, real legal holds and tenant/per-ref isolation. Test actual production caller/SQL/pg-boss/S3 outcomes, not helper success alone.

Undo must transfer, not drop custody: trusted original owner (or non-mutating stamp:false proof for legacy NULL-owner), ledger-first bounded 15-minute handoff, no borrowed/other-actor composer grant, live bytes retained, expiry eventually reclaimed. send.ts:884 and retirement.ts:73 support that ordering. C5 correctly limits the retained C2 result to one controlled schedule; actual near-expiry callers and worker contention still need the admitted native lane.

LOW, INFO and policy boundaries

  • LOW is addressed in source and the plan: both expensive expired-intent arms use MATERIALIZED candidate LIMIT 25 before holder scans (upload-intents.ts:336, :353); consumed housekeeping remains unbounded but does not run that predicate. Preserve 1,000-row EXPLAIN loop-bound proof, held-tail advancement, persistent refusal rotation, both ledgers, org scope and repeated eligibility. Nonblocking wording correction: the posted “one-minute grace” is inaccurate. ABANDONED_UPLOAD_GRACE_MS at :57 is 24 hours; RECLAIM_RETRY_DELAY_MS at :62 is one minute. Failure sets expiry to horizon + 60_000 at :402, already in the past, so it stays nonbindable and becomes sweep-eligible again after roughly one minute. Do not change the grace constant to match the prose.
  • INFO is handled: firstForeignUpload at upload-intents.ts:267 deduplicates and sorts before ownership/stamp locks. Preserve READ COMMITTED transaction-bound proof and non-stamping preflight. The proposed deterministic reversed/repeated-ref transactions and refused-message/stamp rollback strengthen the substrate test; substrate success alone is not full transport-route proof. Failed mail remains a holder until retry/discard/end. Trigger NOWAIT 55P03 remains a separate explicit refusal, not something ref sorting or the 40001/40P01 retry helper resolves.
  • MEDIUM 2 stays root's retention/availability/rollout decision. Trusted historical reconstruction, explicit conservative-withholding disposition, and stop/drain/zero-old-reader-and-destructive-worker rollout authorization are options, not approval inferred from current source. Reader access is not independent document custody. Preserve genuine owned/thread-bound uploads, restorable rows and real legal holds; no destruction-lane override is granted. Actual retention sweep plus persisted destruction audit/governed-record outcomes must distinguish deleted/retained/unknown bytes and record removal. Writer-trigger proof does not prove production reader/worker drain.

Next owner: C5, through later ordinary admission, repairs the fixtures/oracles and preserves the original red evidence; then immutable repaired-source review and fresh named H1 admission for native proof, followed by remaining full integration/audit/rolling-policy gates and distinct whole-task acceptance. Splitting/adding cases increases the case count: require all original coverage plus strengthened cases, not just a nominal “58 pass” target. Keep #4270/#4238 draft, #4208 open and TALE-549 incomplete meanwhile. No code, branch, commit/push, installs, tests, services, CI action, production/history/bucket operation, task-state move or heavy execution occurred in this review.

@yannickmonney

Copy link
Copy Markdown
Contributor Author

Closing this draft together with #4238, which it replaced. The branch fix/chat-holder-retirement-clean (head d24091c79) stays on origin, and refs/pull/4270/head keeps the commits.

Why it is not merged: the last native run at this head was 53 of 58 cases with five failing (diagnosed on 2026-10-05 as stale fixtures, never repaired); the review findings C1, C2 and R3 were only partly closed; two behaviours (the legacy rowless chat attachment, and the withheld replay of historical document attachments) need a policy decision; migration 0150 is taken (the line is at 0224); and the branch is 983 commits behind main.

#4208 stays open. Its LOW and INFO items are separable and still unfixed on the stable line; the details are on #4238.

@yannickmonney
yannickmonney deleted the fix/chat-holder-retirement-clean branch November 2, 2026 17:53
@yannickmonney

Copy link
Copy Markdown
Contributor Author

Update: the branch fix/chat-holder-retirement-clean is now deleted on origin, so the line above that says it stays there no longer holds. Its head is still reachable as refs/pull/4270/head (d24091c79).

From this PR only the LOW and INFO items of #4208 were carried over: "fix(platform): bound upload-intent sweeps and order ownership locks" on the stable train (24286d63c), the same commit as for #4238. The holder-retirement work (the MEDIUM items) was not ported, for the reasons given above, and stays on #4208.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant