Repository navigation
fix(platform): complete deferred sends and memories, prune dead chat doors - #3245
Merged
Merged
Conversation
The Postgres turn store NOTIFYed `chat_stream` on every throttled progress write and on each lifecycle write, and its header described API pods that LISTEN once per process and fan the row out to SSE clients. No such listener exists anywhere in the backend: the per-thread progress lane polls `app.generations` at the store's write throttle, and its own comment notes that a push could not beat that throttle. The NOTIFY was a round trip per write for a mechanism that was never built, and a module doc the next reader would build on. Delete `notifyThread` / `CHAT_STREAM_CHANNEL` and the five call sites, correct the store, service and route comments, and drop the `notified` capture from the store test's fake. Finding: chat-domain-5.
…stream The pipeline's failure finalize passes no `text` — "keep whatever the throttled streaming writes persisted" — and the Convex store honoured that because its progress writes landed on the message. The Postgres twin streams text and reasoning onto `app.generations` only, then `finalizeAssistantMessage` wrote the error onto a message row whose text and parts were still the empty placeholder, and `endGeneration` deleted the generation row a moment later. A reload showed only the error; the live tab's bubble never left streaming presentation (the client drains a streamed key only once the row's own text catches up with what streamed); and the failure finalize NULLed the reasoning column unconditionally. When `text` is undefined, read the generation row's text and reasoning inside one transaction with the failure stamp, copy them onto the message (`coalesce`), and append a trailing text part for the unsettled tail — a tool-round boundary resets the generation text before the round's text lands on the parts, so a non-empty generation text is never a duplicate of a stored part (the store still checks the trailing part). The completed and cancel shapes, which carry `text`, are unchanged. Finding: chat-core-1.
`enqueueDeferredSend` inserted the row with `video_job_ids` unset and enqueued its readiness poll in the same transaction; the route claimed the videos (`bindJobsForDeferredSend`) and stamped the claimed set on the row only AFTER that commit. pg-boss wakes workers over LISTEN/NOTIFY, so the first poll could read the row before the claim wrote its ids: a video-only parked send (`videoJobIds` with no text or attachments — exactly the shape the composer parks while a clip transcribes) passed the readiness matrix with nothing to wait on, fired without its transcript, and its `finally` deleted the row before the route's UPDATE landed — the jobs bound a moment later were attached to a row that no longer existed. The claim now runs on the park transaction, before the INSERT: the row is written with the claimed set, the poll is enqueued last, and all three commit together, so the first poll always sees the whole row. A video-only send whose ids were all unclaimable is refused (`EMPTY_MESSAGE`) instead of parking an empty message. `bindJobsForDeferredSend` takes the caller's `Sql | TransactionSql` and no longer opens its own transaction; `claimDeferredSendVideos` and its route call are gone. Finding: chat-domain-1.
Two dead-ends in the deferred-send fire path. The 0.4 lane settled the tray row the moment the turn persisted the user message (`settleDeferredSendOnUserAppend`); the 0.5 port kept the decorator and dropped its wiring, so the row survived as "sending" for the whole generation — the same message shown twice (bubble + tray) for minutes. `ChatTurnRequest` grows `onUserMessageAppended`; `runChatTurn` wraps the Postgres store with the decorator when it is set, and the poll passes a hook that deletes the row (idempotent with the terminal `finally`). The hook runs only after `beginTurn` succeeded, so `ThreadBusyError` still re-parks the row. A turn refused at a pre-flight gate (model access, attachment ownership, no model) or thrown before the turn-open write (unknown model, unusable credential) was deleted with no trace: `deferred_sends.status` admits only waiting|claimed, the direct lane hands such a refusal back to the composer and the REST lane appends an assistant error row, but here nobody was waiting and the parked text and attachment choice vanished. The poll now appends the user row (text + the attachments it carried) and an assistant error row in the same envelope the REST lane writes, before the row settles. A guardrail refusal inside the pipeline (`steps` non-empty) and a failure after the user row is durable already leave their own rows and get no second trace. Findings: chat-core-4, chat-domain-2.
… time A video claimed for a parked send (`bindJobsForDeferredSend` stamps `message_bound_at_ms`) was unbound only when the user cancelled the send. Every other way the send could end left the jobs bound to nothing: the poll's mop-up after a refused or thrown turn, a turn that fired before a transcript landed (`buildBoundJobAttachments` leaves that job out), and the watchdog's clearing of a wedged claimed row. A bound job is hidden from the composer, excluded from the unbound-GC, and unreachable through the unbind door (which needs ids the tray no longer shows) — its blob and file row leaked for good. The unbind door's guard — a job a SENT user row carries stays bound — is now `unbindJobsWithoutMessage`, shared with the door, and the deferred lane runs it whenever a send is over: in the poll's `finally` (the videos the turn did not carry), in the watchdog's cleared arm (`RETURNING` org and video ids), and when the send is dropped at fire time. The poll also re-gates the thread at fire time. `loadOwnedThread` ran only at park; a thread trashed while the send waited still received the turn (LLM spend, a reply written into the trash racing the retention purge). A row whose thread is no longer the owner's active thread is dropped with its videos released. Trashing a thread now cancels its waiting sends with the same cascade as a manual cancel (`cancelDeferredSendsForThread`, called by the trash door — `threads.ts` cannot import the deferred-send module without a cycle). Touches `domains/video_links/service.ts` only in the unbind pair (the websites-video theme owns the rest of that file). Findings: chat-domain-3, chat-domain-8.
`GET /threads/archived` passed `cursor` and `limit` through `Number()` unchecked: `?cursor=abc` bound the text 'NaN' to `::bigint` (22P02) and `?limit=abc` produced `LIMIT NaN` — an unhandled 500 for a malformed URL where every body on this surface is zod-parsed. `GET /memories/search` did the same for `limit`, and `.slice(0, NaN)` quietly answered `[]`. Both query strings are now zod-coerced and bounded (the listing's own page ceiling, 50), and a malformed value is a 400. Finding: chat-domain-9.
`closeServerGracefully` ends every stream in the `/events` registry before
`server.close()`, then reaps idle sockets and force-closes at the 5 s
deadline — built because one connected browser used to park shutdown until
the orchestrator's SIGKILL. The per-thread chat progress lane
(`GET /threads/:id/stream`) is the process's only other streaming response
and registered nowhere: its `while (!stream.aborted)` loop kept a non-idle
connection open until the force timer, so every deploy with a chat tab
open paid the full deadline before `boss.stop({graceful})` ran.
`realtime/sse.ts` exports `registerLiveStream` / `unregisterLiveStream`
over the same set, the chat lane adds itself around its loop in a
try/finally, and the shutdown wording no longer names `/events` alone.
Finding: chat-domain-10.
`createPgTurnStore` takes the `onUserMessageAppended` hook and applies `settleDeferredSendOnUserAppend` itself, so the turn host's dependency override stays the literal `store: createPgTurnStore(` the shim guard (`shim.test.ts`) reads to prove the 0.4 store is replaced — the previous commit's wrapping in `service.ts` broke that assertion. Finding: chat-core-4 (follow-up).
`POST /threads/:id/capabilities`, `setThreadCapabilities`, `sanitizeThreadCapabilities` and its ceilings, and the `capabilities` / `harness` fields of the create-thread body and `CreateThreadArgs` had no caller: every client creates threads with kind/title/project/agent only, no turn reads `thread_metadata.capabilities` (the shim hard-codes an empty loadout and chat runs the fixed three-tool set), so the door was a 0.4 "equip a conversation" surface that changed nothing if reached. The columns stay, deprecated rather than dropped: branches copy them and the summaries still project them for rows that carry one. `listComposerModels().harnesses` is live and untouched. Finding: chat-domain-6.
Memories were half-wired. MCP `memory.save` landed rows `pending` and nothing could approve one: `POST /chat/memories/:id/review` had no caller (the preferences page rendered the lists read-only "until the memory mutations exist"), so `memory.search` — approved-only — always answered `[]`. Neither the org `user_memories` policy nor the `memories_enabled` preference was read by the server: a person who turned memories off still got proposals written about them. Both reads selected without a LIMIT. Server: `isMemoriesEnabled` resolves the person's preference over the org policy default, OFF when neither is set (the governance schema's posture); `saveMemory` refuses with `MEMORIES_DISABLED` (403 on the route, a tool error on MCP) and `searchApprovedMemories` answers nothing while it is off. The search filter and cap now ride the SQL (ILIKE, literal-escaped, LIMIT ≤ 50); the listing is bounded; review settles only a pending row; a new `deleteMemory` + `DELETE /chat/memories/:id` takes a saved memory out of retrieval — the control the docs already described. App: each pending suggestion carries Save / Discard and each saved memory Delete, wired through `chat/memories:reviewMemory` / `deleteMemory` adapter rows that refresh the lists; labels and toasts ship in en, de and fr. The docs (three locales) say the switch gates the whole feature. The integration lane proves off-until-enabled, delete, and off-again. Finding: chat-domain-4.
… row The lane read the reply as soon as the parked row was gone. Now that the row settles at user append — before the reply streams — that read landed on the assistant placeholder and missed the answer text. Wait for the generation row to disappear as well, and print whether the turn finished and how many answers carry the expected text. Finding: chat-core-4 (integration proof).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Chat domain (
backend/domains/chat/**) fix batch from the backend deep review: the deferred-send lane is completed end to end (video claim ordering, settle at user append, failure trace, video release, fire-time re-gate, trash cascade), the Postgres turn store keeps a streamed partial reply on failure, the listener-lesschat_streamNOTIFY and the dead thread-capability door are gone, the chat progress SSE lane joins the shutdown drain, two query strings are validated, and memories are finished as a feature (server gate on the person's switch / org policy, bounded reads, review + delete controls in the app, docs in three locales).Findings fixed
bindJobsForDeferredSend) now runs on the park transaction before the INSERT; the row is written with the claimed set and the poll is enqueued last, so the first poll can never observe a video-only row before its ids exist.claimDeferredSendVideos+ its route call removed.ChatTurnRequest.onUserMessageAppended;createPgTurnStoreappliessettleDeferredSendOnUserAppendwhen set; the poll deletes the tray row the moment the user row is durable (no more bubble + "sending" row for a whole generation).stepsempty) or thrown before the turn-open write now leaves the user row (text + attachments) and an assistant error row (REST-lane envelope) before the row settles.unbindJobsWithoutMessage(the unbind door's sent-message guard, shared withunbindJobsFromMessage) releases a send's unsent videos in the pollfinally, the watchdog's cleared arm, and the fire-time drop.loadOwnedThreadat fire time (trashed/lost thread → row dropped, videos released,gone); the trash door cancels the thread's waiting sends with the manual-cancel cascade (cancelDeferredSendsForThread).GET /threads/archivedandGET /memories/searchquery strings are zod-coerced and bounded (400 on malformed) instead of binding'NaN'.registerLiveStream/unregisterLiveStreamexported fromrealtime/sse.ts; the chat progress lane enrols around its loop; shutdown wording no longer names/eventsalone.setThreadCapabilities,sanitizeThreadCapabilities+ ceilings, and thecapabilities/harnesscreate fields (server + app args) removed; columns kept (branches copy, summaries project).listComposerModels().harnessesuntouched.notifyThread/CHAT_STREAM_CHANNELand the five NOTIFY call sites deleted; store/service/route comments corrected.isMemoriesEnabled(preference over orguser_memoriespolicy, OFF by default);saveMemoryrefusesMEMORIES_DISABLED(403 / MCP tool error),searchApprovedMemoriesanswers nothing while off and pushes ILIKE filter + LIMIT ≤ 50 into SQL; listing bounded; review only settles pending rows;deleteMemory+DELETE /chat/memories/:id; app Save / Discard / Delete controls (contract entries, adapter rows, hooks, en/de/fr labels + toasts); docs (en/de/fr) state the switch gates the feature; itest lane proves off-until-enabled, delete, off-again.Skipped
chat/questions:getPendingQuestionis a one-shot fetch per thread open on the HTTP lane (norefetchInterval), not a poll; the server surface is complete and pinned by thequestions:itest lane; the producer (ask_question) is a product decision the owner declined on 2026-08-14 (lib/chat/tools.ts). Removing or rewiring it is a product call, not a fix.Tests & gates observed
bunx vitest --run --project server backend/domains/chat/— 8 files / 49 tests passed (before the memories commit); memories + routes suites 19/19; new tests indeferred-sends.test.ts,deferred-sends.watchdog.test.ts,routes.test.ts(new),memories.test.ts(new),store.test.ts,http-shutdowncoverage viaroutes.test.ts.bunx vitest --run --config vitest.ui.config.ts app/features/settings/personalization— 1 file / 11 tests passed.bun run check(worktree root) — exit 0:Tasks: 40 successful, 40 total;@tale/platform:lint: Found 0 warnings and 0 errors.;@tale/platform:test: Test Files 521 passed (521);@tale/platform:test:ui: Test Files 455 passed (455);@tale/docs:test: Test Files 31 passed (31)/Tests 201 passed (201);@tale/ui:test: Test Files 124 passed (124);@tale/shared:test: Test Files 22 passed (22).bun run knip:check— exit 0 (one pre-existing configuration hint:cron-parser services/platform knip.config.ts Remove from ignoreDependencies).run-itest.sh, real Postgres + MinIO), run 1:469/473 checks passed across 134/134 lanes. The four:knowledge: corpus scope driftandwebdav re-home(both known red on main),automation-run tool lane(also FAIL on a main-based run,chat-turn-itest3.log, PASS on others — flaky, not this theme), anddeferred send: parks on indexing…— caused by this PR's own settle-at-append change (the lane read the reply as soon as the row was gone); the lane now waits for the generation row too (ef445fcd9).471/473 checks passed across 134/134 lanes, noRUN TRUNCATED; the two remaining are the known-redknowledge: corpus scope drift is corrected and reported — drifted=null(knowledge theme) andwebdav re-home(webdav theme). This theme's lanes:PASS deferred send: parks on indexing, runs on readiness, cancel works — … settled=true, turnDone=true, answered=1 (want 1), cancel=true;PASS memories: off until enabled, pending until approved, retrieval sees approved only — refusedWhileOff=403 (want 403), pending=1, hiddenWhilePending=true, approvedHits=1, bogus=false (want false), deleted=true, afterDelete=0, refusedAgain=403 (want 403);PASS deferred-send recovery,PASS video links: unbind is org-scoped and keeps a sent message bound,PASS questions: …,PASS chat watchdog ….Notes for the reviewer
domains/video_links/service.tsis touched only in the bind/unbind pair (bindJobsForDeferredSendtakesSql | TransactionSqland no longer opens its own transaction;unbindJobsWithoutMessageextracted from the unbind door) — the websites-video theme owns the rest of that file.core/chat/turn_store.ts(chat-turn theme's tree) is imported, not edited:settleDeferredSendOnUserAppendis applied insidecreatePgTurnStore.trashThreadbecausethreads.ts → deferred-sends.ts → threads.tswould be a new import cycle; the poll's fire-time re-gate covers the window between the flip and the cascade.memory.savewhile memories are off surfaces as a tool error (isError: true, message "Memories are turned off for this account — nothing was saved.") — theMemoryStoreport inlib/chat(sibling tree) has no refusal channel.