Skip to content

feat(pipeline): runtime stage contract validation - #458

Merged
Sinity merged 1 commit into
masterfrom
feature/feat/stage-contract-validation
Apr 26, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/feat/stage-contract-validation

Conversation

@Sinity

@Sinity Sinity commented Apr 26, 2026 •

Copy link
Copy Markdown
Owner

Summary

Closes #447. Adds declarative input/output contracts to PipelineStageSpec
and a runtime validator that fires at every stage boundary.

Problem

The pipeline-stage-audit (swarm 2026-04-26) identified the
implicit-contract pattern as the meta-cause behind the four silent-failure
sites fixed in #453: stages depend on prior-stage outputs through bare
RunExecutionState attributes, with no runtime check verifying the
contract is intact.

Solution

  • StageInput dataclass: named state slot a stage requires.
  • PipelineStageSpec extended with inputs: tuple[StageInput, ...]
    and outputs: tuple[str, ...].
  • All eight stages declare their producer/consumer relations.
  • StageContractError raised on violation, naming stage and missing inputs.
  • validate_stage_contract invoked from run_execution._run_stage_spec
    before the stage body runs.
  • Single-stage runs skip validation (durable archive state can satisfy inputs).

Verification

  • 11 new tests in tests/unit/pipeline/test_stage_contract.py cover
    full / reprocess / publish sequences, missing-producer cases, optional
    inputs, message format, and a sanity check that every declared input has
    a producer somewhere in PIPELINE_STAGE_SPECS.
  • devtools verify (full, with pytest): all checks pass.

Summary by CodeRabbit

  • New Features
    • Pipeline stages now validate contracts, automatically checking that all required inputs are available from previously executed stages.
    • Enhanced error reporting when stage validation fails, clearly identifying which inputs are missing.

Closes #447.

Each PipelineStageSpec now declares which named state slots it consumes
(inputs) and produces (outputs). validate_stage_contract runs at every
stage boundary in run_sources; if a required input was not produced by
an upstream stage in the executed sequence, it raises StageContractError.

Catches misconfigured stage sequences such as [acquire, materialize]
(parse skipped) — the implicit-contract pattern flagged by the
pipeline-stage-audit (swarm 2026-04-26) as the meta-cause behind the
silent-failure cluster fixed in #453.

Single-stage runs skip validation; their inputs come from durable
archive state, not upstream pipeline outputs.

Verification: devtools verify (full, including pytest) — all checks
pass; 11 new contract tests pass.
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

@coderabbitai

coderabbitai Bot commented Apr 26, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

This PR implements runtime contract validation for pipeline stages by introducing stage input/output declarations and a validation mechanism that ensures required inputs are satisfied by previously executed upstream stages before execution.

Changes

Cohort / File(s) Summary
Stage Contract Model & Validation
polylogue/pipeline/stage_specs.py
Added StageInput dataclass with name and required fields; extended PipelineStageSpec with inputs and outputs tuples; introduced StageContractError exception and validate_stage_contract() function that checks required inputs against outputs from previously executed specs; updated PIPELINE_STAGE_SPECS mappings to declare input/output contracts for parse, materialize, render, site, and index stages.
Runtime Validation Integration
polylogue/pipeline/run_execution.py
Modified run_sources to maintain an ordered executed_specs list of PipelineStageSpec objects; updated _run_stage_spec to append stage specs immediately for unmanaged stages and after execution for managed stages; added contract validation call (validate_stage_contract) prior to stage execution for managed stages, enabling validation based on previously executed upstream specs.
Contract Validation Test Suite
tests/unit/pipeline/test_stage_contract.py
New test module covering: permissive validation for single-stage runs; successful contract validation across full and partial execution sequences; contract violation failures when required inputs (processed_ids) are missing from skipped upstream stages (parse); confirmation that optional inputs do not trigger violations; exception message validation; custom spec validation; and consistency checks ensuring all declared stage inputs have corresponding outputs in the pipeline spec catalog.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

Possibly related PRs

Poem

🐰 Contracts written, specs proclaimed,
Stages linked without a shame,
Missing inputs? Fail with grace—
Validation runs at every place!
No more silent faults to creep,
Our pipeline's promises, we keep. ✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title 'feat(pipeline): runtime stage contract validation' directly and concisely summarizes the main change—adding runtime validation for pipeline stage contracts.
Description check ✅ Passed The description follows the template with all required sections (Summary, Problem, Solution, Verification) completed, clearly explaining the change and its context.
Linked Issues check ✅ Passed The PR fully implements the requirements from #447: declarative input/output contracts via StageInput and PipelineStageSpec extensions, runtime validation via validate_stage_contract, StageContractError exception, and comprehensive test coverage.
Out of Scope Changes check ✅ Passed All changes are directly scoped to implementing runtime stage contract validation as specified in #447; no unrelated modifications are present.
Docstring Coverage ✅ Passed Docstring coverage is 83.33% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/feat/stage-contract-validation

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai 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.

Actionable comments posted: 6

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
polylogue/pipeline/run_execution.py (1)

265-294: 🧹 Nitpick | 🔵 Trivial

Validator wiring lacks an integration test.

The unit tests in test_stage_contract.py exercise validate_stage_contract directly but never go through run_sources/_run_stage_spec. Removing the line 271 call would not fail any existing test. Consider a small integration test that drives run_sources with an explicit stage_sequence=("acquire", "materialize") against fakes/stubs and asserts StageContractError propagates — this protects the wiring against accidental regressions.

Want me to sketch such a test using the existing pipeline fixtures?

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/pipeline/run_execution.py` around lines 265 - 294, The test suite
lacks an integration test that verifies validate_stage_contract is actually
invoked through run_sources/_run_stage_spec; add a test that uses the existing
pipeline fixtures (or small fakes/stubs) to call run_sources with explicit
stage_sequence=("acquire","materialize") (or otherwise force pipeline_managed
True) and assert that a mis-wired stage causes validate_stage_contract to raise
StageContractError which propagates out of run_sources; specifically target the
validate_stage_contract -> _run_stage_spec path so removing the
validate_stage_contract call would break the test.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@polylogue/pipeline/run_execution.py`:
- Around line 110-111: The code maintains two parallel trackers executed_stages
(set[str]) and executed_specs (list[PipelineStageSpec]) that are always updated
together; remove executed_stages and derive the set when needed (e.g., {s.name
for s in executed_specs}) to eliminate duplicate state. Update references that
read executed_stages (the checks in the run loop and any uses at the locations
currently using it) to compute the name-set from executed_specs, and remove the
append/management of executed_stages from _run_stage_spec so only executed_specs
is appended.
- Around line 267-271: The code currently appends unmanaged specs into
executed_specs before calling validate_stage_contract, which implicitly treats
external (pipeline_managed=False) stages as contributors to the produced
outputs; add a brief inline comment adjacent to the conditional handling of
spec.pipeline_managed (near executed_stages.add(spec.name),
executed_specs.append(spec), and the validate_stage_contract call) that
documents this intended semantics — that unmanaged/external stages are
considered part of the produced set and therefore are added to executed_specs
prior to validation so downstream contracts may rely on their outputs.

In `@polylogue/pipeline/stage_specs.py`:
- Around line 65-73: The StageContractError __init__ builds a sorted formatted
string but assigns self.missing from the original order, causing inconsistency;
update StageContractError.__init__ to canonicalize the missing sequence once
(e.g., compute sorted_missing = tuple(sorted(missing))) and then use
sorted_missing for both the formatted message and to set self.missing so the
exception message and attribute ordering always match.
- Around line 43-44: The tuple fields `inputs` and `outputs` currently use
`field(default_factory=tuple)`; replace both with the immutable literal defaults
`inputs: tuple[StageInput, ...] = ()` and `outputs: tuple[str, ...] = ()`
(keeping the type annotations), and then remove the now-unused `field` import
from the module if nothing else uses it to simplify the code.

In `@tests/unit/pipeline/test_stage_contract.py`:
- Around line 89-97: Add a new unit test that verifies multiple missing inputs
are both preserved on the exception and appear in the error message: create a
custom PipelineStageSpec named e.g. "custom" with inputs ordered
(StageInput(name="zeta"), StageInput(name="alpha")), call
validate_stage_contract(custom,
executed_specs=(PIPELINE_STAGE_SPECS["acquire"],)) inside a
pytest.raises(StageContractError) context, assert that
set(excinfo.value.missing) == {"zeta","alpha"} and that both "alpha" and "zeta"
appear in str(excinfo.value) to lock behavior of StageContractError and message
formatting.
- Around line 44-50: The test test_publish_sequence_satisfies_inputs is
misleading because render is first so its required processed_ids isn't
validated; update the test to explicitly seed executed with a parse stage spec
(use stage_specs_for_sequence(("parse",)) or the parse PipelineStageSpec) before
iterating so validate_stage_contract exercises render's inputs, or alternatively
update the docstring to state that render is intentionally first and thus its
inputs are not checked; modify the executed initialization and/or docstring
accordingly and keep usage of stage_specs_for_sequence and
validate_stage_contract intact.

---

Outside diff comments:
In `@polylogue/pipeline/run_execution.py`:
- Around line 265-294: The test suite lacks an integration test that verifies
validate_stage_contract is actually invoked through run_sources/_run_stage_spec;
add a test that uses the existing pipeline fixtures (or small fakes/stubs) to
call run_sources with explicit stage_sequence=("acquire","materialize") (or
otherwise force pipeline_managed True) and assert that a mis-wired stage causes
validate_stage_contract to raise StageContractError which propagates out of
run_sources; specifically target the validate_stage_contract -> _run_stage_spec
path so removing the validate_stage_contract call would break the test.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 2f31e485-d4ea-49fd-a1d2-bf7e1081fca7

📥 Commits

Reviewing files that changed from the base of the PR and between b15acbf and ebc1407.

📒 Files selected for processing (3)
  • polylogue/pipeline/run_execution.py
  • polylogue/pipeline/stage_specs.py
  • tests/unit/pipeline/test_stage_contract.py

Comment on lines 110 to +111
executed_stages: set[str] = set()
executed_specs: list[PipelineStageSpec] = []

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick | 🔵 Trivial

Two parallel tracking structures for executed stages.

executed_stages: set[str] and executed_specs: list[PipelineStageSpec] always advance together. The set is only consumed at lines 161 and 275 and can be derived on the fly from executed_specs (e.g., {s.name for s in executed_specs}) or via a tiny helper, eliminating one of the two appends inside _run_stage_spec. Optional cleanup.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/pipeline/run_execution.py` around lines 110 - 111, The code
maintains two parallel trackers executed_stages (set[str]) and executed_specs
(list[PipelineStageSpec]) that are always updated together; remove
executed_stages and derive the set when needed (e.g., {s.name for s in
executed_specs}) to eliminate duplicate state. Update references that read
executed_stages (the checks in the run loop and any uses at the locations
currently using it) to compute the name-set from executed_specs, and remove the
append/management of executed_stages from _run_stage_spec so only executed_specs
is appended.

Comment on lines 267 to +271
if not spec.pipeline_managed:
executed_stages.add(spec.name)
executed_specs.append(spec)
return
validate_stage_contract(spec, executed_specs=executed_specs)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick | 🔵 Trivial

Unmanaged-stage placement relative to validation.

For pipeline_managed=False, the spec is appended to executed_specs before any later managed stage validates. That's fine today (only embed is unmanaged, and it has no declared outputs/inputs), but the policy "external stages contribute to the produced set" is implicit. If a future external stage gets outputs=(...), a downstream contract would silently rely on outputs the framework didn't actually orchestrate. Worth a brief comment here documenting the intended semantics for unmanaged specs.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/pipeline/run_execution.py` around lines 267 - 271, The code
currently appends unmanaged specs into executed_specs before calling
validate_stage_contract, which implicitly treats external
(pipeline_managed=False) stages as contributors to the produced outputs; add a
brief inline comment adjacent to the conditional handling of
spec.pipeline_managed (near executed_stages.add(spec.name),
executed_specs.append(spec), and the validate_stage_contract call) that
documents this intended semantics — that unmanaged/external stages are
considered part of the produced set and therefore are added to executed_specs
prior to validation so downstream contracts may rely on their outputs.

Comment on lines +43 to +44
inputs: tuple[StageInput, ...] = field(default_factory=tuple)
outputs: tuple[str, ...] = field(default_factory=tuple)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick | 🔵 Trivial

Use literal () defaults for immutable tuple fields.

field(default_factory=tuple) is the idiom for mutable defaults; for an immutable empty tuple the literal default is simpler and equivalent (and avoids the per-instance factory call). Same applies to outputs.

♻️ Proposed simplification
-    inputs: tuple[StageInput, ...] = field(default_factory=tuple)
-    outputs: tuple[str, ...] = field(default_factory=tuple)
+    inputs: tuple[StageInput, ...] = ()
+    outputs: tuple[str, ...] = ()

Then field can be dropped from the imports if no other field uses it.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
inputs: tuple[StageInput, ...] = field(default_factory=tuple)
outputs: tuple[str, ...] = field(default_factory=tuple)
inputs: tuple[StageInput, ...] = ()
outputs: tuple[str, ...] = ()
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/pipeline/stage_specs.py` around lines 43 - 44, The tuple fields
`inputs` and `outputs` currently use `field(default_factory=tuple)`; replace
both with the immutable literal defaults `inputs: tuple[StageInput, ...] = ()`
and `outputs: tuple[str, ...] = ()` (keeping the type annotations), and then
remove the now-unused `field` import from the module if nothing else uses it to
simplify the code.

Comment on lines +65 to +73
class StageContractError(RuntimeError):
"""Raised when a stage runs with required inputs not produced upstream."""

def __init__(self, *, stage: str, missing: Sequence[str], reason: str) -> None:
formatted = ", ".join(sorted(missing))
super().__init__(f"Stage {stage!r} missing required input(s) {{{formatted}}}: {reason}")
self.stage = stage
self.missing: tuple[str, ...] = tuple(missing)
self.reason = reason

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick | 🔵 Trivial

Inconsistent ordering between self.missing and the formatted message.

The message sorts missing alphabetically while self.missing preserves declaration order. That's a minor surprise for callers programmatically inspecting the exception vs. reading logs. Consider sorting once in the validator (so both views agree), or canonicalize on the attribute. Not a bug — current tests only assert single-element cases — but worth aligning before consumers rely on either ordering.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/pipeline/stage_specs.py` around lines 65 - 73, The
StageContractError __init__ builds a sorted formatted string but assigns
self.missing from the original order, causing inconsistency; update
StageContractError.__init__ to canonicalize the missing sequence once (e.g.,
compute sorted_missing = tuple(sorted(missing))) and then use sorted_missing for
both the formatted message and to set self.missing so the exception message and
attribute ordering always match.

Comment on lines +44 to +50
def test_publish_sequence_satisfies_inputs() -> None:
"""``publish`` (render, site) satisfies the contract — site's input is optional."""
sequence = stage_specs_for_sequence(("render", "site"))
executed: list[PipelineStageSpec] = []
for spec in sequence:
validate_stage_contract(spec, executed_specs=executed)
executed.append(spec)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick | 🔵 Trivial

Publish-sequence test exercises less than it appears.

render here is the first stage, so its required processed_ids input is not validated (empty executed_specs). The test effectively only validates site against render. Consider seeding executed with a parse spec (or noting in the docstring that render-first is the reason this passes) to make the intent explicit.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/unit/pipeline/test_stage_contract.py` around lines 44 - 50, The test
test_publish_sequence_satisfies_inputs is misleading because render is first so
its required processed_ids isn't validated; update the test to explicitly seed
executed with a parse stage spec (use stage_specs_for_sequence(("parse",)) or
the parse PipelineStageSpec) before iterating so validate_stage_contract
exercises render's inputs, or alternatively update the docstring to state that
render is intentionally first and thus its inputs are not checked; modify the
executed initialization and/or docstring accordingly and keep usage of
stage_specs_for_sequence and validate_stage_contract intact.

Comment on lines +89 to +97
def test_violation_message_contains_stage_and_missing() -> None:
"""Error message names both the stage and the missing inputs."""
materialize = PIPELINE_STAGE_SPECS["materialize"]
acquire = PIPELINE_STAGE_SPECS["acquire"]
with pytest.raises(StageContractError) as excinfo:
validate_stage_contract(materialize, executed_specs=(acquire,))
message = str(excinfo.value)
assert "materialize" in message
assert "processed_ids" in message

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick | 🔵 Trivial

Add a multi-missing-input case.

All raise-tests assert on a single missing input. Given StageContractError sorts missing for the message but self.missing preserves declaration order (see stage_specs.py lines 65-73), there's a behavioral seam that's currently untested. A small test with a custom spec declaring two missing required inputs would lock both the attribute order and the message format.

🧪 Sketch
def test_multiple_missing_inputs_are_all_reported() -> None:
    custom = PipelineStageSpec(
        name="custom",
        log_stage="custom",
        inputs=(StageInput(name="zeta"), StageInput(name="alpha")),
    )
    upstream = PIPELINE_STAGE_SPECS["acquire"]
    with pytest.raises(StageContractError) as excinfo:
        validate_stage_contract(custom, executed_specs=(upstream,))
    assert set(excinfo.value.missing) == {"zeta", "alpha"}
    message = str(excinfo.value)
    assert "alpha" in message and "zeta" in message
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/unit/pipeline/test_stage_contract.py` around lines 89 - 97, Add a new
unit test that verifies multiple missing inputs are both preserved on the
exception and appear in the error message: create a custom PipelineStageSpec
named e.g. "custom" with inputs ordered (StageInput(name="zeta"),
StageInput(name="alpha")), call validate_stage_contract(custom,
executed_specs=(PIPELINE_STAGE_SPECS["acquire"],)) inside a
pytest.raises(StageContractError) context, assert that
set(excinfo.value.missing) == {"zeta","alpha"} and that both "alpha" and "zeta"
appear in str(excinfo.value) to lock behavior of StageContractError and message
formatting.

@Sinity
Sinity merged commit 75ed380 into master Apr 26, 2026
14 checks passed
@Sinity
Sinity deleted the feature/feat/stage-contract-validation branch April 26, 2026 16:13
@Sinity

Sinity commented Apr 28, 2026

Copy link
Copy Markdown
Owner Author

🤖 Post-hoc audit note: this PR received bot review feedback verified against current HEAD as part of #544. 2 finding(s) confirmed still present → tracked in #550.

@Sinity

Sinity commented May 1, 2026

Copy link
Copy Markdown
Owner Author

@codex review

@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: 75ed380105

ℹ️ 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 polylogue/pipeline/run_execution.py Resolved

Copilot AI 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.

Pull request overview

Adds declarative stage input/output contracts to the pipeline stage spec model and introduces runtime validation at stage boundaries to prevent misconfigured stage sequences from silently producing no-ops.

Changes:

  • Extend PipelineStageSpec with inputs/outputs and introduce StageInput + StageContractError.
  • Add validate_stage_contract() and invoke it from the pipeline runner prior to stage execution.
  • Add unit tests covering common sequences, missing-producer scenarios, optional inputs, and error messaging.

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 4 comments.

File Description
polylogue/pipeline/stage_specs.py Adds contract declarations to stage specs and implements the contract validator + error type.
polylogue/pipeline/run_execution.py Tracks executed specs and runs contract validation before executing each stage.
tests/unit/pipeline/test_stage_contract.py New unit tests for contract validation behavior and invariants across stage specs.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +140 to +147
) -> None:
"""Verify ``spec``'s required inputs were produced by an executed upstream stage.

Single-stage runs (``executed_specs`` empty) skip validation: their inputs
come from durable archive state, not upstream pipeline outputs. Multi-stage
runs that omit a required producer raise :class:`StageContractError`.
"""
if not executed_specs:

Copilot AI May 1, 2026

Copy link

Choose a reason for hiding this comment

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

validate_stage_contract() currently skips validation whenever executed_specs is empty. That means the first stage in any multi-stage sequence (e.g. ("render", "site") / publish) is never validated, even if it declares required inputs (like render.inputs = (processed_ids,)). This undermines the stated behavior (“single-stage runs skip validation”) and can still allow silent no-op runs when a multi-stage sequence starts at a downstream stage.

Consider skipping only when the overall run is truly single-stage (e.g. len(stage_specs) == 1 computed by the runner), or make validation aware of the effective execution_stage so leaf-mode stages that read durable state can opt out while multi-stage composites still validate required upstream producers.

Suggested change
) -> None:
"""Verify ``spec``'s required inputs were produced by an executed upstream stage.
Single-stage runs (``executed_specs`` empty) skip validation: their inputs
come from durable archive state, not upstream pipeline outputs. Multi-stage
runs that omit a required producer raise :class:`StageContractError`.
"""
if not executed_specs:
single_stage_run: bool = False,
) -> None:
"""Verify ``spec``'s required inputs were produced by an executed upstream stage.
Validation is skipped only for true single-stage runs, where the stage is
expected to read any required inputs from durable archive state instead of
from upstream pipeline outputs. Callers must pass ``single_stage_run=True``
only when the overall resolved stage sequence contains exactly one stage.
Multi-stage runs that omit a required producer raise
:class:`StageContractError`, including for the first stage in the sequence.
"""
if single_stage_run:

Copilot uses AI. Check for mistakes.
Comment on lines 265 to 272
async def _run_stage_spec(spec: PipelineStageSpec) -> None:
nonlocal index_outcome
if not spec.pipeline_managed:
executed_stages.add(spec.name)
executed_specs.append(spec)
return
validate_stage_contract(spec, executed_specs=executed_specs)
execution_stage = spec.execution_stage(

Copilot AI May 1, 2026

Copy link

Choose a reason for hiding this comment

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

run_execution._run_stage_spec() calls validate_stage_contract(spec, executed_specs=...) before computing execution_stage. For stages like render/index whose implementations have different input needs depending on the stage token (e.g. leaf stage == "render" renders from DB vs stage == "all" uses processed_ids), the validator can’t correctly decide which inputs should be required.

Compute execution_stage first and pass it (or a derived mode flag like leaf_run) into the validator so contracts can be validated against the actual execution mode, rather than relying on “first stage skips” as a proxy.

Copilot uses AI. Check for mistakes.
Comment on lines +44 to +52
def test_publish_sequence_satisfies_inputs() -> None:
"""``publish`` (render, site) satisfies the contract — site's input is optional."""
sequence = stage_specs_for_sequence(("render", "site"))
executed: list[PipelineStageSpec] = []
for spec in sequence:
validate_stage_contract(spec, executed_specs=executed)
executed.append(spec)


Copilot AI May 1, 2026

Copy link

Choose a reason for hiding this comment

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

test_publish_sequence_satisfies_inputs currently passes only because the validator skips the first stage when executed is empty. As written, it never exercises the key contract for render (declared required processed_ids) in the publish sequence, so it doesn’t actually verify that publish satisfies required inputs.

Once the validator distinguishes true single-stage runs vs first-stage-of-multi-stage, this test will likely need to assert either (a) render does not require processed_ids in publish/leaf mode, or (b) publish includes an upstream producer for processed_ids.

Suggested change
def test_publish_sequence_satisfies_inputs() -> None:
"""``publish`` (render, site) satisfies the contract — site's input is optional."""
sequence = stage_specs_for_sequence(("render", "site"))
executed: list[PipelineStageSpec] = []
for spec in sequence:
validate_stage_contract(spec, executed_specs=executed)
executed.append(spec)
def test_publish_sequence_allows_leaf_render_then_site() -> None:
"""``publish`` permits leaf-mode ``render`` and then validates ``site`` after it."""
render = PIPELINE_STAGE_SPECS["render"]
site = PIPELINE_STAGE_SPECS["site"]
validate_stage_contract(render, executed_specs=())
validate_stage_contract(site, executed_specs=(render,))

Copilot uses AI. Check for mistakes.
Comment on lines +271 to 272
validate_stage_contract(spec, executed_specs=executed_specs)
execution_stage = spec.execution_stage(

Copilot AI May 1, 2026

Copy link

Choose a reason for hiding this comment

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

validate_stage_contract() can raise StageContractError, and run_sources() does not currently catch it. As a result, a contract violation aborts the run before persist_run_result() is called, so the failure won’t be captured in RunResult / the run ledger.

If the intended behavior is (per the PR description / issue acceptance criteria) for contract diagnostics to surface in RunResult / readiness reporting, consider catching StageContractError in run_sources and persisting an appropriate failure record (or translating it into the existing run-result error reporting mechanism).

Copilot uses AI. Check for mistakes.
@Sinity
Sinity requested a review from Copilot May 1, 2026 00:44
@Sinity
Sinity removed the request for review from Copilot May 1, 2026 01:05
Sinity added a commit that referenced this pull request May 7, 2026
## Summary

Closes #447. Adds declarative input/output contracts to
`PipelineStageSpec`
and a runtime validator that fires at every stage boundary.

## Problem

The `pipeline-stage-audit` (swarm 2026-04-26) identified the
implicit-contract pattern as the meta-cause behind the four
silent-failure
sites fixed in #453: stages depend on prior-stage outputs through bare
`RunExecutionState` attributes, with no runtime check verifying the
contract is intact.

## Solution

- ``StageInput`` dataclass: named state slot a stage requires.
- ``PipelineStageSpec`` extended with ``inputs: tuple[StageInput, ...]``
  and ``outputs: tuple[str, ...]``.
- All eight stages declare their producer/consumer relations.
- ``StageContractError`` raised on violation, naming stage and missing
inputs.
- ``validate_stage_contract`` invoked from
``run_execution._run_stage_spec``
  before the stage body runs.
- Single-stage runs skip validation (durable archive state can satisfy
inputs).

## Verification

- 11 new tests in ``tests/unit/pipeline/test_stage_contract.py`` cover
  full / reprocess / publish sequences, missing-producer cases, optional
inputs, message format, and a sanity check that every declared input has
  a producer somewhere in ``PIPELINE_STAGE_SPECS``.
- ``devtools verify`` (full, with pytest): all checks pass.

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

* **New Features**
* Pipeline stages now validate contracts, automatically checking that
all required inputs are available from previously executed stages.
* Enhanced error reporting when stage validation fails, clearly
identifying which inputs are missing.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
@Sinity

Sinity commented Oct 1, 2026

Copy link
Copy Markdown
Owner Author

Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.

Only the rows listed above are dispositioned. Held findings remain open.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(pipeline): runtime stage contract validation

2 participants