Skip to content

Commit 6002728

Browse files
Corey Bainesclaude
authored andcommitted
fix(server): settled and idle-released threads no longer stay Waiting
After settling or archiving a Claude thread, or after its provider session was released for being idle, the thread could keep showing "Waiting on a background task". The Claude CLI was gone, but the background-task roster it had saved on its provider threads stayed until someone pressed Stop. Startup recovery cleared rosters; a normal release did not. Release now clears them in one place, `releaseEntry`: - As soon as the session leaves the live map, it records the task ids on the released session's provider threads, including the thread whose detach caused the release (detach removes it from the attached set first). - After the process closes, it removes only those ids. The write commits through a new compare-and-set, `EventSink.writeIfProviderThreadUnchanged`, which compares the whole stored row so an update that does not move `updatedAt` is not overwritten. Conflicts are retried. Tasks a same-id replacement session reported in the meantime survive. - Server shutdown keeps rosters; startup recovery already handles them. Runtimes opt in with `backgroundTasksEndWithProcess`. Claude sets it: its shells, agents, and monitors end with the CLI. No other Pathway adapter writes a roster today (Codex, Cursor, Grok, ACP, OpenCode), so they keep the old behavior; OpenCode in particular should not opt in, since its subagents run on a shared server and can outlive a session. Ported from pingdotgg/t3code#19355. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
1 parent 3862e72 commit 6002728

7 files changed

Lines changed: 452 additions & 5 deletions

File tree

‎apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5600,6 +5600,8 @@ export function makeClaudeAdapterV2(
56005600
providerSessionId: input.providerSessionId,
56015601
providerSession: session,
56025602
events: Stream.fromEffectRepeat(Queue.take(events)),
5603+
// Background shells, agents, monitors, and workflows end with the CLI.
5604+
backgroundTasksEndWithProcess: true,
56035605
hasPendingBackgroundWork: Effect.gen(function* () {
56045606
// Session capability: any native thread with pending work pins idle.
56055607
for (const roster of (yield* Ref.get(pendingBackgroundTasksByNativeThread)).values()) {

‎apps/server/src/orchestration-v2/EventSink.ts‎

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import {
22
CommandId,
33
type OrchestrationV2Run,
44
OrchestrationV2DomainEvent,
5+
type OrchestrationV2ProviderThread,
56
OrchestrationV2StoredEvent,
67
ProviderThreadId,
78
RunAttemptId,
@@ -31,6 +32,7 @@ import {
3132
} from "./EffectOutbox.ts";
3233
import { EventStoreV2 } from "./EventStore.ts";
3334
import {
35+
encodeProviderThreadPayload,
3436
ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION,
3537
ProjectionStoreV2,
3638
} from "./ProjectionStore.ts";
@@ -148,6 +150,22 @@ export interface EventSinkV2Shape {
148150
},
149151
EventSinkV2Error
150152
>;
153+
/**
154+
* Atomically commit only while the stored provider thread still equals
155+
* `expected`, the row its writer read, so a read-modify-write of the row
156+
* cannot overwrite an update published in between. The whole row is
157+
* compared because not every writer moves `updatedAt`.
158+
*/
159+
readonly writeIfProviderThreadUnchanged: (input: {
160+
readonly expected: OrchestrationV2ProviderThread;
161+
readonly events: ReadonlyArray<OrchestrationV2DomainEvent>;
162+
}) => Effect.Effect<
163+
{
164+
readonly committed: boolean;
165+
readonly storedEvents: ReadonlyArray<OrchestrationV2StoredEvent>;
166+
},
167+
EventSinkV2Error
168+
>;
151169
readonly commitCommand: (
152170
input: EventSinkCommitCommandInput,
153171
) => Effect.Effect<EventSinkCommitCommandResult, EventSinkV2Error>;
@@ -434,6 +452,43 @@ const baseLayer: Layer.Layer<
434452
return result;
435453
});
436454

455+
const writeIfProviderThreadUnchangedEffect = Effect.fn(
456+
"orchestrationV2.EventSink.writeIfProviderThreadUnchanged",
457+
)(function* (input: Parameters<EventSinkV2Shape["writeIfProviderThreadUnchanged"]>[0]) {
458+
yield* Effect.annotateCurrentSpan({
459+
"orchestration_v2.event_count": input.events.length,
460+
"orchestration_v2.provider_thread_id": input.expected.id,
461+
});
462+
const expectedJson = yield* encodeProviderThreadPayload(input.expected);
463+
464+
const result = yield* sql.withTransaction(
465+
Effect.gen(function* () {
466+
const rows = yield* sql<{ readonly payload_json: string }>`
467+
SELECT payload_json
468+
FROM orchestration_v2_projection_provider_threads
469+
WHERE provider_thread_id = ${input.expected.id}
470+
LIMIT 1
471+
`;
472+
if (rows[0]?.payload_json !== expectedJson) {
473+
return {
474+
committed: false as const,
475+
storedEvents: [] as ReadonlyArray<OrchestrationV2StoredEvent>,
476+
};
477+
}
478+
479+
const normalized = yield* normalizeEvents(input.events);
480+
const storedEvents = yield* eventStore.append({ events: normalized });
481+
yield* applyStoredEvents(storedEvents);
482+
return { committed: true as const, storedEvents };
483+
}),
484+
);
485+
if (result.committed) {
486+
yield* eventStore.publishCommitted(result.storedEvents);
487+
yield* PubSub.publishAll(liveEvents, result.storedEvents);
488+
}
489+
return result;
490+
});
491+
437492
const existingCommandResult = (commandId: CommandId) =>
438493
Effect.gen(function* () {
439494
const existing = yield* commandReceipts.getByCommandId(commandId);
@@ -680,6 +735,12 @@ const baseLayer: Layer.Layer<
680735
}),
681736
),
682737
),
738+
writeIfProviderThreadUnchanged: (input) =>
739+
writeIfProviderThreadUnchangedEffect(input).pipe(
740+
Effect.mapError(
741+
(cause) => new EventSinkWriteError({ eventCount: input.events.length, cause }),
742+
),
743+
),
683744
commitCommand: (input) =>
684745
commitCommandEffect(input).pipe(
685746
Effect.flatMap((result) =>

‎apps/server/src/orchestration-v2/ProjectionStore.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -691,7 +691,8 @@ const encodeSubagentPayload = Schema.encodeEffect(
691691
const encodeProviderSessionPayload = Schema.encodeEffect(
692692
Schema.fromJsonString(OrchestrationV2ProviderSessionJsonSchema),
693693
);
694-
const encodeProviderThreadPayload = Schema.encodeEffect(
694+
/** Encodes a provider thread exactly as its projection row stores `payload_json`. */
695+
export const encodeProviderThreadPayload = Schema.encodeEffect(
695696
Schema.fromJsonString(OrchestrationV2ProviderThreadJsonSchema),
696697
);
697698
const encodeProviderTurnPayload = Schema.encodeEffect(

‎apps/server/src/orchestration-v2/ProviderAdapter.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -510,6 +510,14 @@ export interface ProviderAdapterV2SessionRuntime {
510510
readonly hasPendingBackgroundWorkForThread?: (
511511
providerThread: OrchestrationV2ProviderThread,
512512
) => Effect.Effect<boolean>;
513+
/**
514+
* Set when every background task this session lists on its provider threads
515+
* runs inside the session's own process and ends when it closes. The session
516+
* manager then clears those tasks when it releases the session. Leave unset
517+
* when a task can outlive the session, for example on a shared server, so
518+
* its thread keeps showing Waiting.
519+
*/
520+
readonly backgroundTasksEndWithProcess?: true;
513521
readonly ensureThread: (
514522
input: ProviderAdapterV2EnsureThreadInput,
515523
) => Effect.Effect<OrchestrationV2ProviderThread, ProviderAdapterV2Error>;

0 commit comments

Comments
 (0)