Skip to content

feat(workflows): record identity must not be capped by a smallint map_index in long-lived streaming flows #717

Done

Description

@rcbevans

Problem

A streaming flow's record identity is a 16-bit index, so one flow can address at most 32,767 records — and crossing the bound is a terminal rejection, not a degradation.

Every record a chain_source emits is stamped with map_index and trace_id. The index is load-bearing for three separate mechanisms, all of which key on it:

  • the emit's idempotency key wf:{flow}:emit:{map_index}:{step} (so a re-emit of a committed page collides instead of duplicating),
  • the step ledger's claim arbiter UNIQUE (flow_id, step_key, COALESCE(map_index,-1), attempt),
  • sibling discrimination inside a map/route/chain fan-out (and the signals table's hold identity).

jobs.map_index is smallint, so the domain is 0..32767. A record at 32768 does not wrap, degrade, or park — the emit door raises MapIndexExhaustedError; the deterministic route terminalizes the source; the run is over, and re-running cannot help because the identity is the index.

That makes the chain surface unusable for the workloads it is aimed at. A long-lived streaming source over a growing population is expected to pass 32k records in a single run; the documented coverage of a real page/fan-out/recurse workload is routinely 100k–200k. The failure mode is the worst kind: the flow looks healthy until record 32,768, then dies terminally with no partial progress and no way to resume.

The naive local remedies all reintroduce exactly the orchestration complexity a flow was adopted to remove:

  • Hash into 32,768 buckets. examples/workflows.py:179-187 ships map_index=abs(hash(doc_id)) % 32000, which the assessment notes as a demo (it is a collision risk in a real identity). Modulo identity collides; a collision is a UniqueViolation that rolls the page back whole, i.e. record loss surfaced as a crash.
  • Shard into N flows. Each shard needs its own cursor, its own run row, its own overlap policy, and a coordinator that knows when the shard set is complete — a second recursive orchestration layer above the flow graph, plus N times the run-history rows.
  • Truncate. Not a remedy; silent data loss on a reporting path.

Evidence

The ceiling is real and typed:

  • src/taskq/workflows/_types.py:74 — MAP_INDEX_CEILING: Final[int] = 32767.
  • src/taskq/workflows/_emit.py:27-33 — module docstring: "The ledger's claim-arbiter column is a SMALLINT — the ceiling is 32767. A page whose record's map_index crosses it raises MapIndexExhaustedError at the emit door … the deterministic route terminalizes the source."
  • src/taskq/workflows/_emit.py:162-176 — MapIndexExhaustedError's contract: the poison record kills itself, never its mates; the valid page-mates commit first, then the error is raised naming the record.
  • src/taskq/workflows/_emit.py:393-415 — the poison filter (0 <= map_index <= MAP_INDEX_CEILING), the all-poison refusal before any work, and the "the record's identity cannot ride the ledger's smallint arbiter" message.
  • src/taskq/workflows/_emit.py:235-269 — the emit child insert stamps map_index into jobs, and the idempotency key wf:{flow_id}:emit:{map_index}:{step_key} is derived from it.
  • src/taskq/migrations/01.00.24_01_pre_workflow_columns.sql:57-91 — ADD COLUMN IF NOT EXISTS map_index smallint NULL on jobs and jobs_archive, with the comment "Retry-in-place preserves (parent_id, map_index)".
  • src/taskq/migrations/01.00.24_02_pre_workflow_tables.sql:66-111 — wf_step_ledger.map_index smallint NULL and UNIQUE (flow_id, step_key, COALESCE(map_index,-1), attempt), documented as "one row per (flow, step, map_index, attempt)".
  • src/taskq/migrations/01.00.34_02_pre_wf_signals_map_index.sql:39-64 — the signals/hold identity also carries map_index smallint.

The refusal is pinned, i.e. the behaviour is deliberate and tested:

  • tests/test_wf_attack_emit.py:236-315 — test_f_emit_2_the_map_index_ceiling_is_a_typed_documented_refusal emits [32767, 32768] and asserts (a) the raised type is not a raw driver error, (b) the message names 32767, (c) exactly one child committed (the valid mate survived), (d) the cursor advanced past the poison page. This is the proof that the ceiling is a hard terminal, not a warning.

Why it cannot simply be widened without thought:

  • docs/guides/workflows.md:2174-2186 § "THE REFUTED-CLAIM DISCIPLINE: map_index is load-bearing" — the pre-stamp shape emitted 200 records and observed 198 UniqueViolations, because every record's child collided onto one row. Any replacement identity must preserve sibling discrimination, the idempotency key's determinism, and the one-query lineage (trace_id), or the fix re-opens a proven defect.

Required

Either remedy is acceptable; the engine's maintainers should pick one and document the tradeoff. Both must be additive for already-written rows.

A. A non-smallint record identity.

  • Widen the arbiter and idempotency key to a type that can address a long stream (bigint or better), or introduce a stable opaque record token (UUIDv7 / ULID) minted at emit alongside an optional ordering hint.
  • map_index may remain as an ordering/diagnostic column, but it must stop being the identity that arbitration and idempotency key on.
  • Sibling discrimination and the idempotency key must be derived from the new identity deterministically, so a re-emitted committed page still collides rather than duplicating.

B. A certified partition handoff.

  • A source can declare partition boundaries (or the engine derives them); when a partition's identity space is exhausted, the engine materializes the successor source/flow with the cursor handoff already applied, the lineage preserved (trace_id continuity, a parent/partition pointer on the run), and no gap in the emit sequence.
  • No modulo hashing, no silent truncation, no shard-count constant an operator must compute correctly.
  • The handoff must be crash-safe at the boundary: a kill between the last record of partition N and the first emit of N+1 loses nothing and duplicates nothing.

Both. If any hard ceiling remains, hitting it must be typed, documented at the author's reading surface, and non-destructive to committed pages — the current poison semantics are the right shape, but the number should be far beyond any realistic stream.

Acceptance criteria

Fleet-level, on real Postgres, with crash windows.

  • Scale. A flow emits 200,000 records in one logical run (either one run, or one partitioned family with a proven handoff) with:
    • zero MapIndexExhaustedError,
    • zero duplicate (flow, record identity, step_key) rows,
    • every record's chain rows terminal exactly once,
    • no page split or skipped tail at any 16-bit boundary (explicitly assert continuity across 32,767 → 32,768 and, for the partition remedy, across every declared boundary).
  • Deterministic identity. Re-emitting the same committed page (simulating a lost acknowledgement) produces a collision and zero duplicates — the property test_f_emit_2 protects today must survive the change.
  • Lineage. From any record, the trace drill-down returns its full chain and its partition (if partitioned), in one query — the trace_id contract stays one-query.
  • Crash at the boundary. Kill the worker (real backend termination) between the last record of partition N and the first statement of N+1; on reclaim: zero records lost, zero duplicated, cursor handoff applied exactly once, successor partition not double-created.
  • Retry at the boundary. A page that fails and re-pends across a boundary resumes at the same identity, not at a re-computed one.
  • Mixed-version. A flow created before the change resumes under the new scheme without re-emitting committed pages; or a documented, tested migration states the boundary and its cost. jobs/jobs_archive/wf_step_ledger/wf_signals all agree on the identity's width after the migration (assert with a schema test on all four).
  • Existing pins stay green. tests/test_wf_attack_emit.py, tests/test_wf_emit_tx_pins.py, the perf bands, and the populated-migration chain test.
  • Docs. The ceiling (or its removal) is stated where a map/chain author reads — the emit/chain docstrings and the workflows guide's map_index prose — and the identity's contract (what discriminates siblings, what keys idempotency) is stated once, normatively.

Impact

The chain surface's value proposition is long-lived record streaming. A per-flow 32k ceiling bounds every consumer whose population is a table that grows, and because the exhaustion is terminal the operator sees a dead run rather than a degraded stream — with the run history showing the flow as fine up to the exact record where it isn't.

Consumers cannot absorb this locally without paying exactly the price flows were adopted to avoid: modulo identity risks silent record loss, and partitioning means N cursors + N run rows + a completion coordinator above the graph. A consumer that already implements recursive successors with a typed cursor has nothing to gain from migrating to a shape that tops out at 32,767 and then dies.

Related: #716 (gating execution-policy surface), #718 (backpressure).

Environment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementimportant

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions