Skip to content

feat(modules/data): query cursors mint typed HandleRef + per-cursor mutex (re-opens #1490) - #1497

Merged
joelteply merged 2 commits into
canaryfrom
feat/data-query-handle-migration-v2
May 31, 2026
Merged

joelteply merged 2 commits into
canaryfrom
feat/data-query-handle-migration-v2

Conversation

@joelteply

Copy link
Copy Markdown
Contributor

Re-opens #1490 which auto-closed when its base branch (feat/command-envelope-pattern) was deleted on merge. Same content; new branch targeting canary.

What lands

Same as #1490 — two commits:

  1. feat(modules/data): query cursors mint typed HandleRef + accept envelope shape — additive migration of data/query-open/next/close from string-id pattern to typed HandleRef with back-compat queryId field
  2. fix(modules/data): per-cursor mutex serializes concurrent query-next — fixes the read-then-async-then-write race that the multi-thread concurrency test caught ("page 1 served 8 times")

7 multi-thread stress tests + 10 envelope/migration tests pin the invariants. See DATA-CURSORS-MODULE.md for the full design rationale.

Original PR

Full description + discussion was on #1490 which is now closed (cannot be reopened — head branch was deleted alongside its base).

joelteply and others added 2 commits May 30, 2026 19:29
…ope shape

Per Joel:
> "You can work out the kinks and reinforce patterns by picking good
>  example commands which push the envelope, npi"

The hand-rolled string `queryId` pattern in `data/query-open` /
`data/query-next` / `data/query-close` predates HandleRef + the typed
envelope. It's the perfect kink-finding migration target: a REAL
long-running stateful operation that currently passes a stringly-typed
session id around, with no kernel-level typing of the handle's owner,
type, or lifetime.

# What this PR does

1. `data/query-open` now MINTS a `HandleRef { owner: "data", id: Uuid,
   type_tag: "data::QueryCursor", created_at_ms }` via
   `CommandResponse::with_handle`. Wire shape gains a top-level
   `handle` field alongside the legacy `data.queryId` (the SAME UUID
   — identity invariant covered by test).

2. `data/query-next` and `data/query-close` accept BOTH shapes via the
   typed envelope:
   - **new canonical**: `{ handle: HandleRef }` on the
     `CommandRequest` envelope
   - **legacy back-compat**: `{ queryId: "<uuid-string>" }` flat in
     the params body

   A single resolver (`resolve_query_cursor_id`) walks the envelope
   first, falls back to the legacy field, and fails loud when neither
   is present — naming both supported shapes so the caller can
   self-correct.

3. The resolver VALIDATES handles aggressively:
   - **wrong owner** → typed error naming both the offending owner and
     the expected (`data`). The grid interceptor is supposed to route
     calls back to the actual owner before dispatch; arriving here
     with the wrong owner means either the routing misfired or a
     caller hand-crafted a bogus handle.
   - **wrong type_tag** → typed error naming both the offending tag
     and the expected (`data::QueryCursor`). Within-module
     discriminator: a future `data::Migration` handle threaded through
     the cursor surface would silently look up nonsense in the
     paginated_queries map; we catch it here.
   - **unknown handle** → typed error naming the cursor + likely
     causes (closed via `query-close`, evicted by future TTL,
     previous process instance).

# What this PR explicitly does NOT do

- Does NOT drop the legacy `queryId` field from the open response or
  the next/close inputs. The migration is additive; consumers
  migrate at their own pace. A follow-up drops `queryId` once every
  TS consumer threads the handle.
- Does NOT change the DashMap key type from `String` to `Uuid`. The
  HandleRef carries a `Uuid` on the wire; the data module
  string-converts at the lookup boundary. Smaller surgery, same
  identity semantics.
- Does NOT add envelope plumbing to OTHER data handlers (create,
  read, update, delete, query, vector/*). Those are one-shot
  operations; they don't need handles. Only long-running stateful
  surfaces benefit from HandleRef.

# Kink-finding outcomes (real bugs the migration design caught)

- Empty-params query-next used to deserialize to `query_id: ""`
  (required-string field). Now BOTH fields are optional and the empty
  case is reachable — without a typed error it would silently
  no-op-404. The resolver names both supported shapes in the error.
- Cross-module handle confusion (owner="chat" reaching the data
  handler) was previously impossible because there was no handle —
  only an opaque string. With typed handles, the validation surface
  exists. The test forces it.
- Cross-resource handle confusion (owner="data" but
  type_tag="data::Migration") same: the test forces a future failure
  mode that the type_tag discriminator was DESIGNED for.

# Patterns reinforced

- **Typed envelope at every typed surface**: every new handler from
  here on parses `CommandRequest::<P>::from_value(params)` at the
  entry. The cross-cutting `handle` / `sessionId` / `userId` fields
  are free.
- **CommandResponse::with_handle for any minted handle**: a single
  fluent expression replaces hand-rolling the JSON. Wire shape stays
  flat — handle lives at top level, data lives nested or flat
  depending on the back-compat needs of the response.
- **Validate the owner AND the type_tag before lookup**: the type
  system can't catch a hand-crafted bogus handle; the resolver must.
  This pattern goes into every future module that consumes handles.

# Tests (10 new + 8 pre-existing, all 18 pass)

New (`modules::data::tests::`):
- `query_open_returns_handle_alongside_legacy_query_id` — additive
  migration: both shapes present
- `query_next_accepts_handle_in_envelope` — new canonical path
- `query_next_still_accepts_legacy_query_id_field` — back-compat
  preserved
- `query_next_rejects_handle_with_wrong_owner` — kink
- `query_next_rejects_handle_with_wrong_type_tag` — kink
- `query_next_rejects_when_neither_handle_nor_query_id_provided` —
  empty-params surfaces typed error
- `query_next_with_unknown_handle_returns_handle_not_found` — stale
  handle typed error
- `query_close_accepts_handle_in_envelope` + after-close stale check
- `query_close_still_accepts_legacy_query_id_field`
- `full_round_trip_open_next_close_via_handles_only` — end-to-end
  through the new canonical shape, 12 rows / 3 pages

Pre-existing (untouched, all pass):
- `test_paginated_query` — legacy `queryId` round-trip via the same
  path; no regression
- `test_paginated_query_count_exact` — same

# Stacks on

PR #1486 (CommandRequest/Response envelopes — used at every entry +
exit of the migrated handlers).

# References

- [docs/architecture/MODULE-ARCHITECTURE.md](docs/architecture/MODULE-ARCHITECTURE.md)
  §10 (recursive bootstrap), §5 (composition)
- PR #1485 (cell shapes — HandleRef used here)
- PR #1486 (envelope pattern — used at every handler surface)

Co-Authored-By: Claude Opus 4.7 <[email protected]>
…+ concurrency tests pin it

Per Joel 2026-05-30: "Each persona exists in its own threads."

# The bug the concurrency test caught

Original `handle_query_next` pattern:
```rust
let state_info = self.paginated_queries.get(&cursor_id).map(|s| (s.current_page, ...));
// ^ DashMap shard lock released HERE
// ... async adapter.query() runs with NO lock ...
self.paginated_queries.get_mut(&cursor_id).map(|mut s| s.current_page += 1);
```

Under N concurrent next-calls on the SAME cursor (canonical
multi-persona scenario, or one persona retrying), every call reads
`current_page=0`, every call computes the same offset, every call
queries the same first page, every call writes `current_page=1`.
Result: 8 concurrent calls all return pageNumber=1; the cursor's
final state is current_page=1 instead of current_page=8.

The new `same_cursor_concurrent_next_does_not_corrupt_state` test
caught this with the assertion *"page 1 served 8 times — the cursor
advanced through it MORE than once, indicating a lost
serialization"*. The fix landed in the same commit.

# The fix

Wrap each cursor's state in a `tokio::sync::Mutex` held across the
async query. Concurrent next-calls on the SAME cursor serialize
(the substrate's promise: page numbering stays monotone).
Concurrent next-calls on DIFFERENT cursors stay fully parallel
because each cursor has its OWN mutex — DashMap's lock-free read
path is preserved.

```rust
paginated_queries: DashMap<String, Arc<tokio::sync::Mutex<PaginatedQueryState>>>
```

`handle_query_next`:
1. Clone the `Arc<Mutex>` OUT of the DashMap shard (brief read lock,
   no contention)
2. `lock().await` the per-cursor mutex
3. Snapshot the read-only fields needed for the query into locals
4. Run the adapter query (mutex held — only ONE caller advances at
   a time)
5. Update state on the still-held lock (atomic with the read)

`handle_query_close` unchanged: `DashMap.remove()` is atomic; if a
concurrent next is mid-flight, it holds an Arc keeping the Mutex
alive — its mutation succeeds against an orphaned state map that's
never read again. From the caller's view: close said success;
in-flight next returns its now-meaningless page; the cursor is
unreachable for subsequent calls. Benign and arguably the correct
contract — callers shouldn't race close with next.

# Substrate doctrine reinforced

Joel's reminder is doctrine, not just a one-off bug fix. Every
ServiceModule that holds per-resource mutable state across an
`.await` MUST hold a per-resource lock for the read-then-async-
then-write window. Module-wide locks are wrong (serialize all
resources). Per-resource locks via `DashMap<Id, Arc<Mutex<State>>>`
are the canonical pattern.

# Concurrency stress tests

Both run with `flavor = "multi_thread", worker_threads = 4` so
tasks actually preempt each other on distinct OS threads.

## `cursors_are_isolated_under_concurrent_open_and_next` (20 personas)

Phase 1: 20 concurrent `query-open` calls. Asserts all 20 cursors
mint DISTINCT HandleRef.id UUIDs.

Phase 2: 20 concurrent `query-next` calls, each against its own
cursor. Asserts each cursor's first page returns pageSize items
and pageNumber=1 (per-cursor state, not shared).

Phase 3: close half the cursors in parallel; assert the OTHER half
STILL serves page 2 correctly. Close MUST be per-cursor — sibling
state untouched.

## `same_cursor_concurrent_next_does_not_corrupt_state` (8 callers, 1 cursor)

30 rows, pageSize 5 → 6 valid pages. Fire 8 concurrent `query-next`
calls against the SAME cursor handle. Asserts each non-tail page
(1..=5) is served AT MOST ONCE — the per-cursor mutex serialized
the advance. Without the fix, page 1 was served 8 times.

# Tests (20/20 pass; 1 ignored onnxruntime)

All 10 pre-existing HandleRef migration tests still pass — no
regression from the locking restructure. The 2 new concurrency
tests pin the invariants going forward.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@joelteply
joelteply merged commit e304217 into canary May 31, 2026
3 checks passed
@joelteply
joelteply deleted the feat/data-query-handle-migration-v2 branch May 31, 2026 00:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant