Model Gateway rollback — four levers, rehearsed 2026-09-26 and 2026-10-12
MG-4.6 · task 4H of LLD #3138 · issue #3150 · HLD #2649 · PRD #2644 v1.5 · milestone 31.
Ordering ruling #3150#issuecomment-5844810104: this rollback is proven BEFORE the #3148 default flip, not after. It is item 3 of #3148's pre-flip checklist.
Core tenet 5 is "rollback always possible in under 5 minutes." Measured end-to-end for the per-agent lever: 5.4 seconds, decide → first incumbent turn served (§10).
Tenet 5 ruling (review of #3650). L3 is a forward change — a code edit, build and deploy — not a deployment reversal, so its 10–40 min is not a Tenet 5 conflict. Tenet 5 for the #3148 flip rests on L2.
Status, 2026-09-29, after #3661. Item 9 — reversal must be one audited action that leaves every agent serving, with no per-agent model edit — is discharged in code: each agent carries a stored, write-time-validated
direct_fallback_model_id(migration 278) whichSetAgentGatewayRoutingapplies tomodel_idin the same statement that clears the flag.THE ASYMMETRY, STATED HERE BECAUSE THIS IS WHERE ITEM 9 IS CALLED DISCHARGED. Item 9 is about rolling BACK, and only that. Rolling forward again is not symmetric: the flag-off write overwrites
model_idwith the fallback and the catalogue coordinate it replaced is recorded nowhere —agent_configurationshas no history table, anddirect_fallback_model_iddeliberately holds the DIRECT model, not the gateway one. The L1a snapshot is the only copy, which is why §4 tells you to keep it.So the second "on" of item 10's
on → off → onneeds a per-agentUpdateAgentedit to restore each catalogue id. The integration testTestGatewayFallback3661_RollingForwardAgainThenBackIsStablesays so in its own body ("the operator restores the catalogue model withUpdateAgentin reality"). Budget for that when timing item 10, and do not read "item 9 is discharged" as "the round trip is one action in both directions". Item 10 — the timed fleet-wide on → off → on rehearsal — is NOT done, and it is what actually demonstrates Tenet 5 for the flip (#3150, gated on 4F). So: read this runbook as evidence that the per-agent lever is reversible in seconds, and that the mechanism L2 needs now exists — not as evidence that the fleet lever has been exercised. It has not.
1. What this rolls back, and what "rollback" means here
The Model Gateway is a pass-through egress proxy for LLM calls. A
gateway-routed agent's turn dials model-gateway:8091 with a short-TTL
agent-scoped bearer; an unrouted agent's turn dials the provider directly from
the worker (the "direct" or "incumbent" path, which MG-4.4 will eventually
delete).
Rolling back means moving traffic from the gateway path back to the incumbent direct path. It does not mean uninstalling the gateway, and it does not undo anything the gateway already wrote (§8).
There is no bypass switch, by ruling (#2646, HLD §9.3). Break-glass is a
time-boxed, named, audited operator procedure — see
docs/runbooks/binauthz-breakglass.md; it is referenced here, not duplicated.
The one mechanic that decides everything below
agent_configurations.gateway_routed is read once per session, by
internal/runtime/session/initializer.go, and frozen into the session snapshot.
internal/runtime/gatewayroute.Route then reads only that snapshot.
So a flag flip binds the NEXT session. It does not move a live one. A session created before the flip keeps the old route until it ends. Every timing claim in this runbook is "decide → first turn of a NEW session", and an operator who flips the flag and watches an existing chat will conclude, wrongly, that the lever did nothing.
2. Signals that say "roll back"
#3633 has landed
(merged 515ea3932, 2026-09-26) and is deployed on beta-dev, so these are real
series, verified against :8091/metrics on 2026-09-29 — not pending ones:
| signal | series / source | threshold |
|---|---|---|
| gateway down | up{job="model-gateway"} == 0 or absent(up{...}) for 2 m | any |
| gateway-attributable failure ratio | model_gateway_upstream_status_total{endpoint_id,status} — 5xx over total | sustained > 5 % |
| governance refusal surge | model_gateway_requests_total{org_id,endpoint_id,outcome} — outcome="deny" share | step change |
| provider latency | model_gateway_upstream_duration_seconds{endpoint_id} p95 | vs. that endpoint's norm |
| metering path dead | model_gateway_tokens_total{direction} flat while requests climb | any |
| cut streams per rollout | in-flight streams were cut in the gateway log | any occurrence |
| in-flight saturation | model_gateway_inflight_upstream_requests pinned at the HPA ceiling | sustained |
| terminal turn failures | GATEWAY_ROUTING_UNAVAILABLE at the worker | any sustained |
Two traps in these series. Both measured 2026-09-29.
1. The series are created LAZILY, per (org_id, endpoint_id), on that pair's
first call. #3148's pre-flip checklist item 2 reads:
curl 127.0.0.1:8091/metrics | grep -c '^model_gateway_requests_total' # expect > 0
On a beta-dev gateway running a post-#3633 image, that command returned
0. One governed turn later it returned 3 children (allow, deny,
unassessed — all three initialised, allow=1). So the check as written gives
a false RED on any freshly restarted gateway that has not yet served a governed
call, and its natural reading — "#3633 is not deployed" — invites a pointless
redeploy. Drive one governed turn first, then grep.
2. An absent series is not a zero. The metric's own help text says so: "an
absent series means that pair has never called rather than never been refused."
A naive error-ratio alert on a quiet org is 0/0 and never fires. Any alert on
these must pair the ratio with absent() — the same blinded-arm discipline as
§9's empty-corpus arms, one layer out.
docs/runbooks/mg-baseline.md explains why the ledger still cannot answer the
availability question, and
#3147 closed as
instrument-only with no baseline established.
Do not use the ledger as a health signal. Two independent reasons, both measured: a total gateway outage writes nothing, so zero rows is not 100 % availability; and the direct cohort writes no rows at all today (§9, finding 2).
The decision rule
Roll back when the gateway is failing turns that the direct path would serve.
A routed agent whose turn fails is terminal — gatewayroute.Route refuses
rather than silently falling back to direct egress, by design — so a gateway
problem is a chat outage for every routed org, not a degradation. With the
#3148 default flipped, "every routed org" is the whole fleet.
3. The levers
| lever | scope | time | needs a deploy? | |
|---|---|---|---|---|
| L1 | agent_configurations.gateway_routed = false | per agent | < 30 s (measured 5.4 s) | no |
| L2 | the #3148 default, reversed | fleet | pending 4F | no (config) |
| L3 | modelgateway.ProductionRoutingReleased = false | fleet | 10–40 min | yes — code, build, redeploy |
| L4 | a process flag in the box-local .env (§4A) | this deployment | < 30 s (measured 12.9 s) | no (config + recreate) |
Pick the narrowest lever that covers the blast radius. L1 for one or a few agents; L2 once it exists, for a fleet-wide bad flip; L4 for a whole feature on this deployment; L3 only per §6.
WHICH LEVERS SURVIVE THE RECONCILER — read this before you touch anything
Deploy Dev Stack (.github/workflows/dev-deploy.yml) runs
scripts/dev-reconcile.sh on every image publish, on repository_dispatch,
and on a */15 * * * * cron (5 → 15 min in #4519) — re-derive that schedule from the workflow, do not
trust this sentence. It hard-resets the shared checkout to origin/main and then
runs docker compose -f docker-compose.dev.yml up -d --remove-orphans
unconditionally (line 637; the other up -d in that file is --no-deps and is
the per-service image-rollback path, not this).
So a rollback is only real if the reconciler re-applies it rather than reverting it, and the difference is not cosmetic — it is the difference between a rollback and a rollback that silently undoes itself inside the tenet-5 window.
| what you changed | survives a reconcile? | why |
|---|---|---|
agent_configurations.gateway_routed (L1) | yes | the reconciler touches no database row |
a line in the box-local .env (L4) | yes — and is APPLIED by it | .env is gitignored, so git reset --hard origin/main does not remove it, and docker compose config interpolates it into the rendered config the reconciler diffs |
ProductionRoutingReleased in code (L3) | yes, once the image is published | it is in origin/main |
docker run/docker exec env on a live container | NO — reverted within one cron period | the rendered config no longer matches, so up -d recreates the container from the compose file |
| a hand-pulled older image tag | NO — reverted within one cron period | the reconciler docker compose pulls :latest and re-ups |
The last two rows are the trap. They are the fastest things to type during an incident, they appear to work, and they are gone within one sweep (≤ 15 min plus schedule delay) with no log line pointing at the cause. If you need an image-level rollback, publish it — do not pin it by hand on the box.
4. L1 — the per-agent lever (the one to reach for)
This is the rehearsed procedure. It has four steps.
#3661 CHANGED WHAT L1c IS. When this runbook was written, L1c was an operator substitution: a model the operator chose under incident pressure, applied by raw SQL, unaudited, because the pre-routing native id was recorded nowhere. #3661 (merged; migration 278) gives each agent a stored, write-time -validated
direct_fallback_model_id, andSetAgentGatewayRoutingapplies it tomodel_idin the same statement that clears the flag. So L1b now does the whole rollback and L1c is a VERIFICATION — you read back what the audited write did, rather than performing a second, unaudited step.The one case that is not automatic is an agent with no stored fallback, which is either a row written before 271 or one routed under
acknowledge_not_rollback_safe(a gateway-only model — an OpenRouter coordinate has no direct equivalent to fall back to). Those agents are named in advance, before any flip, byscripts/check-direct-fallback-census.py. They are not discovered here. Run the census BEFORE a flip, not during a rollback — §4.0.
Set the scope once:
export ORG=00000000-0000-0000-0000-000000000001 # the affected org
export PSQL='docker exec upsquad-postgres psql -U upsquad -d upsquad'
export DECIDE=$(date -u +%Y-%m-%dT%H:%M:%SZ) # keep this: §9 needs it
echo "rollback decided at $DECIDE"
L1.0 — the pre-flip census (run this BEFORE you ever need the rest)
This step is not part of an incident. It is the thing whose absence turned pass 1 of the rehearsal into an outage, and its whole value is that it is run while everything is healthy.
python3 scripts/check-direct-fallback-census.py --scope-org "$ORG"
# rc=0 every routed agent can be rolled back
# rc=1 at least one cannot — it is NAMED, with the reason
# rc=2 could not look (bad DSN, migration 278 not applied, unparseable prefix table)
ON A HOSTED DEPLOYMENT, PASS
--hosted-only. A fallback from a local open-weight family (gemma*,qwen*,llama*,mistral*,phi*,deepseek*) is served keylessly by the worker only whenollama_base_urlis set.git grep WORKER_OLLAMA_BASE_URLfinds it indocker-compose.dev.ymland nowhere else, so such a fallback is real on dev and on-prem and no fallback at all on hosted.The predicate does not guess which shape it is looking at — it cannot observe a worker env var from the orchestrator, and one that guessed would be wrong silently. So the limit is printed on every affected row on every run, and
--hosted-onlyturns it into a finding for the operator who knows the answer. Record which form you ran in the pre-flip evidence.
Every entry must be either fixed — declare a fallback with
SetAgentGatewayRouting(direct_fallback_model_id=…) — or accepted by the
founder by name, --accept <agent_id>, recorded on
#3148. There is no
--accept-all; an acceptance that does not name the agent is not an acceptance,
and an --accept for an agent that is not a finding is an error, so a stale
waiver cannot wave a new agent through.
L1a — record what you are about to change (5 s)
Do this first or you cannot restore the forward state. The rollback of the
rollback needs the model_id values too, not just the flags (L1b changes them
now).
The
direct_fallback_model_idcolumn is why this snapshot is now a revert and not a guess. Before #3661 this snapshot captured the catalogue id the agent was routed with,agent_configurationshad no history table, and the pre-routing native id was therefore recorded nowhere — so choosing the direct model was an operator decision. It is now a stored, validated column, so the snapshot below records both and the rollback restores rather than substitutes.An empty third column is the not-rollback-safe set. It should be empty because L1.0 said so, not because you are seeing it for the first time here.
$PSQL -t -A -F'|' -c \
"SELECT id, gateway_routed, model_id, coalesce(direct_fallback_model_id,'')
FROM agent_configurations
WHERE org_id = '$ORG' ORDER BY id;" > /tmp/mg-rollback-before-$DECIDE.txt
grep '|t|' /tmp/mg-rollback-before-$DECIDE.txt # the agents you are de-routing
§9's
--rolled-back-fromparses the first three columns. The fourth is additional and is ignored by the parser; keep the column order as written.
L1b — flip the flag (< 1 s; measured 0.16 s)
Preferred, audited form — and since #3661 it is the WHOLE rollback.
SetAgentGatewayRouting emits LifecycleEventGatewayRoutingChanged onto the SIEM
stream, and the SQL below does not. It now also writes model_id: on the
true→false transition the statement sets
model_id = COALESCE(direct_fallback_model_id, model_id) under the row's own
FOR UPDATE lock, so there is no window in which an agent is de-routed but cannot
resolve its model. The audit payload carries model_id before/after,
direct_fallback_applied and rollback_safe.
WHAT THE SUBSTITUTION IS RECORDED ON, AND WHO CANNOT SEE IT YET. The write emits
agent.gateway_routing_changed(withmodel_idbefore/after,direct_fallback_applied,rollback_safeandvalidated: direct_fallback_exempt) and, whenmodel_idactually moved,agent.model_changedwithreason: direct_fallback_applied. The fallback is deliberately exempt from the team-admitted-model check — architect ruling B, #3661#issuecomment-5951806819: admission is a claim about the gateway path and the fallback is the model in force off it. It is NOT yet visible to the agent's users, who see a model change they were not told about; #3673 is that deliverable and it gates the #3148 flip. Say in the incident record that the behaviour changed.The previous version of this line said the opposite, and it was right at the time: the RPC "never touches
model_id", so the audited path on its own reproduced the pass-1 dead agent and L1c was required after it. That is what #3148 item 9 asked to be fixed and what #3661 fixed. If you are reading this against a deployment that predates migration 278, the old behaviour applies and the SQL form of L1c below is the stand-in.
Opt-in and opt-out are the same RPC with the other value — there is no
separate disable call, and the field is optional bool so an omitted value is
refused rather than read as false:
curl -sS -X POST \
http://127.0.0.1:8083/upsquad.agent.v1.AgentService/SetAgentGatewayRouting \
-H 'Content-Type: application/json' \
-H "x-tenant-id: $ORG" \
-H "Authorization: Bearer $UPSQUAD_OPERATOR_TOKEN" \
-d '{"agent_id":"<AGENT_UUID>","gateway_routed":false}'
Break-glass form, when no operator bearer is available — it is what the rehearsal used, and it skips the audit event, which is a cost to state out loud in the incident channel:
# Since #3661 the break-glass SQL must do BOTH HALVES, because it is bypassing the
# RPC that now does them together. COALESCE, not a CASE on `model_id LIKE '%/%'`:
# the declared fallback is already the right value for an agent whose pre-routing
# model was native (the capture arm stored that same id), so the assignment is a
# no-op there by construction.
$PSQL -c "UPDATE agent_configurations
SET gateway_routed = false,
model_id = COALESCE(direct_fallback_model_id, model_id),
updated_at = now()
WHERE org_id = '$ORG' AND gateway_routed;"
L1c — VERIFY the fallback was applied (< 1 s)
#3661 turned this step from a substitution into a verification, and the difference is the whole point of that issue. What follows is a read, a comparison, and one narrow escape hatch.
What it used to be, recorded rather than deleted: a routed agent very often
carries a gateway-catalogue model id (openai/gpt-oss-120b:free,
google/gemini-2.5-flash). The direct path hands model_id straight to the native
provider SDK (agent_worker/llm/anthropic.py), which has no such model. Measured
on the first rehearsal pass:
404 not_found_error: model: openai/gpt-oss-120b:free
So L1b alone produced a flag that read back perfectly and an agent that was
dead, and L1c was an operator writing a model of their own choosing, by raw
SQL, unaudited — the rehearsal substituted claude-haiku-4-5-20251001 for a Gemini
agent and an OpenRouter agent, a pragmatic choice and not a correct one.
What it is now. L1b writes model_id = COALESCE(direct_fallback_model_id, model_id) inside the same statement that clears the flag. So verify:
# Every de-routed agent's model must now be its DECLARED fallback, and the third
# column must be non-empty. An empty third column is the not-rollback-safe set,
# which L1.0's census should already have named.
$PSQL -t -A -F'|' -c \
"SELECT id, model_id, coalesce(direct_fallback_model_id,''),
model_id = coalesce(direct_fallback_model_id, model_id) AS restored
FROM agent_configurations
WHERE org_id = '$ORG' AND NOT gateway_routed ORDER BY id;"
# And the falsifiable form — check 7 of §9, which asserts the same property over
# the agents that are STILL routed (i.e. whether the NEXT rollback would work).
python3 scripts/check-direct-fallback-census.py --scope-org "$ORG"
THE ESCAPE HATCH, AND ITS TWO CONDITIONS. If an agent shows an EMPTY
direct_fallback_model_id, the rollback cleared its flag and left its model alone — deliberately: substituting a guess is what #3148 item 9 rejected. Such an agent is either a row written before migration 278, or one routed underacknowledge_not_rollback_safebecause its model has no direct equivalent at all (openai/gpt-oss-120b:freeis an OpenRouter coordinate; the direct path has no OpenRouter provider, so no value of the fallback makes its rollback a revert).Only then, and only for those agents, choose a model — and say in the incident record that you chose it and that the agent's behaviour changed:
export FALLBACK='claude-haiku-4-5-20251001' # a model YOU are choosing$PSQL -c "UPDATE agent_configurationsSET model_id = '$FALLBACK', direct_fallback_model_id = '$FALLBACK',updated_at = now()WHERE org_id = '$ORG' AND NOT gateway_routedAND direct_fallback_model_id IS NULL;"The
direct_fallback_model_id IS NULLpredicate is load-bearing and replaces the oldmodel_id LIKE '%/%'heuristic: it selects exactly the agents that HAVE no declaration, rather than guessing at which ids look unroutable. An agent with a declaration has already been restored and must not be touched.This block should never run. If it does, L1.0 was skipped or an
acknowledge_not_rollback_safeagent was never accepted by name on #3148 — and that is the finding to record, above the model you picked.
claude-haiku-4-5-20251001 is the native id every direct-serving agent on
beta-dev already uses, which is why the rehearsal used it. It is a default, not
an answer.
L1d — prove EACH rolled-back agent is serving (≈ 5 s per agent)
Not optional, not "check the flag", and not "probe an agent". The flag being off proves the lever moved. A completed turn from some healthy agent proves nothing about the agents you de-routed — that was finding N4: the checker's own green case turned out to be the never-routed control agent. Probe every agent in the L1a set, by id.
export PATH=$PATH:$HOME/go/bin # grpcurl
export H="x-tenant-id: $ORG"
PROBES=()
# The subject set IS L1a's `t` rows. Column 1 is the agent_configurations id, which
# is also `agent_sessions.agent_id` — that column FKs to agent_configurations, not
# to agents (core#969), so this id is the join key the checker uses.
for CFG in $(grep '|t|' /tmp/mg-rollback-before-$DECIDE.txt | cut -d'|' -f1); do
AG=$($PSQL -t -A -c "SELECT agent_id FROM agent_configurations WHERE id = '$CFG';")
SID=$(grpcurl -plaintext -H "$H" \
-d "{\"tenant_id\":\"$ORG\",\"user_id\":\"rollback-verify\",\"agent_id\":\"$AG\"}" \
127.0.0.1:50052 upsquad.runtime.v1.LifecycleService/CreateSession \
| python3 -c 'import sys,json;print(json.load(sys.stdin)["sessionId"])')
# The `echo` is REQUIRED. A bare `grpcurl SendMessage` transcript carries NO
# session id, so the checker cannot attribute it to an agent — and a transcript
# committed from an earlier rehearsal would pass. The checker FAILS without it.
F="/tmp/mg-rollback-probe-$DECIDE-$CFG.json"
{ echo "{\"sessionId\":\"$SID\"}"; \
grpcurl -plaintext -max-time 200 -H "$H" \
-d "{\"tenant_id\":\"$ORG\",\"user_id\":\"rollback-verify\",\"agent_id\":\"$AG\",\"session_id\":\"$SID\",\"message\":\"Reply with exactly the word INCUMBENT and nothing else.\"}" \
127.0.0.1:50052 upsquad.runtime.v1.LifecycleService/SendMessage ; \
} | tee "$F" | tail -4
PROBES+=( --probe-transcript "$F" )
done
# The route oracle, for the record. It is NOT sufficient on its own:
# `adapter_resolved` is emitted at langgraph_executor.py:466, BEFORE the LLM call,
# so the pass-1 dead agent emitted it and then 404'd.
docker logs upsquad-agent-worker --since 5m 2>&1 | grep adapter_resolved | tail -5
You need a completed turn for every agent, not one for the set. Then run the
post-condition check (§9) with "${PROBES[@]}".
Rolling L1 forward again
This is a per-agent model_id edit, not "the same RPC with the other value".
The RPC restores the flag; it cannot restore the catalogue coordinate, because
nothing recorded it (see the asymmetry note in §1). The SQL below is therefore the
procedure, and SetAgentGatewayRouting(gateway_routed=true) is how you would flip
the flag alone if the model needed no restoring.
$PSQL -c "UPDATE agent_configurations
SET gateway_routed = true, model_id = '<FROM L1a SNAPSHOT>', updated_at = now()
WHERE id = '<CONFIG_UUID>';"
# THE COLUMN LIST MUST MATCH L1a's, ALL FOUR OF THEM. L1a gained
# `direct_fallback_model_id` in #3661; a three-column SELECT here diffs a 3-field
# line against a 4-field one, so EVERY line differs and "restored byte-identically"
# can never print — measured by review 5352898032 following this step verbatim after
# a correct rollback and a correct roll-forward (diff rc=1, every line). An operator
# would be told a correct restore had failed.
$PSQL -t -A -F'|' -c "SELECT id, gateway_routed, model_id,
coalesce(direct_fallback_model_id,'')
FROM agent_configurations
WHERE org_id = '$ORG' ORDER BY id;" \
| diff /tmp/mg-rollback-before-$DECIDE.txt - && echo "restored byte-identically"
4A. L4 — the config lever (a process flag in the box-local .env)
Rehearsed 2026-10-12 on an isolated compose project. Measured 12.91 s, decide → new config live, with the in-flight generation completing rather than being cut.
This is the lever for turning a whole feature off on this deployment without a
code change. Today there is exactly one such flag, and
CONFIG_LEVERS in scripts/check-model-gateway-rollback.py is the single
declaration of the set — check 8 is the CI guard over it, so a lever added here
and not there (or there and not here) reddens.
| flag | fail-safe value | what disabled does |
|---|---|---|
MODEL_GATEWAY_SUBSCRIBER_ADMISSION | disabled | Mode E admission stops running: every carrier-bearing request is refused subscription_mode_disabled (403). It does not fall through to the other admissions (subscriberauth/select.go). |
It is enabled on beta-dev as of 2026-10-12, so this is a live lever, not a
hypothetical one. It is one of two independent switches — this one is the
operator's deployment gate, llm_endpoints.status is the per-tenant L5
kill-switch — and rolling this one back does not roll back a tenant's, nor the
reverse. Read EnvSubscriberAdmission's doc comment before assuming either.
The procedure — ONE COMMAND, and it is a script, not a paste
# Dry-run first. Validates every precondition that could make the real run LIE,
# and writes and applies nothing.
scripts/mg-config-lever-rollback.sh --to disabled --dry-run
# Then, for real. --capture-log is not optional if you intend to run §9's
# check 5 afterwards (see "The drain evidence" below).
scripts/mg-config-lever-rollback.sh --to disabled \
--capture-log /tmp/mg-gateway-$(date -u +%Y%m%dT%H%M%SZ).log
This used to be a four-step paste, and the paste was wrong. Review 5489757012 executed it against a real Compose renderer and a simulated container and got exit 0 with the feature still enabled, three ways:
| what the operator did | what the paste did | why |
|---|---|---|
.env line had one leading space | reported success, changed nothing | sed exits 0 when it matches nothing |
had MODEL_GATEWAY_SUBSCRIBER_ADMISSION exported in their shell | reported success; rendered config stayed enabled | Compose resolves the process environment before .env |
docker compose up -d failed | reported success | the readback grepped the variable name, not its value |
A rollback that reports success without rolling back is worse than one that
fails, and prose cannot be made fail-closed. So the procedure is
scripts/mg-config-lever-rollback.sh, every step aborts with a named exit
code, and it does not exit 0 until the .env value, the rendered value
and the running container's value all three equal the target and /readyz
returns 200.
| rc | meaning |
|---|---|
| 0 | applied and verified running and ready |
| 2 | could not look (bad args, unreadable file, no timeout(1)) |
| 3 | the .env entry is absent, duplicated, or noncanonical — refused |
| 4 | the process environment would override the file — refused |
| 5 | the write did not take |
| 6 | the Compose apply failed |
| 7 | the deadline expired (tenet 5), named rather than hung |
| 8 | the running value != target — the rollback did not apply |
| 9 | the rendered value != target |
It is bounded, as a whole. One deadline (--deadline-seconds, default
300 = core tenet 5) starts before the edit and every step is charged against
it; each curl carries --max-time and Compose runs under timeout. The
unbounded version of the readiness loop ran against a 503 until the reviewer's
external timeout killed it — a tenet-5 breach that reports nothing, which is
strictly worse than rc=7.
It refuses rather than normalises. A duplicated or export-prefixed .env
entry is reported by name and left alone: rewriting an operator's file in a way
they did not ask for, during an incident, is not a kindness.
The drain evidence — capture it BEFORE the recreate
up -d destroys the old container, and with it the log ring that §9's
check 5 reads: --gateway-log-cmd defaults to docker logs upsquad-model-gateway, which after the recreate is the new container.
Measured: check 5 against a fresh container's log returns
FAIL 5/drain-not-cut EMPTY CORPUS. So the only evidence that this rollback
drained rather than cut has to be taken before the thing that produced it is
removed — which is what --capture-log does, and why it runs before the apply.
Feed it back:
python3 scripts/check-model-gateway-rollback.py --since "$DECIDE" \
--gateway-log-cmd "cat /tmp/mg-gateway-<stamp>.log" \
--rolled-back-from … "${PROBES[@]}" --require-drained-inflight
What happens to in-flight requests — the part that is easy to get wrong
L4c recreates the container, which means SIGTERM, which means the §7 drain.
An in-flight governed generation therefore completes; it is not cut. That is
not a property of the procedure, it is a property of two numbers in
docker-compose.dev.yml, and they are in a two-sided budget:
drain + SIGKILL margin <= stop_grace_period <= tenet 5 - recreate overhead
180s + 30s <= 210s <= 300s - 10s
-------------------------------------------------------------------------
floor 210s SHIPPED 210s ceiling 290s
The shipped value sits exactly on the floor, and that is ACCEPTABLE — the 30 s
is the headroom, not a shortage of it. Ruling on review 5489803877. The same
30 s is budgeted on the other side too: the gateway derives its maximum request
duration as drain − MaxRequestMarginSeconds
(internal/modelgateway/config.go), so a process honouring SIGTERM exits at the
drain cap of 180 s and the grace period is never the binding constraint. Nothing
needs changing here.
What a breach of it does and does not mean — three severities, not one. An earlier revision of this section said raising the drain by one second "starts SIGKILLing in-flight generations". That was wrong, and the error is worth keeping visible because it is the easy mistake:
| condition | what it is | what it is NOT |
|---|---|---|
grace < drain + 30 | a margin breach. At 209 s there is still 29 s of slack; the margin exists for the tail — a generation finishing at the cap, plus shutdown bookkeeping | not a kill, and not something happening to traffic today |
grace < drain | a demonstrated kill. Docker SIGKILLs mid-drain and in-flight generations are cut (measured at 5 s) | — |
grace > ceiling | the lever itself cannot finish inside core tenet 5 — reach for L1 instead | not a safety problem |
If the drain timeout is ever raised far enough that the floor passes the ceiling, the window is empty: no grace period satisfies both, and the remediation is to lower the drain timeout, not to pick a number in between. Check 8 asserts all four cases separately, and 209 s / 291 s are in its arm set precisely because 5 s and 9 m are too far out to catch an off-by-one in either bound.
Keep policy margins, measured timings and enforced bounds distinct. The 30 s
is a policy margin; 12.91 s is a measured timing; --deadline-seconds 300 is an
enforced bound. Only the third one stops anything.
Why that is a static check and not something you verify at the time
Measured 2026-10-12 on an isolated compose project (-p mg-rollback-scratch-3150, no published ports, no volumes, nothing shared with
upsquad-dev), driving a stub with the gateway's own drain contract and a
generation with 12 s of work left at the instant of the flip. Full transcript:
docs/runbooks/model-gateway-rollback-evidence/2026-10-12-config-lever-*.
stop_grace_period | flip → new config live | the in-flight stream | shutdown complete | in-flight streams were cut |
|---|---|---|---|---|
| 210s (as shipped) | 12.91 s | completed (drained_for=12s) | 1 | 0 |
| 5s (mutant) | 5.89 s | SIGKILLED | 0 | 0 |
The broken configuration is FASTER, and it also reports zero cut lines —
SIGKILL stops the process before it can log that it cut anything. So neither a
stopwatch nor the cut-line count tells the two apart. Check 5 does tell them
apart, because it demands a paired start → done sequence and the mutant has an
unpaired start; driven with the two logs above it returns ok (12 026 ms) and
FAIL respectively. But check 5 only speaks after a rehearsal somebody chose to
run, and this hazard arrives as a two-line config edit on a routine merge. The
arithmetic is the only thing that catches it at review time, which is what
check 8 is.
5. L2 — the default lever (pending 4F #3148)
#3148 makes the gateway the default path for every org rather than an opt-in. Its rollback is "the same action, reversed" — one declaration plus the exception list, no deploy — and this section is deliberately unfilled until 4F merges, because the lever's name and shape do not exist yet and a guessed command is worse than an absent one.
Owed the moment 4F merges (#3150 acceptance item 5, #3148 checklist items 3
and 10): execute L2 on → off → on, timed, and record it here and on #3150.
"Served" means a COMPLETED TURN for a previously catalogue-id agent — an
adapter_resolved gateway_routed=False line does not count, because that line was
emitted in pass 1 too, before the 404.
#3148 item 9 is discharged (#3661). Reversal is now one audited action that
leaves every agent serving, with no per-agent model edit: the flag-off transition
applies each agent's stored direct_fallback_model_id to model_id in the same
statement, under the row's own lock. So L2 no longer inherits L1c's defect — with
one standing condition, which is L1.0's census: an agent with no declared
fallback (a pre-migration-271 row, or one routed under
acknowledge_not_rollback_safe because its model has no direct equivalent) is
still de-routed but left on its own model. label:prod-enablement keeps that
register; scripts/check-direct-fallback-census.py must read rc=0 — or every
entry must be accepted by the founder BY NAME on #3148 — before the flip.
What is still owed is the EXERCISE, not the mechanism. L1 remains the only rehearsed per-agent lever and L3 the only rehearsed fleet lever. Item 10 is the timed on → off → on run that makes L2 rehearsed, and it is #3150's.
The blast radius #3148 must accept in writing: on beta-dev, N=1 ⇒ any MG restart
fails every routed agent's new turns (GATEWAY_ROUTING_UNAVAILABLE,
terminal) for the restart window; in-flight turns drain (§7).
6. L3 — the nuclear lever (NOT < 5 minutes)
internal/modelgateway/prodgate.go:
const ProductionRoutingReleased = true // -> false
This is a compile-time constant. Flipping it needs a code change, review, a
build and a redeploy: realistically 10–40 minutes, dominated by CI and image
promotion. scripts/check-model-gateway-exposure.py asserts the constant is
still wired to its caller precisely because it is advertised as a rollback lever
and would restore nothing if the call site had rotted.
When it is the right lever anyway, despite the time:
- The gateway is serving but wrong — mis-metering spend, mis-attributing audit rows, leaking across a tenant boundary. L1/L2 move traffic; only L3 refuses to admit production routing at all.
- L1/L2 are untrustworthy — the flag write is failing, or the population is unknown. L3 does not depend on per-agent state being correct.
- You need a single reviewable artefact for the incident record.
Do not reach for L3 for an outage L1 or L2 fixes in seconds.
7. The rolling-update / drain case
Rehearsed. The drain is real, and the naive check for it is a false green.
The manifests are surge-based — maxSurge: 1, maxUnavailable: 0
(deployments/model-gateway/base/deployment.yaml) — because every replica taken
down holds minutes-long generations, so "unavailable" means "cut somebody's
in-flight answer", not "a request retries". The drain budget is one declaration
with three consumers, and scripts/check-model-gateway-exposure.py asserts the
arithmetic:
preStop sleep 10s
MODEL_GATEWAY_DRAIN_TIMEOUT_SECONDS 900s (base configmap)
margin so SIGKILL does not land on the tail 30s
--------------------------------------------------
terminationGracePeriodSeconds 940s (base)
220s (dev overlay)
The smaller of the process window and the grace period wins. On compose,
MODEL_GATEWAY_DRAIN_TIMEOUT_SECONDS=180, from which the enforced maximum
request duration is derived as drain − 30 = 150 s; the gateway logs
drain_timeout=3m0s max_request_duration=2m30s in its first ten lines.
Rehearse it
Fire SIGTERM while a stream is genuinely in flight, or the test proves nothing. Poll and stop in the same script — a gap between the two lets the stream finish first, which is exactly how the first attempt produced a false green:
# 1. Launch a long governed turn in the background (a routed agent).
# ... CreateSession + SendMessage as in L1d, with a long prompt, backgrounded.
# 2. Poll the in-flight gauge and fire the instant it is non-zero.
for i in $(seq 1 300); do
G=$(curl -s --max-time 2 http://127.0.0.1:8091/metrics \
| awk '/^model_gateway_inflight_upstream_requests/{print $2}')
if [ -n "$G" ] && [ "$G" != "0" ]; then
echo "inflight=$G — firing SIGTERM"
time docker compose -f /opt/upsquad/upsquad-core/docker-compose.dev.yml \
stop -t 210 model-gateway
break
fi
sleep 0.2
done
# 3. Assert: the sequence exists, took NON-ZERO time, and cut nothing.
docker logs upsquad-model-gateway 2>&1 \
| grep -E "draining in-flight streams|shutdown complete|were cut"
docker logs upsquad-model-gateway 2>&1 | grep -c "in-flight streams were cut" # must be 0
-t 210 exceeds the 180 s process window so docker does not SIGKILL the tail.
Restart — docker compose start DOES NOT WORK
$ docker compose -f docker-compose.dev.yml start model-gateway
model-gateway is missing dependency migrate
compose start resolves depends_on against containers that must exist, and
the one-shot upsquad-migrate had been removed when this was hit. Re-derived
2026-09-29: with upsquad-migrate present (Exited (0)), compose start
succeeds — so this is a failure mode that depends on whether the one-shot has
been pruned, not an unconditional one. Which is exactly why you should not rely on
it during an incident.
Use plain docker start — it touches one container, parses no compose file,
resolves no depends_on, reconciles nothing, and creates no volume or network
risk:
docker start upsquad-model-gateway
until [ "$(curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:8091/readyz)" = 200 ]; do sleep 1; done
Measured: ready 1.3 s after docker start. (docker compose up -d --no-deps model-gateway also works but will recreate the container if the compose file has
drifted, which during an incident is a variable you do not want.)
On Kubernetes
The kubelet sends SIGTERM after the preStop sleep and waits
terminationGracePeriodSeconds. With maxUnavailable: 0 the new replica is
Ready before the old one is asked to stop, so a rollout costs no capacity. The
940 s grace is an operational bound, not an enforced maximum stream length —
WriteTimeout is 0 and the upstream client timeout is 0, only the response
header is bounded, so a generation still running at 900 s is cut. Tracked
separately; do not read 940 as a guarantee.
8. What is NOT reversible
Rolling back moves future traffic. It unwrites nothing:
| written while routed | reversible? | why it matters |
|---|---|---|
llm_usage_events rows (governance_outcome non-NULL) | No | spend already metered and attributed; the rollback does not refund or re-cohort it. mg-baseline.md: agent-grain, never row-ratio. |
| audit-chain rows | No, by design | hash-chained (audit_chain_scope=model_gateway). Deleting a row breaks the chain — that is the property. |
| minted agent bearers already in flight | No | short-TTL, LLM-audience. Already-issued tokens stay valid to expiry; the gateway keeps honouring them. To cut them you must stop the gateway (L3-adjacent), not flip a flag. |
| upstream provider calls already sent | No | the provider has the prompt and will bill for it. |
guardrail deny decisions | No | a denied turn stays denied and audited. |
model_id changed by the flag-off transition | Yes, from the L1a snapshot | Since #3661 it is restored from the agent's own DECLARED fallback, so for an agent whose pre-routing model was native this is a pure revert. It is a behaviour change only for an agent whose fallback was declared as something other than its pre-routing model — record that case. |
The consequence for a bad flip: every turn taken while the default was on is metered, audited and billed, permanently. Rollback bounds the blast radius going forward; it does not undo it. That asymmetry is the argument for rehearsing before flipping.
9. The falsifiable post-condition check
python3 scripts/check-model-gateway-rollback.py \
--since "$DECIDE" --scope-org "$ORG" \
--rolled-back-from "/tmp/mg-rollback-before-$DECIDE.txt" \
"${PROBES[@]}" \
--require-drained-inflight
--rolled-back-from is the L1a snapshot: its t rows are the subject set, and
without it check 6 fails by design — a run that cannot name which agents were
rolled back cannot attribute any evidence to them. --probe-transcript is
repeatable and check 6 requires one per rolled-back agent: probing 1 of 3 must
not certify 3.
--scope-modelhas been DELETED. It was added to stop a never-routed agent counting as positive evidence, and it did the opposite twice: it narrowed the failure scan (N1), and it could not distinguish the control agent anyway, because after L1c the control and the de-routed agents share the fallback model. With an enumerated subject set (check 6) a model filter has no remaining purpose. Selecting a subject by filtering a shared population is the root of all four findings this runbook has survived.
Eight post-conditions, each separately named and separately falsifiable (five until #3650, plus check 6's per-agent verdict, #3661's check 7, and #3771's check 8):
| # | asserts | why it is not redundant |
|---|---|---|
| 1 | no agent in the --scope-org has gateway_routed = true | the lever moved |
| 2 | no governed ledger row written since --since | nothing still reaching the gateway |
| 3 | a route line after --since + no failure on any de-routed session + an id-bearing, window-anchored, completed probe | a global gate: some turn took the incumbent path |
| 4 | every model_id in the --scope-org resolves on the direct path, against the worker's own prefix tables | the model in force is one the direct path can serve |
| 5 | last drain took non-zero time and cut nothing | the drain did work |
| 6 | one verdict per rolled-back agent; the run passes iff EVERY agent passes | THIS rollback worked, agent by agent |
| 7 | every agent that is STILL routed carries a direct-resolvable direct_fallback_model_id | the NEXT rollback will work too — a different population at a different time from check 4's (#3661) |
| 8 | the §4A config lever exists, survives the reconciler, and stop_grace_period sits inside [drain+30, 300-10] | the only check that is STATIC. Checks 1–7 need a rollback to have happened; check 8 catches a config edit that breaks the next one, at review time. It is also the only one that detects a grace period below the drain, because that failure logs nothing — see §4A |
Check 8 has no
--skip, and that is deliberate. It reads the repo rather than the stack, so it costs nothing and needs no live gateway. A flag to turn it off would be a flag that gets set during the incident it exists to prevent.
Checks 4 and 7 share one predicate and no copy of it. Both call
scripts/mg_direct_model.py, which PARSES_HOSTED_MODEL_PREFIXES/_LOCAL_MODEL_PREFIXESout ofagent_worker/llm/byok_factory.py— the direct path's own source of truth — so the checker cannot disagree with the worker. Check 4 was originally a'/' in model_idheuristic and said of itself that it was "deliberately a separate named check so it can be replaced by a catalogue lookup without touching the other four"; #3661 is that replacement.It is stronger in both directions, and only since the
/refusal landed. Two witnesses, because neither check dominated the other before that:
id old slash heuristic first #3661 predicate now mixtral-8x7bmissed (no slash) caught caught deepseek/deepseek-r1:freecaught missed (vendor segment matched the local deepseekfamily)caught The middle column is the F1 defect review 5351712949 measured, and the #3661 plan had predicted it in as many words — it said the heuristic would be "retained as a second, independent check … it catches a catalogue coordinate whose prefix happens to collide with a native family". Replacing it was right; replacing it without first refusing
/was not.scripts/mg_direct_model.pynow refuses a/before any prefix is considered, so the two checks coincide and neither is needed as a backstop for the other.A prefix table that will not parse makes the checker exit 2 ("could not look"), never 0. Every model id reading as unresolvable is what a broken regex produces, and it would otherwise look like a total-fleet finding.
Check 6 — the per-agent verdict table, and why checks 1–5 are not enough
Four review rounds found four instances of one defect, and the root was the same every time: the checker inferred its SUBJECT from a log-derived population that the subject shares with non-subjects. C1 counted route evidence as service; N1's scope narrowed the failure scan; N2's anchor fired on a field real transcripts never carry; N4's anchor checked the window but not the agent, so a completed probe of the never-routed control agent passed. The checker's own positive control turned out to be that control agent's session.
So the subject is now enumerated, not inferred. For each t row of the L1a
snapshot, all six must hold, and the default is FAIL:
| arm | source | |
|---|---|---|
| a | gateway_routed is false | DB, live |
| b | model_id has no provider prefix | DB, live |
| c | ≥ 1 session created after --since whose agent_id is this agent | DB agent_sessions |
| d | one of its sessions has adapter_resolved gateway_routed=False | worker log |
| e | no failure signal on any of its sessions | worker log |
| f | a completed, id-bearing probe whose session resolves through the DB to this agent and is one of its in-window sessions from (c) | --probe-transcript |
Missing, unresolvable or ambiguous evidence ⇒ FAIL for that agent, naming what was missing. There is no "some agent was healthy" path left.
N5 — (f) needs BOTH halves, and the first version had only one. Requiring the probe's session to belong to this agent is not enough:
agent_sessionshas no time predicate, so a transcript from an earlier rehearsal of the same agent still resolves to it and satisfied (f) forever. On the live DB both run-3 and run-4 sessions resolve to97a5cf02. N4 was window-without-identity; N5 is identity-without-window — the mirror image. (f) now requires the session to be one of (c)'s in-window sessions. Keep both conjuncts; each alone is a green light on a dead agent.The join key is a schema lie and it matters here.
agent_sessions.agent_idis named likeagents.idand FKs toagent_configurations(id)(core#969) — verified at head: for three real sessions the join hitsagent_configurations1× andagents0×. So the L1a snapshot's first column is the join key. Joining toagentswould match nothing and fail every agent for the wrong reason.
Checks 1 and 2 are both satisfied by a fleet that is uniformly dead — the flag is off and no gateway rows are written precisely because nothing works. Check 3 is the one that distinguishes those two worlds.
Check 3 was WRONG in the first revision of this PR, and the review caught it by replay (#3650 C1). It asserted only
adapter_resolved gateway_routed=False— whichlanggraph_executor.py:466emits after the adapter is built and BEFORE the LLM call. The pass-1 dead agent emitted that line and then took its 404, so the check reportedokon the one failure it existed to catch.adapter_resolvedis a ROUTE signal, never a SERVICE signal. Check 3 now requires three things together: route evidence timestamped after--sinceand no failure signal for any de-routed session (correlated bysession_id); and a probe transcript with a non-emptycompletion.finalResponseand noerrorblock, anchored to a session in the log window so a stale transcript cannot be replayed. Absent a transcript the verdict is unproven, which fails.Two further defects of this same family were found in round 2 and fixed. (N1) The scope filter was applied while building the session set that the failure scan then read, so
--scope-modelnarrowed which sessions could be found dead — and the invocation this runbook prescribed scoped by the control agent's model, so a log containing a dead de-routed session went green. Arm (b) is now unscoped: a failure anywhere in the window reddens, and scope narrows only positive evidence. (N2) The staleness anchor never fired, because a realgrpcurl SendMessagetranscript carries no session id — soprobe_sidswas always empty and the guard was skipped, and a transcript committed from an earlier rehearsal passed. A transcript with no session id is now itself a failure, and the id must be one of the de-routed sessions.
--require-drained-inflight is what stops check 5 certifying a 0 ms drain of an
idle process.
Every check fails on an empty corpus, naming what it examined, rather than reporting clean — four of the seven are absence assertions and an absence over an empty corpus is vacuous. Run the arms themselves:
python3 scripts/check-model-gateway-rollback.py --self-test-empty # the checker prints the arm count; 31 at #3661, rc=0
The arms include a positive control (a real 14 553 ms drain must PASS), without which the other nine are satisfied by a check that fails unconditionally.
10. The rehearsal — beta-dev
Durable transcript:
model-gateway-rollback-evidence/. Committed because the reviewer of #3650 could not re-verify the drain claim — the gateway had restarted and the log lines were gone. The four replay fixtures undertests/scripts/fixtures/mg-rollback/are live inputs to the checker's blinded arms, so they redden CI if their shape drifts.
Three routed agents, one org (…0001): gateway-tester-rpc, Repository map,
engineering test. Restored byte-identically afterwards (§11).
Pass 1 — L1b alone. The procedure as written FAILED.
| step | wall time | result |
|---|---|---|
| flip 3 flags to false | 0.10 s | UPDATE 3 |
| flag read back | 0.11 s | 0 of 18 routed |
| new session | 0.17 s | ok |
| first incumbent turn | 1.90 s | 404 not_found_error: model: openai/gpt-oss-120b:free |
| total decide → failure | 2.27 s | agent de-routed and dead |
Isolated with a negative control: a never-routed agent (generalist,
claude-haiku-4-5-20251001) served on the direct path in 1.0 s, so the direct
path was healthy and the model id was the fault. Procedure fixed — L1c added
— and re-run.
Pass 2 — L1b + L1c together. Passed.
| step | wall time | result |
|---|---|---|
flip flag and model_id (one statement) | 0.16 s | UPDATE 3 |
| flag read back | 0.14 s | 0 routed |
| new session | 0.12 s | ok |
| first incumbent turn | 4.95 s | INCUMBENT |
| total decide → incumbent served | 5.37 s | ≪ 5 min (tenet 5) |
Post-condition check, same instant, rc=0:
ok 1/flag-off 0 of 18 agent_configurations are gateway_routed
ok 2/no-new-governed-rows 0 governed rows since 09:30:24Z, against a non-empty
corpus of 51 prior governed rows (244 total)
ok 3/incumbent-serving 3 of 7 adapter_resolved lines took the incumbent path
ok 4/direct-path-model-… 18 agents examined, none provider-prefixed
ok 5/drain-not-cut last drain held 14553 ms, 0 cut streams
Drain rehearsal — two runs, and the contrast is the evidence
| SIGTERM fired at | drain held | cut lines | exit | proves | |
|---|---|---|---|---|---|
| run 1 | inflight=0 | 0 ms | 0 | 0 | nothing — false green |
| run 2 | inflight=1 | 14 553 ms | 0 | 0 | the drain works |
Run 2's client received a complete 15 058-character response with a completion
block and no error block: the in-flight stream was not cut. docker start
→ readyz=200 in 1.3 s; a routed turn served immediately after.
Both runs emit identical log lines and both have zero cut lines. A checker asserting only "0 streams were cut" certifies run 1. Hence check 5's duration arm.
Three findings the procedure-as-written did not predict
- The flag being off does not mean the incumbent serves. L1c exists because of this. Encoded as check 4.
- The direct path writes NO ledger row, even on success. The successful
generalistturn left the ledger at exactly 193 rows, re-checked after a delay to rule out an async flush; the newest direct row on the deployment is 2026-08-31. So #3150's acceptance wording "record the ledger evidence (a direct row hasgovernance_outcome IS NULL)" cannot be satisfied here, and a check waiting for a new direct row waits forever. The worker log is the oracle instead. Encoded as check 3. docker compose startcannot restart this service (missing dependency migrate). Encoded in §7.
Run 3 — 2026-09-29, re-verification after review
Re-run with the review's CASE WHEN guard and the amended check 3: 5.10 s
decide → INCUMBENT. Checker rc=0 with --probe-transcript, rc=1 without
it — route evidence alone is unproven, which is C1 fixed and demonstrated live.
CASE ELSE verified read-only: would_change=3 preserved_unchanged=15 total=18,
so a native-id agent is not rewritten.
End-to-end expected duration: L1 under 30 seconds including verification (measured 5.4 s + one check run). L2 pending 4F. L3 10–40 minutes.
11. Who can run this, with what
| lever | who | credential |
|---|---|---|
| L1, audited RPC | on-call devops, platform operator | operator bearer for AgentService on context-engine :8083 |
| L1, break-glass SQL | on-call devops | DB superuser (upsquad) via docker exec on beta-dev, or the CloudSQL operator role |
| L2 | on-call devops | config change per #3148, once it exists |
| L3 | devops + architect review | repo write + deploy; it is a code change |
| drain / restart | on-call devops | docker on the devbox, or kubectl + the model-gateway namespace |
A gap, stated rather than papered over: the rehearsal used the SQL form
because no operator bearer was obtainable in the session — the context-engine
HTTP surface returned 403 to an unauthenticated probe, including /healthz.
The audited RPC is therefore documented but not rehearsed, and the SQL form
skips LifecycleEventGatewayRoutingChanged. Minting an operator token for this
runbook is a named follow-up; until it is done, an L1 executed under incident
pressure will very likely take the unaudited path, and the incident record must
say so.
12. Alerts — the precondition to assert before you trust one
ModelGatewayDown and the gateway-error-ratio rule are not added by this
change, deliberately. #3633's series now exist (§2), so the expressions are
writable — but on beta-dev a committed rule would be green in promtool and fire
nothing, for two independent reasons:
- #3636 — GMP
PodMonitoringscrape plus the sync-wave guard — is in the merge queue as of 2026-09-29. An alert on an unscraped target cannot fire, and #3010 recorded these metrics as unscraped. - #2315 (open):
beta-dev Prometheus loads zero alert rules from a stale bind mount — host
inode != container inode — which is why
DiskFreeLownever fired at 100 % disk.
I chose to assert the precondition rather than sequence silently. Whoever adds the rules must prove they are loaded on the target, not merely committed:
# The rule-loading precondition. ZERO groups means #2315 is still biting and
# every rule in the file is decorative, however green promtool was.
curl -s "$PROM/api/v1/rules" | python3 -c '
import sys,json; g=json.load(sys.stdin).get("data",{}).get("groups",[])
print("groups:",len(g),"rules:",sum(len(x.get("rules",[])) for x in g))
sys.exit(1 if not g else 0)'
# And the scrape precondition: the target must be UP, not merely configured.
curl -s "$PROM/api/v1/targets?state=active" \
| grep -c '"job":"model-gateway"'
A promtool unit test passes against the file. Neither of the two commands
above can be satisfied by a file. That difference is the whole of §12.
Owed, tracked on #3150 alongside L2: the two rules, in both
dev/prometheus/rules/ and deploy/alerts/, with promtool unit tests and a
blinded arm in which an absent series FIRES rather than reading clean — because
per §2 trap 2, absent is not zero. Sequenced behind #3636 landing. This change
deliberately touches neither the Prometheus scrape config nor infra/edge/, both
of which are owned by other open devops PRs.
13. Related
docs/runbooks/mg-baseline.md— why the ledger cannot measure availabilitydocs/runbooks/binauthz-breakglass.md— the audited break-glass procedurescripts/check-model-gateway-exposure.py— the drain arithmetic, asserted in CIscripts/check-model-gateway-rollback.py— §9- #3148 pre-flip checklist · #3633 SLI · #2646 no-bypass ruling
Cooperative publication and installed-source boundary (#4721)
The L4 script now uses one local transaction owner to validate and retain the ordinary environment and, when installed, the fixed beta writer authority. The script's original T0/deadline starts before that work. READY only admits the remaining local procedure; the script must receive PUBLISHED and join the owner at exit 0 before rendering/applying. Optional outgoing-log capture runs without the intent lock. Publication uses exclusive sibling staging, file fsync, read/compare, atomic replacement, parent fsync and readback, never live truncation. All values in progress/error/dry-run diagnostics are redacted.
Installed requests for Compose service context-engine or
upsquad-knowledge-mcp refuse before mutation/apply because installed source
adoption is not supplied by this slice. Other installed service requests use the
canonical ordinary Compose file and existing up -d --no-deps; alternate
Compose/project files and exported Compose/source routing overrides refuse.
Unrelated source-free tenant targets retain their existing options. Any partial
fixed beta installation or source-bearing unmanaged input refuses unlocked
fallback. Neither writer modifies the protected source overlay.
Named exits remain: 2 structural/policy/custody/lock refusal; 3 absent, duplicate or noncanonical selected entry; 4 exported selected-lever override; 5 local staging/publication/durability/readback failure; 6 apply failure; 7 expiration of the original deadline in any phase; 8 running mismatch; 9 rendered mismatch. After an attempted rename, failure retains the actual visible configuration; rc 7 also names its publication phase when durability or outcome is uncertain. Do not automatically replay an uncertain operation. Helper success proves only local publication: script exit 0 still requires rendered/running agreement and readiness. Filesystem deadline checks cannot interrupt a stalled OS call.
Every outer capture, render, apply and inspect result is checked against the original deadline before interpreting its output. Partial inspect output cannot mask a failed command. Readiness uses a positive per-request bound clamped to the remaining whole-operation budget, with an outer timeout and a final deadline check before reporting success. Deadline diagnostics distinguish not-published, publication-attempted/unknown and published local state.