Skip to content

Commit 707444c

Browse files
fix(server): a fork made after Edit from here no longer shows the rewound turns
Fork timelines inherited every source run up to the fork's run ordinal, so runs rolled back before the fork was made still appeared in the fork even though the forked agent never received them. A fork now skips source runs that were rolled back before the fork was created (rollback stamps the run's completedAt), in the full projection, the timeline index, the windowed source read and the shell item count. Forks made before the rewind keep the rows they had. AI-assisted; verified with the tests and tools listed above.
1 parent 2e6eca3 commit 707444c

1 file changed

Lines changed: 87 additions & 28 deletions

File tree

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

Lines changed: 87 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -741,6 +741,7 @@ type ProjectionWindow = Omit<
741741
"anchorThreadId"
742742
> & {
743743
readonly suppressLocal?: boolean | undefined;
744+
readonly forkCreatedAt?: DateTime.Utc | undefined;
744745
readonly historyAnchor?: { readonly threadId: ThreadId; readonly itemId: TurnItemId } | undefined;
745746
};
746747

@@ -1071,6 +1072,12 @@ type ShellRunRow = {
10711072
readonly thread_id: string;
10721073
readonly run_id: string;
10731074
readonly ordinal: number;
1075+
readonly rolled_back_at: string | null;
1076+
};
1077+
1078+
type ShellRun = {
1079+
readonly ordinal: number;
1080+
readonly rolledBackAt: DateTime.Utc | null;
10741081
};
10751082

10761083
type SettlementThreadRow = Pick<
@@ -1415,16 +1422,40 @@ function isTurnItemAtOrBeforeRun(input: {
14151422
return ordinal !== undefined && ordinal <= input.sourceRunOrdinal;
14161423
}
14171424

1425+
// Rollback stamps completedAt; a fork made after the rewind never received that run.
1426+
function runRolledBackAt(run: Pick<OrchestrationV2Run, "status" | "completedAt">) {
1427+
return run.status === "rolled_back" ? run.completedAt : null;
1428+
}
1429+
1430+
function isRolledBackBeforeFork(
1431+
rolledBackAt: DateTime.Utc | null,
1432+
forkCreatedAt: DateTime.Utc,
1433+
): boolean {
1434+
return rolledBackAt !== null && DateTime.isLessThan(rolledBackAt, forkCreatedAt);
1435+
}
1436+
1437+
function forkInheritedRunOrdinals(
1438+
runs: ReadonlyArray<OrchestrationV2Run>,
1439+
forkCreatedAt: DateTime.Utc,
1440+
): Map<RunId, number> {
1441+
return new Map(
1442+
runs
1443+
.filter((run) => !isRolledBackBeforeFork(runRolledBackAt(run), forkCreatedAt))
1444+
.map((run) => [run.id, run.ordinal]),
1445+
);
1446+
}
1447+
14181448
function visibleTurnItemsThroughRun(input: {
14191449
readonly sourceProjection: OrchestrationV2ThreadProjection;
14201450
readonly sourceRunId: NonNullable<OrchestrationV2TurnItem["runId"]>;
1451+
readonly forkCreatedAt: DateTime.Utc;
14211452
}): Array<Omit<OrchestrationV2ProjectedTurnItem, "position">> {
14221453
const sourceRun = input.sourceProjection.runs.find((run) => run.id === input.sourceRunId);
14231454
if (sourceRun === undefined) {
14241455
return [];
14251456
}
14261457

1427-
const runOrdinalById = new Map(input.sourceProjection.runs.map((run) => [run.id, run.ordinal]));
1458+
const runOrdinalById = forkInheritedRunOrdinals(input.sourceProjection.runs, input.forkCreatedAt);
14281459
const inheritedPrefix = input.sourceProjection.visibleTurnItems
14291460
.filter(
14301461
(row) => row.item.threadId !== input.sourceProjection.thread.id || row.item.type === "fork",
@@ -1484,6 +1515,7 @@ function buildVisibleTurnItems(input: {
14841515
: visibleTurnItemsThroughRun({
14851516
sourceProjection: input.sourceProjection,
14861517
sourceRunId: forkedFrom.runId,
1518+
forkCreatedAt: input.projection.thread.createdAt,
14871519
});
14881520
const markerItem = makeForkMarkerTurnItem({
14891521
targetProjection: input.projection,
@@ -1832,7 +1864,7 @@ type ShellThreadState = {
18321864
readonly itemCount: number;
18331865
readonly runlessItemCount: number;
18341866
readonly updatedAt: OrchestrationV2ThreadProjection["updatedAt"];
1835-
readonly runOrdinalById: ReadonlyMap<RunId, number>;
1867+
readonly runsById: ReadonlyMap<RunId, ShellRun>;
18361868
readonly itemCountByRunId: ReadonlyMap<RunId, number>;
18371869
};
18381870

@@ -1859,16 +1891,21 @@ function shellStatusFromStoredRunStatus(status: string | null): OrchestrationV2S
18591891
function itemCountThroughRun(input: {
18601892
readonly state: ShellThreadState;
18611893
readonly runId: RunId;
1894+
readonly forkCreatedAt: DateTime.Utc;
18621895
}): number {
1863-
const runOrdinal = input.state.runOrdinalById.get(input.runId);
1896+
const runOrdinal = input.state.runsById.get(input.runId)?.ordinal;
18641897
if (runOrdinal === undefined) {
18651898
return 0;
18661899
}
18671900

18681901
let count = input.state.thread.historyOrigin === "v1_import" ? input.state.runlessItemCount : 0;
18691902
for (const [runId, itemCount] of input.state.itemCountByRunId) {
1870-
const itemRunOrdinal = input.state.runOrdinalById.get(runId);
1871-
if (itemRunOrdinal !== undefined && itemRunOrdinal <= runOrdinal) {
1903+
const itemRun = input.state.runsById.get(runId);
1904+
if (
1905+
itemRun !== undefined &&
1906+
itemRun.ordinal <= runOrdinal &&
1907+
!isRolledBackBeforeFork(itemRun.rolledBackAt, input.forkCreatedAt)
1908+
) {
18721909
count += itemCount;
18731910
}
18741911
}
@@ -1925,7 +1962,11 @@ function visibleItemCountForShell(input: {
19251962

19261963
return (
19271964
inheritedPrefixCount +
1928-
itemCountThroughRun({ state: sourceState, runId: forkedFrom.runId }) +
1965+
itemCountThroughRun({
1966+
state: sourceState,
1967+
runId: forkedFrom.runId,
1968+
forkCreatedAt: state.thread.createdAt,
1969+
}) +
19291970
1 +
19301971
state.itemCount
19311972
);
@@ -3035,12 +3076,23 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
30353076
AND json_extract(source_thread.payload_json, '$.historyOrigin') = 'v1_import'
30363077
)
30373078
)
3038-
OR run.ordinal <= (
3039-
SELECT required_run.ordinal
3040-
FROM orchestration_v2_projection_runs AS required_run
3041-
WHERE required_run.thread_id = item.thread_id
3042-
AND required_run.run_id = ${window.requiredRunId ?? null}
3043-
LIMIT 1
3079+
OR (
3080+
run.ordinal <= (
3081+
SELECT required_run.ordinal
3082+
FROM orchestration_v2_projection_runs AS required_run
3083+
WHERE required_run.thread_id = item.thread_id
3084+
AND required_run.run_id = ${window.requiredRunId ?? null}
3085+
LIMIT 1
3086+
)
3087+
AND NOT COALESCE(
3088+
run.status = 'rolled_back'
3089+
AND julianday(run.completed_at) < julianday(${
3090+
window.forkCreatedAt === undefined
3091+
? null
3092+
: DateTime.formatIso(window.forkCreatedAt)
3093+
}),
3094+
0
3095+
)
30443096
)
30453097
)
30463098
AND NOT (
@@ -4154,6 +4206,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
41544206
userTurnLimit: window.userTurnLimit,
41554207
deferWork: window.deferWork,
41564208
requiredRunId: forkedFrom.runId,
4209+
forkCreatedAt: projection.thread.createdAt,
41574210
suppressLocal: anchor === undefined || anchorIsInDescendant,
41584211
...(anchor === undefined || anchorIsInDescendant
41594212
? {}
@@ -6045,7 +6098,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
60456098
const sourceRun = source.records.runs.find((run) => run.id === fork.runId);
60466099
let inherited: Array<TimelineIndexRow> = [];
60476100
if (sourceRun !== undefined) {
6048-
const ordinals = new Map(source.records.runs.map((run) => [run.id, run.ordinal]));
6101+
const ordinals = forkInheritedRunOrdinals(source.records.runs, records.thread.createdAt);
60496102
const sourceItems = source.local.map((row) => row.item);
60506103
inherited = [
60516104
...source.visible.filter(
@@ -6725,11 +6778,13 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
67256778
const selectShellRunRows = (threadIds?: ReadonlyArray<ThreadId>) =>
67266779
threadIds === undefined
67276780
? sql<ShellRunRow>`
6728-
SELECT thread_id, run_id, ordinal
6781+
SELECT thread_id, run_id, ordinal,
6782+
CASE WHEN status = 'rolled_back' THEN completed_at END AS rolled_back_at
67296783
FROM orchestration_v2_projection_runs
67306784
`
67316785
: sql<ShellRunRow>`
6732-
SELECT thread_id, run_id, ordinal
6786+
SELECT thread_id, run_id, ordinal,
6787+
CASE WHEN status = 'rolled_back' THEN completed_at END AS rolled_back_at
67336788
FROM orchestration_v2_projection_runs
67346789
WHERE thread_id IN (SELECT value FROM json_each(${encodeIdList(threadIds)}))
67356790
`;
@@ -6806,13 +6861,17 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
68066861
readonly runRows: ReadonlyArray<ShellRunRow>;
68076862
readonly itemCountRows: ReadonlyArray<ShellRunItemCountRow>;
68086863
}) => {
6809-
const runOrdinalsByThreadId = new Map<ThreadId, Map<RunId, number>>();
6864+
const runsByThreadId = new Map<ThreadId, Map<RunId, ShellRun>>();
68106865
for (const row of input.runRows) {
68116866
const threadId = ThreadId.make(row.thread_id);
68126867
const runId = RunId.make(row.run_id);
6813-
const existing = runOrdinalsByThreadId.get(threadId) ?? new Map<RunId, number>();
6814-
existing.set(runId, row.ordinal);
6815-
runOrdinalsByThreadId.set(threadId, existing);
6868+
const existing = runsByThreadId.get(threadId) ?? new Map<RunId, ShellRun>();
6869+
existing.set(runId, {
6870+
ordinal: row.ordinal,
6871+
rolledBackAt:
6872+
row.rolled_back_at === null ? null : DateTime.makeUnsafe(row.rolled_back_at),
6873+
});
6874+
runsByThreadId.set(threadId, existing);
68166875
}
68176876
const itemCountsByThreadId = new Map<ThreadId, Map<RunId, number>>();
68186877
for (const row of input.itemCountRows) {
@@ -6822,7 +6881,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
68226881
existing.set(runId, row.item_count);
68236882
itemCountsByThreadId.set(threadId, existing);
68246883
}
6825-
return { runOrdinalsByThreadId, itemCountsByThreadId };
6884+
return { runsByThreadId, itemCountsByThreadId };
68266885
};
68276886

68286887
const shellItemCountMap = (rows: ReadonlyArray<ShellItemCountRow>) =>
@@ -7093,7 +7152,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
70937152
/* Runs once per shell row; the enclosing snapshot or thread read owns the span. */
70947153
Effect.fnUntraced(function* (input: {
70957154
readonly row: ShellThreadRow;
7096-
readonly runOrdinalsByThreadId: ReadonlyMap<ThreadId, Map<RunId, number>>;
7155+
readonly runsByThreadId: ReadonlyMap<ThreadId, Map<RunId, ShellRun>>;
70977156
readonly itemCountsByThreadId: ReadonlyMap<ThreadId, Map<RunId, number>>;
70987157
readonly shellItemCountsByThreadId: ReadonlyMap<
70997158
ThreadId,
@@ -7110,7 +7169,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
71107169
}) {
71117170
const {
71127171
row,
7113-
runOrdinalsByThreadId,
7172+
runsByThreadId,
71147173
itemCountsByThreadId,
71157174
shellItemCountsByThreadId,
71167175
providerThreadsByThreadId,
@@ -7276,7 +7335,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
72767335
itemCount: shellItemCountsByThreadId.get(thread.id)?.itemCount ?? 0,
72777336
runlessItemCount: shellItemCountsByThreadId.get(thread.id)?.runlessItemCount ?? 0,
72787337
updatedAt: thread.updatedAt,
7279-
runOrdinalById: runOrdinalsByThreadId.get(ThreadId.make(row.thread_id)) ?? new Map(),
7338+
runsById: runsByThreadId.get(ThreadId.make(row.thread_id)) ?? new Map(),
72807339
itemCountByRunId: itemCountsByThreadId.get(ThreadId.make(row.thread_id)) ?? new Map(),
72817340
} satisfies ShellThreadState;
72827341
});
@@ -7365,7 +7424,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
73657424
providerThreadRows,
73667425
pendingTurnItemRows,
73677426
}: Effect.Success<ReturnType<typeof readShellSnapshotRows>>) {
7368-
const { runOrdinalsByThreadId, itemCountsByThreadId } = runMapsByThreadId({
7427+
const { runsByThreadId, itemCountsByThreadId } = runMapsByThreadId({
73697428
runRows,
73707429
itemCountRows,
73717430
});
@@ -7375,7 +7434,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
73757434
const states = yield* Effect.forEach(threadRows, (row) =>
73767435
shellThreadStateFromRow({
73777436
row,
7378-
runOrdinalsByThreadId,
7437+
runsByThreadId,
73797438
itemCountsByThreadId,
73807439
shellItemCountsByThreadId,
73817440
providerThreadsByThreadId,
@@ -7481,7 +7540,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
74817540
shellThreadStateFromRow({
74827541
row,
74837542
// Awareness never consumes timeline counts or inherited fork history.
7484-
runOrdinalsByThreadId: new Map(),
7543+
runsByThreadId: new Map(),
74857544
itemCountsByThreadId: new Map(),
74867545
shellItemCountsByThreadId: new Map(),
74877546
providerThreadsByThreadId,
@@ -7772,7 +7831,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
77727831
),
77737832
),
77747833
]);
7775-
const { runOrdinalsByThreadId, itemCountsByThreadId } = runMapsByThreadId({
7834+
const { runsByThreadId, itemCountsByThreadId } = runMapsByThreadId({
77767835
runRows,
77777836
itemCountRows,
77787837
});
@@ -7783,7 +7842,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
77837842
const states = yield* Effect.forEach([...rowsByThreadId.values()], (row) =>
77847843
shellThreadStateFromRow({
77857844
row,
7786-
runOrdinalsByThreadId,
7845+
runsByThreadId,
77877846
itemCountsByThreadId,
77887847
shellItemCountsByThreadId,
77897848
providerThreadsByThreadId,

0 commit comments

Comments
 (0)