Repository navigation
fix(platform): close conversation send, dedupe and scoping gaps - #3225
Merged
Merged
Conversation
`core/conversations/send_message_via_connector.ts` and the reply/bulk-reply functions in `reply_to_conversation.ts` had no live caller: `domains/ conversations/send.ts` is their 0.5 twin and imported only the three pure helpers. The core copy scheduled `internal.conversations.internal_actions. sendMessageViaConnectorAction`, a name no shim table answers, so it could never run. Conversely the conversations shim registered three handlers (`queryConversationMessages`, `createConversation`, `updateConversations`) nothing names. Delete the lane, the handler_names entry, the three orphan handlers, and the exports only they served (types.ts result/args shapes, `notificationFromAddress`, `internetMessageIdFromSendOutput`, `QueryResult`). Add the ctx-shim reachability gate the sandbox and chat shims already carry, so a new `internal.*` reference in sync_mailbox/ingest fails in the suite instead of at an operator's next mail sync, and an orphan handler is flagged. Findings: conversations-5, conversations-v1.
`POST /conversations/messages/:id/attachments` answered an unconditional 501 (`attachment_bytes_unavailable`) behind the write gate, and its client chain — the `downloadAttachments` adapter row, contract entry and `useDownloadAttachments` hook — had no caller anywhere in the app, the e2e specs or the docs. The Gmail/Outlook on-demand fetch the route comment promised does not exist in the tree. Remove the route, the three client hops, the routes.test case and the two integration-check gate rows that counted the door (12 → 11). Attachments captured at sync keep their read-time presigned link; nothing else changes. Findings: conversations-6.
…eplacing it
Every poll re-fetches the message sitting on the sync cursor, and an
already-ingested Message-ID takes the `updateConversationMessage` path
with `buildEmailMetadata(email)` — the envelope only (from/to/cc/…). The
shim wrote that as `metadata = <json>`, a wholesale replace, so the
insert-time `sender` / `isCustomer` the Inbox projection renders were
gone from the newest inbound message of every mailbox after the second
poll.
Merge with `coalesce(metadata, '{}'::jsonb) || <json>` — the idiom every
other message-metadata write in the send lane already uses — so the
envelope refresh lands without dropping what the insert stamped.
Findings: conversations-8.
`PATCH /conversations/:id` accepted any `contactId` and wrote it after checking only the conversation's org; the Inbox list then read the named contact with `WHERE id = ANY(...)` and the reply lane joined it with `ct.id = c.contact_id`, neither scoped to the org. An editor holding another tenant's contact UUID could surface that contact's name/email on their own thread and reply to it through their connector. The write door now looks the contact up in the caller's org and answers the same opaque 404 compose does (`contact_not_found`); the list batch read and the reply join carry the org predicate as defense in depth. The detail projection was already scoped. Findings: conversations-2.
`runSendMessageJob` read the row, checked `delivery_state = 'queued'`, spent seconds in the connector call, then updated the row `sent` with no row-count check. `undoSendMessage` deleted any still-queued row in its own transaction. An undo in the last second of the countdown therefore landed inside the send: the mail left, the row was deleted, the settle updated nothing, and the org had no record of a mail it sent until the Sent-folder sync re-created it. The job now claims the row with ONE conditional update (queued, outbound, this org, `metadata->>'sendClaimedAt' IS NULL`) that stamps the claim and returns the row; no row means undone/settled/duplicate and nothing is sent. Undo refuses a claimed row with the existing `undo_window_closed` 409. Retry clears the stamp with the other stale send stamps so a failed attempt can be re-claimed. The settle returns its row count and warns when a delivered message's row is gone. No new delivery state, so no migration; the watchdog still fails a claimed row whose worker died. Integration probe: the fake SMTP holds a send open, an undo during the hold answers 409 and the row stays queued, the release delivers exactly one mail and settles `sent`. Findings: conversations-1.
…mically `composeEmailConversation` committed the conversation in one transaction and then called `sendMessageViaConnector`, which opened a second one for the message insert, the approval fold and the pg-boss enqueue. A throw in that second transaction (pg-boss unavailable, an insert refusal) left a committed outbound conversation with zero messages and no failed bubble — nothing to retry or discard, only delete. Split the choke point into `sendMessageViaConnectorInTx` (the body, on a caller's transaction) with `sendMessageViaConnector` as the cap check + `begin` wrapper every other send path still uses, and run compose's `createConversation` and the queue in ONE `sql.begin`. The unit test pins that a rejected enqueue rolls the conversation insert back. Findings: conversations-10.
…t races on it Inbound dedupe was check-then-insert: `checkMessageExists` looked the Message-ID up over a PLAIN index (0036; 0064 notes the key "carries no UNIQUE constraint"), and the insert ran in its own transaction. Nothing serializes two sync passes of one mailbox — the schedule scan claims the occurrence, `beginRun` inserts a run without checking for one in flight, and a manual run can join a scheduled one — so a slow pass and the next tick both fetched the same messages, both missed, and both inserted: the same mail twice in the thread, and nothing reconciled it. The contact find-or-create had the same shape over the plain `contacts_org_email`. Migration 0077 makes the rule the schema's: a partial unique index on (org_id, external_message_id) in app.conversation_messages, existing duplicates detached from the key (lowest seq keeps it; the strays carry `metadata.dedupedExternalMessageId`, never deleted), the plain index dropped as a strict subset. The shim's two ingest writers catch the violation and answer the row the Message-ID already landed on, so the loser of a race treats the mail as already landed instead of failing the pass. The contact find-or-create takes a per-(org, email) advisory lock before it looks — contacts keep no unique key because the CRUD door allows two rows per email and a constraint there would need a merge. The outbound settle stamps the connector's Message-ID onto the sent row; the Sent-folder sync can land the same mail first (connector returned, sync polled, settle last). That collision now settles the row `sent` without the id and warns, instead of marking a delivered mail `failed`. The conversations table needs no index of its own: its root message is inserted in the same transaction, so a duplicate root rolls back with it. Real-Postgres probe: two concurrent creates of one root and an append of the same Message-ID yield one message and one conversation, a raw duplicate insert is refused with 23505, and four concurrent find-or- creates of one email make one contact. Findings: conversations-7.
…ox chose The compose pane collected a "send as" address, the route accepted it, compose stamped it as `metadata.to`, the job payload carried `from`, and the header showed `resolveReplyFrom(ourAddress, inbox.fromAddress)` — yet no connector send ever received it: `buildSendInput` had no `from`, the imap-smtp native's input declared none and always used the configured From, and gmail/outlook declare no From input either. The customer and the agent saw different senders, and the field was dead weight from the UI to the job. Build the lane for imap-smtp, the one connector the UI offers a dynamic sender for (`supportsDynamicSender`: imap_smtp on a verified domain). The native accepts `from`, refuses a line break in it, and resolves it with the existing `resolveReplyFrom` against the mailbox's configured From — the mailbox address or a same-domain alias on a non-public domain is honoured, anything else falls back. The guard lives in the native because the connector door is agent-reachable. `buildSendInput` forwards `from` to imap-smtp only and drops it for gmail/outlook (the connected account sends as itself), and the job hands the payload's `from` through. The manifest declares the property so an agent sees it. The pure reply-from helpers move from `backend/core/conversations/ reply_from.ts` to `lib/shared/conversations/reply-from.ts`: the native in `lib/` must not import `backend/`, and the UI and the backend already shared the module. Every importer follows; nothing else changes. Integration probe: the reply into a thread with no recorded recipient leaves as `[email protected]`, the compose with `from: [email protected]` leaves as that alias. Findings: conversations-3.
…ersation binds `materializeEmailAttachments` registers every emailed attachment `skip_rag_indexing = true` — at storage time there is no conversation to scope the corpus row to, and an unscoped row reads as org-wide — and its comment promised that `bindFileToConversation` queues and dispatches the file once the conversation is known. The binder never did: it wrote the link and returned `bound`, and nothing in the tree ever set the skip flag back to false, while `indexUploadedFile`, `markRagQueued` and the requeue sweep all refuse a skip row. `bindEmailAttachments` therefore counted `queued` at 0 forever, and the conversation-scope retrievability branch (#3220, `decideRetrievable` on `file_metadata.conversation_id`) guarded a corpus leg nothing populated. The bind is now what starts indexing: a row that was never queued (`rag_status IS NULL`, no owning document) is un-skipped, marked queued and dispatched (`rag.index_file`, default priority — a mailbox backlog must not outrank an upload) in the SAME transaction as the binding, so a poll that cannot bind leaves the file unindexed rather than unscoped. The outcome vocabulary the consumer already speaks is answered: `bound_and_queued` for a fresh bind, `queued` for a row bound before this lane, `unchanged` once queued. `reuseStoredAttachments` hands a re-poll its stored pointer, so the re-bind lands on the same row and is a no-op. A document's file keeps riding the document's own indexing. Rows bound before this lane (skip true, never queued) are queued on their next poll, which only the message on the sync cursor gets — a backfill of every historical attachment is an embedding-cost decision, not taken here. Integration probe: Bob's mail in the sync lane carries a text attachment; after three polls there is one row, bound to his conversation, un-skipped, queued, with exactly one `rag.index_file` job, retrievable for the admin and denied to the plain inbox member. Findings: conversations-4.
… and twice
`GET /conversations` batched the page's contacts and previews ("no N+1")
and then handed every row to `projectConversationForView(withMessages:
false)`, which issued three more queries per row — newest message,
contact, pending approval — up to 300 on a 100-row page, undoing the
batching the listing built. `GET /conversations/:id` read the whole
thread with `listConversationMessages` for the raw rows it answers and
then again inside the projection, so a long support thread cost O(2N)
rows per open.
The listing now projects its own page: the newest message is fetched as
the FULL row (one DISTINCT ON), the contacts carry `createdAt`, and the
pending approvals come in one `resource_id = ANY(...)` read — four
queries whatever the page size — and `items` is built from them with the
same shared projection the detail door applies. The two loaders
(contacts, pending approval) are the SAME functions the detail door uses,
so the doors cannot read a contact two different ways. The detail door
hands the thread it already loaded into the projection, which presigns a
projected copy and leaves the raw rows untouched. Wire shapes are
unchanged; the unbounded thread walk stays (paging it is a client
contract change).
Findings: conversations-9.
undoSendMessage read the row with a plain SELECT and then ran an unconditional `DELETE ... WHERE id = ?` inside a READ COMMITTED transaction, while the send job's claim is an autocommit UPDATE on its own connection. A claim that committed between the undo's read and its DELETE was re-checked only against `id = ?` on the new row version, so the undo deleted the CLAIMED row: the connector delivered the mail, the org lost its record of it, and settleSent hit 0 rows. The original "mail left, row gone" outcome (conversations-1) survived, narrowed from the seconds of the connector call to the span of the undo transaction — while the send.ts header and the test header claimed it was closed. The DELETE now carries the same predicate as the claim (org, outbound, `delivery_state = 'queued'`, `sendClaimedAt IS NULL`) and returns its row; zero rows is `undo_window_closed` 409 before any audit row or hint is written. The read stays for the 404/409 wording only. The same shape is swept onto discardOutboundMessage (`delivery_state = 'failed'`), so a retry that re-queued the row between the read and the delete is not silently lost. send.test.ts pins the delete's predicate text and parameters, the 0-rows → 409 path with no audit/hint and a rolled-back transaction, and the discard twin.
`isUniqueViolation` moved to db/sql.ts for the conversation ingest and settle writers; scim kept a private copy of the same check. One helper.
…lane send_input.ts still named `internal_actions.sendMessageViaConnectorAction` as a consumer (deleted with the 0.4 send lane); the MIGRATION.md ledger still called the conversation-corpus retrieval leg honest-empty and described the send job as re-checking the row rather than claiming it.
This was referenced Sep 5, 2026
larryro
added a commit
that referenced
this pull request
Sep 5, 2026
0077 is taken by the conversations branch (PR #3225, pushed first); the campaign coordinator assigned 0080 to this branch. Same content, only the file name and the numbers it cites in its comment and cancel reason move. Migrations are applied by file name, so a shared number is a boot failure for whichever branch merges second.
larryro
added a commit
that referenced
this pull request
Sep 5, 2026
Resolves two conflicts with #3227 and #3225: - domains/automations/shim.ts: main added the same listFilesByFolderInternal handler backed by documents/agent-list.ts:listFilesByFolder; keep main's, drop this branch's copy, and un-export listWorkflowFolderFiles (its one remaining consumer is the workflow document.list native in the same file). - lib/connectors/natives/imap-smtp.ts: keep main's From lane (resolveReplyFrom) beside this branch's attachment resolver.
This was referenced Sep 27, 2026
yannickmonney
added a commit
that referenced
this pull request
Sep 28, 2026
An email's body reached no index: the covering note that explains an attachment (the role an applicant names, the order a complaint is about) was invisible to every retrieval leg. Inbound email bodies now index under a message ref and answer the chat assistant, behind the same assignment privacy as an emailed attachment. - lib/knowledge/message-ref.ts: encoder and parser (`msg:<message id>`), the LIKE pattern, and the one definition of what the corpus holds: inbound `email` messages (`isIndexedMessage`). - Ingest: `addMessageToConversation` queues `rag.index_message` in the insert's own transaction for a non-empty inbound email; the job reads an HTML body down to text (html-to-text), heads its chunks with subject and sender, stamps the conversation id, runs the secret scan and PII policy, and ends quietly on refusals no retry changes. Its own queue, so a mailbox backlog never stands in front of an upload. - Gate: the `msg:` deny becomes a branch decided by the message's conversation (`conversationAssignmentAllows`, a live lifecycle, not spam), resolved with the attachments' conversations in one read, and only for a door that asks (`includeConversationMessages`: the chat tools). The corpus pre-filter excludes message rows for every other door, so the sandbox bridge, the MCP door and REST never see a body they do not wrap. - Chat: a body hit is a `conversation` row citing its conversation, its passage wrapped as mail; `rag_fetch` reads the whole body under the inbox role. The timeline never shows a raw `msg:` id, and no source card offers a file preview for one. - Dedup: an email body never clones another row's chunks and nothing clones from one (the header names a correspondent another reader may not see). - Cascade: liveness is the inbound message row; `deleteConversation` queues the release of its bodies, the retention window releases them before it purges (a failed release keeps the conversation), and the corpus reconcile walks message refs apart from blob refs from a random pivot. - Real-Postgres proof: the `checkInboundEmailBodies` integration lane. - Docs (EN/DE/FR), manual boxes CHAT-F49/CHAT-B16, the automation register and the knowledge ledger's stale PENDING notes (queue-on-bind landed in #3225). Refs #3015
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
Closes the conversations-integrity findings of the backend deep review: the undo/send race, the unverified
contactIdwrite door and its unscoped contact reads, the dead "send as" From lane, emailed attachments that were never queued for indexing, the non-unique Message-ID key under a check-then-insert ingest, the metadata replace on re-sync, the two-transaction compose, the double thread read / per-row N+1 on the Inbox doors, and the dead 0.4 send lane with its orphan handlers.Commit order (one per finding group): dead 0.4 lane + shim reachability gate → 501 attachment door → metadata merge → contact scoping → send claim → atomic compose → unique Message-ID (migration 0077) → From lane (imap-smtp) → attachment indexing on bind → Inbox read batching.
Review round 1 (three follow-up commits, history untouched): the undo DELETE became the arbiter of the send's fate (blocking); scim reuses the shared
isUniqueViolation; the send-lane comments and the MIGRATION.md ledger were aligned with the claim and the bind lane.Findings fixed
runSendMessageJobclaims the queued row with one conditional UPDATE (metadata.sendClaimedAt);undoSendMessage's DELETE carries the same predicate (org_id, outbound,delivery_state = 'queued',sendClaimedAt IS NULL,RETURNING id) and answersundo_window_closed409 on 0 rows — the read before it only picks the 404/409 wording — so a claim committing between the undo's read and its delete is refused instead of deleting the claimed row (review round 1);discardOutboundMessagegets the same shape ondelivery_state = 'failed'; retry clears the stamp; settle warns on 0 rows.PATCH /:idlooks thecontactIdup in the caller's org (404contact_not_foundotherwise); list batch read and reply join carry the org predicate.from, resolves it withresolveReplyFromagainst the configured From (mailbox address or same-domain alias on a non-public domain, else fallback);buildSendInputforwards it for imap-smtp only; helpers moved tolib/shared/conversations/reply-from.ts; manifest declares the property.bindFileToConversationun-skips, marks queued and dispatchesrag.index_filein the binding transaction; outcomesbound_and_queued/queued/unchangednow answered.core/conversations/send_message_via_connector.ts, the core reply/bulk-reply functions, the unanswerablesendMessageViaConnectorActionhandler name, three orphan shim handlers and the exports only they served are deleted.POST /messages/:id/attachmentsdoor and its adapter/contract/hook chain are removed.app.conversation_messages(existing duplicates detached, key kept inmetadata.dedupedExternalMessageId; plain index dropped); shim ingest writers land a 23505 on the existing row;findOrCreateContacttakes a per-(org, email) advisory lock; outbound settle tolerates a Sent-folder collision.updateConversationMessagemerges metadata (coalesce(metadata,'{}') || …) instead of replacing it.GET /conversationsprojects from its own batched reads (contacts, full newest message, pending approvals — four queries per page);GET /:idhands the thread it loaded into the projection instead of reading it twice.createConversationand the queue in ONEsql.begin(sendMessageViaConnectorInTx).core/conversations/sync_mailbox.ts) plus the inverse orphan-handler assertion.Skipped
Tests & gates observed
All run in the worktree on the branch tip (e0e3765, after the round-1 repair):
bunx tsc --noEmit→TSC_EXIT=0;bunx oxlint --type-aware→OXLINT_EXIT=0(no findings)bunx vitest --run --project server→Test Files 494 passed (494)/Tests 6010 passed (6010)backend/domains/scim backend/domains/conversations→Test Files 14 passed (14)/Tests 130 passed (130)(send.test.ts alone: 15 tests, incl. the new claim-between-read-and-delete → 409 case and the discard twin)bun run check→Tasks: 40 successful, 40 total(29 cached; platform lint/typecheck/test re-observed uncached above),CHECK_EXIT=0bun run knip:check→KNIP_EXIT=0(one pre-existing configuration hint:cron-parser services/platform knip.config.ts Remove from ignoreDependencies)run-itest.sh, with fix(platform): pass the corpus scope rows as one jsonb parameter #3222's aa3d1d7 cherry-picked temporarily, then dropped):[itest] 469/471 checks passed across 134/134 lanes— noRUN TRUNCATED, every conversation/mail lane PASS (0 conversation FAILs), the same two FAILs as before and both outside this branch:knowledge: corpus scope drift is corrected and reported — drifted=null …is not this branch's:runLanesruns the lanes sequentially andcheckCorpusScopeReconcileruns right aftercheckKnowledge, BEFOREcheckConversations/checkMailboxSyncLane, so no row this branch writes can be its (unorderedLIMIT 1) pick;drifted=nullmeans the pickedapp.documentsrow has noprivate_knowledge.documentstwin — a lane defect for the fix(platform): reconcile and report corpus scope drift #3216/fix(platform): pass the corpus scope rows as one jsonb parameter #3222 owner (the pick needs anORDER BYor a corpus-backed filter). On current main the lane is red anyway (it truncates onjsonb_to_recordset, which fix(platform): pass the corpus scope rows as one jsonb parameter #3222 fixes).webdav re-home (protocol + tree + locks + visibility on pg)— red on main before this campaign (known).Notes for the reviewer
imap_smtpon a verified domain (supportsDynamicSender), and gmail/outlook declare no From input; the guard lives in the native because the connector door is agent-reachable.app.conversationsneeds no index: its root message inserts in the same transaction, so a duplicate root rolls back with it.failedon a Sent-folder collision) until the new image takes over — acceptable for a short roll, self-healing on the next poll. Numbering: 0076 is the latest onorigin/maintoday; re-check at merge time.fromproperty on the imap-smtp manifest is agent-visible; no docs page covers the Inbox compose today, so no docs change.bun run knip:checkprints a pre-existing configuration hint (cron-parserinservices/platform/knip.config.ts), untouched by this branch.aa3d1d7a9cherry-picked temporarily (main truncates at the corpus-reconcile lane without it); it is not part of this branch.