Skip to content
Merged
Prev Previous commit
Next Next commit
fix(engine): refuse a schema-rejected starting state only on flows th…
…at bind sessions (FIX-1788 P1)

A flow binds its sessions when it declares a top-level .readonly()
session-state field or a session.createCheck. Only such a flow refuses, at
create, an initial state its stateSchema rejects. Every other flow keeps
the state as sent, as before, and its actions validate it when they run:
the workforce mailbox and project rooms create sessions half-filled on
purpose. Widening the refusal to every flow waits on FIX-1792.

Adds the off-state test (a flow with neither keeps a rejected state raw,
through the create route) and narrows the docs to say it in those terms.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XMg2dz8sMEdyzCQTRsaMTV
  • Loading branch information
claude committed Oct 7, 2026
commit fa76e459b4534b4a7fd5be0f4d34bbf0d8e25e2a
2 changes: 1 addition & 1 deletion .changeset/session-create-check.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,4 @@
"@flow-state-dev/store-postgres": minor
---

A flow can check every new session's initial state with `session.createCheck`, refuse caller-seeded fields with `session.serverOwned`, and fix a field for a session's life by declaring it `.readonly()` in its session `stateSchema`; `listSessions({ state })` and the list route's `state.<field>` filter select sessions by a readonly field. A session's initial state that fails its `stateSchema` is now refused, on every path that creates one, rather than stored raw. A dispatcher's `session: { key, state }` and a task dispatcher's `state` create the child session with that state. `ensureSessionRecord` now takes the create request beside the record it builds (FIX-1788).
A flow can check every new session's initial state with `session.createCheck`, refuse caller-seeded fields with `session.serverOwned`, and fix a field for a session's life by declaring it `.readonly()` in its session `stateSchema`; `listSessions({ state })` and the list route's `state.<field>` filter select sessions by a readonly field. On a flow that binds its sessions this way (a readonly field or a create check), an initial state that fails the `stateSchema` is refused on every path that creates a session; other flows keep it as sent. A dispatcher's `session: { key, state }` and a task dispatcher's `state` create the child session with that state. `ensureSessionRecord` now takes the create request beside the record it builds (FIX-1788).
2 changes: 1 addition & 1 deletion apps/docs/docs/configuration/flow.md
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ The host verifies credentials. The framework applies `defaultUserId` and `requir

| Field | Type | Default | What it does |
|-------|------|---------|--------------|
| `stateSchema` | Zod object | — | Session state shape. Use `.nullable().default(null)` for fields that start empty. A new session's initial state is parsed through it, and a create it refuses is refused with a 400 naming the field. A top-level field declared `.readonly()` is set when the session is created and never changes. See [Example: one session per project](/docs/fundamentals/state-and-scopes#example-one-session-per-project). |
| `stateSchema` | Zod object | — | Session state shape. Use `.nullable().default(null)` for fields that start empty. A new session's initial state is parsed through it. A top-level field declared `.readonly()` is set when the session is created and never changes. If your flow binds sessions (a readonly field or a `createCheck`), the starting state must match the schema or the create is refused with a 400 naming the field; any other flow keeps a starting state as sent. See [Example: one session per project](/docs/fundamentals/state-and-scopes#example-one-session-per-project). |
| `client` | `{ expose?, derived? }` | private | What crosses to the browser under `clientData.session`. `expose` copies named fields verbatim. `derived` computes named projections from `{ state, resources }`. Names must not collide. |
| `metadata` | Zod schema | — | Declares the session metadata shape (`title`, tags, and so on) for typing. Not enforced at runtime today: neither the session-metadata route nor `ctx.session.setMetadata()` parses against it, so a value outside the schema is persisted unchanged. |
| `retention` | `{ maxItems?, maxAge? }` | unbounded | Bounds the persisted item log. `maxAge` is milliseconds or a duration string (`"7d"`). Oldest completed requests evict first. A request stays until its run has finished, `onFinished` and any background work it started included, and for twice the configured `LIVE_TAIL_LIVENESS_MS` after (one minute by default), so a busy session can briefly exceed its limits; a request kept this way still counts toward `maxItems`, so older history is evicted in its place. Deleting a request also removes its stream events and cached step results. See [Deleting requests](/docs/persistence/overview#deleting-requests) for the edge cases and what a custom store must support. |
Expand Down
12 changes: 7 additions & 5 deletions apps/docs/docs/fundamentals/state-and-scopes.md
Original file line number Diff line number Diff line change
Expand Up @@ -178,9 +178,9 @@ const recent = await ctx.session.getJournal({ limit: 10 });

A new session typically starts via `sessions.createSession({...})` on the client, which returns a stable `sess_<id>` you reuse on every subsequent action call. See [Client Overview](/docs/client/overview).

If you call an action without a `sessionId`, the framework generates a fallback ID (prefix `ephemeral_<ts>_<rand>`) and persists the session record like any other. The action route doesn't return that generated ID to the client, so the session is effectively orphaned — useful for one-shot internal callers and tests, but not a way to start "real" conversations. For production conversational flows, always create the session first and pass the ID through. Such an action starts the session with no initial state, so on a flow whose `stateSchema` requires a field, or whose `createCheck` refuses an empty state, it is refused instead (see the [example below](#example-one-session-per-project)).
If you call an action without a `sessionId`, the framework generates a fallback ID (prefix `ephemeral_<ts>_<rand>`) and persists the session record like any other. The action route doesn't return that generated ID to the client, so the session is effectively orphaned — useful for one-shot internal callers and tests, but not a way to start "real" conversations. For production conversational flows, always create the session first and pass the ID through. Such an action starts the session with no initial state, so on a flow that binds its sessions (see below) and needs a starting value, it is refused instead (see the [example below](#example-one-session-per-project)).

A caller can pass initial `state` when it creates a session. It is parsed through the flow's session `stateSchema`, so missing fields take their defaults. A state the schema refuses is refused with a 400 that names the field (`{ error, field }`), and nothing is written.
A caller can pass initial `state` when it creates a session. It is parsed through the flow's session `stateSchema`, so missing fields take their defaults. A state that doesn't fit the schema is kept as sent, and your actions validate it when they run, unless the flow binds its sessions (below).

Initial state suits preferences and drafts. On its own it is the wrong place for a value that grants anything, because the caller wrote it; a `createCheck` that confirms the value (below) changes that.

Expand All @@ -195,7 +195,9 @@ session: {

A create that sets `reviewers` in its `state` is refused with a 400 whose body names the field (`{ error, field: "reviewers" }`), and nothing is written. Blocks in your flow write it like any other session state.

When a session exists to work on one particular thing, such as one project, put that thing in the session's `stateSchema` and declare it with zod's `.readonly()`. The schema checks the shape of every new session's initial state, and a create it refuses is refused. A readonly field is set when the session is created and never changes. Blocks read it like any other session state, and callers can list sessions by it.
When a session exists to work on one particular thing, such as one project, put that thing in the session's `stateSchema` and declare it with zod's `.readonly()`. A readonly field is set when the session is created and never changes. Blocks read it like any other session state, and callers can list sessions by it.

If your flow binds sessions this way (a readonly field or a create check), the starting state must match the schema or the create is refused, with a 400 that names the field (`{ error, field }`) and nothing written.

Most flows need only the schema. When a rule depends on who is creating the session, or on what exists in the store, such as "this project is yours or shared with you", also declare `session.createCheck`. It runs after the schema has parsed the initial state, receives that state and the caller's identity, and accepts or refuses the create. The [example below](#example-one-session-per-project) walks through both.

Expand Down Expand Up @@ -273,7 +275,7 @@ export const projectAssistant = defineFlow({
})();
```

That one line does the shape validation. `projectId` is required and has no default, so a create without a string `projectId` is refused with a 400 that names the field, and nothing is written. `.readonly()` makes it fixed: it is set when the session is created and never changes. Many flows stop here.
That one line does the shape validation. `.readonly()` makes `projectId` fixed: it is set when the session is created and never changes. It also makes this a flow that binds its sessions, so the starting state must match the schema. `projectId` is required and has no default, so a create without a string `projectId` is refused with a 400 that names the field, and nothing is written. Many flows stop here.

**3. Add a check for the rule that depends on the caller.** The schema can't know whether `q3-launch` exists, or whether this user may open it. That depends on who is asking and on what is stored, which is what `session.createCheck` is for:

Expand Down Expand Up @@ -404,7 +406,7 @@ With the flow above:
| A project that doesn't exist, or one the user wasn't given | `createCheck` | `404` | `{ error: 'No project "q3-launch".' }` |
| No `projectId`, or one that isn't a string | `stateSchema` | `400` | `{ error, field: "projectId" }` |

The last row is refused the same way on a flow with no `createCheck`.
The last row is refused by the schema alone: the readonly field binds the flow's sessions, with or without a `createCheck`.

An action sent without a session id, or to a session id that doesn't exist yet, would start a session with no `projectId`, so it gets that 400 and nothing is written. So does a webhook delivery to a new session id. Create the session first, as in step 4.

Expand Down
6 changes: 4 additions & 2 deletions docs/architecture/state-and-scopes.md
Original file line number Diff line number Diff line change
Expand Up @@ -699,8 +699,10 @@ address nothing reads.

Every creator goes through one function, `birthSession`
(`context/session-birth.ts`). It parses the session's initial state through the
flow's session `stateSchema` (a state the schema refuses is refused, never
stored raw), runs the `serverOwned` refusal for caller-seeded state and the
flow's session `stateSchema` (on a flow that binds its sessions, with a
`.readonly()` field or a `createCheck`, a state the schema refuses is refused;
any other flow keeps it as sent, because the workforce mailbox creates
sessions half-filled on purpose), runs the `serverOwned` refusal for caller-seeded state and the
flow's `session.createCheck` on the parsed state, reclaims the id's resource-state tombstones (FIX-1258),
mints the lineage id unless the caller derives one, and writes `"absent"`. The
caller describes the record it wants and chooses only what a lost race means:
Expand Down
5 changes: 3 additions & 2 deletions packages/client/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -197,8 +197,9 @@ const mine = await sessions.listSessions({ flowKind: "agent", userId, state: { p
```

The filter needs `flowKind` or `flowId`, matches string values exactly, and is
refused for a field that isn't readonly on that flow. A create whose `state` the
schema refuses rejects with a 400 naming the field. A flow can also declare a
refused for a field that isn't readonly on that flow. On a flow with a readonly
field or a create check, a create whose `state` doesn't match the schema rejects
with a 400 naming the field. A flow can also declare a
[`session.createCheck`](https://flow-state.dev/docs/fundamentals/state-and-scopes#creating-sessions)
for a rule that depends on the caller, such as whether the project is theirs; it
rejects with the server's status (400, 403 or 404) and message. Either way, no
Expand Down
6 changes: 4 additions & 2 deletions packages/engine/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -586,8 +586,10 @@ Every path that creates a session (the create route, an action to a session
id that does not exist yet, a webhook delivery, `fsdev run`, and a dispatch
into a child session) creates it from an initial state: the create body's
`state`, `fsdev run --seed-session`, or the `state` a `dispatcher()`'s
`{ key, state }` session names. The flow's session `stateSchema` parses it; a
state the schema refuses is refused, never stored raw. `session.serverOwned`
`{ key, state }` session names. The flow's session `stateSchema` parses it. A
flow that binds its sessions (a top-level `.readonly()` field or a
`createCheck`) refuses a state the schema refuses; any other flow keeps it as
sent, for its actions to validate when they run. `session.serverOwned`
names fields a caller may not seed. Most flows need nothing more. The optional
`session.createCheck` is for a rule that depends on who is creating the session
or on what exists in the store: it receives the verified caller and the parsed
Expand Down
26 changes: 23 additions & 3 deletions packages/engine/src/context/session-birth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@
* resource-state incarnation, and the previous one's tombstones go with it
* ({@link purgeStaleResourceState}).
* - **Checking.** The session's initial state, parsed through the flow's
* `stateSchema` (a state the schema refuses is refused, never kept raw), the
* `stateSchema` (on a flow that binds its sessions, a state the schema
* refuses is refused; see {@link parseInitialSessionState}), the
* `serverOwned` refusal for state a caller seeded, and the flow's
* `createCheck` on what the schema parsed.
*
Expand All @@ -51,7 +52,7 @@ import {
toIsolationFlow
} from "../stores/scope-keys";
import { toBareState } from "../stores/resource-state-views";
import { deepEqual } from "@flow-state-dev/core/helpers";
import { deepEqual, getReadonlyStateKeys } from "@flow-state-dev/core/helpers";

/**
* Release a newborn session from the resource-state tombstones a previous
Expand Down Expand Up @@ -225,13 +226,31 @@ export function refuseServerOwnedState(
}
}

/**
* Whether a flow binds its sessions: it declares a top-level `.readonly()`
* session-state field or a `session.createCheck`. A bound session is defined
* by what it starts with, so its starting state must fit the schema.
*/
function bindsSessions(flow: Pick<BirthFlow, "session">): boolean {
return (
flow.session?.createCheck !== undefined ||
getReadonlyStateKeys(flow.session?.stateSchema).length > 0
);
}

/**
* A new session's initial state: `state` parsed through the flow's session
* `stateSchema`, so every declared key starts with its default and a block
* never reads `undefined` for one.
*
* A state the schema refuses is refused on a flow that binds its sessions
* ({@link bindsSessions}). Any other flow keeps it as sent, and its actions
* validate it when they run: some create sessions half-filled on purpose and
* complete them later (the workforce mailbox reads the missing fields as
* "not yet opened").
*
* @throws SessionCreateRefusedError (400, naming the first failing field) when
* the schema refuses the state. It is never kept raw.
* a bound flow's schema refuses the state.
*/
export function parseInitialSessionState(
flow: Pick<BirthFlow, "kind" | "session">,
Expand All @@ -243,6 +262,7 @@ export function parseInitialSessionState(
if (schema === undefined) return raw;
const parsed = schema.safeParse(raw);
if (parsed.success) return parsed.data as JsonObject;
if (!bindsSessions(flow)) return raw;
const [issue] = parsed.error.issues;
const field = issue?.path[0];
throw new SessionCreateRefusedError(
Expand Down
5 changes: 3 additions & 2 deletions packages/engine/src/routes/session-routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -386,8 +386,9 @@ export async function handleCreateSession(
// terminal-status snapshot refresh.
// 2. Block code that reads `ctx.session.state.foo` before any patch
// would observe `undefined` rather than the schema's default.
// Caller-supplied `body.state` overrides the defaults. The birth parses it,
// and refuses one the schema refuses rather than storing it raw.
// Caller-supplied `body.state` overrides the defaults. The birth parses it;
// on a flow that binds its sessions it refuses one the schema refuses, and
// any other flow keeps it as sent.
const callerState = asObject(body.state);

const orgId = ctx.principal?.orgId ?? DEFAULT_ORG_ID;
Expand Down
24 changes: 24 additions & 0 deletions packages/engine/test/session-birth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,30 @@ describe("the create route", () => {
expect(res.status).toBe(201);
expect((await stores.session.get("p1"))?.state).toEqual({ anything: 1 });
});

// Off state of the create-time schema refusal: only a flow that binds its
// sessions (a readonly field or a create check) refuses. A flow with a schema
// and neither keeps today's behaviour, which workforce's half-filled mailbox
// sessions rely on.
it("keeps a state the schema rejects as sent, on a flow with no readonly field and no check", async () => {
const loose = defineFlow({
kind: "loose",
session: { stateSchema: z.object({ members: z.array(z.string()), mode: z.string().default("chat") }) },
actions: { noop: { inputSchema: z.object({}).passthrough(), block: handler({ name: "loose-noop", execute: () => ({}) }) } }
})({ id: "loose" }) as unknown as FlowInstance;
const registry = createFlowRegistry();
registry.register(loose);
const stores = createInMemoryStores();
const router = createFlowApiRouter({ registry, stores, staleSweepIntervalMs: 0 });

const rejected = await create(router, "loose", { userId: "alice", sessionId: "l1", state: { members: "nope" } });
expect(rejected.status).toBe(201);
expect((await stores.session.get("l1"))?.state).toEqual({ members: "nope" });

const fits = await create(router, "loose", { userId: "alice", sessionId: "l2", state: { members: [] } });
expect(fits.status).toBe(201);
expect((await stores.session.get("l2"))?.state).toEqual({ members: [], mode: "chat" });
});
});

describe("a readonly state field", () => {
Expand Down
Loading