LLM-Driven Extraction of Unstructured Data — Built for API Deployments & ETL Pipeline Workflows
Python ai-agentsdata-engineeringdocument-aigenerative-aiidpjson-extractionllmmcp-serverocrpdf-extractionprompt-engineeringstructured-output
UN-3522 [FEAT] Address Phase 6a Barrier review feedback (#2025)
ali8466e106bacd
diff --git a/workers/api-deployment/tasks.py b/workers/api-deployment/tasks.pyindex 9f87c2c6a..a56f0eb7c 100644--- a/workers/api-deployment/tasks.py+++ b/workers/api-deployment/tasks.py@@ -677,6 +677,12 @@ def _run_workflow_api(# The header tasks + callback now carry the fairness slot for# downstream PG Queue routing — closes the chord-fairness gap noted# in Phase 5.1.+ # Hoist FairnessKey to a local so the chord path and the+ # zero-batch fallback can't drift apart on the slot's shape.+ api_fairness = FairnessKey(+ org_id=str(schema_name),+ workload_type=WorkloadType.API,+ )result = WorkflowOrchestrationUtils.create_chord_execution(batch_tasks=batch_tasks,callback_task_name="process_batch_callback_api",@@ -687,28 +693,44 @@ def _run_workflow_api(},callback_queue=file_processing_callback_queue,app_instance=app,- fairness=FairnessKey(- org_id=str(schema_name),- workload_type=WorkloadType.API,- ),+ fairness=api_fairness,)if not result:+ # TODO(phase-6b): tighten to ``if result is None:``+ # when ``RedisDecrBarrier`` lands. The ``Barrier`` Protocol+ # declares ``None`` as the *sole* "no work enqueued" signal,+ # so identity-against-None is the principled check. Safe to+ # defer today because Celery's ``AsyncResult`` has no custom+ # ``__bool__`` (always truthy), making the truthiness and+ # identity checks behaviourally equivalent. A future+ # substrate handle with a falsy-but-not-None ``__bool__``+ # would be misrouted into the zero-files path under the+ # current truthiness check — that's the regression this TODO+ # forecloses, alongside the substrate that motivates it.+ ## Two reasons ``result`` can be falsy:# 1. Zero ``batch_tasks`` — the barrier short-circuits and# returns ``None``. Pre-Barrier this would have called# ``chord(empty)(callback)`` which Celery handles by# firing the callback immediately with ``[]``. We- # preserve that contract byte-for-byte by dispatching- # the callback explicitly with an empty result list, so+ # preserve that observable end-state by dispatching the+ # callback explicitly with an empty result list, so# workflow_execution_status, API result cache, and# pipeline notifications all run exactly as they would- # have pre-Barrier. (Unreachable in practice — upstream- # requires non-empty ``hash_values_of_files`` — but- # the defence- # closes the theoretical gap.)+ # have pre-Barrier. The new wire isn't literally byte-+ # identical (this is a plain ``send_task`` with an+ # additive fairness header rather than the chord-+ # aggregation primitive), but the observable end-state+ # is equivalent. Effectively unreachable — the upstream+ # ``if not hash_values_of_files:`` early return plus+ # valid ``FileHashData`` inputs mean ``_get_file_batches``+ # always yields >=1 batch — but the defence closes the+ # theoretical gap (e.g. all entries dropped because none+ # are ``FileHashData`` / ``dict``, which would still+ # bypass the upstream guard).# 2. ``batch_tasks`` is non-empty but the barrier returned- # falsy for some other reason — a genuine queue failure.+ # ``None`` for some other reason — a genuine queue failure.if not batch_tasks:logger.info(f"Execution {execution_id} orchestrated with zero "@@ -730,10 +752,7 @@ def _run_workflow_api("organization_id": str(schema_name),},queue=file_processing_callback_queue,- fairness=FairnessKey(- org_id=str(schema_name),- workload_type=WorkloadType.API,- ),+ fairness=api_fairness,)return {"status": "orchestrated",@@ -743,6 +762,13 @@ def _run_workflow_api("files_processed": total_files,"files_from_cache": len(cached_results),"batches_created": 0,+ # ``chord_id`` here is the standalone callback+ # task id (no chord; the dispatch above is a+ # direct ``send_task``). Same response-shape key+ # as the normal path; semantically a task id+ # rather than a chord id. Log/metrics consumers+ # treating ``chord_id`` as "chord identifier"+ # should branch on ``batches_created == 0``."chord_id": callback_result.id,"cached_results": list(cached_results.keys())if cached_resultsdiff --git a/workers/queue_backend/barrier.py b/workers/queue_backend/barrier.pyindex 13c37e520..38b4045c1 100644--- a/workers/queue_backend/barrier.py+++ b/workers/queue_backend/barrier.py@@ -98,10 +98,12 @@ class CeleryChordBarrier:"""Thin wrapper around ``celery.chord``.Behaviour-preserving: the ``chord(header_tasks)(callback_signature)``- call is byte-identical to the inline ``chord(...)`` it replaces.- The only additional behaviour is the optional ``fairness`` header- attachment, which is an additive wire-level change (consumers that- don't read the header are unaffected — same backward-compat+ call shape is the same as the inline ``chord(...)`` it replaces.+ Wire output is byte-identical to the pre-Barrier path when+ ``fairness=None``; when a ``FairnessKey`` is passed the only+ addition is the ``x-fairness-key`` AMQP header on each header+ task and the callback (additive wire-level change — consumers+ that don't read the header are unaffected, same backward-compatposture as Phase 5.1's ``dispatch()`` fairness plumbing).Future ``RedisDecrBarrier`` and ``PgBarrier`` implementations willdiff --git a/workers/tests/test_barrier.py b/workers/tests/test_barrier.pyindex a9ae7fa36..8d24658ca 100644--- a/workers/tests/test_barrier.py+++ b/workers/tests/test_barrier.py@@ -28,6 +28,8 @@ The single ``chord(...)`` call still lives infrom __future__ import annotations+import contextlib+from dataclasses import dataclassfrom unittest.mock import MagicMock, patchimport pytest@@ -82,17 +84,59 @@ class TestBarrierProtocolShape:barrier: Barrier = CeleryChordBarrier()assert callable(getattr(barrier, "enqueue", None))- def test_barrier_handle_protocol_is_minimal(self):- """``BarrierHandle`` only requires ``id: str`` — celery's- ``AsyncResult`` satisfies this. Future substrate handles must- too so existing chord-id logging keeps working."""- # MagicMock with .id attribute is structurally a BarrierHandle.- handle = MagicMock()- handle.id = "task-1"- # Treating it as a BarrierHandle at runtime works (Python's- # Protocols are duck-typed; this test pins the contract).- h: BarrierHandle = handle- assert h.id == "task-1"+ def test_barrier_handle_protocol_satisfied_by_celery_async_result(self):+ """The real production substrate handle — Celery's+ ``AsyncResult`` — must satisfy ``BarrierHandle``. Without+ this, refactors of ``BarrierHandle`` (e.g. adding a+ required attribute) would silently break chord-id logging+ in ``api-deployment/tasks.py``'s response without any test+ catching it. Tautological MagicMock-with-.id-attribute+ tests pass identically even if ``BarrierHandle`` were+ deleted; this one is load-bearing.+ """+ from celery.result import AsyncResult++ # Assert against a real ``AsyncResult`` *instance* — that's+ # what every production call site receives and logs ``.id``+ # from. We don't rely on whether the attribute is class-level,+ # a property, or set in ``__init__``; the instance check is+ # the smallest-blast-radius equivalent of "production sees+ # this object and reads ``.id``".+ #+ # ``required_attrs`` is hand-maintained: if a future refactor+ # adds a required attribute to ``TaskHandle`` /+ # ``BarrierHandle``, add it here too. We do *not* introspect+ # ``TaskHandle.__annotations__`` because runtime-checkable+ # Protocols would force every substrate handle (including+ # third-party ones we don't control) to be runtime-checkable+ # too. Trade-off: the maintenance is manual but the contract+ # is enforced.+ async_result_instance = AsyncResult("placeholder-task-id")+ required_attrs = ("id",)+ missing = [+ a for a in required_attrs if not hasattr(async_result_instance, a)+ ]+ assert missing == [], (+ f"AsyncResult is missing required BarrierHandle attribute(s): "+ f"{missing} — a refactor of BarrierHandle / TaskHandle has "+ f"silently broken the Celery substrate."+ )+ # Pin the declared type too — ``TaskHandle`` says ``id: str``+ # and chord-id logging in the response dict treats it as a+ # string. A future substrate that satisfies ``hasattr`` with+ # e.g. a UUID object or ``None`` would slip past the+ # attribute-presence check above.+ assert isinstance(async_result_instance.id, str), (+ f"AsyncResult.id should be a str (TaskHandle declares "+ f"``id: str``); got {type(async_result_instance.id).__name__}"+ )++ # And ``DispatchHandle`` / ``BarrierHandle`` should both be+ # the same shared ``TaskHandle`` Protocol (no drift risk).+ from queue_backend.handle import DispatchHandle, TaskHandle++ assert BarrierHandle is TaskHandle+ assert DispatchHandle is TaskHandle# --- Wire equivalence with the pre-Barrier chord call ---@@ -358,103 +402,568 @@ class TestOrchestrationUtilsRoutesThroughSingleton:)-# --- Call-site fairness contracts ---+# --- Executing tests for call-site fairness contracts ---+++def _load_api_deployment_tasks():+ """Load ``api-deployment/tasks.py`` as a module.++ The dash in ``api-deployment`` blocks normal ``import+ api-deployment.tasks``. We load via ``importlib.util`` instead so+ the test can drive the real ``_run_workflow_api`` function rather+ than scraping its source.+ """+ import importlib.util+ import inspect+ import pathlib++ src = inspect.getfile(__import__("queue_backend.barrier", fromlist=["a"]))+ api_tasks_path = (+ pathlib.Path(src).parent.parent / "api-deployment" / "tasks.py"+ )+ spec = importlib.util.spec_from_file_location(+ "_api_deployment_tasks_for_test", api_tasks_path+ )+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+++@dataclass+class _WorkflowApiMocks:+ """Spy bundle from ``_setup_workflow_api_mocks``.++ All attributes are bound *before* the production function runs,+ so a test asserting on spies after a raising call (e.g. the+ queue-failure branch) can still inspect them.+ """++ api_tasks: object+ api_client: MagicMock+ create_chord: MagicMock+ dispatch: MagicMock+ decisions_helper: MagicMock+++# Three production branches under test, one knob. Replacing+# ``force_empty_batches`` + ``force_falsy_chord_with_batches`` (two+# bools encoding three states with a runtime mutual-exclusivity+# guard) — the illegal ``(True, True)`` combination is now+# unrepresentable.+_VALID_CHORD_OUTCOMES = ("success", "empty_batches", "queue_failure")+++def _setup_workflow_api_mocks(+ monkeypatch,+ *,+ chord_outcome: str = "success",+ manual_review_required: bool = False,+ num_batches: int = 1,+) -> _WorkflowApiMocks:+ """Setup mocks; caller drives ``_run_workflow_api``.++ Use this when the test needs to assert on spies *after* the+ production function raises (e.g. the queue-failure branch).+ Tests that don't need post-raise assertions can use the thin+ convenience wrapper ``_run_workflow_api_with_mocks``.++ ``chord_outcome`` controls which production branch fires:++ - ``"success"`` — non-empty batches, truthy chord handle. Normal+ chord path completes.+ - ``"empty_batches"`` — ``_get_file_batches`` yields ``[]``,+ chord returns ``None``. Zero-batch defensive dispatch fires.+ - ``"queue_failure"`` — ``_get_file_batches`` yields non-empty+ batches, chord returns ``None`` anyway. Production raises so+ the outer handler can map to ``ExecutionStatus.ERROR``.++ ``num_batches`` controls how many batches ``_get_file_batches``+ returns when ``chord_outcome != "empty_batches"`` — set >1 to+ exercise per-batch multiplicity contracts (e.g. the manual-+ review decision helper is invoked once per batch).+ """+ if chord_outcome not in _VALID_CHORD_OUTCOMES:+ raise AssertionError(+ f"chord_outcome must be one of {_VALID_CHORD_OUTCOMES}, "+ f"got {chord_outcome!r}"+ )++ api_tasks = _load_api_deployment_tasks()+ api_client = MagicMock(name="api_client")+ api_client.get_workflow_execution.return_value = MagicMock(+ success=True, error=None, data={}+ )+ api_client.get_file_history_for_files.return_value = MagicMock(+ success=True, data={"files": {}}+ )+ api_client.update_workflow_execution_status.return_value = MagicMock(success=True)+ api_client.update_pipeline_status.return_value = MagicMock(success=True)++ # Neutralise heavy upstream side effects.+ monkeypatch.setattr(+ api_tasks, "validate_workflow_tool_instances", lambda **kwargs: None+ )+ monkeypatch.setattr(+ api_tasks, "_log_api_file_history_statistics", lambda **kwargs: None+ )+ monkeypatch.setattr(+ api_tasks, "_log_api_batch_creation_statistics", lambda **kwargs: None+ )++ # ``_get_file_batches`` always patched — the real implementation+ # filters non-``FileHashData``/``dict`` entries, which would drop+ # ``MagicMock`` values and silently route into the zero-batch+ # branch. Patching here gives the caller deterministic control+ # over both the branch under test and the batch count.+ if chord_outcome == "empty_batches":+ batches_to_return: list[list[str]] = []+ else:+ batches_to_return = [+ [f"file_in_batch_{i}"] for i in range(num_batches)+ ]+ monkeypatch.setattr(+ api_tasks, "_get_file_batches", lambda **kwargs: batches_to_return+ )++ # Neutralise the per-batch helpers so ``batch_tasks`` is non-empty+ # without constructing real ``FileBatchData`` objects.+ mock_file_data = MagicMock(name="file_data")+ # Real dict (not MagicMock) so ``.get("review_required", False)``+ # returns the requested bool — MagicMocks would return truthy by+ # default from ``.get()``, forcing the manual-review branch.+ mock_file_data.manual_review_config = {+ "review_required": manual_review_required,+ }+ monkeypatch.setattr(+ api_tasks, "_create_file_data", lambda **kwargs: mock_file_data+ )+ monkeypatch.setattr(+ api_tasks, "_create_batch_data", lambda **kwargs: {"batch": "data"}+ )+ # Always create the decisions-helper spy and install it; tests+ # that don't flip ``manual_review_required`` simply never see it+ # invoked. Exposing it on the spy bundle removes the previous+ # caller-supplied/fallback dead branch.+ decisions_helper = MagicMock(+ name="_calculate_manual_review_decisions_for_batch_api",+ return_value=[False],+ )+ if manual_review_required:+ monkeypatch.setattr(+ api_tasks,+ "_calculate_manual_review_decisions_for_batch_api",+ decisions_helper,+ )++ mock_create_chord = MagicMock(name="create_chord_execution")+ # Truthy handle on the success path; ``None`` on the two failure+ # paths. Production's ``if not result:`` branch (today; a future+ # phase-6b PR may tighten to ``if result is None:`` — see the+ # TODO at the call site in ``api-deployment/tasks.py``) then+ # distinguishes the two ``None`` cases via ``batch_tasks`` length.+ if chord_outcome == "success":+ mock_create_chord.return_value = MagicMock(id="chord-result-id")+ else:+ mock_create_chord.return_value = None+ monkeypatch.setattr(+ api_tasks.WorkflowOrchestrationUtils,+ "create_chord_execution",+ mock_create_chord,+ )++ mock_dispatch_result = MagicMock(name="dispatch_result")+ mock_dispatch_result.id = "callback-task-id"+ mock_dispatch = MagicMock(name="dispatch", return_value=mock_dispatch_result)+ monkeypatch.setattr(api_tasks, "dispatch", mock_dispatch)++ return _WorkflowApiMocks(+ api_tasks=api_tasks,+ api_client=api_client,+ create_chord=mock_create_chord,+ dispatch=mock_dispatch,+ decisions_helper=decisions_helper,+ )+++def _run_workflow_api_with_mocks(+ monkeypatch,+ *,+ hash_values_of_files: dict | None = None,+ chord_outcome: str = "success",+ manual_review_required: bool = False,+ num_batches: int = 1,+):+ """Convenience wrapper around ``_setup_workflow_api_mocks``.++ Setup + run; returns ``(result, create_chord, dispatch)`` for+ tests where ``_run_workflow_api`` doesn't raise. Tests that need+ to assert on spies after a raising call should use+ ``_setup_workflow_api_mocks`` directly so the spies are bound+ before the raise.+ """+ mocks = _setup_workflow_api_mocks(+ monkeypatch,+ chord_outcome=chord_outcome,+ manual_review_required=manual_review_required,+ num_batches=num_batches,+ )+ files = hash_values_of_files if hash_values_of_files is not None else {+ "f1": MagicMock(name="FileHashData_f1"),+ }+ result = mocks.api_tasks._run_workflow_api(+ api_client=mocks.api_client,+ schema_name="org_test",+ workflow_id="wf-1",+ execution_id="exec-1",+ hash_values_of_files=files,+ scheduled=False,+ execution_mode=None,+ pipeline_id="pipe-1",+ use_file_history=False,+ task_id="task-1",+ )+ return result, mocks.create_chord, mocks.dispatchclass TestCallSiteFairnessContracts:"""Pin the ``FairnessKey`` shape each production call site declares.- A refactor that swaps the workload types, drops the ``fairness=``- kwarg, or transposes the org-id source goes undetected by the- isolated barrier tests above. These tests assert the contract at- the call site boundary.+ These were originally source-string-match tests. The problem:+ ``FairnessKey(...)`` appears at *both* the chord call site and+ the zero-batch fallback in ``api-deployment/tasks.py``, so a+ substring assertion would pass even if the primary chord call+ dropped ``fairness=`` entirely. These executing tests patch the+ helper and inspect the actual call args."""- def test_api_deployment_declares_api_workload_with_schema_name(self):- """``api-deployment/tasks.py`` must pass ``WorkloadType.API``- and ``org_id=str(schema_name)``.+ def test_api_deployment_passes_api_fairness_to_create_chord(+ self, monkeypatch+ ):+ """The chord call site in ``_run_workflow_api`` must pass+ ``fairness=FairnessKey(org_id=str(schema_name),+ workload_type=WorkloadType.API)`` to ``create_chord_execution``."""+ # ``chord_outcome="success"`` patches ``_get_file_batches``+ # to return a non-empty list and ``create_chord_execution``+ # to return a truthy handle so the chord path actually fires+ # (helper patches documented in ``_setup_workflow_api_mocks``).+ _result, mock_create_chord, mock_dispatch = _run_workflow_api_with_mocks(+ monkeypatch,+ hash_values_of_files={"f1": MagicMock(name="file_1")},+ chord_outcome="success",+ )+ # ``create_chord_execution`` MUST be called with the right+ # fairness — a refactor that drops ``fairness=`` or swaps the+ # workload type fails here loudly.+ assert mock_create_chord.called, (+ "_run_workflow_api did not call create_chord_execution"+ )+ fairness_kwarg = mock_create_chord.call_args.kwargs.get("fairness")+ assert fairness_kwarg is not None, "fairness= kwarg missing"+ assert fairness_kwarg == FairnessKey(+ org_id="org_test", workload_type=WorkloadType.API+ )+ # And the zero-batch fallback ``dispatch(...)`` MUST NOT have+ # fired — otherwise this test would silently pass via the+ # fallback's own ``fairness=`` argument even if the primary+ # ``create_chord_execution`` call dropped its ``fairness=``.+ # (Code-review feedback — no assertion in the original revision.)+ assert not mock_dispatch.called, (+ "Zero-batch fallback dispatch fired during the chord-path "+ "test — _get_file_batches mock returned empty unexpectedly, "+ "or create_chord_execution returned falsy. The chord-path "+ "fairness assertion above would otherwise be exercising the "+ "fallback's own fairness arg, not the chord call's."+ )+ # Header-task batch_tasks must be non-empty (else create_chord+ # would have been a no-op pass-through to the empty-header+ # guard inside the barrier).+ batch_tasks = mock_create_chord.call_args.kwargs.get("batch_tasks")+ assert batch_tasks, (+ "batch_tasks passed to create_chord_execution was empty — "+ "the chord path was not actually exercised"+ )++ def test_general_passes_non_api_fairness_to_create_chord(self, monkeypatch):+ """``general/tasks.py``'s ``_orchestrate_file_processing_general``+ must pass ``fairness=FairnessKey(org_id=organization_id,+ workload_type=WorkloadType.NON_API)`` to ``create_chord_execution``.- ``api-deployment`` is not a valid Python identifier (the dash- prevents ``import api-deployment.tasks``), so the test reads- the source file by path instead of importing the module.+ ``general/tasks.py`` is directly importable (no dash), so the+ test patches the helper at the module level and drives the+ function with a minimal fixture."""- import inspect- import pathlib+ from general import tasks as general_tasks++ api_client = MagicMock(name="api_client")+ api_client.get_workflow_execution.return_value = MagicMock(+ success=True, data={}+ )+ api_client.update_workflow_execution_status.return_value = MagicMock(+ success=True+ )++ # Patch only what's needed to reach the chord call.+ monkeypatch.setattr(+ general_tasks,+ "_get_file_batches_general",+ lambda **kwargs: [MagicMock(name="batch_1")],+ )+ monkeypatch.setattr(+ general_tasks, "_create_batch_data_general", lambda **kwargs: MagicMock()+ )- # Derive workers root from a sibling importable module- # (``queue_backend.barrier``) so the path stays correct under- # any test runner working directory.- src = inspect.getfile(__import__("queue_backend.barrier", fromlist=["a"]))- api_tasks_path = (- pathlib.Path(src).parent.parent / "api-deployment" / "tasks.py"+ mock_create_chord = MagicMock(name="create_chord_execution")+ mock_create_chord.return_value = MagicMock(id="chord-id")+ monkeypatch.setattr(+ general_tasks.WorkflowOrchestrationUtils,+ "create_chord_execution",+ mock_create_chord,+ )++ # ``contextlib.suppress`` over a bare ``except Exception: pass``+ # to declare intent explicitly: any post-``create_chord_execution``+ # raise (e.g. the mocked api_client's status update path) is+ # tolerated, because the next ``assert mock_create_chord.called``+ # is what proves the chord call was actually reached.+ with contextlib.suppress(Exception):+ general_tasks._orchestrate_file_processing_general(+ api_client=api_client,+ workflow_id="wf-1",+ execution_id="exec-1",+ source_files={"f1": MagicMock(name="file_1")},+ pipeline_id="pipe-1",+ scheduled=False,+ execution_mode=None,+ use_file_history=False,+ organization_id="org_test",+ )++ assert mock_create_chord.called, (+ "_orchestrate_file_processing_general did not call "+ "create_chord_execution"+ )+ fairness_kwarg = mock_create_chord.call_args.kwargs.get("fairness")+ assert fairness_kwarg is not None, "fairness= kwarg missing"+ assert fairness_kwarg == FairnessKey(+ org_id="org_test", workload_type=WorkloadType.NON_API+ )+ # Match the api-deployment sibling: header tasks must be+ # non-empty so we're not silently exercising an empty-header+ # short-circuit.+ batch_tasks = mock_create_chord.call_args.kwargs.get("batch_tasks")+ assert batch_tasks, (+ "batch_tasks passed to create_chord_execution was empty — "+ "the chord path was not actually exercised")- text = api_tasks_path.read_text()- # Assert the FairnessKey block at the chord call site declares- # the contract this PR's commit message claims it does.- assert "fairness=FairnessKey(" in text- assert "workload_type=WorkloadType.API" in text- assert "org_id=str(schema_name)" in text- def test_general_declares_non_api_workload_with_organization_id(self):- """``general/tasks.py`` must pass ``WorkloadType.NON_API`` and- ``org_id=organization_id``."""- import inspect- import pathlib+class TestApiDeploymentZeroFilesContract:+ """Executing pin for the api-deployment zero-batch handler.++ Originally a source-string-match test. The problem with the+ string-match form: it would pass even if the dispatch branch+ were deleted — the matched tokens (``args=[[]]``,+ ``process_batch_callback_api``, ``if not batch_tasks:``) also+ appear on the chord path or in surrounding code. A test that+ doesn't execute the branch can't prove the branch works.++ This version drives the actual code path via ``_run_workflow_api``+ with mocked dependencies and forced-empty batches, then asserts+ ``dispatch(...)`` is called once with the chord-empty semantic+ (``args=[[]]``) and the same fairness slot the chord path would+ have used.++ Effectively unreachable in production — the upstream ``if not+ hash_values_of_files:`` early return plus valid ``FileHashData``+ inputs mean ``_get_file_batches`` always yields >=1 batch — but+ the executing test locks the defensive contract so a future+ refactor that drops it fails loudly.+ """- src = inspect.getfile(__import__("queue_backend.barrier", fromlist=["a"]))- general_tasks_path = (- pathlib.Path(src).parent.parent / "general" / "tasks.py"+ def test_zero_batch_branch_dispatches_callback_with_empty_list(+ self, monkeypatch+ ):+ result, _create_chord, mock_dispatch = _run_workflow_api_with_mocks(+ monkeypatch,+ hash_values_of_files={"f1": MagicMock(name="file_1")},+ chord_outcome="empty_batches",)- text = general_tasks_path.read_text()- assert "fairness=FairnessKey(" in text- assert "workload_type=WorkloadType.NON_API" in text- assert "org_id=organization_id" in text+ # Dispatch was called exactly once, with the chord-empty+ # semantic (args=[[]]) and the same fairness slot the chord+ # path uses.+ mock_dispatch.assert_called_once()+ call = mock_dispatch.call_args+ assert call.args[0] == "process_batch_callback_api"+ assert call.kwargs.get("args") == [[]]+ callback_kwargs = call.kwargs.get("kwargs")+ assert callback_kwargs == {+ "execution_id": "exec-1",+ "pipeline_id": "pipe-1",+ "organization_id": "org_test",+ }+ # Pin the callback queue too — without this a refactor that+ # routes the zero-batch callback to the wrong queue (or drops+ # the ``queue=`` kwarg entirely) would pass undetected.+ # (Code-review feedback — no assertion in the original revision.)+ assert call.kwargs.get("queue") == "api_file_processing_callback"+ assert call.kwargs.get("fairness") == FairnessKey(+ org_id="org_test", workload_type=WorkloadType.API+ )+ # Response shape: orchestrated with zero batches, callback+ # task id surfaced as chord_id (semantically a task id, not a+ # chord id — see the inline comment at the call site).+ assert result["status"] == "orchestrated"+ assert result["batches_created"] == 0+ assert result["chord_id"] == "callback-task-id"-# --- Zero-files contract (regression pin for T1) ---+class TestApiDeploymentQueueFailureContract:+ """Executing pin for the "genuine queue failure" branch.-class TestApiDeploymentZeroFilesContract:- """Pin the api-deployment zero-files handler.-- Before the Barrier uplift, ``chord(empty)(callback)`` returned a- truthy ``AsyncResult`` (Celery fires the body immediately with- ``[]``). The Barrier returns ``None`` for empty headers, so the- caller now has to handle the ``None`` case explicitly — otherwise- the existing ``if not result: raise`` would map zero-files runs- to ``ExecutionStatus.ERROR``.-- The post-Barrier handler explicitly dispatches the callback with- an empty result list to preserve pre-Barrier behaviour- byte-for-byte: ``workflow_execution_status`` updates, API result- caching, and pipeline notifications all run exactly as they would- have pre-Barrier. Unreachable in practice (upstream guarantees- non-empty ``hash_values_of_files``) but this test pins the defensive- contract so a future refactor doesn't silently regress.+ When ``batch_tasks`` is non-empty but ``create_chord_execution``+ returns ``None`` (a broker outage / serialisation failure that+ bypasses the empty-header guard), the production code raises+ and the outer handler maps it to ``ExecutionStatus.ERROR``.++ This is the higher-severity sub-branch — a broker failure+ mapping to ERROR is real production behaviour, not the+ unreachable zero-files defence; this branch can fire on a real+ broker outage or serialisation failure."""- def test_api_deployment_zero_files_dispatches_callback_with_empty_list(self):- import inspect- import pathlib-- src = inspect.getfile(__import__("queue_backend.barrier", fromlist=["a"]))- api_tasks_path = (- pathlib.Path(src).parent.parent / "api-deployment" / "tasks.py"- )- text = api_tasks_path.read_text()-- # Defensive branch present and dispatches the callback via- # the seam (queue_backend.dispatch), not raw send_task — the- # dispatch-sites canary in test_dispatch_sites_characterisation.py- # enforces that. The literal strings are part of the- # externally-observable response + behaviour contract.- assert "if not batch_tasks:" in text- assert "dispatch(" in text # routed through queue_backend seam- assert '"process_batch_callback_api"' in text # callback fired- assert "args=[[]]" in text # body=[] matches chord-empty semantic- assert '"batches_created": 0' in text+ def test_falsy_chord_with_non_empty_batches_raises(self, monkeypatch):+ """When the barrier returns ``None`` despite non-empty+ ``batch_tasks``, ``_run_workflow_api`` must raise — the outer+ task handler then maps this to ``ExecutionStatus.ERROR`` for+ the pipeline status update."""+ # Pin the exact production message rather than a loose+ # ``queue|failed|chord`` regex — the loose form would also+ # match a misconfigured-harness ``AssertionError`` or any+ # setup error whose message contains "failed", masking a+ # harness misconfiguration as a passing assertion.+ mocks = _setup_workflow_api_mocks(+ monkeypatch, chord_outcome="queue_failure"+ )+ with pytest.raises(Exception, match=r"Failed to queue execution task exec-1"):+ mocks.api_tasks._run_workflow_api(+ api_client=mocks.api_client,+ schema_name="org_test",+ workflow_id="wf-1",+ execution_id="exec-1",+ hash_values_of_files={"f1": MagicMock(name="file_1")},+ scheduled=False,+ execution_mode=None,+ pipeline_id="pipe-1",+ use_file_history=False,+ task_id="task-1",+ )++ def test_falsy_chord_with_non_empty_batches_does_not_dispatch_fallback(+ self, monkeypatch+ ):+ """The fallback ``dispatch(args=[[]], ...)`` MUST NOT fire on+ the genuine-queue-failure branch — that's reserved for the+ zero-batch defence. A future refactor that routed both+ falsy-result cases through the same fallback would silently+ lose the ERROR signal.++ Previous revision had this assertion inside+ ``contextlib.suppress(Exception)`` and bound ``mock_dispatch``+ from the function's tuple return — which never executed because+ the production code raised before the return. ``AssertionError``+ is an ``Exception`` so the suppress would have swallowed any+ failing assert too. Both defects fixed by:++ 1. Setting up mocks via ``_setup_workflow_api_mocks`` so spies+ are bound *before* ``_run_workflow_api`` runs.+ 2. Asserting on ``mocks.dispatch.called`` *outside* the+ ``pytest.raises`` block so an assertion failure surfaces.+ """+ mocks = _setup_workflow_api_mocks(+ monkeypatch, chord_outcome="queue_failure"+ )+ with pytest.raises(Exception, match=r"Failed to queue execution task exec-1"):+ mocks.api_tasks._run_workflow_api(+ api_client=mocks.api_client,+ schema_name="org_test",+ workflow_id="wf-1",+ execution_id="exec-1",+ hash_values_of_files={"f1": MagicMock(name="file_1")},+ scheduled=False,+ execution_mode=None,+ pipeline_id="pipe-1",+ use_file_history=False,+ task_id="task-1",+ )+ # The fallback dispatch was monkeypatched on the module and+ # survives the raise; assert outside the ``pytest.raises``+ # block so an assertion failure isn't swallowed.+ assert not mocks.dispatch.called, (+ "Genuine queue failure must raise, not silently dispatch the "+ "zero-batch fallback callback"+ )+++class TestApiDeploymentManualReviewContract:+ """Executing pin for the manual-review decision branch.++ When ``file_data.manual_review_config["review_required"]`` is+ ``True``, the per-batch loop calls+ ``_calculate_manual_review_decisions_for_batch_api`` to mutate+ ``manual_review_config["file_decisions"]`` before the batch+ data rides the chord. The base ``_run_workflow_api_with_mocks``+ hard-codes ``review_required=False`` for the other tests, so+ this class flips the knob to keep the manual-review path+ exercised under an executing test.+ """++ def test_manual_review_required_invokes_decision_helper_per_batch(+ self, monkeypatch+ ):+ """With ``review_required=True``, the decision helper is+ invoked exactly once per batch and the chord still fires+ with the same fairness slot as the non-review path.++ Drives the helper with ``num_batches=3`` so the "once per+ batch" contract is genuinely exercised — a regression+ invoking the helper 0× or 2× per batch wouldn't be caught+ with only one batch."""+ num_batches = 3+ mocks = _setup_workflow_api_mocks(+ monkeypatch,+ chord_outcome="success",+ manual_review_required=True,+ num_batches=num_batches,+ )+ mocks.api_tasks._run_workflow_api(+ api_client=mocks.api_client,+ schema_name="org_test",+ workflow_id="wf-1",+ execution_id="exec-1",+ hash_values_of_files={"f1": MagicMock(name="file_1")},+ scheduled=False,+ execution_mode=None,+ pipeline_id="pipe-1",+ use_file_history=False,+ task_id="task-1",+ )++ # N batches → exactly N helper calls.+ assert mocks.decisions_helper.call_count == num_batches, (+ f"Manual-review decision helper must run once per batch — "+ f"got {mocks.decisions_helper.call_count}, "+ f"expected {num_batches}"+ )+ # Chord path still fires with API fairness — the manual-review+ # branch must not divert into the fallback dispatch.+ assert mocks.create_chord.called+ assert not mocks.dispatch.called+ fairness_kwarg = mocks.create_chord.call_args.kwargs.get("fairness")+ assert fairness_kwarg == FairnessKey(+ org_id="org_test", workload_type=WorkloadType.API+ )if __name__ == "__main__":diff --git a/workers/tests/test_chord_sites_characterisation.py b/workers/tests/test_chord_sites_characterisation.pyindex 79a8202e6..5732ef44e 100644--- a/workers/tests/test_chord_sites_characterisation.py+++ b/workers/tests/test_chord_sites_characterisation.py@@ -274,9 +274,20 @@ class TestChordSiteInventory:but rejects docstring / comment mentions like ``the chord(...)primitive``.- Comment / docstring lines are also explicitly skipped as- belt-and-suspenders against a future call site that lacks the- ``=`` prefix (e.g. a return-value-discarded ``chord(...)``).+ **Known blind spot**: a return-value-discarded ``chord(batch)(cb)``+ at column 0 (no assignment) would slip past this regex AND the+ comment-line filter. The companion ``test_chord_import_only_in_barrier``+ canary catches the common ``from celery import chord`` import+ form — so a stray call site reachable via that import would+ still trip it. However, aliased imports (``from celery import+ chord as c``) or module-attribute access (``import celery`` ++ ``celery.chord(...)``) would evade *both* canaries. We accept+ this gap because (a) those import shapes are non-idiomatic and+ not used anywhere in workers/, and (b) ``barrier.py`` is the+ sole sanctioned chord call site in the codebase, so any stray+ call would surface in code review long before runtime. If a+ future PR ships either of those import shapes outside+ ``barrier.py``, the canaries need broadening."""import pathlibimport re