Skip to content

fix(platform): close the #3785 mail stamp pass review findings - #3808

Merged
yannickmonney merged 9 commits into
mainfrom
fix/mail-stamp-release-helper-holder-recheck
Sep 29, 2026
Merged

yannickmonney merged 9 commits into
mainfrom
fix/mail-stamp-release-helper-holder-recheck

Conversation

@yannickmonney

Copy link
Copy Markdown
Contributor

Follow-up to #3785, from its review. Each item was re-checked on main before the fix. There is one commit per item, a commit for the registers, and four commits from an adversarial review of the first five. Each commit passes the touched suites and the type check on its own.

What changed

One release-enqueue helper (domains/knowledge/release-queue.ts, new). The reconcile's re-queue of the bytes it could not delete (requeueBlobFailures, release.ts) and the mail lanes' release (queueMessageRefRelease, conversations/message-corpus.ts) each had their own 500-ref constant and their own chunking loop. Both now go through queueRefRelease(tx, organizationId, refs, { onChunkError? }) and RELEASE_REFS_PER_JOB.

  • The helper has a module of its own, so the mail lanes reach it without importing the release seam's dependencies.
  • queueMessageRefRelease keeps its name for its three callers (conversation delete, retention, spam verdict) and delegates to the helper. A failed enqueue still throws into the caller's transaction.
  • The reconcile passes onChunkError: a failed job is logged, and the next one is still queued, as before.
  • The review found one more lane that hands the job many refs, releaseUnlistedTaskBlobRefs (tasks/retire.ts). It queued all the refs a task hard delete orphaned as one job, and a project's task tree can orphan thousands. It now goes through the same helper, still in the retire's own transaction.

The log says when a failed byte delete was re-queued (release.ts). requeueBlobFailures now logs the blob-stage failures itself, after the enqueue:

  • ... (blob): <msg> — re-queued to knowledge.release_refs when the job went through;
  • ... (blob): <msg> — not re-queued when it did not, followed as before by the job's could not re-queue ... their bytes stay: line with the error.

warnReleaseFailures keeps the corpus-stage lines. The pinned wordings in release.reconcile.test.ts are updated. A new test covers one failed job among two: 500 lines say "not re-queued", 1 says "re-queued", and one job line follows.

One holder for a shared ref (knowledge/service.ts, folders/paths.ts). Several documents can hold one blob ref: a WebDAV COPY, or one upload bound as two documents. The corpus has one row for it. The indexer indexed an unbound file holding such a ref as the ref's lowest-id active holder (activeDocumentHoldingRef), but the other scope writers wrote whichever document they read. In the nightly scope pass:

  • within a page, Postgres applied either twin to the row;
  • across pages, a later page's twin overwrote an earlier one's;
  • so the row read as drift again every night.

Every scope writer now writes the holder's scope:

  • The nightly scope pass and syncRagDocumentScopes read each ref's holder alone: AND NOT EXISTS (… o.id < d.id …) over active documents, the brief's clause.
  • The indexer reads the holder first for a file filed into a document too. A COPY's file row stays with its source document, whose id can be the higher one; without this, the indexer and the scope pass would still disagree after every re-index of such a file. When no active document holds the ref (its own document trashed, say), the file still indexes as the document it is filed in.
  • syncRagDocumentScope (from the review) writes the scope of its document's ref holder. The document's own scope is written only when it is the holder, or when no active document holds the ref (a trashed document keeps reaching its row, as before). Before, an edit of a non-holder twin wrote its own scope, and the next night the pass reported "the per-edit sync had failed for these".
  • subtreeDocumentFolderPaths (from the review), which feeds syncRagFolderSubtree on a folder rename or move, reads each ref's holder alone.

The stamp clear's recheck has a client-side bound (knowledge/service.ts, clearMailStampRows).

  • The problem. The recheck reads on an app transaction while the corpus transaction holds up to 100 rows. Its only bound was the server-side statement_timeout (10 s), and a half-open app connection never delivers it: postgres.js then waits until TCP gives up.
  • The bound. The read now races 15 s (STAMP_RECHECK_ANSWER_MS). When the bound lapses, the corpus transaction rolls back with its stamps still on, clearMailStamps logs "a clear did not finish", and the next night retries it.
  • The pass goes on. The clear's outcome is now its corpus transaction's (Promise.withResolvers). The read-only app transaction around it is waited for at most 15 s more. Without that second wait, the pass would queue behind the dead connection's ROLLBACK, because postgres.js begin awaits it.
  • Unchanged. A clear whose corpus side committed still counts, and its app transaction failing to end is still logged. A failure of the app transaction before the corpus side begins (its BEGIN, the timeout) still fails the clear.
  • What it does not cover. It covers a connection that stops answering during the clear. One already dead when the clear opens its app transaction locks no corpus row, and holds the pass as it would hold any other read of the pass. The docstring and the registers say so.
  • No .cancel(). I left out the optional .cancel() on purpose. It sends the cancel request over a new connection to the same server, which is unreachable in exactly the case this bound exists for. When the connection is sound, the server's own timeout answers first.

Registers. The emailed-attachment rows of automation.md and MIGRATION.md now describe:

  • the holder rule and every writer that follows it;
  • the 500-ref jobs (a task retire included) and their log line;
  • what the recheck's bound covers.

The scope-stamp row of automation.md names the holder rule and the new lane.

Verification

  • Unit tests. The new and changed tests fail against the old sources.
    • release-queue.test.ts (new): chunking at RELEASE_REFS_PER_JOB and its boundary, throw vs onChunkError.
    • release.reconcile.test.ts: the new wordings and the mixed-outcome case.
    • scope-reconcile.test.ts: twins across a page boundary with pages of 1, 2 and 3; the batch sync of the twin alone writes nothing; the single-document sync of either twin writes the holder's scope, and a trashed document with no active holder still writes its own. The fakes answer a holders-only read only when the statement carries the clause.
    • service.mail-stamp.test.ts:
      • A filed file with a lower-id twin indexes as the twin; one with no active holder indexes as its own document. The holder read is pinned to ORDER BY d.id LIMIT 1 over active documents.
      • A recheck that never answers, with fake timers. The fake connection is lost: its read and its transaction's end never settle. The corpus side has not rolled back at 10 s and has at 15 s. The pass is still waiting at 29.999 s and has gone on with the next clear at 30 s, and only that clear counts.
    • retire.test.ts: 501 orphaned refs go out as jobs of 500 and 1.
  • Mutation checks.
    • The helper always throwing → its hook test and the reconcile's failed-re-queue test fail.
    • A chunk off by one → 3 of the 4 helper tests fail.
    • The app transaction's end not bounded → the fake-timer test times out.
    • The app transaction's end bounded by 1 ms instead → the fake-timer test fails.
  • vitest related on every changed source file (release-queue.ts, release.ts, message-corpus.ts, knowledge/service.ts, folders/paths.ts, tasks/retire.ts; server and client projects): 257 files, 3,387 tests, all passed.
  • Lint, format, knip. oxlint --type-aware --type-check on every changed TypeScript file: clean. oxfmt and bun run lint:manual: green. check-guide on automation.md: the same output as main. knip --workspace services/platform: only the known cross-workspace false positive (oidcOrganizationClaims).
  • Real Postgres 16 (local, pgvector, a moto S3), backend:integration. CI does not run this suite.
    • The new checkScopeRefHolder lane, on an organization of its own, plants a trashed lowest id, the holder and a twin on one ref, and runs:
      • the reconcile, one document to a page: corrected 1/scanned 1, then 0, the holder's scope;
      • the batch sync of the twin alone: writes nothing;
      • the single-document sync of either twin: the holder's scope;
      • a rename of the twin's folder and of the holder's: only the holder's writes the path.
    • On main the reconcile check fails (first=corrected 2/scanned 2 → ["team-twin"], second=corrected 2: the row is drift again on every run). Without the review's per-edit fix, the twin's edit writes ["team-twin"] and its folder rename writes the twin's folder.
    • Final state, checkFiles, checkProviderCredentials, checkProviderCredentialConfiguration, checkKnowledge, checkCorpusScopeReconcile, checkScopeRefHolder, checkEmailedAttachments, checkRetention: 66/68 checks. This includes all 12 emailed-attachment checks (the dead-conversation race with a concurrent clone during the clear among them), the knowledge checks that a folder stamp follows document moves and folder renames, and retention.
    • The two failures are environmental and happen on main too: the boot BM25 check (no ParadeDB pg_search), and moto's blobGone=false. A filtered run on main (without the provider-credential lanes) showed the same environmental failures, plus checkKnowledge's own, which needs a seeded embedding credential.
  • A half-open app connection, on Postgres 16 with the app's own postgres.js pool. A throwaway probe holds a lock on one corpus row so that the first of two clears (100 + 50 rows) waits at its UPDATE. It then SIGSTOPs the app backend that ran the clear's SET LOCAL statement_timeout: the socket stays open and the kernel still acknowledges writes, but nothing comes back, not even the server's timeout.
    • Branch: the first clear's rows were lockable again 15.4 s after the recheck went out, with all 100 stamps still on. The pass returned at 30.3 s with cleared=50 and the "did not finish ... the recheck did not answer within 15000 ms" line. No unhandled rejection after SIGCONT.
    • Main: the rows stayed locked for the whole 75 s the backend was stopped, and the pass only finished after SIGCONT.
  • Review. An independent read-only review of the first five commits found no correctness bug in the clear or the SQL. Its medium finding (the two per-edit scope syncs), its two low findings (the pass-level overclaim, the unbounded retire job) and its test nits are fixed in the last four commits.

Left open

  • A WebDAV COPY writes no scope itself, so a copy that becomes its ref's holder (a random uuid below its source's) gets its scope written that night by the scope pass, counted once as drift.
  • One corpus row per ref means a shared ref is found through its holder's scope alone. A twin in another folder or team does not surface it in that scope's pre-filtered search. This was already so before, when the holder was simply whichever twin was written last; it is now at least the same twin every night.
  • A connection lost in the middle of a postgres.js transaction remains a general hazard (fix(platform): close the #3739 mail stamp pass review findings #3785's note). This change bounds how long the corpus rows and the pass wait on a connection that dies during a clear. A statement issued on a transaction handle after its socket closed is still postgres.js's to handle, and a connection already dead at a clear's BEGIN (or at any other read of the pass) still holds the pass until TCP gives up.

No schema change, no migration, no user-visible strings.

Refs #3785

The corpus reconcile's re-queue of the bytes it could not delete and the
mail lanes' release each chunked their refs into knowledge.release_refs
jobs with a loop and a 500-ref constant of their own. Both now go through
queueRefRelease and RELEASE_REFS_PER_JOB in knowledge/release-queue.ts, a
module of its own so the mail lanes reach it without the release seam's
imports.

queueMessageRefRelease keeps its name for the mail lanes and delegates:
an enqueue that fails still fails the caller's transaction. The reconcile
hands in onChunkError, so a failed job is logged as before and the next
one is still queued.
The reconcile logged every failed release as "reconcile release failed
for <ref> (<stage>): <msg>" and only then re-queued the blob-stage refs
to knowledge.release_refs. A re-queue that went through logged nothing,
so an operator read a byte delete the job would retry as final.

requeueBlobFailures now logs the blob-stage lines itself, after the
enqueue. Each ends "re-queued to knowledge.release_refs", or "not
re-queued" when its job could not be queued, followed as before by the
job's "could not re-queue ... their bytes stay" line with the error.
warnReleaseFailures keeps the corpus-stage lines.
A WebDAV COPY leaves two documents on one blob ref, and the corpus has
one row for it. The indexer indexed an unbound file holding such a ref as
its lowest-id active holder (activeDocumentHoldingRef), but the nightly
scope pass and syncRagDocumentScopes wrote every active document: within
a page Postgres applied either twin to the row, a later page's twin
overwrote an earlier one's, and the row was drift again every night. On
real Postgres the old pass corrected the same row twice on every run.

Both statements now read each ref's holder alone, the active document no
lower-id active document shares its ref with, so they write the scope the
indexer indexes the ref as. The indexer reads the holder first for a file
filed into a document too (the file row of a COPY stays with its source,
whose id can be the higher one), and falls back to the bound document
when no active document holds the ref.

The new checkScopeRefHolder lane proves it on real Postgres: a trashed
lowest id, the holder and its twin on pages of their own, and a batch
sync of the twin alone.
A clear took the stamps off up to 100 corpus rows, then read their
backing again on an app transaction, and the rows stayed locked until
that read answered. Its only bound was the app transaction's server-side
statement_timeout. A half-open app connection (peer gone, no reset)
never delivers that timeout, so postgres.js waited until TCP gave up,
minutes later, while indexers and releases on those refs waited behind
the locks.

The recheck now races a 15 s client-side bound, above the server's 10 s.
When it lapses the corpus transaction rolls back with its stamps still
on, and the next night retries the clear. The clear is what its corpus
transaction did: the read-only app transaction around it is waited for
only as long again, so the pass goes on past a dead connection instead
of queueing behind its ROLLBACK. A commit whose app transaction does not
end cleanly still counts and is logged as before.

On Postgres 16, with the recheck's backend stopped (SIGSTOP), the first
clear's rows were lockable again after 15.4 s and the pass went on to
the next clear at 30 s. Before, they stayed locked as long as the backend
was stopped.
…isters

The emailed-attachment rows of automation.md and MIGRATION.md now say
that a ref several documents share is indexed and scoped as its holder,
that a re-queued byte delete goes out in jobs of at most 500 refs and
says so in its log line, and that the clear's recheck has a 15 s bound
of its own which the pass does not wait out. The scope stamps row of
automation.md names the holder rule and the checkScopeRefHolder lane,
and the attachment row lists release-queue.test.ts.
The scope pass, the batch scope sync and the indexer now agree on a
ref's holder, but the two other scope writers still wrote whichever
document was edited. syncRagDocumentScope wrote an edited twin's scope
over the holder's, and syncRagFolderSubtree wrote every document under
a renamed folder, two twins under it in one statement. The next night
the scope pass wrote the holder's scope back and reported "the per-edit
sync had failed for these" after every edit of a non-holder twin (a
WebDAV COPY, or one upload bound as two documents).

syncRagDocumentScope now writes the scope of its ref's holder
(activeDocumentHoldingRef), and the edited document's own only when no
active document holds the ref, so an edit of a trashed document still
reaches its row. subtreeDocumentFolderPaths reads each ref's holder
alone, as the reconcile does.

checkScopeRefHolder covers both on real Postgres. Without this change,
the twin's edit writes its own team and the twin's folder rename writes
its folder's path. The indexer's holder test now also pins the order it
reads the holder in.
releaseUnlistedTaskBlobRefs handed every ref a hard delete orphaned to
one knowledge.release_refs job, and a project's whole task tree can
orphan thousands. It now queues them through queueRefRelease, at most
RELEASE_REFS_PER_JOB to a job, as the mail lanes and the reconcile do,
still in the retire's own transaction. The docstrings that said every
release lane bounds its jobs are now true, and say which lanes they
mean.
The fake-timer test proved the clear rolls back when its recheck never
answers and that the pass then goes on, but a pass that waited for the
dead app transaction's end for a millisecond or for the whole 15 s bound
passed alike. It now checks the pass is still waiting a millisecond
before that second bound lapses, and has gone on to the next clear once
it has.
The registers and the stamp clear's docstring said the pass goes on
past a dead connection. The bound covers a connection that stops
answering during the clear, its recheck and its app transaction's end.
One already gone at the clear's BEGIN holds no corpus row, and holds the
pass as any other read of it would. Both now say that.

The emailed-attachment rows also name every scope writer as following
the holder, and one upload bound as two documents as a second way to
share a ref. They name a task retire among the lanes that bound their
release jobs.
@yannickmonney
yannickmonney merged commit d06bf9b into main Sep 29, 2026
50 checks passed
@yannickmonney
yannickmonney deleted the fix/mail-stamp-release-helper-holder-recheck branch September 29, 2026 06:04
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