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/session-stop-request.md
Original file line number Diff line number Diff line change
@@ -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.
9 changes: 9 additions & 0 deletions apps/docs/docs/fundamentals/flows.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion docs/architecture/execution-and-errors.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
4 changes: 3 additions & 1 deletion labs/app-lab/test/shell.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ export type {
OrgScopeHandle,
RequestScopeHandle,
SessionScopeHandle,
StopRequestOutcome,
UserScopeHandle,
} from "./types/scope";
export type { ScopeStateOps } from "./types/state";
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -308,6 +308,7 @@ export type {
SessionMetadata,
SessionMetadataInput,
SessionScopeHandle,
StopRequestOutcome,
UserScopeHandle
} from "./scope";

Expand Down
21 changes: 21 additions & 0 deletions packages/core/src/types/scope.ts
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,19 @@ export type SessionMetadataInput = SessionMetadata & {
metadata?: Record<string, unknown>;
};

/**
* 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
Expand All @@ -191,6 +204,14 @@ export type SessionScopeHandle<
appendJournal(entry: JournalEntryInput): Promise<void>;
getJournal(options?: { limit?: number; offset?: number }): Promise<JournalEntry[]>;
setMetadata(input: SessionMetadataInput): Promise<void>;
/**
* 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<StopRequestOutcome>;
} & ScopeStateOps<TState>;

export type UserScopeHandle<
Expand Down
26 changes: 25 additions & 1 deletion packages/engine/src/context/createExecutionContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import type {
SessionItemViews,
SessionMetadataInput,
SessionScopeHandle,
StopRequestOutcome,
UserScopeHandle,
TokenCounter
} from "@flow-state-dev/core/types";
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -2665,6 +2667,28 @@ export async function createExecutionContext<
...(input.metadata !== undefined ? { metadata: input.metadata } : {})
});
},
stopRequest: async (targetId: string): Promise<StopRequestOutcome> => {
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.
Comment thread
jhoffner marked this conversation as resolved.
Resolved
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()
Expand Down
25 changes: 24 additions & 1 deletion packages/engine/src/context/session-request-scope.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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<RequestRecord, "sessionId" | "tenantId" | "userId" | "orgId" | "flowKind" | "flowId">,
scope: ReturnType<typeof sessionRequestScope>
): 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)
);
}
64 changes: 64 additions & 0 deletions packages/engine/src/execution/record-request-stop.ts
Original file line number Diff line number Diff line change
@@ -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<RequestRecord, "id" | "createdAt" | "incarnation">
): Promise<RequestStopResult> {
// 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" };
}
51 changes: 13 additions & 38 deletions packages/engine/src/routes/abort-routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down Expand Up @@ -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 });
}
Loading
Loading