Skip to content

fix(connectors): an answer too old to post closes its Slack request quietly - #48642

Closed
AmethystLiang wants to merge 1 commit into
mainfrom
AmethystLiang/reply-stale-expiry
Closed

AmethystLiang wants to merge 1 commit into
mainfrom
AmethystLiang/reply-stale-expiry

Conversation

@AmethystLiang

@AmethystLiang AmethystLiang commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

When Orca comes back from a restart or a crash, it can find Slack requests whose answer was never sent. If that answer is over an hour old, or a restart left the request open for over a day, the thread has moved on, so Orca no longer posts it.

Files Added Deleted Net
Test 8 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1426 $\color{#cf222e}{\Huge{\mathbf{−}}}$​17 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1409
Prod 24 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​805 $\color{#cf222e}{\Huge{\mathbf{−}}}$​225 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​580

What Changed

  • Old answers close quietly. A request is filled as quiet in two cases:
    • Answer clock: recovery finds the answer after the fact, and the turn that wrote it ended over 1 h ago. This includes a held answer from an empty-turn retry that never ran, judged by when its turn ended.
    • Request clock: the request was admitted before this process started, so a restart left it open, and it is over 24 h old when filled.
      A live turn's request, a hidden retry's included, never starts the request clock.
      With reply-outbox support, Orca sends a quiet outcome. If support is lost before a saved quiet row drains, Orca clears the row locally.
  • Exemptions. A row with no admission date (one an older build wrote) never ages by the request clock, on any path. Neither does a request a usage-limit pause told its thread to wait for: a new paused mark keeps that through later cuts, claims and retry holds.
  • A quiet close keeps its own key. It is filled under its own delivery id, and the answer of the requests filled with it never keys on that id. So the outbox sends disjoint events, and accepting one never deletes a row the other covers.
  • One batch, per-row results. A fill's rows are written as one command in one writer transaction, which returns whether each row changed. So the batch commits whole or not at all.
    • A quiet close's warn line and counter fire only when its row changed.
    • When the call itself fails, each quiet close in it is probed once by primary key. One this attempt wrote proves the batch committed, so the sender is woken before the original error is rethrown. A probe that fails leaves the closes logged as unconfirmed, never counted.
    • A recovery pass that fails is settled again after 30 s, and a live fill that throws still hands its rows to recovery.
    • The diagnostic names the time it classified the close, not a commit time.
  • Columns. Each outbox row records admitted_at from the journal writer's own clock, and locally expired_reason and paused. They are added like the earlier columns, with no user_version change.
  • Retired work stays retired. Work begun before a dispose (another host, or connectors off), and a live turn end since reset, write, hold, ask, watch, schedule and wake nothing once they resume. This covers:
    • boot's first read, each settle pass and a fill nested in it, and a claim;
    • a live end's fill and its retry hold and send;
    • the turn-end and retry callbacks, bound to the lifetime they began in;
    • a reply write's check, made just before it is posted to the writer worker, after any wait;
    • the sender wake after a write that committed anyway.
      A dispose drops a pass queued to run again. A boot that asks to open a chat while a pass runs gets that pass run again, with the chat opened. No boot follows connectors off.

Why

Main's claim-based recovery (#46044, #46068, #47898) settles the requests a restart cut. A request recovered days later still posted its answer or a "stopped" notice into a thread that had moved on. Checked against how comparable products handle this.

Linked Issue

Refs #46048.

Visual Proof

N/A: no UI. The change is which recovered replies the reply outbox sends to Slack, and the tests below cover it.

Testing

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below
  • Every added test fails without this change (guard cases, listed below, pass on both by design) and avoids the test anti-patterns

The reply tests run on the reply matrix's real journal file, admission writer, recovery, fill and outbox packer.

  • connector-reply-stale-clocks.test.ts covers both clocks, an undated row, a day-old cut, and a usage-limit pause.
  • connector-reply-stale-custody.test.ts covers:
    • an old claimed request and a fresh steer as disjoint events: accept either first, replay, page by page;
    • a live hidden retry, and a paused request that a restart then cut;
    • held answers, and undated rows at boot;
    • the count against a losing writer, a drain that accepts the row right after its commit, a lost acknowledgement, a write that never ran, and a probe that fails;
    • the "classified at" label.
  • connector-reply-stale-batch.test.ts covers:
    • the partial-write replay falsifier: one write fails before commit, whatever committed is drained, then recovery runs from the recorded turn;
    • the sender woken for a batch that committed though its call threw, on the live fill and on a recovery pass;
    • recovery taking over a live batch that failed before commit;
    • a retired live end, which sends no retry, writes nothing and wakes nothing;
    • the live end's lifetime reaching its fill, and a turn-end callback that outlived its recovery.
  • external-conversation-reply-recovery-dispose.test.ts holds a real recovery boundary across a dispose: the pending window read, the boot's first read, a fill nested in a pass, a pass queued to run again, a boot asking to open a chat during a pass, and a turn end after connectors stop.
  • journal-sql-owner-admit.test.ts withdraws a write that waited for record installation before it was posted to the writer worker.
  • journal-sql-connector-replies.test.ts covers every reply write's admit on the lane, and per-row batch results.
  • The schema tests cover the upgrade of an older reply table, per-row fill results, and the keyed probe.
  • Guards that pass with or without the change: an answer within the hour, a usage-limit request's own close, a request a restart left open with no pause behind it, and a turn end retired before it filled.

Performance

The live turn end and recovery make the same reads as before, and each fill is still one write command: one writer round trip and one transaction, whatever the batch size. Only a write call that fails adds work: one read-only primary-key lookup per quiet close in that batch, on the reply lane. No session-wide read is added. The lifetime checks are comparisons.

Risk

Level: Medium.

  • A request closed quietly posts nothing. Its reason stays only in the local row.
  • Rollback: an older build's reads select reply rows by named column or map SELECT * by name, so it ignores the three added nullable columns. quiet is an outcome older builds already send. An older build does not keep the paused mark when it writes a cut, but no older build reads that mark.
  • A plain revert restores the previous behaviour. The added columns stay and are unused.

Review

AI-assisted change. Cross-platform: no platform-specific code. SSH/remote: unchanged; recovery runs where the journal lives.

@coderabbitai

coderabbitai Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • Resume reviews
  • Trigger review
Walkthrough

Connector reply journal rows now include admission timestamps, usage-limit pause state, and quiet-close reasons. Recovery classifies stale answers and requests, closes stale replies quietly, and checks whether recovery work remains current before writes. Recovered verdicts include turn-end timing. Tests cover freshness rules, close accounting, writer admission, and disposal during recovery.

Merge Risk: Moderate · up to 8da6c

This change closes stale Slack replies quietly. Several lifecycle and identity edge cases in recovery are still open: legacy requests could be closed quietly, disposed recovery work could still write or watch, and a failed write could leave a request unwatched. These should be resolved or explicitly accepted before merge.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the primary change: an answer too old to post closes its Slack request quietly. The raw summary and objectives show the change adds quiet closes for stale recovered answers and request…
Description check Passed The description follows the repository template and fills most sections. It has an ELI5, a detailed What Changed section with the mechanism, a Why section, Testing with specific test files, Performanc…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title names the primary change: an answer too old to post closes its Slack request quietly. The raw summary and objectives show the change adds quiet closes for stale recovered answers and requests older than the restart-based limit, with the Slack (connector reply outbox) context. The title covers the main behavior. It omits the batch-write and lifetime-fencing work, which is expected for a short title.

Full details: Description check

Explanation

The description follows the repository template and fills most sections. It has an ELI5, a detailed What Changed section with the mechanism, a Why section, Testing with specific test files, Performance, and Risk with a level and rollback notes. Gaps: the Linked Issue section reads 'Refs #46048' but the template requires 'Fixes #' for an actual issue, and the 'Fixes' line is blank. The 'Why' section is thin: it cites prior PRs and says the approach was checked against comparable products, but it does not explain why this approach beat the alternatives. The 'Manual testing' box is unchecked, and the AI Disclosure section is left as the template comment. The Review section is brief, and the Agent skill upstream boundary and Checklist items are not ticked.

Resolution

Replace 'Refs #46048' with a 'Fixes #' issue link, or confirm the issue is the intended one. Expand the Why section to explain why this design was chosen over the alternatives considered. Complete the AI Disclosure section, since the author states the change is AI-assisted. Tick or explain the unchecked testing and checklist items, including whether manual testing was done.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

Review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: e26f8918-6c16-4fd2-9d56-7b2acbebefb2
Commits

Reviewing files that changed from the base of the PR and between 7f2a281 and 1591ed3.

Files selected for processing: 17

  • src/main/external-conversations/connector-reply-matrix.test-fixture.ts
  • src/main/external-conversations/connector-reply-stale-and-whole.test.ts
  • src/main/external-conversations/external-conversation-reply-evidence.ts
  • src/main/external-conversations/external-conversation-reply-fill.ts
  • src/main/external-conversations/external-conversation-reply-freshness.ts
  • src/main/external-conversations/external-conversation-reply-recovery.ts
  • src/main/external-conversations/external-conversation-reply-turn-fill.ts
  • src/main/external-conversations/external-conversation-restart-cut-replies.ts
  • src/main/external-conversations/external-conversations-install.ts
  • src/main/native-chat/agent-session-journal/connector-replies/journal-connector-replies-read.ts
  • src/main/native-chat/agent-session-journal/connector-replies/journal-connector-replies-schema.test.ts
  • src/main/native-chat/agent-session-journal/connector-replies/journal-connector-replies-schema.ts
  • src/main/native-chat/agent-session-journal/connector-replies/journal-connector-replies.ts
  • src/main/native-chat/agent-session-journal/connector-replies/journal-connector-tools-ran.test.ts
  • src/main/native-chat/agent-session-journal/journal-domain-queue-command.ts
  • src/main/native-chat/agent-session-journal/journal-domain-submission-admission.ts
  • src/shared/agent-session/journal/journal-connector-reply.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 5 remain after this review.

export const replyRowAdmittedAt = (
items: readonly AgentJournalRenderItem[],
row: JournalConnectorReplyRow
): number | undefined => row.admittedAt ?? replyRowMessage(items, row)?.observedAt

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Major · Functional Correctness · Quick win

Keep legacy rows undated on the recovery close path.

On this path, replyRowAdmittedAt supplies the message's observedAt as the admission time for a row that has no admitted_at. A legacy row whose message is more than 24 hours old then matches old_request. Recovery closes it quietly, and its answer is never posted. The PR excludes rows without an admission date from the 24-hour check, and the freshness module says a missing date loses no answer. The sibling call in the same module passes row.admittedAt directly. This path should do the same.

Suggested fix

-          replyRowAdmittedAt(snapshot.items, row),
+          row.admittedAt,

Dated rows keep their age check. Legacy rows keep their pending answer. The turn-fill path, which also uses replyRowAdmittedAt, is not changed by this edit.

Comment on lines +79 to +87
const last = items.findLast(
(item) =>
isRootAgentJournalItem(item) &&
item.turnScope?.kind === 'turn' &&
item.turnScope.turnItemId === turnItemId
)
if (last?.body.kind !== 'message' || last.body.role !== 'assistant') {
return undefined
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Major · Functional Correctness · Quick win

Exclude shutdown notices from the last-content check.

When a restart interrupts a turn after assistant prose, the shutdown writer appends a turn-scoped status row. cutReply selects that row and returns no prose, so the continuation posts only its own answer. Ignore the shutdown notice while preserving the tool-call check.

@AmethystLiang
AmethystLiang force-pushed the AmethystLiang/reply-stale-expiry branch from 1591ed3 to b70334c Compare November 25, 2026 04:42

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

Review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 57eded2b-1aeb-4f5d-a914-eeb74c2ad24f
Commits

Reviewing files that changed from the base of the PR and between 1591ed3 and b70334c.

Files selected for processing: 19

  • src/main/external-conversations/connector-reply-matrix.test-fixture.ts
  • src/main/external-conversations/connector-reply-stale-and-whole.test.ts
  • src/main/external-conversations/connector-reply-stale-custody.test.ts
  • src/main/external-conversations/external-conversation-reply-evidence.ts
  • src/main/external-conversations/external-conversation-reply-fill.ts
  • src/main/external-conversations/external-conversation-reply-freshness.ts
  • src/main/external-conversations/external-conversation-reply-held.ts
  • src/main/external-conversations/external-conversation-reply-recovery-dispose.test.ts
  • src/main/external-conversations/external-conversation-reply-recovery.ts
  • src/main/external-conversations/external-conversation-reply-turn-fill.ts
  • src/main/external-conversations/external-conversation-reply-verdict-fills.ts
  • src/main/external-conversations/external-conversation-turn-ends.ts
  • src/main/external-conversations/external-conversation-whole-answer.ts
  • src/main/native-chat/agent-session-journal/connector-replies/journal-connector-replies-read.ts
  • src/main/native-chat/agent-session-journal/connector-replies/journal-connector-replies-schema.ts
  • src/main/native-chat/agent-session-journal/connector-replies/journal-connector-replies.ts
  • src/main/native-chat/agent-session-journal/durable-rows/journal-storage-schema.ts
  • src/shared/agent-session/journal/agent-journal-bot-message-fields.ts
  • src/shared/agent-session/journal/journal-connector-reply.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review.

const { outcome } = told
const prose =
outcome === 'answered' && told.prose && whole.has(conversation)
? wholeAnswer(turn.carried, told.prose)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Major · Functional Correctness · Quick win

Keep the continuation's own answer whole when it fits the cap.

When a restart continuation has carried prose, wholeAnswer falls back to capAnswer(whole, cap) if fewer than MIN_PREFIX_BYTES remain for the prefix. That cut keeps the leading bytes, which belong to the carried prose. The continuation's own answer is therefore cut from its end, or dropped entirely when the prefix uses the full budget, even though the own answer fits under the cap alone. For example, with a carried prefix at the cap and an own answer 100 bytes below the cap, the reply contains only earlier prose and the cut note.

The function's doc comment says the continuation's own words stay whole where they fit, and that nothing is left out without a note. The fallback breaks both rules. Require the following behavior. When the own answer fits within the cap, it appears in full. The carried prose fills only the remaining budget. Any carried prose that is cut or omitted must be marked with the cut note. The choice of behavior when the remaining budget is below MIN_PREFIX_BYTES is left to the implementation.

Comment on lines +162 to +163
const generation = this.generation
const live = () => generation === this.generation

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Major · Stability & Availability · Quick win

Preserve cancellation across the owning boot.

With three queued sessions, disposal invalidates the first two active passes. When either pass returns, boot starts the third session. That session captures the new generation here, so its checks pass and it can write or subscribe on the disposed host. Disposal during the initial boot read has the same problem.

Capture the generation for the entire boot operation. Check it after the initial read and before starting each session. A separate boot invoked after disposal must still use the new generation.

Based on learnings, reset validation must also prevent stale work from scheduling another operation.

Source: Learnings

Comment on lines +215 to +217
if (!live()) {
return
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor · Stability & Availability · Quick win

A disposed recovery pass can still fill rows after its opener read.

dispose() says a pass that is still reading finishes as nothing. In fillRecoveredTurn, the generation check runs before readEndedChatTurnOpener. If disposal occurs during that read, the helper still calls deps.fillTurn. conversationReplyFill then reads the journal and can write fills. Nothing in the fill layer or the journal path checks the recovery generation. On the abort path, the host and its store remain available, so the write can proceed.

Pass a liveness predicate into fillRecoveredTurn and check it after the opener read, before fillTurn:

Suggested fix (helper window)

 export async function fillRecoveredTurn(
   chat: Pick<ReplyRecoveryChat, 'journalReads'>,
   sessionId: string,
   snapshot: AgentJournalSnapshot,
   turn: AgentJournalRenderItem,
   deps: {
     fillTurn: ConversationReplyFill
     isBot: (sessionId: string) => boolean
     agentOf: (sessionId: string) => string
-  }
+  },
+  live: () => boolean = () => true
 ): Promise<{ kind: 'unresolved' | 'cut'; stamps: AgentJournalConnectorDelivery[] }> {
   const record = readAgentJournalTurn(turn.body)
   const outcome = readAgentJournalTurnOutcome(record)
   const items = snapshot.items.filter((item) => item.sequence <= turn.sequence)
   const opener = await readEndedChatTurnOpener(
     () => chat.journalReads(sessionId),
     items,
     turn.itemId
   )
+  if (!live()) {
+    return { kind: 'unresolved', stamps: [] }
+  }
   const stamps = connectorReplyTurnStamps(snapshot, opener, turn.itemId)

Pass live from settleOnce at the call site in external-conversation-reply-recovery.ts. This closes only the opener window. The fill layer also needs a liveness check after its own store.read and before any write, because its awaits in external-conversation-reply-fill.ts also cross disposal. Apply the same generation predicate there. That change is not shown here because the write path beyond line 200 was not inspected.

@AmethystLiang
AmethystLiang force-pushed the AmethystLiang/reply-stale-expiry branch from b70334c to a05537b Compare November 25, 2026 06:23
@AmethystLiang AmethystLiang changed the title fix(connectors): an answer too old to post closes its Slack request quietly, and a restart continuation answers with the whole reply fix(connectors): an answer too old to post closes its Slack request quietly Nov 25, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

Caution

Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

⚠️ Outside diff range comments (1)

Major · Recovered continuation replies send only the… · external-conversation-reply-turn-fill.ts:81-82

src/main/external-conversations/external-conversation-reply-turn-fill.ts:81-82
Major · Functional Correctness · Heavy lift

Recovered continuation replies send only the final turn's prose.

fillRecoveredTurn passes snapshot.items and one turn.itemId to structuredAgentSessionTurnReply. The helper scans only rows whose turnScope.turnItemId matches that id and stops at the first non-empty prose. For a continuation, the earlier cut turns (for example, "First part." before "Final part.") are not in that scan. The recovered reply therefore carries only "Final part.", and the earlier prose is not sent. The helper also has no cut-chain or 32 KiB cap handling, so the required whole-reply assembly does not happen on this path.

Assemble the prose from every cut in the chain, oldest first, before the continuation's reply. Apply the 32 KiB cap with the "cut short here" note to the earlier prose. Pass the chain to turnReplyOf, or build the combined prose and earlierProse in fillRecoveredTurn.

Review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 6c3f403c-263f-47b3-a69e-afe9753da2e0
Commits

Reviewing files that changed from the base of the PR and between b70334c and a05537b.

Files selected for processing: 15

  • src/main/connector-cloud/connector-reply-outbox.ts
  • src/main/external-conversations/connector-reply-matrix.test-fixture.ts
  • src/main/external-conversations/connector-reply-stale-clocks.test.ts
  • src/main/external-conversations/connector-reply-stale-custody.test.ts
  • src/main/external-conversations/external-conversation-reply-evidence.ts
  • src/main/external-conversations/external-conversation-reply-fill.ts
  • src/main/external-conversations/external-conversation-reply-freshness.ts
  • src/main/external-conversations/external-conversation-reply-pause.ts
  • src/main/external-conversations/external-conversation-reply-recovery-dispose.test.ts
  • src/main/external-conversations/external-conversation-reply-recovery.ts
  • src/main/external-conversations/external-conversation-reply-turn-fill.ts
  • src/main/external-conversations/external-conversation-reply-verdict-fills.ts
  • src/main/native-chat/agent-session-journal/connector-replies/journal-sql-connector-replies.test.ts
  • src/main/native-chat/agent-session-journal/connector-replies/journal-sql-connector-replies.ts
  • src/shared/agent-session/journal/journal-connector-reply.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 2 remain after this review.

Comment on lines +197 to +198
const expired = row && (stale.has(rowKey(row)) || row.fill?.expiredReason !== undefined)
if (!answers.has(conversation) && !expired) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Major · Data Integrity & Integration · Heavy lift

Do not reuse a quiet close's answer identity for a later answer.

When a stale row is deleted after its quiet close is accepted, the answer-head loop treats the absent row as not expired. A later fill for a fresh stamp in the same conversation can then take the deleted row's deliveryId as its answerDeliveryId. The cloud keys reply events by that field, so the answer can collide with the accepted quiet close. The answer for the fresh request may then be merged or rejected, and it may not reach the thread.

The trigger needs a partial batch write: the quiet close commits, and the fill write for the fresh row throws. The comment at lines 183-185 says a request closed as too old never moves the answer key. This path violates that stated intent.

The required behavior is that a reply event's answerDeliveryId never equals the answerDeliveryId of an accepted quiet close in the same conversation. The fix must keep that identity from being reused after the expired row is removed. Choose the mechanism that meets this requirement.

Comment on lines +167 to +170
await this.settleOnce(sessionId, opening).catch(
(error: unknown) =>
error === STALE_PASS ||
console.warn('[connector] could not settle reply outbox rows', error)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Major · Stability & Availability · Quick win

A failed boot write leaves the session unwatched and never wakes the sender.

When closer.write rejects, the rest of the batch is already committed. settleOnce then skips the owed-row check, the watch installation, and the filled() call. The pass catch logs the error and nothing retries the session. Requests that stay unfilled have no publication watch, so they wait for the next turn end, admission, or pause-status event in that chat. A chat that stays idle can leave them unanswered.

The fix should keep the wakeup and watch steps reachable after a partial write failure. Unresolved rows should remain watched, and filled() should run when any write in the batch committed. A retry of the failed session is also acceptable. The choice is open. Without one of these, a single transient write failure during boot can strand requests until the chat has new activity.

console.warn('[connector] could not settle reply outbox rows', error)
)
} while (this.again.has(sessionId))
opening = this.again.get(sessionId)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Major · Stability & Availability · Quick win

Clear pending reruns when recovery is disposed.

dispose() stops recovery and invalidates the running pass, but it leaves again entries from before disposal. When a timer-driven pass is awaiting, a rerun queued before disposal survives. After the stale pass exits, the loop at line 172 reads that entry and calls settleOnce again. The new call captures the post-dispose generation, so its checks pass. The rerun can then write and watch while recovery is stopped, which the PR intends to prevent for an old host.

Clear the pending reruns in dispose(). Reruns requested after disposal are queued later and still run.

Suggested fix

   dispose(): void {
     this.generation += 1
     this.stopped = true
     this.watches.forEach((release) => release())
     this.watches.clear()
     this.timers.forEach((timer) => clearTimeout(timer))
     this.timers.clear()
     this.paused.clear()
+    this.again.clear()
   }

@AmethystLiang
AmethystLiang force-pushed the AmethystLiang/reply-stale-expiry branch from a05537b to 9025df5 Compare November 25, 2026 07:47
…uietly

Follow-up to the restart reply recovery that landed in #46044, #46068 and
#47898 (refs #46048).

- A fill recovery makes from a turn that ended over an hour ago (a held
  empty-turn answer judged by when its turn ended), or a fill of a request
  admitted before this process started and over a day old, closes the
  request quietly (no post). A live turn's request, a hidden retry's
  included, never starts the request clock; a row with no admission date
  never ages by it on any path; a row a usage-limit pause ever owed keeps
  a paused mark through later cuts, claims and retry holds, and never
  ages by it either.
- A quiet close fills under its own delivery id, and the answer of the
  requests filled with it never keys on that id, so the outbox sends
  disjoint events. Rows record admitted_at and, locally, expired_reason.
- A fill's rows are written as one command in one writer transaction that
  returns each row's result, so a batch commits whole or not at all. A
  quiet close is counted and logged only when its row changed. A call that
  fails probes its quiet closes once by key: one this attempt wrote wakes
  the sender before the error is rethrown. A failed recovery pass is
  settled again, and a live fill that throws still hands its rows to
  recovery.
- Work begun before a dispose (another host, connectors off), and a live
  turn end since reset, writes, holds, asks, watches, schedules and wakes
  nothing: boot, each pass and nested fill, claims, the live fill and its
  retry hold and send, the turn-end and retry callbacks, and the reply
  write's admit, asked just before it is posted to the writer worker.
@AmethystLiang
AmethystLiang force-pushed the AmethystLiang/reply-stale-expiry branch from 9025df5 to 8da6ce9 Compare November 25, 2026 07:53

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

Review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: ff7c206a-dc99-4f09-b8cf-a439cbc484ac
Commits

Reviewing files that changed from the base of the PR and between a05537b and 9025df5.

Files selected for processing: 21

  • src/main/connector-cloud/connector-reply-outbox.ts
  • src/main/external-conversations/connector-reply-journal.test-fixture.ts
  • src/main/external-conversations/connector-reply-matrix.test-fixture.ts
  • src/main/external-conversations/connector-reply-stale-batch.test.ts
  • src/main/external-conversations/connector-reply-stale-custody.test.ts
  • src/main/external-conversations/external-conversation-failure.ts
  • src/main/external-conversations/external-conversation-reply-empty-retry.ts
  • src/main/external-conversations/external-conversation-reply-fill.ts
  • src/main/external-conversations/external-conversation-reply-freshness.ts
  • src/main/external-conversations/external-conversation-reply-recovery-dispose.test.ts
  • src/main/external-conversations/external-conversation-reply-recovery.ts
  • src/main/external-conversations/external-conversation-reply-verdict-fills.ts
  • src/main/external-conversations/external-conversation-turn-ends.ts
  • src/main/external-conversations/external-conversations-install.ts
  • src/main/native-chat/agent-session-journal/connector-replies/journal-connector-replies-schema.test.ts
  • src/main/native-chat/agent-session-journal/connector-replies/journal-connector-replies.ts
  • src/main/native-chat/agent-session-journal/connector-replies/journal-sql-connector-replies.test.ts
  • src/main/native-chat/agent-session-journal/connector-replies/journal-sql-connector-replies.ts
  • src/main/native-chat/agent-session-journal/journal-sql-maintenance.ts
  • src/main/native-chat/agent-session-journal/journal-sql-owner-admit.test.ts
  • src/main/native-chat/agent-session-journal/journal-sql-owner.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 0 remain after this review.

.finally(() => {
release()
deps.settled(turn.sessionId)
deps.settled(turn.sessionId, turn.current)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Major · Stability & Availability · Heavy lift

A held retry that settles after a host replacement can leave its request without recovery.

When the host is replaced during a hidden retry's send, the replacement pass excludes the sending row through retrySending and unwatches its session (external-conversation-reply-recovery.ts:213-219). If that row is the only unfilled row, no watch remains. When the send later returns 'refused', release() clears the sending marker. The settled callback then passes the lifetime captured before the replacement, and turnEnded skips later(sessionId) because that lifetime is no longer current (external-conversation-reply-recovery.ts:159-163). Nothing in the replacement schedules recovery for that session, so the held request can stay unfilled until a recovery trigger the inspected path does not include.

The retired-operation guard must stay. After a held send settles, the current generation must own recovery for that session. It must either keep a watch or schedule a pass. The mechanism is open.

Source: Learnings

this.deps.filled()
return
}
const closer = staleCloser(this.deps.processStartedAt ?? PROCESS_STARTED_AT)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor · Functional Correctness · Quick win

Create the verdict closer after the asynchronous evidence reads.

staleCloser captures Date.now() here. Recovery then awaits chat opening, evidence reads, recovered-turn fills, and usage-limit lookups before it classifies held answers.

If a held answer is 59 minutes old here and those operations take two minutes, fillVerdicts still classifies it as 59 minutes old. It posts an answer that is now 61 minutes old instead of closing quietly. The 24-hour request boundary has the same problem.

Create a new closer immediately before the verdict classification. Keep the missing-session closer near its separate fill call.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Additional comments: 1

src/main/external-conversations/connector-reply-stale-batch.test.ts: 1

127-127: Trivial · Maintainability & Code Quality · Quick win

Unverified finding
Verification ran but could not confirm this finding. It is shown for review, not as a verified issue.

Exercise rollback after an earlier row update.

failsWithD2 rejects before it calls the real writer. This test checks recovery and event keys, but it does not exercise rollback inside the batch transaction.

Add a case that fails the second SQL update after the first update executes. Before draining or recovery, assert that both d1 and d2 remain unfilled. Keep the final event assertions.

Based on learnings, an atomicity check must verify every row in the failed batch.

Source: Learnings

Review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 197634ca-75c9-4d0f-afdd-975225029eae
Commits

Reviewing files that changed from the base of the PR and between 9025df5 and 8da6ce9.

Files selected for processing: 2

  • src/main/external-conversations/connector-reply-stale-batch.test.ts
  • src/main/native-chat/agent-session-journal/connector-replies/journal-connector-replies.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 0 remain after this review.

@AmethystLiang
AmethystLiang marked this pull request as draft November 25, 2026 09:08
@AmethystLiang

Copy link
Copy Markdown
Contributor Author

Closing: the original bug was fixed on main by #46044, #46068 and #47898; the remaining quiet-expiry extra is not worth the added recovery complexity.

@AmethystLiang
AmethystLiang deleted the AmethystLiang/reply-stale-expiry branch November 25, 2026 09:08
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