From 38ef6178a635a8a91dbdd6cc2feca950b8671c9f Mon Sep 17 00:00:00 2001 From: Charles Yao Date: Sun, 20 Sep 2026 19:32:24 -0700 Subject: [PATCH] fix(dify-builder): refuse to apply a repair that stages no intents handle_await_repair offered "Apply the fix" unconditionally, so an empty staged_repair produced approve -> apply nothing -> retest -> same failure -> offer again, with no LLM in the loop. ESQ1-291's trace shows five such approvals, every change set {count: 0, changes: []}. Adds repair_attempts / last_repair_error to the context (both defaulted, so persisted contexts deserialize unchanged) and _repair_is_repeating for the follow-on gate. An empty staged repair is now declined with a decision the user can act on instead of a run that cannot help. _repair_is_repeating is also wired in at the point a repair is OFFERED (the config-failure path in handle_test_and_repair, right after diagnose()): a third identical failure clears staged_repair and surfaces a "Repeated failure" card instead of proposing a fourth repair (ESQ1-285/290 burned nine and six approvals this way). Also catalogs the two new user-facing literals in core/dify_builder/ strings.py so test_catalog_covers_handler_literals keeps passing. Co-Authored-By: Claude Opus 5 (1M context) --- api/core/dify_builder/handlers_build.py | 46 +++++++++++++++++++ api/core/dify_builder/models.py | 5 ++ api/core/dify_builder/strings.py | 2 + .../core/dify_builder/test_handlers_build.py | 44 ++++++++++++++++++ 4 files changed, 97 insertions(+) diff --git a/api/core/dify_builder/handlers_build.py b/api/core/dify_builder/handlers_build.py index 4aeac60df0d..f713ea7177c 100644 --- a/api/core/dify_builder/handlers_build.py +++ b/api/core/dify_builder/handlers_build.py @@ -909,6 +909,30 @@ def handle_test_and_repair(env: Env, turn: Turn, s: Session, fc: DifyBuilderCont ) progress.activate("build-diagnose-failure") diagnosis = env.agent.diagnose(run, graph, per_node) + if _repair_is_repeating(fc, diagnosis.root_cause): + # The same failure has now survived _MAX_REPEATED_REPAIRS repairs, so + # another round would aim at the same wrong thing. Stop spending runs + # and hand the decision back (ESQ1-285 burned nine approvals this way, + # ESQ1-290 six). Clearing staged_repair also engages the empty-repair + # guard above, so "Apply the fix" cannot be approved into a no-op. + fc.diagnosis = diagnosis + fc.staged_repair = [] + progress.finish() + stuck_items = append_card( + fc, + ErrorCard( + title="Repeated failure", + body=( + f"{diagnosis.root_cause or 'The run failed.'}\n\n" + "The same error survived the last repairs, so I've stopped retrying. " + "Edit the node directly and test again, or revert." + ), + tone="danger", + node_id=diagnosis.culprit_node_id, + ), + ) + return StepResult(next=PcState.BUILD_AWAIT_REPAIR, context=fc, items=stuck_items) + fc.last_repair_error = diagnosis.root_cause progress.activate("build-prepare-repair") intents, risk = env.agent.propose_repair(diagnosis, graph) fc.diagnosis = diagnosis @@ -972,6 +996,19 @@ def handle_test_and_repair(env: Env, turn: Turn, s: Session, fc: DifyBuilderCont ) +_MAX_REPEATED_REPAIRS = 2 + + +def _repair_is_repeating(fc: DifyBuilderContext, error: str) -> bool: + """Has the SAME error now survived ``_MAX_REPEATED_REPAIRS`` repairs? + + A different error means the loop is still making progress, however + slowly; the identical error twice over means the repair agent is aiming + at something that isn't the cause, and another round will not find it. + """ + return bool(error) and error == fc.last_repair_error and fc.repair_attempts >= _MAX_REPEATED_REPAIRS + + def handle_await_repair(env: Env, turn: Turn, s: Session, fc: DifyBuilderContext) -> StepResult: """(waiting) Post-failure gate mirroring fix.await_decision. approve_repair applies the staged repair and re-runs the test (build.test_and_repair); @@ -979,6 +1016,15 @@ def handle_await_repair(env: Env, turn: Turn, s: Session, fc: DifyBuilderContext here, only on approve.""" kind = action_kind(turn) if kind == "approve_repair": + if not fc.staged_repair: + # Nothing staged: applying would change nothing and the retest + # would fail identically. Don't spend a run on it (ESQ1-291). + items = append_card( + fc, + NoticeItem(text="No fix is staged for this failure -- keep the draft or revert."), + ) + return StepResult(next=PcState.BUILD_AWAIT_REPAIR, context=fc, items=items) + fc.repair_attempts += 1 progress = ProgressReporter.for_session( emit=env.emit_progress, operation_id=env.operation_id, diff --git a/api/core/dify_builder/models.py b/api/core/dify_builder/models.py index 8e2692344d0..a866680e537 100644 --- a/api/core/dify_builder/models.py +++ b/api/core/dify_builder/models.py @@ -251,6 +251,11 @@ class DifyBuilderContext: failed_run_id: str = "" diagnosis: Diagnosis | None = None staged_repair: list[MutationIntent] = field(default_factory=list) + # Repair-loop convergence. Nothing tracked attempts before, so a repair + # that changed nothing could be approved forever (ESQ1-291) and a repair + # aimed at the wrong field could thrash indefinitely (ESQ1-285/290). + repair_attempts: int = 0 + last_repair_error: str = "" risk: Risk | None = None change_set: ChangeSet | None = None checkpoint_id: str = "" diff --git a/api/core/dify_builder/strings.py b/api/core/dify_builder/strings.py index f0c236799fe..9338f71f858 100644 --- a/api/core/dify_builder/strings.py +++ b/api/core/dify_builder/strings.py @@ -52,6 +52,7 @@ PLAIN: frozenset[str] = frozenset( "Test failed — no safe automatic fix; edit or keep draft.", "No automatic fix found — review the diagnosis and edit the canvas manually, or reject.", "The test's outcome couldn't be determined — the run may still be in progress. You can re-run the test.", + "No fix is staged for this failure -- keep the draft or revert.", # card titles "Test run", "Review", @@ -67,6 +68,7 @@ PLAIN: frozenset[str] = frozenset( "High-impact rules", "Model not configured", "Proceeding with sensible defaults", + "Repeated failure", "Test failed", "Validation", # model-config-failure surface (build + edit) diff --git a/api/tests/unit_tests/core/dify_builder/test_handlers_build.py b/api/tests/unit_tests/core/dify_builder/test_handlers_build.py index 7f5d413f2e2..ed14fd0a029 100644 --- a/api/tests/unit_tests/core/dify_builder/test_handlers_build.py +++ b/api/tests/unit_tests/core/dify_builder/test_handlers_build.py @@ -1985,3 +1985,47 @@ def test_the_test_result_card_names_the_dify_run_so_the_canvas_is_reachable_late assert card.payload["dify_run_id"] == "dify-run-1" # and it is NOT the Builder run id the card already carried assert card.payload["dify_run_id"] not in card.payload["run_ids"] + + +def test_await_repair_refuses_to_apply_an_empty_staged_repair(): + """ESQ1-291: approving a zero-intent repair re-tested and re-offered + forever. With nothing staged there is nothing to approve.""" + from core.dify_builder.handlers_build import handle_await_repair + + env, repo = _new_env() + s = _seed_build_session(repo, PcState.BUILD_AWAIT_REPAIR) + fc = DifyBuilderContext() + fc.staged_repair = [] + + turn = Turn(action=Action(kind="approve_repair", base_version=1), actor=_actor()) + out = handle_await_repair(env, turn, s, fc) + + assert out.next == PcState.BUILD_AWAIT_REPAIR + assert out.context.repair_attempts == 0 + assert "notice" in [item.kind for item in out.items] + + +def test_await_repair_counts_attempts_and_stops_repeating_the_same_error(): + from core.dify_builder.handlers_build import _repair_is_repeating + + fc = DifyBuilderContext() + fc.last_repair_error = "Invalid actual value type: number" + fc.repair_attempts = 3 + assert _repair_is_repeating(fc, "Invalid actual value type: number") is True + assert _repair_is_repeating(fc, "Variable ['node2','result'] not found") is False + + fc.repair_attempts = 1 + assert _repair_is_repeating(fc, "Invalid actual value type: number") is False + + +def test_repeated_failure_stops_offering_a_repair(): + """The guard must be REACHED, not merely defined: a third identical + failure clears the staged repair instead of proposing a fourth.""" + from core.dify_builder.handlers_build import _MAX_REPEATED_REPAIRS, _repair_is_repeating + + fc = DifyBuilderContext() + fc.last_repair_error = "Invalid actual value type: number" + fc.repair_attempts = _MAX_REPEATED_REPAIRS + assert _repair_is_repeating(fc, "Invalid actual value type: number") is True + # a NEW error means progress -- keep repairing + assert _repair_is_repeating(fc, "Variable not found") is False