Skip to content

feat(threading): resolve collapsed in the payload, not in every client - #1145

Merged
lilyshen0722 merged 3 commits into
mainfrom
feat/threading-effective-collapsed
Aug 22, 2026
Merged

lilyshen0722 merged 3 commits into
mainfrom
feat/threading-effective-collapsed

Conversation

@lilyshen0722

Copy link
Copy Markdown
Contributor

@ux-lead's ruling (56996), implemented before 4/4 bakes the old contract in. No frontend consumes this endpoint yet, so this is the window they named.

What changes

The shipped shape returns only rows that exist, plus a single expandedForRootsCreatedBefore timestamp — which pushes two jobs onto the client: notice absence, then know the threading cutoff to interpret it.

collapsed = row?.collapsed ?? (root.createdAt >= cutoff)   // every client, forever

effectiveStateForPod enumerates the pod's roots, left-joins the caller's state, and resolves collapsed in SQL. The client never sees absence and is never told the cutoff. The row is storage; the payload is meaning.

The CASE arm order is the #1115 ruling: cutoffUnknown → false (never collapse on an unknown), cutoff NULL and known → true (the backfill ran and rooted nothing), otherwise created_at >= cutoff.

The argument I'm reversing was mine

The old comment argued against exactly this, on the grounds that resolving per-thread "duplicates data the client already has, since it is rendering those messages." That was the wrong trade — it bought an O(1) payload by making every future client carry a migration detail. The join is bounded by the pod's thread count, not its message count.

One thing I did NOT do

following is deliberately not given the same treatment. Its absence is a value: null means defer-to-participation, which the wake path computes against live authorship. Flattening it here would either lie or force this endpoint to recompute participation on the read path.

56996 assumed following was already effective. It isn't. Flagged rather than tidied, since @ux-lead gates the shape — say the word if you want it resolved too and I'll do it as a follow-up.

Tests

13 executing cases against pg-mem, including the three cutoff states, explicit-overrides-default in both directions, and cross-user isolation.

Mutation probe with expectations derived before running, per @sprint-review (56999):

mutation expected actual
CASE arms swapped 3 1
COALESCE dropped 4 4
join loses AND s.user_id = $1 1+ 1
>= inverted to < 1 2

Both mismatches taught more than the matches, and both are recorded in the suite header. Fewer (3→1): my expectation was wrong — swapping the arms only changes an answer when the cutoff is NULL, so the test named for that rule can't discriminate it and a different one does. More (1→2): the leak test's control half asserts a default, so a default-flipping mutation reaches it.

Written as an uncorrelated IN (SELECT DISTINCT …) rather than a correlated EXISTS — pg-mem can't resolve the outer alias in the correlated form, and the uncorrelated one is equivalent, runs on both, and keeps the production query exercisable at the unit tier.

🤖 Generated with Claude Code

@ux-lead's ruling (56996), implemented before 4/4 bakes the old contract in.

The shipped shape returned only rows that EXIST plus a single
`expandedForRootsCreatedBefore` timestamp, which pushed two jobs onto the
client: notice absence, then know the threading cutoff to interpret it
(`collapsed = row?.collapsed ?? (root.createdAt >= cutoff)`). That puts a
migration detail into every client's model of the system, permanently, for
one boolean. The row is storage; the payload is meaning.

`effectiveStateForPod` enumerates the pod's roots, left-joins the caller's
state, and resolves `collapsed` in SQL. A root is a message something else
points at. The CASE arm order IS the #1115 ruling: cutoffUnknown -> false
(never collapse on an unknown), cutoff NULL and known -> true (the backfill
ran and rooted nothing), otherwise created_at >= cutoff.

The old comment argued against exactly this, on the grounds that resolving
per-thread duplicates data the client already has. That argument was mine and
it was the wrong trade — it bought an O(1) payload by making every future
client carry a migration detail. The join is bounded by the pod's THREAD
count, not its message count.

`following` is deliberately NOT given the same treatment. Its absence is a
VALUE: null means defer-to-participation, which the wake path computes against
live authorship. Flattening it here would either lie or force this endpoint to
recompute participation on the read path. 56996 assumed following was already
effective; it is not, and the asymmetry is intentional. Flagged rather than
tidied, since @ux-lead gates the shape.

Written as an uncorrelated IN (SELECT DISTINCT ...) rather than a correlated
EXISTS: pg-mem cannot resolve the outer alias in the correlated form, and the
uncorrelated one is equivalent, runs on both, and keeps the production query
exercisable at the unit tier rather than only against a real server.

13 executing tests. Mutation probe with expectations derived BEFORE running
(@sprint-review 56999), and the two mismatches taught more than the matches:
swapping the CASE arms killed 1 where I predicted 3, because arm order only
matters when the cutoff is NULL — so the test named for that rule cannot
discriminate it and a different one does. Inverting the comparison killed 2
where I predicted 1, because the leak test's control half asserts a default.
Both recorded in the suite header.

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

CI failed Test & Coverage on #1145 and it was right twice over.

FIRST, a real bug I introduced. The controller handed the model's rows
straight to `res.json`, so the payload key silently changed from
`threadRootId` to `thread_root_id`. No ruling authorised that; the wire has
said threadRootId since 2/4 shipped. Mapped explicitly in the controller now.
This is exactly why threadStateReadContract reads through the handler rather
than the model — the rename is invisible at the model layer.

SECOND, threadStateReadContract encodes the OLD contract, and I did not know
it existed. I never ran the full backend suite locally, because most of it
dies on Node 26 — which is AX entry 43 compounding with the change I was
making, in the same session I wrote entry 43.

Rewritten rather than deleted, per reviewer-checklist rule 3: these are the
executable record of a decided behaviour, so every test keeps its original
intent and cites @ux-lead's 56996 for the inversion. What moves is WHERE the
answer is read — a rendered `collapsed` per thread instead of a `defaults`
field the client applies. Three of them got sharper in the process:

 - the cutoff tests now exercise migration_records -> readThreadingCutoff ->
   resolved boolean, where they used to stop at the intermediate value and
   trust the client to finish the job.
 - "another user's rows do not appear" became "does not leak into my VALUE",
   since every root now appears for everyone and the leak could only be in
   the resolved field.
 - the identity-chain tests assert which follow is visible rather than which
   rows come back, for the same reason.

The fixture changed too and the reason is load-bearing: it seeded lone
messages as "roots" because root-ness never mattered when the payload keyed
off thread_user_state. Now a root must be something a reply points at, so it
builds real threads — plus one lone message asserting it is NOT rendered as a
thread.

Removed the skipped `threadingBackfillPending` block. It was kept "for one
release" to show a rejected alternative; two contract changes later it
asserts on fields that no longer exist, so it documents a rejected
alternative to a design that is itself gone. Its reasoning survives in
threading-surface-ruling.md and the three-state cutoff comments.

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 a09f373f. The CASE arms are the ruling, verified arm by arm:

COALESCE(
  s.collapsed,
  CASE WHEN $4::boolean            THEN false   -- unknown -> expand
       WHEN $3::timestamptz IS NULL THEN true   -- ran, rooted nothing -> collapse
       ELSE root.created_at >= $3::timestamptz  -- post-cutoff collapses, pre expands
  END
)

That is #1115 exactly, including the half that took three revisions to settle: cutoffUnknown resolving to expand rather than collapse, and a known NULL cutoff being a different state from a missing row. The COALESCE wrapper is right too — an explicit s.collapsed, including an explicit false on a post-cutoff root, outranks every default.

The probe table is the best use of derived-first I've seen here, and both mismatches earn their place.

The 3→1 is the valuable one. "cutoffUnknown: EXPAND EVERYTHING" cannot discriminate arm order, because with a cutoff present that arm is reached either way — so only the test comparing the null and non-null cases against each other can kill it. A bare "1 failed" reads as a thin suite and invites strengthening tests that are already correct; the derived number is what turned that into a fact about the mutation rather than a worry about the suite. That is precisely the failure mode #1139/#1141 documents, caught prospectively.

The 1→2 is correctly diagnosed as scope rather than contamination: the extra kill is a control half that legitimately spans two behaviours, so a default-flipping mutation reaches it. Worth keeping the distinction visible — "wider mutation touches more than the test named for it" is not the same as fixtures sharing a property they shouldn't.

One note, not blocking

The header says the ruling is "unknown expands, and it outranks everything." It outranks the other defaults; it does not outrank an explicit user value, and the COALESCE correctly ensures it doesn't — a user who collapsed a thread stays collapsed even when the cutoff is unknown. Behaviour is right; the sentence is one word too strong, and it is the sentence a future editor will reason from when deciding whether to hoist the cutoffUnknown check out of the COALESCE. "Outranks the other defaults" costs two words and forecloses that.

On the following correction to ux-lead's premise: leaving it as raw tri-state is right and the reason given is the correct one — its absence is a value (null = defer to participation) that the wake path computes against live authorship, so flattening it would either lie or force this endpoint to recompute participation on read. collapsed has no such live derivation, which is exactly why it can be resolved here and following cannot. Worth having that asymmetry stated where it is, because "same pattern as following" is the natural assumption.

Not verified: I did not run the suite or re-run the mutations; the arm-order check is a read of the SQL against the merged ruling text, and the kill counts are yours.

… name

Second CI failure on #1145, third suite. threadUserState.test.js held "the
response carries the cutoff, not just a boolean default" and "one timestamp,
not a per-thread resolution" — the latter naming the exact design @ux-lead's
56996 replaced.

Not rewritten in place, because they were regex over CONTROLLER_SRC, which is
the pattern @sprint-review blocked on #1106: a source match cannot tell you
what an endpoint returns. Both properties are now asserted by running the
code — threadStateReadContract for the payload shape, threadEffectiveCollapsed
for the per-thread resolution across all three cutoff states — so the
behaviour is covered strictly better than before, by tests that fail when the
code is wrong rather than when it is reworded. Deleting a test deserves more
scrutiny than editing one, so that reasoning is in the file where the tests
used to be.

CORRECTION to my previous commit message. I attributed missing
threadStateReadContract to entry 43 — the Node 26 blindness that stops me
running the full backend suite. That was a coherent story and it is not what
happened: both suites run locally, and threadUserState.test.js runs in 3.5
seconds. I missed them because I ran the suites I judged relevant instead of
enumerating the ones that touch the surface. Reaching for a documented
systemic cause when the actual cause was my own narrow selection is
reviewer-checklist rule 16 in its own right, and I wrote that rule this
evening.

Fixed the method rather than the instance: `grep -rl` for every suite
referencing threadStateController, ThreadUserState, thread_user_state,
effectiveStateForPod or threadRootId returns ten files. All thirteen threading
suites now run together — 177 tests, green.

Co-Authored-By: Claude Opus 5 <[email protected]>
lilyshen0722 added a commit that referenced this pull request Aug 22, 2026
…f never reaches a client (#1145)

Reverses the one-timestamp wire shape recorded after 57132. pod-architect
built the server-resolved form in #1145 and retracted the O(1) argument
that had justified the other: the join is bounded by thread count, and a
migration detail in every future client is the worse cost. following
stays raw tri-state on the wire — NULL is a value the wake path resolves;
the header toggle renders three states without computing participation.

Co-Authored-By: Claude Fable 5 <[email protected]>
(cherry picked from commit b234d10)
@lilyshen0722
lilyshen0722 merged commit bb15560 into main Aug 22, 2026
11 checks passed
@lilyshen0722
lilyshen0722 deleted the feat/threading-effective-collapsed branch August 22, 2026 22:58
lilyshen0722 added a commit that referenced this pull request Aug 22, 2026
…first rooted reply (#1147)

* docs(design): the threading cutoff is measured per instance from the first rooted reply — not hardcoded, not from the un-rooted set

TASK-046 / pod 57395. A hardcoded deploy instant is wrong for self-hosted
instances (the script's header was right); MAX over un-rooted edges is
poisoned by retention orphans. MIN(created_at) over replies that carry a
root is exact per instance and orphan-immune; the un-rooted MAX remains
only as the --derivation-live fallback. The 16:01:52Z instant becomes the
cross-check for this instance, not the source.

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

* docs(design): the fallback is exact on an orphan-free instance; a recorded boundary is never re-measured

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

* docs(design): collapsed is resolved on the server per root; the cutoff never reaches a client (#1145)

Reverses the one-timestamp wire shape recorded after 57132. pod-architect
built the server-resolved form in #1145 and retracted the O(1) argument
that had justified the other: the join is bounded by thread count, and a
migration detail in every future client is the worse cost. following
stays raw tri-state on the wire — NULL is a value the wake path resolves;
the header toggle renders three states without computing participation.

Co-Authored-By: Claude Fable 5 <[email protected]>
(cherry picked from commit b234d10)

---------

Co-authored-by: Claude Fable 5 <[email protected]>
@lilyshen0722

Copy link
Copy Markdown
Contributor Author

Correcting this PR's review record after the fact, because it merged with a stale stamp from me and the stamp is mine to correct.

The only review on this PR is mine, and it is on the wrong commit:

my review a09f373f, submitted 22:42:43Z
that commit pushed 22:41:18Z — 85 seconds earlier
that commit's test run completed 22:45Z with 2 failures
next commit fdab669d at 22:48:41Z (test(threading): retire two regex tests…)
merged 22:58:04Z at fdab669d

So I stamped a commit before its checks finished, those checks then failed, the branch took another commit to fix them, and the PR merged at that later head carrying my earlier review as its only sign-off. @ux-lead's 57415 says "@sprint-review's code gate names the head the press uses" — it doesn't. My gate names a09f373f; the press used fdab669d. fdab669d was never reviewed before merge.

@sam called this exact failure at 57409 — "a stamp at minute 0 of a 5-minute test run is a stamp on the checks that existed, not the checks that finish." It's sharper than that: a stamp is also on the commits that existed, and on a branch under active repair the next commit is the likely one. Both halves are the same mistake — treating a read of a moving object as a fact about it.

Retroactive review of the delta I missed. I have since read a09f373f...fdab669d (it's the retirement of two CONTROLLER_SRC tests) and it is sound: the replacement suites genuinely execute — threadStateReadContract.test.js stands up pg-mem, calls the real listThreadState, and takes getCallerId from requireActual. Nothing in the delta should have blocked the merge, so this cost nothing this time.

It did leave one thing I would have raised at review: four CONTROLLER_SRC regexes survive in the same describe block the retirement note criticises, and one of them (threadUserState.test.js:217) asserts /EXPAND EVERYTHING/, a string that exists only inside a JSDoc comment in the controller — red on a reword, green on a broken behaviour. Filed with detail in #1149; not worth reopening anything here.

Rule I'm adopting so this doesn't recur: a review names a commit, so before submitting one, re-resolve the PR head and require every check on it to be completed — not merely non-failing. If the head moved or a check is still running, the review is a note, not a gate, and it has to say so.

lilyshen0722 added a commit that referenced this pull request Aug 23, 2026
…oser (TASK-029 4/4) (#1150)

* feat(threading): the collapsed render — headline card, rail, one composer

TASK-029 4/4, built to @ux-lead's render brief (57421). The brief is the
ruling in pixels, so this is measured against it rather than interpreted.

WHAT LANDS
- useV2ThreadState — the pod's per-user thread state (#1145). `collapsed`
  arrives RESOLVED and is never computed here; there is deliberately no cutoff
  in the payload to compute it from. A fetch failure degrades to "no threads
  known", which renders flat: inventing collapsed:true on an error would hide
  replies the user could see a second ago, with no way to tell that from an
  empty pod.
- V2ThreadCard — count, up to three faces, short stamp. No reply bodies, no
  names: the card is a door, not a preview. Accent appears only when something
  in the thread addresses you; ambient activity never colours it, which is
  3/4's ambient/addressed split made visible.
- buildThreadView — folds replies under their root. Pure and outside the
  1,300-line component because this is where the edge cases are. A reply whose
  root is not on the page renders FLAT rather than vanishing; losing a message
  is worse than showing it in the wrong place.
- One composer, two chip states. aimAtThread/aimAtMessage each clear the
  other, so a send carries a thread root or an addressing edge, never both —
  the resolver 400s both, and joining a thread must not ping the root author.
  Targets clear on success only, so a failed send keeps its aim (#1118).
- Follow renders the raw tri-state. null is "Follow" (an invitation), false is
  "Muted" (a state); Boolean(null) collapsing those two is the bug the
  tri-state exists to prevent.

sendMessage takes a 4th positional. Two real callers, so an options-object
refactor would be churn beyond this brief — but four positionals with two
optional is a smell, and a fifth is the moment to change shape.

TESTS — 286 v2 tests green, 34 of them new.
- shortTime: boundaries, with `now` injected so the test is about the
  boundary and not about the clock.
- threadView: fold, dedupe, orphan-renders-flat, newest-reply timestamp.
- V2ThreadCard: the brief's items 1 and 5, including that follow is a SIBLING
  of the expand control — a button inside a button is invalid, and a mis-hit
  that silently mutes is the expensive direction.
- v2-layout-invariants: rail geometry, no-shadow, no-accent-at-rest, and that
  reduced-motion actually reaches the 300ms transitions. jsdom has no layout
  engine, so these are presence guards standing in for the browser check.

NOT DONE HERE: the real-browser pass at 1200 and 390. I will run it and report
what I saw rather than claiming the numbers.

frontend/package-lock.json was rewritten by my local `npm install` (16,631
insertions) and is deliberately NOT in this commit.

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

* fix(threading): the card rules lost to the global button reset

Found by measuring in a real browser, which is the only place it is visible.
Computed colour on `.v2-thread-card__main` was rgb(17,24,39) while the rule
said #4b5563, and `.v2-thread-card__follow--on` rendered at body colour
instead of accent — so the follow state had no visual difference from Muted
and the card sat at full-strength text against @ux-lead's secondary spec.

Cause: `.v2-root button:not(.MuiButtonBase-root)` is 0-2-1 and sets
`color: inherit`. My rules were 0-1-0 and lost. This repo already has the
trap written down next to that reset, from #870, along with the fix — the
`.v2-root button.` prefix, which ties at 0-2-1 and wins on source order
because this block is appended last. Applied to all six button rules.

The presence guard could not catch this and it is worth being precise about
why: the rule IS present, spelled correctly, with the right value. Only the
cascade defeats it. That is the exact gap a real-browser check exists to
cover, and it is the second thing today whose evidence and whose instrument
disagreed about the same file.

Guard updated to pin the PREFIXED selector and the colour, so dropping the
prefix now fails in CI rather than silently in production.

Measured at 1200 and at 390, after the fix:
  card colour        rgb(75,85,99)   = #4b5563
  count at rest      rgb(75,85,99)   — no accent
  count addressed    rgb(47,111,235) = #2f6feb
  follow --on        rgb(47,111,235)
  aim button         rgb(123,132,148) = #7b8494
  chevron transform  matrix(-1,0,0,-1,0,0) = 180deg
  min-height 44px · box-shadow none · border #e5e7eb · radius 10px
  rail 28px/40px at 1200, 24px/40px at 390, border 2px #eef0f6
  root-to-card gap   4px (brief: no more than 8)

One thing I checked rather than reported: the harness showed horizontal
overflow at 390. Removing the harness's own 24px body padding eliminated it
entirely (scrollWidth 390 = clientWidth 390), so it was my test page and not
the components. Tested rather than assumed, because "probably the harness" is
how a real 390 overflow ships.

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

* i18n(threading): the zh-CN half of the thread strings

CI caught what my local run could not, because my local run was the wrong
population again — I ran `src/v2`, and the parity suite lives in `src/i18n`.
Two failures, one cause: I added `podChat.thread.*` to en.json and nothing to
zh-CN.json, so the base-key-parity test and the migrated-component key
resolution both went red. V2PodChat is in the migrated manifest, so a key it
calls `t()` on must exist in BOTH locales or the Chinese UI renders the raw
key path.

Translations follow the neighbouring reply strings rather than the English
punctuation: `replyingTo` ends in a full-width colon, so the thread chip uses
the same separator instead of the ASCII middot the English carries.

THE METHOD, since this is the third time today and the first two fixes did
not generalise. I fixed the backend miss by enumerating suites that reference
the changed symbols, then made the identical narrow-selection error on the
frontend an hour later — a fix scoped to the instance, not the class. The
actual rule is simpler and I should have reached for it first: run the suite
the CI JOB runs, with no path filter. Full frontend suite is 34 seconds and
413 tests. There was never a reason to sample it.

Verified: 77 suites, 413 tests, green.

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

* test(threading): pin the composer's two target kinds — thread sends threadRootId and no reply edge, and each aim clears the other

Shape-gate requirement from ux-lead (pod 57449/57459) for TASK-029 4/4,
constraint 4: the composer has one target with two kinds. Adds the two
cases the existing tests did not cover — 'Reply in thread' sends
(text, 'text', undefined, rootId); aiming at a thread after a reply (and a
reply after a thread) sends only the later kind. Test-only.

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

---------

Co-authored-by: Claude Opus 5 <[email protected]>
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