Skip to content
Nelson D’SouzaEmail me
Writing

Fallbacks that fail loudly

Fallbacks should fail loudly. Five, each written for a real failure, made outages look like success. Three questions for code that answers when it can’t know.

By · · 15 min read

  • Reliability
  • Observability
  • Production AI
  • Deployment
In this note
  1. The pattern every codebase has
  2. Five times it hid the outage
  3. Five months of missing cross references
  4. A chat that never remembered a turn
  5. Five hops, any one of which could drop a field
  6. Two errors swallowed by design
  7. And on this site
  8. Why none of them were visible
  9. Repairs, and what they cost
  10. Make the degraded state part of the response
  11. Log it, never pass
  12. Tell "none" from "some"
  13. Test that degradation announces itself
  14. Refuse to run in a state you cannot afford
  15. Delete the fallback that covers nothing
  16. Keep the contract when you fall back
  17. The gate had a fallback too
  18. One status code, two meanings
  19. A third outcome with its own exit code
  20. What three outcomes still can't see
  21. Should this fallback exist?
  22. What none of this finds

For five months, most of Theo Scriptura’s chapter pages had no cross references, and the unit tests passed. An analytics copilot went through two deploys and a round of end-to-end checks with a multi-turn chat that never once remembered a turn. Those two, and three more dead features across the same two products, had one thing in common. A fallback written for a real failure did its job, and the output kept the shape of success.

Every one of those fallbacks was added on purpose, by someone thinking clearly. “A suppression check must not break a send pipeline.” “Forgetting is a much better failure than refusing to answer.” Both sentences are true, and I’d still defend them. The deploy gate I relied on to catch this class had the same flaw. When it couldn’t reach production, it still had to answer something, so it answered “broken”, and the obvious repair would have taught it to answer “fine”.

The pattern every codebase has#

You have a call that might fail: a database query, a driver import, an optional hint from another service. The feature around it should survive that failure. So you write the pattern every codebase has:

try:
    return fetch_the_real_thing()
except Exception:
    logger.exception("could not fetch, using default")
    return DEFAULT

The page renders, the pipeline keeps sending, and the error goes to a log. That’s graceful degradation by the book.

Five times it hid the outage#

Five months of missing cross references#

Theo Scriptura has a page for each of the Bible’s 1,189 chapters. Each page has a “Cross references” section, filled by a query against a table called verse_connections.

That table didn’t exist. No migration had ever created it, so every query against it failed. The code around it looked like this:

const fallback = getStaticChapterCrossReferences(bookName, chapter, limit)
const { data, error } = await supabase.from("verse_connections")...
if (error || !data) return fallback          // no log, no metric

The static fallback held curated entries for 11 chapters. So 11 chapters looked completely right, and the other 1,178 rendered no “Cross references” section at all. From the outside, a missing section reads as “this chapter has none”. An older route that read the same table had returned 500 to every signed-in caller for nine months, and 401 to everyone else, so an unauthenticated probe couldn’t have found it either.

The chapter pages stayed that way for five months. Their unit tests passed the whole time, because they were true:

it("has curated cross-reference fallbacks for Romans 4 study resources", ...)
it("has curated fallbacks for high-value chapter study pages", ...)

They asserted that the hardcoded table had entries for the chapters it had entries for, which was the only code path that ever ran. Nobody had written the test that mattered: does a chapter outside those 11 render anything? It was found during an unrelated site audit, by opening a chapter outside the list.

A chat that never remembered a turn#

Geysera’s analytics copilot answers analytics questions in plain English. It gained multi-turn conversation, backed by LangGraph’s Postgres checkpointer (the component that saves the conversation state between turns). The feature was merged, deployed twice and verified. Every question got a correct answer.

Multi-turn had never worked, not once, in any environment. When I drove three turns through the browser, it went like this:

  • I asked which pages a group of buyers had seen.
  • The assistant asked what time period to analyse.
  • I said the last 90 days.
  • The assistant asked which metric I wanted, with no memory of having asked me anything.
The chat that never rememberedSequence diagram of 10 messages between User, Copilot API, LangGraph, get_checkpointer(), psycopg. Each step is listed as text below.UserCopilot APILangGraphget_checkpointer()psycopg"the last 90 days"run turn on the threadneed a checkpointerimportImportError: no pq wrapperlog, return NoneNonecompile statelessasks for the metric again200, no warning
  1. User to Copilot API: “"the last 90 days"”
  2. Copilot API to LangGraph: “run turn on the thread”
  3. LangGraph to get_checkpointer(): “need a checkpointer”
  4. get_checkpointer() to psycopg: “import”
  5. psycopg replies to get_checkpointer(): “ImportError: no pq wrapper”
  6. get_checkpointer(), internally: “log, return None”
  7. get_checkpointer() replies to LangGraph: “None”
  8. LangGraph, internally: “compile stateless”
  9. LangGraph replies to Copilot API: “asks for the metric again”
  10. Copilot API replies to User: “200, no warning”
Fig. 1 The chat that never remembered The import fails, the fallback returns None, and the graph compiles without memory. The response that reaches the user has the same shape either way.

The cause was packaging. The checkpointer package depends on psycopg, the Postgres driver for Python. Plain psycopg 3 ships no libpq, the C client library it talks to Postgres through. Its pure-Python implementation expects the operating system to provide one, and the container image had none. The binary wheel, psycopg[binary], bundles libpq. Same import name, completely different runtime. The dependency resolver picked the base package, because that is what the checkpointer package asked for.

So every attempt to build the checkpointer raised at import, and this caught it:

except Exception:
    # Forgetting is a much better failure than refusing to answer.
    logger.exception("copilot: checkpointer unavailable, continuing stateless")
    return None

The reasoning in that comment is still correct. The API response looked identical whether memory worked or not, so two deploys and a round of verification all passed.

The way it was found is the more useful part. I first fixed a real bug: the history renderer dropped the assistant’s own clarifying question, so the planner never saw what it had asked. I deployed that, re-ran the same three turns, and got the identical failure. With no checkpointer, the history was empty on every turn, so there was nothing for the better renderer to render.

What found it was to stop reasoning from behaviour and call the component directly, inside the deployed container:

saver = await checkpoint.get_checkpointer()
print("checkpointer:", type(saver).__name__ if saver else "NONE (stateless!)")

There was a second casualty. The copilot’s longer-term memory, a mem0 vector store, used psycopg too. A live test of it had passed, but only because psycopg[binary] had been installed by hand into a container during an earlier spike, so the test ran against a package the deployed image didn’t have.

Five hops, any one of which could drop a field#

The third case is Geysera’s email preview. A “council” of models writes copy variants, each carrying provenance: which style it was written in, its body blocks, a framework. If the provenance arrives, the email renders with a card layout for that style. If it doesn’t, a legacy template renders it instead.

Provenance crossed five boundaries before it reached the renderer: the council’s output over MCP, a CopyVariant, a CopyVariantResult, the RenderPreviewInput that Temporal serialises, and the EmailComposerContext the renderer reads. Temporal’s workflow serialisation turns a dataclass into JSON and back. All four preview cells on the dashboard rendered with the legacy template, and there was no error, because nothing had failed in a way that could raise one.

Provenance across five hopsArchitecture diagram with 8 nodes, 7 connections, 1 group. Each step is listed as text below.Field-dropout test: each fieldremoved, every hopCouncil output (MCP)CopyVariantCopyVariantResultTemporal JSON:RenderPreviewInputEmailComposerContexthas_council_provenance?Per-style rendererLegacy rendererlog: presentlog: droppedyes (log: route)no (log: fallback)
  1. Field-dropout test: each field removed, every hop contains Council output (MCP), CopyVariant, CopyVariantResult, Temporal JSON: RenderPreviewInput, EmailComposerContext.
  2. Council output (MCP) to CopyVariant: “log: present”
  3. CopyVariant to CopyVariantResult: “log: dropped”
  4. CopyVariantResult to Temporal JSON: RenderPreviewInput
  5. Temporal JSON: RenderPreviewInput to EmailComposerContext
  6. EmailComposerContext to has_council_provenance?
  7. has_council_provenance? to Per-style renderer: “yes (log: route)”
  8. has_council_provenance? to Legacy renderer: “no (log: fallback)”
Fig. 2 Provenance across five hops Dropping any field the router needs, at any hop, flips the routing check to false, and the email renders with the legacy template. The fix logs the state at each hop and tests every hop with each field removed in turn.

Three habits made it hard to diagnose. Each hop translated with getattr(v, "body_blocks", None), which looks defensive but turns a misspelt field name into a quiet None. No hop logged the provenance state, so there was no way to bisect which one dropped a field. And the routing check was a boolean that could not tell “this variant has no provenance” from “this variant has some of it”. Both produced the legacy template.

Two errors swallowed by design#

The fourth case has no infrastructure in it at all. A function moved between modules. Its body came across; its module-level import of the database did not. Three of its four callers passed the connection in explicitly and were fine. The fourth called it bare, inside a try whose except Exception returned None, by design, because the value was an optional hint and a database blip must never break the caller.

So it raised NameError on every call, the error was swallowed exactly as intended, and the copilot’s planner had no plan-tier hint for any tenant. The whole suite stayed green. The handler was written for an operational failure and caught a programming error, which is the standing hazard of except Exception around a value treated as optional.

The fifth case had the same shape, in the check that decides whether an address must not be emailed. Its query named a column that does not exist, an except: pass swallowed the error, and the primary suppression signal never once returned true. Every check quietly used the secondary path.

And on this site#

A sixth was caught before it reached production. The ask agent’s spend cap and rate limit fell back to an in-memory store when the shared store’s variables were unset, and the hosting platform’s Redis integration sets differently named ones. In production, both limits would have quietly become per instance. The review that caught it, and the rest of what it found in that agent, is in The server owns an agent’s truth and its money.

Why none of them were visible#

Put the five side by side and three causes recur.

The fallback’s output has the same shape as success. An empty list is a valid list of cross references. A stateless answer is a valid answer. A legacy-rendered email is a valid email. None is a valid “no hint”, and a check that fell through to its secondary signal still returns a valid yes or no. Nothing downstream can tell the difference, because at the type level there is none.

Tests never touch the failing dependency. A mocked checkpointer never imports psycopg. A unit test of the fallback table exercises only the fallback. In both cases the test runs the one branch that works, and passes for exactly as long as the feature stays broken.

The debug environment is not the deployed one. The live memory test passed in a container with a hand-installed wheel.

Underneath all three is the reason for the fallback in the first place. A fallback’s job is to make failure look like something else. When it does that job perfectly and nobody is told, failure and success become the same observation.

Silent and loud degradationFlowchart with 9 nodes, 8 connections. Each step is listed as text below.RequestDependencyOK?Real answerFallback answerSame shape assuccessUser can't tellAnswer + degradedflagwarnings[] and a loglineUser sees thedegraded stateyesnobeforeafter
  1. Request to Dependency OK?
  2. Dependency OK? to Real answer: “yes”
  3. Dependency OK? to Fallback answer: “no”
  4. Fallback answer to Same shape as success: “before”
  5. Same shape as success to User can't tell
  6. Fallback answer to Answer + degraded flag: “after”
  7. Answer + degraded flag to warnings[] and a log line
  8. warnings[] and a log line to User sees the degraded state
Fig. 3 Silent and loud degradation Both paths keep the feature alive. The loud path leaves operator-visible telemetry—and, when user behaviour depends on it, a `warnings[]` signal in the response.

Repairs, and what they cost#

Each repair below makes one of these failures announce itself, and each has a price. The last section is a fallback I would keep.

Make the degraded state part of the response#

The copilot now tells the caller when a requested conversation cannot persist. A one-shot question loses nothing, so it says nothing:

from agents.signal.copilot import checkpoint
 
async def _persistence_warning(thread_id: str | None) -> list[str]:
    if not thread_id:
        return []
    if await checkpoint.get_checkpointer() is None:
        return ["Conversation history is unavailable, so follow-up questions "
                "will not see earlier turns. Ask complete questions until this is fixed."]
    return []

It goes into both the normal and the streaming responses, under warnings. A log line alone isn’t enough, because nobody reads the logs of a feature that appears to work. The cost is a field every client has to render, and a product decision about what the user should be told.

The driver is now declared directly, psycopg = {version = "^3.2", extras = ["binary"]}, with a comment explaining why. The lock file was checked for the wheel itself (psycopg-binary 3.3.4), not only the base package. After the fix, the second turn’s state held two entries of history; before, it always held one.

The warning is the right signal for a database that is down for a while. A missing native library is a different fault. It is true of the image from the moment it is built, and no user can do anything about it. The API’s startup warms the copilot in a fire-and-forget task, on purpose, so a slow warm-up never delays readiness, and that also means a container without libpq starts and serves traffic. An import check at startup that fails the container would turn that fault into a failed deploy instead of a warning on the first conversation. That check doesn’t exist yet.

Log it, never pass#

The suppression check logs a warning now, saying it fell back. The provenance chain has six log sites in one event namespace, council.provenance.*, with states for present, dropped, route and fallback. When a field goes missing, the logs say which hop lost it. The getattr defaults became plain attribute access, so a misspelt field raises AttributeError at once.

Tell “none” from “some”#

This is the most reusable idea in the provenance fix. “All provenance fields are empty” is a legitimate legacy variant. “Some fields present, others empty” is always a bug, because nothing upstream produces half a provenance. The routing code now warns whenever any provenance arrived and the email still went to the legacy template, with the reason: the feature flag is off, or the provenance is incomplete.

The same distinction applies to return values. “We fell back” and “the answer is negative” are different facts. A suppression check that returns False when the query failed is claiming that the address is not suppressed. If those two cases share a value, the caller cannot act correctly on either.

Test that degradation announces itself#

A test of the fallback is not a test of the feature. Two kinds of test replace it. One forces the dependency to fail and asserts that the response says so:

with patch("...checkpoint.get_checkpointer", new=AsyncMock(return_value=None)):
    r = await _post("/signal/copilot/ask", {"question": "revenue?", "thread_id": "chat-1"})
assert any("history is unavailable" in w for w in r.json()["warnings"])

The other asserts on the real return value, and pairs it with a control. For the function that lost its import, one test checks that it returns the tenant’s tier rather than None. A second makes the database raise and checks that it still returns None. Without the second, “make it strict” looks like a fix. Without the first, the feature can stay dead forever.

The handler itself still catches Exception, so those two tests are what guard this function now. Narrowing the except clause to specific transient I/O errors is stronger than keeping broad except Exception, so programmer errors like NameError or AttributeError still crash loudly where someone will see them. As it stands, the next optional hint written with a bare except Exception has the same hazard, whatever its tests cover.

For provenance, a parametrised test pushes a complete council response through all five hops, removes one field at a time, and asserts that losing any of the three fields the router needs flips the routing check.

Refuse to run in a state you cannot afford#

Some fallbacks should not exist in production at all. The ask agent now refuses model calls with a 503 when production has no shared store, rather than run with per-instance limits, and logs the store kind once per process. That costs availability: a misconfigured deploy has no ask agent until someone sets the variables, which is the trade I want for a spending limit.

Delete the fallback that covers nothing#

For Theo, the fix was deletion. The cross references already existed as assets in the native apps: 341,279 links covering all 1,189 chapters. The web had no copy. So the table was created and loaded, the fallback was removed, and an error is now logged while the section hides itself. The test that closed it runs in a browser, on a chapter outside the old 11.

The reason to delete it came from one question: what does this fallback make true when it fires? It was written for one state, the database being unreachable, and in that state the chapter page has no verses to render either: it was insuring a page that was already broken. In practice it only ever fired for a missing table, and its entire observed contribution was to turn a total outage into 11 pages that looked right.

Partial coverage is the dangerous kind. Zero correct chapters would have been obvious. Eleven out of 1,189 survived for five months, because the “high-value” chapters, the ones anyone was likely to check, were the ones that worked.

Keep the contract when you fall back#

The fallback I like best is in a chess tutor. Its opponent is Maia-2, a model trained to play like a human of a given rating. Maia ranks moves badly in the first few half-moves, so for roughly the first ten the opponent plays from an opening book. When the game leaves the book, it falls back to Maia, not to Stockfish. Stockfish, a conventional engine, would be the easy substitute, and that is the problem: it would put a 3000-rated move into a 1200-rated game. An odd opening move is a smaller failure than an opponent that stops being the opponent you chose.

The book is validated when it’s built, because a typo in a move would otherwise look like the book running out early.

The gate had a fallback too#

Theo Scriptura ships with one command, pnpm ship. It builds, deploys, promotes the build, smoke-tests the live site, and moves the domain back to the previous deployment if the smoke fails. The smoke step came down to this:

let smokePassed = true
try { execFileSync("node", ["scripts/ci/smoke-production-local.mjs"]) }
catch { smokePassed = false }
 
if (!smokePassed) { /* roll back */ }

That catch is a fallback, and it has the same flaw as the five above. A probe has to reach the system before it can report anything about it, so it has three possible outcomes. It reached the system and the system behaved; it reached it and the system misbehaved; or it never got a real answer. A boolean has two slots, and the third outcome lands in whichever one the default points at. Here the default pointed at fail.

One afternoon every check came back 429, Too Many Requests, and the script rolled back a deploy that was correct. The tell was in the list. / is a prerendered page, and nothing in the app can return a 429 for it. Vercel’s DDoS mitigation had rate-limited my workstation after three deployments and several smoke runs inside half an hour. The log said “Smoke failed”, so my next move would have been to hunt for a bug that didn’t exist.

One status code, two meanings#

The repair that comes to mind first is to treat 429 as inconclusive. It would have stopped this rollback. Theo’s Ask feature allows two questions per five hours for each IP address. When they’re spent, its streaming endpoint returns 429, and that 429 is the feature working. The smoke suite’s Ask probes call that endpoint from the same IP as every other check, so a broken deploy can hide behind the quota: when the limiter answers first, the 500 underneath never shows. A filter wide enough to drop the noise drops that regression with it, and the gate goes green over a broken build.

The status code can’t settle it. What settles it is which layer produced the response, and that takes evidence only one layer emits. Vercel’s edge marks its own interventions three ways: an x-vercel-mitigated header, an x-vercel-challenge-token header on the interstitial page, and that page’s own <title>. An application response carries none of them, at any status. The check matches the exact <title> element rather than the phrase anywhere in the body, so a page that writes about the firewall can’t read as the firewall.

It was checked against a control. The probe against the live site came back mitigated: a challenge header, a 429 and a retry-after of 30. Against example.com, which sits behind a different provider, it came back with no header and a 200, so the check can also say no.

A third outcome with its own exit code#

When a smoke run has real failures, the runner probes / once and lets that answer classify the whole run. Nothing in the codebase rate-limits /, so an application limiter can’t pass for the edge—though probing / once assumes a global IP-wide challenge rather than per-route or sliding-window WAF rules.

No edge evidence means the failures stand and the deploy rolls back. That’s the only outcome allowed to change production. Edge evidence earns one retry, after the edge’s own retry-after. If the edge is still blocking, the build stays live and the run ends INCONCLUSIVE, with each check listed as unanswered and an exit code of 75. That’s EX_TEMPFAIL in BSD’s sysexits.h, the code for a temporary failure worth retrying, so any caller can tell “unverified” from “broken” without parsing text.

What three outcomes still can’t see#

Three outcomes make the gate honest about what it saw, and that’s all they do. The classifier knows one layer. If the edge probe fails at the network level, that counts as “not mitigated”, so a DNS blip still ends in a rollback; telling a network fault from an app fault needs a second vantage point, and the script has only one. Because one probe classifies the whole run, a real regression that lands during a mitigation gets reported as unanswered. That’s the safe direction, since the remedy for an unanswered check is to re-run it. The example.com control proves only that the check can say no. The sharper control would be my own site on a day it isn’t being mitigated.

The real repair, a firewall rule that lets the smoke suite through on a header only it sends, isn’t made yet. Until it is, an inconclusive run leaves a live build that someone still has to check from a network the edge isn’t blocking. Exit 75 says so, and that’s all it does.

Should this fallback exist?#

A fallback is a second implementation of the feature, and a probe’s default verdict is a second measurement. Both need what the first one needs: a test that can fail, a signal when they run, and a reason to exist in the state where they fire. The cases above reduce that to three questions, in order:

Should this fallback exist?Flowchart with 8 nodes, 8 connections. Each step is listed as text below.When does it fire?Useful in thatstate?Delete itSamecontract?Fix the semantics ordelete itLouder thanwhat itreplaces?Add the flag, the logand the testKeep itnoyesnoyesnoyes
  1. When does it fire? to Useful in that state?
  2. Useful in that state? to Delete it: “no”
  3. Useful in that state? to Same contract?: “yes”
  4. Same contract? to Fix the semantics or delete it: “no”
  5. Same contract? to Louder than what it replaces?: “yes”
  6. Louder than what it replaces? to Add the flag, the log and the test: “no”
  7. Louder than what it replaces? to Keep it: “yes”
  8. Add the flag, the log and the test to Keep it
Fig. 4 Should this fallback exist? Ask in order, of a fallback or a probe's default. A no to either of the first two means fix or delete; one that passes both stays, but only once it is louder than what it replaces.

Theo’s cross references fail the first question. A legacy email template for a variant that half-arrived fails the second: it isn’t the email the council wrote, so the fix was to tell “none” from “some” and warn on “some”. The smoke gate’s catch fails the second too, since “I couldn’t reach production” is a different claim from “production is broken”. Its replacement keeps a separate answer for that state and says it out loud. The stateless copilot passes the first two (a correct one-shot answer is still useful, and it’s still the same copilot) and failed only the third, which is what the warnings field fixed.

What none of this finds#

Every fix here came after someone noticed, and none of them finds the next silent fallback. The warnings field only helps if each client renders it. A warning-level log only helps if something alerts on it. What the fixes buy is that these degraded states now exist somewhere a person or a test will look. Finding the others still means asking, of every except that returns a value and every catch that picks a verdict, what that value claims.

Built in: Theo Scriptura, Geysera

All writing