Skip to content

Commit 7a49fc9

Browse files
committed
fix(effect): address provider and worker review findings
1 parent b5ff7b9 commit 7a49fc9

16 files changed

Lines changed: 284 additions & 30 deletions

File tree

‎apps/server/src/orchestration/Layers/CheckpointReactor.ts‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@ import * as Effect from "effect/Effect";
1717
import * as Layer from "effect/Layer";
1818
import * as Option from "effect/Option";
1919
import type * as PlatformError from "effect/PlatformError";
20-
import * as Schema from "effect/Schema";
2120
import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
2221
import { isTemporaryWorktreeBranch } from "@t3tools/shared/git";
2322

@@ -27,7 +26,7 @@ import {
2726
resolveThreadWorkspaceCwd,
2827
} from "../../checkpointing/Utils.ts";
2928
import * as CheckpointStore from "../../checkpointing/CheckpointStore.ts";
30-
import { PersistenceSqlError } from "../../persistence/Errors.ts";
29+
import { isPersistenceSqlError } from "../../persistence/Errors.ts";
3130
import { ProviderService } from "../../provider/Services/ProviderService.ts";
3231
import { CheckpointReactor, type CheckpointReactorShape } from "../Services/CheckpointReactor.ts";
3332
import { forkParkedStream } from "../../serverActivation.ts";
@@ -42,7 +41,6 @@ import * as WorkspaceEntries from "../../workspace/WorkspaceEntries.ts";
4241

4342
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
4443
const PERSISTENCE_RETRY_COUNT = 2;
45-
const isPersistenceSqlError = Schema.is(PersistenceSqlError);
4644

4745
type ReactorInput =
4846
| {

‎apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3027,6 +3027,7 @@ describe("ProviderCommandReactor", () => {
30273027
);
30283028

30293029
await waitFor(() => harness.stopSession.mock.calls.length === 1);
3030+
await harness.drain();
30303031
const readModel = await harness.readModel();
30313032
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
30323033
expect(thread?.session).not.toBeNull();

‎apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts‎

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2207,6 +2207,70 @@ describe("ProviderRuntimeIngestion", () => {
22072207
});
22082208
});
22092209

2210+
it("caps buffered assistant text while repeated spill writes fail", async () => {
2211+
const harness = await createHarness({
2212+
dispatchFailure: {
2213+
commandType: "thread.message.assistant.delta",
2214+
count: 9,
2215+
},
2216+
});
2217+
const now = "2026-01-01T00:00:00.000Z";
2218+
const turnId = asTurnId("turn-buffer-bounded");
2219+
const itemId = asItemId("item-buffer-bounded");
2220+
2221+
harness.emit({
2222+
type: "turn.started",
2223+
eventId: asEventId("evt-turn-started-buffer-bounded"),
2224+
provider: ProviderDriverKind.make("codex"),
2225+
createdAt: now,
2226+
threadId: asThreadId("thread-1"),
2227+
turnId,
2228+
});
2229+
await harness.drain();
2230+
2231+
for (const [index, character] of ["a", "b", "c"].entries()) {
2232+
harness.emit({
2233+
type: "content.delta",
2234+
eventId: asEventId(`evt-message-delta-buffer-bounded-${index}`),
2235+
provider: ProviderDriverKind.make("codex"),
2236+
createdAt: now,
2237+
threadId: asThreadId("thread-1"),
2238+
turnId,
2239+
itemId,
2240+
payload: {
2241+
streamKind: "assistant_text",
2242+
delta: character.repeat(30_000),
2243+
},
2244+
});
2245+
await harness.drain();
2246+
}
2247+
2248+
expect(harness.remainingDispatchFailures).toBe(0);
2249+
2250+
harness.emit({
2251+
type: "item.completed",
2252+
eventId: asEventId("evt-message-completed-buffer-bounded"),
2253+
provider: ProviderDriverKind.make("codex"),
2254+
createdAt: now,
2255+
threadId: asThreadId("thread-1"),
2256+
turnId,
2257+
itemId,
2258+
payload: {
2259+
itemType: "assistant_message",
2260+
status: "completed",
2261+
},
2262+
});
2263+
await harness.drain();
2264+
2265+
const thread = (await harness.readModel()).threads.find(
2266+
(entry) => entry.id === asThreadId("thread-1"),
2267+
);
2268+
const message = thread?.messages.find((entry) => entry.id === "assistant:item-buffer-bounded");
2269+
2270+
expect(message?.text).toBe("a".repeat(24_000));
2271+
expect(message?.streaming).toBe(false);
2272+
});
2273+
22102274
it("flushes and completes buffered assistant text when an approval request opens", async () => {
22112275
const harness = await createHarness();
22122276
const now = "2026-01-01T00:00:00.000Z";

‎apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts‎

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -26,13 +26,12 @@ import * as Duration from "effect/Duration";
2626
import * as Effect from "effect/Effect";
2727
import * as Layer from "effect/Layer";
2828
import * as Option from "effect/Option";
29-
import * as Schema from "effect/Schema";
3029
import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
3130

3231
import { ProviderService } from "../../provider/Services/ProviderService.ts";
3332
import { ProjectionTurnRepository } from "../../persistence/Services/ProjectionTurns.ts";
3433
import { ProjectionTurnRepositoryLive } from "../../persistence/Layers/ProjectionTurns.ts";
35-
import { PersistenceSqlError } from "../../persistence/Errors.ts";
34+
import { isPersistenceSqlError } from "../../persistence/Errors.ts";
3635
import { isGitRepository } from "../../git/Utils.ts";
3736
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
3837
import { ThreadBackgroundLivenessService } from "../ThreadBackgroundLiveness.ts";
@@ -102,7 +101,6 @@ const TASK_DESCRIPTION_BY_TASK_TTL = Duration.minutes(120);
102101
const MAX_BUFFERED_ASSISTANT_CHARS = 24_000;
103102
const PERSISTENCE_RETRY_COUNT = 2;
104103
const STRICT_PROVIDER_LIFECYCLE_GUARD = process.env.T3CODE_STRICT_PROVIDER_LIFECYCLE_GUARD !== "0";
105-
const isPersistenceSqlError = Schema.is(PersistenceSqlError);
106104

107105
type TurnStartRequestedDomainEvent = Extract<
108106
OrchestrationEvent,
@@ -1094,7 +1092,11 @@ const make = Effect.gen(function* () {
10941092
onNone: () => delta,
10951093
onSome: (text) => `${text}${delta}`,
10961094
});
1097-
yield* Cache.set(bufferedAssistantTextByMessageId, messageId, nextText);
1095+
const retainedText =
1096+
nextText.length > MAX_BUFFERED_ASSISTANT_CHARS
1097+
? nextText.slice(0, MAX_BUFFERED_ASSISTANT_CHARS)
1098+
: nextText;
1099+
yield* Cache.set(bufferedAssistantTextByMessageId, messageId, retainedText);
10981100
return nextText.length <= MAX_BUFFERED_ASSISTANT_CHARS ? "" : nextText;
10991101
}),
11001102
),
@@ -1688,7 +1690,19 @@ const make = Effect.gen(function* () {
16881690
delta: spillChunk,
16891691
...(turnId ? { turnId } : {}),
16901692
createdAt: now,
1691-
});
1693+
}).pipe(
1694+
Effect.tapError((cause) =>
1695+
Effect.logWarning(
1696+
"assistant text exceeded its buffer during a persistence failure",
1697+
{
1698+
messageId: assistantMessageId,
1699+
retainedCharacters: MAX_BUFFERED_ASSISTANT_CHARS,
1700+
droppedCharacters: spillChunk.length - MAX_BUFFERED_ASSISTANT_CHARS,
1701+
cause,
1702+
},
1703+
),
1704+
),
1705+
);
16921706
yield* clearBufferedAssistantText(assistantMessageId);
16931707
}
16941708
} else {

‎apps/server/src/persistence/Errors.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ export class PersistenceDecodeError extends Schema.TaggedErrorClass<PersistenceD
6969
return `Decode error in ${this.operation}: ${this.issue}`;
7070
}
7171
}
72-
const isPersistenceSqlError = Schema.is(PersistenceSqlError);
72+
export const isPersistenceSqlError = Schema.is(PersistenceSqlError);
7373
const isPersistenceDecodeError = Schema.is(PersistenceDecodeError);
7474

7575
// Kept for orchestration/projection call sites, which are being revamped separately.

‎packages/contracts/src/baseSchemas.test.ts‎

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -18,14 +18,22 @@ describe("ValidIsoDateTime", () => {
1818
"2026-08-22T14:00:00Z",
1919
"2026-08-22T14:00:00+02:00",
2020
"2026-08-22T14:00:00-07:00",
21+
"2024-02-29T12:00:00Z",
2122
])("accepts the timestamp %s", (value) => {
2223
expect(decodeValidIsoDateTime(value)).toBe(value);
2324
});
2425

25-
it.each(["", "not a date", "today", "2026-08-22", "2026-13-22T14:00:00Z"])(
26-
"rejects the invalid timestamp %s",
27-
(value) => {
28-
expect(() => decodeValidIsoDateTime(value)).toThrow();
29-
},
30-
);
26+
it.each([
27+
"",
28+
"not a date",
29+
"today",
30+
"2026-08-22",
31+
"2026-13-22T14:00:00Z",
32+
"2026-02-29T00:00:00Z",
33+
"2026-02-30T00:00:00Z",
34+
"2026-04-31T00:00:00Z",
35+
"2026-01-01T24:00:00Z",
36+
])("rejects the invalid timestamp %s", (value) => {
37+
expect(() => decodeValidIsoDateTime(value)).toThrow();
38+
});
3139
});

‎packages/contracts/src/baseSchemas.ts‎

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,9 +27,21 @@ const ISO_DATE_TIME_PATTERN =
2727

2828
export const ValidIsoDateTime = IsoDateTime.check(
2929
Schema.isPattern(ISO_DATE_TIME_PATTERN),
30-
Schema.makeFilter((value) => Option.isSome(DateTime.make(value)), {
31-
expected: "a valid ISO 8601 date and time",
32-
}),
30+
Schema.makeFilter(
31+
(value) => {
32+
const parsed = DateTime.make(value);
33+
if (Option.isNone(parsed) || Number(value.slice(11, 13)) > 23) {
34+
return false;
35+
}
36+
37+
const date = value.slice(0, 10);
38+
const parsedDate = DateTime.make(`${date}T00:00:00.000Z`);
39+
return Option.isSome(parsedDate) && DateTime.formatIsoDateUtc(parsedDate.value) === date;
40+
},
41+
{
42+
expected: "a valid ISO 8601 date and time",
43+
},
44+
),
3345
);
3446
export type ValidIsoDateTime = typeof ValidIsoDateTime.Type;
3547

‎packages/effect-acp/src/errors.test.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,16 @@ describe("effect-acp errors", () => {
6868
expect(error.cause).toBe(cause);
6969
});
7070

71+
it("represents an ended transport without inventing an underlying cause", () => {
72+
const error = new AcpError.AcpTransportError({
73+
operation: "write-output-stream",
74+
detail: "ACP output stream ended.",
75+
});
76+
77+
expect(error.message).toBe("ACP transport operation write-output-stream failed.");
78+
expect(error.cause).toBeUndefined();
79+
});
80+
7181
it("preserves structured extension handler failures behind stable request errors", () => {
7282
const cause = new AcpError.AcpTransportError({
7383
operation: "read-input-stream",

‎packages/effect-acp/src/errors.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -170,7 +170,7 @@ export class AcpTransportError extends Schema.TaggedErrorClass<AcpTransportError
170170
method: Schema.optional(Schema.String),
171171
detail: Schema.optional(Schema.String),
172172
pid: Schema.optionalKey(Schema.Int),
173-
cause: Schema.Defect(),
173+
cause: Schema.optional(Schema.Defect()),
174174
},
175175
) {
176176
override get message() {

‎packages/effect-acp/src/protocol.test.ts‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -727,6 +727,57 @@ it.layer(NodeServices.layer)("effect-acp protocol", (it) => {
727727
}),
728728
);
729729

730+
it.effect("does not deliver notifications after the output writer terminates the protocol", () =>
731+
Effect.gen(function* () {
732+
const { stdio, input } = yield* makeInMemoryStdio();
733+
const cause = PlatformError.systemError({
734+
_tag: "Unknown",
735+
module: "Stdio",
736+
method: "write",
737+
cause: new Error("broken output pipe"),
738+
});
739+
const termination = yield* Deferred.make<AcpError.AcpError>();
740+
const lateMessageRead = yield* Deferred.make<void>();
741+
const notificationCount = yield* Ref.make(0);
742+
const transport = yield* AcpProtocol.makeAcpPatchedProtocol({
743+
stdio: Stdio.make({
744+
args: stdio.args,
745+
stdin: stdio.stdin,
746+
stdout: () => Sink.forEach((_chunk: string | Uint8Array) => Effect.fail(cause)),
747+
stderr: stdio.stderr,
748+
}),
749+
serverRequestMethods: new Set(),
750+
logIncoming: true,
751+
logger: (event) =>
752+
event.stage === "decoded" &&
753+
Array.isArray(event.payload) &&
754+
event.payload.some((message) => message.tag === "x/barrier")
755+
? Deferred.succeed(lateMessageRead, undefined).pipe(Effect.asVoid)
756+
: Effect.void,
757+
onNotification: () => Ref.update(notificationCount, (count) => count + 1),
758+
onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid),
759+
});
760+
761+
yield* transport.notify("x/trigger", {});
762+
yield* Deferred.await(termination);
763+
yield* Queue.offer(
764+
input,
765+
encoder.encode(
766+
`${encodeUnknownJsonString({ jsonrpc: "2.0", method: "x/late", params: 1 })}\n`,
767+
),
768+
);
769+
yield* Queue.offer(
770+
input,
771+
encoder.encode(
772+
`${encodeUnknownJsonString({ jsonrpc: "2.0", method: "x/barrier", params: 2 })}\n`,
773+
),
774+
);
775+
yield* Deferred.await(lateMessageRead);
776+
777+
assert.equal(yield* Ref.get(notificationCount), 0);
778+
}),
779+
);
780+
730781
it.effect("keeps only the latest handled notifications for the raw stream", () =>
731782
Effect.gen(function* () {
732783
const { stdio, input } = yield* makeInMemoryStdio();

0 commit comments

Comments
 (0)