From 527197c48447991f01cef018b25b4d6251b10496 Mon Sep 17 00:00:00 2001 From: EtanHey Date: Tue, 24 Nov 2026 01:58:55 +0200 Subject: [PATCH 1/5] fix(client): a delivered queued message hidden by an old cache shows again A cached thread kept the visibility the old rule gave it. Before #41307, a queued message whose run a restart cancelled was hidden even though the agent got it, and the client cached that. Reopening a thread resumed from the cache without rechecking, so the message stayed missing and find-in-thread paged back through history forever looking for it. Restoring a cached projection (from disk or memory) now reruns the current visibility rule, so delivered queued input comes back and input that never started stays hidden. Co-Authored-By: GPT-6.1 Sol Co-Authored-By: Claude Opus 5.5 --- .../legacy-delivered-queued-cache.json | 12 +++++ .../src/state/orchestrationV2Projection.ts | 22 +++++++- .../src/state/threads-sync.test.ts | 52 +++++++++++++++++++ packages/client-runtime/src/state/threads.ts | 10 +++- 4 files changed, 92 insertions(+), 4 deletions(-) create mode 100644 packages/client-runtime/src/state/fixtures/legacy-delivered-queued-cache.json diff --git a/packages/client-runtime/src/state/fixtures/legacy-delivered-queued-cache.json b/packages/client-runtime/src/state/fixtures/legacy-delivered-queued-cache.json new file mode 100644 index 0000000000000..a38f08ab12e85 --- /dev/null +++ b/packages/client-runtime/src/state/fixtures/legacy-delivered-queued-cache.json @@ -0,0 +1,12 @@ +{ + "sourceCommit": "9f24cac6d42f99e92569b7cbd97ec07932f232d8", + "sequence": [ + "run.created:queued", + "turn-item.updated:queued_turn", + "run.updated:starting", + "run.updated:running", + "run.updated:cancelled", + "turn-item.updated:later-input" + ], + "cache": "{\"schemaVersion\":5,\"environmentId\":\"environment-test\",\"threadId\":\"thread-v2\",\"snapshot\":{\"snapshotSequence\":6,\"projection\":{\"thread\":{\"createdBy\":\"user\",\"creationSource\":\"web\",\"id\":\"thread-v2\",\"projectId\":\"project-v2\",\"title\":\"Thread\",\"providerInstanceId\":\"codex\",\"modelSelection\":{\"instanceId\":\"codex\",\"model\":\"gpt-5.4\"},\"runtimeMode\":\"full-access\",\"interactionMode\":\"default\",\"branch\":null,\"worktreePath\":null,\"activeProviderThreadId\":null,\"lineage\":{\"parentThreadId\":null,\"relationshipToParent\":null,\"rootThreadId\":\"thread-v2\"},\"forkedFrom\":null,\"createdAt\":\"2026-06-20T00:00:00.000Z\",\"updatedAt\":\"2026-06-20T00:00:00.000Z\",\"archivedAt\":null,\"settledOverride\":null,\"settledAt\":null,\"lastVisitedAt\":null,\"deletedAt\":null},\"runs\":[{\"id\":\"retained-queued-run\",\"threadId\":\"thread-v2\",\"ordinal\":1,\"providerInstanceId\":\"codex\",\"modelSelection\":{\"instanceId\":\"codex\",\"model\":\"gpt-5.4\"},\"providerThreadId\":null,\"userMessageId\":\"Delivered before recovery\",\"rootNodeId\":\"retained-queued-node\",\"activeAttemptId\":null,\"status\":\"cancelled\",\"requestedAt\":\"2026-06-20T00:00:00.000Z\",\"startedAt\":\"2026-06-20T00:00:00.000Z\",\"completedAt\":\"2026-06-20T00:00:00.000Z\",\"checkpointId\":null,\"contextHandoffId\":null}],\"attempts\":[],\"nodes\":[],\"subagents\":[],\"providerSessions\":[],\"providerThreads\":[],\"providerTurns\":[],\"runtimeRequests\":[],\"messages\":[],\"plans\":[],\"turnItems\":[{\"id\":\"Delivered before recovery\",\"threadId\":\"thread-v2\",\"runId\":\"retained-queued-run\",\"nodeId\":null,\"providerThreadId\":null,\"providerTurnId\":null,\"nativeItemRef\":null,\"parentItemId\":null,\"ordinal\":1,\"status\":\"completed\",\"title\":null,\"startedAt\":\"2026-06-20T00:00:00.000Z\",\"completedAt\":\"2026-06-20T00:00:00.000Z\",\"updatedAt\":\"2026-06-20T00:00:00.000Z\",\"createdBy\":\"user\",\"creationSource\":\"web\",\"type\":\"user_message\",\"messageId\":\"Delivered before recovery\",\"inputIntent\":\"queued_turn\",\"text\":\"Delivered before recovery\",\"attachments\":[]},{\"id\":\"Later input\",\"threadId\":\"thread-v2\",\"runId\":null,\"nodeId\":null,\"providerThreadId\":null,\"providerTurnId\":null,\"nativeItemRef\":null,\"parentItemId\":null,\"ordinal\":301,\"status\":\"completed\",\"title\":null,\"startedAt\":\"2026-06-20T00:00:00.000Z\",\"completedAt\":\"2026-06-20T00:00:00.000Z\",\"updatedAt\":\"2026-06-20T00:00:00.000Z\",\"createdBy\":\"user\",\"creationSource\":\"web\",\"type\":\"user_message\",\"messageId\":\"Later input\",\"inputIntent\":\"turn_start\",\"text\":\"Later input\",\"attachments\":[]}],\"checkpointScopes\":[],\"checkpoints\":[],\"contextHandoffs\":[],\"contextTransfers\":[],\"visibleTurnItems\":[{\"position\":0,\"visibility\":\"local\",\"sourceThreadId\":\"thread-v2\",\"sourceItemId\":\"Later input\",\"item\":{\"id\":\"Later input\",\"threadId\":\"thread-v2\",\"runId\":null,\"nodeId\":null,\"providerThreadId\":null,\"providerTurnId\":null,\"nativeItemRef\":null,\"parentItemId\":null,\"ordinal\":301,\"status\":\"completed\",\"title\":null,\"startedAt\":\"2026-06-20T00:00:00.000Z\",\"completedAt\":\"2026-06-20T00:00:00.000Z\",\"updatedAt\":\"2026-06-20T00:00:00.000Z\",\"createdBy\":\"user\",\"creationSource\":\"web\",\"type\":\"user_message\",\"messageId\":\"Later input\",\"inputIntent\":\"turn_start\",\"text\":\"Later input\",\"attachments\":[]}}],\"updatedAt\":\"2026-06-20T00:00:00.000Z\"},\"historyCursor\":\"history-cursor\",\"hasMoreHistory\":true,\"latestLocalTurnOrdinal\":301}}" +} diff --git a/packages/client-runtime/src/state/orchestrationV2Projection.ts b/packages/client-runtime/src/state/orchestrationV2Projection.ts index d936fa7726df2..218c3219ffbd0 100644 --- a/packages/client-runtime/src/state/orchestrationV2Projection.ts +++ b/packages/client-runtime/src/state/orchestrationV2Projection.ts @@ -266,11 +266,15 @@ function upsertVisibleTurnItem( // items never received stay absent. function restoreQueuedUserItems( projection: OrchestrationV2ThreadProjection, - runId: OrchestrationV2Run["id"], + runId?: OrchestrationV2Run["id"], ): OrchestrationV2ThreadProjection["visibleTurnItems"] { let visibleTurnItems = projection.visibleTurnItems; for (const item of projection.turnItems) { - if (item.runId !== runId || item.type !== "user_message" || item.inputIntent !== "queued_turn") + if ( + (runId !== undefined && item.runId !== runId) || + item.type !== "user_message" || + item.inputIntent !== "queued_turn" + ) continue; if (!shouldShowLocalTurnItem(projection, item)) continue; visibleTurnItems = upsertVisibleTurnItem( @@ -283,6 +287,20 @@ function restoreQueuedUserItems( return visibleTurnItems; } +// Older caches can retain delivered queued input hidden by the former visibility rule. +// Request cards retained outside the window must not be pulled into the timeline. +export function restoreCachedProjectionVisibility( + projection: OrchestrationV2ThreadProjection, +): OrchestrationV2ThreadProjection { + const visibleTurnItems = restoreQueuedUserItems({ + ...projection, + visibleTurnItems: activeVisibleTurnItems(projection), + }); + return visibleTurnItems === projection.visibleTurnItems + ? projection + : { ...projection, visibleTurnItems }; +} + export function applyOrchestrationV2ProjectionEvent( projection: OrchestrationV2ThreadProjection | null, event: OrchestrationV2DomainEvent, diff --git a/packages/client-runtime/src/state/threads-sync.test.ts b/packages/client-runtime/src/state/threads-sync.test.ts index d14b8a66c40cd..0490a8db54b61 100644 --- a/packages/client-runtime/src/state/threads-sync.test.ts +++ b/packages/client-runtime/src/state/threads-sync.test.ts @@ -1,3 +1,4 @@ +import legacyQueuedCache from "./fixtures/legacy-delivered-queued-cache.json" with { type: "json" }; import { EnvironmentAuthorizationError, EnvironmentId, @@ -77,6 +78,9 @@ const PREPARED: PreparedConnection = { httpAuthorization: null, target: TARGET, }; +const decodeLegacyThreadCache = Schema.decodeEffect( + Schema.fromJsonString(StoredOrchestrationThreadSnapshot), +); const BASE_PROJECTION: OrchestrationV2ThreadProjection = { ...v2Projection, thread: { ...v2Projection.thread, title: "Cached thread" }, @@ -423,6 +427,54 @@ const deleted = (sequence = 3): OrchestrationV2ThreadStreamItem => { }; describe("EnvironmentThreads", () => { + it.effect.each([ + ["disk", true], + ["retained", true], + ["disk", false], + ["retained", false], + ] as const)( + "restores cached queued-input visibility before history loads (%s, started=%s)", + ([cacheKind, started]) => + Effect.gen(function* () { + const stored = yield* decodeLegacyThreadCache(legacyQueuedCache.cache); + const projection = started + ? stored.snapshot.projection + : { + ...stored.snapshot.projection, + runs: stored.snapshot.projection.runs.map((run) => ({ ...run, startedAt: null })), + }; + expect(projection.turnItems.map((item) => item.id)).toContain("Delivered before recovery"); + expect(projection.visibleTurnItems.map((row) => row.sourceItemId)).toEqual(["Later input"]); + const h = yield* makeHarness({ + loadCached: Effect.succeedSome({ ...stored.snapshot, projection }), + ...(cacheKind === "retained" + ? { + resumeCache: { + owner: undefined, + snapshot: { + state: { + ...EMPTY_ENVIRONMENT_THREAD_STATE, + data: Option.some(projection), + status: "live", + }, + sequence: stored.snapshot.snapshotSequence, + persisted: true, + }, + }, + } + : {}), + completionMarker: true, + }); + yield* Queue.offer(h.inputs, synchronized()); + const state = yield* awaitThreadState(h.observed, (value) => value.status === "live"); + expect( + Option.getOrThrow(state.data).visibleTurnItems.map((row) => row.sourceItemId), + ).toEqual(started ? ["Delivered before recovery", "Later input"] : ["Later input"]); + expect(yield* Ref.get(h.loaderCalls)).toBe(0); + expect(yield* Ref.get(h.lastSubscribeAfterSequence)).toBe(stored.snapshot.snapshotSequence); + }), + ); + it.effect.each([ ["disk", false], ["retained", false], diff --git a/packages/client-runtime/src/state/threads.ts b/packages/client-runtime/src/state/threads.ts index c0921417ba5cf..19af253a6398e 100644 --- a/packages/client-runtime/src/state/threads.ts +++ b/packages/client-runtime/src/state/threads.ts @@ -44,7 +44,10 @@ import { subscriptionRetryDelay, } from "../rpc/client.ts"; import { parseThreadKey, threadKey } from "./entities.ts"; -import { applyOrchestrationV2ProjectionEvent } from "./orchestrationV2Projection.ts"; +import { + applyOrchestrationV2ProjectionEvent, + restoreCachedProjectionVisibility, +} from "./orchestrationV2Projection.ts"; import { THREAD_SNAPSHOT_IDLE_TTL_MS } from "./threadRetention.ts"; import { followStreamInEnvironment } from "./runtime.ts"; import * as ThreadHistoryController from "./threadHistoryController.ts"; @@ -221,6 +224,7 @@ function matchesThreadSnapshot( function cachedThreadState(value: EnvironmentThreadState): EnvironmentThreadState { return { ...value, + data: Option.map(value.data, restoreCachedProjectionVisibility), status: value.status === "deleted" || (value.status === "live" && Option.isSome(value.data)) ? value.status @@ -290,7 +294,9 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make loaded, (snapshot) => !hasMissingPendingQuestionCard(snapshot.projection), ); - const cachedThread = Option.map(cached, (snapshot) => snapshot.projection); + const cachedThread = Option.map(cached, (snapshot) => + restoreCachedProjectionVisibility(snapshot.projection), + ); // Seed the resume cursor from the cached snapshot so a warm cache can catch up // via `afterSequence` instead of re-downloading the full thread body. const initialSequence = From 1a97353e7e1a66db81d3e739d93b0c3bcf055720 Mon Sep 17 00:00:00 2001 From: EtanHey Date: Tue, 24 Nov 2026 02:13:30 +0200 Subject: [PATCH 2/5] test(client): build the stale cache inline and keep only the cases that fail on main Co-Authored-By: Claude Opus 5.5 --- .../legacy-delivered-queued-cache.json | 12 ---- .../src/state/threads-sync.test.ts | 68 ++++++++++++------- 2 files changed, 42 insertions(+), 38 deletions(-) delete mode 100644 packages/client-runtime/src/state/fixtures/legacy-delivered-queued-cache.json diff --git a/packages/client-runtime/src/state/fixtures/legacy-delivered-queued-cache.json b/packages/client-runtime/src/state/fixtures/legacy-delivered-queued-cache.json deleted file mode 100644 index a38f08ab12e85..0000000000000 --- a/packages/client-runtime/src/state/fixtures/legacy-delivered-queued-cache.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "sourceCommit": "9f24cac6d42f99e92569b7cbd97ec07932f232d8", - "sequence": [ - "run.created:queued", - "turn-item.updated:queued_turn", - "run.updated:starting", - "run.updated:running", - "run.updated:cancelled", - "turn-item.updated:later-input" - ], - "cache": "{\"schemaVersion\":5,\"environmentId\":\"environment-test\",\"threadId\":\"thread-v2\",\"snapshot\":{\"snapshotSequence\":6,\"projection\":{\"thread\":{\"createdBy\":\"user\",\"creationSource\":\"web\",\"id\":\"thread-v2\",\"projectId\":\"project-v2\",\"title\":\"Thread\",\"providerInstanceId\":\"codex\",\"modelSelection\":{\"instanceId\":\"codex\",\"model\":\"gpt-5.4\"},\"runtimeMode\":\"full-access\",\"interactionMode\":\"default\",\"branch\":null,\"worktreePath\":null,\"activeProviderThreadId\":null,\"lineage\":{\"parentThreadId\":null,\"relationshipToParent\":null,\"rootThreadId\":\"thread-v2\"},\"forkedFrom\":null,\"createdAt\":\"2026-06-20T00:00:00.000Z\",\"updatedAt\":\"2026-06-20T00:00:00.000Z\",\"archivedAt\":null,\"settledOverride\":null,\"settledAt\":null,\"lastVisitedAt\":null,\"deletedAt\":null},\"runs\":[{\"id\":\"retained-queued-run\",\"threadId\":\"thread-v2\",\"ordinal\":1,\"providerInstanceId\":\"codex\",\"modelSelection\":{\"instanceId\":\"codex\",\"model\":\"gpt-5.4\"},\"providerThreadId\":null,\"userMessageId\":\"Delivered before recovery\",\"rootNodeId\":\"retained-queued-node\",\"activeAttemptId\":null,\"status\":\"cancelled\",\"requestedAt\":\"2026-06-20T00:00:00.000Z\",\"startedAt\":\"2026-06-20T00:00:00.000Z\",\"completedAt\":\"2026-06-20T00:00:00.000Z\",\"checkpointId\":null,\"contextHandoffId\":null}],\"attempts\":[],\"nodes\":[],\"subagents\":[],\"providerSessions\":[],\"providerThreads\":[],\"providerTurns\":[],\"runtimeRequests\":[],\"messages\":[],\"plans\":[],\"turnItems\":[{\"id\":\"Delivered before recovery\",\"threadId\":\"thread-v2\",\"runId\":\"retained-queued-run\",\"nodeId\":null,\"providerThreadId\":null,\"providerTurnId\":null,\"nativeItemRef\":null,\"parentItemId\":null,\"ordinal\":1,\"status\":\"completed\",\"title\":null,\"startedAt\":\"2026-06-20T00:00:00.000Z\",\"completedAt\":\"2026-06-20T00:00:00.000Z\",\"updatedAt\":\"2026-06-20T00:00:00.000Z\",\"createdBy\":\"user\",\"creationSource\":\"web\",\"type\":\"user_message\",\"messageId\":\"Delivered before recovery\",\"inputIntent\":\"queued_turn\",\"text\":\"Delivered before recovery\",\"attachments\":[]},{\"id\":\"Later input\",\"threadId\":\"thread-v2\",\"runId\":null,\"nodeId\":null,\"providerThreadId\":null,\"providerTurnId\":null,\"nativeItemRef\":null,\"parentItemId\":null,\"ordinal\":301,\"status\":\"completed\",\"title\":null,\"startedAt\":\"2026-06-20T00:00:00.000Z\",\"completedAt\":\"2026-06-20T00:00:00.000Z\",\"updatedAt\":\"2026-06-20T00:00:00.000Z\",\"createdBy\":\"user\",\"creationSource\":\"web\",\"type\":\"user_message\",\"messageId\":\"Later input\",\"inputIntent\":\"turn_start\",\"text\":\"Later input\",\"attachments\":[]}],\"checkpointScopes\":[],\"checkpoints\":[],\"contextHandoffs\":[],\"contextTransfers\":[],\"visibleTurnItems\":[{\"position\":0,\"visibility\":\"local\",\"sourceThreadId\":\"thread-v2\",\"sourceItemId\":\"Later input\",\"item\":{\"id\":\"Later input\",\"threadId\":\"thread-v2\",\"runId\":null,\"nodeId\":null,\"providerThreadId\":null,\"providerTurnId\":null,\"nativeItemRef\":null,\"parentItemId\":null,\"ordinal\":301,\"status\":\"completed\",\"title\":null,\"startedAt\":\"2026-06-20T00:00:00.000Z\",\"completedAt\":\"2026-06-20T00:00:00.000Z\",\"updatedAt\":\"2026-06-20T00:00:00.000Z\",\"createdBy\":\"user\",\"creationSource\":\"web\",\"type\":\"user_message\",\"messageId\":\"Later input\",\"inputIntent\":\"turn_start\",\"text\":\"Later input\",\"attachments\":[]}}],\"updatedAt\":\"2026-06-20T00:00:00.000Z\"},\"historyCursor\":\"history-cursor\",\"hasMoreHistory\":true,\"latestLocalTurnOrdinal\":301}}" -} diff --git a/packages/client-runtime/src/state/threads-sync.test.ts b/packages/client-runtime/src/state/threads-sync.test.ts index 0490a8db54b61..9610cd7c98d78 100644 --- a/packages/client-runtime/src/state/threads-sync.test.ts +++ b/packages/client-runtime/src/state/threads-sync.test.ts @@ -1,4 +1,3 @@ -import legacyQueuedCache from "./fixtures/legacy-delivered-queued-cache.json" with { type: "json" }; import { EnvironmentAuthorizationError, EnvironmentId, @@ -50,7 +49,7 @@ import { decodeOrDiscardOrchestrationCache, } from "../platform/orchestrationCache.ts"; import * as RpcSession from "../rpc/session.ts"; -import { v2Now, v2Projection, v2ThreadId } from "./orchestrationV2TestFixtures.ts"; +import { v2MessageRow, v2Now, v2Projection, v2ThreadId } from "./orchestrationV2TestFixtures.ts"; import { onThreadRequestsResolved, type ThreadRequestsResolved } from "./threadRequests.ts"; import { EMPTY_THREAD_HISTORY_META } from "./threadHistoryMerge.ts"; import * as ThreadHistoryController from "./threadHistoryController.ts"; @@ -78,9 +77,6 @@ const PREPARED: PreparedConnection = { httpAuthorization: null, target: TARGET, }; -const decodeLegacyThreadCache = Schema.decodeEffect( - Schema.fromJsonString(StoredOrchestrationThreadSnapshot), -); const BASE_PROJECTION: OrchestrationV2ThreadProjection = { ...v2Projection, thread: { ...v2Projection.thread, title: "Cached thread" }, @@ -427,26 +423,47 @@ const deleted = (sequence = 3): OrchestrationV2ThreadStreamItem => { }; describe("EnvironmentThreads", () => { - it.effect.each([ - ["disk", true], - ["retained", true], - ["disk", false], - ["retained", false], - ] as const)( - "restores cached queued-input visibility before history loads (%s, started=%s)", - ([cacheKind, started]) => + it.effect.each(["disk", "retained"] as const)( + "shows a delivered queued message that an older %s cache hid", + (cacheKind) => Effect.gen(function* () { - const stored = yield* decodeLegacyThreadCache(legacyQueuedCache.cache); - const projection = started - ? stored.snapshot.projection - : { - ...stored.snapshot.projection, - runs: stored.snapshot.projection.runs.map((run) => ({ ...run, startedAt: null })), - }; - expect(projection.turnItems.map((item) => item.id)).toContain("Delivered before recovery"); - expect(projection.visibleTurnItems.map((row) => row.sourceItemId)).toEqual(["Later input"]); + // Before #41307, a restart that cancelled a started run hid its queued message. + const runId = RunId.make("run-cancelled-after-start"); + const later = v2MessageRow("Later input", 2); + const delivered = { + ...v2MessageRow("Delivered before restart", 1).item, + runId, + inputIntent: "queued_turn", + } as OrchestrationV2TurnItem; + const projection: OrchestrationV2ThreadProjection = { + ...BASE_PROJECTION, + runs: [ + { + id: runId, + threadId: THREAD_ID, + ordinal: 1, + providerInstanceId: BASE_PROJECTION.thread.providerInstanceId, + modelSelection: BASE_PROJECTION.thread.modelSelection, + providerThreadId: null, + userMessageId: MessageId.make("Delivered before restart"), + rootNodeId: null, + activeAttemptId: null, + status: "cancelled", + requestedAt: v2Now, + startedAt: v2Now, + completedAt: v2Now, + checkpointId: null, + contextHandoffId: null, + }, + ], + turnItems: [delivered, later.item], + visibleTurnItems: [later], + }; const h = yield* makeHarness({ - loadCached: Effect.succeedSome({ ...stored.snapshot, projection }), + loadCached: Effect.succeedSome({ + snapshotSequence: CACHED_SNAPSHOT_SEQUENCE, + projection, + }), ...(cacheKind === "retained" ? { resumeCache: { @@ -457,7 +474,7 @@ describe("EnvironmentThreads", () => { data: Option.some(projection), status: "live", }, - sequence: stored.snapshot.snapshotSequence, + sequence: CACHED_SNAPSHOT_SEQUENCE, persisted: true, }, }, @@ -469,9 +486,8 @@ describe("EnvironmentThreads", () => { const state = yield* awaitThreadState(h.observed, (value) => value.status === "live"); expect( Option.getOrThrow(state.data).visibleTurnItems.map((row) => row.sourceItemId), - ).toEqual(started ? ["Delivered before recovery", "Later input"] : ["Later input"]); + ).toEqual([delivered.id, later.sourceItemId]); expect(yield* Ref.get(h.loaderCalls)).toBe(0); - expect(yield* Ref.get(h.lastSubscribeAfterSequence)).toBe(stored.snapshot.snapshotSequence); }), ); From 3e7cf3b6819b2d86af5e55ddf4036d8c71280424 Mon Sep 17 00:00:00 2001 From: EtanHey Date: Tue, 24 Nov 2026 02:14:31 +0200 Subject: [PATCH 3/5] test(client): keep the reason in the regression comment, drop the PR number Co-Authored-By: Claude Opus 5.5 --- packages/client-runtime/src/state/threads-sync.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/client-runtime/src/state/threads-sync.test.ts b/packages/client-runtime/src/state/threads-sync.test.ts index 9610cd7c98d78..9dc93757b2269 100644 --- a/packages/client-runtime/src/state/threads-sync.test.ts +++ b/packages/client-runtime/src/state/threads-sync.test.ts @@ -427,7 +427,7 @@ describe("EnvironmentThreads", () => { "shows a delivered queued message that an older %s cache hid", (cacheKind) => Effect.gen(function* () { - // Before #41307, a restart that cancelled a started run hid its queued message. + // The former rule hid the queued message of a started run that a restart cancelled. const runId = RunId.make("run-cancelled-after-start"); const later = v2MessageRow("Later input", 2); const delivered = { From 21601fa7b6e6eb17de35e1b24e3061cb4400b765 Mon Sep 17 00:00:00 2001 From: EtanHey Date: Tue, 24 Nov 2026 02:50:26 +0200 Subject: [PATCH 4/5] fix(client): drop thread caches that hid a delivered queued message Replace the restore-time visibility pass with a thread cache version bump (full 5 -> 7, compact 6 -> 8, since 6 is taken by the compact format). Caches written before the shared rule changed are discarded and the thread loads a fresh snapshot once, with no extra work on every cache restore. Co-Authored-By: Claude Opus 5.5 --- .../environment-cache-store.test.ts | 6 +- .../src/platform/orchestrationCache.ts | 5 +- .../src/platform/threadCacheEncoding.ts | 2 +- .../src/state/orchestrationV2Projection.ts | 22 +----- .../src/state/threads-sync.test.ts | 74 +------------------ packages/client-runtime/src/state/threads.ts | 10 +-- 6 files changed, 14 insertions(+), 105 deletions(-) diff --git a/apps/mobile/src/connection/environment-cache-store.test.ts b/apps/mobile/src/connection/environment-cache-store.test.ts index 1205c746e9fa1..3c04fc9069fda 100644 --- a/apps/mobile/src/connection/environment-cache-store.test.ts +++ b/apps/mobile/src/connection/environment-cache-store.test.ts @@ -463,8 +463,8 @@ describe("mobile SQLite environment cache store", () => { yield* store.saveThread(ENVIRONMENT_ID, snapshot); const id = cacheId(ENVIRONMENT_ID, "thread", THREAD_ID); const encoded = JSON.parse(memory.values.get(id)!); - expect(encoded.schemaVersion).toBe(6); - expect(memory.schemaVersions.get(id)).toBe(6); + expect(encoded.schemaVersion).toBe(COMPACT_THREAD_CACHE_SCHEMA_VERSION); + expect(memory.schemaVersions.get(id)).toBe(COMPACT_THREAD_CACHE_SCHEMA_VERSION); expect(encoded.snapshot.turnItemsOmitLocalVisible).toBe(true); expect(encoded.snapshot.turnItemCount).toBe(3); expect(encoded.snapshot.visibleTurnItemCount).toBe(4); @@ -512,7 +512,7 @@ describe("mobile SQLite environment cache store", () => { yield* store.saveThread(ENVIRONMENT_ID, snapshot); const raw = memory.values.get(cacheId(ENVIRONMENT_ID, "thread", THREAD_ID))!; const encoded = JSON.parse(raw); - expect(encoded.schemaVersion).toBe(6); + expect(encoded.schemaVersion).toBe(COMPACT_THREAD_CACHE_SCHEMA_VERSION); expect(encoded.snapshot.turnItemsOmitLocalVisible).toBe(false); expect(encoded.snapshot.turnItemCount).toBe(2); expect(encoded.snapshot.projection.turnItems).toHaveLength(2); diff --git a/packages/client-runtime/src/platform/orchestrationCache.ts b/packages/client-runtime/src/platform/orchestrationCache.ts index 3d24e03f113f9..ed9cac492cc8a 100644 --- a/packages/client-runtime/src/platform/orchestrationCache.ts +++ b/packages/client-runtime/src/platform/orchestrationCache.ts @@ -10,8 +10,9 @@ import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; export const ORCHESTRATION_CACHE_SCHEMA_VERSION = 3 as const; -// Older caches may contain human turns that bypassed server history budgets. -export const ORCHESTRATION_THREAD_CACHE_SCHEMA_VERSION = 5 as const; +// Older caches may contain human turns that bypassed server history budgets, or hide the +// delivered queued message of a run that a restart cancelled. +export const ORCHESTRATION_THREAD_CACHE_SCHEMA_VERSION = 7 as const; /** * The server snapshot the cached rows descend from. Written only for rows that have one, so a diff --git a/packages/client-runtime/src/platform/threadCacheEncoding.ts b/packages/client-runtime/src/platform/threadCacheEncoding.ts index 6466763a4de1b..147b76a265437 100644 --- a/packages/client-runtime/src/platform/threadCacheEncoding.ts +++ b/packages/client-runtime/src/platform/threadCacheEncoding.ts @@ -14,7 +14,7 @@ import { } from "./orchestrationCache.ts"; // Keep the full format for web/desktop; older clients discard compact records. -export const COMPACT_THREAD_CACHE_SCHEMA_VERSION = 6 as const; +export const COMPACT_THREAD_CACHE_SCHEMA_VERSION = 8 as const; /** * A thread followed live keeps every item it streams, so its projection can grow diff --git a/packages/client-runtime/src/state/orchestrationV2Projection.ts b/packages/client-runtime/src/state/orchestrationV2Projection.ts index 218c3219ffbd0..d936fa7726df2 100644 --- a/packages/client-runtime/src/state/orchestrationV2Projection.ts +++ b/packages/client-runtime/src/state/orchestrationV2Projection.ts @@ -266,15 +266,11 @@ function upsertVisibleTurnItem( // items never received stay absent. function restoreQueuedUserItems( projection: OrchestrationV2ThreadProjection, - runId?: OrchestrationV2Run["id"], + runId: OrchestrationV2Run["id"], ): OrchestrationV2ThreadProjection["visibleTurnItems"] { let visibleTurnItems = projection.visibleTurnItems; for (const item of projection.turnItems) { - if ( - (runId !== undefined && item.runId !== runId) || - item.type !== "user_message" || - item.inputIntent !== "queued_turn" - ) + if (item.runId !== runId || item.type !== "user_message" || item.inputIntent !== "queued_turn") continue; if (!shouldShowLocalTurnItem(projection, item)) continue; visibleTurnItems = upsertVisibleTurnItem( @@ -287,20 +283,6 @@ function restoreQueuedUserItems( return visibleTurnItems; } -// Older caches can retain delivered queued input hidden by the former visibility rule. -// Request cards retained outside the window must not be pulled into the timeline. -export function restoreCachedProjectionVisibility( - projection: OrchestrationV2ThreadProjection, -): OrchestrationV2ThreadProjection { - const visibleTurnItems = restoreQueuedUserItems({ - ...projection, - visibleTurnItems: activeVisibleTurnItems(projection), - }); - return visibleTurnItems === projection.visibleTurnItems - ? projection - : { ...projection, visibleTurnItems }; -} - export function applyOrchestrationV2ProjectionEvent( projection: OrchestrationV2ThreadProjection | null, event: OrchestrationV2DomainEvent, diff --git a/packages/client-runtime/src/state/threads-sync.test.ts b/packages/client-runtime/src/state/threads-sync.test.ts index 9dc93757b2269..73478830743d2 100644 --- a/packages/client-runtime/src/state/threads-sync.test.ts +++ b/packages/client-runtime/src/state/threads-sync.test.ts @@ -49,7 +49,7 @@ import { decodeOrDiscardOrchestrationCache, } from "../platform/orchestrationCache.ts"; import * as RpcSession from "../rpc/session.ts"; -import { v2MessageRow, v2Now, v2Projection, v2ThreadId } from "./orchestrationV2TestFixtures.ts"; +import { v2Now, v2Projection, v2ThreadId } from "./orchestrationV2TestFixtures.ts"; import { onThreadRequestsResolved, type ThreadRequestsResolved } from "./threadRequests.ts"; import { EMPTY_THREAD_HISTORY_META } from "./threadHistoryMerge.ts"; import * as ThreadHistoryController from "./threadHistoryController.ts"; @@ -423,74 +423,6 @@ const deleted = (sequence = 3): OrchestrationV2ThreadStreamItem => { }; describe("EnvironmentThreads", () => { - it.effect.each(["disk", "retained"] as const)( - "shows a delivered queued message that an older %s cache hid", - (cacheKind) => - Effect.gen(function* () { - // The former rule hid the queued message of a started run that a restart cancelled. - const runId = RunId.make("run-cancelled-after-start"); - const later = v2MessageRow("Later input", 2); - const delivered = { - ...v2MessageRow("Delivered before restart", 1).item, - runId, - inputIntent: "queued_turn", - } as OrchestrationV2TurnItem; - const projection: OrchestrationV2ThreadProjection = { - ...BASE_PROJECTION, - runs: [ - { - id: runId, - threadId: THREAD_ID, - ordinal: 1, - providerInstanceId: BASE_PROJECTION.thread.providerInstanceId, - modelSelection: BASE_PROJECTION.thread.modelSelection, - providerThreadId: null, - userMessageId: MessageId.make("Delivered before restart"), - rootNodeId: null, - activeAttemptId: null, - status: "cancelled", - requestedAt: v2Now, - startedAt: v2Now, - completedAt: v2Now, - checkpointId: null, - contextHandoffId: null, - }, - ], - turnItems: [delivered, later.item], - visibleTurnItems: [later], - }; - const h = yield* makeHarness({ - loadCached: Effect.succeedSome({ - snapshotSequence: CACHED_SNAPSHOT_SEQUENCE, - projection, - }), - ...(cacheKind === "retained" - ? { - resumeCache: { - owner: undefined, - snapshot: { - state: { - ...EMPTY_ENVIRONMENT_THREAD_STATE, - data: Option.some(projection), - status: "live", - }, - sequence: CACHED_SNAPSHOT_SEQUENCE, - persisted: true, - }, - }, - } - : {}), - completionMarker: true, - }); - yield* Queue.offer(h.inputs, synchronized()); - const state = yield* awaitThreadState(h.observed, (value) => value.status === "live"); - expect( - Option.getOrThrow(state.data).visibleTurnItems.map((row) => row.sourceItemId), - ).toEqual([delivered.id, later.sourceItemId]); - expect(yield* Ref.get(h.loaderCalls)).toBe(0); - }), - ); - it.effect.each([ ["disk", false], ["retained", false], @@ -547,7 +479,7 @@ describe("EnvironmentThreads", () => { }), ); - it.effect("discards an oversized version-4 cache and requests a fresh bounded snapshot", () => + it.effect("discards an oversized version-5 cache and requests a fresh bounded snapshot", () => Effect.gen(function* () { const item: OrchestrationV2TurnItem = { id: TurnItemId.make("old-unbounded-cache-item"), @@ -579,7 +511,7 @@ describe("EnvironmentThreads", () => { }); const stale = encoded.replace( `"schemaVersion":${ORCHESTRATION_THREAD_CACHE_SCHEMA_VERSION}`, - '"schemaVersion":4', + '"schemaVersion":5', ); let discarded = false; const h = yield* makeHarness({ diff --git a/packages/client-runtime/src/state/threads.ts b/packages/client-runtime/src/state/threads.ts index 19af253a6398e..c0921417ba5cf 100644 --- a/packages/client-runtime/src/state/threads.ts +++ b/packages/client-runtime/src/state/threads.ts @@ -44,10 +44,7 @@ import { subscriptionRetryDelay, } from "../rpc/client.ts"; import { parseThreadKey, threadKey } from "./entities.ts"; -import { - applyOrchestrationV2ProjectionEvent, - restoreCachedProjectionVisibility, -} from "./orchestrationV2Projection.ts"; +import { applyOrchestrationV2ProjectionEvent } from "./orchestrationV2Projection.ts"; import { THREAD_SNAPSHOT_IDLE_TTL_MS } from "./threadRetention.ts"; import { followStreamInEnvironment } from "./runtime.ts"; import * as ThreadHistoryController from "./threadHistoryController.ts"; @@ -224,7 +221,6 @@ function matchesThreadSnapshot( function cachedThreadState(value: EnvironmentThreadState): EnvironmentThreadState { return { ...value, - data: Option.map(value.data, restoreCachedProjectionVisibility), status: value.status === "deleted" || (value.status === "live" && Option.isSome(value.data)) ? value.status @@ -294,9 +290,7 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make loaded, (snapshot) => !hasMissingPendingQuestionCard(snapshot.projection), ); - const cachedThread = Option.map(cached, (snapshot) => - restoreCachedProjectionVisibility(snapshot.projection), - ); + const cachedThread = Option.map(cached, (snapshot) => snapshot.projection); // Seed the resume cursor from the cached snapshot so a warm cache can catch up // via `afterSequence` instead of re-downloading the full thread body. const initialSequence = From 38ea81ad596625f0a4f7eee33281a775ca350525 Mon Sep 17 00:00:00 2001 From: EtanHey Date: Tue, 24 Nov 2026 03:09:56 +0200 Subject: [PATCH 5/5] revert(client): restore the proven cache-restore fix; the version bump stays a suggestion Co-Authored-By: Claude Opus 5.5 --- .../environment-cache-store.test.ts | 6 +- .../src/platform/orchestrationCache.ts | 5 +- .../src/platform/threadCacheEncoding.ts | 2 +- .../src/state/orchestrationV2Projection.ts | 22 +++++- .../src/state/threads-sync.test.ts | 74 ++++++++++++++++++- packages/client-runtime/src/state/threads.ts | 10 ++- 6 files changed, 105 insertions(+), 14 deletions(-) diff --git a/apps/mobile/src/connection/environment-cache-store.test.ts b/apps/mobile/src/connection/environment-cache-store.test.ts index 3c04fc9069fda..1205c746e9fa1 100644 --- a/apps/mobile/src/connection/environment-cache-store.test.ts +++ b/apps/mobile/src/connection/environment-cache-store.test.ts @@ -463,8 +463,8 @@ describe("mobile SQLite environment cache store", () => { yield* store.saveThread(ENVIRONMENT_ID, snapshot); const id = cacheId(ENVIRONMENT_ID, "thread", THREAD_ID); const encoded = JSON.parse(memory.values.get(id)!); - expect(encoded.schemaVersion).toBe(COMPACT_THREAD_CACHE_SCHEMA_VERSION); - expect(memory.schemaVersions.get(id)).toBe(COMPACT_THREAD_CACHE_SCHEMA_VERSION); + expect(encoded.schemaVersion).toBe(6); + expect(memory.schemaVersions.get(id)).toBe(6); expect(encoded.snapshot.turnItemsOmitLocalVisible).toBe(true); expect(encoded.snapshot.turnItemCount).toBe(3); expect(encoded.snapshot.visibleTurnItemCount).toBe(4); @@ -512,7 +512,7 @@ describe("mobile SQLite environment cache store", () => { yield* store.saveThread(ENVIRONMENT_ID, snapshot); const raw = memory.values.get(cacheId(ENVIRONMENT_ID, "thread", THREAD_ID))!; const encoded = JSON.parse(raw); - expect(encoded.schemaVersion).toBe(COMPACT_THREAD_CACHE_SCHEMA_VERSION); + expect(encoded.schemaVersion).toBe(6); expect(encoded.snapshot.turnItemsOmitLocalVisible).toBe(false); expect(encoded.snapshot.turnItemCount).toBe(2); expect(encoded.snapshot.projection.turnItems).toHaveLength(2); diff --git a/packages/client-runtime/src/platform/orchestrationCache.ts b/packages/client-runtime/src/platform/orchestrationCache.ts index ed9cac492cc8a..3d24e03f113f9 100644 --- a/packages/client-runtime/src/platform/orchestrationCache.ts +++ b/packages/client-runtime/src/platform/orchestrationCache.ts @@ -10,9 +10,8 @@ import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; export const ORCHESTRATION_CACHE_SCHEMA_VERSION = 3 as const; -// Older caches may contain human turns that bypassed server history budgets, or hide the -// delivered queued message of a run that a restart cancelled. -export const ORCHESTRATION_THREAD_CACHE_SCHEMA_VERSION = 7 as const; +// Older caches may contain human turns that bypassed server history budgets. +export const ORCHESTRATION_THREAD_CACHE_SCHEMA_VERSION = 5 as const; /** * The server snapshot the cached rows descend from. Written only for rows that have one, so a diff --git a/packages/client-runtime/src/platform/threadCacheEncoding.ts b/packages/client-runtime/src/platform/threadCacheEncoding.ts index 147b76a265437..6466763a4de1b 100644 --- a/packages/client-runtime/src/platform/threadCacheEncoding.ts +++ b/packages/client-runtime/src/platform/threadCacheEncoding.ts @@ -14,7 +14,7 @@ import { } from "./orchestrationCache.ts"; // Keep the full format for web/desktop; older clients discard compact records. -export const COMPACT_THREAD_CACHE_SCHEMA_VERSION = 8 as const; +export const COMPACT_THREAD_CACHE_SCHEMA_VERSION = 6 as const; /** * A thread followed live keeps every item it streams, so its projection can grow diff --git a/packages/client-runtime/src/state/orchestrationV2Projection.ts b/packages/client-runtime/src/state/orchestrationV2Projection.ts index d936fa7726df2..218c3219ffbd0 100644 --- a/packages/client-runtime/src/state/orchestrationV2Projection.ts +++ b/packages/client-runtime/src/state/orchestrationV2Projection.ts @@ -266,11 +266,15 @@ function upsertVisibleTurnItem( // items never received stay absent. function restoreQueuedUserItems( projection: OrchestrationV2ThreadProjection, - runId: OrchestrationV2Run["id"], + runId?: OrchestrationV2Run["id"], ): OrchestrationV2ThreadProjection["visibleTurnItems"] { let visibleTurnItems = projection.visibleTurnItems; for (const item of projection.turnItems) { - if (item.runId !== runId || item.type !== "user_message" || item.inputIntent !== "queued_turn") + if ( + (runId !== undefined && item.runId !== runId) || + item.type !== "user_message" || + item.inputIntent !== "queued_turn" + ) continue; if (!shouldShowLocalTurnItem(projection, item)) continue; visibleTurnItems = upsertVisibleTurnItem( @@ -283,6 +287,20 @@ function restoreQueuedUserItems( return visibleTurnItems; } +// Older caches can retain delivered queued input hidden by the former visibility rule. +// Request cards retained outside the window must not be pulled into the timeline. +export function restoreCachedProjectionVisibility( + projection: OrchestrationV2ThreadProjection, +): OrchestrationV2ThreadProjection { + const visibleTurnItems = restoreQueuedUserItems({ + ...projection, + visibleTurnItems: activeVisibleTurnItems(projection), + }); + return visibleTurnItems === projection.visibleTurnItems + ? projection + : { ...projection, visibleTurnItems }; +} + export function applyOrchestrationV2ProjectionEvent( projection: OrchestrationV2ThreadProjection | null, event: OrchestrationV2DomainEvent, diff --git a/packages/client-runtime/src/state/threads-sync.test.ts b/packages/client-runtime/src/state/threads-sync.test.ts index 73478830743d2..9dc93757b2269 100644 --- a/packages/client-runtime/src/state/threads-sync.test.ts +++ b/packages/client-runtime/src/state/threads-sync.test.ts @@ -49,7 +49,7 @@ import { decodeOrDiscardOrchestrationCache, } from "../platform/orchestrationCache.ts"; import * as RpcSession from "../rpc/session.ts"; -import { v2Now, v2Projection, v2ThreadId } from "./orchestrationV2TestFixtures.ts"; +import { v2MessageRow, v2Now, v2Projection, v2ThreadId } from "./orchestrationV2TestFixtures.ts"; import { onThreadRequestsResolved, type ThreadRequestsResolved } from "./threadRequests.ts"; import { EMPTY_THREAD_HISTORY_META } from "./threadHistoryMerge.ts"; import * as ThreadHistoryController from "./threadHistoryController.ts"; @@ -423,6 +423,74 @@ const deleted = (sequence = 3): OrchestrationV2ThreadStreamItem => { }; describe("EnvironmentThreads", () => { + it.effect.each(["disk", "retained"] as const)( + "shows a delivered queued message that an older %s cache hid", + (cacheKind) => + Effect.gen(function* () { + // The former rule hid the queued message of a started run that a restart cancelled. + const runId = RunId.make("run-cancelled-after-start"); + const later = v2MessageRow("Later input", 2); + const delivered = { + ...v2MessageRow("Delivered before restart", 1).item, + runId, + inputIntent: "queued_turn", + } as OrchestrationV2TurnItem; + const projection: OrchestrationV2ThreadProjection = { + ...BASE_PROJECTION, + runs: [ + { + id: runId, + threadId: THREAD_ID, + ordinal: 1, + providerInstanceId: BASE_PROJECTION.thread.providerInstanceId, + modelSelection: BASE_PROJECTION.thread.modelSelection, + providerThreadId: null, + userMessageId: MessageId.make("Delivered before restart"), + rootNodeId: null, + activeAttemptId: null, + status: "cancelled", + requestedAt: v2Now, + startedAt: v2Now, + completedAt: v2Now, + checkpointId: null, + contextHandoffId: null, + }, + ], + turnItems: [delivered, later.item], + visibleTurnItems: [later], + }; + const h = yield* makeHarness({ + loadCached: Effect.succeedSome({ + snapshotSequence: CACHED_SNAPSHOT_SEQUENCE, + projection, + }), + ...(cacheKind === "retained" + ? { + resumeCache: { + owner: undefined, + snapshot: { + state: { + ...EMPTY_ENVIRONMENT_THREAD_STATE, + data: Option.some(projection), + status: "live", + }, + sequence: CACHED_SNAPSHOT_SEQUENCE, + persisted: true, + }, + }, + } + : {}), + completionMarker: true, + }); + yield* Queue.offer(h.inputs, synchronized()); + const state = yield* awaitThreadState(h.observed, (value) => value.status === "live"); + expect( + Option.getOrThrow(state.data).visibleTurnItems.map((row) => row.sourceItemId), + ).toEqual([delivered.id, later.sourceItemId]); + expect(yield* Ref.get(h.loaderCalls)).toBe(0); + }), + ); + it.effect.each([ ["disk", false], ["retained", false], @@ -479,7 +547,7 @@ describe("EnvironmentThreads", () => { }), ); - it.effect("discards an oversized version-5 cache and requests a fresh bounded snapshot", () => + it.effect("discards an oversized version-4 cache and requests a fresh bounded snapshot", () => Effect.gen(function* () { const item: OrchestrationV2TurnItem = { id: TurnItemId.make("old-unbounded-cache-item"), @@ -511,7 +579,7 @@ describe("EnvironmentThreads", () => { }); const stale = encoded.replace( `"schemaVersion":${ORCHESTRATION_THREAD_CACHE_SCHEMA_VERSION}`, - '"schemaVersion":5', + '"schemaVersion":4', ); let discarded = false; const h = yield* makeHarness({ diff --git a/packages/client-runtime/src/state/threads.ts b/packages/client-runtime/src/state/threads.ts index c0921417ba5cf..19af253a6398e 100644 --- a/packages/client-runtime/src/state/threads.ts +++ b/packages/client-runtime/src/state/threads.ts @@ -44,7 +44,10 @@ import { subscriptionRetryDelay, } from "../rpc/client.ts"; import { parseThreadKey, threadKey } from "./entities.ts"; -import { applyOrchestrationV2ProjectionEvent } from "./orchestrationV2Projection.ts"; +import { + applyOrchestrationV2ProjectionEvent, + restoreCachedProjectionVisibility, +} from "./orchestrationV2Projection.ts"; import { THREAD_SNAPSHOT_IDLE_TTL_MS } from "./threadRetention.ts"; import { followStreamInEnvironment } from "./runtime.ts"; import * as ThreadHistoryController from "./threadHistoryController.ts"; @@ -221,6 +224,7 @@ function matchesThreadSnapshot( function cachedThreadState(value: EnvironmentThreadState): EnvironmentThreadState { return { ...value, + data: Option.map(value.data, restoreCachedProjectionVisibility), status: value.status === "deleted" || (value.status === "live" && Option.isSome(value.data)) ? value.status @@ -290,7 +294,9 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make loaded, (snapshot) => !hasMissingPendingQuestionCard(snapshot.projection), ); - const cachedThread = Option.map(cached, (snapshot) => snapshot.projection); + const cachedThread = Option.map(cached, (snapshot) => + restoreCachedProjectionVisibility(snapshot.projection), + ); // Seed the resume cursor from the cached snapshot so a warm cache can catch up // via `afterSequence` instead of re-downloading the full thread body. const initialSequence =