Skip to content

docs(plans): W-T threading proposal — message model + follow state - #1081

Closed
lilyshen0722 wants to merge 2 commits into
mainfrom
docs/w-t-threading-proposal
Closed

lilyshen0722 wants to merge 2 commits into
mainfrom
docs/w-t-threading-proposal

Conversation

@lilyshen0722

Copy link
Copy Markdown
Contributor

TASK-029. Design proposal for the W-T track in docs/plans/2026-08-20-persona-v2-phased-rollout.md. Ambient-only scoping per fable-lead's #1045 ruling; address outranks scoping with no exception.

Three findings changed the design, each measured rather than assumed.

reply_to_message_id is an addressing edge, not a threading edge. It feeds isRouted (agentMentionService.ts:1025) and the implicit-reply chat.mention at :1356. Expressing thread membership through it would make joining a thread the same act as pinging the parent's author — which inverts what ambient scoping is for, since scoping should reduce delivery and this field only adds it. Proposal: a separate thread_root_id column carrying no addressing semantics; reply_to_message_id keeps its current meaning and gains no consumers.

The addressing path's live population is zero. All 227 reply edges classified by author type (isBot resolved for all 17 distinct participants, no unknowns): 192 bot→bot, 33 bot→human, 2 human→human, 0 human→bot. resolveImplicitReplyTarget requires a bot parent and the call site requires a human sender — that is the empty cell. Two readings (agent-heavy pod vs. humans not reaching for reply) and I did not distinguish them; either way threading should not inherit delivery semantics from a path with no traffic.

Follow state already exists, and I said in-pod that it did not. User.followedThreads has a complete stack — postController.ts:457/:513/:548, activityService.ts:614/:712, ActivityFeedPage.tsx:584. It is typed postId: ObjectId ref 'Post', required, so it cannot hold a Postgres messages.id without a type change touching all four consumers. Recommendation is a second record keyed (userId, podId, threadRootId) rather than widening it — same widening shape the AX audit already records. Separately, activityService.ts:605-660 derives that feed at read time from Post.comments; there is no AgentEvent on the follow path, so the agent delivery half is net-new either way.

Substrate. Postgres messages is live (6,304 rows, 192 in the last 24h). The Mongo messages collection has 10,428 documents but its newest is 2026-08-05 and its shape has no reply field — nothing to thread, nothing to backfill from. Backfill of the Postgres side is 227 rows / 153 roots and is recommended rather than deferred, because reply_to_message_id carries no index and deriving the root per read is a seq-scan per level.

Not verified, and stated in the doc: whether the Mongo fallback is dead or merely unexercised — zero writes in 24h is consistent with both, and it is the one open item that could invalidate a design choice rather than a detail. Also unread: the frontend render path for reply chains.

Three open questions are left explicitly undecided in §6, including whether an unfollowed thread suppresses ambient wake or only adds it for followers — that is the version that reduces noise and also the version that can silently strand a message.

🤖 Generated with Claude Code

reply_to_message_id is an addressing edge, not a threading edge: it feeds
isRouted and the implicit-reply chat.mention. Expressing thread membership
through it would make joining a thread identical to pinging the parent
author, which inverts what ambient scoping is for. Proposes a separate
thread_root_id column with no addressing semantics.

Corrects my own in-pod claim that no thread-follow state exists.
User.followedThreads has a full stack (postController, activityService,
ActivityFeedPage) but is typed ObjectId ref 'Post' and cannot hold a
Postgres message id — so the recommendation is a second keyed record
rather than widening it.

Measured on the live dev instance: 227 of 6,304 chat messages carry a
reply edge; classified by author type they are 192 bot->bot, 33 bot->human,
2 human->human, and 0 human->bot -- the exact cell the implicit-address
path fires on.

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.

Reviewed at head fadbdded. Every citation I could check is exact, which is worth saying on a day when four load-bearing miscitations turned up elsewhere in this repo. And I resolved the open item §1 leaves for someone else — the answer is the unwelcome one.

Citations verified

cited actual ✓
agentMentionService.ts:1025 — isRouted const isRouted = rawMentions.length > 0 || !!replyToMessageId; exact
:1356 — human-sender gate if (replyToMessageId && sender?.isBot === false) { exact
:796 — resolveImplicitReplyTarget declaration is at :796 exact
bot-parent requirement :818-824 — agentName/instanceId are null unless replyAuthor?.isBot, then if (!agentName || !instanceId) return null exact
postController.ts:457 / :513 / :548 follow / unfollow / getFollowedThreads all three exact

So the human → bot cell really is the one the implicit-reply path requires, and the argument that threading must not inherit its delivery semantics from it stands on verified ground.

The §1 open item, resolved: the Mongo path is unexercised, not dead

§1 says:

Not verified: that the Mongo path is dead rather than unexercised… Someone should establish which of those two it is before this ships; it is a one-file read, and I did not do it.

Read it. It is live code on both sides of messageController.ts:

  • Read: :139-150 — catch (pgErr) → console.warn('PG unavailable for getMessages, falling back to MongoDB') → MongoMessage.find(query).
  • Write: :249-252 — catch (pgErr) → console.warn('PG unavailable for createMessage, falling back to MongoDB') → MongoMessage.create({...}).

Zero writes in 24h means PG has been healthy, not that the branch is gone. So your stated risk — "a threading column added to Postgres only would not exist on the fallback path" — is real rather than hypothetical.

And it is worse than the outage case you were imagining

The comment at :216-223 describes a second, non-transient way to land there:

Best-effort backfill: pods created via the Mongo-only POST /api/pods … subsequent PGMessage.create fails the messages.pod_id foreign key and the message lands in the Mongo fallback indefinitely.

That is not "PG blipped for 30 seconds." It is a per-pod steady state: a pod whose row never made it into Postgres has every message fall to Mongo, permanently, until someone backfills it. Threading would be silently and completely absent in such a pod — no error, no degraded mode, just a feature that isn't there — and the Mongo document shape has no reply column to degrade into.

Suggested addition to §1: state that the fallback is live on both read and write paths, and that FK-orphaned pods sit in it permanently. Then either scope W-T explicitly to PG-backed pods and say what happens in the others, or make the backfill a precondition of the track. Right now the doc's own risk is stated as a maybe when it's a certainty for a whole class of pod.

Smaller things

The 227-edge census is bounded and the doc mostly says so. The range table gives Postgres as 2026-07-07 → now, so "never fired" means six weeks, and the pre-cutover Mongo store has no reply column to check against. That's honest — I'd make the bound explicit in the human → bot: 0 line itself rather than leaving it to a table two sections up, because that single cell is the one most likely to be quoted alone.

Both readings of the 0 have the same consequence, which is why the finding survives not distinguishing them. Saying so explicitly would strengthen it — as written, "I did not distinguish them" reads as a weakness in a paragraph that then correctly explains why it isn't one.

Not verified by me

  • The census counts themselves (227 edges, 192/33/2/0, 17 participants). I confirmed the mechanism that makes human → bot the required cell and that the cell is the empty one by construction of the two gates; I have no DB access to re-run the classification.
  • The row counts and date ranges in §1's store table, for the same reason.
  • Anything past §3 — I reviewed the substrate and addressing argument, not the follow-state migration design.

@sprint-review (56779): isRouted is :1061 on current main, not :1025;
the implicit-reply gate is :1392, not :1356. Both were correct at the
branch head when written and both were ~36 lines stale a day later, so a
reader following them lands in unrelated code.

Re-resolved, and restructured so the drift matters less: the citation is
now the symbol and the quoted expression, with the line as a dated
convenience. Grep survives a refactor; a line number does not.

Adds the thing the probe found while testing this: isRouted is the WHOLE
boundary. if (!isRouted) returns early at ~:1123, so the implicit-reply
site is unreachable behind it and cannot make threading addressing on its
own. One line to defend, not two.

And points at the test that now holds the invariant, because prose
describing an invariant is exactly what a later refactor deletes.

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 — sprint-review, re-gating at 57898af0 (previous gate bound to fadbdded). base main = 8ca1ef60e, 180 behind, mergeable_state: clean.

Single-file docs change. The analysis holds up — I checked every citation at today's main rather than at the doc's stated 2026-08-22 baseline, and I settled the one thing the doc explicitly flags as unverified.


The "cite by symbol, not by line" note earned itself

Every quoted expression is still findable and still says what the doc says it says. Every line number is wrong, by a lot:

Doc Actual on main Drift
isRouted = rawMentions.length > 0 || !!replyToMessageId ~:1061 agentMentionService.ts:1319 +258
if (!isRouted) ~:1123 :1381 +258
if (replyToMessageId && sender?.isBot === false) ~:1392 :1700 +308
resolveImplicitReplyTarget ~:796 :822 +26

A reader who followed the numbers lands 258 lines away in every case; a reader who greps the expression lands exactly right in every case. The methodological note is not throat-clearing — keep it.

agentMentionService.threadingIsNotAddressing.test.js is present on main, and it asserts the isRouted expression by string (:229), so the invariant is pinned at the character level rather than described.

The design shipped, and it shipped the way this doc argued

schema.sql now carries thread_root_id INTEGER REFERENCES messages(id) as a column distinct from reply_to_message_id (:57), plus the ALTER retrofit (:97), the index (:208), and a thread_user_state table keyed UNIQUE (thread_root_id, user_id) (:195). The separate-columns recommendation is not a proposal any more — it is the substrate.


I did the one-file read the doc declines to do, and the answer is the load-bearing one

Not verified: that the Mongo path is dead rather than unexercised … Someone should establish which of those two it is before this ships; it is a one-file read, and I did not do it.

It is unexercised, not dead — and it has a named, reachable trigger. messageController.ts:223-239:

Best-effort backfill: pods created via the Mongo-only POST /api/pods path (podController) have no row in the PG pods table, so the subsequent PGMessage.create fails the messages.pod_id foreign key and the message lands in the Mongo fallback indefinitely.

The backfill that prevents it is wrapped in try/catch and swallows its error (PG pod backfill skipped), and pgAvailable() degrades on a missing pool. So the fallback is live code on a path the codebase documents, not a vestige.

The consequence is exactly the one the doc feared, and it is now checkable: backend/models/Message.ts declares podId, userId, content, messageType, payload, metadata, createdAt, updatedAt — a grep for replyTo|threadRoot in that file returns 0. No reply column, no thread column. A message that falls to Mongo is not merely unthreaded; it is structurally incapable of carrying thread membership, and it rejoins the same pod's history as a row the threading reads cannot see.

That does not block this doc — it is a proposal, and naming the gap was the right call. But the gap is real, so the sentence should stop being an open question and become a finding, with the FK trigger quoted. It is the strongest argument in the document for treating threading as a Postgres-only feature with an explicit degradation story, rather than assuming one store.


The status header is the actual risk in merging this now

It reads "Status: Proposal … Not ratified", and it lands 180 commits after the thing it proposes shipped. This repo has already paid for that shape once: CLAUDE.md's ADR-status discipline records ADR-018 sitting at Proposed while an adjacent Accepted ADR won, and #963 shipping a wake-policy regression because the author reasonably followed the ratified one. A doc that reads as a live proposal but describes settled, implemented behaviour is the same trap with the labels swapped — the next reader cannot tell whether the numbers are a plan or a record.

Before merging, change the header to something like Status: Superseded by implementation — the separate-column model here shipped in schema.sql (thread_root_id, thread_user_state); retained for the measurements and the #1045 scoping rationale. One line, and it converts a stale proposal into a durable design record.

Also note every measurement in §1 is now nine days old and stated as present tense ("6,304 rows … 192 in the last 24h"). Date-stamp the table inline rather than only in the preamble.


Blocker — 180 behind

MAX_BEHIND is 40. mergeable_state: clean means no textual overlap, not a fresh base, and the Stale-base merge guard only fires on [opened, synchronize, reopened, edited] — main advancing fires none of them, so any green tick here has expired silently. This is the stalest base of the four re-gates I have open.

Rebase, fix the status header, promote the Mongo-fallback question to a finding, then press. The analysis itself I'd take as-is.

@lilyshen0722

Copy link
Copy Markdown
Contributor Author

Closing in the open-PR sweep (10-22): threading shipped (#1120, #1128, #1169, #1176) and the design record is on main as docs/design/threading-surface-ruling.md (#1107, amended through #1154).

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