Skip to content

LLM-Driven Extraction of Unstructured Data — Built for API Deployments & ETL Pipeline Workflows

UN-3508 [FEAT] Plumb fairness through ExecutionDispatcher (#2009)

ali7c0e25102fbe
diff --git a/unstract/sdk1/src/unstract/sdk1/execution/dispatcher.py b/unstract/sdk1/src/unstract/sdk1/execution/dispatcher.py
index e6be76d7c..25a5da1f0 100644
--- a/unstract/sdk1/src/unstract/sdk1/execution/dispatcher.py
+++ b/unstract/sdk1/src/unstract/sdk1/execution/dispatcher.py
@@ -99,10 +99,46 @@ class ExecutionDispatcher:
"""
return f"{_QUEUE_PREFIX}{executor_name}"
+ @staticmethod
+ def _build_send_kwargs(
+ context: ExecutionContext,
+ queue: str,
+ *,
+ headers: dict[str, Any] | None = None,
+ link: Signature | None = None,
+ link_error: Signature | None = None,
+ task_id: str | None = None,
+ ) -> dict[str, Any]:
+ """Common ``send_task`` kwargs builder for the three dispatch modes.
+
+ Optional kwargs are dropped when ``None`` so the resulting call
+ shape matches the minimum-arity form Celery expects for ``link``
+ / ``link_error`` handling and so callers that pass no headers
+ see the same on-wire call as before headers existed.
+ """
+ out: dict[str, Any] = {
+ "args": [context.to_dict()],
+ "queue": queue,
+ }
+ # Treat falsy (None, ``{}``) as drop. An empty header dict is
+ # never legitimate — ``FairnessKey.as_header()`` always returns
+ # a populated mapping — so silently forwarding ``{}`` would
+ # document a producer-side build bug rather than catch it.
+ if headers:
+ out["headers"] = headers
+ if link is not None:
+ out["link"] = link
+ if link_error is not None:
+ out["link_error"] = link_error
+ if task_id is not None:
+ out["task_id"] = task_id
+ return out
+
def dispatch(
self,
context: ExecutionContext,
timeout: int | None = None,
+ headers: dict[str, Any] | None = None,
) -> ExecutionResult:
"""Dispatch context as a Celery task and wait for result.
@@ -111,6 +147,15 @@ class ExecutionDispatcher:
timeout: Max seconds to wait. ``None`` reads from
the ``EXECUTOR_RESULT_TIMEOUT`` env var,
falling back to 3600s.
+ headers: Optional Celery message headers (routing metadata
+ out-of-band of the task body — see
+ ``queue_backend.fairness.FAIRNESS_HEADER_NAME``
+ (currently ``"x-fairness-key"``) for the canonical
+ constant). Caller is responsible for the header schema.
+ Falsy values (``None``, ``{}``) are dropped — the
+ downstream ``send_task`` call is invoked without
+ ``headers=`` so the on-wire shape matches the
+ no-headers baseline.
Returns:
ExecutionResult from the executor.
@@ -136,11 +181,8 @@ class ExecutionDispatcher:
queue,
)
- async_result = self._app.send_task(
- _TASK_NAME,
- args=[context.to_dict()],
- queue=queue,
- )
+ send_kwargs = self._build_send_kwargs(context, queue, headers=headers)
+ async_result = self._app.send_task(_TASK_NAME, **send_kwargs)
logger.info(
"Task sent: celery_task_id=%s, waiting for result...",
async_result.id,
@@ -172,11 +214,13 @@ class ExecutionDispatcher:
def dispatch_async(
self,
context: ExecutionContext,
+ headers: dict[str, Any] | None = None,
) -> str:
"""Dispatch without waiting. Returns task_id for polling.
Args:
context: ExecutionContext to dispatch.
+ headers: Optional Celery message headers (see ``dispatch``).
Returns:
The Celery task ID (use with ``AsyncResult`` to poll).
@@ -198,11 +242,8 @@ class ExecutionDispatcher:
queue,
)
- async_result = self._app.send_task(
- _TASK_NAME,
- args=[context.to_dict()],
- queue=queue,
- )
+ send_kwargs = self._build_send_kwargs(context, queue, headers=headers)
+ async_result = self._app.send_task(_TASK_NAME, **send_kwargs)
return async_result.id
def dispatch_with_callback(
@@ -211,6 +252,7 @@ class ExecutionDispatcher:
on_success: Signature | None = None,
on_error: Signature | None = None,
task_id: str | None = None,
+ headers: dict[str, Any] | None = None,
) -> AsyncResult:
"""Fire-and-forget dispatch with Celery link callbacks.
@@ -231,6 +273,7 @@ class ExecutionDispatcher:
task_id: Optional pre-generated Celery task ID. Useful
when the caller needs to know the task ID before
dispatch (e.g. to include it in callback kwargs).
+ headers: Optional Celery message headers (see ``dispatch``).
Returns:
The ``AsyncResult`` from ``send_task``. Callers can
@@ -257,21 +300,15 @@ class ExecutionDispatcher:
queue,
)
- send_kwargs: dict[str, Any] = {
- "args": [context.to_dict()],
- "queue": queue,
- }
- if on_success is not None:
- send_kwargs["link"] = on_success
- if on_error is not None:
- send_kwargs["link_error"] = on_error
- if task_id is not None:
- send_kwargs["task_id"] = task_id
-
- async_result = self._app.send_task(
- _TASK_NAME,
- **send_kwargs,
+ send_kwargs = self._build_send_kwargs(
+ context,
+ queue,
+ headers=headers,
+ link=on_success,
+ link_error=on_error,
+ task_id=task_id,
)
+ async_result = self._app.send_task(_TASK_NAME, **send_kwargs)
logger.info(
"Task sent with callbacks: celery_task_id=%s",
async_result.id,
diff --git a/workers/file_processing/structure_tool_task.py b/workers/file_processing/structure_tool_task.py
index d89d1c9d6..cfa0e316a 100644
--- a/workers/file_processing/structure_tool_task.py
+++ b/workers/file_processing/structure_tool_task.py
@@ -23,7 +23,8 @@ from pathlib import Path
from typing import Any
from file_processing.worker import app
-from queue_backend import worker_task
+from queue_backend import FairnessKey, worker_task
+from queue_backend.fairness import WorkloadType
from shared.enums.task_enums import TaskName
from shared.infrastructure.context import StateStore
@@ -39,6 +40,26 @@ logger = logging.getLogger(__name__)
EXECUTOR_TIMEOUT = int(os.environ.get("EXECUTOR_RESULT_TIMEOUT", 3600))
+def _fairness_headers(
+ organization_id: str,
+) -> dict[str, dict[str, str | int | None]]:
+ """Fairness header for executor dispatches.
+
+ Structure-tool dispatches are workflow-execution work — both ETL
+ and API workflows route through here. ``NON_API`` is the safe
+ default (API traffic preempting is a strictly weaker mistake than
+ the inverse).
+
+ TODO(UN-3504): propagate the caller's WorkloadType (API vs ETL)
+ instead of hard-coding ``NON_API``. Requires the chord-lift work
+ so the workflow type flows from the chord caller down to here.
+ """
+ return FairnessKey(
+ org_id=organization_id,
+ workload_type=WorkloadType.NON_API,
+ ).as_header()
+
+
# -----------------------------------------------------------------------
# Constants mirrored from tools/structure/src/constants.py
# These are the keys used in tool_metadata and payload dicts.
@@ -465,7 +486,11 @@ def _execute_structure_tool_impl(params: dict) -> dict:
file_execution_id=file_execution_id,
executor_params=agentic_params,
)
- at_result = dispatcher.dispatch(at_ctx, timeout=EXECUTOR_TIMEOUT)
+ at_result = dispatcher.dispatch(
+ at_ctx,
+ timeout=EXECUTOR_TIMEOUT,
+ headers=_fairness_headers(organization_id),
+ )
if not at_result.success:
return at_result.to_dict()
at_output_data = at_result.data.get("output", {}) or {}
@@ -504,7 +529,11 @@ def _execute_structure_tool_impl(params: dict) -> dict:
},
)
pipeline_start = time.monotonic()
- pipeline_result = dispatcher.dispatch(pipeline_ctx, timeout=EXECUTOR_TIMEOUT)
+ pipeline_result = dispatcher.dispatch(
+ pipeline_ctx,
+ timeout=EXECUTOR_TIMEOUT,
+ headers=_fairness_headers(organization_id),
+ )
pipeline_elapsed = time.monotonic() - pipeline_start
if not pipeline_result.success:
@@ -717,7 +746,11 @@ def _run_agentic_extraction(
"include_source_refs": enable_highlight,
},
)
- agentic_result = dispatcher.dispatch(agentic_ctx, timeout=EXECUTOR_TIMEOUT)
+ agentic_result = dispatcher.dispatch(
+ agentic_ctx,
+ timeout=EXECUTOR_TIMEOUT,
+ headers=_fairness_headers(organization_id),
+ )
if not agentic_result.success:
return agentic_result.to_dict()
diff --git a/workers/queue_backend/dispatch.py b/workers/queue_backend/dispatch.py
index 274922bf5..21f0ea68c 100644
--- a/workers/queue_backend/dispatch.py
+++ b/workers/queue_backend/dispatch.py
@@ -12,7 +12,7 @@ from typing import Any, Protocol
from celery import current_app
-from .fairness import FAIRNESS_HEADER_NAME, FairnessKey
+from .fairness import FairnessKey
class DispatchHandle(Protocol):
@@ -38,7 +38,7 @@ def dispatch(
``fairness`` is attached as the ``x-fairness-key`` header (not in
kwargs). Pass ``None`` for non-workflow worker tasks.
"""
- headers = {FAIRNESS_HEADER_NAME: fairness.to_dict()} if fairness is not None else None
+ headers = fairness.as_header() if fairness is not None else None
return current_app.send_task(
task_name,
args=args,
diff --git a/workers/queue_backend/fairness.py b/workers/queue_backend/fairness.py
index 30ef04849..83af4fea1 100644
--- a/workers/queue_backend/fairness.py
+++ b/workers/queue_backend/fairness.py
@@ -53,3 +53,10 @@ class FairnessKey:
"workload_type": self.workload_type.value,
"pipeline_priority": self.pipeline_priority,
}
+
+ def as_header(self) -> dict[str, dict[str, str | int | None]]:
+ """Celery ``send_task(headers=...)`` payload.
+
+ Shape: ``{FAIRNESS_HEADER_NAME: self.to_dict()}``.
+ """
+ return {FAIRNESS_HEADER_NAME: self.to_dict()}
diff --git a/workers/tests/canary_helpers.py b/workers/tests/canary_helpers.py
new file mode 100644
index 000000000..8aed9dc28
--- /dev/null
+++ b/workers/tests/canary_helpers.py
@@ -0,0 +1,52 @@
+"""Shared AST-walk helpers for inventory-style canary tests.
+
+Several test files audit the production code tree (forbid a raw
+dispatch, require a kwarg, etc.). The file-walking + parse-with-skip
+logic is identical across them; this module is the intended single
+home. Two pre-existing characterisation tests still inline the same
+walk (``test_dispatch_sites_characterisation.py``,
+``test_chord_sites_characterisation.py``) — migrating those is
+tracked as a follow-up.
+"""
+
+from __future__ import annotations
+
+import ast
+import pathlib
+import warnings
+
+WORKERS_ROOT = pathlib.Path(__file__).parent.parent
+
+# Always-skip top-level directories. Callers pass a wider set if they
+# need to additionally exclude e.g. the seam module itself.
+DEFAULT_SKIP_TOP_DIRS = frozenset({"tests", "__pycache__", "htmlcov", ".venv"})
+
+
+def iter_production_trees(
+ skip_top_dirs: frozenset[str] = DEFAULT_SKIP_TOP_DIRS,
+) -> list[tuple[pathlib.Path, ast.AST]]:
+ """Return a list of ``(rel_path, parsed_tree)`` tuples for every
+ .py file outside the skip set.
+
+ Unparseable files emit a ``UserWarning`` and are skipped — silent
+ skipping would let canaries pass vacuously on a botched merge.
+ Tests can promote the warning to an error via
+ ``warnings.simplefilter("error", UserWarning)`` if they want
+ strict enforcement.
+ """
+ out: list[tuple[pathlib.Path, ast.AST]] = []
+ for py in WORKERS_ROOT.rglob("*.py"):
+ rel = py.relative_to(WORKERS_ROOT)
+ if rel.parts and rel.parts[0] in skip_top_dirs:
+ continue
+ try:
+ tree = ast.parse(py.read_text(), filename=str(py))
+ except SyntaxError as exc:
+ warnings.warn(
+ f"canary scan skipping unparseable file {rel}: {exc}",
+ UserWarning,
+ stacklevel=2,
+ )
+ continue
+ out.append((rel, tree))
+ return out
diff --git a/workers/tests/test_callback_sanity.py b/workers/tests/test_callback_sanity.py
index 5d2b11fe7..0efd7519f 100644
--- a/workers/tests/test_callback_sanity.py
+++ b/workers/tests/test_callback_sanity.py
@@ -142,10 +142,16 @@ class TestEagerHealthcheckRoundTrip:
"""
def test_eager_healthcheck_round_trip(self, eager_app):
- # Find the healthcheck task; its module-qualified name varies.
+ # Find the callback worker's healthcheck task specifically.
+ # ``eager_app.tasks`` is a SHARED celery registry: every worker
+ # module that registers a ``healthcheck`` (executor,
+ # file_processing, log_consumer, ...) lands in the same dict.
+ # A bare ``endswith(".healthcheck")`` match returns whichever
+ # was inserted first, which depends on pytest collection /
+ # import order and produces flaky cross-worker results.
healthcheck = next(
t for name, t in eager_app.tasks.items()
- if name.endswith(".healthcheck") or name == "healthcheck"
+ if name == "callback.worker.healthcheck"
)
result = healthcheck.apply()
@@ -163,7 +169,7 @@ class TestEagerHealthcheckRoundTrip:
healthcheck = next(
t for name, t in eager_app.tasks.items()
- if name.endswith(".healthcheck") or name == "healthcheck"
+ if name == "callback.worker.healthcheck"
)
result = healthcheck.apply()
diff --git a/workers/tests/test_canary_helpers.py b/workers/tests/test_canary_helpers.py
new file mode 100644
index 000000000..fdd0976e0
--- /dev/null
+++ b/workers/tests/test_canary_helpers.py
@@ -0,0 +1,72 @@
+"""Unit tests for the shared ``iter_production_trees`` helper.
+
+Locks the fail-loud-by-default contract that the canary modules
+(``test_executor_dispatch``, ``test_fairness_key``) rely on via
+``pytestmark = pytest.mark.filterwarnings("error::UserWarning")``.
+Without that promotion an unparseable production file would be
+silently dropped and every canary would pass vacuously over a
+smaller tree — exactly the failure mode this helper claims to
+prevent.
+"""
+
+from __future__ import annotations
+
+import warnings
+
+import pytest
+
+from .canary_helpers import iter_production_trees
+
+
+class TestUnparseableFileBehaviour:
+ def test_unparseable_file_emits_userwarning(self, tmp_path, monkeypatch):
+ """Drop a syntactically invalid .py inside the audited root
+ and confirm the helper surfaces the failure as a
+ ``UserWarning`` (the signal the canary modules promote to
+ error). Without this, a botched merge in production would
+ leave canaries silently green.
+ """
+ from . import canary_helpers
+
+ # Point the helper at an isolated tree so we don't pollute
+ # the real workers/ root with a broken file.
+ monkeypatch.setattr(canary_helpers, "WORKERS_ROOT", tmp_path)
+ (tmp_path / "broken.py").write_text("def oops(:\n")
+ (tmp_path / "ok.py").write_text("x = 1\n")
+
+ with warnings.catch_warnings(record=True) as captured:
+ warnings.simplefilter("always", UserWarning)
+ result = iter_production_trees(skip_top_dirs=frozenset())
+
+ # The good file still made it into the audit set.
+ assert any(rel.name == "ok.py" for rel, _ in result)
+ # The broken one is skipped *and* warned about.
+ assert not any(rel.name == "broken.py" for rel, _ in result)
+ assert any(
+ "unparseable" in str(w.message) and "broken.py" in str(w.message)
+ for w in captured
+ if issubclass(w.category, UserWarning)
+ )
+
+ def test_warning_promoted_to_error_under_filterwarnings(
+ self, tmp_path, monkeypatch
+ ):
+ """When the caller installs
+ ``pytest.mark.filterwarnings("error::UserWarning")`` (or the
+ equivalent ``warnings.simplefilter("error", UserWarning)``)
+ the helper fails loud instead of silently skipping. This is
+ the contract the canary modules at module level rely on.
+ """
+ from . import canary_helpers
+
+ monkeypatch.setattr(canary_helpers, "WORKERS_ROOT", tmp_path)
+ (tmp_path / "broken.py").write_text("def oops(:\n")
+
+ with warnings.catch_warnings():
+ warnings.simplefilter("error", UserWarning)
+ with pytest.raises(UserWarning, match="unparseable"):
+ iter_production_trees(skip_top_dirs=frozenset())
+
+
+if __name__ == "__main__":
+ pytest.main([__file__, "-v"])
diff --git a/workers/tests/test_executor_dispatch.py b/workers/tests/test_executor_dispatch.py
new file mode 100644
index 000000000..e57e329db
--- /dev/null
+++ b/workers/tests/test_executor_dispatch.py
@@ -0,0 +1,232 @@
+"""Tests for the file_processing → executor boundary: header forwarding
+through ExecutionDispatcher and inventory canary for raw send_task calls.
+"""
+
+from __future__ import annotations
+
+import ast
+from typing import Any
+from unittest.mock import MagicMock
+
+import pytest
+from celery import Celery
+
+from queue_backend import FairnessKey
+from queue_backend.fairness import WorkloadType
+from unstract.sdk1.execution.context import ExecutionContext, Operation
+from unstract.sdk1.execution.dispatcher import ExecutionDispatcher
+
+from .canary_helpers import iter_production_trees
+
+# Promote ``UserWarning`` from ``iter_production_trees`` (emitted on
+# unparseable production files) to a test failure. Without this an
+# unparseable file would be silently dropped from the audited tree
+# and the canary would pass vacuously over a smaller set —
+# exactly the failure mode the helper claims to prevent.
+pytestmark = pytest.mark.filterwarnings("error::UserWarning")
+
+
+def _make_context(**overrides: Any) -> ExecutionContext:
+ defaults: dict[str, Any] = {
+ "executor_name": "legacy",
+ "operation": Operation.EXTRACT,
+ "run_id": "file-exec-1",
+ "execution_source": "tool",
+ "organization_id": "org-1",
+ "request_id": "req-1",
+ "log_events_id": "log-1",
+ "execution_id": "exec-1",
+ "file_execution_id": "file-exec-1",
+ "executor_params": {"adapter_instance_id": "a"},
+ }
+ defaults.update(overrides)
+ return ExecutionContext(**defaults)
+
+
+class TestExecutionDispatcherForwardsHeaders:
+ """``ExecutionDispatcher`` propagates the ``headers`` kwarg to Celery."""
+
+ def _patched_app(self) -> tuple[ExecutionDispatcher, MagicMock]:
+ app = MagicMock(spec=Celery)
+ async_result = MagicMock()
+ async_result.id = "task-1"
+ async_result.get.return_value = {"success": True, "data": {}}
+ app.send_task.return_value = async_result
+ return ExecutionDispatcher(celery_app=app), app
+
+ # The three dispatch entry points share the same header-forwarding
+ # contract via ``_build_send_kwargs``; parametrize over them so a
+ # divergence (e.g. one method dropping ``headers=``) surfaces with
+ # per-method failure granularity via the parametrize IDs.
+ @pytest.mark.parametrize(
+ "method", ["dispatch", "dispatch_async", "dispatch_with_callback"]
+ )
+ def test_forwards_headers(self, method):
+ # Use ``FairnessKey.as_header()`` as the fixture rather than
+ # hand-built dicts so the test exercises the exact wire shape
+ # real producers emit (including ``pipeline_priority``).
+ headers = FairnessKey(
+ org_id="org-1", workload_type=WorkloadType.NON_API
+ ).as_header()
+ d, app = self._patched_app()
+ getattr(d, method)(_make_context(), headers=headers)
+ assert app.send_task.call_args.kwargs["headers"] == headers
+
+ @pytest.mark.parametrize(
+ "method", ["dispatch", "dispatch_async", "dispatch_with_callback"]
+ )
+ def test_omits_headers_when_none(self, method):
+ # Caller passes no headers ⇒ ``headers`` kwarg not forwarded
+ # to send_task (preserves the call shape Celery's link /
+ # link_error handling expects).
+ d, app = self._patched_app()
+ getattr(d, method)(_make_context())
+ assert "headers" not in app.send_task.call_args.kwargs
+
+ @pytest.mark.parametrize(
+ "method", ["dispatch", "dispatch_async", "dispatch_with_callback"]
+ )
+ def test_omits_headers_when_empty_dict(self, method):
+ """Empty header dicts are dropped (treated as a no-headers
+ call). ``FairnessKey.as_header()`` can never legitimately
+ return ``{}`` — forwarding it would document a producer-side
+ build bug rather than catch it.
+ """
+ d, app = self._patched_app()
+ getattr(d, method)(_make_context(), headers={})
+ assert "headers" not in app.send_task.call_args.kwargs
+
+ def test_dispatch_with_callback_combines_headers_and_callbacks(self):
+ """All four optional kwargs (headers, on_success, on_error,
+ task_id) land on the same ``send_task`` call. A merge bug in
+ ``_build_send_kwargs`` would slip through the single-kwarg
+ forwarding tests above.
+ """
+ from celery.canvas import Signature
+
+ d, app = self._patched_app()
+ headers = FairnessKey(
+ org_id="org-1", workload_type=WorkloadType.NON_API
+ ).as_header()
+ on_success = MagicMock(spec=Signature)
+ on_error = MagicMock(spec=Signature)
+ d.dispatch_with_callback(
+ _make_context(),
+ on_success=on_success,
+ on_error=on_error,
+ task_id="t-1",
+ headers=headers,
+ )
+ kwargs = app.send_task.call_args.kwargs
+ assert kwargs["headers"] == headers
+ assert kwargs["link"] is on_success
+ assert kwargs["link_error"] is on_error
+ assert kwargs["task_id"] == "t-1"
+
+
+class TestFairnessKeyComposesWithHeaders:
+ """The header that producers actually build round-trips correctly."""
+
+ def test_fairness_header_shape(self):
+ fairness = FairnessKey(
+ org_id="org-1", workload_type=WorkloadType.NON_API, pipeline_priority=5
+ )
+ assert fairness.as_header() == {
+ "x-fairness-key": {
+ "org_id": "org-1",
+ "workload_type": "non_api",
+ "pipeline_priority": 5,
+ }
+ }
+
+ def test_fairness_header_shape_orgless(self):
+ # org_id=None must serialise to JSON null, not get dropped or
+ # coerced — downstream consumers rely on the field's presence.
+ fairness = FairnessKey(org_id=None, workload_type=WorkloadType.API)
+ assert fairness.as_header() == {
+ "x-fairness-key": {
+ "org_id": None,
+ "workload_type": "api",
+ "pipeline_priority": 5,
+ }
+ }
+
+
+class TestExecuteExtractionDispatchInventory:
+ """Canary: ``execute_extraction`` must only be dispatched via
+ ``ExecutionDispatcher``. Raw **string-literal**
+ ``*.send_task("execute_extraction", ...)`` elsewhere is forbidden.
+
+ Known blind spots (deliberate — widening adds AST resolution cost
+ for low real-world risk on a 1-line dispatcher seam):
+ * constant references (``T = "execute_extraction"; send_task(T, ...)``)
+ * f-strings
+ * ``apply_async`` calls
+ These are documented in the assertion message so future authors
+ don't trust the canary absolutely.
+ """
+
+ def test_no_raw_execute_extraction_dispatch_outside_dispatcher(self):
+ offenders = [
+ f"{rel}:{lineno}"
+ for rel, tree in iter_production_trees()
+ for lineno in _raw_execute_extraction_calls(tree)
+ ]
+ assert offenders == [], (
+ "Production code calls ``*.send_task(\"execute_extraction\", ...)`` "
+ "outside ``ExecutionDispatcher``. Use "
+ "``ExecutionDispatcher.dispatch(...)`` instead so fairness "
+ "headers and queue routing stay consistent. (Detection "
+ "covers string-literal task names only; constant references, "
+ "f-strings, and apply_async are blind spots.) Found:\n "
+ + "\n ".join(offenders)
+ )
+
+ def test_detector_matches_string_literal_send_task(self):
+ """Positive-detection lock: feed a known-bad snippet and
+ assert the detector flags it. Without this the canary above
+ could silently rot (e.g. ``ast.walk`` returning nothing) and
+ always report ``offenders == []`` regardless of the tree.
+ """
+ bad = ast.parse('app.send_task("execute_extraction", args=[])')
+ assert _raw_execute_extraction_calls(bad) == [1]
+
+ def test_detector_skips_documented_blind_spots(self):
+ """Lock the deliberate blind spots in the assertion message:
+ a constant reference, an f-string, and an ``apply_async`` call
+ all evade the canary. Documenting them as tests means a future
+ author who widens the detector intentionally has to update
+ these assertions — flagging that the canary scope changed.
+ """
+ constant_ref = ast.parse(
+ "T = 'execute_extraction'\napp.send_task(T, args=[])"
+ )
+ fstring = ast.parse(
+ 'name = "extraction"\napp.send_task(f"execute_{name}", args=[])'
+ )
+ apply_async = ast.parse(
+ 'app.apply_async("execute_extraction", args=[])'
+ )
+ assert _raw_execute_extraction_calls(constant_ref) == []
+ assert _raw_execute_extraction_calls(fstring) == []
+ assert _raw_execute_extraction_calls(apply_async) == []
+
+
+def _raw_execute_extraction_calls(tree: ast.AST) -> list[int]:
+ hits: list[int] = []
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.Call):
+ continue
+ func = node.func
+ if not (isinstance(func, ast.Attribute) and func.attr == "send_task"):
+ continue
+ if not node.args:
+ continue
+ first = node.args[0]
+ if isinstance(first, ast.Constant) and first.value == "execute_extraction":
+ hits.append(node.lineno)
+ return hits
+
+
+if __name__ == "__main__":
+ pytest.main([__file__, "-v"])
diff --git a/workers/tests/test_fairness_key.py b/workers/tests/test_fairness_key.py
index 74e8352c3..0ef3e53a5 100644
--- a/workers/tests/test_fairness_key.py
+++ b/workers/tests/test_fairness_key.py
@@ -4,7 +4,6 @@ from __future__ import annotations
import ast
import json
-import pathlib
from dataclasses import FrozenInstanceError
from unittest.mock import patch
@@ -19,28 +18,26 @@ from queue_backend.fairness import (
MIN_PRIORITY,
WorkloadType,
)
+from .canary_helpers import (
+ DEFAULT_SKIP_TOP_DIRS,
+ WORKERS_ROOT,
+ iter_production_trees,
+)
-# Helpers extracted so the audit tests below stay flat (SonarCloud
-# S3776 cognitive-complexity threshold).
+# Promote ``UserWarning`` from ``iter_production_trees`` (emitted on
+# unparseable production files) to a test failure. An unparseable
+# file silently dropped from the audited tree would let every canary
+# below pass vacuously — exactly the failure mode the helper claims
+# to prevent.
+pytestmark = pytest.mark.filterwarnings("error::UserWarning")
-_WORKERS_ROOT = pathlib.Path(__file__).parent.parent
-_SKIP_TOP_DIRS = frozenset(
- {"tests", "__pycache__", "htmlcov", ".venv", "queue_backend"}
-)
+# Fairness-canary helpers also skip the seam module itself (it
+# legitimately defines and exports the fairness constants).
+_SKIP_TOP_DIRS = DEFAULT_SKIP_TOP_DIRS | frozenset({"queue_backend"})
-def _iter_production_trees() -> list[tuple[pathlib.Path, ast.AST]]:
- out: list[tuple[pathlib.Path, ast.AST]] = []
- for py in _WORKERS_ROOT.rglob("*.py"):
- rel = py.relative_to(_WORKERS_ROOT)
- if rel.parts and rel.parts[0] in _SKIP_TOP_DIRS:
- continue
- try:
- tree = ast.parse(py.read_text(), filename=str(py))
- except SyntaxError:
- continue
- out.append((rel, tree))
- return out
+def _trees():
+ return iter_production_trees(skip_top_dirs=_SKIP_TOP_DIRS)
def _aliased_dispatch_imports(tree: ast.AST) -> list[tuple[int, str]]:
@@ -234,7 +231,7 @@ class TestDispatchCallSitesPassFairness:
# Alias imports would defeat the bare-name canary below.
aliased = [
f"{rel}:{lineno} (as {alias})"
- for rel, tree in _iter_production_trees()
+ for rel, tree in _trees()
for lineno, alias in _aliased_dispatch_imports(tree)
]
assert aliased == [], (
@@ -246,7 +243,7 @@ class TestDispatchCallSitesPassFairness:
def test_every_production_dispatch_passes_fairness(self):
offenders = [
f"{rel}:{lineno}"
- for rel, tree in _iter_production_trees()
+ for rel, tree in _trees()
for lineno in _dispatch_calls_missing_fairness(tree)
]
assert offenders == [], (
@@ -266,8 +263,8 @@ class TestNoConsumerYet:
forbidden_tokens = ("x-fairness-key", "FAIRNESS_HEADER_NAME")
readers: list[str] = []
- for py in _WORKERS_ROOT.rglob("*.py"):
- rel = py.relative_to(_WORKERS_ROOT)
+ for py in WORKERS_ROOT.rglob("*.py"):
+ rel = py.relative_to(WORKERS_ROOT)
if rel.parts and rel.parts[0] in _SKIP_TOP_DIRS:
continue
for line_no, line in enumerate(py.read_text().splitlines(), start=1):
diff --git a/workers/tests/test_sanity_phase5.py b/workers/tests/test_sanity_phase5.py
index 4d00a571f..e414d9d2d 100644
--- a/workers/tests/test_sanity_phase5.py
+++ b/workers/tests/test_sanity_phase5.py
@@ -947,6 +947,18 @@ class TestStructureToolSingleDispatch:
assert "answer_params" in ctx.executor_params
assert "pipeline_options" in ctx.executor_params
+ # Fairness header lands on the dispatch call. A regression that
+ # drops ``headers=`` or flips ``NON_API``→``API`` here would
+ # otherwise stay green — keep this assertion paired with the
+ # ``_fairness_headers`` unit test in test_structure_tool_task.py.
+ assert dispatcher.dispatch.call_args.kwargs["headers"] == {
+ "x-fairness-key": {
+ "org_id": "org-1",
+ "workload_type": "non_api",
+ "pipeline_priority": 5,
+ }
+ }
+
# ---------------------------------------------------------------------------
# Operation enum completeness
diff --git a/workers/tests/test_structure_tool_task.py b/workers/tests/test_structure_tool_task.py
new file mode 100644
index 000000000..8bdb541ec
--- /dev/null
+++ b/workers/tests/test_structure_tool_task.py
@@ -0,0 +1,54 @@
+"""Direct unit tests for ``file_processing.structure_tool_task`` helpers.
+
+Locks contracts that the integration test in ``test_sanity_phase5.py``
+exercises indirectly. Specifically guards ``_fairness_headers``:
+
+* The hard-coded ``WorkloadType.NON_API`` default. Per the docstring,
+ ``API`` is "strictly worse" here — flipping it would silently
+ preempt ETL work under API traffic.
+* The wire shape consumers see at the dispatcher. A regression in
+ ``FairnessKey.as_header()``'s serialisation surfaces here too.
+
+Paired with the ``headers=`` assertion in
+``test_sanity_phase5.TestStructureToolSingleDispatch`` — together
+they cover both "the helper returns the right thing" and "the call
+site forwards it".
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from file_processing.structure_tool_task import _fairness_headers
+from queue_backend.fairness import WorkloadType
+
+
+class TestFairnessHeaders:
+ def test_returns_non_api_wire_shape(self):
+ """``_fairness_headers`` emits the canonical ``x-fairness-key``
+ envelope with ``workload_type='non_api'`` and the default
+ ``pipeline_priority=5``."""
+ assert _fairness_headers("org-1") == {
+ "x-fairness-key": {
+ "org_id": "org-1",
+ "workload_type": "non_api",
+ "pipeline_priority": 5,
+ }
+ }
+
+ def test_org_id_is_propagated_verbatim(self):
+ wire = _fairness_headers("another-org")
+ assert wire["x-fairness-key"]["org_id"] == "another-org"
+
+ def test_workload_type_is_non_api_not_api(self):
+ """Pinned because the docstring calls ``NON_API`` "the safe
+ default" and ``API`` "strictly worse" — a regression that
+ flips this would silently let API traffic preempt ETL work.
+ """
+ wire = _fairness_headers("org-1")
+ assert wire["x-fairness-key"]["workload_type"] == WorkloadType.NON_API.value
+ assert wire["x-fairness-key"]["workload_type"] != WorkloadType.API.value
+
+
+if __name__ == "__main__":
+ pytest.main([__file__, "-v"])