diff --git a/.changeset/session-stop-request.md b/.changeset/session-stop-request.md new file mode 100644 index 0000000000..31207af9b7 --- /dev/null +++ b/.changeset/session-stop-request.md @@ -0,0 +1,6 @@ +--- +"@flow-state-dev/core": minor +"@flow-state-dev/engine": minor +--- + +A block can stop another request running in its own session with `ctx.session.stopRequest(requestId)`. It records the same stop as the abort route, reaches a request in another process on its next heartbeat, and answers `"stopped"`, `"already-finished"` or `"not-in-this-session"` (FIX-1690). Anything that implements `SessionScopeHandle` itself must add the method. diff --git a/apps/docs/docs/fundamentals/flows.md b/apps/docs/docs/fundamentals/flows.md index 3054252f60..dd6a6c9dc3 100644 --- a/apps/docs/docs/fundamentals/flows.md +++ b/apps/docs/docs/fundamentals/flows.md @@ -247,6 +247,15 @@ When an action executes: 4. The root block executes asynchronously 5. Lifecycle hooks fire on completion or error +A block can also stop another request running in its own session, the way the abort route does from outside. It's how an action that takes a message can make room for it: + +```ts +const outcome = await ctx.session.stopRequest(requestId); +// "stopped" | "already-finished" | "not-in-this-session" +``` + +The stop is recorded on the request, so it reaches a request running in another process on that process's next heartbeat, exactly like an abort. `"not-in-this-session"` is the answer for any id outside the session, including one that doesn't exist, so the call can't be used to learn about other sessions' requests. + See [Actions](/docs/fundamentals/actions) for the full picture. ### Entries only the flow can reach diff --git a/docs/architecture/execution-and-errors.md b/docs/architecture/execution-and-errors.md index b9cff96bd5..25e1669d94 100644 --- a/docs/architecture/execution-and-errors.md +++ b/docs/architecture/execution-and-errors.md @@ -186,7 +186,7 @@ pipeline Background `.sideChain()` tasks are decoupled from the request's transport-level abort signal (FIX-663). Each request has three `AbortController`s: - `registered`: the abort-registry controller, tagged with the incarnation of the request the run executes as. It fires on an explicit cancellation only, never on a transport signal. Three paths reach it: - - the `/abort` endpoint, when the request is running in this process. The fire is fenced on the incarnation it cancelled, so it does not reach a later request under the same id; + - the `/abort` endpoint, or a block's `ctx.session.stopRequest(id)` for a request in its own session (FIX-1690), when the request is running in this process. Both go through one write, `recordRequestStop` (`execution/record-request-stop.ts`); the route admits the caller by owner and tenant, the session hook by `requestInSessionScope`. The fire is fenced on the incarnation it cancelled, so it does not reach a later request under the same id; - the run's own reads of the request store: once as it starts, then on each heartbeat tick, when the intent was recorded by another process (FIX-1026). Both reads are fenced the same way; - an unfenced fire (host shutdown, the CLI stopping its turn), which stops whatever runs under the id. diff --git a/labs/app-lab/test/shell.test.tsx b/labs/app-lab/test/shell.test.tsx index 2b1fdb8d5b..9538b7cd68 100644 --- a/labs/app-lab/test/shell.test.tsx +++ b/labs/app-lab/test/shell.test.tsx @@ -127,7 +127,9 @@ describe("the composer (V6)", () => { expect(input.value).toBe("kept line"); release(); await screen.findByText("kept line", { selector: "[data-testid=transcript-line-body]" }); - expect(input.value).toBe(""); + // The live stream can draw the kept line before the post's next status poll + // answers, and only that answer clears the draft: wait for it, don't race it. + await waitFor(() => expect(input.value).toBe("")); // And the channel holds it. const state = await clients.sessions.getSessionState("ops.side", { includeItems: true, itemTypes: ["component"] }); expect(JSON.stringify(state.items)).toContain("kept line"); diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 08a3121d98..4b05cdaa75 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -16,6 +16,7 @@ export type { OrgScopeHandle, RequestScopeHandle, SessionScopeHandle, + StopRequestOutcome, UserScopeHandle, } from "./types/scope"; export type { ScopeStateOps } from "./types/state"; diff --git a/packages/core/src/types/index.ts b/packages/core/src/types/index.ts index 8665b53a88..2f32543545 100644 --- a/packages/core/src/types/index.ts +++ b/packages/core/src/types/index.ts @@ -308,6 +308,7 @@ export type { SessionMetadata, SessionMetadataInput, SessionScopeHandle, + StopRequestOutcome, UserScopeHandle } from "./scope"; diff --git a/packages/core/src/types/scope.ts b/packages/core/src/types/scope.ts index 0d0e98cc3d..d903cdaab5 100644 --- a/packages/core/src/types/scope.ts +++ b/packages/core/src/types/scope.ts @@ -175,6 +175,19 @@ export type SessionMetadataInput = SessionMetadata & { metadata?: Record; }; +/** + * What {@link SessionScopeHandle.stopRequest} came to. + * + * - `"stopped"`: the stop is recorded on the request. A request running in this + * process has its signal fired now; one running in another process is + * stopped on that process's next heartbeat, as an abort is. + * - `"already-finished"`: the request had already ended; nothing was written. + * - `"not-in-this-session"`: no request under that id belongs to this session + * (another session's, another tenant's, or none at all). Nothing was written, + * and the answer does not say which. + */ +export type StopRequestOutcome = "stopped" | "already-finished" | "not-in-this-session"; + /** * Session scope handle — exposes per-session state and metadata. Resources * have been lifted to the flat `ctx.resources` registry (FIX-435); a @@ -191,6 +204,14 @@ export type SessionScopeHandle< appendJournal(entry: JournalEntryInput): Promise; getJournal(options?: { limit?: number; offset?: number }): Promise; setMetadata(input: SessionMetadataInput): Promise; + /** + * Stop another request running in this session, by its id. + * + * The same stop the abort route records for a client, reached from a block: + * the request ends `aborted`. Only a request of this session can be stopped; + * any other id answers `"not-in-this-session"`. + */ + stopRequest(requestId: string): Promise; } & ScopeStateOps; export type UserScopeHandle< diff --git a/packages/engine/src/context/createExecutionContext.ts b/packages/engine/src/context/createExecutionContext.ts index 2bc3db1cbb..debc4590d9 100644 --- a/packages/engine/src/context/createExecutionContext.ts +++ b/packages/engine/src/context/createExecutionContext.ts @@ -16,6 +16,7 @@ import type { SessionItemViews, SessionMetadataInput, SessionScopeHandle, + StopRequestOutcome, UserScopeHandle, TokenCounter } from "@flow-state-dev/core/types"; @@ -114,7 +115,8 @@ import { type RequestPrincipal } from "./request-principal"; import { refuseInstancePin } from "./instance-pin"; -import { sessionRequestScope } from "./session-request-scope"; +import { requestInSessionScope, sessionRequestScope } from "./session-request-scope"; +import { recordRequestStop } from "../execution/record-request-stop"; import { ownerKeyMaySeed } from "../resources/owner-private"; import { outputItemToSessionItem, @@ -2665,6 +2667,28 @@ export async function createExecutionContext< ...(input.metadata !== undefined ? { metadata: input.metadata } : {}) }); }, + stopRequest: async (targetId: string): Promise => { + const target = await stores.request.get(targetId); + // Only a request this session's own reads would show; anything else + // gets the answer an unknown id gets, so the reply says nothing about + // another session's requests. + if ( + target === undefined || + !requestInSessionScope( + target, + sessionRequestScope(sessionId, sessionRef.current, options.tenantId) + ) + ) { + return "not-in-this-session"; + } + // The abort route's own write (`recordRequestStop`), not a copy of it. + const stop = await recordRequestStop(stores.request, target); + // Gone between the read and the write: answered like an unknown id, + // as the abort route answers it 404. + if (stop.kind === "gone") return "not-in-this-session"; + if (stop.kind === "finished") return "already-finished"; + return "stopped"; + }, ...sessionOpsEmitting }, () => sessionContainer.read() diff --git a/packages/engine/src/context/session-request-scope.ts b/packages/engine/src/context/session-request-scope.ts index 87e8ecb265..2d5a83351e 100644 --- a/packages/engine/src/context/session-request-scope.ts +++ b/packages/engine/src/context/session-request-scope.ts @@ -6,7 +6,8 @@ * run in the session hands its model (`createExecutionContext`). One definition, so a request a * session's reads leave out can never reach a model through the history load. */ -import type { SessionRecord } from "../stores/types"; +import { matchesOrgFilter, matchesTenantFilter } from "../stores/scope-keys"; +import type { RequestRecord, SessionRecord } from "../stores/types"; /** * The request filter for what a session shows, in its snapshot and its @@ -58,3 +59,25 @@ export function sessionRequestScope( ...(session.flowId != null ? { flowId: session.flowId } : {}) }; } + +/** + * Whether `record` is a request {@link sessionRequestScope} selects: the one + * filter, applied to a single record read by id. Every key is matched exactly, + * as the store filters match a present key. + * + * @param record The stored request. + * @param scope The session's scope, from {@link sessionRequestScope}. + */ +export function requestInSessionScope( + record: Pick, + scope: ReturnType +): boolean { + return ( + record.sessionId === scope.sessionId && + matchesTenantFilter(scope, record.tenantId) && + record.userId === scope.userId && + matchesOrgFilter(scope, record.orgId) && + record.flowKind === scope.flowKind && + (scope.flowId === undefined || record.flowId === scope.flowId) + ); +} diff --git a/packages/engine/src/execution/record-request-stop.ts b/packages/engine/src/execution/record-request-stop.ts new file mode 100644 index 0000000000..6f40483f00 --- /dev/null +++ b/packages/engine/src/execution/record-request-stop.ts @@ -0,0 +1,64 @@ +/** + * The one write that stops a running request: the abort route's, shared with + * a block's `ctx.session.stopRequest`. + * + * Both callers check first that the caller may reach the request (the route by + * owner and tenant, the session hook by session scope), then hand the record + * they checked here. Neither re-implements the incarnation fence or the + * terminal check: a second copy is how one of them would learn to overwrite a + * finished request. + */ +import { resolveRequestIncarnation } from "../stores/scope-keys"; +import type { RequestRecord, RequestStatus, RequestStore } from "../stores/types"; +import { abortRequest } from "./abort-registry"; + +/** + * What recording a stop came to. + * + * - `gone`: the checked request no longer holds its id (deleted, or the id was + * taken by another request since the check). Nothing was written. + * - `finished`: the request had reached a terminal `status`. Nothing was written. + * - `fired`: the stop is recorded and the request's controller in this process + * was fired. + * - `recorded`: the stop is recorded; the process running the request picks it + * up on its next heartbeat. + */ +export type RequestStopResult = + | { kind: "gone" } + | { kind: "finished"; status: RequestStatus } + | { kind: "fired" } + | { kind: "recorded" }; + +/** + * Record a stop on `record`, the request the caller already checked, and fire + * its controller when it runs in this process. + * + * @param requests The request store the record was read from. + * @param record The record the caller's access check admitted. + */ +export async function recordRequestStop( + requests: RequestStore, + record: Pick +): Promise { + // The request the caller's check read. Everything below acts on it and on + // nothing else that later takes the id. + const incarnation = resolveRequestIncarnation(record); + + // Atomic and fenced: written only while still `in_progress`, and only to + // this incarnation, so a finished or re-taken id is never written. + const result = await requests.setFieldsIfStatus( + record.id, + { abortRequested: true }, + ["in_progress"], + Date.now(), + incarnation + ); + + if (result.status === undefined) return { kind: "gone" }; + if (!result.applied) return { kind: "finished", status: result.status }; + + // Fire the in-memory controller if the checked request runs in this + // process. A controller of a later request under the id is not it; that + // request never received the intent, so it is left running. + return abortRequest(record.id, incarnation) ? { kind: "fired" } : { kind: "recorded" }; +} diff --git a/packages/engine/src/routes/abort-routes.ts b/packages/engine/src/routes/abort-routes.ts index 45c707fa8f..29a55f2199 100644 --- a/packages/engine/src/routes/abort-routes.ts +++ b/packages/engine/src/routes/abort-routes.ts @@ -2,9 +2,8 @@ * Abort route handler for cancelling in-flight requests. */ import type { StoreRegistry } from "../stores/types"; -import { resolveRequestIncarnation } from "../stores/scope-keys"; import type { ResolvedPrincipal } from "../transports/types"; -import { abortRequest } from "../execution/abort-registry"; +import { recordRequestStop } from "../execution/record-request-stop"; import { callerReachesRequest, jsonResponse, unknownRequestResponse } from "./route-utils"; import type { ParsedFlowRoute } from "./parseFlowRoute"; @@ -46,41 +45,17 @@ export async function handleAbortRequest( return unknownRequestResponse(requestId); } - // The request the owner check above read. Everything below acts on it and - // on nothing else that later takes the id. - const incarnation = resolveRequestIncarnation(record); - - // One atomic step: record the intent only while the request is still - // running. A read-then-write cannot express this — the worker can commit a - // terminal status between the two, and writing afterwards would restore an - // `in_progress` record over a finished one. Fenced to the checked request by - // its incarnation: if the id was deleted and taken by someone else since, - // the write misses and the caller gets the unused-id answer; if the owner's - // own retry handed the record off, the incarnation held and the write lands. - const result = await ctx.stores.request.setFieldsIfStatus( - requestId, - { abortRequested: true }, - ["in_progress"], - Date.now(), - incarnation - ); - - if (result.status === undefined) { - return unknownRequestResponse(requestId); - } - - if (!result.applied) { - return jsonResponse(409, { - error: `Request "${requestId}" is already in terminal state "${result.status}"` - }); - } - - // Fire the in-memory controller if the checked request runs in this - // process. A controller of a later request under the id is not it; that - // request never received the intent, so it is left running. - if (abortRequest(requestId, incarnation)) { - return new Response(null, { status: 204 }); + const stop = await recordRequestStop(ctx.stores.request, record); + switch (stop.kind) { + case "gone": + return unknownRequestResponse(requestId); + case "finished": + return jsonResponse(409, { + error: `Request "${requestId}" is already in terminal state "${stop.status}"` + }); + case "fired": + return new Response(null, { status: 204 }); + case "recorded": + return new Response(null, { status: 202 }); } - - return new Response(null, { status: 202 }); } diff --git a/packages/engine/test/abort.test.ts b/packages/engine/test/abort.test.ts index 790da7aa6e..70e836ac0f 100644 --- a/packages/engine/test/abort.test.ts +++ b/packages/engine/test/abort.test.ts @@ -1,7 +1,7 @@ -import { defineFlow, handler, sequencer } from "@flow-state-dev/core"; +import { defineFlow, handler, sequencer, type StopRequestOutcome } from "@flow-state-dev/core"; import { DEFAULT_ORG_ID } from "@flow-state-dev/core"; import { z } from "zod"; -import { afterEach, describe, expect, it, beforeEach } from "vitest"; +import { afterEach, describe, expect, it, beforeEach, vi } from "vitest"; import { continueRequest, createInMemoryStores, @@ -991,6 +991,8 @@ function makeBlockingFlow(options: { kind: string; heartbeatIntervalMs?: number; selfCompleteAfterMs?: number; + /** Add a `stop` action that stops another request through `ctx.session.stopRequest`. */ + withStop?: boolean; }) { return defineFlow({ kind: options.kind, @@ -1026,7 +1028,22 @@ function makeBlockingFlow(options: { }); }) }) - } + }, + ...(options.withStop === true + ? { + stop: { + inputSchema: z.object({ requestId: z.string() }), + block: handler({ + name: "stops-another", + inputSchema: z.object({ requestId: z.string() }), + outputSchema: z.object({ outcome: z.string() }), + execute: async (input, ctx) => ({ + outcome: await ctx.session.stopRequest(input.requestId) + }) + }) + } + } + : {}) } })(); } @@ -3739,3 +3756,215 @@ describe("a run's abort controller carries the incarnation it executes as", () = ); }); }); + +// --------------------------------------------------------------------------- +// A block stopping another request in its own session (`ctx.session.stopRequest`) +// +// The same stop the abort route records, reached from code: the target reads +// `aborted` and its signal fires, here or (through the heartbeat) in another +// process. A request outside the caller's session is refused the way the +// route refuses an unreachable one: no write, and an answer that does not +// tell it apart from an unknown id. +// --------------------------------------------------------------------------- + +/** A blocking `run` that completes on its own after 1.5 s, and a `stop`. */ +function makeStoppableFlow(kind: string) { + return makeBlockingFlow({ kind, heartbeatIntervalMs: 20, selfCompleteAfterMs: 1_500, withStop: true }); +} + +describe("ctx.session.stopRequest — a block stops a request in its own session", () => { + type Run = typeof runAction; + + async function startTarget( + run: Run, + stores: StoreRegistry, + flow: ReturnType, + requestId: string, + where: { sessionId: string; tenantId?: string; userId?: string } + ) { + const promise = run({ + orgId: DEFAULT_ORG_ID, + flow, + actionName: "run", + input: {}, + requestId, + userId: where.userId ?? "u_stop", + sessionId: where.sessionId, + ...(where.tenantId !== undefined ? { tenantId: where.tenantId } : {}), + stores, + runtimeConfig: {} + }); + // Running before the stop is sent. + for (let i = 0; i < 50; i += 1) { + if ((await stores.request.get(requestId))?.status === "in_progress") break; + await new Promise((r) => setTimeout(r, 10)); + } + expect((await stores.request.get(requestId))?.status).toBe("in_progress"); + // Boxed, so awaiting the start does not also await the run. + return { done: promise }; + } + + async function stopFrom( + run: Run, + stores: StoreRegistry, + flow: ReturnType, + targetId: string, + where: { sessionId: string; tenantId?: string; userId?: string; requestId: string } + ): Promise { + const result = await run({ + orgId: DEFAULT_ORG_ID, + flow, + actionName: "stop", + input: { requestId: targetId }, + requestId: where.requestId, + userId: where.userId ?? "u_stop", + sessionId: where.sessionId, + ...(where.tenantId !== undefined ? { tenantId: where.tenantId } : {}), + stores, + runtimeConfig: {} + }); + expect(result.error).toBeUndefined(); + return (result.output as { outcome: StopRequestOutcome }).outcome; + } + + it("stops a running request in the same session, in this process", async () => { + const stores = createInMemoryStores(); + const flow = makeStoppableFlow("stop-hook-local"); + const target = await startTarget(runAction, stores, flow, "req_stop_target", { + sessionId: "sess_stop" + }); + + const outcome = await stopFrom(runAction, stores, flow, "req_stop_target", { + sessionId: "sess_stop", + requestId: "req_stop_caller" + }); + expect(outcome).toBe("stopped"); + + const result = await target.done; + expect(result.error).toBeUndefined(); + expect(result.output).not.toBe("completed naturally"); + const record = await stores.request.get("req_stop_target"); + expect(record?.status).toBe("aborted"); + expect(record?.abortRequested).toBe(true); + }); + + it("reaches a request running in another process through its heartbeat", async () => { + const stores = createInMemoryStores(); + const flow = makeStoppableFlow("stop-hook-xproc"); + const target = await startTarget(runAction, stores, flow, "req_stop_xproc", { + sessionId: "sess_stop_xproc" + }); + + // A fresh copy of the engine is a second process: its abort registry has + // never seen the target's controller, so only the stored intent and the + // target's own heartbeat can stop it. + vi.resetModules(); + const other = (await import("../src")) as { runAction: Run }; + const otherRegistry = await import("../src/execution/abort-registry"); + expect(other.runAction).not.toBe(runAction); + // Precondition: the target's controller is visible here and not there. + expect(hasActiveAbortController("req_stop_xproc")).toBe(true); + expect(otherRegistry.hasActiveAbortController("req_stop_xproc")).toBe(false); + + const outcome = await stopFrom(other.runAction, stores, flow, "req_stop_xproc", { + sessionId: "sess_stop_xproc", + requestId: "req_stop_xproc_caller" + }); + expect(outcome).toBe("stopped"); + + await target.done; + const record = await stores.request.get("req_stop_xproc"); + expect(record?.status).toBe("aborted"); + }); + + it("refuses a running request of another session, and leaves it running", async () => { + const stores = createInMemoryStores(); + const flow = makeStoppableFlow("stop-hook-other-session"); + const target = await startTarget(runAction, stores, flow, "req_stop_other", { + sessionId: "sess_a" + }); + + const outcome = await stopFrom(runAction, stores, flow, "req_stop_other", { + sessionId: "sess_b", + requestId: "req_stop_other_caller" + }); + expect(outcome).toBe("not-in-this-session"); + const after = await stores.request.get("req_stop_other"); + expect(after?.abortRequested).not.toBe(true); + + expect((await target.done).output).toBe("completed naturally"); + expect((await stores.request.get("req_stop_other"))?.status).toBe("completed"); + }); + + it("refuses a running request of another tenant under the same session id", async () => { + const stores = createInMemoryStores(); + const flow = makeStoppableFlow("stop-hook-other-tenant"); + const target = await startTarget(runAction, stores, flow, "req_stop_tenant", { + sessionId: "sess_shared", + tenantId: "tenant_a" + }); + + const outcome = await stopFrom(runAction, stores, flow, "req_stop_tenant", { + sessionId: "sess_shared", + tenantId: "tenant_b", + requestId: "req_stop_tenant_caller" + }); + expect(outcome).toBe("not-in-this-session"); + expect((await stores.request.get("req_stop_tenant"))?.abortRequested).not.toBe(true); + + expect((await target.done).output).toBe("completed naturally"); + }); + + it("answers an unknown id as not in this session", async () => { + const stores = createInMemoryStores(); + const flow = makeStoppableFlow("stop-hook-unknown"); + const outcome = await stopFrom(runAction, stores, flow, "req_never_was", { + sessionId: "sess_unknown", + requestId: "req_unknown_caller" + }); + expect(outcome).toBe("not-in-this-session"); + }); + + it("stops the calling request itself when it names its own id", async () => { + // Not refused: the caller asked to stop a request in its own session, and + // its own is one. Pinned so the behaviour does not change by accident. + const stores = createInMemoryStores(); + const flow = makeStoppableFlow("stop-hook-self"); + const result = await runAction({ + orgId: DEFAULT_ORG_ID, + flow, + actionName: "stop", + input: { requestId: "req_stop_self" }, + requestId: "req_stop_self", + userId: "u_stop", + sessionId: "sess_self", + stores, + runtimeConfig: {} + }); + expect(result.output).toBeUndefined(); + const record = await stores.request.get("req_stop_self"); + expect(record?.status).toBe("aborted"); + expect(record?.abortRequested).toBe(true); + }); + + it("reports a finished request as already finished, and writes nothing", async () => { + const stores = createInMemoryStores(); + const flow = makeStoppableFlow("stop-hook-finished"); + const target = await startTarget(runAction, stores, flow, "req_stop_done", { + sessionId: "sess_done" + }); + await target.done; + const finished = await stores.request.get("req_stop_done"); + expect(finished?.status).toBe("completed"); + + const outcome = await stopFrom(runAction, stores, flow, "req_stop_done", { + sessionId: "sess_done", + requestId: "req_stop_done_caller" + }); + expect(outcome).toBe("already-finished"); + const after = await stores.request.get("req_stop_done"); + expect(after?.status).toBe("completed"); + expect(after?.abortRequested).not.toBe(true); + expect(after?.version).toBe(finished?.version); + }); +}); diff --git a/packages/engine/test/session-request-scope-parity.test.ts b/packages/engine/test/session-request-scope-parity.test.ts new file mode 100644 index 0000000000..a4901745ba --- /dev/null +++ b/packages/engine/test/session-request-scope-parity.test.ts @@ -0,0 +1,100 @@ +/** + * `requestInSessionScope` and the stores agree on which requests a session + * holds. + * + * The stop hook fences on `requestInSessionScope`, a predicate over one + * record. A session's own reads fence on the same `sessionRequestScope` + * filter, evaluated by each store. Two evaluations of one filter can drift: a + * key the stores honour and the predicate skips is a hole in the stop hook's + * fence. So every key gets a record that differs on it alone, and the + * predicate must answer what each store's listing answers. + */ +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { DEFAULT_ORG_ID } from "@flow-state-dev/core"; +import { afterAll, describe, expect, it } from "vitest"; +import { createFilesystemStores, createInMemoryStores } from "../src"; +import { + requestInSessionScope, + sessionRequestScope, +} from "../src/context/session-request-scope"; +import type { RequestRecord, StoreRegistry } from "../src/stores/types"; + +const SESSION = "sess_parity"; +const TENANT = "tenant_a"; + +/** The session the scope is built from: a bound instance, and a legacy one. */ +const SESSIONS = { + bound: { userId: "alice", orgId: DEFAULT_ORG_ID, flowKind: "chat", flowId: "chat-1" }, + legacy: { userId: "alice", orgId: DEFAULT_ORG_ID, flowKind: "chat" }, +} as const; + +/** One record per key, each differing from a matching one on that key alone. */ +const VARIANTS: Record & { tenantId?: string }> = { + matching: {}, + "other session": { sessionId: "sess_other" }, + "other tenant": { tenantId: "tenant_b" }, + "no tenant": { tenantId: undefined }, + "other owner": { userId: "bob" }, + "other org": { orgId: "org_other" }, + "other flow kind": { flowKind: "support" }, + "other flow instance": { flowId: "chat-2" }, + "no flow instance": { flowId: undefined }, +}; + +function record(id: string, patch: Partial): RequestRecord { + const base = { + id, + flowKind: "chat", + flowId: "chat-1", + actionName: "run", + userId: "alice", + orgId: DEFAULT_ORG_ID, + sessionId: SESSION, + tenantId: TENANT, + status: "completed", + startedAtMs: 1, + completedAtMs: 2, + version: 1, + createdAt: 1, + updatedAt: 2, + state: {}, + items: [], + } as unknown as Record; + const merged = { ...base, ...patch } as Record; + for (const key of Object.keys(merged)) if (merged[key] === undefined) delete merged[key]; + return merged as unknown as RequestRecord; +} + +const scratch = mkdtempSync(path.join(tmpdir(), "session-scope-parity-")); +afterAll(() => rmSync(scratch, { recursive: true, force: true })); + +const STORES: Array<[string, () => StoreRegistry]> = [ + ["in-memory", () => createInMemoryStores()], + [ + "filesystem", + () => createFilesystemStores({ rootDir: mkdtempSync(path.join(scratch, "fs-")), developmentOnly: true }), + ], +]; + +describe.each(STORES)("the stop hook's fence matches the session's reads (%s)", (_name, makeStores) => { + for (const [sessionName, session] of Object.entries(SESSIONS)) { + it(`agrees on every key, for a ${sessionName} session`, async () => { + const stores = makeStores(); + const records = Object.entries(VARIANTS).map(([name, patch], i) => [name, record(`req_${i}`, patch)] as const); + for (const [, rec] of records) await stores.request.set(rec.id, rec, "any"); + + const scope = sessionRequestScope(SESSION, session, TENANT); + const listed = new Set((await stores.request.list({ ...scope })).map((r) => r.id)); + + const disagreements = records + .filter(([, rec]) => requestInSessionScope(rec, scope) !== listed.has(rec.id)) + .map(([name, rec]) => `${name}: predicate ${requestInSessionScope(rec, scope)}, store ${listed.has(rec.id)}`); + expect(disagreements).toEqual([]); + // Or the agreement is vacuous: the matching record is in, the session's own reads find it. + expect(listed.has("req_0")).toBe(true); + expect(listed.size).toBeLessThan(records.length); + }); + } +});