Every API so far has been built by people who wanted you to succeed: documented, versioned, polite. Now meet the other 80% of enterprise integration. A dispatch system from 2003 holds the crew assignments Maria needs, and it speaks three dead languages: a SOAP endpoint whose WSDL vanished with the vendor, nightly fixed-width mainframe extracts, and a "REST API" documented entirely in one retired employee's memory. This is the unglamorous reality FDEs actually deploy into — and the translation layer that keeps it from infecting everything you've built.

Assumes: Stage 3 posts 1–6, especially REST, Deeply (reading contracts) and Auth in the Wild (HMAC). Everything runnable below is stdlib-only, all local — no accounts, no 2003 hardware required.

Monday, 8:05 AM. Maria: "Ops wants crew assignments next to every open complaint. Dispatch has that data — it's in CASEMAN."

You: "CASEMAN. What's the integration story?"

Dev (who has seen this movie before): "2003. Three doors, all hostile. There's a SOAP endpoint — the WSDL's gone, the vendor's gone, but the endpoint still answers. Every night it drops a fixed-width extract on an FTP server. And there's a 'REST API' that Sal wrote in 2016. Sal retired in 2019."

You: "So the documentation is Sal."

Dev: "The documentation is my memory of Sal. Which is: it returns 200 when it fails, and the field names change depending on its mood."

Maria: "Can we just… replace it?"

Dev: "Replacing CASEMAN is a multi-year program. You need crew data next month."

You: "So we build the translation layer now — and replacement stays possible later."

Before you code: clarify the ask

You: "Maria — what do you actually need from CASEMAN? Not the system, the data."

Maria: "For each open complaint: which crew is assigned, and the case status. That's it."

You: "How fresh? Real-time?"

Maria: "The extract is nightly. If crew assignments are a day old, nobody dies. The console just can't show last week's."

You: "Dev — when CASEMAN changes, who tells us?"

Dev: "Nobody. It changed a field name in 2021 and we found out from a council member."

You: "Then the deliverable isn't just the data — it's a tripwire. We need to know the day it changes shape, not the month after."

Input: CASEMAN — a SOAP endpoint, a nightly fixed-width extract, and an undocumented API
Output: crew assignments and case statuses in CityOps' clean shape, plus an alert the day CASEMAN changes
Deadline: before ops planning next month

Notice the two asks hiding in one: the data and the tripwire. Legacy systems don't send changelogs. If you don't build the detection, "it changed in 2021 and we found out from a council member" happens to you too.

The minimal concept

Three hostile formats, one pattern:

The translation layer (adapter): legacy mess in, clean records out. You don't "integrate with" a legacy system — you build a bulkhead. On one side: fixed-width slices, XML namespaces, mood-swing JSON. On the other: the same clean dict shape the rest of CityOps already speaks. Nothing legacy-shaped ever crosses the boundary. The adapter is the only module allowed to know CASEMAN exists.

Document the spec you reverse-engineer. There is no WSDL, no docs, Sal is golfing. So the spec file you write — field positions, namespace URIs, observed behaviors — becomes the documentation. Future-you is the customer of present-you's notes.

Assume it will change without telling you. The tripwire isn't paranoia, it's the 2021 field-name incident as a design requirement: count what you see (record types, field names, value distributions) — and trip on contract changes while baselining the rest.

Build it, part 1: the mainframe extract

The nightly file looks like this — no headers, no commas, no quotes. Position is meaning:

HD20261001CITYOPS NIGHTLY DISPATCH EXTRACT
DT4583807420260930BKDSNYOCRW-01
DT4583807520260930BKDSNYOCRW-01
DT4584100320260930MNDOB CCRW-07
DT4584100420260930BXHPD OCRW-03
DT45841
TR00000004

Each data row is exactly 31 characters: record type (2), complaint id (8), date (8), borough code (2), agency (4), status (1), crew (6). Two contract notes before the code. Encoding: mainframe extracts are defined in bytes, not Python characters — this parser assumes the file was decoded as the documented single-byte encoding (ask the source owner; don't guess), and every width below is a byte width that happens to equal the character width only for that encoding. Dates: eight digits aren't a date — the parser below checks datetime.strptime(date, "%Y%m%d"), because 20261345 passes an isdigit() check and isn't a day that ever happened. The parser is slice math against a spec — the spec is a list, not scattered magic numbers, because the spec is the documentation:

SPEC = [("rtype", 0, 2, str.strip), ("cid", 2, 10, str.strip),
        ("date", 10, 18, str.strip), ("borough", 18, 20, str.strip),
        ("agency", 20, 24, str.strip), ("status", 24, 25, str.strip),
        ("crew", 25, 31, str.strip)]

BOROUGH = {"BK": "BROOKLYN", "MN": "MANHATTAN", "BX": "BRONX",
           "QN": "QUEENS", "SI": "STATEN ISLAND"}
STATUS = {"O": "Open", "C": "Closed"}

def parse_line(line, lineno):
    if len(line) != 31:
        return None, f"line {lineno}: expected 31 chars, got {len(line)}"
    rec = {name: fn(line[a:b]) for name, a, b, fn in SPEC}
    if rec["rtype"] != "DT":
        return None, f"line {lineno}: unknown record type {rec['rtype']!r}"
    if rec["borough"] not in BOROUGH:
        return None, f"line {lineno}: unknown borough {rec['borough']!r}"
    if rec["status"] not in STATUS:
        return None, f"line {lineno}: unknown status {rec['status']!r}"
    if not (rec["date"].isdigit() and len(rec["date"]) == 8):
        return None, f"line {lineno}: bad date {rec['date']!r}"
    rec["borough"] = BOROUGH[rec["borough"]]
    return rec, None

But parse_line is only the inner boundary. The orchestration classifies every line first — header, data, trailer, or unknown — so a line never reaches the parser unless its record type earned it. And the trailer gets reconciled: it claims the file holds 4 data records, so 4 is what we check for:

# Three independent counters. The invariant is:
#   observed == accepted + quarantined   (nothing vanishes silently)
# The trailer is checked SEPARATELY against its documented meaning.
observed = accepted = quarantined = 0
quarantine_reasons = []
for lineno, raw in enumerate(lines, start=1):
    line = raw.rstrip("\n")
    rtype = line[:2]
    if rtype == "HD":
        continue                                # header: file metadata
    if rtype == "TR":
        expected = int(line[2:].strip())        # trailer: the control total
        continue
    observed += 1                               # every DT row counts, valid or not
    if rtype != "DT":
        quarantined += 1
        quarantine_reasons.append(
            f"line {lineno}: unknown record type {rtype!r}")
        continue
    rec, error = parse_line(line, lineno)
    if error:
        quarantined += 1
        quarantine_reasons.append(error)
    else:
        accepted += 1

assert observed == accepted + quarantined, "rows went missing!"
# Trailer semantics come from the source spec, not from wishful thinking.
# CASEMAN's spec: the trailer counts ALL data records written, valid or not.
if expected != observed:
    raise ValueError(
        f"trailer says {expected} data records, file holds {observed} "
        f"({accepted} accepted, {quarantined} quarantined)")

The correction that matters: the first draft compared the trailer against accepted rows only — 4 == 4, "reconciled," while the file actually held 5 data records. That's a false reconciliation: the control total agreed with the survivors, not with the file. The honest accounting is three counters and one invariant (observed == accepted + quarantined), with the trailer checked against observed under its documented meaning. Under CASEMAN's spec the trailer counts all data records written — so a trailer of 4 against 5 observed rows is an inconsistency to investigate, not a success to report. Never let the trailer count only the rows that make the example pass.

The real run — including the row the mainframe corrupted:

observed=5 accepted=4 quarantined=1  (invariant holds: 5 == 4 + 1)
QUARANTINE: line 6: expected 31 chars, got 7
trailer: expected=4 observed=5 -> INCONSISTENT (investigate: did the writer
  count only valid rows, or did a row go missing between write and read?)

Note what changed: the run no longer prints reconciled=True. Five data rows were observed, four accepted, one quarantined — and the trailer's 4 disagrees with the observed 5. Under the documented trailer semantics that's an inconsistency, and the run says so loudly instead of green-lighting a file that doesn't add up. The quarantine reason (line 6, truncated) is preserved with the raw bytes for the diff against tomorrow's file.

Four rows parsed, one quarantined with its line number and the reason. The BK → BROOKLYN mapping is the translation layer doing its first job: downstream never learns that boroughs were once two-letter codes. And the truncated row goes to quarantine, not to the trash — same instinct as the intake pipeline's dead-letter queue. Then the trailer gets its say: the file claims 4 data records, we parsed 4, so the extract reconciles. This is post 3's rule — don't trust a metric you can't reconcile — wearing mainframe clothes: don't trust an extract just because every line parsed. Reconcile its control totals. The lesson is now executable: legacy data fails at the boundary instead of becoming plausible garbage downstream.

One date note before anyone squints: the header says the file was generated 20261001, but the records are dated 20260930. That's the normal shape of a nightly extract — last night's assignments, pulled this morning. The dates in the records are record dates, not file dates.

Build it, part 2: the SOAP endpoint

The endpoint still answers. The envelope it returns is namespaced XML — and namespaces are the entire game:

<?xml version="1.0"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
               xmlns:cs="http://city.gov/caseservice/2003">
  <soap:Body>
    <cs:GetCaseStatusResponse>
      <cs:Case>
        <cs:CaseId>45838074</cs:CaseId>
        <cs:Status>IN PROGRESS</cs:Status>
        <cs:AssignedCrew>CRW-01</cs:AssignedCrew>
        <cs:LastUpdate>2026-03-16T21:34:00</cs:LastUpdate>
      </cs:Case>
    </cs:GetCaseStatusResponse>
  </soap:Body>
</soap:Envelope>

Parse it with stdlib xml.etree.ElementTree. The naive attempt first — because everyone writes it once:

import xml.etree.ElementTree as ET

root = ET.fromstring(SOAP)
naive = root.findall(".//CaseId")
print("naive findall('.//CaseId') ->", [e.text for e in naive])
naive findall('.//CaseId') -> [] (empty: namespaces hide everything)

Empty. Not an error — empty, which is worse, because it looks like "no cases" instead of "your query was wrong." In ElementTree, CaseId without a namespace matches nothing when the document puts every element inside http://city.gov/caseservice/2003. The fix is a namespace map, used on every lookup:

NS = {"soap": "http://schemas.xmlsoap.org/soap/envelope/",
      "cs": "http://city.gov/caseservice/2003"}

def required_text(parent, tag):
    elem = parent.find(f"cs:{tag}", NS)
    if elem is None or elem.text is None:
        raise ValueError(f"SOAP response missing required field: {tag}")
    return elem.text

cases = []
for case in root.findall(".//cs:Case", NS):
    cases.append({tag: required_text(case, tag)
                  for tag in ("CaseId", "Status", "AssignedCrew", "LastUpdate")})
print("namespaced parse ->", cases)
namespaced parse -> [{'CaseId': '45838074', 'Status': 'IN PROGRESS', 'AssignedCrew': 'CRW-01', 'LastUpdate': '2026-03-16T21:34:00'}]

The namespace URIs go in the adapter module as constants, next to a comment with the date you discovered them — because if a successor version changes the namespace URI, the diff will tell the story. A changed URI can mean a changed vocabulary, not just a cosmetic rename, so treat it as a contract event. The envelope's verbosity is irrelevant; what matters is that the same four fields come out the other side in the same clean shape as the fixed-width rows.

One more scenario — the one this whole lesson is about. CASEMAN quietly drops AssignedCrew from the response one day. Without required_text, the parse dies with AttributeError: 'NoneType' object has no attribute 'text' — a mystery. With it, the boundary fails with intent (real run against the drifted envelope):

ValueError: SOAP response missing required field: AssignedCrew

Schema changed → meaningful boundary error, not a mysterious NoneType exception. That's the difference between a tripwire and a landmine.

Build it, part 3: the undocumented API

Sal's API has no docs, so you write the docs by interrogation. The method: probe systematically, record what it does — status, body shape, key names — and turn the observations into a behavior map. Never trust the status code alone; Dev warned you, and he was right:

GET /cases     -> 200, list[2] — but the two rows use DIFFERENT key names
GET /cases/999 -> 200, {"err": "not found", "code": 404}   # the 200 that lies
GET /docs      -> 404, {"error": "no docs here, kid"}
GET /lookup    -> 202, {"ticket": "t-881"}                 # async: come back later
POST /lookup (no key)    -> 200, {}                        # empty 200: missing credential?
POST /lookup (with key)  -> 202, {"ticket": "t-881"}

All real runs against a local stand-in I built with Sal's exact personality. Read the map like a field report: /cases/999 returns 200 with an error body — the status lied, the body told the truth. /lookup without the key returns 200 with an empty body — not an error, just silence. The 202 means "accepted, check back," not "done" — and the adapter has to know how completion is discovered: polling endpoint, ticket status, callback, or whatever mechanism you observe. "Accepted, check back" is only useful if the adapter knows where to check back.

Now the translation. The /cases payload can't decide on a naming convention — row one says caseId, row two says CaseId — so the adapter absorbs it:

def first_present(row, *keys):
    """Return the value of the first key actually present — because a
    present-but-empty value is data, not a missing key."""
    for key in keys:
        if key in row:
            return row[key]
    return None

def get_cases():
    with urllib.request.urlopen(BASE + "/cases", timeout=5) as r:
        print("GET /cases ->", r.status)
        rows = json.load(r)
    out = []
    for row in rows:
        cid = first_present(row, "caseId", "CaseId")
        if cid is None:
            # required meaning is missing: quarantine, don't normalize
            quarantine(row, reason="missing complaint id")
            continue
        out.append({"complaint_id": cid,
                    "status": str(first_present(row, "status", "Status")
                                  or "UNKNOWN").title(),
                    "assigned_crew": first_present(row, "crew", "AssignedCrew"),
                    "source": "legacy-api"})
    return out
GET /cases -> 200
{'complaint_id': '45838074', 'status': 'In Progress', 'assigned_crew': 'CRW-01', 'source': 'legacy-api'}
{'complaint_id': '45838075', 'status': 'Open', 'assigned_crew': 'CRW-01', 'source': 'legacy-api'}

Two details worth naming. First, row.get("caseId") or row.get("CaseId") looks equivalent to first_present, but it treats a present-but-empty value as missing — or can't tell "the key was absent" from "the key held an empty string." first_present checks key presence, because missing key ≠ falsy value. Second, a row with no complaint id under any known name doesn't get normalized with a None — it quarantines. The rule: normalize known variation, quarantine missing required meaning. Being flexible with legacy systems means absorbing their dialects, not exporting their ambiguity.

And the lying 200 gets a boundary check — the REST, Deeply rule ("read the code before the body") with a legacy amendment: then read the body anyway:

with urllib.request.urlopen(BASE + "/cases/999", timeout=5) as r:
    body = json.load(r)
    if isinstance(body, dict) and ("err" in body or "error" in body):
        quarantine(body, reason="200 with error body")
QUARANTINE: /cases/999 returned 200 with error body {'err': 'not found', 'code': 404} — the status lied, the body told the truth

Break it, three ways

1. The off-by-one slice. Someone "cleans up" the spec and shifts the borough slice one character left. No exception, no warning — fixed-width parsing doesn't fail, it just reads the wrong columns:

line: 'DT4583807420260930BKDSNYOCRW-01 '
borough slice [18:20] -> 'BK'  (correct: BK -> BROOKLYN)
borough slice [17:19] -> '6B'  (off by one: '6B' -> UNKNOWN, silently)

'6B' isn't a borough code — in a naive parser it would map to UNKNOWN, and every Brooklyn complaint would quietly become unfilterable. The failure mode of fixed-width isn't a crash, it's plausible garbage. The defense: the spec gets a test with known values, and every parsed field is validated against its known set (borough codes, status codes, date shapes). With the parser above, that '6B' hits unknown borough '6B' and the row quarantines — a loud failure, not a quiet UNKNOWN. This is the same boundary instinct as every validation lesson before it — applied to column positions.

2. The 200 that shipped. Before the boundary check existed, the first version of this adapter trusted the status code — REST, Deeply compliant, Sal non-compliant. /cases/999 returned 200, the adapter stored {'err': 'not found'} as a case, and the console showed a complaint with no id and status "not found" for a week. Nobody noticed because 200 means "fine," and everything downstream believed it. The fix is the two-line check above, plus the rule it encodes: with legacy systems, the status code is a rumor; the body is the witness. Quarantine on suspicion, investigate on the log.

3. The third naming convention. One Tuesday, the API ships CASE_ID — SCREAMING_SNAKE, a third dialect in one payload. The normalizer doesn't recognize it, so there's no complaint id to normalize — and the row quarantines instead of flowing downstream with a None (real run):

QUARANTINE: missing complaint id, row={'CASE_ID': '45838076', 'status': 'OPEN', 'crew': 'CRW-02'}
unseen keys: ['CASE_ID'] -> alert fires: legacy source changed shape

The adapter's real defense isn't the fallback chain — it's the two tripwires working together. Every key the normalizer doesn't recognize gets counted and alerted; every row missing a required field quarantines instead of normalizing. That's the tripwire from the clarify-the-ask conversation: the day CASEMAN changes shape, you know that day. The fallback chain handles the mess; the unseen-key counter detects the next one; the quarantine keeps the ambiguity from crossing the boundary. This is the 2021 field-name incident, converted into a design requirement.

Productionize: the adapter contract

Five habits turn the demos into the thing that survives CASEMAN:

One adapter module per legacy interface — and one normalized output contract. The lesson's first draft let each adapter emit its own shape (cid vs CaseId vs complaint_id; "O" vs "IN PROGRESS" vs "In Progress"). That's not an adapter boundary — that's three dialects in a trench coat. Every adapter normalizes to the same domain record before anything downstream sees it:

# The ONE shape that crosses the adapter boundary. Every adapter emits
# exactly this — validated, or the record is quarantined. Never "close enough".
CREW_STATUS = {"Open": "Open", "In Progress": "In Progress",
               "Closed": "Closed", "Escalated": "Escalated"}

def normalize_assignment(*, complaint_id, raw_status, assigned_crew,
                         source_updated_at, ingested_at):
    status = CREW_STATUS.get(str(raw_status).strip().title())
    if status is None:
        raise ValueError(f"unknown crew status {raw_status!r}")
    if not str(complaint_id).strip():
        raise ValueError("empty complaint_id")
    return {"complaint_id": str(complaint_id),
            "status": status,                    # mapped, not .title()'d blindly
            "assigned_crew": assigned_crew or None,
            "source": "caseman",                 # one source, three doors
            "source_updated_at": source_updated_at,  # from source, or None
            "ingested_at": ingested_at}          # our clock, always set
fixed-width -> {'complaint_id': '45838074', 'status': 'Open', 'assigned_crew': 'CRW-01', ...}
soap        -> {'complaint_id': '45838074', 'status': 'In Progress', 'assigned_crew': 'CRW-01', ...}
rest api    -> {'complaint_id': '45838074', 'status': 'In Progress', 'assigned_crew': 'CRW-01', ...}
# Same keys, same value domains. The console never learns which door it came through.

Status goes through an explicit mapping — .title() alone changes spelling without checking meaning. Timestamps come from the source and ingestion metadata, or None when the source doesn't provide them — never invented. CASEMAN is one source with three interfaces, so caseman_fw.py, caseman_soap.py, caseman_api.py — each one owns its spec, its quirks, and its tripwires, behind one stable façade: from adapters import crew_assignments(). The rest of CityOps never learns CASEMAN exists. When the mainframe finally dies, you delete a module, not untangle a codebase.

Archive evidence, not raw PII — resolved with Lisa first. The first draft said "archive every extract file, every SOAP response, every payload, verbatim." That conflicts with the regional architecture lesson's rule — PII redacted before it rests anywhere — and "restricted access plus retention" doesn't resolve it on its own. The corrected policy, agreed with the data owner and Lisa before anything is stored: archive the sanitized payload (post-redaction bytes) with the quarantine reason and the source metadata needed for replay and diffing. Raw-payload archiving happens only under a documented exception with explicit controls — and the exception names what PII it covers, who can access it, and when it expires. Alerts carry a pointer to the quarantined input, never the payload itself. (Same reason the intake pipeline keeps its dead-letter queue: evidence first — but evidence with a lock on the door, and the lock's rules in writing.)

Write the spec you reverse-engineered. A markdown file next to each adapter: field positions, namespace URIs, observed behaviors, the probe results, Sal's quirks as you discover them. Date every discovery. This file is the documentation the vendor never shipped — and the onboarding doc for the next FDE.

Tripwires, not just parsing — and two kinds of them. Schema and contract changes are binary: an unknown record type, an unseen field name, a missing required field → immediate alert and quarantine. Data-distribution changes are not: record counts move nightly, borough mixes shift seasonally, volumes breathe. Those get threshold and anomaly monitoring against a baseline, not a pager. Schema drift can be binary; data drift needs a baseline. Page on every count movement and people learn to ignore the tripwire — which is exactly how the 2021 incident stays possible.

Don't make your integration depend on the legacy system changing. Meet its current contract at the boundary — you don't file a ticket against a 2003 dispatch system expecting JSON by Friday. But an FDE absolutely collaborates with the owning team when improving the upstream is feasible and valuable; the adapter just means you're never blocked on it. If the owning team later improves the source, your adapter gives you one place to absorb that change. The day your delivery depends on the legacy system changing for you is the day you've built on sand. This is also why the exception rule matters here more than anywhere: catch only to add context (which source, which line, which field) or to quarantine — never to silently coerce garbage into shape.

The principle underneath all five habits: be liberal in observation, strict at your boundary. CASEMAN can produce caseId, CaseId, SOAP namespaces, fixed-width codes, and lying 200s — your adapter may understand all of them. But CityOps gets exactly {complaint_id, status, assigned_crew, source}, or it gets nothing plus a quarantine record. Accept known legacy variation. Never export legacy ambiguity.

Explain it to the customer

"Maria — the adapter prototype works against fixtures: all three CASEMAN doors (nightly extract, SOAP, undocumented API) now produce one normalized crew-assignment record, and the tripwires fire on contract drift. What's not done yet: the production join into the console, the scheduled nightly load, and freshness monitoring — those are the next deliverables, and until they land, 'refreshed nightly' is the plan, not the reality. On freshness honesty: 'a day old at most' is the design target; the real freshness metric will be extract time vs. load time per source, tracked once the scheduler runs. And Dev — the part you'll like: if the extract changes shape, if the SOAP envelope renames a field, if Sal's API invents a fourth naming convention, we get an alert that day with a pointer to the quarantined input and the exact contract check that failed — not a council member telling us next month. The legacy mess lives in three adapter modules and nowhere else."

The pattern, as always: what she gets, the freshness caveat stated up front, then the thing Dev actually wanted — proof that the next silent change won't be silent.

Must know

  • The translation layer (adapter): legacy mess in, clean records out — one adapter module per legacy interface, nothing legacy-shaped crosses the boundary
  • Fixed-width: the spec is a list of (name, start, end); validate every field against its known set — plausible garbage is the failure mode
  • SOAP: namespaces hide everything from naive queries — a namespace map on every lookup, URIs as documented constants; required fields fail with intent (ValueError), not a mysterious AttributeError
  • Undocumented APIs: probe systematically, record behavior not promises — when observed behavior contradicts HTTP semantics, validate both status and body instead of trusting either alone
  • Tripwires: schema/contract changes alert immediately (unknown types, unseen keys, missing required fields); data-distribution changes get threshold monitoring — schema drift can be binary, data drift needs a baseline
  • Archive raw inputs under the source's security and retention policy — restricted access, alerts link to the archive; write the spec you reverse-engineered

Useful later

  • EBCDIC and code pages — when the mainframe's bytes aren't even ASCII
  • WS-Security and SAML tokens — when the SOAP endpoint wants enterprise auth, not just XML
  • Change-data-capture off legacy DBs — when nightly extracts get too slow and you need the transaction log
  • Formal schema registries — when the team outgrows hand-written spec files

Don't memorize this

  • Slice positions — remember the spec is a list, validated against known values; the positions live in the adapter
  • Namespace URIs — remember namespaces hide everything; the URIs live in the adapter as constants
  • Sal's quirks — remember probe, record, tripwire; the quirks live in the spec file you wrote

Where this lands in CityOps

The adapters feed the intake pipeline a new source: crew assignments join the 311 records, and the console's detail view gains its "assigned crew" line. The quarantine path they share is the same one Milestone 2 built — short lines, lying 200s, and renamed fields all land in the same dead-letter discipline, with raw evidence attached. And the tripwire habit generalizes: every external source CityOps ever touches gets the same treatment — count what you see, alert when it moves.

In Milestone 3 the CityOps API grows, and these adapters sit behind it like everything else: the API serves clean records, and no consumer ever learns that one of its sources is a mainframe. That's the whole lesson, one layer up: the translation layer doesn't just protect your code from the legacy system — it protects your customers from ever knowing it exists.

The signature line for this one: meet the legacy system where it is — and keep its mess behind the boundary. FastAPI taught you that an API is a contract you sign with strangers — this is the lesson for when the stranger won't sign, won't document, and retired in 2019.

Field check

  1. The extract gains a new record type DX your spec doesn't list. Walk through what happens in the parser — and what should happen.
  2. A SOAP response parses to an empty list with no error. Name the most likely cause and the one-line diagnostic.
  3. Sal's API returns 200 with {"err": "not found"}. Your adapter stored it as a case. What was the design mistake — and what's the fix?
  4. The API starts sending CASE_ID alongside caseId. Your adapter handles the value fine. What still needs to fire, and why?
  5. Maria asks: "Why not just rewrite CASEMAN?" Give her the two-sentence answer an FDE gives.
What good answers look like

1. The orchestration classifies record types before parsing: HD → header, TR → trailer, DT → data, anything else → quarantine. A DX row hits the unknown branch — it's quarantined with the raw line and its line number, and the unseen-record-type counter fires the alert. Even if it somehow reached parse_line, the rtype != "DT" check would reject it. A human then decides: new spec entry or corruption. Parsing unknown types silently is how plausible garbage gets in — so classify first, parse only what you recognize, alert on the rest. 2. Namespaces — the naive findall(".//CaseId") matches nothing when elements live in a namespace, and ElementTree returns an empty list instead of an error. Diagnostic: print the root tag (root.tag shows the {namespace}tag form) and check whether your queries carry the namespace map. 3. The mistake was trusting the status code as the verdict — the adapter treated 200 as "fine" and stored the error body as data. The fix is the boundary check: inspect the body for error shapes (err/error keys) regardless of status, and quarantine on suspicion. With legacy systems whose observed behavior contradicts HTTP semantics, the status code is a rumor; the body is the witness. 4. The unseen-key alert must still fire. The value being handled is luck (the fallback chain); the new key is evidence the source changed shape, and the next change might not be handled. The tripwire exists to detect change, not just to survive it — alert, document the new key in the spec file, add it to the normalizer deliberately. 5. "Replacing CASEMAN may eventually be the right program, but Maria needs crew data next month and replacement is a separate migration with its own risk, owners and timeline. We can isolate today's dependency behind an adapter now, while keeping replacement possible later."