Skip to content
Source
Sign inSign up
pingdotgg/t3code

fix(server): queue messages sent during context compaction #9620

Closedflamboh(GitHub profile, opens in a new tab)wants to merge 1 commit intomain fromrefs/pull/9620/headopened View on GitHub

Note

🤖 Fable 5.1 on behalf of Oliver

Problem

Sending a message while a thread is compacting its context (after /compact) fails with "Wait for context compaction to finish before sending another message." The web client removes the optimistic message and restores the draft, so the message is never delivered. This affects every provider because the guard lives in the orchestration reactor, not in an adapter.

Fix

The reactor now holds messages that arrive during compaction in a per-thread FIFO and sends them once the compaction fiber settles, using the same send path a fresh message takes.

  • Compaction success or a failed compaction that still restores the session to ready both drain the queue in order.
  • If the thread stops or the session ends in error, each queued message gets its own provider.turn.start.failed activity so clients restore the draft instead of silently losing it.
  • A second /compact during compaction keeps its existing failure.
  • The projection now lets a queued message replace the pending /compact turn-start row and keeps that row when the compaction restores the session, so the replayed turn still projects starting and keeps its proposed-plan reference.

No contract, decider, web, or mobile changes. Messages were already persisted immediately, so clients see them optimistically and get acknowledged when the turn starts.

Tests

  • ProviderCommandReactor.test.ts: queued message is sent after a failed compaction restores the session, two messages drain in FIFO order, queued message fails when the thread stops mid-compaction.
  • ProjectionPipeline.test.ts: a turn start deferred behind compaction becomes the pending row after the session restores.

Implemented by GPT-5.6 Sol via codex exec, orchestrated and reviewed by Claude Fable 5.1 in Claude Code.

Note

Queue messages sent during context compaction

Ensures messages sent while context compaction is in progress are queued and retained after the session is restored. Adds an integration test in ProjectionPipeline.test.ts verifying that a deferred non-compaction turn-start request survives compaction completion and preserves its message, proposed-plan metadata, and original request timestamp.

📊 Macroscope summarized 6014e20. 3 files reviewed, 4 issues evaluated, 0 issues filtered, 4 comments posted

🗂️ Filtered Issues

    1. github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted

    2. @@ -1288,7 +1275,20 @@
      1288- yield* projectionTurnRepository.replacePendingTurnStart({
      1275+ const nextPendingTurnStart = {
      12891276 threadId: event.payload.threadId,
      12901277 messageId: event.payload.messageId,
      12911278 sourceProposedPlanThreadId: event.payload.sourceProposedPlan?.threadId ?? null,
      12921279 sourceProposedPlanId: event.payload.sourceProposedPlan?.planId ?? null,
      12931280 requestedAt: event.payload.createdAt,
      1281+ };
      1282+ const requestedMessage = yield* projectionThreadMessageRepository.getByMessageId({
      1283+ messageId: event.payload.messageId,
      12941284 });
      1285+ const isCompactRequest =
      1286+ Option.isSome(requestedMessage) &&
      1287+ requestedMessage.value.role === "user" &&
      1288+ (requestedMessage.value.attachments?.length ?? 0) === 0 &&
      1289+ requestedMessage.value.text.trim().toLowerCase() === "/compact";
      1290+ if (isCompactRequest) {
      1291+ if (compactRequestIds.has(event.payload.threadId)) {
      1292+ return;
      1293+ }
      1294+ compactRequestIds.set(event.payload.threadId, event.payload.messageId);
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Layers/ProjectionPipeline.ts:1294

      A failed replacePendingTurnStart leaves compactRequestIds populated even though the database transaction rolled back, so the next /compact for that thread returns at the duplicate check without creating a pending-start row. Move the map update until after replacePendingTurnStart succeeds.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration/Layers/ProjectionPipeline.ts around line 1294:
      
      A failed `replacePendingTurnStart` leaves `compactRequestIds` populated even though the database transaction rolled back, so the next `/compact` for that thread returns at the duplicate check without creating a pending-start row. Move the map update until after `replacePendingTurnStart` succeeds.
      @@ -1333,8 +1333,15 @@
      1333- event.commandId?.startsWith("server:provider-session-set:") === true) ||
      1333+ const restoredReadySession =
      1334+ event.payload.session.status === "ready" &&
      1335+ event.commandId?.startsWith("server:provider-session-set:") === true;
      1336+ const terminalSession =
      13341337 event.payload.session.status === "error" ||
      13351338 event.payload.session.status === "stopped" ||
      1336- event.payload.session.status === "interrupted"
      1337- ) {
      1338- yield* projectionTurnRepository.deletePendingTurnStartByThreadId({
      1339- threadId: event.payload.threadId,
      1340- });
      1339+ event.payload.session.status === "interrupted";
      1340+ if (restoredReadySession || terminalSession) {
      1341+ const pendingTurnStart =
      1342+ yield* projectionTurnRepository.getPendingTurnStartByThreadId({
      1343+ threadId: event.payload.threadId,
      1344+ });
      1345+ const compactRequestId = compactRequestIds.get(event.payload.threadId);
      1346+ const pendingTurnBelongsToCompaction =
      1347+ compactRequestId === undefined ||
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Layers/ProjectionPipeline.ts:1347

      After a restart, a restoring ready session deletes a queued message's pending turn-start row, so the queued turn loses its pending-message/proposed-plan metadata and is no longer projected as starting. Because compactRequestIds is in-memory, compactRequestId === undefined must not be treated as proof that the pending row belongs to /compact; only delete it when a known compaction request matches (while terminal sessions can still clear it unconditionally).

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration/Layers/ProjectionPipeline.ts around line 1347:
      
      After a restart, a restoring `ready` session deletes a queued message's pending turn-start row, so the queued turn loses its pending-message/proposed-plan metadata and is no longer projected as `starting`. Because `compactRequestIds` is in-memory, `compactRequestId === undefined` must not be treated as proof that the pending row belongs to `/compact`; only delete it when a known compaction request matches (while terminal sessions can still clear it unconditionally).
      @@ -345,3 +345,13 @@
      345345 const threadModelSelections = new Map<string, ModelSelection>();
      346346 const compactingThreadIds = new Set<ThreadId>();
      347347 const stoppingThreadIds = new Set<ThreadId>();
      348+ type TurnStartRequestedEvent = Extract<
      349+ ProviderIntentEvent,
      350+ { type: "thread.turn-start-requested" }
      351+ >;
      352+ type QueuedTurnStart = {
      353+ readonly event: TurnStartRequestedEvent;
      354+ readonly message: ThreadTitleMessage;
      355+ };
      356+ // Compaction fibers replay these events in arrival order after restoring the session.
      357+ const queuedTurnStarts = new Map<ThreadId, Array<QueuedTurnStart>>();
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High Layers/ProviderCommandReactor.ts:357

      When the server restarts during compaction, queued user messages are never delivered and no failure activity is recorded. queuedTurnStarts exists only in memory, while start subscribes to a hot stream, so the already-persisted thread.turn-start-requested events are not replayed after the map is lost; persist the queue or replay pending requests during startup.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration/Layers/ProviderCommandReactor.ts around line 357:
      
      When the server restarts during compaction, queued user messages are never delivered and no failure activity is recorded. `queuedTurnStarts` exists only in memory, while `start` subscribes to a hot stream, so the already-persisted `thread.turn-start-requested` events are not replayed after the map is lost; persist the queue or replay pending requests during startup.
      @@ -1400,3 +1449,3 @@
      14001449 Effect.andThen(restoreCompaction(event.payload.threadId, true)),
      14011450 Effect.catchCause(recoverCompactionFailure),
      14021451 Effect.ensuring(Effect.sync(() => void compactingThreadIds.delete(event.payload.threadId))),
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High Layers/ProviderCommandReactor.ts:1451

      A turn start arriving after compaction completes but before drainQueuedTurnStarts finishes is sent immediately, so it can reach the provider before earlier queued prompts and breaks the claimed per-thread FIFO order. Effect.ensuring clears compactingThreadIds before the drain runs; keep the thread marked compacting through the entire drain and ensure arrivals during the drain are consumed before releasing it.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration/Layers/ProviderCommandReactor.ts around line 1451:
      
      A turn start arriving after compaction completes but before `drainQueuedTurnStarts` finishes is sent immediately, so it can reach the provider before earlier queued prompts and breaks the claimed per-thread FIFO order. `Effect.ensuring` clears `compactingThreadIds` before the drain runs; keep the thread marked compacting through the entire drain and ensure arrivals during the drain are consumed before releasing it.
    3. Approvability

      Verdict: Not approved

      Macroscope's review found this PR not approvable — This substantial server-side behavior change adds an in-memory per-thread FIFO and modifies compaction/session-restoration projection semantics, allowing prompts to be delivered asynchronously across lifecycle boundaries. Restart, persistence, and ordering edge cases remain material, so the change warrants human review.

      Not approved because:

      • 4 blocking correctness issues found at or above your repo's Minimum Blocking Severity
      Adjust the Minimum Blocking Severity for this repo — including turning it Off — in [Settings](https://app.macroscope.com/pingdotgg/settings#Repos). You can add or adjust custom eligibility rules. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).
    4. Probably worth doing with orchestrator v2, rather than now

Sign in to join this conversation.