You are an opinionated principal-engineer-level reviewer. The team wants a real architectural answer to a recurring class of bug, not generic principles. Take a position. Propose specific structural moves with named files / boundaries / mechanisms. Be concise but substantive — aim for ~1000 words. Do not hedge.
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:
Assistant
I’ll ground this in the actual boundary files you named, then answer architecturally. Since this is read-only, I’m looking for the contract definitions, route derivation duplication, and current migration/RPC shape rather than changing anything.
Assistant
The current app tree already has a create-task/routeContract.ts, which is important: it shows the right local patch direction exists, but the architectural issue remains because the route logic still lives as copied executable code in TS, Python, and SQL/seed data. I’m checking those exact seams now so the recommendation can name the enforcement points.
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 move is to stop treating “route contract” as application logic and make it a versioned protocol artifact. Three repos are acceptable only if the protocol is not owned by any one of them. Right now it is owned by memory, which is why the same bug keeps reappearing.
Position
Collapse the contract boundary, not necessarily every runtime. Create a dedicated reigh-contracts release unit and make app, worker, orchestrator, and DB consume generated artifacts from it. If the team will not fund that, merge the repos. What is not acceptable is continuing with hand-copied route logic in Python, TypeScript, SQL, and migrations.
Source Of Truth
Create a new repo or top-level package, preferably banodoco/reigh-contracts, with:
contracts/routes.yaml
Defines task types, route dimensions, aliases, allowed route model families, guidance modes, continuity cases, profiles, support state, template IDs, selector namespace/version, and backend eligibility.
contracts/task-params.schema.json
JSON Schema per task type. This explicitly separates public routing fields from worker-internal runtime fields.
The current files selectedRoute.ts, template_routing.py, and the capability seed migrations should become generated or thin wrappers around generated code. Nobody edits route derivation directly in app or worker repos.
DB Owns Admission
The DB must become the contract enforcement point, not just the place where bad tasks go to die.
Create one insertion path:
public.create_task_with_route_contract(...)
public.create_child_task_with_route_contract(...)
Edge functions and worker orchestrator handlers stop inserting directly into tasks. They pass semantic task params to the RPC. The RPC stamps:
(selector_namespace, selector_version, selected_backend, route_key) must exist in route_backend_capabilities, or the task is rejected/blocked at creation.
The current create-task/routeContract.ts is the right tactical patch, but architecturally it is in the wrong layer. Edge functions should not be trusted to remember route stamping. They should be clients of a DB admission API.
Kill The Ambiguous Namespaceparams.model_family is currently poisoned because it means two different things. Remove it from the wire contract.
Use:
params.route_model_family: public routing enum, generated schema allows only wan22_i2v, wan22_vace, ltx2, ltx2_distilled, qwen, z_image, etc.
params.runtime_model_family: worker-internal runtime enum, e.g. wan, ltx.
Generated schemas should reject params.model_family for newly created tasks. Worker code may translate route_model_family to runtime_model_family internally, but the reverse must not leak back into task params. This directly eliminates Bug 3.
Immutable Worker Deploys
The RunPod startup script doing git fetch origin main && git reset --hard origin/main is indefensible for production. It destroys deploy provenance.
Replace it with immutable worker artifacts:
Build worker Docker image or tarball from a commit.
Publish with labels:
worker_git_sha
contract_version
capabilities_hash
Orchestrator spawns a specific image digest or exact commit SHA, never “whatever main is right now.”
Worker heartbeat must publish those same fields.
Orchestrator refuses promotion if they do not match the selected pool contract.
If images are too expensive immediately, the one-week bridge is: orchestrator writes required_worker_git_sha into worker metadata/env, startup checks out that exact SHA, and exits non-zero if unavailable. Still not ideal, but better than floating origin/main.
Readiness Must Have Teethmetadata.ready_for_tasks should be part of a versioned readiness protocol:
The orchestrator file worker_state.py should make this a finite-state-machine invariant:
spawning without required readiness protocol after timeout -> terminate pod, mark worker error.
This timeout must not depend on queued_count.
A heartbeating worker missing readiness metadata is not “almost active”; it is incompatible.
Any detector that knows a pod is incompatible should either terminate, block, or page. Logging is not a state transition.
Bug 1 happened because the system observed enough evidence and still kept paying for the pod. That is a broken control loop, not a missing log.
Release Pipeline
Create a contract release train:
Change reigh-contracts.
Generate TS/Python/SQL.
Run contract conformance in all consumers:
TS edge tests against selectedRoute.generated.ts
Python worker tests against selected_route_generated.py
Postgres tests against generated SQL functions and capability rows
Build worker artifact.
Deploy DB migration.
Deploy edge functions.
Deploy orchestrator with required contract_version and worker artifact digest.
Canary one worker pool.
Promote.
Cross-repo is fine only if GitHub Actions wires these together. A contract PR should not be mergeable unless all three repos pass against the same generated contract artifact.
Good Enough
Good enough is not “more tests.” Good enough is:
Generated route derivation in TS/Python/SQL from one manifest.
DB-only task admission RPC.
Immutable worker version selection.
Orchestrator readiness protocol with termination on mismatch.
Queued-but-unclaimable tasks become Blocked with structured reason, not immortal Queued.
First Week
Do this first:
Add contracts/golden-route-cases.jsonl and make TS, Python, and Postgres consume it in CI.
Add DB constraints/triggers rejecting missing or unknown route contracts on new Queued tasks.
Change RunPod startup to checkout a required SHA, not origin/main.
Terminate stuck spawning workers regardless of queue depth.
That week does not finish the architecture, but it flips the system from silent drift to loud drift. The deeper fix is the contract release unit. Without it, this class of bug will keep returning under new names.