Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/freeze-running-turn-when-cancel-cannot-abort.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@truefoundry/trueforge-core': patch
'@truefoundry/trueforge': patch
---

Cancel a session even when the owning executor is gone (restart) or Redis cannot confirm abort. Freeze the running turn in the store so a new turn can start. `freezeAndGetTurn` now takes the cancellation reason (barge-in stays `cancelled-for-next-turn`; explicit cancel stays `client-cancelled`). Redis timeout and transport failures still freeze, with a warning that the cancel is not clean.
23 changes: 18 additions & 5 deletions packages/trueforge-core/src/agent-session/SessionHandle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,14 +90,14 @@ function collectContextAppends(
})();
}

function cancelledTurnDoneEvent(): TurnDoneEvent {
function cancelledTurnDoneEvent(reason: CancellationReason): TurnDoneEvent {
return {
type: EventType.TURN_DONE,
id: newEventId(),
created_at: new Date().toISOString(),
state: {
status: 'cancelled',
reason: CancellationReason.CancelledForNextTurn,
reason,
completed_at: new Date().toISOString(),
},
thread_id: null,
Expand Down Expand Up @@ -179,10 +179,9 @@ export class SessionHandle<
}): Promise<TurnHandle<TTurnCustom>> {
const previousTurnId = resolvePreviousTurnId(input.previous_turn_id, this.session.last_turn_id);
const previous = previousTurnId
? await this.store.freezeAndGetTurn({
session_id: this.session.session_id,
? await this.freezeTurn({
turn_id: previousTurnId,
turn_done_event: cancelledTurnDoneEvent(),
reason: CancellationReason.CancelledForNextTurn,
})
: undefined;

Expand Down Expand Up @@ -309,6 +308,20 @@ export class SessionHandle<
}
}

/**
* Conditionally cancel a running turn in this session and return the
* now-immutable record. Already-terminal turns are returned unchanged.
* Missing turn → {@link TurnNotFoundError}.
*/
async freezeTurn(input: { turn_id: string; reason: CancellationReason }): Promise<TurnRecord<TTurnCustom>> {
return this.store.freezeAndGetTurn({
session_id: this.session.session_id,
turn_id: input.turn_id,
reason: input.reason,
turn_done_event: cancelledTurnDoneEvent(input.reason),
});
}

/** Returns the turn handle (store-backed; not executable), or undefined if not found. */
async getTurn(turn_id: string): Promise<TurnHandle<TTurnCustom> | undefined> {
return TurnHandle.get({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import type { SessionRecord } from '../models/SessionRecord';
import type { TurnRecord } from '../models/TurnRecord';
import type { PersistedTurnEvent, SessionEventItem } from '../schemas/events';
import type { TokenPagination } from '../schemas/pagination';
import type { TerminalTurnState } from '../schemas/turn';
import type { CancellationReason, TerminalTurnState } from '../schemas/turn';

/**
* Caller-supplied fields for creating a session; the store owns timestamps and tip state.
Expand Down Expand Up @@ -107,6 +107,8 @@ export interface CreateTurnInput<TTurnCustom extends object = Record<string, nev
export interface FreezeAndGetTurnInput {
session_id: string;
turn_id: string;
/** Written onto the turn row when the freeze actually cancels a running turn. */
reason: CancellationReason;
/** Caller-built cancelled turn.done event; store persists atomically with state flip when it cancels. */
turn_done_event: PersistedTurnEvent;
}
Expand Down Expand Up @@ -279,11 +281,10 @@ export interface ISessionStore<
createTurn(input: CreateTurnInput<TTurnCustom>): Promise<void>;

/**
* One tx: (a) conditionally cancel a running turn with
* {@link CancellationReason.CancelledForNextTurn}; (b) if it did cancel,
* insert the caller-built `turn_done_event` — already-terminal turns skip the
* event insert; (c) return the now-immutable turn record. Missing turn →
* {@link TurnNotFoundError}.
* One tx: (a) conditionally cancel a running turn with `reason`; (b) if it
* did cancel, insert the caller-built `turn_done_event` — already-terminal
* turns skip the event insert; (c) return the now-immutable turn record.
* Missing turn → {@link TurnNotFoundError}.
*/
freezeAndGetTurn(input: FreezeAndGetTurnInput): Promise<TurnRecord<TTurnCustom>>;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import type { SessionRecord } from '../models/SessionRecord';
import type { TurnRecord, TurnSnapshot } from '../models/TurnRecord';
import type { PersistedTurnEvent, SessionEventItem } from '../schemas/events';
import type { TokenPagination } from '../schemas/pagination';
import { CancellationReason, type TerminalTurnState } from '../schemas/turn';
import type { TerminalTurnState } from '../schemas/turn';
import { assertCreateTurnThreadDelta } from './assertCreateTurnThreadDelta';
import type {
AddThreadsInput,
Expand Down Expand Up @@ -346,7 +346,7 @@ export class InMemorySessionStore<
if (turn.state.status === 'running') {
const cancelledState: TerminalTurnState = {
status: 'cancelled',
reason: CancellationReason.CancelledForNextTurn,
reason: input.reason,
completed_at: new Date().toISOString(),
};
turn.state = cancelledState;
Expand Down
30 changes: 30 additions & 0 deletions packages/trueforge-core/tests/agent-session/sessions.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { EventType } from '../../src/agent-session/schemas/events';
import { CancellationReason } from '../../src/agent-session/schemas/turn';
import { Sessions } from '../../src/agent-session/Sessions';
import { InMemorySessionStore } from '../../src/agent-session/store/InMemorySessionStore';
import { TurnNotFoundError } from '../../src/agent-session/store/SessionStoreErrors';
import { TurnHandle } from '../../src/agent-session/TurnHandle';
import { makeAgentSpec, makeTestResolver, mintTestTurnId } from './testHelpers';

Expand Down Expand Up @@ -98,6 +100,34 @@ describe('Sessions / SessionHandle / TurnHandle (storage + createTurn)', () => {
expect(getSession).not.toHaveBeenCalled();
});

it('freezeTurn cancels a running turn with the given reason', async () => {
const store = new InMemorySessionStore();
const sessions = new Sessions({ sessionStore: store });
const session = await sessions.create({
tenant_id: tenant,
session_id: 's1',
created_by: 'user-1',
agent: { type: 'inline', spec: makeAgentSpec() },
});
const turn = await session.createTurn({
turn_id: mintTestTurnId(),
previous_turn_id: 'none',
signal: new AbortController().signal,
resolver: makeTestResolver(),
});
const frozen = await session.freezeTurn({
turn_id: turn.id,
reason: CancellationReason.ClientCancelled,
});
expect(frozen.state).toMatchObject({
status: 'cancelled',
reason: CancellationReason.ClientCancelled,
});
await expect(
session.freezeTurn({ turn_id: 'missing-turn', reason: CancellationReason.ClientCancelled }),
).rejects.toBeInstanceOf(TurnNotFoundError);
});

it('custom value vs merge-fn', async () => {
const store = new InMemorySessionStore<{ tag: string }, { n: number }>();
const sessions = new Sessions({ sessionStore: store });
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
() =>
store.freezeAndGetTurn({
...keys,
reason: CancellationReason.ClientCancelled,
turn_done_event: makeTurnDoneEvent(makeCancelledTurnState(CancellationReason.ClientCancelled)),
}),
() =>
Expand Down Expand Up @@ -1220,9 +1221,11 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
const record = await store.freezeAndGetTurn({
session_id: sessionId,
turn_id: 'turn-1',
reason: CancellationReason.CancelledForNextTurn,
turn_done_event: makeTurnDoneEvent(cancelledState),
});
expect(record.state.status).toBe('cancelled');
expect(record.state).toMatchObject({ reason: CancellationReason.CancelledForNextTurn });
const { data } = await store.listTurnEvents({
session_id: sessionId,
turn_id: 'turn-1',
Expand Down Expand Up @@ -1297,6 +1300,23 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
}
});

it('cancels a running turn with the caller-supplied reason', async () => {
const store = createStore();
await seedSession(store);
await store.createTurn(makeCreateTurnInput({ sessionId, turnId: 'turn-1' }));
const cancelledState = makeCancelledTurnState(CancellationReason.ClientCancelled);
const record = await store.freezeAndGetTurn({
session_id: sessionId,
turn_id: 'turn-1',
reason: CancellationReason.ClientCancelled,
turn_done_event: makeTurnDoneEvent(cancelledState),
});
expect(record.state).toMatchObject({
status: 'cancelled',
reason: CancellationReason.ClientCancelled,
});
});

it('on an already-terminal turn is a plain read without duplicating turn.done', async () => {
const store = createStore();
await seedSession(store);
Expand All @@ -1306,6 +1326,7 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
await store.freezeAndGetTurn({
session_id: sessionId,
turn_id: 'turn-1',
reason: CancellationReason.CancelledForNextTurn,
turn_done_event: makeTurnDoneEvent(doneState),
});
const { data } = await store.listTurnEvents({
Expand All @@ -1327,11 +1348,13 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
store.freezeAndGetTurn({
session_id: sessionId,
turn_id: 'turn-1',
reason: CancellationReason.CancelledForNextTurn,
turn_done_event: makeTurnDoneEvent(cancelledState),
}),
store.freezeAndGetTurn({
session_id: sessionId,
turn_id: 'turn-1',
reason: CancellationReason.CancelledForNextTurn,
turn_done_event: makeTurnDoneEvent(cancelledState),
}),
]);
Expand All @@ -1358,6 +1381,7 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {
store.freezeAndGetTurn({
session_id: sessionId,
turn_id: 'turn-1',
reason: CancellationReason.CancelledForNextTurn,
turn_done_event: makeTurnDoneEvent(cancelledState),
}),
store.updateTurnState({
Expand Down
Loading
Loading