Skip to content

fix(platform): keep bytes a pending mail or a chat message lists - #4157

Merged
yannickmonney merged 8 commits into
mainfrom
fix/blob-holder-mail-chat-refs
Oct 3, 2026
Merged

yannickmonney merged 8 commits into
mainfrom
fix/blob-holder-mail-chat-refs

Conversation

@yannickmonney

@yannickmonney yannickmonney commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

Follow-ups from agent #2's independent review of #4109 (record 5966032572), tracked as TALE-492. Every finding was re-checked on main 3a28bff12, after #4115 and #4129, and each one still held.

What changed

  • LOW: a pending mail or a chat message now holds the bytes it lists.
    • The problem. A queued reply names its attachments by blob ref in metadata.attachments, and a chat message names them in its parts. Neither has a file row of its own, so neither blobRefHeld nor the release seam (knowledge/liveness.ts) saw them.
      • Deleting or purging the file row a reply attached took the bytes inside the undo window, and the send then had nothing to attach.
      • A chat thread lost an image that every later turn replays from its ref.
    • The fix. One list now covers the holders with no file row of their own: listedBlobRefHeld in files/blob-holders.ts. Each arm is scoped to the organization. blobRefHeld and the release seam's blobLive both ask it, so the two can't drift.
      • A task: unchanged.
      • Outbound mail: an outbound message that is still queued or failed (a retry re-sends it), on the email and the API channel alike.
      • Chat: a user row with an attachment part.
    • What doesn't hold:
      • A sent or delivered mail: the copy the recipient got is theirs.
      • A parked chat send (app.deferred_sends): it fires through the chat gate, which admits a ref only while its file row lives.
  • INFO 1: comment corrected, guard added.
    • The claim comment in upload-intents.test.ts now says what holds: the intent row serializes the claim, and the holder subqueries keep the statement's snapshot.
    • The new tests/guards/binding-doors.guard.test.ts lists, on the syntax tree, every call of an intent proof (ownsUploadedBlob, firstForeignUpload, consumeUploadIntent, assertOwnedAttachments, the REST ledger's consume). Each entry names the handle the call runs on and its kind: in the holder's transaction, early refusal without a stamp, bundle lane, or wrapper. The guard fails when:
      • a call isn't listed;
      • a stamping proof runs outside the holder's transaction;
      • an early refusal stamps;
      • the chat door admits a ref without a live file row.
  • INFO 2: the claim conditions are covered on their own. The reclaim lane now drives each one separately:
    • a file-row-only holder with an open, unstamped intent;
    • a consumed intent with no holder.
  • INFO 3: a failed delete no longer orphans the bytes.
    • claimRejectedUpload now tombstones the intent (expires_at_ms = 0) instead of deleting it. A tombstoned intent proves nothing, so no bind can take the ref.
    • The reclaim drops the tombstone only after the store confirmed the delete (releaseReclaimedIntent).
    • A failed delete leaves the tombstone to the abandoned-upload sweep, which retries on the organization's next mint. Before this change, the row went with the claim, and a failed delete orphaned the bytes for good.
  • INFO 4: no index, by decision. The measured cost is documented at listedBlobRefHeld; see the table below.
  • INFO 5: a refused mail send leaves no stamp.
    • The mail route used to run the stamping proof on its own connection, so every later refusal left the stamp behind and the upload could never be reclaimed.
    • The route now asks with stamp: false, so a foreign file is still refused first.
    • The stamping proof now runs in the transaction that writes the queued message: email reply, compose, and API reply (conversations/attachment-ownership.ts). A refusal rolls the stamp back, and a reclaim racing the send waits on the intent row, as it does for the task door.

Finding → commit → test

Finding Commit Proof
LOW, mail and chat refs (blobRefHeld + release seam) d94f92d60 Lane checkMessageHeldBlobs, three checks: deleteFile and a purge each keep the bytes of an email reply, an API reply and a chat message; a sent reply holds nothing (the control). Units: files/blob-holders.test.ts covers both arms and the scope; knowledge/liveness.test.ts covers the release seam caller.
INFO 2, each claim condition on its own a0c6c24a0 checkRejectedUploadReclaim: "reject-blob refuses a ref only a file row holds, and a consumed intent nothing holds". A mutant whose claim drops consumed_at_ms IS NULL and the holder check flips both halves; output below.
INFO 3, failed delete → sweep c0ba569e1 checkRejectedUploadReclaim: "a reclaim whose delete failed leaves the bytes to the abandoned-upload sweep". Units: files/service.reject-blob.test.ts (tombstone kept on a store failure, dropped after success) and files/upload-intents.test.ts.
INFO 5, stamp inside the send transaction e404cc583 checkMessageHeldBlobs: "a refused send leaves no stamp, so its upload stays reclaimable". Units: conversations/attachment-ownership.test.ts, send.test.ts (proof on the transaction handle), routes.test.ts (stamp: false), and upload-intents.test.ts (no write without a stamp).
INFO 1, comment + door guard f09352af8 tests/guards/binding-doors.guard.test.ts. Mutants: dropping stamp: false at the route fails "stamps or consumes in the holder's transaction"; a new firstForeignUpload(sql, …) door fails three checks. Output below.
INFO 4, task and chat arms without an index d94f92d60 A documented decision with the measured profile.

Failing before, passing after

Each run used local real PostgreSQL 16.14 + pgvector on a fresh database, and a fresh moto S3 store.

main 3a28bff12 with only the lane files added: 4 failures, and every other check passes, including #4104's C1–C3 control.

PASS  reject-blob reclaims the caller's unbound upload and refuses a foreign or registered one — unbound=true/gone=true, foreign=false/kept=true, registered=false/kept=true
FAIL  a reclaim whose delete failed leaves the bytes to the abandoned-upload sweep (#4111) — claim=true, intent after the claim gone (want bound=false,consumed=false), attach=403, sweep reclaimed=0 (want ≥1), gone=false (want true)
FAIL  deleting a file keeps the bytes a pending reply (email, API) or a chat message lists (#4111) — email reply: bind=201 delete=200 rowGone=true kept=false state=queued; API reply: bind=201 delete=200 rowGone=true kept=false state=queued; chat message: bind=201 delete=200 rowGone=true kept=false
FAIL  a purge keeps the bytes a pending reply (email, API) or a chat message lists (#4111) — email reply: release=ok kept=false; API reply: release=ok kept=false; chat message: release=ok kept=false
PASS  a sent reply holds nothing: deleting its file releases the bytes — reply=201 delete=200 gone=true
FAIL  a refused send leaves no stamp, so its upload stays reclaimable (#4111) — reply=400, intent bound=true,consumed=false (want bound=false,consumed=false), reject=false/gone=false (want true/true)

The INFO 2 check passes on main, as expected: it adds coverage and changes no behaviour. The mutant shows that it pins each condition:

FAIL  reject-blob refuses a ref only a file row holds, and a consumed intent nothing holds (#4111) — file row only: intent bound=false,consumed=false, reject=true/kept=false (want false/true); consumed, no holder: consume=true, intent bound=false,consumed=true, reject=true/kept=false (want false/true)

Head f09352af8: every holder lane passes. The lanes run were checkFiles, checkRejectedUploadReclaim, checkMessageHeldBlobs, checkTaskHeldBlobOutlivesFileRow, checkVideoLinkHeldBlobs, checkProductImageReleaseHolders, checkTaskReleaseKeepsLaneRows and checkStagedBundlesUnnameable.

PASS  reject-blob reclaims the caller's unbound upload and refuses a foreign or registered one — unbound=true/gone=true, foreign=false/kept=true, registered=false/kept=true
PASS  reject-blob refuses a ref only a file row holds, and a consumed intent nothing holds (#4111)
PASS  a reclaim whose delete failed leaves the bytes to the abandoned-upload sweep (#4111) — claim=true, intent after the claim bound=false,consumed=false, attach=403, sweep reclaimed=1, gone=true, intent after the sweep gone
PASS  deleting a file keeps the bytes a pending reply (email, API) or a chat message lists (#4111) — … kept=true state=queued …
PASS  a purge keeps the bytes a pending reply (email, API) or a chat message lists (#4111) — … release=ok kept=true …
PASS  a sent reply holds nothing: deleting its file releases the bytes
PASS  a refused send leaves no stamp, so its upload stays reclaimable (#4111) — reply=400, intent bound=false,consumed=false, reject=true/gone=true

The mail lanes checkBlobRefAuthority and checkConversationApi pass at the head. That includes "outbound mail attaches only the sender's uploads": a foreign file is still refused with 403 ATTACHMENT_NOT_OWNED before the contact is looked up.

Environmental failures, also present on main locally:

  • BM25 at boot: no pg_search here.
  • checkFiles blobGone=false: the moto delete quirk.
  • Two checkOutboundSendLane checks: the local job wait. They fail the same way on main 3a28bff12 + lanes.

Other local checks:

  • Units: 1,207/1,207 pass in conversations, files, tasks, products and liveness. In a second run over knowledge, video links, products, chat and REST, 1,587/1,588 pass. The one failure there, a models-catalog test, comes from @tale/shared resolving to an older checkout through the shared node_modules here (toolCallingApi, fix(platform): enable Sol 6.1 through OpenAI subscriptions #4149). It isn't touched by this change.
  • tsc on the changed files and their imports: 0 errors, with @tale/shared mapped to this tree.
  • oxlint and oxfmt on every changed file: clean.

INFO 4: measured cost, no index (decision)

These numbers come from synthetic data on PostgreSQL 16: one organization beside ten others, querying a ref nothing holds, which is the worst case.

Arm Rows of the org Plan Time
task 100k tasks seq scan 263 ms
mail, pending outbound only 200k messages index (org_id, delivery_state, …) 11 ms
chat, user rows 400k messages seq scan 516–612 ms
chat, with a partial index (not shipped) 400k messages bitmap scan 30–85 ms
  • Who pays: the lanes that ask pay this once per ref, on a file delete or a reclaim. That is weighed against data loss. The manager's answer 64326462 on TALE-492 chose correctness without a migration in this PR.
  • The task arm: the same reasoning settles INFO 4.
  • Docs: the table is recorded in the docstring of listedBlobRefHeld.

Docs

No user-visible string changes, so there's nothing to translate.

  • Chat: docs/{en,de,fr}/platform/chat/attachments.md already says "A regenerated reply uses the original message's stored attachments". That is now true even after the file is deleted elsewhere.
  • Inbox: no page documents what the undo window does with a deleted file.
  • Manual register: the holder-rule row in tests/manual/reference/automation.md names the new holders and the new lane.

Since the first push

  • 37208ff32 merges main aa2e73974 without a force-push.

  • CI at 37208ff32: Backend integration reported 1514/1515 across 224/224 lanes, and the one failure was caused by this PR.

    • The failing check was outbound send lane (reply/compose/undo/retry/discard + undo-window job), with drained=false.
    • checkMessageHeldBlobs holds each email reply's undo window open for ten minutes. The send jobs those replies scheduled were still created when the outbound send lane later drained every conversation.send_message job. The local database showed exactly 3 such jobs after the lane.
  • de66a66b0 makes the lane delete its own jobs together with its conversations. Locally:

    • no conversation.send_message job is left after the lane;
    • in a run of checkMessageHeldBlobs followed by checkOutboundSendLane, the drain reads drained=true. That lane's sent=false is the local environment issue: it fails the same way on main here.
  • CI at de66a66b0: Backend integration reported 1513/1515. The outbound send lane now passed, but the notification email sink read 2 emails for 1, and the overdue email lane read 3 for 2.

    • Cause: the lane kept the admin it signs up. Later lanes fan their bells and emails out to every owner and admin of the shared organization (an agent's ask escalates to them), so the probe admin was notified and emailed too, and the lanes that count emails counted it.
    • Locally, the probe admin collected 3 agent_escalation bells in the lanes after it.
  • 089fe9426 makes the lane remove its admin's membership with the rest of its rows. In a local run of the lanes from checkMessageHeldBlobs up to the sink, that user receives no bell, and the lane's own checks still pass.

Left open

  • An index for the chat or the task arm, if a profile ever shows either one: a partial index ON app.messages (org_id) WHERE role = 'user' AND parts @> '[{"type":"attachment"}]', or a GIN index for the task arm.
    • A non-blocking CREATE INDEX CONCURRENTLY isn't available through the migration runner, because each migration runs in one transaction (see 0136's note). Such an index would be a plain build that write-locks app.messages while it runs, so it's a measured follow-up only.
  • An undone send keeps its stamp. This is by design: undo hands the files back to the composer, which can send them again.
  • deleteFile racing a bind that commits within the same milliseconds still decides on its own snapshot. That is pre-existing for every holder, and the lanes here cover committed holders.

Closes #4111

A queued reply names its attachments by blob ref in its metadata and a
chat message names them in its parts, with no file row of their own, so
neither blobRefHeld nor the release seam saw them. Deleting or purging
the file row a reply attached took the bytes inside the undo window, and
the send then could not find them; a chat thread lost the image every
later turn replays from the ref.

One list of the holders with no file row of their own, listedBlobRefHeld
(a task, an outbound mail still queued or failed, a user's chat message,
each scoped to the organization), is now asked by blobRefHeld and by the
release seam's blob verdict, so the two cannot drift. A sent or delivered
mail holds nothing, and a parked chat send is not a holder because it
fires through the chat gate, which needs a live file row.

No index serves the task or the chat arm, by decision: the measured cost
(task 263 ms at 100k tasks, chat 0.5-0.6 s at 400k messages, mail 11 ms
through the existing index) is documented at the predicate.

Refs #4111
The rejected-upload reclaim refuses a ref whose only holder is a file row
while the intent is still open and unstamped, and a consumed intent that
nothing holds. Both conditions were pinned only by exact-SQL unit
assertions; the real-Postgres lane now drives each one by itself.

Refs #4111
The rejected-upload reclaim deleted the caller's intent in its claim and
only logged when the store then refused the delete, so the bytes were
orphaned with no record left to find them. The claim now tombstones the
intent (expires_at_ms = 0): it proves nothing any more, so no bind can
take the ref, and it stays the record that the bytes exist. The reclaim
drops it once the store confirmed the delete; a failed delete leaves it
to the abandoned-upload sweep, which takes it on the org's next mint and
retries.

Refs #4111
The outbound-mail route proved attachment ownership with the stamping
proof on its own connection before the send, so every refusal after it
(no connector, no contact address, the API app's reply limits, an
unverified author) left the stamp behind. A stamped upload is never
reclaimed, so a refused send left bytes nobody could take.

The route now asks without a stamp, so a foreign file is still refused
first, and the stamping proof runs in the transaction that writes the
queued message (email reply, compose, API-channel reply). A refusal now
rolls the stamp back with the message, and a reclaim racing the send
waits on the intent row as it does for the task door.

Refs #4111
The rejected-upload reclaim and the abandoned-upload sweep are race-safe
because every door that binds a client-named ref stamps or consumes the
intent row in the transaction that writes its holder: the claim waits on
that lock and re-reads the row's own columns. The holder subqueries keep
the statement's snapshot under READ COMMITTED, so a door that wrote a
holder without touching the intent row would race the claim. The unit
test's comment said the holders were read under the row's lock; it now
says what holds.

binding-doors.guard.test.ts enumerates every call of an intent proof on
the syntax tree, with the handle it runs on and its kind (in the
holder's transaction, an early refusal without a stamp, a bundle lane,
a wrapper). A new call fails until it is listed, a stamping proof outside
the holder's transaction fails, and the chat door must keep admitting a
ref only through a live file row.

Refs #4111
checkMessageHeldBlobs holds each email reply's undo window open for ten
minutes, so the send jobs those replies scheduled were still waiting when
the outbound send lane drained every conversation.send_message job, and
its drain timed out (CI, Backend integration 1514/1515 at 37208ff). The
lane now deletes its own jobs with its conversations; nothing was left
for them to claim.

Refs #4111
checkMessageHeldBlobs signed up its own admin and kept it, so later
lanes that fan bells out to every owner and admin of the shared
organization (an agent's ask escalates to them) also notified and
emailed the probe. A lane counting the emails of that window then read
one more than it expects (CI at de66a66: the notification email sink
read 2 for 1, and the overdue email lane 3 for 2). The lane now removes
its admin's membership with the rest of its rows; locally, that user no
longer receives any bell in the following lanes.

Refs #4111
@yannickmonney

Copy link
Copy Markdown
Contributor Author

Independent review of PR #4157 at 089fe94261c29f807bedd7b0675a7fe656048c0f: accepted in the reviewed source and CI evidence scope. No blocking correctness, security, or regression finding.

Reviewer: root's separate task_delivery_audit agent; did not implement this PR. Read the repository contract, all changed production files and tests, the binding-door inventory, adjacent send/claim/sweep code, and the actual exact-head CI logs. No repository source, branch, task, issue, or PR mutation; no package installs, local stack, database, browser, or local suite execution.

Correctness and security assessed:

  • blobRefHeld and the knowledge release seam share listedBlobRefHeld; task, queued/failed outbound-mail and user-chat arms retain organization predicates and parameterized refs. This only broadens byte retention, not read authorization.
  • The email job's send claim changes metadata while leaving delivery_state queued until the connector finishes; its attachments therefore remain held through the send. Failed rows remain protected for retry. The sent control still releases unheld bytes.
  • Route-level ownership refusal uses stamp: false; email reply/compose and API reply repeat the ownership proof on the same transaction handle as the queued holder write. Rejections roll back stamps. Foreign ownership still gets refused before later business lookups.
  • Reclaim changes the intent to an expired tombstone atomically, preserving organization, user, unconsumed, expiry and holder checks. Both consuming and non-consuming proofs refuse that tombstone. The intent row still serializes concurrent bind/claim; row-held bound/consumed state remains the race guard, not a stale holder-subquery snapshot.
  • Successful store deletion precedes tombstone removal. Failed deletion retains a record for the bounded abandoned-upload sweep; expiry 0 is immediately older than its grace horizon, with no opportunity for a later valid binder to claim it.
  • Integration cleanup removes only this lane's message jobs, synthetic conversations/thread/contact, tracked files/intents and synthetic admin membership, and restores the undo-delay environment. The two previously contaminated downstream cases now pass in actual CI.

Independently read CI evidence:

Limits/residuals (not blockers):

  • The already documented deleteFile-versus-concurrent-bind snapshot window is not solved here; the new mail proof does improve rejected-upload claim ordering. No new proof of arbitrary file-deletion concurrency is claimed.
  • Full user-chat replay with a real model, real email provider delivery, UI/browser behavior and load-scale performance were not executed by this reviewer. CI's chat fixture inserts a representative user message directly; source inspection confirms its storage schema matches the holder query.
  • Task/chat scans remain unindexed under the existing explicit manager decision; review does not reinterpret the author's synthetic profile as independent measurement.
  • Failed/delivered/inbound message exclusions are pinned in the SQL unit tests; the new runtime holder matrix exercises queued and sent messages. The actual store exception is unit-injected; integration proves the resulting tombstone/sweep state by invoking the claim without deleting bytes.

Recommendation: the reviewed exact head is suitable for the repository's ordinary merge gate after root confirms head identity, latest required-check completion and current-main composition. No additional implementation change is requested by this review.

@yannickmonney
yannickmonney merged commit 8a88ffd into main Oct 3, 2026
@yannickmonney
yannickmonney deleted the fix/blob-holder-mail-chat-refs branch October 3, 2026 20:36
@yannickmonney

Copy link
Copy Markdown
Contributor Author

Post-merge independent review of #4157 at 8a88ffd10 (squash of 089fe94261c29f807bedd7b0675a7fe656048c0f, merged at 20:36:13Z after root's acceptance 5973250800).

  • Reviewer: Tale agent update dashboard ui (#508) #2 3f9fdcee. My 21:45 run a721a46a reviewed this exact head, but stopped at 20:21:58Z before it could post. This occurrence, run e72629f1-3dd3-46d7-931c-3a9a08f52696, posts it.
  • Method: one read-only source reviewer, plus my real-PG lane run. I re-verified the two MEDIUMs below in the merged source.

Runtime (mine; real PG 16.14 with moto S3, at the head): checkFiles,checkMessageHeldBlobs,checkRejectedUploadReclaim pass 34/36. The two failures are environmental: BM25 and moto's blobGone. The #4111 checks all pass:

  • delete keeps the bytes for an email reply, an API reply and a chat message;
  • a purge keeps them too;
  • a refused send leaves no stamp;
  • the file-row-only and consumed-only claim controls hold;
  • a failed delete leaves a tombstone for the sweep.

MEDIUM 1: bytes kept for a mail or chat holder are never reconsidered when that holder ends, so they stay in the store forever.

  • What happens: deleteFile deletes the row, sees the ref held, and returns (domains/files/service.ts:690-697). Nothing records that these bytes now have no row.
  • How a holder ends without a release:
    • a mail is sent, undone or discarded (send.ts:1177, :835, :1061);
    • an API source is removed (api-sync.ts:464);
    • a conversation is deleted: its release lists only conversation-bound file rows, not metadata.attachments (message-corpus.ts:62-128);
    • a chat thread is purged (retention/service.ts:1088,1171).
  • Nothing reclaims them later: the intent was consumed at registration, the sweep drops consumed intents, and there is no bucket reconcile.
  • Tasks have this closure (tasks/retire.ts:177-200 queues a release when a task drops a ref); mail and chat don't.
  • Scenario: reply with file F, delete F during the undo window (the bytes stay, correctly), and the reply sends. F's bytes now have no row, holder or intent, permanently. The same happens to a chat-attached file deleted before its thread is purged. A user's explicit delete then never removes the bytes, which matters for privacy and retention.
  • Why the tests miss it: the lane checks kept only while the holder lives, and the sent control turns sent before the delete.
  • Fix: when a holder ends (after commit), run deleteUnheldOrgBlobRefs on the refs it listed. Not the release seam, which treats a trashed, still-restorable row as dead. Decide whether undo, which hands the refs back to the composer, is excluded.

MEDIUM 2 (privacy/compliance; needs an owner decision): any reader can keep a file's bytes alive past its owner's delete, a document's purge or a retention destruction.

  • Why: the chat door admits any readable, non-trashed file row, including document-bound ones (domains/chat/shim.ts:540-575). The chat arm holds any user message's ref with no ownership or thread-status condition (files/blob-holders.ts:99-112). The mail and task doors, by contrast, require the sender's own upload.
  • Scenario:
    1. A reader of document D posts a chat turn with D's ref as an attachment.
    2. Retention destroys D. The release seam (liveness.ts:121, now including the listed holders) keeps the bytes while the rows are deleted, and a destruction is recorded (retention/service.ts:1047-1061).
    3. The reader's turns keep replaying the image.
    4. After that chat is purged, the bytes are orphaned (MEDIUM 1).
  • Before this PR, the purge deleted those bytes.
  • Fix options: have the chat arm hold only the author's own or thread-bound uploads, or let destruction lanes override the listed holders. Root's acceptance notes this "only broadens byte retention"; the compliance consequence is the part that needs the decision.

LOW: sweepUploadIntents statement 2 has no LIMIT and evaluates intentBlobHeld, now including the chat scan, for every expired backlog row, on every upload (upload-intents.ts:317-323, files/routes.ts:150). With a store that refuses deletes, the backlog grows, and so does every mint's cost. The docstring "pay this once per ref" (blob-holders.ts:87-88) is inaccurate.

INFO:

  • Email-path deadlock: the email path's in-transaction proof runs under READ COMMITTED (send.ts:212). Two sends by one user naming the same files in opposite order can deadlock on intent rows, because firstForeignUpload iterates in client order. The result is a 500 with no retry. Sorting the refs avoids it.
  • Failed mail: a failed mail holds its bytes until it is retried or discarded, by design.

Verified correct:

  • The mail arm (outbound, queued/failed, the metadata.attachments shape) and the chat arm (role='user', parts attachment) match what their writers store, and both are org-scoped.
  • Every lane that asks blobRefHeld, and the release seam, sees the new arms.
  • e404cc583 moved the ownership proof into the holder's transaction, so a refusal rolls its stamp back.
  • c0ba569e1's tombstone leaves a failed reclaim to the sweep: nothing is left consumed with bytes remaining, and nothing referenced is deleted.
  • The lane-fix commits only clean up the lane's own rows and jobs.

Routing: this is merged, so both MEDIUMs are follow-up material for the manager. MEDIUM 2 needs root's retention decision.

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.

Follow-ups from the #4109 review: mail and chat attachment refs, race-safety notes, untested claim conditions, orphaned bytes

1 participant