Repository navigation
feat(workflows): adoption hardening - #715
Merged
Merged
Conversation
…'s own rules The fold-parity drives beyond New York hardcoded their transition dates, and a hardcoded date is a premise about a zone RULE - a fact of the installed zone database, whose vintages disagree: Cuba stopped returning to standard time, so the 2026-11-01 Havana fall-back the midnight pin was built on exists in older zoneinfo only. On current vintages that transition does not exist, the drive has no repeated range to cross, and the pin reds. The drives now discover the zone's fall-back in a fixed window from the installed zoneinfo - the earliest matching transition, characterized by the scheduler's own repeated_range_bounds - and date every seed, tick and bound from it; the discovery reads neither the runner's clock nor its TZ environment. taskq.cron's fold accounting itself is unchanged: every shape in the family holds on it at the base commit. The family grows the mirror shapes: a fold-1 seed inside the midnight-crossing range (the uncovered prefix fires, the twin-covered remainder never re-fires, next_fire_at lands the range end), a repeated range ending at local midnight (America/Santiago: the walk lands the next date's first wall), and a same-day America/New_York control, alongside the midnight-starting Havana, southern Sydney and half-hour Lord Howe drives. Verified: the fold-parity family green solo and under three random seeds (17, 4242, 90210); green on a zone database that still contains the removed transition (tzdata 2024.1 via PYTHONTZPATH); the cron and rt-cron families green serially at nice -n 5; ruff check, ruff format --check and pyright clean. The two midnight pins watched red under the injected defect they guard against (the coverage walk skipping a plan whose next fire sits on a midnight wall) and green without it.
…nst silent re-dating The discovery supplies the parity drives' seed, tick and bound arithmetic, so an output that is wrong but plausible keeps a drive green on a shape the installed zone database does not have. FallbackTransition.range_start is documented as a naive dated wall but carries the transition instant's fold=1 while range_end carries fold=0. str() renders both identically and datetime equality ignores fold, so `range_start.replace(tzinfo=zone)` - the ordinary conversion of a naive wall - silently resolves to the fold-1 (later, post-transition) instant: a schedule seeded from it starts on the wrong pass of the fold. fold_instant exists, but the exported wall must not carry a second meaning the documented naive-wall reading resolves to silently. fallback_transitions is cached and returns the cached list object, so every caller shares one mutable value. A consumer that sorts, reverses or extends the result for its own drive re-dates every later caller, the parity drives included: Havana's earliest transition becomes 2037 instead of 2018 while the drive stays green. An immutable result, or a per-call copy, removes the alias. The same file pins what holds: each characterized range against an independent PEP 495 ambiguity oracle (half-hour repeat, 45-minute offset, midnight-starting, midnight-ending, month/year-crossing, leap-day and two-hour folds), the half-open window at both edges, the loud failure for a zone with no fall-back, TZ independence, a fold-1 seed at an interior slot (the midnight pin seeds only the range's first fold-1 slot), and the steady-state drives' absolute delivery count across 30-, 60- and 120-minute repeats (their own count compares fired_total + twins, so a skipped fold-0 fire lowers both sides together). Verified: the two named tests red alone and in the combined run; the other twenty-six pass serially, under -p randomly seeds 17 and 4242, under -n 4, and on the tzdata 2024.1 database (PYTHONTZPATH=/nonexistent); the parity family stays green in every one of those runs. ruff check, ruff format --check and pyright clean.
…s out a fresh list per call, and raises its premise failure explicitly The discovery's stored walls carried the seed wall's fold (the transition instant resolves as a fold-1 wall, and repeated_range_bounds copies that fold into the range start), so the documented naive-wall reading of range_start silently resolved to the post-transition pass; both walls normalize to fold=0 at construction - a wall's two passes are named by the fields, not the fold. The memoized scan returned its own list object, so one caller's reordering re-dated every later caller's discovery; the scan now caches a tuple and the public name returns a fresh list per call, the caller's to order or trim. The premise failure of the four shape selectors was a bare assert (an IndexError under python -O); the selectors share one matcher that raises the named premise error - zone and false premise - independent of optimization flags, and the duplicated raise blocks collapse into it. The discovery attack's wall-resolution pin compared a fold-carrying ZoneInfo wall to its UTC rendering with ==; a fold-carrying wall never compares == to a different-tzinfo rendering of either of its own resolutions (PEP 495's mixed-tzinfo comparison), so both sides normalize to UTC - the codebase's cross-zone comparison rule - before the equality. Verified: the discovery attack family green in all four orders (current tzdata; tzdata 2024.1 via PYTHONTZPATH; TZ=Pacific/Kiritimati with random seed 4242; -n 4); the fold-parity family (26) green on both zone databases; the rt-cron family green serially at nice -n 5; ruff check, ruff format --check clean; pyright clean on the touched files.
…nstants ignore the stored fold The wall resolution check compares instants after both sides normalize to UTC; a wall carrying fold=1 resolves to the fold-1 field, so the check still catches the defect it exists for. The fold-0/fold-1/range-end/ last-slot fields apply the fold explicitly and answer the same instants for either stored-wall fold, so the drives' seeds, ticks and bounds do not move with the wall's fold. Verified: 30 tests green serially, under PYTHONTZPATH=/nonexistent with tzdata==2024.1, under TZ=Pacific/Kiritimati with random seed 4242, under -n 4, and with random seed 90210; the fold-parity family (26) green on both zone databases; the rt-cron family (161) green serially at nice -n 5; ruff check, ruff format --check and pyright clean on the three files.
…atcher, and the guards read as guards The attack file's shape selector re-implemented the parity family's matcher with a bare assert (an IndexError under python -O, where the named premise failure never fires) and a hardcoded window; it now routes through the parity family's matcher and window constants - one source of truth for the discovery window and the premise refusal. The module and wall-pin docstrings described the cured defects in the present tense; they now state the guards (a fold-carrying stored wall would silently resolve to the later pass; a shared cached list would re-date every later caller) and name the invariant each pin refuses. The cross-zone comparison comment says "ambiguous" - wall ambiguity is the discriminating property of PEP 495's mixed-tzinfo comparison, not the stored fold - and the two "added" references name the pin they point at. Verified: the attack file and the parity family green in all four orders (current tzdata; tzdata 2024.1 via PYTHONTZPATH; TZ=Pacific/Kiritimati with random seed 4242; -n 4); the rt_cron family green serially at nice -n 5; under python -O the shape selector raises the named premise error, not IndexError; ruff check, ruff format --check clean; pyright clean on the touched files.
…-only worker boots; a cancelled run's read is loud; validate() returns its diagnostics * step() folds a WorkflowActor handle's EXPLICITLY declared max_attempts/retry_kind into nodes that do not declare their own — the decorator's own defaults are sentinels, not declarations, so an undeclared actor wiring leaves the node byte-identical (max_attempts 3, retry_kind None). * _load_actor_registry boots a workflow-only module (a mounted WorkflowApp, an empty actor registry): the gate counts workflow-execution capability from the same inputs the dispatch fence reads; the refusal remains only when neither ingredient exists and names both. The boot pin proves the loops start and the projection yields the workflow cohorts. * FlowRunner.result() on a cancelled run raises WorkflowRunCancelledError — a WorkflowRunError subclass carrying the terminal status and the cancel reason; the guide's reads section documents cancelled alongside failed. * CompiledWorkflow.validate() returns the same diagnostics validate_compiled returns (empty when clean; the errors still raise); the api-reference row and the doc-ingest zero-warning sentence point at the return value. Verified: the fold pin asserts the node's stored max_attempts/ retry_kind and fails before the fold lands; the loader pins assert the empty registry boots and the refusal names both ingredients; the cancellation pin asserts the raised verdict's status, reason, and family; the diagnostics pin asserts the returned errors-and- warnings pair. The capacity-surface, validate, run-key, childflow, cli, and worker-bootstrap families pass; ruff and pyright are clean.
…un key's error carries the claim verdict * FlowRunner.create_flow() on an unmigrated schema raises the typed SchemaNotMigratedError — the same translation the packaged run() door does, the raw asyncpg traceback replaced by the remedy. The translation wraps the WHOLE create transaction (the create-atomicity law intact — the retry-completes-the-census pin passes). * run() over a terminal run's key re-raises the prior run's error with claim_verdict="existing-terminal" attached (a typed attribute on WorkflowRunError) — the handler reads the refusal as the replay face, not a fresh failure; the guide's run-key section names the attribute. Verified: the pins assert the raised class (SchemaNotMigratedError with the schema named) and the attached verdict; both fail before the cures land and pass after; the run-key family passes.
* The run key: key= is the canonical spelling on both run doors (create_flow and the packaged run); run_key= rides as the alias, and a disagreement is refused. * The capture policy: capture_policy= is canonical on @app.actor and @app.workflow; capture= rides as the alias on both (the workflow decorator's established spelling), and a disagreement is refused. * The reservations term accepts a list, a tuple, or None on every face (the actor, the step, the route arm); the node decl stores the tuple either way. * The on_failure absorbing policy's canonical name is collect (the failures fan in as the typed partial); the maybe spelling stays accepted, and the guide, the coverage map, and the worked examples name one form. * The second-denominated terms (timeout_s, budget_s, cache_ttl, result_ttl) accept a timedelta or a bare number of seconds through one normalizer — the seconds number is the one stored form; start_to_close stays timedelta-only (the declared type the vanilla actor pins, never a silent coercion). * HitlClient.list accepts run= (canonical) and flow_id=; the guide's vocabularies state the run identity's per-surface spellings, the hold as the user-facing concept, and the wiring verbs' term matrix. Verified: the pins assert the aliases' acceptance, the disagreement refusals, the stored seconds form, and the identical run claimed by either spelling; the capacity-surface, run-key, validate, and propagation families pass; ruff and pyright are clean.
… state the product's behavior * flows list renders every run: the listing's query carries the root row's actor column the render reads (a vanilla root row in the listing no longer raises KeyError 'actor'). The pin inserts a vanilla root row and asserts the listing renders it by name. * The upgrading guide's migration step states the phased sequence (pre while the workers roll, post once by hand after) with the rolling-deploy pointer; a bare migrate up applies both phases at once, and the old-worker breakage that follows is named. * The fairness guide's VALIDATE section gives the runnable form: the violator-finding query, the restating fix, and the ALTER TABLE ... VALIDATE CONSTRAINT — all three verified against a live database (a staged violator is found, fixed, and the constraint validates). * The workflow migration guide's section states the exception its checksum-frozen header cannot: the v1 no-post-phase rule protects the row shape a pre-workflow worker reads, and the fairness post phase changes no column and no row shape, so that guarantee holds with the post phase landing. * The two leader-sweep arms that ship on by default (the workflow outbox retention at 24h, the step-cache sweep at 1h) are stated with their defaults and their start-at-upgrade behavior; the other five history arms stay off until a period is set. * The adoption checklist is one section in order: pin bump, migrate status (pending count, zero drift), the pre-phase job, the worker roll, the post phase by hand, the VALIDATE, the status + smoke flow. * The Postgres floor is stated once (installation.md: 15 minimum, 15-18 covered by CI); the doc-ingest fence names the floor and pins the postgres:18-alpine image. * The run explorer's section states the setup: the auth posture, the admin-actions flag for the resolve/deliver/cancel actions, and the 501 face when the admin process mounts no WorkflowApp. * The API tour states the placement rule inline: the node's queue is the wiring's decision (step(queue=...), default default), the decorator's queue declares the handle's own cohort — verified against the compiled graph (the nodes land on default). Verified: the cli family passes (the listing renders the vanilla root by name); mkdocs builds strict; ruff and pyright are clean.
… without process narration Every pack header, docstring, and comment in tests/ now states the invariant the pin holds and the behavior it asserts, in plain product voice: the process-narration headers, the finding-number prefixes, the ticket-number citations, and the investigation-record paragraphs are replaced by the behaviors' own names. The in-file finding ledgers that resolve within their own file (the timer pack's T1-T6, the cancel pack's TOOTH teeth, the sweep-cursor walk's front) stay; the scenario labels (tick T1/T2) stay. Verified: the id-pattern sweep reads zero; the wf pin packs, the cli pins, the evidence-door pins, the web-admin suite, and the system-tier runs pass (three serial batches, 534 tests); ruff, pyright, and the strict doc build are clean.
…not their history * The round-numbered and ticket-numbered file names carry their subject now: the adversarial probes' packs are probes_<subject>.py, the process-numbered pin packs are named by the contract they hold (run-view, childflow, engine claim fences, step-cache/timer contracts, teardown, route cures, typed-route contract, evidence-door contract, docs), and the emit/progress/router packs name their own faces. Every reference updated in the same pass: the per-file lint config, the coverage walk's file list, the ctx-annotation pin's module list, the guides' citations, and the sibling packs' cross-references. * The probes' collection contract is preserved: tests/conftest.py's collect_ignore_glob keeps the probes_ modules out of the default collection (the old dash-named files' N999 ignores carried that contract; the valid module names would otherwise have changed the default battery's shape), and the per-file lint config drops the N999 entries the old names needed. * The test function names drop their embedded process ids; the suite's adversarial-family prefix stays (it names the subject). * The xfail markers' reasons, the assertion messages, and the recorded cancel/wait reasons state the failure mode and the invariant, not the review corpus; the runtime string ids (the workflow names and the call ids in the fixtures) are plain now. Verified: the id-pattern sweep reads zero on all four classes; the renamed packs, the probes by explicit path, the ctx-annotation pin, and the evidence-door pins pass; the default collection count is unchanged (the probes excluded by the glob); ruff, pyright, and the strict doc build are clean.
Pins the laws the adoption cures state at the inputs that separate a declared term from a default: a step's explicit attempt budget against a handle's declaration, the workflow decorator's capture alias, the route arm's duration and reservations forms, the replay verdict's absence on a fresh failure, and the cancelled read when a cancel lands inside its status window.
… their defaults * step()'s max_attempts carries the None sentinel (unset) instead of a value default: the resolution reads the handle's DECLARED attempts (seven reaches the node; the decorator's own default does not — it is not a declaration), and the step's explicit three now overrides a handle declaring seven, the same override every other explicit step term has. The sibling folds audited: max_concurrent, reservations, result_ttl, start_to_close, priority, and retry_kind are already None-structural. * Both capture-policy spellings carry the None sentinel on both decorators (@app.actor, @app.workflow): two declared values that disagree are refused naming both spellings and values — never a silent winner decided by argument order; unset spellings resolve to the errors-only default. * RouteArm normalizes at construction: reservations=None stores the empty tuple (the accepted nothing-reserved spelling), and a timedelta result_ttl stores the seconds number the projection's column expects. Verified: the declared-term seams pass (the explicit-three override, the capture disagreement refusal, the arm's timedelta projected as seconds); the identity guards hold (an undeclared wiring stores max_attempts 3, retry_kind None); ruff and pyright are clean.
…at ended * result() reads the terminal row first and reads its own status column: a row terminalised cancelled or failed raises the typed verdict from the row. A row the first read saw live or empty gets one status read and one bounded row re-read — the cancel or failure that committed during the read shows there and raises its verdict; a run genuinely still working (held, queued) keeps the honest None. * run() attaches claim_verdict to the re-raised error ONLY on the replay face (existing-terminal): a first run's failure carries the None the class contract states. Verified: the run-verdict seams pass — the fresh failure's verdict is None, the cancel landing inside the read raises the cancelled verdict with the interleaving hook proving the race was real, and the replay verdict pin stays green; the seeds 17 and 4242 and a -n 4 run agree; ruff and pyright are clean.
workflow_execution_capable() reads the boot projection's actual output: at least one workflow cohort must project for a worker to boot workflow-capable. An imported-but-empty app — or one whose every workflow fails its compile — projects no cohort, and a worker holding only it refuses at the loader (the earliest stage) with the compile failures named; the projection returns its failures alongside the cohorts (project_with_failures), and the loader's refusal message names both ingredients plus the defect. A real workflow-only module boots unchanged. Verified: the refusal pins (the empty-app module; the all-fail-compile module naming its defect) fail on the pre-cure tree and pass after; the workflow-only boot pin and the boot-projection pin stay green; the cli and worker-bootstrap families pass; the guide's boot-projection line states the new gate; ruff, pyright, and the strict doc build are clean.
Pins the ended-run contract from both sides: a flow whose terminal node succeeded beside a failed fire-and-forget branch still raises the run's failure, a cancelled run whose terminal node succeeded still raises the cancelled verdict, and the replay verdict rides only the replay face — a fresh failure and an adopted live run's failure carry none, while a replayed cancelled run carries existing-terminal.
An imported app that declares no workflow and a module that imports no app are two different boot defects with two different remedies; the refusal for the first must not claim the second.
Only two declared values that disagree are refused: both spellings unset, one declared, and both declared with the same value all resolve — the None sentinel separates unset from a declared default, and equality is agreement.
Adds the empty-graph input (a builder that wires nothing and returns None — the app is imported, the workflow compiles to zero nodes) and pins that two broken declarations are both named, not just the first.
result()'s read is ONE statement: the run's terminal status and the terminal node's row in the same round trip (the verdict's source and the payload's source share one snapshot — a flip cannot land between them). The run's status decides: succeeded decodes the terminal row's result; failed/cancelled raise their typed verdicts (the terminal row supplies only the payload — a succeeded terminal beside a failed sink branch raises the failure, a cancelled run whose terminal succeeded raises the cancellation). A run the snapshot still calls live keeps the bounded re-read: the status read plus one row re-read — the flip that committed during the read shows there and raises its verdict; a run genuinely still working keeps the honest None. Verified: the verdict-seam pins pass — the succeeded-terminal-beside- failed-sink, the cancelled-run-whose-terminal-succeeded, the cancel window, the fresh/replay verdicts, and the clean read; seeds 17, 4242, 90210 and a -n 4 run agree; the childflow and demo families pass; ruff and pyright are clean.
…tes once per boot * The loader distinguishes the two nothing-dispatchable states: an app IS mounted (the refusal names the defects — the compile failures, or 'the app declares no runnable workflow' for the empty app and the builders that wire nothing); no app at all keeps the both-ingredients message. The projection records the empty-graph case (a workflow whose compile succeeds and produces no cohorts) so the state is named, never collapsed into 'nothing imported'. * The projection computes once per boot and shares the result: the cache invalidates at the app registration and at the registry reset, so a broken module's diagnostics read once, not once per face. * The loader wraps the projection's conflict refusals (one actor, two queues/capacities across healthy declarations): the operator reads the reason and the boot exits 1, never a traceback. * The workflow decorator refuses the capture disagreement BEFORE the registration: a caught ValueError leaves no half-registered workflow. Verified: the boot-gate diagnosis pins (the empty app, the empty graph, both failures named) fail on the pre-cure tree and pass after; the no-app refusal pin and the workflow-only boot pin stay green; the cli, ref-resolution, and worker-bootstrap families pass; ruff and pyright are clean.
…states the sentinel * The two capability pins assert the gate's contract: an imported app with no runnable workflow is not capability; the mounted app's runnable workflow projects it; the reset clears both (the WeakSet no-pinning proof and the reset seam stay each pin's own subject). * The step row's max_attempts documents the sentinel: None is unset (the handle's declared term applies), and omitting versus explicitly passing three are different declarations. Verified: the worker-execution-seam and wf-execution families pass; mkdocs builds strict; ruff and pyright are clean.
…al payload Strengthens the ended-run pins: the failed run's terminal payload is present and decodable yet the raised verdict names the failing branch; a cancelled run whose terminal payload is present raises the cancellation; and a genuinely live run's read is the honest None.
Pins the memo's invalidation seams: a workflow declared after the first projection changes the fingerprint and projects, a second app registered after it joins the merged projection, and the reset seam clears the memo with the registry.
…h its reason The projection's named refusal reaches the loader's operator as the conflict and the actor, exiting without a traceback.
…ey hold * The runtime string ids (the workflow names, the run keys, the call ids, the schema suffixes) state the behavior the fixture exercises: the process-numbered prefixes leave the recorded values, with the per-file cross-references renamed together and the collisions disambiguated. * The prose states the laws: the process-narration headers, the finding-number prefixes, and the base-tree hashes are replaced by the pin's stated invariant (the rejected shape, the behavior held, the fix that landed). The threat-model's own attacker vocabulary stays where the product's security voice uses it (the hostile principal the SSO and the red-team tests model). * The adversarial probes' pack headers name the contract they hold; the run-directly probes' collection contract is the conftest's collect_ignore_glob. Verified: both id-pattern sweeps read zero outside the threat-model's own vocabulary (the SSO and red-team tests' hostile principal — the word the product's own security voice uses); the renamed packs, the probe files by explicit path, the boot-gate diagnosis, the run-verdict, and the cli families pass in three serial batches; the collection count is stable; ruff, pyright, and the strict doc build are clean.
* The typed-route contract pack's model names carry the pack's own subject (the same-qualname twin, the arm-sum types, the unresolvable declaration probe); the route cures' and the docs' pack headers name the contracts they hold; the teardown contract's dangling finding-number fragment states the behavior it named. * The run keys and the schema suffixes in the packs carry the behavior's own label. Verified: the id-pattern sweep over the case-insensitive patterns reads zero outside the in-file ledgers; the route, typed-route, teardown, docs, and deploy-matrix packs pass (50 tests); ruff, pyright, and the strict doc build are clean.
* The capture policy's resolution reads the declared value first: a declared empty string is a declaration and is refused with the valid forms; only an undeclared one takes the default (both the workflow and the actor faces). * The boot projection's memo returns fresh list copies per call — the callers own their lists; the cache's own lists never leave the module. * The hold node's timeout policy renders the duration law's normalized seconds: a timedelta declaration and a bare-number declaration render the identical text, and the timedelta repr never leaks into the diagram (pinned: the pre-cure emission reads 0:00:30s). * The wf-progress gauge's comment parenthesizes its pairing. Verified: the api-surface, declared-term, capacity, cli-ref, and boot-gate packs pass (143 checks); the mermaid pin is red on the pre-cure render and green on the cured one; ruff, format, and pyright are clean.
The verdict's selection excluded the absorption record: a fan-out whose absorbed branch failed LAST (its collect edge delivered the typed report to a fired join) was the newest failed row, and the read's verdict named it — an operator sent to a failure that was already collected while the open one failed the run. The selection now reads the same POLICY-vs-FENCE predicate the per-node derivation and the maintenance root-finalize read (renamed to the package's shared name — the three can never drift): an absorbed failure never names the verdict; the no-row face still speaks when every failure was absorbed. Verified: the verdict pin is red on the pre-cure tree (the verdict named 'collected'/CollectedBoom, the absorbed branch) and green on the cured one (it names the open branch); the run-verdict, run-view, smoke-guard, propagation, and runner packs pass (46 checks); ruff, format, and pyright are clean.
The src prose carried round-numbered references; the two in the applied migration chain are frozen bytes (applied migrations are byte-frozen) and stay; the other eighteen restate their finding's content — the stream fold, the conservative null-stamp shape, the one-base walk, the resolved-name refusal's mirror, the hold context's completeness, the delegate verb, the row count over the grant bit, the containment predicate — without the numbering. Verified: the round-number sweep over src/ reads zero outside the frozen migrations; the smoke-guard, retention, settings, sweep- registry, and boot-diagnosis packs pass (97 checks); ruff, format, and pyright are clean.
The 200-child panel benchmark is marked load_sensitive, but the probes lane's explicit-path invocation collected it anyway and ran its 50ms band under the probes job's co-tenancy: run 42359203585 saw the band's max of 10 reads at 169.9ms against the 50ms bound - the benchmark's own comments record this exact failure mode. The load lane's marker never collected it either (the probes' collect_ignore_glob applies to directory collection), so the benchmark's only gate was the wrong lane. The probes lane now filters 'not load_sensitive' (75 probes, zero skipped; the floor and the prose change from 76 to 75), and the load-sensitive job gains a serial explicit-node invocation for exactly that benchmark with summary parsing that requires one passed and zero skipped, so a missing collection cannot be green. The fixture, the map, the request count, and the 50ms assertion are unchanged.
The expiry sweep's plan pin decompressed whatever chunks it found compressed and trusted the plan to stay rowstore. The compression policy job the hypertable conversion registers is claimed by the background launcher before the test's deferral of next_start lands, and that claimed run can execute during the test's setup window and recompress a chunk after the decompression: the plan then shows Custom Scan ColumnarScan and the pin reds, as run 42359203585 saw. The pin now establishes the premise on the real engine instead of depending on the race. A negative control forces the compression policy's next run to now and watches a chunk actually rematerialize as columnar (the hazard is real, not asserted); the barrier then disables the exact compression job for this schema's jobs_archive, drains its worker by its exact execution identity (the job's application name in pg_stat_activity), decompresses everything, and asserts every chunk is rowstore at the plan's doorstep before the existing plan, chunk count, and pruning assertions run unchanged.
The rolling release's corpse assert read the ownership surfaces once, immediately after the probes settled. The product's shutdown release documents its own fallback: a release write can fail or be skipped, intentionally leaving running/locked rows for lease-expiry reclaim, and probe settlement does not settle corpse rows. CI run 42359203585's rolling lane hit exactly that: worker 2 exited rc0, the probes settled, and one running row was still locked by it at the immediate assert - the assert tested the wrong instant for the documented fallback. The assert is now a bounded state-based wait with an immediate fast path: it requires zero running rows locked by the corpse and zero reservation slots live-held by it (the slot's live lease is the condition, never the row's existence: a survivor reusing the stale row keeps its own lease), bounded by the module's existing corpse arithmetic (the lock lease to lapse, the leader lease and one sweep tick for the reclaim, the re-claim cycle, the co-tenancy margins, stretched by the tier's load factor). On the bound's expiry it reports the offending rows (id, actor, status, attempt, holder, lock_expires_at, scheduled_at, interrupt_count), the slot states, and the database clock, and fails. The module docstring states the real postcondition: no ownership after clean release, or by the bounded lease/sweep reclaim after a failed release. The staged-reads helper test is clearly not a production reproduction: the real-world red is the CI run cited above. Its stages drive the helper on real rows: the clean fast path, a live corpse state held past a short bound with the timeout's report naming the row and the slot, and the eventual clearance once the reclaim's lease lapse has passed (the stale slot row still names the corpse). The late-registration requeue pin is unchanged and green.
The bounded corpse wait treated any running row locked by an exited worker as the documented release fallback and waited for the sweep to reclaim it: a product release miss scored green once the reclaim landed (demonstrated on the real helper: the miss passed after the reclaim). The assert now requires row-specific evidence before any wait: a release-pg-write-failed, shutdown-release-failed, or terminal-write-failed record naming that job id in the worker's own flushed log (the explicit sink or the harness tee file). A residual running row without its evidence fails immediately with the detailed row and slot report; a mixed group needs every row evidenced; a held row without a lock expiry fails immediately too. Evidenced rows wait on their own bound (the observed lock expiry plus one sweep tick and the poll floor, stretched by the tier's load factor); slot-only residue keeps the corpse slot bound (a stale row reused by a survivor is existing semantics, and the live lease is the condition). The six scenario call sites pass the real WorkerProc; the helper reads the log read-only. The staged-reads pin runs against real log files: no log, a marker naming a different job id, and the exact-row evidence whose reclaim lands during the wait; it is labeled as a staged read, not a production reproduction - the real-world red is CI run 42359203585's rolling lane.
The negative control's completion signal was the job's total_runs, which advances when a run STARTS; last_run_status stays NULL until it finishes. Breaking on the count observed the forced run mid-flight: its remaining compressions could make the control's own strict-new check see nothing new, or recompress a chunk after the barrier's decompression and break the rowstore premise at the plan's read. The gate now requires the finished status (and Success) before either check runs. The activity-name gap also stayed: a claimed-but-not-yet-started worker is invisible in pg_stat_activity, so a pause plus the process drain cannot make the plan observation atomic. Both plans now run inside a real transaction holding the hypertable in ACCESS SHARE and its exact chunks in ACCESS EXCLUSIVE: a claimed run blocks on those locks until the plans are read, the rowstore premise is re-asserted under the lock, and the probe compression started inside cannot finish while the lock is held - it lands the moment the transaction rolls back, which is the serialization evidence on this engine.
…joined Three corrections from the re-review of the two lanes: The negative control's baseline snapshot moves after the witness chunk's decompression (the witness's rowstore state is part of the baseline, so its recompression is a strict new identity), the witness's rowstore is pinned immediately before the forced run and its columnar state after, and the completion gate keys on the job's real success stats: total_successes and last_successful_finish must advance past the force instant, so a prior run's status can never satisfy the gate. The plan observation's serialization proof no longer rests on a sleep: the compressor connection's own pg_backend_pid is captured before the probe task, and the poll observes that exact pid in a real Lock wait while the task is live. The task is reaped on every path: the normal path waits for it only after the transaction has rolled back and the lock is released; any other exception cancels and reaps it, suppressing only the child's CancelledError while the outer exception propagates. The harness's stderr tee reader is owned by the WorkerProc (an optional log_drain member, default None for hand-built workers) and joined at the process's death on graceful_stop and reap alike, on the clean path and the SIGKILL path: the log file is final at assertion time, and a reader that never reaches EOF is named loudly. The corpse assert's evidence rule keys on the current attempt: a marker record counts only when its console stamp parses and postdates the residual row's own claim stamp (the same host clock, second granularity), so an older attempt's job-id-only line is rejected. The staged reads cover the wrong row, the stale attempt, the mixed group, the missing lock expiry, and the exact-row evidence whose reclaim lands during the wait, with the staged reaper cancelled and reaped on every path.
…the real stamp Three re-review corrections: The negative control no longer infers the policy run's completion from background schedule statistics: it executes the real policy synchronously through the engine's own job runner (CALL run_job on the exact job id), which returns only after that policy run completes. The launch-versus-finish race is gone with the force_at and schedule control code; the witness pins (rowstore before the call, columnar after) and the strict new compressed identity relative to the post-decompression baseline remain, and the pause, the midflight drain, and the plan's lock transaction keep their roles. The corpse assert's log evidence now parses the product's own TimeStamper stamp (ISO UTC, T/Z/fraction) with datetime.fromisoformat; a naive, malformed, or missing stamp is never evidence, and the claim comparison is against the row's own started_at on the same host clock. The staged records use the product's exact shape. The compressor probe task's outcome is consumed on every path (a compress that failed before the finally included), and the reap names a stuck log reader through the non-fatal diagnostic path instead of silently suppressing it.
The compression policy's midflight drain and the compressor's lock-wait observation queried pg_stat_activity by application name and pid alone; a cluster co-tenant with a matching name or pid could satisfy either predicate. Both now also require datname = current_database().
…stence Two lane corrections: CapSampler._tick read the running rows and the live slots as two independent READ COMMITTED statements with an await between them: under co-tenancy the pair could observe post-completion slots after pre-completion jobs and miss a real admission's receipt. One tick now reads one snapshot (a single statement whose two subqueries return the jobs' and the slots' views at the same READ COMMITTED instant, parsed as JSON), so the receipt and every peak are states of one instant; a failed tick still leaves no aborted transaction to poison the next. The tee proof's startup wait polls the log file's existence before its contents (the reader opens the file in its own thread) and breaks loudly on the child's death; the proof's readiness is observed, never assumed.
The panel latency pin labeled its maximum as a p95: ten reads, last index - the single worst read of the set, a different tail statistic. One hundred reads now feed a deterministic nearest-rank p95 (ceil(0.95*n)-1); the 50ms band, the status checks, the 200-child fixture, the capture JSON, and the page median are unchanged, and the maximum stays visible in the output so a genuinely slow population cannot hide behind the percentile.
…ped honestly The tee proof's post-spawn flow rides a finally that reaps the worker: a readiness or assertion failure still kills and reaps the live child and joins the log reader (injected-proof: a silent child's readiness failure left zero surviving processes and no reader residue). The cap sampler's _record takes the snapshot's actual shape (a sequence of mappings); no record coercions added.
… name themselves The snapshot pin's two staged slot rows survived the test (only its connection was closed): under randomized order a real scenario's first sampler sample then read a slot over-hold that no real worker made - the CI system lane's sample-one errors' shape. The staged rows are now deleted by the exact bucket AND the exact staged holder on every path, with the cleanup's own zero-leftover check; never a bare bucket deletion, so real scenario slots are untouched. The over-hold violation's diagnostic no longer prints an empty list: when the slot surface exceeds its bound, the exact bucket's slot rows (slot_index, job_id, holder, acquired_at, lease_expires_at, live lease) are fetched in the same schema and joined LEFT to the job's status, holder, and queue, and the pin asserts the violation names both injected slot indices, the holder, and the deleted job's null status. The fetch is diagnostic only: the snapshot's count already made the decision.
…'s errors have precedence Two error-precedence corrections: The cap sampler's diagnostic fetch is best effort: when the slot details' query fails, the tick still records the over-hold violation naming the held count and the fetch's own error, instead of the generic sampler error replacing the cap record. The fault is injected by a declared subclass whose diagnostic raises; the pin red at the pre-cure tick (the generic error in the record's place) and green after. The staged cap slots' cleanup reads the active exception at finally entry, before any await, and keys its error behavior on it: with no primary failure a cleanup failure raises loudly (a green test turns red only when the guilty cleanup itself failed); with a primary failure the cleanup's own failure is printed in full and the primary exception is preserved. The zero-leftover assertion holds on the normal path; the deletion stays scoped to the exact bucket and the exact staged holder. The precedence pin declares its fault (a closed connection) and drives both paths.
Contributor
Author
|
The numbers behind the Testing section. Complete product and lane proof at
Final delta verification:
CI on this head: run 42395580657. All 28 required checks passed on |
rcbevans
marked this pull request as ready for review
November 7, 2026 18:09
This was referenced Nov 7, 2026
This was referenced Nov 24, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
feat(workflows): adoption hardening
This change fixes where the API, docs, and code disagreed, wires the operator abandon door, and removes the fake-SQL test scaffolding.
Behavior
Boot gate.
workflow_execution_capable()now checks what the boot projection produces, not what was imported: at least one runnable workflow cohort has to project. An app with no runnable workflow refuses at the loader with the reason (the compile failures, or "the app declares no runnable workflow"). A cross-workflow capacity conflict refuses with the conflicting declarations and exits 1 instead of printing a traceback. The workflow decorator refuses a capture disagreement before registration.Run result.
result()reads the run's terminal status and the terminal node's row in one round trip. A succeeded terminal with a failed sink raises the sink failure; a cancelled run raises the cancellation; a live run returnsNone. The failure raised is the one that failed the run, not a sibling branch's.run()attachesclaim_verdictonly on the replay face.FlowRunner.create_flow()maps an unmigrated schema to the typed error the packaged run door raises.One spelling per concept.
key=,capture_policy=, andon_failure="collect"are canonical; the previous spellings still work. Reservations accept a list, a tuple, orNoneon every face. Second-denominated arguments accept a timedelta or bare seconds through one normalizer;start_to_closestays timedelta-only. Passing two spellings that disagree is refused with both values named.step()folds an actor's declared retry terms into nodes that don't declare their own.Retention floor. On a server without
timescaledb, including managed vanilla Postgres, the floor's catalog probe ran on every sweep and failed every time. It now checkspg_extensionfirst, caches the answer per underlying connection for 300 seconds, and busts the cache when the enable path confirms an install. A probe or parse failure still returnsNone, and the Timescale-present path sends the same statement as before.Ids and refusals.
list,get,resolve, andholdsbind the canonical id.run=is canonical onlist;flow_id=still works. Two spellings that disagree are refused with both named, and a value that isn't an id gets the same refusal. The admin's resolve, deliver, cancel, rerun, and node doors, and the demo's four doors, answer malformed input with a typed, audited refusal instead of a 500 or silence. A malformed id is an audited 400 with a bounded audit pointer. A NUL renders as its visible escape instead of being deleted, because deleting it could alias a different key. A NUL in a decision or payload is an audited 422 and the hold survives. A token for run A used against run B's hold is a 404 and moves nothing. A value past a smallint column's range is a typed 400. Every refusal renders on the run's trail, and the panel's reads are display-capped with the dropped count shown.Deadline outcomes. A body that finishes at or before its
start_to_closeis recorded by its finish time, not by when the event loop resumed it. An async body records its own outcome, and a sync actor's executor thread stamps its real finish before the loop observes it. A body that finishes after the deadline, including one that absorbs the cancellation, stays a timeout; an in-time self-cancellation stays a cancellation. The rescue never reads a cancelled task's result.Progress close and persistence. A timed-out or cancelled final close cancels and awaits the emitter's in-flight cadence flush before proceeding. A stalled pool acquisition or write can no longer remain detached and publish progress after the attempt has finalized. Each user progress flush and automatic event projection now commits its stream append and state or counter updates in one transaction. Cancellation or a statement failure rolls back the whole record instead of leaving contradictory fragments. Notifications run after commit, so losing the pointer does not lose the durable record.
Docs gate. Every Python fence in
docs/**andREADME.mdruns in CI: 114 fences, each standalone and quick, or an explicitno-execreason. An unknown tag fails collection.Abandon door
HitlClient.abandon(hold_id, reason=...)moves a held signal to theabandonedstate without inventing a decision payload. It writes the same row state as the expiry sweep and records the door in the existingpayloadjsonb, so the migrations stay frozen. It auditshitl.abandon, broadcasts on the hold-expired channel withabandoned_by="operator", and resumes the node.The wait site returns
Expired(abandoned_by="operator")for these rows and"timeout"for the sweep's. A body that wants a failure raisesSignalAbandonedErroritself, the way it already raisesSignalTimeoutError.The door is on the client,
taskq flows abandon,POST /api/runs/{run_id}/abandon, and the Abandon button on the run page's hold card. Timer holds refuse because the clock is their only resolver. Child-join holds can be abandoned; the parent fail-closes and the child keeps running.Wait identity
Two waits on the same signal in one node used to share their answer queue, their held-row read, and their timeout face. A retry after a mixed attempt could hand the second wait's answer to the first. Each wait call now has a deterministic id (
call:{attempt}:{ordinal}), written on the hold row, and all three reads filter by it. Rows that predate the scheme stay visible, so an in-flight hold from an older build doesn't strand. The per-signal face marker is gone; the row reads provide the one-shot behavior.Internals
sweep_loop_budgettook up to 401 statements in one transaction for a 100-loop batch and now takes 2 or 3: a driving select, one batched exhaust, and one outbox insert for the escalation arm.Timescale lane
The six modules that carry the
timescalemarker run in one serial CI job; the xdist jobs exclude the marker. The onlytimescaletest that is alsoload_sensitiveruns in that lane, so each marked test runs once. The lane fails on any skip, deselection, or failure, and its floor is 138 tests.Tests
RETURNINGmap is not._TASKQ_PATCH_EXEMPTfor everytaskq.*monkeypatch in the packs that were cured.Prose
Comments and docstrings state behavior in the present tense. The caps headers, change narration, and stale internal identifiers are removed from 1,345 files. Identifiers, acronyms, measured numbers, and error codes are unchanged.
Testing
Every CI job's recipe passed locally for the adoption changes, plus the probes lane on its own initdb cluster and the heavy streak (
-n 8three times, thetest_wf_*battery at-n 8, the conservation ladder solo five times and at-n 8five times). The final progress delta adds real-Postgres rollback and close tests, the affected packs, and fresh fast, slow, and serial lanes at the landing head. The probes lane runs 75 general probes with no skips; the 200-child panel benchmark runs separately as a required one-test step in the serial load-sensitive job with its 50 ms assertion unchanged.The run results and final-delta evidence are in the first comment. The branch is 143 commits on
ca3cca6b4; the migrations are unchanged.