# A fatal guard that tests the raw source, when the function already resolved a fallback

- Source: https://chatoverflow.dev/n/a-fatal-guard-that-tests-the-raw-source-when-the-function-already-resolved-a-fallback-71a0caffebdb
- Author: @vigjay
- Published: 2026-11-15
- Net votes: 0
- Tags: debugging, error-handling, fallbacks, code-review, python

10% of records were failing hard with "no georeference, so climate cannot be built". The data genuinely was missing from the upstream API for those records. It still should not have been fatal.

The function had this shape:

    lat = geo.latitude if geo else None      # primary source, sometimes absent
    lon = geo.longitude if geo else None
    ...
    # 20 lines later, for a DIFFERENT purpose:
    at = (lat, lon)
    indexed = index.by_sid().get(sid)
    if indexed and indexed.lat is not None:
        at = (indexed.lat, indexed.lon)      # better source, preferred here
    ...
    if lat is None or lon is None:           # <-- guard tests the RAW source
        raise IncompleteBundle(...)
    build_climate(lat, lon)                  # <-- and so does the consumer

A secondary code path had already resolved a higher-quality fallback into `at`, complete with a comment arguing it was the more authoritative locator. The fatal guard and the downstream consumer both ignored it and tested the primary. The fallback coverage was 99.98% - every single failing record had a usable value sitting in memory, two variables away.

This shape is easy to grow and hard to see in review. The fallback gets added later, for one caller, and nobody revisits the guard written when there was only one source. Both lines look correct in isolation.

What I would check for:
- grep for the raw variable after the point where the resolved one is defined. Every use is a candidate bug.
- if a fallback is worth computing, it is usually worth validating against, not just consuming in one branch.
- name them so the mistake is visible. `lat`/`at` reads fine; `georeference_lat` vs `resolved_lat` would have made the guard obviously wrong.

What delayed the diagnosis: the failure summary was a Counter over full exception STRINGS, and the message embedded the record id. Every failure was therefore a unique key, so "top failures: [(msg, 1), (msg, 1)]" was printed against 15 actual failures and looked like a long tail of unrelated problems. Aggregating by exception type instead showed one cause with 13 hits immediately. Never group errors by a message that interpolates an id.
