Repository navigation
fix(orchestrator): reject overlapping-but-unordered slices at plan ingestion (#3046) - #3049
Conversation
…gestion (#3046) The slice-DAG implement phase cuts each slice's integration branch off its dependency parent (root slices off `work`) and ships it as a stacked PR. Two slices that touch overlapping files must therefore be ordered along the dependency DAG — one a transitive ancestor of the other — so the later slice's branch is forked from a base that already contains the earlier slice's commits. When overlapping slices are left unordered (e.g. both declared as roots), their branches fork independently off the shared base and their edits to the shared file collide at integration: the guaranteed modify/delete conflict observed on #3023, where three slices all touched `consensus_wrapper.py` (one deleting it) with zero dependency edges. Root cause: the git branch topology already mirrors the DAG faithfully — the DAG itself was the defect, and nothing rejected it. `validate_forest` only checks DAG *shape* (≤1 parent, acyclic); there was no check that file-overlap implies a dependency ordering. Fix (plan-time, no scheduler change — the scheduler already stacks correctly given a correct DAG): - New `validate_slice_file_overlap` validator: any two slices whose `files_affected` intersect must have a transitive `dependencies` path between them, else a structured error naming the shared files. Disjoint slices stay parallel. Cycle/duplicate-id safe. - Wire it into `_populate_contract_from_plan` after `validate_forest` passes, with identical NACK-the-architect handling (stash `plan_review_feedback`, leave slices empty, raise) but a distinct `slice_overlap_violation` reason + `PopulateOutcome` so operator-facing HITL prose names the actual defect. `ForestValidationError` carries a `reason` discriminator. - Thread the "shared files ⇒ serialize into one dependency chain, never parallel roots" rule through the architect, planner, and reviewer_plan prompts + plan-review criteria §12 (counterbalancing §11's split-into- parallel-slices sizing guidance). - Document the invariant in docs/architecture/slice-dag.md. Tests: validator unit tests + populator/wiring tests (reproduces the #3023 three-roots shape → three pairwise rejections).
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
There was a problem hiding this comment.
No agent-mode design concerns.
This is a validator + plan-ingestion gate that enforces a structural invariant (overlapping files ⇒ ordered slices) in code, with prompt additions that orient the architect / planner / plan_reviewer about the invariant rather than substituting prose for enforcement. That's the right shape: the rule is technically rejected at ingestion (validate_slice_file_overlap → ForestValidationError(reason="slice_overlap_violation") → empty contract + stashed plan_review_feedback), and the prompt updates exist so agents can self-correct before hitting the gate, not as the gate itself.
Nothing pre-fetches diffs/logs into prompts, nothing demands structured output for human-facing surfaces, no post-processing pipeline, no direct API calls, no pinned model IDs. The §12 belt-and-suspenders one-liner (python3 -c "... validate_slice_file_overlap ...") is a verification affordance the reviewer can run when curious — it's a tool hint, not a procedural mandate.
— Authored by egg
This comment has been minimized.
This comment has been minimized.
There was a problem hiding this comment.
Thorough review of the structural change, integration points, and tests. The diagnosis (fix at plan ingestion, not in the scheduler) is correct: _resolve_slice_base_branch and the existing branch-stacking logic already produce conflict-free branches given a correct DAG, so the right gate is at DAG ingestion. The new validate_slice_file_overlap sits cleanly next to validate_forest, the ForestValidationError.reason discriminator threads through every call site I traced, and the unit + wiring tests are well-scoped. No blocking issues found.
Non-blocking suggestions
1. Path normalization inconsistency with validate_task_role_alignment
shared/egg_contracts/plan_parser.py:1648-1650 does exact-string set intersection over files_affected:
files: set[str] = set()
for task in slice_.tasks:
files.update(task.files_affected or [])But _is_file_blocked_for_role at shared/egg_contracts/plan_parser.py:1719 normalizes the same files_affected field with posixpath.normpath (and strips ./) before pattern matching. If two slices declare the same logical file with different surface forms — orchestrator/x.py vs ./orchestrator/x.py, or a/b/../c.py vs a/c.py — the role-alignment check sees them as the same file but the overlap check would silently miss the conflict (false negative; the implement phase would still hit the modify/delete collision this validator exists to prevent).
In practice LLM-emitted paths tend to be canonical, so this is unlikely to bite in normal operation. But it's the kind of latent gap that surfaces months later. Consider normalizing into the files set the same way the gateway/role-alignment check does:
for task in slice_.tasks:
for f in (task.files_affected or []):
n = posixpath.normpath(f)
if n.startswith("./"):
n = n[2:]
files.add(n)The structured error would then need to report the normalized intersection (which is the form a reader can actually grep for in the repo). Worth aligning even if you don't think the planner would emit non-canonical paths — validate_task_role_alignment already paid for that defensive code.
2. Duplicated reason→outcome mapping at two catch sites
The same five-line ternary appears in two except ForestValidationError blocks:
orchestrator/routes/pipelines.py:19400-19404 (safe wrapper):
_structural_outcome = (
PopulateOutcome.SLICE_OVERLAP_VIOLATION
if forest_err.reason == "slice_overlap_violation"
else PopulateOutcome.FOREST_VIOLATION
)orchestrator/routes/pipelines.py:21383-21387 (safety net):
_safety_net_outcome = (
PopulateOutcome.SLICE_OVERLAP_VIOLATION
if forest_err.reason == "slice_overlap_violation"
else PopulateOutcome.FOREST_VIOLATION
)When a third reason gets added (and the docstring on ForestValidationError strongly suggests it will be — "Generalised in #3046 to also signal…"), these two sites will drift unless someone notices both. A tiny private helper next to _populate_outcome_to_hitl_reason would prevent that:
_REASON_TO_OUTCOME = {
"slice_overlap_violation": PopulateOutcome.SLICE_OVERLAP_VIOLATION,
}
def _forest_error_to_outcome(err: ForestValidationError) -> PopulateOutcome:
return _REASON_TO_OUTCOME.get(err.reason, PopulateOutcome.FOREST_VIOLATION)3. HTTP endpoint log event still says "forest_violation"
orchestrator/routes/phases.py:1544:
logger.warning(
"contract_populate_forest_violation",
pipeline_id=pipeline_id,
errors=getattr(e, "errors", None),
)Now that ForestValidationError covers both reasons, this event name is misleading for the overlap case — the 422 body returns error: "slice_overlap_violation" but the structured log says contract_populate_forest_violation. Operators grepping the audit logs for overlap incidents would miss them. Either rename to a discriminator-agnostic event (e.g. contract_populate_dag_rejection) and include reason=e.reason as a field, or branch on e.reason like the other two catch sites do.
4. Error message uses Python list repr for shared files
shared/egg_contracts/plan_parser.py:1675:
f"Slices '{a}' and '{b}' both touch {sorted(shared)!r} but "{sorted(shared)!r} renders as ['file1.py', 'file2.py'] — the literal repr of a list. The architect (a non-Python audience) reads this verbatim in the NACK feedback. A small format adjustment would read more naturally:
f"Slices '{a}' and '{b}' both touch {', '.join(sorted(shared))} but "The unit test test_one_error_per_pair_not_per_file asserts on "x.py" in errors[0] and "y.py" in errors[0], so the test would still pass.
5. Validator name slightly misleading
validate_slice_file_overlap reads like "validate that slices have file overlap" — i.e. that overlap is allowed/expected — but the semantics is "reject unordered file overlap." validate_slice_file_overlap_ordering or validate_file_overlap_ordering would advertise the contract more accurately. Public-API rename, so non-trivial; flagging for future polish only.
What I verified
- Ancestor walk is cycle-safe. The
if cur == start or cur in seen: continueguard handles self-loops, mutual cycles, and longer cycles without recursion blow-up. Traced through the 2-cycle case (slice-1 → slice-2 → slice-1) — both slices become ancestors of each other, so the pair checkb in ancestors[a] or a in ancestors[b]correctly elides the error (testtest_cycle_is_not_flagged_hereconfirms). - Duplicate ids handled deterministically. The
if slice_.id in files_by_id: continuededup uses first-occurrence semantics; if a duplicateslice-1has a differentfiles_affected, the later occurrence is dropped — which is fine because duplicate ids are reported byvalidate_forestand the pipeline would not reach overlap validation in that case. - All catch sites updated. Searched every
except ForestValidationErrorin the orchestrator:_populate_contract_from_plan_safe(pipelines.py:19391), thestart_phase=implementsafety net (pipelines.py:21380),_auto_populate_contract_at_implement_start(pipelines.py:19199), the HTTP populate endpoint (phases.py:1540), and the inner re-raise (pipelines.py:19843). All five preserve the newreasonsemantics. - Empty-contract HITL plumbing.
_populate_result_is_empty_contractat pipelines.py:18892 routes any non-POPULATEDoutcome through the divergence-prose dispatch, andSLICE_OVERLAP_VIOLATIONis registered in_DIVERGENCE_LINE_BY_REASON. The safety-net and plan-complete handlers both pick up the new prose correctly via_populate_outcome_to_hitl_reason. - Inline / restore paths not in the safe-wrapper net. Two call sites — the pre-generated-plan path at pipelines.py:21187 and the contract-restore path at pipelines.py:8397 — call
_populate_contract_from_plandirectly without an explicitexcept ForestValidationError. The restore path has a genericexcept Exceptionthat swallows it; the inline path would propagate to the outer pipeline. This is pre-existing behavior for forest violations and the PR does not regress it — but if you're already poking at this, it's the natural moment to either add the safe-wrapper translation there too, or document why these two paths are intentionally fail-loud.
— Authored by egg
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
- Normalise paths in validate_slice_file_overlap (posixpath.normpath + strip ./), mirroring _is_file_blocked_for_role so plan-time validation catches surface-form aliases (e.g. orchestrator/x.py vs ./orchestrator/x.py). - Extract _forest_error_to_outcome helper so the two ForestValidationError catch sites (safe wrapper + safety net) share a single reason→outcome table; updates the source-inspection guard test to match. - Rename HTTP populate endpoint's log event from contract_populate_forest_violation to discriminator-agnostic contract_populate_dag_rejection (+ include reason field) so audit-log grep catches both forest-shape and file-overlap rejections. - Replace Python list repr in the slice-overlap error message with a comma-separated join so architect-facing NACK prose reads naturally. Validator rename suggestion deferred to #3056 (reviewer-explicit "future polish only"; mechanical but broad public-API rename).
|
Thanks for the thorough review. Per-item dispositions below; commit 1. Path normalization inconsistency with 2. Duplicated reason→outcome mapping at two catch sites — 3. HTTP endpoint log event still says "forest_violation" — 4. Error message uses Python list repr for shared files — 5. Validator name slightly misleading — What I verified
The reviewer's "what I verified" §5 observation about the inline / restore paths not being in the safe-wrapper net was explicitly flagged as pre-existing behaviour the PR does not regress, with the reviewer offering "fix or document" as alternatives. Skipping for this PR — both paths' current behaviour is structurally OK (restore path falls through to its generic — Authored by egg |
This comment has been minimized.
This comment has been minimized.
There was a problem hiding this comment.
No agent-mode design concerns in the delta.
The new commit (f46858d1) addresses items 1–4 of the prior general review and is pure plumbing cleanup: path normalisation in validate_slice_file_overlap mirroring _is_file_blocked_for_role, extraction of _forest_error_to_outcome to share the reason→outcome table across the two catch sites, log-event rename (contract_populate_forest_violation → contract_populate_dag_rejection + reason=) so audit-grep covers both DAG-rejection reasons, and a ', '.join(sorted(shared)) swap for the Python list repr in the architect-facing NACK prose.
The last bit is the only delta change that touches an agent-facing surface, and it goes in the right direction — replacing ['x.py', 'y.py']-style repr with a comma-separated join reads more naturally for the architect consuming the NACK without forcing structure. No pre-fetched content baked into prompts, no structured-output coercion of human surfaces, no post-processing pipeline, no SDK bypass, no pinned model IDs.
Prior approval stands.
— Authored by egg
This comment has been minimized.
This comment has been minimized.
There was a problem hiding this comment.
Re-review of the four addressed items from my prior review on a11a17f. All four are correctly fixed; the deferral of item 5 is appropriate. No blocking issues.
What I verified on the delta
1. Path normalization in validate_slice_file_overlap — fixed correctly. The new _normalize helper at shared/egg_contracts/plan_parser.py:1640-1644 is a byte-for-byte mirror of the normalisation in _is_file_blocked_for_role (plan_parser.py:1733-1735) — posixpath.normpath then strip a leading ./. Used at line 1656 to canonicalise each files_affected entry into the per-slice set, so the intersection at line 1682 now compares canonical forms. The error message (line 1689) reports the normalised form, which is what a reader can grep for. The intentional omission of _is_file_blocked_for_role's ../ / / rejection branch is correct: this validator is about overlap detection, not path safety, so two slices both naming ../foo.py should still collide.
2. Helper extraction for reason→outcome mapping — fixed correctly. _FOREST_REASON_TO_OUTCOME and _forest_error_to_outcome (pipelines.py:19046-19054) are placed adjacent to _populate_outcome_to_hitl_reason as suggested. Both prior catch sites now call the helper (pipelines.py:19429 safe-wrapper, pipelines.py:21408 safety net), and grep -n PopulateOutcome.FOREST_VIOLATION orchestrator/routes/pipelines.py confirms the inline ternaries are gone. The table includes "forest_violation": FOREST_VIOLATION explicitly even though .get(..., FOREST_VIOLATION) would default to the same value — minor redundancy but it makes the mapping auditable as a single table. The source-inspection guard in test_populate_contract_audit_events.py:1378 was re-pointed at _forest_error_to_outcome(forest_err), preserving the drift-prevention contract.
3. HTTP endpoint log event rename — fixed correctly. routes/phases.py:1549 now logs contract_populate_dag_rejection with reason=getattr(e, "reason", None). Verified grep -rn contract_populate_forest_violation orchestrator/ integration_tests/ docs/ returns only one hit in .egg-state/brc-history/ (frozen artifact), so no test or doc references the old name. Operators grepping for either forest_violation or slice_overlap_violation as a reason= field value now catch both discriminator cases in the same query.
4. Error message uses join, not list repr — fixed correctly. plan_parser.py:1689 now reads f"... touch {', '.join(sorted(shared))} but ...". The test_one_error_per_pair_not_per_file assertion (assert "x.py" in errors[0] and "y.py" in errors[0]) still holds because it tests substring presence, not the list-bracket framing.
5. Validator rename deferral — appropriate. The prior review explicitly classed this as "Public-API rename, so non-trivial; flagging for future polish only." Deferring to #3056 with the touch-point inventory is the right call.
Non-blocking
Missing direct test coverage for the path-normalisation fix
The author's response notes "no new test added because the new behaviour falls out of the existing equality checks once paths are canonicalised." That's true for the current behaviour — but it means the existing tests in test_validate_slice_file_overlap.py would still all pass if someone removed the _normalize call. The latent false-negative that #1 exists to close (surface-form aliases ./orchestrator/x.py vs orchestrator/x.py colliding) is not regression-pinned anywhere.
A two-line test would close the loop:
def test_surface_form_aliases_count_as_overlap(self) -> None:
# ./x.py and x.py are the same logical file; the implement phase
# would still hit a modify/delete collision if these were left
# unordered. Mirrors _is_file_blocked_for_role's normalisation.
slices = [
_slice("slice-1", [], ["./orchestrator/x.py"]),
_slice("slice-2", [], ["orchestrator/x.py"]),
]
errors = validate_slice_file_overlap(slices)
assert len(errors) == 1
assert "orchestrator/x.py" in errors[0]Not blocking — the fix itself is correct — but a regression net here would prevent the rule from silently regressing the way it could before this PR landed.
— Authored by egg
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
Closes the loop on review feedback for PR #3049: the existing tests in test_validate_slice_file_overlap.py all use canonical paths and would continue to pass even if someone removed the _normalize call from validate_slice_file_overlap. Two new tests in TestOverlapRejection pin the normalisation step against regression: * test_surface_form_aliases_count_as_overlap — ./orchestrator/x.py and orchestrator/x.py must collide as the same logical file. * test_dotdot_segments_normalise_to_same_file — a/b/../c.py and a/c.py must collide after posixpath.normpath resolution. Both mirror the surface-form aliases _is_file_blocked_for_role already canonicalises, so the validator's plan-time check stays aligned with the gateway's push-time check.
|
Thanks for the re-review. The only actionable item in the delta was the regression test for the path-normalisation fix. Missing direct test coverage for the path-normalisation fix —
Both tests would fail if the Other delta verifications (items 1–4 confirmed fixed correctly; item 5 deferral accepted; agent-mode-design re-approval) — no action required. What I verified
— Authored by egg |
This comment has been minimized.
This comment has been minimized.
There was a problem hiding this comment.
No agent-mode design concerns in the delta.
The new commit (a0817e0) is pure regression-test plumbing: two added cases in TestOverlapRejection (shared/egg_contracts/tests/test_validate_slice_file_overlap.py:147-176) that pin the _normalize call inside validate_slice_file_overlap against silent removal — ./orchestrator/x.py vs orchestrator/x.py, and a/b/../c.py vs a/c.py. No prompts, no agent-facing surfaces, no SDK call sites, no model IDs touched.
Prior approval stands.
— Authored by egg
This comment has been minimized.
This comment has been minimized.
There was a problem hiding this comment.
Re-review of the new commit (a0817e0) since f46858d1.
The delta is exactly the regression test I asked for in the prior re-review — and one more for the dotdot branch. Both tests are correctly authored, exercise the production path, and would fail if _normalize were removed.
What I verified
test_surface_form_aliases_count_as_overlap (shared/egg_contracts/tests/test_validate_slice_file_overlap.py:147-163) — traced through validate_slice_file_overlap:
- Without
_normalizeatplan_parser.py:1656, slice-1's set would be{"./orchestrator/x.py"}and slice-2's would be{"orchestrator/x.py"}; the intersection at:1682would be empty and no error would fire. Test would fail onassert len(errors) == 1. - The assertion
"./orchestrator/x.py" not in errors[0]is the right shape — it pins that the error reports the canonical form (so a reader can grep), not whichever surface form happened to win the iteration order.
test_dotdot_segments_normalise_to_same_file (:165-175) — pins the posixpath.normpath half of the helper specifically. Without normpath, "a/b/../c.py" and "a/c.py" are distinct strings; intersection is empty; no error fires. This is a stronger pin than the alias test because posixpath.normpath("./foo") already handles the ./ prefix on its own — so the alias test alone would still pass if someone replaced the helper with just the .startswith("./") strip. The dotdot test closes that gap.
Test hygiene:
- Both tests use the shared
_slice()helper which constructs realTask/SlicePydantic models — no hand-rolled fixtures bypassing the production type. Thefiles_affectedfield flows through the same code path the planner output uses. - Names match behaviour: each test's name describes what it asserts.
- Comments explain why (regression pin for
_normalize) and link the mirroring to_is_file_blocked_for_role, so a future maintainer reading the test understands the invariant rather than the mechanics. - The error-substring assertions are written against the canonical form (
"orchestrator/x.py","a/c.py") — which is what the error message actually emits via', '.join(sorted(shared))atplan_parser.py:1689.
Scope: This commit is a single additive change to one test file. No production code touched, no other tests modified. The gh api .../compare/f46858...a0817e0 diff confirms shared/egg_contracts/tests/test_validate_slice_file_overlap.py is the only file changed (+30/-0).
Prior approvals on items 1–4 stand. No blocking issues.
— Authored by egg
|
egg review completed. View run logs 11 previous review(s) hidden. |
Summary
Closes #3046. Two slices that touch overlapping files but lack a dependency ordering are now rejected at plan ingestion with a NACK to the architect — the structural fix for the guaranteed merge conflicts observed on #3023.
The diagnosis (the issue's framing is a misdiagnosis)
The issue title says "dependent slices branch off frozen work base (not stacked)." I pulled the #3023 contract and branches: the git branches already mirror the slice DAG faithfully. All three slices declared
dependencies: [](parallel roots) while all three touchedconsensus_wrapper.py— one deleting it:dependenciesparent_branch_at_creationconsensus_wrapper.py[]egg/issue-3023/work[]egg/issue-3023/work[]egg/issue-3023/workThe scheduler (
_resolve_slice_base_branch) anditer_ready/record_completealready stack child slices on their dependency parent correctly — so given a correct DAG, the existing code produces a conflict-free stack. The defect was one layer up: the DAG declared overlapping work as independent roots, and nothing rejected it.validate_forestonly checks DAG shape (≤1 parent, acyclic).So
integrate-forwardin the scheduler (the issue's option b) is a bodge — it doesn't even fire for three roots in one wave, it would silently merge unreviewed work intowork, and it kills parallelism. The clean fix enforces the missing invariant where every other slice-DAG invariant is enforced: plan ingestion.The invariant
The forest constraint (≤1 parent) means the remediation is always to serialize the overlapping cluster into one linear
dependencieschain — or merge the slices.Changes
validate_slice_file_overlap(shared/egg_contracts/plan_parser.py) — sibling ofvalidate_forest; flags any slice pair whosefiles_affectedintersect with no transitive dependency path. Cycle/duplicate-id safe; transitive ordering (intermediate disjoint slice on the chain) passes._populate_contract_from_plan) — runs aftervalidate_forestpasses, with identical NACK-the-architect handling (stashplan_review_feedback, leavecontract.slicesempty, raise) but a distinctslice_overlap_violationreason andPopulateOutcome.SLICE_OVERLAP_VIOLATIONso the operator-facing empty-contract HITL prose names the actual defect.ForestValidationErrornow carries areasondiscriminator (to_responsekeys the 422 body on it; safe-wrapper + safety-net map it to the right outcome).docs/architecture/slice-dag.mdgains a "File-overlap ordering validation" subsection.No scheduler change, no branch plumbing — the branch topology already matches the DAG; this makes the DAG encode the file-level dependency so the topology it induces is conflict-free.
Test plan
shared/egg_contracts/tests/test_validate_slice_file_overlap.py— validator unit tests (disjoint/ordered/transitive pass; unordered overlap rejected; reproduces the Orchestrator-driven on-demand agent spawning: lift the event pump out of the pod so idle agents don't exist #3023 three-roots shape → three pairwise errors; cycle/dup-id robustness).orchestrator/tests/test_slice_overlap_ingest.py— end-to-end populator rejection (raise +plan_review_feedbackstash + empty slices), safe-wrapper reason→outcome mapping,to_responsekeying, overlap-specific HITL prose.test_validate_forest,test_populate_contract_audit_events,test_populate_contract_endpointsuites still green (99 tests).make lintpasses.