Skip to content

spec(FIX-1322): addressed dispatch and durable instance ownership - #1633

Closed
jhoffner wants to merge 4 commits into
mainfrom
spec/FIX-1322
Closed

jhoffner wants to merge 4 commits into
mainfrom
spec/FIX-1322

Conversation

@jhoffner

@jhoffner jhoffner commented Sep 7, 2026 •

Copy link
Copy Markdown
Collaborator

Dispatch forgets which copy of a flow was selected, and saved sessions identify only its kind. A restart or later read can therefore choose another copy's configuration or data.

What this does

Carry the selected instance through existing dispatch and persist its owner on sessions and requests. Check that owner before execution, recovery, authorization or later data access. Keep singleton addresses and known history compatible; do not add another transport, recipient API, chat redesign or message-board routing.

Delivery plan: FIX-1321's registry/cardinality switch and FIX-1322's complete consumer/owner cutover land atomically in one shared implementation PR, with FIX-1322 as integration owner. Exact lookup cannot land ahead of live kind-addressed consumers. Separate issue scopes, acceptance and goal accountability remain; both individual specs and the later cross-spec gate need owner approval before implementation. This is an absorbed engineering sequencing decision, not whole-spec approval. FIX-1323 stays separate with its identity/owner prerequisites; rollout is not safe until the full floor proof includes isolation.

Need your sign-off

Approve the direction in Parts I+II, not implementation or merge. Build as scoped. The objective approval is already recorded; this individual specification still needs approval.

Saved work cannot transfer just because another instance was addressed

  • Same-kind peers own separate sessions and requests; explicitly addressed replies to the original owner remain supported.
  • If this is wrong: recovery could silently run another copy's configuration or access its data.

Unknown historical owners require an inventoried cutover

  • Keep known singleton history compatible; custom-id deployments explicitly map historical owners while producers are quiesced.
  • If this is wrong: an upgrade guesses who owns saved work, or operators face migration work they did not expect.

Historical child history: preserve links or keep one runtime lookup?

  • Decision needed (§12): if old cross-flow children exist for custom-id destinations, the new child derivation and promise to preserve old record ids conflict. Stamping owners alone cannot make repeat dispatch find those children. No affected deployment history has been established.
  • Recommendation: re-key affected children and dependent references during the quiesced offline migration. Repeat dispatch retains one runtime derivation, but saved ids/links change and the migration inventory grows.
  • Alternative: explicitly adopt owner-stamped legacy keys. Old ids/links survive, but a second persisted lookup/precedence rule and ongoing ambiguity handling become permanent obligations.
  • What changes the recommendation: verified absence of affected history permits a preflight exclusion; a requirement to preserve old saved links favours adoption. A wrong choice splits child history or breaks saved references.
  • Before individual sign-off: resolve this conditional migration promise. Neither alternative is selected by the atomic sequencing decision; do not infer a resolution during implementation.

Parts worth reviewing closely

The rest is for the technical reviewer.

  • §7 admission: do all creators, race winners and queue materializers check owners before acceptance/effects? A host-only guard leaves direct execution unsafe.
  • §7 migration and feat(dispatch): cross-flow fire-and-forget with named runtime miss (D-8) #1600 boundary: do legacy id/kind collisions refuse without guessing, while explicit replies preserve the resolved recipient's ownership?
  • §8–§11 consumer cutover: typed clients, React retry, CLI and record-backed data readers must carry identity too. No new UI or Devtool feature is included.

Known limitation: existing resource-tombstone reclamation races remain FIX-1000's scope; this spec does not claim cross-store atomic generations. The independent historical-child-key fork in §12 remains unresolved; no POC is in flight.

Full spec · Linear issue · Linear spec · Epic. Never merge this spec PR.

How to review this direction document

How to review this

This is a direction document, not an implementation. Reviewing it well means
answering one question: is this the right approach?

In scope to challenge:

  • The problem framing — are we solving the right thing?
  • The approach — will it work, does it fit the architecture and docs/philosophy.md?
  • Any numbered Decision in §6 — that's the sign-off surface.
  • Missing constraints, edge cases, or dependencies that would invalidate the design.
  • Scope — a deliverable that shouldn't ship, or one that's missing.

Out of scope — deliberately unsettled here, and owned by the implementing agent:

  • Names, signatures, file paths, and module layout.
  • Local structure: which helper, how a function is decomposed, error-message wording.
  • Micro-optimizations and style preferences.
  • Test names and internal test structure (the behaviours to test are in §10; the tests
    themselves are not).
  • Anything Part II left open on purpose — it is directional by design, and a gap at
    that altitude is intended, not an omission.
  • The solution sketch, at the line level. A spec may include a rough pseudocode sketch
    showing the shape of the proposed solution. It is knowingly incomplete, is not real
    code, and is not what will ship. Review it for directional viability and key design
    aspects only
    — is this the right shape, in the right layer, composing the right way?
    Do not report that it lacks error handling, omits edge cases, names things that
    don't exist in the repo, or wouldn't build: all of that is true on purpose, and the
    names are deliberately not real. A sketch that has to survive line-level review stops
    being cheap, and then nobody writes one.
  • Any POC files on this branch, entirely. This PR is never merged, so it may carry
    throwaway proof-of-concept code, characterization tests, or an HTML mockup built to
    validate the direction (spec-poc). None of it
    ships. Read it to judge whether the shape holds; do not review it as code. Its
    quality is not a finding, and its findings are summarized in §7 — the summary is what a
    reviewer reacts to.

One request, if you are an automated reviewer: the two lists above are the whole
difference between a useful review of this document and a long one. Volume is not signal
here — a single finding above the line is worth more than twenty below it.

Feedback in the second list is welcome and gets recorded verbatim in §13 for the
implementer to weigh against real code. It will not be argued with, and it will not be
folded into the design prose — that would pretend the spec can settle something it
can't. Please don't re-raise it: one mention is enough for it to land in §13.

The one exception is the sketch and the POC. Line-level feedback on either is
dropped, not recorded — there is nothing for an implementer to weigh about code that
isn't shipping, and a §13 note would imply otherwise. Feedback about their direction is
not line-level and is treated like any other above-the-bar finding.

Engineering calls
  • Retain historical address-slot spelling flowKind with instance-id values; persisted kind metadata stays actual kind and new flowId is durable owner. A blind field copy would collapse the distinction again.
  • Consume FIX-1321's exact-only get(address); no second resolver or public pair. Integrate adjacent open feat(dispatch): cross-flow fire-and-forget with named runtime miss (D-8) #1600 rather than assuming it landed.
  • One shared implementation PR for FIX-1321 + FIX-1322, with FIX-1322 owning integration; no independent landing workers, alias, first-wins fallback, temporary collection ban, new child or public pair. FIX-1322 alone retains its approximately 65 production files, 12 behaviour groups and 30 mostly narrow documentation surfaces; these are not combined-PR estimates. Partial ownership enforcement is unsafe.
  • This direct EM sequencing fold adds zero automatic review rounds (aggregate: one); it is not a fresh feedback sweep and claims no unseen PR activity handled.
  • Document-quality reviews covered technical invariants, scope/dependencies and documentation placement. Folded missing client/React materializers and corrected feat(dispatch): cross-flow fire-and-forget with named runtime miss (D-8) #1600 reply interpretation. No executable validation, production source, tests, formatters or builds were run.
Tradeoffs, practices, usage and full decisions

3. Tradeoffs & alternatives

A registry-only fix loses the owner on persistence. A new address object expands callers and violates the single-id contract. Retain existing address slots, distinct from stored kind metadata. Complexity is at admission and restart/migration boundaries.

4. Focus practices

  • BP-030: tolerate known old singleton shapes, never invent a collection owner.
  • BP-035: exercise re-entry, queue admission and create-race winners, not just initial dispatch.
  • Tenet 5: owner checks precede writes, resolver selection and resource loading.

5. What using it looks like

Existing field spellings remain; address values are instance ids. Proposed outcomes:

import { createClient } from "@flow-state-dev/client";
const east = createClient({ flowKind: "review-east", userId: "u_1" });
const west = createClient({ flowKind: "review-west", userId: "u_1" });
await east.sendAction("review", { invoiceId: "inv_42" });
// A west action carrying a session owned by east refuses; it does not transfer it.
fsdev run review-east review --input '{"invoiceId":"inv_42"}'
# Runs east; a collection's bare kind never picks a member.

Decisions in full

  1. Addressing saved work through another instance cannot transfer it. Reject implicit adoption. Locks in: same-kind peers start separate work; recovery cannot substitute for an unavailable owner.
  2. Unknown historical owners require explicit migration. Reject guessing from available copies. Locks in: custom-id deployments need an inventoried, quiesced cutover; known singleton history remains compatible.

@jhoffner jhoffner added the spec label Sep 7, 2026
@linear-code

linear-code Bot commented Sep 7, 2026

Copy link
Copy Markdown

FIX-1322

@vercel

vercel Bot commented Sep 7, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

3 Skipped Deployments
Project Deployment Actions Updated
flow-state-dev-docs Ignored Ignored Sep 7, 2026 8:47pm UTC
flow-state-dev-kitchen-sink Ignored Ignored Sep 7, 2026 8:47pm UTC
flow-state-dev-ui Ignored Ignored Preview Sep 7, 2026 8:47pm UTC

Request Review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 7, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-07T20:01:05.947179Z 608b673 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Simplify review — direction sound; trim spec surface before implementation

Verdict: COMMENT (same posture as FIX-1321 / PR #1631). The core approach is the right one for this epic; the complexity is mostly honest spec surface area, not over-engineered product scope.

Approach assessment

Promoting the lookup bug to wire-slot reuse + durable flowId + one shared admission check is the cleanest path given the constraints:

  • Registry-only fix loses ownership on persistence (correctly rejected in §3).
  • A parallel address object / second selector violates the single-id contract (correctly rejected).
  • Retaining flowKind spelling while values become instance ids preserves singleton compatibility without a public API break.
  • Partial owner enforcement really is unsafe — the one-PR choice is defensible even at ~65 files.

I don't see a simpler product design that still satisfies the approved flow-instances floor. Using a third-party package doesn't help here; identity, CAS, and registry are in-repo concerns.

Where it went further than necessary

The spec repeats its footprint many times:

  1. Four inventories for the same work (§6 planning size, §8 module table, §10 twelve behaviours, §11 thirty doc rows). Keep one authoritative build map (§8) and reduce the others to outcome classes + "see §8."
  2. §11 documentation matrix (30 rows) — many rows are "terminology correction or link" (your own words). Consider ~8 canonical surfaces (setup, persistence overview, inbound transports, + three architecture pages) with package READMEs getting one paragraph + link. This pattern worked well on FIX-1321.
  3. §7 #1600 child/reply/lineage re-derives adjacent PR semantics. Four invariant bullets + pointer to #1600 would preserve the contract without a second copy of that PR.
  4. Migration runbook (§7 L122–123) — refusal rules belong in spec; the step-by-step operator checklist may fit better in the persistence migration doc FIX-1323/FIX-1322 share, keeping only "no flowId = flowKind blanket backfill" and drain requirement here.
  5. External precedents (§7) — informative but trimmable; epic + §3 already establish the principles.

Implementation notes (not blockers)

  • Centralize the helper beside evaluateAdoption / binding-errors / pickPrincipalResolver — the codebase already has convergence points for this class of check; avoid per-route reimplementation across ~65 touchpoints.
  • Performance: dual transport+execution admission is inherent to durable queues; acceptable if ctx.flow is threaded and flow_id indexes are added for list filters.
  • #1600 coordination is the real merge hazard — refresh branch before coding; converge flowId metadata shape so cross-flow dispatch stamps and durable record fields don't diverge.

What I'd approve as-is

  • Decisions §6 (no implicit transfer; explicit migration for unknown owners)
  • Address vs owner vs kind role table
  • Legacy dual-read rules and collection queue-drain constraint
  • Honest FIX-1000 boundary (owner admission ≠ atomic reclamation)

No changeset needed (spec-only). No major concerns that block directional approval.

Open in Web View Automation 

Sent by Cursor Automation: Review For Best Approach

Comment thread spec/FIX-1322.md Outdated

**Non-goals:** registry/cardinality (FIX-1321), storage namespaces (FIX-1323), new delivery modes, message boards, fan-out, Devtool, Workforce minting, chat redesign/removal.

**Planning size:** approximately 65 production files · 12 test behaviours · 30 documentation surfaces · **1 implementation PR**; partial owner enforcement is unsafe.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The planning-size banner is useful once. The same footprint is re-stated in §8 (module table), §10 (12 behaviours), and §11 (30 doc rows). Consider keeping §8 as the single authoritative build map and reducing the others to category counts + "see §8" — same trim we suggested on FIX-1321.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Drop — editorial preference, not a direction defect. §8 is the build map; §10 lists observable regressions and §11 assigns documentation surfaces. They serve distinct consumers. Keeping lifecycle, reader, typed-client and React coverage rather than shrinking it to counts.

Comment thread spec/FIX-1322.md

#### Baseline and the shared contract

Research baseline: fresh `origin/main` at `cc4bd1e41`. The immutable epic reviewed here is [PR #1617 at e1d5b701](https://github.com/fixpoint-labs/flow-state-dev/blob/e1d5b701096105eb04954b4ec41545b3dc25e7cf/spec/_epics/flow-instances.md). Its stale pending-objective text is superseded by the owner's session approval, recorded in FIX-1320 comment `4a714d24-2f94-4066-af07-15a74e7355ab`; no individual approval is implied.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Baseline paragraph packs three commit SHAs, PR links, and a FIX-1320 comment UUID. For a direction spec, consider collapsing to: "Baseline: main @ research head; epic @ PR #1617; depends on FIX-1321 exact get(address)." SHAs can live in spec evolution or implementation notes.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Drop — §7 Baseline retains immutable research and approval provenance so objective approval cannot be mistaken for individual sign-off. No directional defect requires moving it.

Comment thread spec/FIX-1322.md
For a dispatch originating inside a running instance, omitted cross-flow selector binds explicitly to that running instance's id. An explicit selector always resolves as an id, even if its string equals the sender's kind; it must not shortcut to the sender. Adapters may receive the declaration from their existing application binding. Handler matching alone is not recipient selection. Existing integrations without a declared collection recipient refuse rather than selecting a copy or expanding to every copy; no new targeting configuration is commissioned.

#### Convergence and ordering

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good convergence point. Consider explicitly anchoring the shared helper to existing machinery — extend evaluateAdoption / binding-errors / pickPrincipalResolver rather than introducing a parallel "ownership subsystem." The codebase already treats user/tenant/org binding mismatches this way; instance owner is the same class of check at a different boundary.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note for implementation — retained verbatim in §13 at 260372e and the FIX-1322 Linear mirror. §7 already requires one engine-owned check beside existing adoption helpers; exact helper placement remains an implementer call, not a new subsystem.

Comment thread spec/FIX-1322.md

The existing `ensureSessionRecord` resource-tombstone reclamation race is not closed by an owner check: a delayed creator can purge a winner's tombstones before losing session CAS. `ensure-session-record.ts` documents the required scope-generation work as FIX-1000. This issue prevents adoption/execution and admission-owned writes against a foreign owner; it does not promise atomic resource reclamation across stores or commission scope generations. Validate the race winner without moving reclamation into a new unsafe ordering.

#### Child, reply and lineage boundary

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

#1600 coupling is real but this subsection re-derives that PR's mechanics. Could this collapse to 3–4 invariant bullets + pointer?

  • Same-instance boundary uses resolved id, not kind string
  • Same-kind peers get cross-flow treatment
  • Explicit reply requires stored owner == resolved recipient
  • No parent-owner filtering of cross-owner descendants

Implementer still must converge #1600; the spec doesn't need to be a second copy.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Drop — §7 Child, reply and lineage boundary records the issue-local ownership contract needed by an isolated implementer; §8/§12 require refreshing and converging #1600. Keeping the explicit reply fact: resolving the original owner can legitimately re-enter its session; a wrong/default recipient refuses. No new reply mode or cut coverage.

Comment thread spec/FIX-1322.md
2. Without `flowId`, preserve default singleton history only when the resolved definition is a singleton whose `id`, `kind` and stored `flowKind` all agree. Deployment inventory must establish this was historically a default singleton, not a custom-id instance now relabelled. Runtime string equality cannot discover deployment history.
3. Any ownerless collection/custom-id history requires an explicit per-record owner mapping and offline backfill, or a named `migration-required` refusal. One currently registered collection member proves nothing. A legacy `flowKind: engineer` must not be assigned to an unrelated billing instance whose id happens to be `engineer`.

Commission a documented **adapter-native offline cutover**, not a generic migration service: quiesce producers and execution; drain old queues/active work; back up and inventory session/request records plus FIX-1323's cells; map explicit record ids to known registered ids; validate kind, tenant, session/request and parent/lineage relationships; backfill owner fields without changing record ids; verify readback before resuming. An interrupted run is safe to repeat for already-identical mappings; a conflicting stamped owner stops it. No store-wide transaction or all-scope enumeration is assumed. SQL schema changes may add nullable legacy owner columns but must not blanket-backfill `flowId = flowKind` for collection history.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Refusal semantics and "no flowId = flowKind blanket backfill" belong here. The full operator playbook (quiesce → drain → backup → inventory → map → backfill → verify) may be better as one canonical migration doc referenced from persistence overview — FIX-1323 already owns cell provenance. Reduces spec size without weakening the "no guessing" decision.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Drop — §11 already makes persistence/overview the primary migration checklist and links companion pages rather than duplicating recipes. §7 retains the migration constraints the owner is signing off; no extra migration page/service is commissioned. The separate child-key contract question is now visible in §12, not silently solved by moving prose.

Comment thread spec/FIX-1322.md

The existing primitive is application binding plus `dispatcher()` / `host.dispatch`; there is no user-space hook that makes all durable readers obey that binding. The delta is framework lifecycle composition, not discoverability or vendor knowledge. Keep this approved scope rather than a wrapper, a second address, or new workflow machinery.

External precedents inform principles, not APIs: [Orleans logical grain identity](https://learn.microsoft.com/en-us/dotnet/orleans/grains/grain-identity) survives activations, but its composite type/key address is rejected here; [Temporal workflow versus run identity](https://docs.temporal.io/workflow-execution/workflowid-runid) supports stable ownership and explicit conflict refusal, not importing replacement policies; [Cloudflare durable-object migrations](https://developers.cloudflare.com/durable-objects/reference/durable-objects-migrations/) support declared historical identity changes, not guessing from today's deployment. No library or dependency is needed. Read-only research found the owning paths; no executable POC or validation was run during specification.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Orleans/Temporal/Cloudflare inform principles you already established in §3 and the epic. Consider trimming to a one-line footnote — same note we left on FIX-1321.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Drop — §7 Necessity and research is one paragraph documenting principles and rejected imported APIs. This is an editorial preference without an approach defect.

Comment thread spec/FIX-1322.md

**Goal:** a model-free real-path harness under `goals/flow-instances/owner-continuity/` with two registered collection instances A/B whose handlers and configuration return distinguishable markers. Through the actual host and filesystem or SQLite stores, address A then B; restart the host over those stores; re-enter A's session/request, read A's state/resource projection and attempt all of that through B. A remains A, B refuses before execution or mutation, and removing/reordering B never redirects A. Exercise the actual CLI and BullMQ adapter/worker target round-trip separately; no mock dispatcher may stand in for the external delivery path. No model is needed because the goal is deterministic identity, not generated content.

Once FIX-1323 is integrated, run the assembled epic scenario using isolated user state and resources: A and B write different markers, later reads see only their own, wrong-instance session re-entry refuses, lone bare kind refuses, collision exact id wins, and default singleton URLs/buckets still work. The owner-continuity goal can prove this issue without claiming the separately owned isolation key change has landed.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Worth one clarifying sentence: the owner-continuity goal can prove FIX-1322 ownership without FIX-1323 isolation keys landing, but the full epic Proof (two instances with distinct isolated state) still requires FIX-1323. Avoid readers inferring epic floor from this issue alone.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Drop — already explicit in §10: "The owner-continuity goal can prove this issue without claiming the separately owned isolation key change has landed." The preceding paragraph reserves the assembled isolated-state scenario until FIX-1323 is integrated. All goal proof remains planned/unrun.

Comment thread spec/FIX-1322.md

Once FIX-1323 is integrated, run the assembled epic scenario using isolated user state and resources: A and B write different markers, later reads see only their own, wrong-instance session re-entry refuses, lone bare kind refuses, collision exact id wins, and default singleton URLs/buckets still work. The owner-continuity goal can prove this issue without claiming the separately owned isolation key change has landed.

**Twelve CI behaviours** (each should fail on a plausible regression):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Behaviours 1, 4, 7, and 8 largely restate the same admission/re-entry invariant in different ingress costumes. If the goals/flow-instances/owner-continuity/ harness proves the tracer bullet, consider collapsing to ~5 outcome classes (dispatch retention, persistence round-trip, wrong-owner refusal, #1600 boundary, legacy/migration) with "extend existing suites per §8 slice" rather than a mandatory 12-test checklist.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Drop — §10 names behaviours, not a mandatory count of test files. Direct admission, queued acceptance, post-restart re-entry and saved-record authorization can fail independently; grouping tests is an implementation choice, not permission to omit those paths. The real-path goal and existing-suite requirement already stand.

Comment thread spec/FIX-1322.md

**Required:** public target semantics, durable owner refusal and operational migration are observable contracts. Extend existing pages; **no new page or sidebar change**. Existing Engine/Advanced/persistence categories already fit. Audience is application authors first, adapter authors and operators where named. Lead with the outcome, define instance versus kind once, use complete minimal TypeScript/CLI examples at implementation, and show refusal behavior without marketing language or issue history (`docs/contributing/user-docs.md`, `writing-for-humans.md`). Fresh writer/editor review applies during implementation; do not expand into a corpus rewrite.

Each row is one surface (30 total). Most companion changes are a terminology correction or link, not another tutorial.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This 30-row matrix is the largest bloat vector. You already say most rows are "terminology correction or link." Consider specifying ~8 canonical surfaces (setup, persistence overview, inbound transports, durable execution, authentication, + inbound-transports / dispatched-work / state-and-scopes architecture) with package READMEs getting one paragraph + link to the canonical page. East/west refusal example appears in §5, §202, §205, and §224–229 — define once, link elsewhere.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Drop — §11 already instructs terminology/link-only companion edits, no new pages, and primary-page cross-links. Removing typed-client, React and adapter promise corrections would leave public callers with obsolete owner/address semantics. Keeping the surface inventory; no corpus rewrite.

@jhoffner jhoffner left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

second-look (restraint lens) — full findings in the file-level and inline comments below.


Generated by Claude Code

Comment thread spec/FIX-1322.md

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Second-look (restraint lens), spec target. Forward estimate: ~65 production files, 12 CI behaviours, 30 doc surfaces, 1 implementation PR, on top of a 247-line spec.

Verdict: Appropriately scoped. I ran the five lenses (premise, requirement-origin, YAGNI, 80/20, hindsight) against §§7–12 and couldn't land a candidate that clears the calibration gate (concrete leaner alternative + net removal that's actually worth it + articulable loss + not a documented contract). Specifics below.

Why the size holds up, not just asserted:

  • The persistence requirement (flowId on SessionRecord/RequestRecord/ActiveRequestEntry, round-tripped through all 4 store adapters) isn't scope creep — it's literally the reported bug ("a restart... can choose another copy's configuration or data"). A registry-only, non-persisted fix (the narrower alternative I checked first) reproduces the exact symptom on restart, so it fails on requirement-origin, not just taste.
  • The legacy-cutover/migration section is required by BP-030 (tolerate old persisted shapes) once a new required identity field lands on already-deployed records — not a speculative "migration service." It already rejects the generic-service shape itself ("not a generic migration service").
  • "One coherent PR, partial enforcement is unsafe" — I looked for a phased alternative (persist first, enforce later behind a flag) and rejected it myself: a stamped-but-unchecked owner field is a false sense of security on a cross-tenant data-access boundary, which is arguably worse than today's bug. The spec already made this call for the right reason.
  • Doc surfaces: git grep -l flowKind across docs turns up ~50 files; the spec touches 30, and explicitly hands off the sections owned by sibling specs (FIX-1321 owns declaration/cardinality in flows-and-actions.md, FIX-1323 owns namespace sections in state-and-scopes.md) rather than re-touching them. That's the narrower set, not the padded one.
  • The (kind, id?) → exact-id addressing gap is real today: InMemoryFlowRegistry.flowsByKind already stores multiple ids per kind in packages/engine/src/registry/flow-registry.ts, so multi-instance flows already exist in the registry — this spec is closing a real, currently-reachable persistence/admission gap, not building ahead of a capability that doesn't exist yet.

Considered & deemed justified

  • Exact-owner filtering added to session/request enumeration (§7) — extends filtering that already exists (debug-routes.ts, session-routes.ts already filter by flowKind); not new admin surface.
  • 12 CI behaviours for a cross-tenant-adjacent security boundary spanning ~8 entry points (HTTP, generic/typed client, CLI, BullMQ, MCP, webhook, internal/task, direct execution) — proportionate, not padding.
  • Non-goals list (registry/cardinality, storage namespaces, new delivery modes, message boards, fan-out, Devtool, Workforce minting, chat redesign) — a real restraint pass already happened before this reached review.

One dependency-risk note, not a bloat finding (see inline comment on §12): the child/reply/lineage boundary in §7 is written against PR #1600, which is open and unlanded — worth a second look at sequencing, not surface.

No refactoring opportunity for improve-codebase-architecture: this PR carries no code (never-merged spec doc per BP-037), and the architecture gap it's closing (registry already supports multi-instance-per-kind; persistence/admission never carried the selected id) is exactly what §7 already proposes to fix.


Generated by Claude Code

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Recorded as agent review, not Jake's individual approval. No change requested by the restraint verdict. Scope and owner-admission coverage remain intact; the sequencing observation is answered on its own thread.

Comment thread spec/FIX-1322.md
### 12. Dependencies, open questions & follow-ups

- **FIX-1321 merges first:** exact-id registry and explicit collection declaration are technical prerequisites. No collection deployment is safe from registry changes alone. FIX-1323 can develop independently against the shared id/owner seam; full floor Proof requires all three.
- **#1600 is adjacent, OPEN at a9b1fc261:** converge its dispatch/action rename and child/reply/lineage changes before FIX-1322 merges. It is not a child, an already-landed implementation or authority to start code. Refresh status/head during implementation; if still open, coordinate seam ownership rather than ship competing versions.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sequencing note, not a restraint/bloat finding (out of this lens): §7's "Child, reply and lineage boundary" spends real design weight — the same-instance/cross-instance boundary swap, the explicit-reply-to-original-owner rule, the session-not-addressable refusal shape — locked in against PR #1600, which is still open and described here as "not... an already-landed implementation." If #1600 changes shape during its own review before this merges, that subsection is the part most likely to need rework. Worth confirming at implementation time that "refresh #1600 before coding" actually happens rather than building against a stale mental model of it — not asking for scope to be cut here, since the dispatch-ownership story is genuinely incomplete without covering replies to a specific owner.


Generated by Claude Code

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Drop — already required by §8 opening and §12: refresh #1600 before coding and converge its action/dispatch/child/reply/lineage seams before FIX-1322 merges. No stale implementation is treated as landed. Explicit reply to the resolved original owner remains allowed; wrong recipient refuses.

@jhoffner

jhoffner commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author

FSD Architect — coherence clear on #1633 / FIX-1322 at 608b673.

§6 ratified (both)

  1. Addressing saved work through another instance cannot transfer it — yes. Same-kind peers start separate work; recovery cannot substitute an unavailable owner. Matches epic(flow-instances): singleton|collection cardinality; address by global id; isolation follows instance #1617 Theme 4 / D-10 durable-ownership floor.

  2. Unknown historical owners require explicit migration — yes. No guessing from available copies; known singleton history stays compatible; custom-id / collection history needs inventoried quiesced cutover. Matches epic(flow-instances): singleton|collection cardinality; address by global id; isolation follows instance #1617 Theme 5 (migration without inventing owners).

§7 close-review

Address vs owner split: Keep historical wire address-slot spelling (flowKind value = selected flow.id); additive SessionRecord/RequestRecord/ActiveRequestEntry.flowId as durable owner; stored flowKind stays actual definition kind. No parallel public selector. Blind copy of address into both fields correctly called out as wrong.

Convergence: One engine-owned owner check at transport admission, execution admission, and saved-record access — before enqueue materialization, active registration, preload, or adoption. Host-only guard would leave direct runAction unsafe; this closes that.

Boundaries hold:

Merge order: FIX-1321 first; converge #1600 before this impl merges; one coherent ownership PR (partial enforcement unsafe). Never-merge this spec PR. Individual-spec approval still needed (objective-only is already on #1617).

No two-direction fork vs #1631 / #1632 / #1617 / D-10 / #1600. No new D-n. No Jake ping.

— FSD Architect

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 608b673603

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread spec/FIX-1322.md

- **Transport admission:** `createInboundTransportHost` resolves the declared recipient and validates existing session/request identities before enqueue materialization or acceptance. The current unconditional queued request write must not overwrite a foreign request id. Preserve accepted/discoverable semantics and existing concurrency policy.
- **Execution admission:** direct `runAction`, local dispatcher, queue worker, continuation and retry must all reach owner checks **before** active registration, `latestRequestId`, user/org creation, history/resource preload or request adoption. Context construction must also guard its direct entry and re-check a create-race winner. An early check without an atomic create/adoption check is insufficient.
- **Saved-record access:** management authorization selects the stored owner's principal resolver before applying existing tenant/user/org rules. Session/request routes then reject an addressed-instance mismatch before state transitions or data access. State, resource and debug handlers use the same resolved owner to select schemas/providers. No owner-specific reader resolves by stored kind independently.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Use owner IDs for anonymous management filtering

When same-kind instances override authentication differently, the current host-wide listing and recovery paths cannot enforce this owner-specific rule: unauthenticatedFlowKinds() reduces open instances to flow.kind, and session listing, active-request listing, and interrupted-request sweeping filter on that set. An anonymous peer therefore makes every authenticated peer of the same kind anonymously visible and allows its requests to be marked interrupted. Require these authorization filters to use durable owner IDs or evaluate each record's owner resolver, while retaining flowKind only as an administrative grouping filter.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note for implementation — retained verbatim in §13 at 260372e and the Linear mirror. §7 saved-record access already requires stored-owner resolver selection, and §8 includes route-auth/recovery. The current unauthenticatedFlowKinds kind set is a concrete consumer to migrate, not an exception for host-wide listings or mutation. Administrative kind grouping never grants authorization.

Comment thread spec/FIX-1322.md

Use that shared logic at both admission levels:

- **Transport admission:** `createInboundTransportHost` resolves the declared recipient and validates existing session/request identities before enqueue materialization or acceptance. The current unconditional queued request write must not overwrite a foreign request id. Preserve accepted/discoverable semantics and existing concurrency policy.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Make queued request-ID admission atomic

For concurrent queued deliveries using the same caller-supplied request ID, validating existing records before materialization is a TOCTOU race: both admissions can observe absence, while the current host unconditionally registers the active entry and writes the request with "any". Require an atomic create-if-absent/lost-winner owner check plus owner-fenced active-entry registration and cleanup before acceptance; otherwise one instance can overwrite or deregister the other's work despite the promised collision refusal.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note for implementation — retained verbatim in §13 at 260372e and the Linear mirror. §7/§9 already promise no foreign request overwrite or acceptance, including independent execution rechecks; a pre-read alone cannot satisfy that contract. Include concurrent request creation, active-entry ownership and failure cleanup in the existing atomic admission work, rather than treating only pre-existing collisions as covered.

Comment thread spec/FIX-1322.md
2. Without `flowId`, preserve default singleton history only when the resolved definition is a singleton whose `id`, `kind` and stored `flowKind` all agree. Deployment inventory must establish this was historically a default singleton, not a custom-id instance now relabelled. Runtime string equality cannot discover deployment history.
3. Any ownerless collection/custom-id history requires an explicit per-record owner mapping and offline backfill, or a named `migration-required` refusal. One currently registered collection member proves nothing. A legacy `flowKind: engineer` must not be assigned to an unrelated billing instance whose id happens to be `engineer`.

Commission a documented **adapter-native offline cutover**, not a generic migration service: quiesce producers and execution; drain old queues/active work; back up and inventory session/request records plus FIX-1323's cells; map explicit record ids to known registered ids; validate kind, tenant, session/request and parent/lineage relationships; backfill owner fields without changing record ids; verify readback before resuming. An interrupted run is safe to repeat for already-identical mappings; a conflicting stamped owner stops it. No store-wide transaction or all-scope enumeration is assumed. SQL schema changes may add nullable legacy owner columns but must not blanket-backfill `flowId = flowKind` for collection history.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Migrate changed child-session keys

For an existing custom-ID cross-flow child, changing key derivation from destination kind to destination ID makes the next identical dispatch compute a different session ID. This cutover explicitly leaves record IDs unchanged, so backfilling flowId cannot make the new derivation find the old child; it creates a second session and forks its requests, resources, and lineage. Define either an owner-stamped legacy-key adoption rule or a complete re-key of the session and dependent records.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Spec-level persisted-contract fork surfaced in §12 at 260372e and the correct Linear mirror; neither proposed contract has been silently selected. If old custom-id cross-flow children exist, owner-only backfill with unchanged record ids cannot preserve repeat-key continuity under new derivation. Recommendation: one runtime derivation with explicit offline re-key of affected children/dependents, accepting changed saved ids/links and migration breadth; alternative: owner-stamped legacy-key adoption, preserving ids but adding persisted lookup/precedence compatibility. Current main lacks cross-flow child dispatch and #1600 is unlanded, so affected deployed history is not established. Verified empty inventory removes the conditional migration need; stable-link requirements favour adoption. Owner decision remains open; no POC loop trigger, implementation or approval inferred.

@jhoffner

jhoffner commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author

First bounded external spec-feedback batch handled against 608b673; published notes/open decision at 260372e and verified the existing FIX-1322 Linear document (0c55adbe-6a0c-4872-bf71-b8b1735eb118).

  • Cursor helper/performance advice and Codex anonymous-management filtering / concurrent queued admission details are retained in §13 for implementation. Existing shared owner admission still covers lifecycle, readers, typed clients and React.
  • Editorial slimming suggestions dropped with section pointers; goal-boundary and feat(dispatch): cross-flow fire-and-forget with named runtime miss (D-8) #1600 refresh/convergence reminders were already required by §10 and §8/§12. No new reply mode: correctly resolving the original owner permits its existing reply, while the wrong recipient refuses.
  • Codex child-key migration finding is a real conditional persisted-contract question, surfaced in §12. Recommendation/tradeoffs are in that section and the thread; no re-key/adoption contract selected without the owner's decision, and no affected deployed history assumed.

Accounting: one review round spent (0 → 1), specLevelFound=true. Handled external review/comments through 2026-09-07T20:01:08Z (Codex completion notice; findings/review at 20:01:03Z). FSD Architect and generated second-look commentary are agent feedback, not Jake's individual sign-off. This is not a cross-spec pass. No code, executable validation, goal proof, approval, merge or spec closure. Return to individual owner review with the §12 question visible; bot silence is not a gate.

Re-draft: fold EM delivery sequencing without changing issue scope or historical-child migration fork.
@jhoffner

jhoffner commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author

Approved

@jhoffner jhoffner added the spec approved This spec is ready for implementation label Sep 7, 2026
@jhoffner jhoffner closed this Sep 7, 2026
@jhoffner

jhoffner commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author

FSD Architect — epic index hygiene after individual approval.

Jake approved #1633 / FIX-1322 (Approved, spec approved, closed never-merged at 23e2f845). Fold the §4 running-index FIX-1322 row: leave “awaiting individual approval” / “In Spec Review” — mark Spec Approved (never-merge; no impl authorization).

Floor status: FIX-1321 (#1631) + FIX-1322 (#1633) both Spec Approved. Theme 8 atomic landing (FIX-1322 integration owner) still needs #1632 / FIX-1323 individual approval + the later cross-spec gate before coding. No new product fork vs D-10 / #1616 / #1600.

Open fence (do not invent): #1633 §12 historical-child-key fork is still unresolved on the approved head — re-key during quiesced migration (recommendation) vs owner-stamped legacy-key adoption. Spec text said resolve before sign-off; approval did not pick. Implementers must not infer. Either Jake picks, or defer to inventory: verified absence → documented preflight exclusion; presence → needs the locked alternative before cutover.

Cite D-10 / #1616. No Jake ping beyond this record.

— FSD Architect

jhoffner commented Sep 8, 2026

Copy link
Copy Markdown
Collaborator Author

Cross-spec alignment (2026-09-08)

Spec updated on spec/FIX-1322 at a0f4fbc (EM decisions from the epic's cross-spec coherence pass; direction unchanged elsewhere). Linear document synced.

  1. Historical child keys decided (new §6 Decision 3): affected cross-flow children and their dependent references are re-keyed during the quiesced offline migration, gated on the inventory preflight. No legacy-key adoption, no second lookup rule. §7 record-id preservation now applies only to non-affected records.
  2. PR feat(dispatch): cross-flow fire-and-forget with named runtime miss (D-8) #1600 landed (main, 2026-09-07T21:55Z, 7843f23f). Main already derives cross-flow child keys from the target kind and stamps metadata.dispatch.flowId; the new owner field and that stamp coincide on cross-flow arrivals, and the implementation must say so or read one from the other.
  3. FIX-1322 owns the flowId exact-owner list filter and flowId projections (session, request, ChildSessionSummary) plus their docs; FIX-1324 consumes them.
  4. One offline cutover checklist in persistence/overview.md, extended by FIX-1323; migration-required is the single stop condition.

Generated by Claude Code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

spec approved This spec is ready for implementation spec

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant