Skip to content

Commit 7adb470

Browse files
committed
fix(threads): keep imported positions compatible with official updates [skip ci]
1 parent 90b5d7d commit 7adb470

5 files changed

Lines changed: 13 additions & 122 deletions

File tree

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

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,6 @@ const encodeEventIds = Schema.encodeSync(Schema.fromJsonString(Schema.Array(Sche
7474
export interface EventSinkV2Shape {
7575
readonly write: (input: {
7676
/** Idempotent ingestion of source records whose event IDs are deterministic. */
77-
readonly chronological?: boolean;
7877
readonly expectedThread?: OrchestrationV2AppThread;
7978
readonly skipExistingEventIds?: boolean;
8079
/** Return no events if another thread owns this native session at commit time. */
@@ -87,7 +86,6 @@ export interface EventSinkV2Shape {
8786
readonly events: ReadonlyArray<OrchestrationV2DomainEvent>;
8887
}) => Effect.Effect<ReadonlyArray<OrchestrationV2StoredEvent>, EventSinkV2Error>;
8988
readonly writeWithEffects: (input: {
90-
readonly chronological?: boolean;
9189
readonly expectedThread?: OrchestrationV2AppThread;
9290
readonly skipExistingEventIds?: boolean;
9391
/**
@@ -343,7 +341,6 @@ const layerBase: Layer.Layer<
343341

344342
const normalizeEvents = Effect.fnUntraced(function* (
345343
events: ReadonlyArray<OrchestrationV2DomainEvent>,
346-
chronological = false,
347344
) {
348345
const runOrdinals = new Map(
349346
events.flatMap((event) =>
@@ -360,7 +357,6 @@ const layerBase: Layer.Layer<
360357
.normalize(
361358
event.payload,
362359
event.payload.runId === null ? undefined : runOrdinals.get(event.payload.runId),
363-
chronological,
364360
)
365361
.pipe(Effect.map((payload) => ({ ...event, payload })))
366362
: Effect.succeed(event),
@@ -474,7 +470,6 @@ const layerBase: Layer.Layer<
474470
input.guardPendingUserInputCancellations === true
475471
? yield* guardUserInputCancellations(events)
476472
: events,
477-
input.chronological,
478473
);
479474
const committed = yield* eventStore.append({
480475
...(input.commandId === undefined ? {} : { commandId: input.commandId }),
Lines changed: 0 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import { assert, it } from "@effect/vitest";
22
import { RunId, ThreadId, TurnItemId } from "@t3tools/contracts";
33
import * as Effect from "effect/Effect";
4-
import * as DateTime from "effect/DateTime";
54
import * as Layer from "effect/Layer";
65
import * as SqlClient from "effect/sql/SqlClient";
76

@@ -57,61 +56,3 @@ it.effect("reuses an item's position without attempting another allocation inser
5756
);
5857
}).pipe(Effect.provide(layerTest)),
5958
);
60-
61-
it.effect("orders external history before live messages and upgrades legacy positions", () =>
62-
Effect.gen(function* () {
63-
const positions = yield* TurnItemPositionStore.TurnItemPositionStoreV2;
64-
const threadId = ThreadId.make("external-history");
65-
const input = { threadId, runId: null, turnItemId: TurnItemId.make("recent") };
66-
const legacy = yield* positions.allocate(input);
67-
assert.equal(legacy, 1);
68-
const recentAt = DateTime.makeUnsafe("2026-11-02T12:00:00Z");
69-
const recent = yield* positions.allocate({
70-
...input,
71-
chronological: true,
72-
sourceTimestamp: recentAt,
73-
});
74-
const old = yield* positions.allocate({
75-
...input,
76-
turnItemId: TurnItemId.make("history"),
77-
chronological: true,
78-
sourceTimestamp: DateTime.makeUnsafe("2026-11-01T12:00:00Z"),
79-
});
80-
const simultaneous = yield* positions.allocate({
81-
...input,
82-
turnItemId: TurnItemId.make("tool"),
83-
chronological: true,
84-
sourceTimestamp: recentAt,
85-
});
86-
assert.isBelow(old, recent);
87-
assert.isAbove(simultaneous, recent);
88-
const managed = {
89-
...input,
90-
turnItemId: TurnItemId.make("managed"),
91-
runId: RunId.make("managed-run"),
92-
runOrdinal: 1,
93-
};
94-
const beforeRepair = yield* positions.allocate(managed);
95-
assert.isBelow(beforeRepair, old);
96-
const afterRepair = yield* positions.allocate({
97-
...managed,
98-
sourceTimestamp: DateTime.makeUnsafe("2026-11-02T14:00:00Z"),
99-
});
100-
assert.isAbove(afterRepair, simultaneous);
101-
assert.equal(
102-
yield* positions.allocate({
103-
...managed,
104-
sourceTimestamp: DateTime.makeUnsafe("2026-11-02T15:00:00Z"),
105-
}),
106-
afterRepair,
107-
);
108-
assert.equal(
109-
yield* positions.allocate({
110-
...input,
111-
chronological: true,
112-
sourceTimestamp: DateTime.makeUnsafe("2026-11-02T13:00:00Z"),
113-
}),
114-
recent,
115-
);
116-
}).pipe(Effect.provide(layerTest)),
117-
);

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

Lines changed: 9 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import { OrchestrationV2TurnItem, RunId, ThreadId, TurnItemId } from "@t3tools/contracts";
22
import * as Context from "effect/Context";
33
import * as Effect from "effect/Effect";
4-
import * as DateTime from "effect/DateTime";
54
import * as Layer from "effect/Layer";
65
import * as Schema from "effect/Schema";
76
import * as SqlClient from "effect/sql/SqlClient";
@@ -16,21 +15,17 @@ export class TurnItemPositionStoreError extends Schema.TaggedError<TurnItemPosit
1615
) {}
1716

1817
const isTurnItemPositionStoreError = Schema.is(TurnItemPositionStoreError);
19-
const CHRONOLOGICAL_POSITION_MIN = 100_000_000_000_000;
2018

2119
export interface TurnItemPositionStoreV2Shape {
2220
readonly allocate: (input: {
2321
readonly threadId: ThreadId;
2422
readonly turnItemId: TurnItemId;
2523
readonly runId: RunId | null;
2624
readonly runOrdinal?: number;
27-
readonly sourceTimestamp?: DateTime.Utc;
28-
readonly chronological?: boolean;
2925
}) => Effect.Effect<number, TurnItemPositionStoreError>;
3026
readonly normalize: (
3127
item: OrchestrationV2TurnItem,
3228
runOrdinal?: number,
33-
chronological?: boolean,
3429
) => Effect.Effect<OrchestrationV2TurnItem, TurnItemPositionStoreError>;
3530
}
3631

@@ -47,55 +42,14 @@ export const layer: Layer.Layer<TurnItemPositionStoreV2, never, SqlClient.SqlCli
4742
const allocate: TurnItemPositionStoreV2Shape["allocate"] =
4843
/* This helper runs for individual orchestration events; the enclosing operation owns the span. */
4944
Effect.fnUntraced(
50-
function* ({
51-
threadId,
52-
turnItemId,
53-
runId,
54-
runOrdinal: suppliedRunOrdinal,
55-
sourceTimestamp,
56-
chronological = false,
57-
}) {
58-
const existing = yield* sql<{ ordinal: number | null; chronological: number }>`
59-
SELECT (SELECT ordinal FROM orchestration_v2_turn_item_positions
60-
WHERE thread_id = ${threadId} AND turn_item_id = ${turnItemId} LIMIT 1) AS ordinal,
61-
EXISTS (SELECT 1 FROM orchestration_v2_turn_item_positions
62-
WHERE thread_id = ${threadId} AND ordinal >= ${CHRONOLOGICAL_POSITION_MIN}) AS chronological
63-
`;
64-
if (
65-
sourceTimestamp !== undefined &&
66-
(chronological || existing[0]?.chronological === 1)
67-
) {
68-
// Reserve a millisecond bucket for source-ordered imports. Existing native
69-
// positions remain stable; legacy arrival-order imports are upgraded once.
70-
const base = 1_000_000 + DateTime.toEpochMillis(sourceTimestamp) * 1000;
71-
if (!Number.isSafeInteger(base) || base < 1_000_000)
72-
return yield* new TurnItemPositionStoreError({
73-
threadId,
74-
turnItemId,
75-
cause: "Invalid source timestamp",
76-
});
77-
if (existing[0]?.ordinal != null && existing[0].ordinal >= CHRONOLOGICAL_POSITION_MIN)
78-
return existing[0].ordinal;
79-
const rows = yield* sql<{ ordinal: number }>`
80-
SELECT COALESCE(MAX(ordinal), ${base - 1}) + 1 AS ordinal
81-
FROM orchestration_v2_turn_item_positions
82-
WHERE thread_id = ${threadId} AND ordinal >= ${base} AND ordinal < ${base + 1000}
83-
`;
84-
const ordinal = rows[0]!.ordinal;
85-
if (ordinal >= base + 1000)
86-
return yield* new TurnItemPositionStoreError({
87-
threadId,
88-
turnItemId,
89-
cause: "Source timestamp position bucket exhausted",
90-
});
91-
yield* sql`
92-
INSERT INTO orchestration_v2_turn_item_positions (thread_id, turn_item_id, ordinal)
93-
VALUES (${threadId}, ${turnItemId}, ${ordinal})
94-
ON CONFLICT(thread_id, turn_item_id) DO UPDATE SET ordinal = excluded.ordinal
95-
`;
96-
return ordinal;
97-
}
98-
if (existing[0]?.ordinal != null) return existing[0].ordinal;
45+
function* ({ threadId, turnItemId, runId, runOrdinal: suppliedRunOrdinal }) {
46+
const existing = yield* sql<{ readonly ordinal: number }>`
47+
SELECT ordinal
48+
FROM orchestration_v2_turn_item_positions
49+
WHERE thread_id = ${threadId} AND turn_item_id = ${turnItemId}
50+
LIMIT 1
51+
`;
52+
if (existing[0] !== undefined) return existing[0].ordinal;
9953

10054
const runRows =
10155
runId === null
@@ -150,14 +104,12 @@ export const layer: Layer.Layer<TurnItemPositionStoreV2, never, SqlClient.SqlCli
150104
return TurnItemPositionStoreV2.of({
151105
allocate,
152106
// Per-event normalization shares the enclosing orchestration span.
153-
normalize: Effect.fnUntraced(function* (item, runOrdinal, chronological) {
107+
normalize: Effect.fnUntraced(function* (item, runOrdinal) {
154108
return yield* allocate({
155109
threadId: item.threadId,
156110
turnItemId: item.id,
157111
runId: item.runId,
158112
...(runOrdinal === undefined ? {} : { runOrdinal }),
159-
sourceTimestamp: item.startedAt ?? item.updatedAt,
160-
chronological: chronological ?? false,
161113
}).pipe(Effect.map((ordinal) => (item.ordinal === ordinal ? item : { ...item, ordinal })));
162114
}),
163115
});

‎apps/server/src/project/ClaudeSessionAttachment.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -464,7 +464,6 @@ const make = Effect.gen(function* () {
464464
}
465465
for (let i = 0; i < events.length; i += 100)
466466
yield* sink.write({
467-
chronological: true,
468467
skipExistingEventIds: true,
469468
events: events.slice(i, i + 100),
470469
});

‎apps/server/src/project/ClaudeSessionHandoff.test.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -194,6 +194,10 @@ it.effect.each(["wait", "interrupt"] as const)(
194194
yield* service.change({ action: "handoff", threadId: attached.threadId, interrupt }),
195195
).toEqual({ threadId: attached.threadId, attached: false, readOnly: false });
196196
expect(interruptions).toBe(interrupt ? 1 : 0);
197+
const imported = yield* sql<{ ordinal: number }>`SELECT ordinal
198+
FROM orchestration_v2_projection_turn_items WHERE thread_id = ${attached.threadId}
199+
ORDER BY ordinal`;
200+
expect(imported.map((item) => item.ordinal)).toEqual([1, 2]);
197201
const after = yield* projections.getThread(attached.threadId);
198202
expect(after.worktreePath).toBe("/work/later");
199203
// Deployed histories retain these former fields; the current codec strips them without a migration.

0 commit comments

Comments
 (0)