You are reviewing the architecture of a production AI/ML task system, asked one question: what's the right deep solution to actually solve this CLASS of bugs once and for all? Read-only analysis. Be opinionated, propose real architectural moves, do not hedge. Length cap: ~1000 words. Do not propose half-measures; the team wants the genuine structural answer, even if it's expensive.
The system
Three deployment surfaces:
Workers — Python codebase at /Users/user_c042661f/Documents/reigh-workspace/reigh-worker/. Run as RunPod GPU pods. Each pod runs a startup script that does git fetch origin main && git reset --hard origin/main on a network volume, then launches the worker. Workers claim tasks, run inference, complete them. Multiple worker backends exist (wgp, vibecomfy) with different capability sets.
Orchestrator — Python codebase at /Users/user_c042661f/Documents/reigh-workspace/reigh-worker-orchestrator/. Deployed on Railway, auto-deployed from a feature branch on banodoco/reigh-worker-orchestrator. Manages worker lifecycle (spawn, promote to active, terminate), scaling decisions based on queue depth.
App + edge functions + DB — TypeScript codebase at /Users/user_c042661f/Documents/reigh-workspace/reigh-app/. Supabase edge functions (Deno/TS) own task creation, claim handshake, status transitions. PostgreSQL owns the data model (tasks, workers, route_backend_capabilities, route_backend_selectors) and a set of RPCs (claim_next_task_service_role, route_backend_claim_decision, etc.) that enforce gates at the DB layer.
The three surfaces share wire-level contracts:
DB schema (rows, JSONB shapes inside tasks.params, capability registry rows)
Edge-function input/output shapes
Worker heartbeat / preflight metadata format (e.g. metadata.ready_for_tasks)
"Route key" — a string encoding (task_type, model_family, guidance, continuity, profile) used to match a task to a worker that has declared the matching capability
The same conceptual functions (e.g. "given a task's params, derive its route_key") exist independently in:
I’ll keep this read-only and focus on the structural answer, but I’m going to quickly inspect the named routing/contract files so the recommendation is grounded in the current shape rather than only the incident summary.
DB seed rows in route_backend_capabilities (capability registry written by migration)
Each codebase is in a separate repo with separate deploy lifecycle. There are no codegen relationships between them, no shared schema definition file, no cross-repo CI. Humans keep them aligned by remembering to update both sides when any contract changes.
The bugs we've hit in this single debugging session
Bug 1 — Cross-repo deployment skew. The orchestrator added a new gate: "worker stays in spawning lifecycle until it publishes metadata.ready_for_tasks = True". The worker-side code that publishes that flag was developed and tested via live-test branches but the merge to origin/main of the worker repo never happened. Result: every production pod spawned in the last week ran 8-day-old code that didn't know about the flag, sat in spawning forever (still heartbeating thanks to a guardian subprocess), the orchestrator's safety net for "stuck spawning" had a gate (queued_count > 0) that an empty queue silently disabled, so the zombie pod ran for 18.5h burning $0.69/hr. Git history shows this same contract was added 4 months earlier, immediately reverted with the message "revert: worker not updated yet," and then re-introduced later — same person, same trap.
Bug 2 — Cross-layer contract enforcement gap. The Postgres claim RPC requires every task to have a non-null route_key (column) and a route_contract object (inside params JSONB), and runs a lateral join route_backend_claim_decision(...) ON rd.eligible that filters out anything ineligible. The edge-function create-task and its resolver tree (travelBetweenImages.ts, qwenImageStyle.ts, etc.) never built a route_contract for any task type that flows through it. Zero resolvers had any reference to "route_contract". Result: every production-side task ever created via the edge function has route_key = NULL, gets categorically rejected from claims, and sits Queued indefinitely. Live-test tasks worked fine because they use a completely separate Python script path that writes the contract directly.
Bug 3 — Dual-implementation drift across language boundary. Within the worker (Python), params.model_family holds an internal classification with enum {"ltx", "wan"}, used by the worker's runtime for FPS / frame-step decisions. Independently, the route-key system uses a richer enum {"wan22_i2v", "wan22_vace", "ltx2", "ltx2_distilled", "qwen", "z_image"} to identify capabilities. Both the Python route-derivation function (_route_model_family) AND the TS port (routeModelFamily) honor params.model_family as an explicit override — short-circuiting before normalizing. So when the orchestrator handler in the worker writes params["model_family"] = "wan" (internal value) into child tasks, the TS edge function then also reads that and builds a route_key with model-wan, which is not a key the capability registry knows about. Tasks become syntactically valid but semantically un-claimable. Same root structure as Bug 2 but at the language boundary instead of the layer boundary — two implementations of the same function in different languages, each defensively respecting an override the other side wrote in the wrong namespace.
The pattern
All three bugs share a shape: the system has accumulated cross-boundary contracts (cross-repo, cross-layer, cross-language) faster than it has accumulated mechanisms that enforce equivalence across the boundary. Each contract relies on a human remembering to update both sides; failure mode is silent at deploy time and produces runtime symptoms that look unrelated to the original change. The detection mechanisms that exist (orchestrator's stuck-worker timeouts, edge function's input validation, DB RPCs' eligibility filters, the worker's runtime validation of parent/child route contracts) all log their negative verdicts but none escalate — so the system sat for 18 hours with three independent detectors all noticing "this is wrong" and none refusing to proceed.
The question
Given this shape — multiple independent codebases, multiple languages, multiple deploy lifecycles, contracts that span boundaries with no mechanical enforcement, a recurring pattern of asymmetric contract evolution producing silent runtime failures — what's the right deep architectural move to make this class of bug structurally impossible (or at minimum, structurally loud) going forward?
Consider:
Cost of change vs. value
Real-world constraints (team is shipping features actively; can't pause for a 6-month refactor)
What you'd accept as "good enough" vs. what you'd push back on
Whether the answer is one big move, several medium moves, or a cultural/process shift
What you'd do FIRST if you only had one week
Don't propose vague principles ("add more tests"). Propose specific structural changes: where the source of truth would live, what gets generated from what, which boundaries collapse, which detection mechanisms get teeth, what the new deploy pipeline looks like. Take a position. If the right answer is "you've built something that fundamentally shouldn't be three repos and two languages," say so.
The right deep move is to treat this as a distributed protocol, not shared application logic.
Right now Reigh has three independently deployed programs speaking an implicit protocol through Postgres rows, JSONB, route strings, worker metadata, and edge-function payloads. That protocol has no owner, no compiler, no version negotiation, and no release gate. So the system is behaving exactly like an unversioned distributed system behaves: asymmetric rollout creates silent incompatibility.
I would create a single control-plane contract artifact and make every surface consume it.
Concretely:
Move route selection, task contract schemas, heartbeat/preflight schemas, worker capability schemas, and claim eligibility inputs into one versioned contract package.
This should not be copied TS/Python. It should be a declarative source of truth: JSON Schema / OpenAPI / protobuf / typed YAML, plus a small compiler. From that source, generate:
TypeScript validators and types for Supabase edge functions.
Python Pydantic/dataclass validators for workers and orchestrator.
SQL migrations or seed files for route_backend_capabilities, selectors, enum domains, and DB constraints.
Golden fixtures used by all repos.
A contract_version and contract_hash.
Stop deriving route keys independently in TS, Python, and SQL.
There should be exactly one canonical route selector. Either:
generate both TS and Python implementations from the same declarative selector table, or
make route selection a DB RPC / small routing service and have callers ask it.
I would prefer generated code from a declarative registry for latency and deploy simplicity, with DB constraints generated from the same registry. But hand-maintained ports are done. That is the bug.
Make route_key an opaque registry ID, not a string assembled from loosely named params.
The current string composition leaks internal concepts into the wire protocol. params.model_family = "wan" and route model = "wan22_vace" are different domains that accidentally share a field name. Generated schemas should make that impossible:
runtime_model_family: "wan" | "ltx" for worker runtime internals.
arbitrary params.model_family should not influence routing unless the contract schema for that task type explicitly says it does.
Make contract-invalid writes impossible at the database boundary.
The DB should not merely filter bad tasks out during claim. It should reject them on insert/update.
For every tasks row entering Queued, enforce:
route_key IS NOT NULL
params.route_contract exists
params.route_contract.route_key = tasks.route_key
route_key exists in generated capability/selector registry
contract version is supported
selected backend/profile/namespace are known
A task that cannot be claimed should not be allowed to become queued. “Queued but categorically unclaimable” should be a database invariant violation, not an operational state.
Give detectors teeth.
Logging negative verdicts is not detection. It is telemetry.
Required behavior:
Worker missing required heartbeat fields: terminate pod after a short grace period, regardless of queue depth.
Orchestrator sees spawning past TTL: terminate or page. Queue depth must not disable lifecycle safety.
Claim RPC rejects route contract: create a terminal task failure with structured reason or raise an alert on first occurrence.
Any route demand with zero eligible backend capacity for N minutes: page or block creation, depending on user-facing semantics.
Unify release gating around contract compatibility.
The deployment pipeline should look like this:
Contract PR changes schemas/registry/selectors.
Generated TS/Python/SQL artifacts are updated.
CI runs golden corpus tests in all repos:
edge creates every supported task type
DB accepts it
claim decision finds eligible backend
worker can parse it
orchestrator can reason about required worker metadata
No repo deploys against a new contract unless it declares support for that contract version/hash.
Orchestrator only spawns workers whose heartbeat advertises a compatible contract hash.
Workers refuse to start if their local contract package does not match the expected deployed contract, unless explicitly in canary mode.
Collapse repos if the team can stomach it.
My opinion: the control plane should not be split across three repos. Worker inference code can stay separate if GPU runtime constraints demand it, but app edge functions, DB migrations, orchestrator lifecycle logic, and shared contract definitions belong in one monorepo or one release train.
If you keep three repos, you must compensate with a real contract artifact and cross-repo CI. Without that, this class of bug will keep recurring.
What I would reject as insufficient: adding a few tests, adding more logs, adding docs, adding a checklist, or asking reviewers to remember route-contract changes. Those help only until the next tired human ships an asymmetric change. The failure mode is structural, so the fix has to be mechanical.
What I would do in the first week:
Create reigh-contracts with the route registry, task route schemas, heartbeat schema, and contract version/hash.
Generate TS validators and Python validators from it.
Add golden fixtures for every task type that can be queued.
Add DB constraints so new queued tasks without valid route_key / route_contract are rejected.
Change orchestrator spawning TTL to terminate missing-ready_for_tasks workers unconditionally.
Add CI jobs in all three repos that consume the same contract fixtures.
The expensive end state is a versioned protocol with generated clients, generated DB constraints, compatibility-gated deploys, and hard failure on invalid state. That is the line between “three services sharing hope” and an actual production distributed system.