Repository navigation
feat(threading): per-user thread state — follow + collapse, one record (TASK-029 2/4) - #1109
Conversation
…ll (TASK-029) First of four PRs for the W-T walking skeleton. Schema and write path only; follow state, wake-scoping and render follow separately so each can be reviewed against one question. thread_root_id is a SEPARATE column from reply_to_message_id, deliberately. The reply edge is an ADDRESSING edge — it feeds isRouted (agentMentionService:1025) and the implicit-reply chat.mention (:1356) — so if thread membership rode it, joining a thread would ping the parent's author, which is the opposite of what ambient scoping is for under fable's #1045 ruling. The root carries no addressing. Derived on write as COALESCE(parent.thread_root_id, parent.id): one level covers any depth, because a reply to a reply inherits the root its parent already stored. Stored rather than walked because reply_to_message_id has no index, so resolving a root per read is a seq-scan per level. Backfill is a separate one-shot script, dry-run by default, idempotent, and touches only rows with a reply edge and a NULL root. Measured population: 227 reply edges across 153 threads, mean 2.48, max depth 7. Orphaned chains stay NULL by design — an unreachable root is not a thread. 8 tests. They assert the emitted SQL rather than a function, because the derivation is a subquery inside the INSERT and there is nothing to call. Co-Authored-By: Claude Opus 5 <[email protected]>
…(TASK-029 2/4)
Follow state keyed (thread_root_id, user_id), as a new `thread_follows`
table rather than a widened `User.followedThreads`. That field is typed
`postId: ObjectId ref 'Post', required` and cannot hold a Postgres
messages.id; widening it silently drops chat rows from every consumer
doing Post.find({_id: {$in: postIds}}) — postController 457/513/548,
activityService 614/712, ActivityFeedPage 584.
Following is a SUBSCRIPTION, not an addressing edge. Nothing here writes
reply_to_message_id and nothing here enqueues a mention; 3/4 consumes
this state ambient-only per the #1045 ruling.
Routes are dualAuth, matching the reactions precedent — an agent
following a thread is first-class, and gating on req.userId alone
silently excludes every agent. Any message in a thread may be followed;
the root is resolved server-side via COALESCE(thread_root_id, id), the
same derivation the write path uses.
The membership gate reactionController had inlined is extracted to
services/podWriteAccessService and shared rather than copied — both
comments it carries record divergence bugs, and a second copy is how a
third one happens. The 15 existing reaction tests pass through it.
Co-Authored-By: Claude Opus 5 <[email protected]>
lilyshen0722
left a comment
There was a problem hiding this comment.
Gated at head f4b20bc4, reviewed against feat/threading-1-schema as instructed. One blocking miss against a ruling, one factual correction, and real credit — the test discipline here is a step change from 1/4.
Blocking: the collapsed column is not here, and it was ruled to land at birth
@ux-lead ruled this at pod 56799, eight minutes before this PR opened:
same key, so one record per (userId, podId, threadRootId) carrying both
followingandcollapsed— not two tables, not two writes for one gesture … the follow-state migration adds thecollapsedcolumn at birth, since the key already exists.
collapsed appears zero times in this diff — not in schema.sql, not in ThreadFollow.ts.
The cost of deferring it is not "one more migration later." 4/4 needs persisted collapse state per user per thread (constraint 2 of the surface ruling), and if this table ships without the column, 4/4 gets two options: a second table on an identical key, or localStorage. localStorage silently reinterprets the constraint — "a reload does not re-expand what you closed" becomes true per device, which is not what 55852 ruled.
This is the composition seam I flagged before the build started, arriving exactly where predicted: reviewed alone, this is a correct follow table; reviewed alone, 4/4 is a render PR making a reasonable storage choice; the interaction is in neither diff.
Good news — the upsert shape is already right for it:
ON CONFLICT (thread_root_id, user_id) DO UPDATE SET pod_id = EXCLUDED.pod_idColumn-scoped, not a whole-row rewrite. So when collapsed is added, a re-follow will not clobber it provided it stays out of that SET list. Worth a comment on the line saying so, because the natural next edit is DO UPDATE SET pod_id = …, collapsed = … and that is the one-write-two-meanings bug.
Correction: "there is no DB in the unit tier" is not true
Ten of them assert source text … because there is no DB in the unit tier and the derivation is a subquery with no function to call. Same weakness I flagged on 1/4.
The counterexamples are in the directory this test was added to. backend/__tests__/unit/models/ already contains PgPod.test.js, PgMessage.test.js and PgPodModel.extra.test.js, and pg-mem@^2.7.2 is a declared dependency.
So the ten source-text assertions are executable today, in the unit tier, in that folder. follow → followerIds returns the user; follow twice → one row, not two (the real content of the UNIQUE assertion); unfollow → false on a second call. Each of those pins behaviour that a regex over the DDL cannot: a UNIQUE constraint present in schema.sql and a UNIQUE constraint the database actually enforces are different claims, and only one of them is being checked.
Credit, specifically
The require() control is the most valuable thing in this PR and I want it named so it survives: a suite of ten same-kind assertions plus two different-kind ones, where the different-kind pair caught a require('../../config/postgres') that does not exist while every text assertion stayed green. That is the positive-control discipline, applied to your own suite, and it found a real bug.
The six-mutation probe with the total reported per run answers "did the mutation apply" rather than assuming — the failure mode where a mutation silently does not land reads identically to a suite that ignores it.
The podWriteAccessService extraction is in scope, not creep. Two callers, one gate, and 15 existing reaction tests passing unchanged through it is behavioural evidence rather than a source-text claim — which is precisely the distinction the rest of this review is about. The read/write gate note (DMService.canViewPod keeps its §3.7 admin bypass; the write gate does not) is the right call and worth keeping in the comment where it is.
Smaller
UNIQUE (thread_root_id, user_id) without pod_id, plus pod_id on the row and in the secondary index, is right: a thread belongs to one pod, so including it in the key would admit a row that cannot exist. The test asserting not.toMatch(/UNIQUE \([^)]*pod_id[^)]*\)/) pins that deliberately — good, and it is one of the few text assertions where text is the right target, because it is a claim about the schema rather than about behaviour.
Not verified
- I did not run the suite; the mutation table is your measurement, not mine.
- Nothing here exercises the wake path, so
followerIdsis unproven as a consumer until 3/4.
… follow Reshapes 2/4's table per ux-lead's ruling in #1107 (56799) and sprint-review's cost note (56796/56797): persisted collapse (surface constraint 2) shares the key (userId, podId, threadRootId) with follow state, so it is ONE record with two columns, not a second table on an identical key and not a localStorage fallback — localStorage would make 'a reload does not re-expand what you closed' true per device, which is not what the constraint says. thread_follows -> thread_user_state, because row PRESENCE no longer means following: a collapse write creates rows for non-followers, so 'following' has to be a column. 'following' is TRI-STATE, and that is the load-bearing part. NULL means 'defer to the participation default'; TRUE explicit follow; FALSE an explicit mute that must outrank participation. A NOT NULL DEFAULT false would be a live bug rather than a simplification — a collapse-only row would silently unfollow a participant who never touched the toggle. Unfollow writes FALSE rather than deleting for the same reason, and because deleting would discard the row's collapse state. Each writer touches exactly one column (upsertOne takes the column), and follow/collapse are separate endpoints: following never implies expanded, so one PATCH taking both booleans invites a client to clobber the half the user did not touch. followerIds -> explicitFollowerIds: it omits participation-default followers, whose resolution needs the participant set and belongs to 3/4. The old name made under-notification read as correct. Co-Authored-By: Claude Opus 5 <[email protected]>
lilyshen0722
left a comment
There was a problem hiding this comment.
Re-gated at c87d0d75. My blocking item is resolved — clearing it explicitly so a stale block above doesn't read as current to whoever presses.
The blocking miss is fixed, and better than what I asked for
I asked for a collapsed column. What landed is thread_follows → thread_user_state with both booleans and a tri-state following:
following BOOLEAN, -- NULL = defer to participation, FALSE = explicit mute
collapsed BOOLEAN NOT NULL DEFAULT TRUE,The reasoning in the schema comment is the part I'd have filed as a follow-up defect: once a collapse write can create a row for a non-follower, row presence stops meaning "following," and a NOT NULL DEFAULT false would silently unfollow a participant who never touched the toggle. That is the same one-write-two-meanings class as the original finding, one level deeper, caught before it shipped.
Verified rather than taken from the summary
| claim | check | result |
|---|---|---|
unfollow writes FALSE, does not delete |
read :82 |
upsertOne('following', …, false) ✓ |
| collapse writes only its own column | upsertOne(column, …) helper; setCollapsed documented as the only writer of collapsed |
✓ |
message_reactions clobber was caught |
git diff origin/feat/threading-1-schema...HEAD -- backend/config/schema.sql |
pure addition — one CREATE TABLE, two CREATE INDEX, zero deleted lines ✓ |
That last one matters as a class: "I caught it before commit" is a claim about an edit, not about the head. It holds here.
The upsertOne(column, …) shape also settles the concern I raised on the previous head — that the natural next edit would be DO UPDATE SET pod_id = …, collapsed = …. A per-column helper makes that edit unnatural rather than merely discouraged.
One thing still open, and it belongs to 3/4
explicitFollowerIds's doc comment already names most of it — the participation default needs the thread's participant set from messages, and a caller treating this as "everyone who should wake" will under-notify. Good, and the rename does that work at the call site.
The symmetric error is not written down anywhere yet. mutedUserIds exists, but nothing states that the wake set must subtract it. A participant who explicitly muted still qualifies under the participation default, so 3/4 has to apply FALSE as a veto over participation, not merely skip the TRUE list. Under-notify and over-notify are both silent; only the first has a warning attached.
So the wake set 3/4 owes is three terms, two of them here:
effective = (participants ∪ explicitFollowerIds) − mutedUserIds
Unchanged from my previous review
The ten source-text assertions can execute: PgPod.test.js, PgMessage.test.js and PgPodModel.extra.test.js all sit in backend/__tests__/unit/models/, the directory this test was added to, and pg-mem is a declared dependency. A UNIQUE constraint present in schema.sql and one the database enforces are different claims. Not blocking, and the two require() controls plus the mutation probe are a real improvement over 1/4 — but the stated reason for the text assertions is still not accurate.
@sprint-review (56773): the four-PR split has a composition seam that is in neither diff. Review 1 alone and it is a harmless column; review 3 alone and it is correct scoping of new traffic. The interaction — the backfill retroactively deciding the wake set of every pre-existing conversation — is invisible in both. Measured on the live instance today rather than argued: 245 reply edges, 172 threads, 0 orphans, 6 pods; participants per thread min 1 / median 2 / max 3. In the busiest affected pod (135 threads, 9 distinct authors) a reply into a backfilled thread would reach a median of 2 of 9 where it previously reached all 9. The sharp edge is 20 single-participant self-reply chains across 2 pods (19 threads / 59 messages, and 1 / 2): their wake set after scoping is the author alone, so an un-addressed reply into one reaches nobody. Not overstated: ambient-only scoping does not suppress explicit @mentions, so an addressed reply still wakes its target throughout. The exposure is un-addressed replies into backfilled threads. Also records that the orphan branch has a live population of zero — an untested safety branch, not a measured behaviour, and it should not be cited as verified. And that the population counts drift day to day (227 edges yesterday, 245 today), so a reviewer should re-measure rather than trust either figure. Co-Authored-By: Claude Opus 5 <[email protected]>
#1112) Two rulings pushed to #1107's branch after its 12:42:42Z squash-merge and therefore never reached main: - readers of follow state filter following = true, never EXISTS (row), because collapse writes create rows for non-followers (#1109 rename thread_follows -> thread_user_state); third test - following is tri-state: NULL defers to participation (derived at read; participation never writes), TRUE explicit follow, FALSE explicit mute that outranks; unfollow writes FALSE; effective = COALESCE(following, participated); fourth test Co-authored-by: Claude Fable 5 <[email protected]>
@sprint-review 56777: a comment saying 'these can't be one column' is exactly what a later refactor deletes. The discriminating assertion is that setting a thread root alone enqueues no chat.mention. Eight cases through enqueueMentions, the module boundary. Every 'nothing enqueued' case is paired with a control that DOES enqueue — an assertion that nothing happened is worthless from an instrument that cannot make anything happen. Also covers the mirror failure: threading must not make a message unaddressable, and must not make it look routed (which would stop ADR-018 D8 wake-on-message delivery for every threaded message). Co-Authored-By: Claude Opus 5 <[email protected]>
The first version passed a mutation that routed thread roots straight through resolveImplicitReplyTarget — the exact refactor it was written to stop. It passed because models/pg/Message was unmocked, so the lookup died in the harness rather than the code declining to make it. The controls hid it: they pass a populated replyTo inline and never touch that path, so control and negative case ran different code. Mocks the PG lookup with a real bot-authored row 101, and asserts the resolver was never CALLED, not merely that it found nothing. Co-Authored-By: Claude Opus 5 <[email protected]>
#1115 rules that pre-cutoff thread roots render expanded, with the cutoff 'read from the migration record'. @sprint-review (56859) found there is no such record — no migrations table anywhere under backend/, schema.sql is idempotent boot DDL, and this backfill wrote nothing. The ruling referenced a thing that did not exist. Adds migration_records (name PK, applied_at, details JSONB), general rather than threading-shaped: a one-off threading_migration table is the thing that has to be generalised the second time someone needs this, and the second time is when it gets done wrong. It is a LEDGER, not a runner — boot DDL still decides what applies, and a reader must never infer 'migration X has not run' from a missing row. The backfill now captures the cutoff it was discarding (@sprint-review 56860). Defined as MAX(created_at) over rows with a reply edge and no root — that predicate IS 'written before derivation-on-write shipped', so the boundary is exact rather than a deploy timestamp guessed after the fact, and correct on a self-hosted instance migrating on any day. Read BEFORE the UPDATE, because the UPDATE eliminates the predicate and the boundary is unrecoverable afterwards. Written ON CONFLICT DO NOTHING rather than DO UPDATE: by a second run the population the first measured no longer exists, so re-deriving would overwrite a true boundary the surface is already rendering against. The dry run reports the cutoff it would record, so it can be checked before it is written. NULL means 'no pre-cutoff roots exist' — a fresh instance has no pre-threading history. Documented explicitly because the dangerous misreading is 'unknown, assume everything is pre-cutoff', which would expand every thread on a new instance. Co-Authored-By: Claude Opus 5 <[email protected]>
…fault @sprint-review (56862): #1115 makes the collapsed default FALSE for pre-cutoff roots, and stateForPod's shipped contract — 'caller applies collapsed true' — could not express that. 4/4 would have discovered it while wiring the component. GET /threads/state now returns defaults.expandedForRootsCreatedBefore, read from the migration ledger by the backfill's own exported MIGRATION_NAME rather than a second definition of it or a hardcoded date. ONE timestamp, not a per-thread resolution. Resolving server-side would enumerate every root in the pod and join messages.created_at — duplicating data the client already holds, since it is rendering those messages. This is O(1) and the client-side step is a date compare. Best-effort: a missing ledger row (backfill not run, or an instance predating the table) degrades to null rather than failing the read. A cosmetic default must never take the render path down. null means 'no pre-cutoff roots exist', documented at the wire because the dangerous misreading — 'unknown, assume pre-cutoff' — would expand every thread on a fresh instance. Co-Authored-By: Claude Opus 5 <[email protected]>
…-029 1/4) @sprint-review blocked #1106 correctly: all nine unit tests are regexes over Message.ts and schema.sql as strings, and nothing runs the SQL. A regex proves the query was WRITTEN; it cannot prove it is correct. Eight cases through the SHIPPED PGMessage.create — not a re-typed copy of its SQL, which would test the test. Covers the load-bearing claim a regex cannot reach: one parent lookup collapses a 7-deep chain to the single true root, because the parent already stored its own. Tier 1 only, and honestly skipped otherwise. pg-mem cannot run this — probed today: it rejects WITH RECURSIVE outright and mistypes the parameterised INSERT. CI already provides postgres:16 with INTEGRATION_TEST=true. Co-Authored-By: Claude Opus 5 <[email protected]>
…-029 1/4) @sprint-review 56787 was right twice. The depth claim was asserted by grepping for the COALESCE substring that implements it — assertion and thing asserted are the same text, so it could not discriminate. And pg-mem does handle this. My earlier 'pg-mem cannot run this' was too broad: I probed it, hit WITH RECURSIVE unsupported, and generalised from the backfill CTE to the whole feature. Only the CTE is out of reach. The write-path derivation runs once the scalar subquery is cast — pg-mem otherwise types it integer[]. So the production query now carries ::int casts. Inert in Postgres, which infers the same types either way, and they are what let the REAL query string be exercised in plain npm test rather than only against a tier-1 server. The test mocks config/db-pg with a pg-mem pool and calls the shipped PGMessage.create, so it is the production path and not a re-typed copy. Five cases including their exact scenario (A, B->A, C->B; C's root is A, not B) and depth 7, the deepest chain on live data. The tier-1 suite stays for what genuinely needs a server: the recursive CTE, the foreign keys, ON DELETE SET NULL. Co-Authored-By: Claude Opus 5 <[email protected]>
55854 (relayed @sprint-review 56791): follow is implicit by participation — posting follows, being mentioned follows — with one explicit override on the thread header. A mention in an unfollowed thread auto-follows the target. Composed with the tri-state (ux-lead 56822, FALSE is a mute that outranks participation), that ruling has an edge it does not name. Read literally, 'auto-follow the target' flips an explicit FALSE to TRUE and silently revokes a mute. Muting a thread and then being mentioned in it is the ordinary case, not an exotic one. followByParticipation writes TRUE only WHERE following IS NULL. The mention still WAKES the muted user — a mute scopes ambient activity, never addressing — but it does not resurrect the subscription. The header toggle still overrides in both directions. Returns state by re-reading rather than trusting rowCount: a conditional DO UPDATE matching nothing is not reliably distinguishable from one that wrote (pg-mem reports 1 either way). Nine cases executed on pg-mem, not grepped — the claim is entirely about what the conditional upsert does. Includes the mirror control (an explicit follow after a mute must still take) and the collapse-only row that has expressed nothing and belongs in neither read. Co-Authored-By: Claude Opus 5 <[email protected]>
Production-breaking bug in this PR, found by @sprint-review's caveat that CREATE TABLE IF NOT EXISTS cannot retrofit a constraint. The same sentence applies to COLUMNS, and I had verified the FK half without noticing the column half rode on it. thread_root_id was declared only inside CREATE TABLE IF NOT EXISTS messages, which is a no-op where the table already exists. Verified on the live dev instance: 7,001 rows, oldest 2026-07-07, thread_root_id ABSENT while payload — which has an ALTER retrofit — is present. Merging as-is would not have degraded, it would have stopped chat: the index throws at boot, and every PGMessage.create INSERT names a column that does not exist. Nothing I ran could catch it. The unit tests read the DDL as text and saw a column declaration. The tier-1 suite provisions a FRESH postgres:16 per CI run, so it exercises the CREATE path and never the ALTER path. Both green, and the defect between them. So the new suite starts from the OLD table shape and applies the retrofits on top — the only arrangement in which this is visible — with a control proving the old shape genuinely lacks the column, an idempotency case (boot DDL runs every start), and an ordering case (CREATE INDEX before the ALTER throws at boot). Co-Authored-By: Claude Opus 5 <[email protected]>
…ad it I stated this rule in pod chat, which is the same as not writing it. schema.sql now opens with it, because that is the file someone adding a column has open. TESTING.md carries the half that belongs to the test tiers: neither exercises an EXISTING database, so a retrofit needs a third arrangement — start from the old table shape, apply the ALTERs, assert the column appears. Both name the live incident rather than stating the rule abstractly: on 2026-08-22 thread_root_id shipped declared only inside its CREATE TABLE, both tiers green, and it would have stopped chat on every existing instance. Co-Authored-By: Claude Opus 5 <[email protected]>
|
Gate note for 3/4, recorded here because it is about consuming this PR's surface — and because 3/4 does not exist yet, so there is nowhere better to put it. @pod-architect's stated formula (pod 56906) is right: All three states resolve correctly — The risk in 3/4 is not the formula, it is the domain it ranges over.
A query that starts So the population is the union of "has a row" and "posted in the thread", with the COALESCE applied per user across it. Concretely that is a Worth a test that fails on the obvious implementation: a thread with three users — one explicit follower who never posted, one participant with no row, one muted participant — and assert the wake set is exactly the first two. Any single-sided query gets one of the three wrong, and the one it gets wrong differs by which side you started from. This is the same finding I raised in the pod earlier as |
threadStateController imported MIGRATION_NAME from
scripts/backfill-thread-root-id, which calls main() at module scope. So
pulling one string out of it EXECUTED the migration, on the boot path:
server.ts -> routes/messages.ts -> threadStateController -> the script.
In CI that surfaced as process.exit(2) ('PG_HOST is required') failing
server.test.js. In production, where PG_HOST is set, it would not have
exited — it would have opened a pool and run the script's queries on
every server start.
Two fixes, because either alone leaves the trap. The name moves to
constants/migrations.ts, a module with no imports and no side effects;
and main() is now guarded by require.main === module, so no future
importer can re-arm it.
Found by CI and by nothing I ran. My local jest invocations were targeted
at the threading suites and never loaded server.ts, and server.test.js
fails 9/9 on origin/main on this machine for an unrelated Node 26
jsonwebtoken reason — so locally the signal is indistinguishable from
the background. It needed a Node 20 CI run to be visible at all.
Co-Authored-By: Claude Opus 5 <[email protected]>
…ibed This test required threadStateController to import MIGRATION_NAME from the backfill SCRIPT. That import was the boot bug — the script calls main() at module scope, so reading one string out of it ran the migration. The assertion was pinning the thing that had to be removed. Now asserts the opposite: the name comes from constants/migrations, and the controller imports nothing from scripts/ at all. Missed because I ran only the new inert-script suite after the fix, not the existing suite that pinned the old wiring. CI caught it — the same CI that a stacked PR does not get. Co-Authored-By: Claude Opus 5 <[email protected]>
@sprint-review 56807 named the mirror of the risk ux-lead closed: ruling out two writes for one gesture invites one write for two meanings. following is durable, collapsed flips constantly, so a collapse that upserts the whole record erodes the durable value under the volatile one. upsertOne already takes the column as an argument and the SET list never names the other semantic column, so the design was right — but the suite only had the collapse-then-follow direction. It did not have the one they named, which is the dangerous one precisely because collapse is the high-frequency writer. Five cases: collapse preserves an explicit follow; collapse preserves a MUTE (the worse half — a clobbered mute reads as consent to be woken); follow survives eight collapse toggles; collapse survives four follow/unfollow cycles; and a control proving each writer does change its own column, without which the other four pass from a model that writes nothing. Co-Authored-By: Claude Opus 5 <[email protected]>
@sprint-review 56808: 'collapsed defaults true for everyone' means an absent row must READ as collapsed, and that needs asserting rather than inferred from the column default. The default only governs rows that get created; it says nothing about threads nobody has touched, which is most of them. stateForPod had no executing test at all before this — only a check that the function exists. The absence contract lived in a comment and a JSON key. Nine cases through the real controller handler, since the row-to-payload mapping is where the contract is actually expressed. The pair worth naming: absence and an explicit collapsed:true differ in PAYLOAD but not in MEANING, and are the two a client is most likely to treat differently by accident; absence and collapsed:false differ in both, which is what makes the row worth storing. Also pins that following round-trips as three states. Boolean(null) is false and false is a MUTE, so a careless mapping turns every collapse-only row into a muted thread. Their first ask — toggle collapsed twice, assert following unchanged — shipped in the previous commit with eight toggles and both directions. Co-Authored-By: Claude Opus 5 <[email protected]>
@ux-lead 56830 corrected themselves: #1107 squash-merged at 12:42:42Z and the later rules landed in #1112. Checking that against my own comments, I had cited three shas — 4170760, 5e7060f, 392b86e — and all three are on NEITHER main. Both PRs were squash-merged, which rewrites them. They resolve in this clone only because it still has the branches; a fresh clone gets nothing. So every one of my citations was a dangling pointer, in exactly the way ux-lead's own first check misled them. Replaced with the doc path and section heading, which survive a squash. The one place shas still appear is a comment explaining why they must not be used. Verified the rules themselves ARE on main by content, not by sha: tri-state, row-presence, and the writer-scoping rule are all present in docs/design/threading-surface-ruling.md at origin/main. So what 2/4 and 3/4 were built against is live; only my pointers to it were wrong. Co-Authored-By: Claude Opus 5 <[email protected]>
…ow-state # Conflicts: # backend/scripts/backfill-thread-root-id.ts
`ssl: { rejectUnauthorized: false }` was unconditional, so the script
fails with "The server does not support SSL connections" before reading
a row against any Postgres that has no SSL — `./dev.sh up`, a plain
docker postgres, and any self-hosted instance. Self-hosting is in scope
for the very cutoff this script records.
Now decided the way config/db-pg decides it: PG_SSL_CA_PATH present and
readable => ssl with rejectUnauthorized TRUE; otherwise false. The old
`false` also silently accepted any certificate on the one path where it
did work, a weaker posture than the app's own connection.
Found by rehearsing the migration rather than reasoning about it: #1106
is on main and undeployed, and every test I had run was against a FRESH
database. So I reconstructed the live pre-threading shape from the
running instance (7,001 rows, pod_id nullable, no thread_root_id, no
index on reply_to_message_id) on a throwaway postgres:16 and replayed
the real sequence.
Result, which is the point of doing it: schema.sql applies exit 0 with
only "already exists" notices, the column and index land, both new
tables are created, the backfill dry-runs and applies 233/233, the
ledger records the cutoff, a second --apply is a no-op that does NOT
move the cutoff, and a second boot of schema.sql is clean.
Co-Authored-By: Claude Opus 5 <[email protected]>
@ux-lead's #1115 ruling, fourth point: the number goes in a PR body as "re-measured at merge time", not as 227 or 245. That was the one part of the ruling I had not done — the script header led with two frozen figures and mentioned re-measuring once, at the bottom. The two figures are the argument for the rule. 227 edges / 153 threads on 2026-08-21 and 245 / 172 on 2026-08-22, same instance, one day apart. Both are now marked as dated observations kept for SHAPE — a few-hundred -row UPDATE rather than a table rewrite — with the digits explicitly not current. A rule stated without its counter-example reads as pedantry and gets dropped, so both numbers stay, visibly disagreeing. The mechanism that makes quoting unnecessary already existed and is now named at the top: the dry run prints the live count AND the cutoff it would record before anything is written. That output is the authoritative number for a PR body or a deploy note. Four tests pin it, including that the phrasing the ruling rejects — a bare count asserted as the population — cannot come back. Co-Authored-By: Claude Opus 5 <[email protected]>
@sprint-review's #1113 finding and @sprint-impl's fix at ad274e3 apply to my own suite. My mock hand-wrote `getCallerId: (req) => req.userId`. Mine was worse than a copied list. The real chain is `req.user?._id || req.userId || req.agentUser?._id`, so the mock skipped the first branch and — the part that matters — the AGENT branch, which is the entire reason these routes are dualAuth. Every read test in the file passed without ever resolving an agent caller. Now spreads requireActual and stubs only `callerHasPodWriteAccess`, the one function that queries Mongo. Adds the two cases the old mock made unreachable: a cm_agent_* caller (req.agentUser, with req.userId absent, which is what agentRuntimeAuth actually produces) sees its own rows, and req.user._id wins over req.userId in the documented order. Probe: replacing the chain with `String(req.userId || '')` — the mock's own logic, promoted into the source — turns exactly those two red. Under the old mock that same change turned nothing red, which is the point. Co-Authored-By: Claude Opus 5 <[email protected]>
…itely
@sprint-review 56862 asked whether the pre-cutoff comparison resolves
server-side. It does, via one timestamp — but following that through
against the live instance exposed an ambiguity in my own answer.
A missing ledger row reported `cutoff: null`, and my own comment
documented it as "no pre-cutoff roots exist (fresh instance, or the
backfill has not run)". Those two are lumped together and need OPPOSITE
renders:
fresh instance, no history -> nothing is pre-cutoff; collapse all.
backfill pending, history -> cutoff UNKNOWN; collapsing everything
buries existing conversation under
headline cards, which is exactly the
failure #1115's carve-out prevents.
Not hypothetical: the live instance is the second case right now — 245
reply edges with no root, ledger empty. Had 4/4 shipped before the
backfill ran, the carve-out would have silently not applied.
Distinguished by the one fact that separates them: un-rooted reply edges
only exist if there is pre-threading history nobody has processed. The
extra query runs only when the ledger row is missing, and the catch fails
toward "pending" — a render that expands too much costs a click, one
that hides history is not obviously recoverable because the user cannot
tell anything is missing.
Four cases, including that the cutoff wins once written even if orphans
remain, since orphans legitimately stay NULL forever and must not make a
completed run look unstarted.
Co-Authored-By: Claude Opus 5 <[email protected]>
both of which were wrong in the same direction, toward collapsing. Three deltas against what I had: 1. A MISSING LEDGER ROW MEANS UNKNOWN, AND UNKNOWN EXPANDS. I returned pending:false when no un-rooted edges existed, which told the client to collapse everything. On an already-backfilled instance whose row was lost, that hides all history — and the user cannot tell anything is missing, which is why an ambiguous state has to resolve to the noisy side rather than the destructive one. 2. THE UN-ROOTED PROBE IS RETIRED, not fixed. It cannot work: after a backfill the old threads are rooted and indistinguishable from new ones, so zero un-rooted means "no history" OR "already backfilled", and the row that would tell them apart is the missing one. It also counted ORPHANS — a reply whose parent is gone stays un-rooted by design, so one dead row would have pinned the instance to expand forever. 3. THE BACKFILL NOW WRITES THE ROW EVEN WHEN IT ROOTS ZERO EDGES. "Ran and rooted nothing" is knowledge; absence of a row is not. Without this, a fresh instance finishes the script with no row and sits permanently expanded while being perfectly migrated — and the safety of "missing means unknown" depends on a migrated instance being unable to present a missing row. The four superseded tests are skipped rather than deleted for one release. They encode the shape the ruling rejected, and a reader who finds only the new ones cannot tell the old shape was considered. Co-Authored-By: Claude Opus 5 <[email protected]>
@sprint-review 56911 verified the DO NOTHING and the read-before-UPDATE. Following that through surfaced a precondition neither the script nor the deploy shows on its own. The zero-edges branch writes the ledger row with a NULL cutoff, meaning "ran, and there was no pre-threading history". That is only TRUE once derivation-on-write is live, because from then on every new reply carries a root and the un-rooted population is closed. Run it BEFORE the deploy and zero edges means "not yet" rather than "none". The null cutoff is then wrong, ON CONFLICT DO NOTHING makes it permanent, and the surface collapses pre-existing threads on an instance that does have history — the exact harm #1115's carve-out prevents. On this instance derivation deployed 16:01:52Z and the backfill had not run, so the ordering held by luck rather than by anything written down. Three tests: the precondition is stated, the CONSEQUENCE is stated (a bare "run after X" gets read as advice), and both ledger writes are still DO NOTHING — if either became DO UPDATE the precondition relaxes and the comment goes stale. Also re-verified sprint-review's line citations against the current head: their conclusions hold, their line numbers do not. I added a second INSERT after they read it. Co-Authored-By: Claude Opus 5 <[email protected]>
…ated; the backfill ships with the reader (#1131) * docs(design): the un-rooted probe's retention false positive is tolerated; the backfill ships with the reader Follow-up to #1115 (pen was down at af01679). sprint-review (pod 57204): retention deletes a root, ON DELETE SET NULL un-roots the chain, and a descendant with a live parent matches the probe forever. Tolerated because the probe can only add expand and the missing-row branch is only reachable before the first backfill; so the backfill runs in the same deploy window as #1109. Re-rooting on delete is TASK-043. Co-Authored-By: Claude Fable 5 <[email protected]> * docs(design): the cutoff is a known event carried as a constant, never MAX(created_at) over un-rooted edges Co-Authored-By: Claude Fable 5 <[email protected]> * docs(design): the cutoff constant is the #1106 deploy cutover (run 32583152570), not the data-derived 12:21:11Z Co-Authored-By: Claude Fable 5 <[email protected]> * docs(design): pin the measured cutover — backend pod startTime 2026-08-22T16:01:52Z Co-Authored-By: Claude Fable 5 <[email protected]> * docs(design): the un-rooted probe is retired — a missing ledger row is unknown and expands, nothing else consulted pod-architect removed backfillPending (pod 57210): after a backfill zero un-rooted edges is ambiguous, and the count included retention orphans. The doc now matches the code: expand if the row is missing; cutoff only when it exists. Retention consequences re-homed to the backfill predicate and TASK-043. Pre-gate amendment to #1131, not a new PR. Co-Authored-By: Claude Fable 5 <[email protected]> * docs(design): the orphan mechanism is a deleted root, not a dead parent — reply_to is ON DELETE SET NULL Co-Authored-By: Claude Fable 5 <[email protected]> --------- Co-authored-by: Claude Fable 5 <[email protected]>
…bout it @sprint-review 56912: "there's no check that derivation is live" — the header warned about the ordering and nothing enforced it. A warning is the part people skip, and DO NOTHING freezes a wrong boundary as firmly as a right one. Zero eligible edges is ambiguous and the two readings write opposite records. Derivation live => genuinely no pre-threading history, null cutoff correct. Derivation NOT live => the population is still growing, null cutoff wrong and permanent. Now resolved by POSITIVE evidence where it exists: a row with both a reply edge and a root can only have been written by derivation, since the backfill has not run. Presence is proof. Absence is not proof of the opposite — a live instance with no replies looks identical to a backend that predates the feature. So the script does not assume: it REFUSES, exits 3, and names both readings and what to do about each. --derivation-live is the operator's explicit assertion for the genuinely-empty case, and the ledger records which path was taken (observed vs asserted-by-flag) so a later reader can tell evidence from a claim. Verified against a real postgres:16 in all three states: no evidence refuses and writes nothing; the flag records as asserted; observable derivation records as observed with no flag needed. The first run of that third case appeared to refuse — I had hidden the seed's errors with >/dev/null and the rows were never inserted. A probe whose setup fails silently reports the same thing as a real finding. Co-Authored-By: Claude Opus 5 <[email protected]>
… three @sam (56969) named this mechanism in advance, from the 2026-08-04 incident, and it was missing from the entry. Confirmed against what actually happened: #1106 merged at 15:15:08Z, GitHub retargeted #1109 from the parent branch to main, and the next workflow run on that branch was 15:53:20Z — 38 minutes later, triggered by a push. Zero runs at 15:15. So mechanism 3: the base changes, no event fires, and every existing check silently becomes a check against a base the PR no longer has. It is the worst of the three because nothing about it looks wrong. No conflict, no thin list, no red. The PR is green and mergeable, and it now MEANS something different from what was tested — it merges into main rather than into its parent — while every check on it was computed against the old base. A green rollup is exactly what you would expect to see, and exactly what you get. Two rules added. Sam's press plan is the working mitigation and is recorded as such: merge the parent, verify the child's baseRefName flipped and the PR did not auto-close, then force a head event so CI runs against main. The second is a way to check it after the fact, which the entry needed and did not have. The base-scoped guards are the tell — Package Version Guard and PR Base Freshness both declare `pull_request: branches: [ main ]`, so their PRESENCE certifies a run happened with main as base. That is how #1109 is confirmed to have satisfied the rule before merging: both guards appear in its 18:30 run. Reading the check NAMES answers a question the check COUNT cannot — which is the same lesson as the denominator paragraph above, arrived at from the opposite direction. Co-Authored-By: Claude Opus 5 <[email protected]>
…en (#1135) * docs(ax): entry 41 — a conflicting PR loses its suite and renders green Three PRs reported as green at their heads. #1109 had squash-merged four minutes before I pushed two commits to its branch, so the PR reported a green rollup for the parent commit while the fix sat untested on a closed branch. #1120 and #1128 were CONFLICTING, which means no merge ref, which means tests.yml never dispatched — leaving only the push-triggered CodeQL jobs and a four-for-four green page. Both failures are absences, and the rollup folds over the checks that exist rather than the checks that should. Records the sha-level check instead, and the rule that a stack must be rebased the moment its base squash-merges. Co-Authored-By: Claude Opus 5 <[email protected]> * docs(ax): entry 41 was wrong about the mechanism — there are two @sprint-review falsified the sentence "a conflicting PR never dispatches tests" by finding eight green runs on 3f31d10, a conflicting head, Tier 1 among them. Their measurement was right and my sentence was wrong. Resolved by timestamps rather than by argument, and the answer is that both of us had half of it: 9366e11 pushed 18:53:21Z, conflict began 18:50:59Z but was not yet computed -> full 11-check dispatch 4942ad3 pushed 18:57:12Z, conflict known by then -> CodeQL only, no pull_request dispatch 3f31d10 pushed 19:38:29Z, became conflicting 19:44:07Z -> full dispatch, then the conflict arrived after So: push while KNOWN-conflicting and pull_request does not dispatch. Become conflicting AFTERWARDS and every check stays attached to the sha, still green, now describing a tree that no longer exists — nothing re-runs, because nothing was pushed. The second is the worse one and the entry did not have it. Mechanism 1 at least leaves a suspiciously thin check list. Mechanism 2 leaves a complete, genuinely-passing 11-check rollup on a PR that cannot be merged and whose tests never ran against the tree merging would produce. No artifact anywhere records that. It is also why mechanism 1 reads as false to anyone measuring after the fact — which is exactly what happened here. Row 1 is worth keeping for the window it exposes: a push 142 seconds after the merge that broke it still got a full dispatch, because mergeability had not been recomputed yet. Which side of that recomputation your push lands on decides which mechanism you get, and nothing in the UI marks the boundary. Title and rule updated: a COMPLETE green rollup on a conflicting PR is the worse signal, not the reassuring one. Co-Authored-By: Claude Opus 5 <[email protected]> * docs(ax): entry 41's own table carried a wrong count @sprint-review (57336): row 3 said "11 checks" for 3f31d10. Measured, it is 8 runs across 5 unique names. Re-derived rather than taken: 9366e11 total=11 unique=11 4942ad3 total=4 unique=4 3f31d10 total=8 unique=5 They are right, and the sting is that 8-across-5 is a number I had counted correctly myself an hour earlier, in this pod, before writing 11 into the table. The entry is about instruments whose output does not mean what it appears to; the table was mine and it did the same thing. Run count and name count disagree by three because sprint-impl's manual re-dispatch landed on the same sha as the automatic run, so the split is now stated explicitly: 5 pull_request + 3 workflow_dispatch. The mechanism claim is unaffected — pull_request DID dispatch at 19:38, while the PR was still mergeable — but "11 checks" was doing rhetorical work the evidence did not support. Also dropped "11-check rollup" from the mechanism-2 paragraph for the same reason. Added what I did NOT measure, because the difference is more interesting than the count: the two PRs' pull_request sets differ in MEMBERSHIP, 11 names against 5, not merely in size. #1120 targets main and #1136 targeted a feature branch, and several workflows filter on base — but that is a hypothesis about the difference and it is labelled as one rather than slipped in as a finding. Co-Authored-By: Claude Opus 5 <[email protected]> * docs(ax): the check-set denominator is a property of the base, not the repo @sprint-review (57341) settled the membership question I had labelled as an unchased hypothesis. Re-derived rather than accepted: the 5 names on 3f31d10 are a STRICT subset of the 11 on 9366e11, with exactly six extras — CodeQL plus its three Analyze jobs, the version-bump guard, and the stale-base guard. Two of those are merge-to-main guards and are correctly base-scoped: package-version-guard.yml and pr-base-freshness.yml both declare `pull_request: branches: [ main ]`, so a PR onto a feature branch is outside their remit by design. The other four are CodeQL's, and there is no codeql.yml in this repo at all — GitHub default setup, scoped somewhere our workflow files cannot show you. The consequence is bigger than the correction that prompted it, and it is now the paragraph's point: a PR's "full" check set is a property of its BASE. Eleven is complete onto main; five is complete onto a feature branch. There is no fixed denominator, so a check COUNT means nothing on its own — and a stacked PR retargeted to main at merge time will be judged by guards that never ran against it. That is the same error I made one paragraph earlier when I wrote "11 checks" for a row that had 8, inside an entry about instruments that report numbers meaning something other than they appear to. Co-Authored-By: Claude Opus 5 <[email protected]> * docs(ax): a base retarget fires nothing, and that is the worst of the three @sam (56969) named this mechanism in advance, from the 2026-08-04 incident, and it was missing from the entry. Confirmed against what actually happened: #1106 merged at 15:15:08Z, GitHub retargeted #1109 from the parent branch to main, and the next workflow run on that branch was 15:53:20Z — 38 minutes later, triggered by a push. Zero runs at 15:15. So mechanism 3: the base changes, no event fires, and every existing check silently becomes a check against a base the PR no longer has. It is the worst of the three because nothing about it looks wrong. No conflict, no thin list, no red. The PR is green and mergeable, and it now MEANS something different from what was tested — it merges into main rather than into its parent — while every check on it was computed against the old base. A green rollup is exactly what you would expect to see, and exactly what you get. Two rules added. Sam's press plan is the working mitigation and is recorded as such: merge the parent, verify the child's baseRefName flipped and the PR did not auto-close, then force a head event so CI runs against main. The second is a way to check it after the fact, which the entry needed and did not have. The base-scoped guards are the tell — Package Version Guard and PR Base Freshness both declare `pull_request: branches: [ main ]`, so their PRESENCE certifies a run happened with main as base. That is how #1109 is confirmed to have satisfied the rule before merging: both guards appear in its 18:30 run. Reading the check NAMES answers a question the check COUNT cannot — which is the same lesson as the denominator paragraph above, arrived at from the opposite direction. Co-Authored-By: Claude Opus 5 <[email protected]> * docs(ax): base is necessary and not sufficient — paths move the set too Found by applying this entry's own denominator paragraph to the PR carrying it. #1135 is docs-only, targets main, and reports 10 checks where #1120 reports 11. The missing one is E2E Tests: playwright.yml filters on frontend/**, backend/**, e2e/** and playwright.config.*, and a docs/** diff matches none, so the workflow never dispatches and the check never exists. I had written that the check set is a property of the BASE. That is true and incomplete — it is a function of (base, paths touched), and I only found the second half because the claim was sitting on a PR that contradicted it. The visible consequence is worth stating because it will be read wrong: a docs-only PR settles at MERGEABLE/UNSTABLE rather than CLEAN, permanently. No future event produces the absent check. UNSTABLE here means "a check you might expect is not present", not "something failed" — all ten that ran are green. A "merge only when CLEAN" rule waits forever on documentation, and anyone reading UNSTABLE as breakage goes hunting a failure that does not exist. Three of this entry's corrections have now come from treating a check count as comparable across PRs that were never comparable. Co-Authored-By: Claude Opus 5 <[email protected]> * docs(ax): I read a pending check as a missing one and built a theory on it Retracting a consequence I committed to this entry an hour ago and posted to the pod as actionable: that a docs-only PR settles at MERGEABLE/UNSTABLE permanently, because the paths-filtered E2E check never dispatches, and that a merge-only-when-CLEAN rule therefore deadlocks on documentation. False. Waited for the runs to finish instead of reading a snapshot: #1142 MERGEABLE/CLEAN checks=10 E2E absent #1143 MERGEABLE/CLEAN checks=10 E2E absent An absent E2E Tests does not prevent CLEAN — it is not required, so its non-existence costs nothing. The UNSTABLE I saw on #1135 was a check still PENDING, not a check MISSING, and it cleared by itself. The membership finding survives and is independently verified from playwright.yml and from E2E=0 on all three PRs. Only the consequence I hung off it was fabricated. Keeping the retraction in the entry rather than deleting the paragraph, because the failure mode is the entry's own subject. I read a transient as structural and then built a mechanism to explain it — paths filter, no dispatch, no check, never CLEAN. Every step of that chain is true in isolation. What made it convincing enough to commit and broadcast was the coherence, not the evidence, and none of it was ever connected to the observation it claimed to explain. Co-Authored-By: Claude Opus 5 <[email protected]> * docs(ax): why the base flip fires nothing, not just that it fired nothing @sprint-review (57010) supplied the cause behind the measurement. Re-derived rather than accepted, and every part holds: release-safety.yml [opened, synchronize, reopened, ready_for_review] package-version-guard.yml [opened, synchronize, reopened, ready_for_review] pr-base-freshness.yml [opened, synchronize, reopened] Four others on pull_request — tests, playwright, secret-scan, mintlify — take the default set, which is that list minus ready_for_review. `grep -rn edited .github/workflows/` returns nothing at all. So the retarget does fire an event. It fires one nothing is subscribed to, which is exactly why update-branch works where a base flip does not: it pushes a head commit and produces synchronize. Kept the two halves separate because their evidence differs. Zero runs at the retarget, and no subscriber to `edited`, are both measured here. That GitHub emits `edited` specifically on a base change is documentation, not an event payload I captured — consistent with the observation rather than demonstrated by it. That distinction is rule 16's, applied to my own addendum. Also recorded the fix that was considered and declined: adding `edited` to those types lists would make retargets re-run CI by themselves, and would also re-run CI on every title and body edit, which is a bad trade here. The mitigation stays a deliberate head event. Writing down the rejected option so the next reader does not re-derive it and reach the other conclusion. Co-Authored-By: Claude Opus 5 <[email protected]> * docs(ax): a push cadence under the suite's runtime never lands on the tip @sprint-review (57014): 3/4 took four heads in twelve minutes while tests.yml runs 5-6, so no run could ever cover the tip. Folded into the existing verify-by-sha rule rather than added as a fourth mechanism, because it is not one — it is the same "checks describe a superseded state", self-inflicted. What the rule did not carry is the difference between detecting it and escaping it: comparing sha-to-tip finds the mismatch every time and suggests re-dispatching, which reproduces it. Only noticing the RATE tells you the fix is to stop pushing. Co-Authored-By: Claude Opus 5 <[email protected]> * docs(ax): a workflow fix reaches a stacked PR through its BASE, not its head Fourth mechanism, found by chasing @sprint-review's #1132 measurement (57463): its entire check list is one skipped Release Branch Guard, and it reads CLEAN because nothing is failing because nothing ran. They measured the counts and declined to claim the cause. This is the cause. For a pull_request event GitHub reads the workflow definition from the MERGE REF — base + head — so the base branch's copy of the file decides whether the event matches at all. #1123 dropped `branches: [main]` from tests.yml on main at 15:20:27Z. #1132's head was pushed at 18:11:30Z, three hours later, and still got nothing, because its base `docs/ax-two-call-sites` was last touched at 06:52 and still carries the old filter. Read the file on that branch to confirm rather than inferring it. The general form is worth more than the instance: a workflow fix on main reaches a stacked PR only when that PR's BASE absorbs it. Not the head. So "we fixed CI for stacked PRs" is true of the repo and false of every PR already stacked on a stale branch, and nothing in the UI separates the two. Recorded both wrong guesses I made first, because the sequence is the point. I proposed "the head predated the fix" — refuted by timestamps, it postdates it by three hours — then "a paths filter" — refuted by reading tests.yml, which has none. Rule 16 killed both: make the mechanism predict something and go check. Co-Authored-By: Claude Opus 5 <[email protected]> * docs(ax): mechanism 4 is sprint-review's finding, not mine They established it at 15:25:50Z — "for pull_request, the trigger is read from the PR's own merge ref" — measured on #1120, whose head was pushed 15:22:21Z, two minutes after #1123 merged, and got zero runs because its base still carried the old filter. They also corrected their own earlier "merge #1123 first and the ordering stops mattering" in the same message. I derived the same thing nine hours later from #1132 and wrote it up as "@sprint-review measured the counts and explicitly declined to claim the cause; this is the cause." Both halves wrong: they did claim it, and they were first. Their message was unread in my redelivery queue while I re-derived it from a different PR. Corrected in place rather than quietly reworded, because the entry is about evidence and a provenance error inside it is the same defect. Two instances, two PRs, one mechanism — theirs is the finding, mine is the confirmation, and the independent second instance is worth keeping for exactly that reason. Co-Authored-By: Claude Opus 5 <[email protected]> * docs(ax): a hand-dispatch is the artifact that hides the bug it works around @sprint-review (57058) nearly retracted a correct finding. They measured zero runs on #1120's 0147fa2, then one run six minutes later — which reads as "my earlier claim was wrong, #1123 did reach it." The second run was my hand-dispatch landing between their two checks. The `event` field is the only discriminator. `workflow_dispatch` proves someone pushed a button; `pull_request` proves the trigger matched. Counting runs cannot tell those apart, and the count is what a reader reaches for. The general form is why it belongs in the entry rather than in the pod: a manual dispatch is the STANDARD response to noticing a PR has no checks. So the act of working around the bug manufactures the exact artifact that makes the bug look absent — and the person most likely to measure afterwards is the one who dispatched, comparing against their own memory of "it had nothing before." I am that person here. Every hand-dispatch I ran on this stack today is noise in anyone else's measurement of the same shas, which is a cost of the workaround I had not counted. The table earlier in this entry already splits its counts by event; this adds the rule that made the split necessary. Co-Authored-By: Claude Opus 5 <[email protected]> --------- Co-authored-by: Claude Opus 5 <[email protected]>
Second of four gated PRs on the threading walking skeleton. Stacked on #1106 (1/4, schema + derivation) — review against 1/4, not main; the base flips to
mainonce 1/4 merges.The ruling this implements
Persisted collapse (surface constraint 2) and follow state share the key
(userId, podId, threadRootId). ux-lead ruled one record carrying both booleans — not two tables, not two writes for one gesture, and not localStorage (which would make "a reload does not re-expand what you closed" true per device, which is not what the constraint says). Collapse ships here rather than in 4/4 because the key already exists.Not a widened
User.followedThreads. That field is typedpostId: { type: ObjectId, ref: 'Post', required: true }(User.ts:24-29) and cannot hold a Postgresmessages.id. Widening it would silently drop chat rows from everyPost.find({ _id: { $in: postIds } })consumer —postController:457/:513/:548,activityService:614/:712,ActivityFeedPage:584.followingis tri-state, and that is the load-bearing partThe name change from
thread_followsis not cosmetic: row presence no longer means following. A collapse write creates rows for users who are not following, so if presence meant following, expanding a thread would subscribe you to it.Given that, the obvious
following BOOLEAN NOT NULL DEFAULT falseis a live bug, not a simplification. The ruling says following defaults from participation — a participant with no row is following. A collapse-only row withfollowing = falsewould silently unfollow a participant who never touched the toggle.NULLTRUEFALSEConsequences that fall out of it:
FALSE, it does not delete the row. Deleting would mean "no explicit choice", which re-subscribes a participant on the next reply — and would discard their collapse state.IS TRUE/IS FALSE, never= true, soNULLis never conflated with either.explicitFollowerIds, notfollowerIds. It omits participation-default followers. The shorter name would have made under-notification read as correct at the call site.Following never implies expanded
collapseddefaultsTRUEfor everyone including followers — a followed thread wakes you and floats in Activity, it does not open itself in the channel.Two mechanisms enforce that the two booleans stay independent:
upsertOnetakes the column as an argument, so every writer touches exactly one. A follow cannot re-collapse an expanded thread; an expand cannot subscribe you.PATCHtaking both. A combined write invites a client to send the pair and clobber the half the user did not touch.Routes
dualAuthon all four, matching the reactions precedent. An agent holding thread state is first-class; gating onreq.userIdalone silently excludes every agent.COALESCE(thread_root_id, id), the same derivation the write path uses. A client should never need to know whether the message it is looking at is a root.GETreturns only rows that exist, plus the defaults on the wire ({ collapsed: true, following: null }) — so a change to the defaults is visible at the boundary rather than only in two codebases that have to agree.routes/messages.ts.PUT /collapsedrejects a missing or non-boolean body rather than coercing; absence is the caller's bug, and coercion would let a malformed client silently collapse threads.Refactor included: one membership gate, not two
reactionControllerhadcallerHasPodAccessinlined. Rather than copy it, it moved toservices/podWriteAccessServiceand both callers share it. Both comments that function carries record divergence bugs — the agent path checking Mongo while the human path checked only the lazily-synced PG mirror, and 65 of 66 real HQ members silently 403'ing as a result. A second copy is how a third one happens.The 15 existing reaction tests pass unchanged through the extracted gate — behavioural evidence, not a source-text assertion.
Deliberately the write gate and not
DMService.canViewPod, which is the read gate and carries an intentional §3.7 admin bypass for ops observability. Admins do not get to write into pods they have not joined.Tests — and their honest weakness
19 tests, all green. Most assert source text (schema DDL, emitted SQL), because there is no DB in the unit tier and the write path is a subquery with no function to call. Same weakness I flagged on 1/4.
Two are a deliberate control for exactly that: they
require()the model and the controller for real. This caught a live bug — the first draft required../../config/postgres, a file that does not exist, and every text assertion still passed. A suite whose assertions are all one kind has no control.Mutation probe, 11 mutations, each run independent (
git reset --hardbetween, with a per-iteration assertion that the restore actually restored) and each reporting 19 total so the suite compiled rather than silently failing to load:following NOT NULL DEFAULT false— the participant-unfollow bugcollapseddefaults FALSE — following implies expandedexplicitFollowerIdsrenamed tofollowerIds= true, conflating NULL with unfolloweddualAuthWhat is not here
explicitFollowerIdsandmutedUserIdsare the two halves 3/4 needs; joining them against the thread's participant set is 3/4's job, in the wake path.GET /threads/state.🤖 Generated with Claude Code