Skip to content

fix(threading): a leftover row is a violation, not a design note - #1133

Merged
lilyshen0722 merged 2 commits into
mainfrom
fix/threading-backfill-leftover-invariant
Aug 22, 2026
Merged

lilyshen0722 merged 2 commits into
mainfrom
fix/threading-backfill-leftover-invariant

Conversation

@lilyshen0722

Copy link
Copy Markdown
Contributor

Two commits that landed on feat/threading-2-follow-state about four minutes
after #1109 squash-merged. The PR was already closed, so they never reached
main and nothing tested them. Recovered here off current main, unchanged.

1. A leftover row is an invariant violation, not a design note

The backfill used to close with:

remaining with a reply edge and no root: N (orphaned chains stay NULL by design)

@sprint-review showed that on this database that sentence cannot be true.
I had checked the write direction — the reply_to_message_id FK refuses a
reply whose parent does not exist. They pointed out the delete direction is
also shut: ON DELETE SET NULL means deleting a parent clears the child's
reply edge rather than orphaning it, so the child stops matching the
predicate entirely. Both routes to a dangling edge are closed.

So where the FK binds, a non-zero N is not orphaned history. It is the
recursive walk failing to reach rows it should have — reported as by-design,
in a parenthesis, at exit 0. And the cutoff recorded on that same run would
have been computed over the rows the walk missed.

Verified against the live instance rather than assumed: all three FKs are
present, including messages_reply_to_message_id_fkey … ON DELETE SET NULL,
and there are zero dangling edges.

The line is now conditional on the constraint actually being installed, asked
of pg_constraint rather than assumed in either direction:

  • FK present → INVARIANT VIOLATION on stderr, exitCode = 4, naming why
    the cutoff is not trustworthy on that run.
  • FK absent → the old wording, which is accurate on an instance predating
    the constraint, where genuine orphans are possible.

Asking the database is the point. CREATE TABLE IF NOT EXISTS never retrofits
a constraint onto an existing table — the same gap that nearly shipped
thread_root_id as a column that would never have existed on any live
instance. A self-hosted deployment can legitimately be in either world.

2. Two stale claims in my own test headers

Both were completeness claims that were true of the cases I had hit and false
of the space:

  • "only the recursive CTE is out of reach at this tier" — WITH … INSERT is
    also unsupported by pg-mem.
  • "tier 1 is where foreign keys and ON DELETE CASCADE get exercised" —
    pg-mem enforces both.

Tests

4 new cases in threadingCutoffRecord.test.js (26 pass): that the
unconditional by-design wording is gone, that a leftover reports as a
violation and exits non-zero, that the FK is checked rather than presumed,
and that the message says why the cutoff depends on it.

🤖 Generated with Claude Code

lilyshen0722 and others added 2 commits August 22, 2026 12:03
@sprint-review 56933 flagged a pod message of mine as stale against my
own file. The message was already retracted in-pod; the FILES were not,
and they are what outlives the chat.

Two overclaims, both mine:

1. "Only the backfill's recursive CTE is out of reach" is a claim about
   pg-mem, and I know of at least one more limitation without having
   surveyed them — `WITH ... INSERT` also fails, found while probing
   workarounds. Nothing shipped uses it, which is precisely why the
   completeness claim was untested. Rescoped to "of what this codebase
   needs".

2. The same header sent readers to tier 1 for "the foreign keys, ON
   DELETE SET NULL". pg-mem enforces both — threadFollowByParticipation
   rejects a phantom root and observes a CASCADE, on pg-mem, since the
   tables started coming from schema.sql. That line would have pushed a
   reader to the slow tier for something the fast one already covers.

The tier-1 header carried the original "pg-mem cannot run this — a real
server or it is nothing", which outlived the finding that disproved it
by four hours. Corrected in place rather than rewritten, and it now says
why claim 1 is deliberately covered at both tiers, so nobody deletes the
fast suite as redundant: it is the one that runs on every push.

Third completeness claim of mine to need correcting today. The pattern
is stating a bound ("only X", "there are two") when I have checked the
instances I happened to hit rather than the space.

Co-Authored-By: Claude Opus 5 <[email protected]>
@sprint-review 56936 carried my FK finding further than I had, and it
turns a reassuring log line into a masked failure.

I showed the write half: the FK refuses a reply to a missing parent, so
a dangling edge cannot be written. They showed the delete half closes
the other direction — ON DELETE SET NULL means deleting a parent CLEARS
the child's reply edge rather than orphaning it, so the child stops
matching the backfill's predicate entirely. Both routes are shut.

Which means the script's own line was explaining away a bug:

  remaining with a reply edge and no root: N (orphaned chains stay NULL by design)

If that state is unreachable, a non-zero N is the recursive CTE failing
to reach rows it should have — reported as by-design, in a parenthesis,
at exit 0. Same shape as a diagnosis written for one cause printing on
every trigger.

Now: leftover + FK present => INVARIANT VIOLATION on stderr, exit 4, and
it says why it matters (the recorded cutoff assumes that set is empty).
Leftover + no FK => the old wording, which is honest there.

Their caveat is why it asks rather than asserts: CREATE TABLE IF NOT
EXISTS never retrofits a constraint, so the FK binds only databases
created after it entered schema.sql. They could not run the query that
settles it; I could. On the live instance all three FKs are present —
including reply_to_message_id with ON DELETE SET NULL — and there are
zero dangling edges, so the strong form holds there.

Co-Authored-By: Claude Opus 5 <[email protected]>

@lilyshen0722 lilyshen0722 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Gate: approve at c003d0ab. CLEAN, base=main. This is the right fix and it is built on the right reasoning.

The defect being removed is a genuine one and worth naming precisely. The old line printed (orphaned chains stay NULL by design) unconditionally — a diagnosis written for one cause, printed on every trigger, in a parenthesis, at exit 0. It would have explained away a recursive CTE that failed to reach rows it should have. That is the same shape as a guard whose hardcoded failure text names one cause and re-prints on every other.

The conditional is the part I would have insisted on, and it is already here. CREATE TABLE IF NOT EXISTS never retrofits a constraint, so the FK binds only databases created after it entered the file. On an older instance orphans genuinely are possible and "by design" is the honest wording. Asking pg_constraint which world the database is in — rather than assuming either — is exactly right, and it makes the check correct on both.

The error text is a model of the form. It states the observation, both reasons a dangling edge should be impossible (the FK refuses the write; ON DELETE SET NULL clears the edge rather than orphaning the child), the inference that follows, and the consequence: "the recorded boundary assumes this set is empty." A reader who hits this knows what to investigate and why it matters, which is more than most invariant failures manage.

I checked the case that would have made the diagnosis wrong. A retention-deleted root (TASK-043) leaves a grandchild with a live parent and a null root, which lands in exactly this still_null count on a later run — and the message would then blame the walk. It does not, because the walk reaches it: deleting root R promotes C to reply_to_message_id IS NULL, which is the recursive CTE's seed condition, so G is joined through C and rooted. Any row the CTE can reach gets rooted, so a leftover really does mean unreachable, and the message is accurate for the population that can actually survive.

One note, not blocking

The test at "but asks the database whether the FK actually binds first" carries hand-rolled wrap tolerance:

expect(SRC).toMatch(/predates `?\n?\s*\+?\s*'?the reply_to_message_id FK/);

That is the matcher-spanning-a-comment-line-break problem being worked around inside the regex rather than removed. It passes today, it is hard to read, and it fails the moment the concatenation is re-indented differently. Normalising whitespace on SRC before matching — the fix already applied elsewhere today — makes all four of these assertions shorter and immune to reflow. Same note I left on #1120's wiring guard, same reason.

Not verified: I did not run the script against a database with still_null > 0, so the FK-present and FK-absent branches are read rather than executed. The tests here assert the source text of both, not their behaviour — which is appropriate for a message and an exit code, but means neither branch has been observed firing.

@lilyshen0722
lilyshen0722 merged commit f0e4a5d into main Aug 22, 2026
12 checks passed
@lilyshen0722
lilyshen0722 deleted the fix/threading-backfill-leftover-invariant branch August 22, 2026 19:42
@lilyshen0722

Copy link
Copy Markdown
Contributor Author

Do not run --apply on this script until TASK-046 lands (ux-lead, 2026-08-22 22:30Z; pod 57375).

The 22:28Z dry run on the live pod recorded cutoff 2026-08-22T12:21:11Z — produced by CUTOFF_SQL = SELECT MAX(created_at) (backfill-thread-root-id.ts:141), i.e. data-derived. The ruling (docs/design/threading-surface-ruling.md, #1131) is that the cutoff is a known event carried as a constant: the derivation deploy cutover, 2026-08-22T16:01:52Z (backend pod startTime at image 5032bc3e; the script's own header at :46 names it). The ledger row is permanent under ON CONFLICT DO NOTHING, so a wrong value cannot be re-run away.

Fix before pressing: replace CUTOFF_SQL with the constant; delete :122-123 ("NULL … never as unknown" — the rejected rule, contradicted by :186); re-run the dry run (expect 245 rows / 172 threads / 16:01:52Z); then --apply.

@lilyshen0722

Copy link
Copy Markdown
Contributor Author

Update (22:55Z): the fix is #1148 — cutoff = first rooted reply (MIN over rooted replies), un-rooted MAX only as a --derivation-live fallback, cutoffSource recorded, rejected sentence removed. Hold on --apply stands until #1148 is deployed and a fresh dry run prints a cutoff just after 2026-08-22T16:01:52Z.

@lilyshen0722

Copy link
Copy Markdown
Contributor Author

Update (22:50Z) — operator instructions for the --apply, superseding the two notes above:

  1. Wait for fix(threading): the backfill records the first rooted reply as the cutoff, not the newest un-rooted one (TASK-046) #1148 (TASK-046) to merge and deploy. It makes the backfill read the ledger first, record the cutoff from the first derivation-written reply (falling back to the newest un-rooted reply only behind --derivation-live), write cutoffSource, and run the UPDATE + ledger INSERT in one transaction.
  2. Run the dry run in the live pod. It prints the un-rooted count, the rooted-reply count, and the cutoff it would record with its source.
  3. If it prints rooted replies: 0 (nobody has replied since derivation went live), the primary is NULL and the fallback value — 2026-08-22T12:21:11Z — is the exact last pre-threading reply on this orphan-free instance. Run --apply --derivation-live; the ledger records it flagged newest-unrooted-fallback. If it prints a positive rooted count, run plain --apply.
  4. Expect 245 rows / 172 threads either way.

The hold was against an unflagged, unattributed data-derived value; after #1148 that cannot be written. Ruling text: docs/design/threading-surface-ruling.md (#1147).

@lilyshen0722

Copy link
Copy Markdown
Contributor Author

Hold lifted (23:10Z). #1148 merged and deployed (run 32604079755); the live dry run prints 245 rows / 172 threads and cutoff 2026-08-22T16:16:37Z from the first derivation-written reply (9 rooted replies observed). Plain --apply is correct; no --derivation-live needed.

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