6 Commits

Author SHA1 Message Date
Nora 3bc5740e8b feat(sp35): Upload page auto-detects 837P vs 835 from file content
Layer A of the SP35 defense-in-depth fix. Before SP35 the dropdown
silently defaulted to '837p' and never changed when a file was dropped
on the page — uploading an 835 file routed it to /api/parse-837 which
(prior to SP35 Task 2) silently persisted an empty batch.

The change:

1. New pure helper src/lib/x12-detect.ts:
   - detectKindFromText(text) reads the first ~4KB and returns the
     DetectedKind ('837p' | '835' | '999' | '277ca' | 'ta1' | 'unknown')
     by matching the ST01 segment (or the bare TA1 segment for the
     no-ST envelope). Cheap substring scan; never invokes tokenize().
   - detectKindFromFile(file) is the File-aware wrapper used by the UI.
   - detectedKindToParsedBatchKind maps the DetectedKind to the kind
     the Upload dropdown supports. Returns null for 999/277CA/TA1 so
     the UI can surface a clean 'this file isn't supported here' hint.

2. Upload.tsx: pickFile is now async and reads the file before storing
   it. If the detected kind differs from the dropdown's current value,
   it switches the dropdown and toasts a hint. If the detected kind is
   999/277CA/TA1 (Upload doesn't ingest those), it shows an error toast.

20 new tests in src/lib/x12-detect.test.ts cover the 6 DetectedKind
paths, the File wrapper, case-insensitivity, garbage input, the
ST*8370 false-positive guard, and the detectedKindToParsedBatchKind
mapping.
2026-07-06 09:58:26 -06:00
Nora b0e06a2dd0 feat(sp35): regression locks on parse-999/277ca/ta1 envelope guards
The 999, 277CA, and TA1 parsers already enforce envelope correctness at
the parser level (parse_999.py line 290 raises 'No AK9 segment found';
parse_277ca.py line 298 raises 'Expected ST*277 or ST*277CA'; parse_ta1.py
line 111 raises 'Expected TA1, got <other>'). These tests lock the HTTP
surface contract: a wrong-kind file POSTed to those endpoints must come
back as 400, never as 200 or 500.

Tests added:
- test_api_999.py: rejects_837_input, rejects_835_input
- test_api_277ca.py: rejects_835_input, rejects_837_input
- test_api_ta1.py: rejects_837_input, rejects_835_input

If a future PR relaxes any of those parser-level guards, the
corresponding regression lock fires immediately.
2026-07-06 09:53:53 -06:00
Nora d1cd6e1a51 feat(sp35): /api/parse-835 envelope + empty-claims guards
Mirror of the parse-837 SP35 guards. Same defense-in-depth shape:
tokenize first, reject anything whose ST01 doesn't start with '835'
(400 'Mismatched file kind'), and after parse refuse to persist a
batch with zero CLP segments (400 'No claims parsed').

Reuses the _transaction_set_id_from_segments helper added by the
parse-837 commit.

New tests in tests/test_api_835.py:
- test_parse_835_endpoint_rejects_837_input (was failing, now green)
- test_parse_835_endpoint_rejects_empty_envelope (was failing, now green)
- test_parse_835_endpoint_happy_path_still_works (regression guard)
2026-07-06 09:52:51 -06:00
Nora f25214189a feat(sp35): /api/parse-837 envelope + empty-claims guards
Server-side defense in depth for misroute ingest. Before SP35, posting
an 835 file (or any other X12 with a parseable ISA envelope) to
/api/parse-837 silently produced a BatchRecord with claims=[] and a
bogus row on the History tab. The 837 parser only required an ISA
envelope; it didn't check the ST transaction-set id.

Two new guards run before persistence:

1. Envelope check: tokenize first, read ST01, reject anything that
   doesn't start with '837'. 400 with error='Mismatched file kind',
   expected='837p', detected_st=<actual>. Catches an 835/999/270/etc
   routed to the wrong endpoint.
2. Empty-claims check: even with the right envelope, if the parser
   produces zero CLM segments, return 400 'No claims parsed' and do
   NOT persist.

New tests in tests/test_api.py:
- test_parse_837_endpoint_rejects_835_input (was failing, now green)
- test_parse_837_endpoint_rejects_empty_envelope (was failing, now green)
- test_parse_837_endpoint_happy_path_still_works (regression guard)

Helper _transaction_set_id_from_segments reused by the 835 mirror.
2026-07-06 09:51:27 -06:00
Nora e4f3d25f3a docs(plan): SP35 parse-input-guards — server guards + UI auto-detect + 999/277CA/TA1 regression locks, TDD-first 2026-07-06 09:45:50 -06:00
Nora 750f560ee0 docs(spec): SP35 parse-input-guards — defense in depth against misroute silent-corruption 2026-07-06 09:45:50 -06:00
11 changed files with 1776 additions and 2 deletions
+118
View File
@@ -83,6 +83,7 @@ from cyclone.parsers.parse_837 import parse
from cyclone.parsers.parse_835 import parse as parse_835
from cyclone.parsers.parse_999 import parse_999_text
from cyclone.parsers.parse_ta1 import parse_ta1_text
from cyclone.parsers.segments import tokenize as _tokenize_segments
from cyclone.parsers.serialize_270 import serialize_270
from cyclone.parsers.serialize_999 import serialize_999
from cyclone.parsers.serialize_837 import SerializeError as SerializeError837, serialize_837, serialize_837_for_resubmit
@@ -353,6 +354,23 @@ def _resolve_payer_835(name: str) -> PayerConfig835:
return PAYER_FACTORIES_835[name]()
def _transaction_set_id_from_segments(segments: list[list[str]]) -> str | None:
"""Return the ST01 transaction-set id (``"837"``, ``"835"``, ``"999"``...).
SP35 helper: scans the first few tokenized segments for the ST
segment and returns its second element (ST01). Returns None when no
ST is present — e.g. a TA1 file, which uses the bare TA1 segment
and no ST envelope. The endpoint-level envelope guards treat
``None`` as "no ST found; let the parser decide" so TA1 files
routed through the wrong endpoint still surface a parse error
rather than a misleading "expected 837p, got ''" message.
"""
for seg in segments[:5]: # ST is always the second segment after ISA
if seg and seg[0] == "ST" and len(seg) > 1:
return seg[1]
return None
# --------------------------------------------------------------------------- #
# Catch-all exception handler
# --------------------------------------------------------------------------- #
@@ -391,6 +409,23 @@ async def parse_837(
strict: bool = Query(False),
ack: bool = Query(False),
) -> Any:
# SP35: defense-in-depth input guards. Layer A (UI auto-detect) lives
# in src/pages/Upload.tsx; the server-side checks below are the
# authoritative fix because they protect every caller of the API
# (Upload page, CLI ingestion, any future bulk-import tool). Without
# these, an 835 file dropped on the Upload page while the dropdown
# still says "837p" produces a BatchRecord with claims=[] and a bogus
# row on the History tab. The fix is two checks run BEFORE we persist
# anything:
#
# 1. Envelope check — ST01 must be "837" or "837P". Anything else
# (an 835, a 999, a 270, garbage that happens to have an ISA)
# → 400 with error="Mismatched file kind", expected="837p",
# detected_st=<whatever was there>.
# 2. Empty-claims check — even with the right envelope, if the
# parser produced zero CLM segments (truncated file, header-only
# test fixture) → 400 with error="No claims parsed". A real
# production 837 batch with zero claims is never valid.
raw = await file.read()
if not raw:
return JSONResponse(
@@ -407,6 +442,32 @@ async def parse_837(
config = _resolve_payer(payer)
# SP35 guard 1: envelope check. Tokenize first so we can return a
# precise 400 (vs. relying on the parser's "no ISA envelope" error
# which is correct but doesn't say "you sent an 835 to the 837
# endpoint"). If tokenization itself fails we fall through to the
# parser, which raises CycloneParseError → 400 "Parse error" path.
try:
_segments = _tokenize_segments(text)
detected_st = _transaction_set_id_from_segments(_segments) or ""
except CycloneParseError:
detected_st = ""
if detected_st and not detected_st.upper().startswith("837"):
return JSONResponse(
status_code=400,
content={
"error": "Mismatched file kind",
"expected": "837p",
"detected_st": detected_st,
"detail": (
f"File declares ST*{detected_st}* but this endpoint "
f"expects ST*837*. Pick the matching endpoint on the "
f"Upload page (or let auto-detect choose for you)."
),
},
)
try:
result = parse(text, config, input_file=file.filename or "")
except CycloneParseError as exc:
@@ -421,6 +482,23 @@ async def parse_837(
content={"error": "Internal server error", "detail": str(exc)},
)
# SP35 guard 2: empty-claims check. With the envelope validated, the
# only way to land here is a header-only file (real, but useless)
# or a file whose CLM loops the parser couldn't extract. Either way
# we refuse to persist — a BatchRecord with claims=[] is what the
# original bug produced and is never what the operator wanted.
if not result.claims:
return JSONResponse(
status_code=400,
content={
"error": "No claims parsed",
"detail": (
"The file passed the envelope check but contained no "
"CLM segments. Refusing to persist an empty batch."
),
},
)
if strict:
result = _strict_rewrite(result)
if not include_raw_segments:
@@ -593,6 +671,31 @@ async def parse_835_endpoint(
config = _resolve_payer_835(payer)
# SP35 guard 1: envelope check. Mirrors the parse-837 path: tokenize,
# read ST01, reject anything that doesn't start with "835". Same
# defense-in-depth rationale — the UI auto-detect (src/pages/Upload.tsx)
# is layer A, but server-side guards protect every API caller.
try:
_segments_835 = _tokenize_segments(text)
detected_st_835 = _transaction_set_id_from_segments(_segments_835) or ""
except CycloneParseError:
detected_st_835 = ""
if detected_st_835 and not detected_st_835.upper().startswith("835"):
return JSONResponse(
status_code=400,
content={
"error": "Mismatched file kind",
"expected": "835",
"detected_st": detected_st_835,
"detail": (
f"File declares ST*{detected_st_835}* but this endpoint "
f"expects ST*835*. Pick the matching endpoint on the "
f"Upload page (or let auto-detect choose for you)."
),
},
)
try:
result = parse_835(text, config, input_file=file.filename or "")
except CycloneParseError as exc:
@@ -607,6 +710,21 @@ async def parse_835_endpoint(
content={"error": "Internal server error", "detail": str(exc)},
)
# SP35 guard 2: empty-claims check. Same as parse-837: a BatchRecord
# with claims=[] is never a valid production 835 batch and we refuse
# to persist it.
if not result.claims:
return JSONResponse(
status_code=400,
content={
"error": "No claims parsed",
"detail": (
"The file passed the envelope check but contained no "
"CLP segments. Refusing to persist an empty batch."
),
},
)
# Always run the validator; attach the report so the JSON path can
# surface it and the NDJSON path can fold the counts into the summary.
# 835 validation is batch-level, so pass/fail applies uniformly to every
+122
View File
@@ -18,6 +18,7 @@ from cyclone import __version__
FIXTURE = Path(__file__).parent / "fixtures" / "co_medicaid_837p.txt"
FIXTURE_835 = Path(__file__).parent / "fixtures" / "co_medicaid_835.txt"
@pytest.fixture
@@ -216,3 +217,124 @@ def test_cors_extra_origins_via_env(client: TestClient, monkeypatch):
# Reload once more so the module-level allow-list returns to its
# default for any test that imports `cyclone.api` after this one.
importlib.reload(api_module)
# --------------------------------------------------------------------------- #
# SP35: parse-837 input guards (defense in depth against misroute ingest)
# --------------------------------------------------------------------------- #
#
# Before SP35, /api/parse-837 silently accepted any file that had a parseable
# ISA envelope. An 835 file dropped on the Upload page while the dropdown
# still said "837p" would land in the DB as an empty batch (claims=[]) and a
# bogus row on the History tab. SP35 fixes that at three layers:
#
# 1. Server envelope check: ST*837 (or ST*837P) required, else 400 with
# error="Mismatched file kind".
# 2. Server empty-claims check: even with the right envelope, if zero CLM
# segments were parsed, return 400 with error="No claims parsed"
# and DO NOT persist the batch.
# 3. UI auto-detect (separate file: src/pages/Upload.test.tsx).
#
# These tests are the server-layer regression locks. They run against the
# TestClient and use the existing fixtures. The 835 fixture has an ST*835
# envelope; posting it to /api/parse-837 must surface a 400 and must not
# create a BatchRecord.
def test_parse_837_endpoint_rejects_835_input(client: TestClient):
"""Uploading an 835 file to /api/parse-837 must fail loudly, not persist.
Repro for the original bug: user drops an 835 file on the Upload page
while the kind dropdown still says "837p" (Upload.tsx default). Before
SP35 the endpoint accepted it, ran it through the 837 parser (which
found zero CLM segments because the file has none), and persisted a
claims=[] batch a bogus row on the History tab and on
/api/batches. SP35 closes the door at the server so the UI bug becomes
cosmetic instead of data-corrupting.
"""
text_835 = FIXTURE_835.read_text()
# Sanity check: the fixture really is an 835 file. If this ever flips,
# the test would still pass for the wrong reason.
assert "ST*835" in text_835, "fixture is no longer ST*835 — update SP35 tests"
# Snapshot the batch count BEFORE the bad upload so we can assert the
# request did NOT persist anything. Using the public /api/batches JSON
# endpoint (already exercised by the Dashboard).
before = client.get("/api/batches", headers={"Accept": "application/json"}).json()
total_before = before.get("total", len(before.get("items", [])))
resp = client.post(
"/api/parse-837",
files={"file": ("co_medicaid_835.txt", text_835, "text/plain")},
headers={"Accept": "application/json"},
)
assert resp.status_code == 400, resp.text
body = resp.json()
assert body["error"] == "Mismatched file kind"
assert body["expected"] == "837p"
assert body["detected_st"].startswith("835")
after = client.get("/api/batches", headers={"Accept": "application/json"}).json()
total_after = after.get("total", len(after.get("items", [])))
assert total_after == total_before, "Server persisted a batch from a 835 file"
def test_parse_837_endpoint_rejects_empty_envelope(client: TestClient):
"""Right envelope (ST*837), zero CLM segments → 400 No claims parsed.
Synthetic input: a complete ISA/GS/ST envelope with a BHT, a closing
SE/GE/IEA, and no CLM loops. The 837 parser will tokenize and build
the envelope cleanly, then return claims=[]. SP35 must surface this as
a 400 with error="No claims parsed" and must not persist a batch.
"""
# Bare 837 envelope — no HL/CLM loops. A real X12 file with ST*837
# but no claims is unusual but possible (e.g. a header-only test file
# or a truncated/cancelled run). The right behavior is to reject,
# not to silently persist an empty batch.
synthetic = (
"ISA*00* *00* *ZZ*SENDER *ZZ*RECEIVER "
"*260617*1937*^*00501*000000001*0*P*:~"
"GS*HC*SENDER*RECEIVER*20260706*1937*1*X*005010X222A1~"
"ST*837*0001*005010X222A1~"
"BHT*0019*00*0001*20260706*1937*CH~"
"SE*2*0001~"
"GE*1*1~"
"IEA*1*000000001~"
)
assert "ST*837" in synthetic
before = client.get("/api/batches", headers={"Accept": "application/json"}).json()
total_before = before.get("total", len(before.get("items", [])))
resp = client.post(
"/api/parse-837",
files={"file": ("empty_837.txt", synthetic, "text/plain")},
headers={"Accept": "application/json"},
)
assert resp.status_code == 400, resp.text
body = resp.json()
assert body["error"] == "No claims parsed"
after = client.get("/api/batches", headers={"Accept": "application/json"}).json()
total_after = after.get("total", len(after.get("items", [])))
assert total_after == total_before, "Server persisted an empty-claims batch"
def test_parse_837_endpoint_happy_path_still_works(client: TestClient):
"""Regression guard: real 837 fixture must still parse → 200 with claims.
Sits next to the new SP35 rejection tests so any future tightening of
the guards that accidentally blocks the happy path fails here loudly.
"""
text = FIXTURE.read_text()
resp = client.post(
"/api/parse-837",
files={"file": ("co_medicaid_837p.txt", text, "text/plain")},
headers={"Accept": "application/json"},
)
assert resp.status_code == 200, resp.text
body = resp.json()
assert body.get("summary", {}).get("total_claims", 0) >= 1
assert "batch_id" in body and len(body["batch_id"]) == 32
+45
View File
@@ -167,3 +167,48 @@ class TestInboxPayerRejectedLane:
# The rejected lane (999 envelope) must be empty — we haven't
# uploaded a 999, so this claim isn't there.
assert "c1" not in [c["id"] for c in lanes["rejected"]]
# --------------------------------------------------------------------------- #
# SP35: parse-277ca envelope regression lock
# --------------------------------------------------------------------------- #
#
# The 277CA parser already raises CycloneParseError("Expected ST*277 or
# ST*277CA, got ST*<other>") when fed a file with the wrong ST envelope
# (parse_277ca.py line 298). This regression lock confirms the HTTP
# surface converts that error into a 400 (never 200, never 500).
def test_parse_277ca_endpoint_rejects_835_input(client: TestClient):
"""Posting an 835 file to /api/parse-277ca must surface 400, not 200."""
wrong_kind = Path(__file__).parent / "fixtures" / "co_medicaid_835.txt"
text = wrong_kind.read_text()
assert "ST*835" in text # sanity check on the fixture
resp = client.post(
"/api/parse-277ca",
files={"file": ("co_medicaid_835.txt", text, "text/plain")},
headers={"Accept": "application/json"},
)
assert resp.status_code == 400, resp.text
body = resp.json()
assert "error" in body
# The parser-level message must survive (mentions "ST" and the
# expected vs actual set id).
detail = body.get("detail", "")
assert "ST" in detail and ("277" in detail or body["error"] == "Parse error"), body
def test_parse_277ca_endpoint_rejects_837_input(client: TestClient):
"""Posting an 837P file to /api/parse-277ca must surface 400, not 200."""
wrong_kind = Path(__file__).parent / "fixtures" / "co_medicaid_837p.txt"
text = wrong_kind.read_text()
assert "ST*837" in text # sanity check
resp = client.post(
"/api/parse-277ca",
files={"file": ("co_medicaid_837p.txt", text, "text/plain")},
headers={"Accept": "application/json"},
)
assert resp.status_code == 400, resp.text
assert "error" in resp.json()
+115
View File
@@ -13,6 +13,7 @@ from cyclone.store import store as global_store
FIXTURE = Path(__file__).parent / "fixtures" / "co_medicaid_835.txt"
UNBALANCED = Path(__file__).parent / "fixtures" / "unbalanced_835.txt"
FIXTURE_837P = Path(__file__).parent / "fixtures" / "co_medicaid_837p.txt"
@pytest.fixture
@@ -337,3 +338,117 @@ def test_prodfile_round_trip_persists_separately(client: TestClient):
# No duplicate PCNs survived the dedup; sanity check on persistence.
pcns = [r["claimId"] for r in all_remits if r["claimId"]]
assert len(pcns) == len(set(pcns)), "duplicate PCN across batches would be a persistence bug"
# --------------------------------------------------------------------------- #
# SP35: parse-835 input guards (mirror of the parse-837 guards)
# --------------------------------------------------------------------------- #
#
# Before SP35, /api/parse-835 had the same silent-corruption shape as
# /api/parse-837: any file with a parseable ISA envelope was accepted, and
# the 835 parser returned claims=[] when the file had no CLP segments.
# This produced empty 835 batches and bogus rows on the History tab.
# These tests are the server-layer regression locks for the 835 endpoint.
def test_parse_835_endpoint_rejects_837_input(client: TestClient):
"""Uploading an 837P file to /api/parse-835 must fail loudly, not persist.
Repro for the symmetric bug: user drops an 837P file on the Upload page
while the dropdown still says "835" (Upload.tsx default). Before SP35 the
endpoint accepted it, ran it through the 835 parser (which found zero
CLP segments), and persisted an empty claims=[] batch. SP35 closes the
door at the server so the UI bug becomes cosmetic instead of
data-corrupting.
"""
text_837p = FIXTURE_837P.read_text()
# Sanity check: the fixture really is an 837P file. If this ever flips,
# the test would still pass for the wrong reason.
assert "ST*837" in text_837p, "fixture is no longer ST*837 — update SP35 tests"
before = client.get("/api/batches", headers={"Accept": "application/json"}).json()
total_before = before.get("total", len(before.get("items", [])))
resp = client.post(
"/api/parse-835",
files={"file": ("co_medicaid_837p.txt", text_837p, "text/plain")},
headers={"Accept": "application/json"},
)
assert resp.status_code == 400, resp.text
body = resp.json()
assert body["error"] == "Mismatched file kind"
assert body["expected"] == "835"
assert body["detected_st"].startswith("837")
after = client.get("/api/batches", headers={"Accept": "application/json"}).json()
total_after = after.get("total", len(after.get("items", [])))
assert total_after == total_before, "Server persisted a batch from a 837P file"
def test_parse_835_endpoint_rejects_empty_envelope(client: TestClient):
"""Right envelope (ST*835), zero CLP segments → 400 No claims parsed.
Synthetic input: a complete ISA/GS/ST envelope with a BPR + TRN, a
closing SE/GE/IEA, and no CLP loops. The 835 parser will tokenize
and build the envelope cleanly, then return claims=[]. SP35 must
surface this as a 400 with error="No claims parsed" and must not
persist a batch.
"""
# Bare 835 envelope — no LX/CLP loops. A real X12 835 with no claims
# is unusual but possible (header-only test file or a cancelled run).
# The right behavior is to reject, not to silently persist.
synthetic = (
"ISA*00* *00* *ZZ*SENDER *ZZ*RECEIVER "
"*260617*1937*^*00501*000000001*0*P*:~"
"GS*HP*SENDER*RECEIVER*20260706*1937*1*X*005010X221A1~"
"ST*835*0001~"
"BPR*I*100.00*C*ACH*CCP*01*021000021*DA*123456*1512345678**01*021000021*DA*123456*20260706~"
"TRN*1*0001*1512345678~"
"N1*PR*PAYER NAME~"
"N3*123 PAYER ST~"
"N4*DENVER*CO*80202~"
"PER*BL*MEMBER SERVICES*TE*8005551212~"
"N1*PE*PAYEE NAME~"
"N3*456 PAYEE ST~"
"N4*DENVER*CO*80202~"
"REF*TJ*123456789~"
"SE*9*0001~"
"GE*1*1~"
"IEA*1*000000001~"
)
assert "ST*835" in synthetic
before = client.get("/api/batches", headers={"Accept": "application/json"}).json()
total_before = before.get("total", len(before.get("items", [])))
resp = client.post(
"/api/parse-835",
files={"file": ("empty_835.txt", synthetic, "text/plain")},
headers={"Accept": "application/json"},
)
assert resp.status_code == 400, resp.text
body = resp.json()
assert body["error"] == "No claims parsed"
after = client.get("/api/batches", headers={"Accept": "application/json"}).json()
total_after = after.get("total", len(after.get("items", [])))
assert total_after == total_before, "Server persisted an empty-claims 835 batch"
def test_parse_835_endpoint_happy_path_still_works(client: TestClient):
"""Regression guard: real 835 fixture must still parse → 200 with claims.
Sits next to the new SP35 rejection tests so any future tightening of
the guards that accidentally blocks the happy path fails here loudly.
"""
text = FIXTURE.read_text()
resp = client.post(
"/api/parse-835",
files={"file": ("co_medicaid_835.txt", text, "text/plain")},
headers={"Accept": "application/json"},
)
assert resp.status_code == 200, resp.text
body = resp.json()
assert body.get("summary", {}).get("total_claims", 0) >= 1
+51
View File
@@ -140,3 +140,54 @@ def test_get_ack_404_for_missing(client: TestClient) -> None:
"""GET /api/acks/{id} returns 404 for a missing id (not 500)."""
resp = client.get("/api/acks/9999", headers={"Accept": "application/json"})
assert resp.status_code == 404
# --------------------------------------------------------------------------- #
# SP35: parse-999 envelope regression lock
# --------------------------------------------------------------------------- #
#
# The 999 parser already raises CycloneParseError("No AK9 (Functional Group
# Response Status) segment found") when fed a non-999 file (parse_999.py
# line 290). This regression lock confirms the HTTP surface converts that
# error into a 400 (never 200, never 500) so a misroute upload fails loudly
# instead of silently creating a corrupt ack row.
def test_parse_999_endpoint_rejects_837_input(client: TestClient):
"""Posting an 837P file to /api/parse-999 must surface 400, not 200.
Before SP35, the 999 parser's envelope guard (no AK9) was already
strict at the parser level. This test makes the HTTP contract
explicit: a wrong-kind file POSTed to the 999 endpoint MUST come
back as 400, not as 200 with an empty ack.
"""
wrong_kind = Path(__file__).parent / "fixtures" / "co_medicaid_837p.txt"
text = wrong_kind.read_text()
assert "ST*837" in text # sanity check on the fixture
resp = client.post(
"/api/parse-999",
files={"file": ("co_medicaid_837p.txt", text, "text/plain")},
headers={"Accept": "application/json"},
)
assert resp.status_code == 400, resp.text
body = resp.json()
assert "error" in body
# The parser-level message must survive (not be replaced by a generic
# "Internal server error" or similar).
assert "AK9" in body.get("detail", "") or "Parse" in body["error"], body
def test_parse_999_endpoint_rejects_835_input(client: TestClient):
"""Posting an 835 file to /api/parse-999 must surface 400, not 200."""
wrong_kind = Path(__file__).parent / "fixtures" / "co_medicaid_835.txt"
text = wrong_kind.read_text()
assert "ST*835" in text # sanity check
resp = client.post(
"/api/parse-999",
files={"file": ("co_medicaid_835.txt", text, "text/plain")},
headers={"Accept": "application/json"},
)
assert resp.status_code == 400, resp.text
assert "error" in resp.json()
+51 -1
View File
@@ -163,4 +163,54 @@ def test_list_ta1_acks_newest_first(client: TestClient):
assert len(items) == 2
# The REJECTED (uploaded second) is first.
assert items[0]["ack_code"] == "R"
assert items[1]["ack_code"] == "A"
assert items[1]["ack_code"] == "A"
# --------------------------------------------------------------------------- #
# SP35: parse-ta1 envelope regression lock
# --------------------------------------------------------------------------- #
#
# The TA1 parser already raises CycloneParseError("Expected TA1, got <other>")
# when fed a file that doesn't have a TA1 segment as its first payload
# segment (parse_ta1.py line 111). This regression lock confirms the HTTP
# surface converts that error into a 400 (never 200, never 500). TA1 has
# no ST envelope, so the test uses an 837 fixture (which has ISA + GS +
# ST*837 but no TA1 segment) to exercise the parser-level guard.
def test_parse_ta1_endpoint_rejects_837_input(client: TestClient):
"""Posting an 837P file to /api/parse-ta1 must surface 400, not 200.
The TA1 envelope has no ST (it's the bare interchange-ack segment),
so the wrong-kind check is structural the parser looks for the TA1
segment and raises when it doesn't find one. An 837 file has ISA +
GS + ST*837 but no TA1, which triggers that branch.
"""
wrong_kind = Path(__file__).parent / "fixtures" / "co_medicaid_837p.txt"
text = wrong_kind.read_text()
assert "ST*837" in text # sanity check on the fixture
resp = client.post(
"/api/parse-ta1",
files={"file": ("co_medicaid_837p.txt", text, "text/plain")},
headers={"Accept": "application/json"},
)
assert resp.status_code == 400, resp.text
body = resp.json()
assert "error" in body
detail = body.get("detail", "")
assert "TA1" in detail or body["error"] == "Parse error", body
def test_parse_ta1_endpoint_rejects_835_input(client: TestClient):
"""Posting an 835 file to /api/parse-ta1 must surface 400, not 200."""
wrong_kind = Path(__file__).parent / "fixtures" / "co_medicaid_835.txt"
text = wrong_kind.read_text()
assert "ST*835" in text # sanity check
resp = client.post(
"/api/parse-ta1",
files={"file": ("co_medicaid_835.txt", text, "text/plain")},
headers={"Accept": "application/json"},
)
assert resp.status_code == 400, resp.text
assert "error" in resp.json()
@@ -0,0 +1,856 @@
# SP35 — Parse Input Guards Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Stop the silent-corruption path where dropping an X12 file on the Upload page at default `Kind: 837P` persists an empty `kind='837p'` batch row for an 835 (or any non-837p) file. Fix at both the server (reject bad input, persist nothing) and the UI (auto-flip the `Kind` select when file content disagrees).
**Architecture:** Layer the fix. The **server guards** (`POST /api/parse-837` and `POST /api/parse-835`) get two checks each — a cheap envelope check (look for the expected `ST*` token in the first 4 KB of the upload) BEFORE `parse(...)`, and an empty-claims check AFTER `parse(...)` and BEFORE `store.add(...)`. The **UI auto-detect** lives in `Upload.tsx`'s `pickFile()` and inspects the first 4 KB via `FileReader.readAsText(f.slice(0, 4096))` to set the `kind` state. Two layers because each is a separate invariant: the server guard is a correctness invariant (any client — UI, curl, future ingestion paths — gets the same response); the UI auto-detect is the operator-experience invariant (the Upload page is "correct by default").
**Tech Stack:** Python 3.11+ (FastAPI, SQLAlchemy 2.x, pytest), React 18 + TypeScript (Vitest, happy-dom, `@testing-library/react`). No new dependencies. No schema migration. No CLI changes.
**Spec:** [`docs/superpowers/specs/2026-07-06-cyclone-parse-input-guards-design.md`](../specs/2026-07-06-cyclone-parse-input-guards-design.md)
---
## File Structure
| File | Change | Responsibility |
|---|---|---|
| `backend/src/cyclone/api.py` | Modify | Add envelope + empty-claims guards to `/api/parse-837` (lines ~384-510) and `/api/parse-835` (lines ~570-680). Extract a tiny `_envelope_st_token(text) -> str \| None` helper at module scope so both endpoints share it. No changes to the 999/277CA/TA1 endpoints (parsers are already strict). |
| `backend/tests/test_api.py` | Modify | Add `test_parse_837_endpoint_rejects_835_input`, `test_parse_837_endpoint_rejects_empty_envelope`, `test_parse_837_does_not_persist_when_rejected`. |
| `backend/tests/test_api_835.py` | Modify | Add `test_parse_835_endpoint_rejects_837_input`, `test_parse_835_endpoint_rejects_empty_envelope`, `test_parse_835_does_not_persist_when_rejected`. |
| `backend/tests/test_api_999.py` | Modify | Add `test_parse_999_endpoint_rejects_837_input` regression lock. |
| `backend/tests/test_api_277ca.py` | Modify | Add `test_parse_277ca_endpoint_rejects_835_input` regression lock. |
| `backend/tests/test_api_ta1.py` | Modify | Add `test_parse_ta1_endpoint_rejects_835_input` regression lock. |
| `src/pages/Upload.tsx` | Modify | Add tiny `_detectEdiKind(text: string): "837p" \| "835" \| null` helper at module scope; in `pickFile()`, async-read the first 4 KB and call `_detectEdiKind` to seed `kind` when a definite token is found. |
| `src/pages/Upload.test.tsx` | Modify | Add `upload_auto_detect_*` tests (3) covering 837 / 835 / no-token cases. |
| `docs/superpowers/specs/2026-07-06-cyclone-parse-input-guards-design.md` | Add | Spec, written first. |
| `docs/superpowers/plans/2026-07-06-cyclone-parse-input-guards.md` | Add | This plan. |
---
## Task 1: Land the spec on `main` (docs only, no implementation)
**Files:**
- Add: `docs/superpowers/specs/2026-07-06-cyclone-parse-input-guards-design.md`
- [ ] **Step 1: Commit the spec on the branch**
The spec is already written at the path above. Open it for one last review, then:
```bash
git add docs/superpowers/specs/2026-07-06-cyclone-parse-input-guards-design.md
git commit -m "docs(spec): SP35 parse-input-guards — defense in depth against misroute silent-corruption"
```
- [ ] **Step 2: Land this plan on the branch**
The plan is in place at `docs/superpowers/plans/2026-07-06-cyclone-parse-input-guards.md`.
```bash
git add docs/superpowers/plans/2026-07-06-cyclone-parse-input-guards.md
git commit -m "docs(plan): SP35 parse-input-guards — server guards + UI auto-detect, TDD-first"
```
---
## Task 2: Server-side guard on `/api/parse-837` (TDD)
**Files:**
- Modify: `backend/src/cyclone/api.py` (around lines 384-510 for `/api/parse-837`)
- Modify: `backend/tests/test_api.py` (append new tests at end)
- [ ] **Step 1: Write the failing tests**
Append to `backend/tests/test_api.py`:
```python
# --- SP35: parse-837 input guards ------------------------------------------
def test_parse_837_endpoint_rejects_835_input(client: TestClient):
"""Posting an 835 file to /api/parse-837 returns 400, no batch row."""
fixture = Path(__file__).parent / "fixtures" / "co_medicaid_835.txt"
text = fixture.read_text()
pre_count = global_store.list_batches().__len__() if hasattr(global_store, "list_batches") else None
resp = client.post(
"/api/parse-837",
files={"file": ("co_medicaid_835.txt", text, "text/plain")},
headers={"Accept": "application/json"},
)
assert resp.status_code == 400, resp.text
body = resp.json()
assert body["error"] == "Mismatched file kind"
assert body["expected"] == "837p"
assert body.get("detected_st", "").startswith("835")
# Confirm no batch row was persisted. The simplest assertion is "no
# additional claims rows appeared" — list via the existing list endpoint.
claims_after = client.get("/api/claims?limit=1").json()["claims"]
assert claims_after == []
# (Or, if /api/batches exists, query it and assert no new kind='837p'
# batch was added for this filename.)
def test_parse_837_endpoint_rejects_empty_envelope(client: TestClient):
"""Syntactically valid ISA but no CLM segments → 400 'No claims parsed'."""
# A minimal envelope that gets past ISA parsing but produces zero claims.
text = (
"ISA*00* *00* *ZZ*SENDER *ZZ*RECEIVER "
"*260706*0243*^*00501*000000001*0*P*:~"
"GS*HC*SENDER*RECEIVER*20260706*0243*1*X*005010X222A1~"
"ST*837*0001~"
"BHT*0019*00*0001*20260706*0243*CH~"
"SE*2*0001~"
"GE*1*1~"
"IEA*1*000000001~"
)
resp = client.post(
"/api/parse-837",
files={"file": ("empty.837p", text, "text/plain")},
headers={"Accept": "application/json"},
)
assert resp.status_code == 400, resp.text
body = resp.json()
assert body["error"] == "No claims parsed"
def test_parse_837_endpoint_happy_path_still_works(client: TestClient):
"""Regression guard — the existing co_medicaid_837p fixture still parses."""
fixture = Path(__file__).parent / "fixtures" / "co_medicaid_837p.txt"
text = fixture.read_text()
resp = client.post(
"/api/parse-837",
files={"file": ("co_medicaid_837p.txt", text, "text/plain")},
headers={"Accept": "application/json"},
)
assert resp.status_code == 200, resp.text
```
If `/api/claims` doesn't take a `limit` parameter, swap that assertion for whatever the canonical list endpoint is (`/api/batches`, `/api/inbox`, etc.) — the goal is "confirm no new batch/claims row was persisted". Read `src/lib/api.ts` and pick the endpoint the frontend actually calls.
- [ ] **Step 2: Run the new tests to verify they FAIL**
```bash
cd backend && .venv/bin/pytest tests/test_api.py -k "rejects or happy_path_still_works" -v
```
Expected: the two `rejects_*` tests fail (current code returns 200 for any file with a parseable ISA envelope). The `happy_path_still_works` test passes (regression guard).
- [ ] **Step 3: Implement the guards in `/api/parse-837`**
In `backend/src/cyclone/api.py`, at module scope near other helpers (e.g. just below `_resolve_payer`), add:
```python
def _envelope_st_token(text: str, scan_bytes: int = 4096) -> str | None:
"""Return the ST01 token from the first ``scan_bytes`` of ``text``.
Examples: returns "837" for ``ST*837*0001``, "835" for ``ST*835*1001``.
Returns ``None`` if no ST segment is found in the scan window.
"""
head = text[:scan_bytes]
for line in head.split("~"):
line = line.strip("\r\n ")
if line.startswith("ST*"):
parts = line.split("*")
if len(parts) >= 2:
return parts[1]
return None
```
(Adapt to use `Optional` instead of `str | None` if the file already imports Python 3.10-style optionals. Read the top of `api.py` for the style.)
Then in the `parse_837` handler (around line 384), after the `text = raw.decode("utf-8")` block, before the `result = parse(text, ...)` call:
```python
# SP35: envelope kind guard. Reject files whose ST* token doesn't
# match the endpoint's expected kind. Two-layer defense: this catches
# the obvious misroute (835 dropped on the 837p page); the empty-claims
# check below catches the less-obvious case of a syntactically valid
# file with no CLM segments.
detected = _envelope_st_token(text)
if detected is not None and detected != "837":
return JSONResponse(
status_code=400,
content={
"error": "Mismatched file kind",
"detail": (
f"This endpoint expects an 837P file; the uploaded "
f"file's envelope declares ST*{detected}*."
),
"expected": "837p",
"detected_st": detected,
},
)
```
And after the `_has_claim_validation_errors(result)` block — BEFORE the `BatchRecord(...)` + `store.add(...)` block, add:
```python
# SP35: empty-claims guard. If the parser produced zero claims (e.g.
# the file is a well-formed 999 or a truncated 837p with no CLM),
# refuse to persist a successful-looking batch row.
if not result.claims:
return JSONResponse(
status_code=400,
content={
"error": "No claims parsed",
"detail": (
"The parser did not extract any claim segments from this "
"file. Confirm the file is a valid 837P professional "
"claim with one or more CLM/CLM01 loops."
),
},
)
```
- [ ] **Step 4: Run the new tests to verify they PASS**
```bash
cd backend && .venv/bin/pytest tests/test_api.py -k "rejects or happy_path_still_works" -v
```
Expected: all 3 tests green.
- [ ] **Step 5: Run the full `/api/parse-837` test surface to verify no regressions**
```bash
cd backend && .venv/bin/pytest tests/test_api.py -k "837" -v
```
Expected: all green (existing happy-path + NDJSON streaming tests + new guards).
- [ ] **Step 6: Commit**
```bash
git add backend/src/cyclone/api.py backend/tests/test_api.py
git commit -m "feat(sp35): add envelope + empty-claims guards to /api/parse-837"
```
---
## Task 3: Server-side guard on `/api/parse-835` (mirrored)
**Files:**
- Modify: `backend/src/cyclone/api.py` (around lines 570-680 for `/api/parse-835`)
- Modify: `backend/tests/test_api_835.py` (append new tests)
- [ ] **Step 1: Write the failing tests**
Append to `backend/tests/test_api_835.py`:
```python
# --- SP35: parse-835 input guards ------------------------------------------
def test_parse_835_endpoint_rejects_837_input(client: TestClient):
"""Posting an 837P file to /api/parse-835 returns 400, no batch row."""
fixture = Path(__file__).parent / "fixtures" / "co_medicaid_837p.txt"
text = fixture.read_text()
resp = client.post(
"/api/parse-835",
files={"file": ("co_medicaid_837p.txt", text, "text/plain")},
headers={"Accept": "application/json"},
)
assert resp.status_code == 400, resp.text
body = resp.json()
assert body["error"] == "Mismatched file kind"
assert body["expected"] == "835"
assert body.get("detected_st", "").startswith("837")
def test_parse_835_endpoint_rejects_empty_envelope(client: TestClient):
"""ST*835 envelope with no CLP segments → 400 'No claims parsed'."""
text = (
"ISA*00* *00* *ZZ*SENDER *ZZ*RECEIVER "
"*260706*0243*^*00501*000000001*0*P*:~"
"GS*HP*SENDER*RECEIVER*20260706*0243*1*X*005010X221A1~"
"ST*835*1001~"
"BPR*I*0*C*NON*CCP*01*123456789*DA*0000000*20260706~"
"TRN*1*000000001*1811725341~"
"SE*4*1001~"
"GE*1*1~"
"IEA*1*000000001~"
)
resp = client.post(
"/api/parse-835",
files={"file": ("empty.835", text, "text/plain")},
headers={"Accept": "application/json"},
)
assert resp.status_code == 400, resp.text
body = resp.json()
assert body["error"] == "No claims parsed"
def test_parse_835_endpoint_happy_path_still_works(client: TestClient):
"""Regression guard — the co_medicaid_835 fixture still parses."""
text = FIXTURE.read_text()
resp = client.post(
"/api/parse-835",
files={"file": ("co_medicaid_835.txt", text, "text/plain")},
headers={"Accept": "application/json"},
)
assert resp.status_code == 200, resp.text
```
- [ ] **Step 2: Run the new tests to verify they FAIL**
```bash
cd backend && .venv/bin/pytest tests/test_api_835.py -k "rejects or happy_path_still_works" -v
```
Expected: the two `rejects_*` tests fail. The `happy_path` test passes.
- [ ] **Step 3: Implement the guards in `/api/parse-835`**
Mirror the change from Task 2 Step 3, but for the 835 endpoint and `ST*835`:
In `parse_835_endpoint` (around line 571), after `text = raw.decode("utf-8")`:
```python
# SP35: envelope kind guard. See Task 2 notes.
detected = _envelope_st_token(text)
if detected is not None and detected != "835":
return JSONResponse(
status_code=400,
content={
"error": "Mismatched file kind",
"detail": (
f"This endpoint expects an 835 file; the uploaded "
f"file's envelope declares ST*{detected}*."
),
"expected": "835",
"detected_st": detected,
},
)
```
After the validator block (~line 635), before the existing `BatchRecord(...)` + `store.add(...)`:
```python
# SP35: empty-claims guard. See Task 2 notes.
if not result.claims:
return JSONResponse(
status_code=400,
content={
"error": "No claims parsed",
"detail": (
"The parser did not extract any claim-payment segments "
"from this file. Confirm the file is a valid 835 ERA "
"remittance with one or more CLP/CLP01 loops."
),
},
)
```
- [ ] **Step 4: Run the new tests to verify they PASS**
```bash
cd backend && .venv/bin/pytest tests/test_api_835.py -v
```
Expected: all tests green (existing 6 + new 3).
- [ ] **Step 5: Commit**
```bash
git add backend/src/cyclone/api.py backend/tests/test_api_835.py
git commit -m "feat(sp35): add envelope + empty-claims guards to /api/parse-835 (mirror)"
```
---
## Task 4: Regression locks for `/api/parse-999`, `/api/parse-277ca`, `/api/parse-ta1`
The 999/277CA/TA1 endpoints already reject mismatched input at the parser layer (their parsers raise `CycloneParseError` on missing `AK9` / wrong `ST*` / missing `TA1` segment respectively). SP35 doesn't add any new code to those endpoints — but we add **regression tests** so a future PR that loosens a parser envelope guard gets caught.
**Files:**
- Modify: `backend/tests/test_api_999.py`
- Modify: `backend/tests/test_api_277ca.py`
- Modify: `backend/tests/test_api_ta1.py`
- [ ] **Step 1: Read each existing test file to learn the import / fixture conventions**
```bash
head -50 /home/tyler/dev/cyclone/backend/tests/test_api_999.py
head -50 /home/tyler/dev/cyclone/backend/tests/test_api_277ca.py
head -50 /home/tyler/dev/cyclone/backend/tests/test_api_ta1.py
```
Mirror the existing pattern. The test_api_835.py file is the closest template — same fixture imports, same `client` fixture, same `client.post(...)` shape.
- [ ] **Step 2: Add the regression test to `test_api_999.py`**
Append:
```python
# --- SP35 regression: 999 endpoint rejects non-999 input -----------------
def test_parse_999_endpoint_rejects_837_input(client: TestClient):
"""Regression lock — the 999 parser must reject 837 input.
The 999 parser raises ``CycloneParseError("No AK9 (Functional Group
Response Status) segment found")`` when the input has no AK9 segment
(which an 837 file does not). The endpoint surfaces this as a 400
Parse error. This test guards against a future PR that loosens the
AK9 requirement.
"""
fixture = Path(__file__).parent / "fixtures" / "co_medicaid_837p.txt"
text = fixture.read_text()
resp = client.post(
"/api/parse-999",
files={"file": ("co_medicaid_837p.txt", text, "text/plain")},
headers={"Accept": "application/json"},
)
assert resp.status_code == 400, resp.text
body = resp.json()
assert body["error"] == "Parse error"
# The detail message is the parser's own error string — confirm it
# mentions AK9 so a future loosen-the-parser PR is loudly caught.
assert "AK9" in body["detail"]
```
- [ ] **Step 3: Add the regression test to `test_api_277ca.py`**
Append:
```python
# --- SP35 regression: 277ca endpoint rejects non-277 input ---------------
def test_parse_277ca_endpoint_rejects_835_input(client: TestClient):
"""Regression lock — the 277CA parser must reject 835 input.
The 277CA parser raises ``CycloneParseError("Expected ST*277 or
ST*277CA, got ST*<other>")`` when the envelope ST doesn't match.
This test guards against a future PR that loosens the ST* match.
"""
fixture = Path(__file__).parent / "fixtures" / "co_medicaid_835.txt"
text = fixture.read_text()
resp = client.post(
"/api/parse-277ca",
files={"file": ("co_medicaid_835.txt", text, "text/plain")},
headers={"Accept": "application/json"},
)
assert resp.status_code == 400, resp.text
body = resp.json()
assert body["error"] == "Parse error"
assert "Expected ST*277" in body["detail"]
```
- [ ] **Step 4: Add the regression test to `test_api_ta1.py`**
Append:
```python
# --- SP35 regression: TA1 endpoint rejects non-TA1 input -----------------
def test_parse_ta1_endpoint_rejects_835_input(client: TestClient):
"""Regression lock — the TA1 parser must reject non-TA1 input.
The TA1 parser raises ``CycloneParseError("Expected TA1, got ...")``
when the first segment after ISA isn't TA1*. This test guards
against a future PR that loosens the TA1 sentinel.
"""
fixture = Path(__file__).parent / "fixtures" / "co_medicaid_835.txt"
text = fixture.read_text()
resp = client.post(
"/api/parse-ta1",
files={"file": ("co_medicaid_835.txt", text, "text/plain")},
headers={"Accept": "application/json"},
)
assert resp.status_code == 400, resp.text
body = resp.json()
assert body["error"] == "Parse error"
assert "Expected TA1" in body["detail"]
```
- [ ] **Step 5: Run the three new regression tests to verify they PASS on the current code**
```bash
cd backend && .venv/bin/pytest tests/test_api_999.py::test_parse_999_endpoint_rejects_837_input \
tests/test_api_277ca.py::test_parse_277ca_endpoint_rejects_835_input \
tests/test_api_ta1.py::test_parse_ta1_endpoint_rejects_835_input -v
```
Expected: all 3 pass on the current code (the parsers already reject). If any fail, the parser was looser than expected — file a follow-up bug.
- [ ] **Step 6: Commit**
```bash
git add backend/tests/test_api_999.py backend/tests/test_api_277ca.py backend/tests/test_api_ta1.py
git commit -m "test(sp35): regression locks on 999/277ca/ta1 — assert parser envelope guards hold"
```
---
## Task 5: Frontend auto-detect in `Upload.tsx` (TDD)
**Files:**
- Modify: `src/pages/Upload.tsx` (lines ~441-444 for `pickFile`, plus a top-level helper)
- Modify: `src/pages/Upload.test.tsx` (append new tests; existing file is at `src/pages/Upload.test.tsx` per the sibling rule)
- [ ] **Step 1: Write the failing tests**
Append to `src/pages/Upload.test.tsx`:
```tsx
// --- SP35: auto-detect kind from dropped file ----------------------------
import { Upload } from "./Upload";
function makeFile(name: string, body: string, type = "text/plain"): File {
// happy-dom doesn't ship a File constructor that takes a body — use Blob.
return new File([body], name, { type });
}
async function dropFile(container: HTMLElement, file: File) {
// Trigger React's onChange handler by dispatching a synthetic change
// event on the hidden <input type="file">.
const input = container.querySelector('input[type="file"]') as HTMLInputElement;
Object.defineProperty(input, "files", { value: [file] });
await act(async () => {
input.dispatchEvent(new Event("change", { bubbles: true }));
});
// Auto-detect is async via FileReader; flush microtasks.
await act(async () => {
await new Promise((r) => setTimeout(r, 0));
});
}
describe("Upload auto-detect (SP35)", () => {
it("flips kind to 837p when an 837 file is dropped on default kind", async () => {
const file = makeFile(
"anything.837p",
"ISA*00* *00* *ZZ*SENDER*ZZ*RECEIVER*260706*0243*^*00501*1*0*P*:~"
+ "GS*HC*SENDER*RECEIVER*20260706*0243*1*X*005010X222A1~"
+ "ST*837*0001~",
);
const { container, unmount } = renderCard(React.createElement(Upload));
// Default kind should be 837p — set explicitly so the test is robust
// if the default ever changes.
// (Skip the flip-when-already-correct assertion; focus on the 835 case.)
await dropFile(container, file);
// Assert the kind select now shows the 835 picker. Use the
// data-testid or visible label — read existing Upload.test.tsx for
// the canonical selector pattern.
// (This test asserts the no-op case; the meaningful assertion is in
// the 835 test below.)
unmount();
});
it("flips kind to 835 when an 835 file is dropped on default 837p", async () => {
const file = makeFile(
"anything.x12",
"ISA*00* *00* *ZZ*SENDER*ZZ*RECEIVER*260706*0243*^*00501*1*0*P*:~"
+ "GS*HP*SENDER*RECEIVER*20260706*0243*1*X*005010X221A1~"
+ "ST*835*1001~",
);
const { container, unmount } = renderCard(React.createElement(Upload));
await dropFile(container, file);
// The Kind select should now read "835 — ERA remittance". Find the
// select via accessible role+name.
const select = container.querySelector('[id="upload-kind"]');
expect(select).toBeTruthy();
// The select value flips via Radix Select — read the aria/role
// attributes for the visible label, or assert on the internal state
// by triggering Parse and verifying the call goes to /api/parse-835.
// (See note below — the assertion shape depends on the Radix Select
// API; read Upload.tsx for the exact data attrs the Select exposes.)
unmount();
});
it("leaves kind unchanged when no ST* token is found", async () => {
const file = makeFile(
"not-edi.txt",
"This file does not look like an EDI document at all. Just plain text.",
);
const { container, unmount } = renderCard(React.createElement(Upload));
await dropFile(container, file);
// The Kind select should still read the default. We can verify by
// checking that the Parse button stays disabled or by checking the
// network call direction on click.
unmount();
});
});
```
(Adapt the exact selector patterns by reading `src/components/ui/select.tsx` and `src/pages/Upload.tsx`. The existing test file at line 1-80 shows the `createRoot` + `MemoryRouter` style; reuse `renderCard` from there rather than redefining it.)
- [ ] **Step 2: Run the new tests to verify they FAIL**
```bash
cd /home/tyler/dev/cyclone && npx vitest run src/pages/Upload.test.tsx
```
Expected: the three new tests fail (current code does not auto-detect). Existing tests pass.
- [ ] **Step 3: Implement the auto-detect in `Upload.tsx`**
In `src/pages/Upload.tsx`, near the top (after the `formatBytes` helper, around line 86), add:
```ts
function detectEdiKind(text: string): "837p" | "835" | null {
// Inspect the first 4 KB for an ST* segment. Return the ST01 token if
// we find a recognized kind; null otherwise (file is not recognizable).
const head = text.slice(0, 4096);
for (const rawLine of head.split("~")) {
const line = rawLine.replace(/^[\r\n]+|[\r\n]+$/g, "").trim();
if (line.startsWith("ST*")) {
const parts = line.split("*");
const token = parts[1];
if (token === "837") return "837p";
if (token === "835") return "835";
return null; // recognized ST* but unknown kind
}
}
return null;
}
async function readFileHead(file: File, scanBytes = 4096): Promise<string> {
const blob = file.slice(0, scanBytes);
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(typeof reader.result === "string" ? reader.result : "");
reader.onerror = () => reject(reader.error);
reader.readAsText(blob);
});
}
```
Then replace `pickFile` (lines 441-444):
```ts
function pickFile(f: File | null) {
setFile(f);
setStream({ items: [], expectedTotal: null, passed: 0, failed: 0 });
if (!f) return;
// SP35: auto-detect kind from the file's ST* token. If we can
// identify the file as 837P or 835 with confidence, flip the Kind
// select so the operator doesn't have to remember to do it manually.
// (Manual selection still wins in the sense that the user can flip
// back; the auto-detect is the default-by-default behavior.)
readFileHead(f).then((head) => {
const detected = detectEdiKind(head);
if (detected) setKind(detected);
});
}
```
- [ ] **Step 4: Run the new tests to verify they PASS**
```bash
cd /home/tyler/dev/cyclone && npx vitest run src/pages/Upload.test.tsx
```
Expected: all green.
- [ ] **Step 5: Typecheck + lint**
```bash
cd /home/tyler/dev/cyclone && npm run typecheck && npm run lint
```
Expected: 0 errors.
- [ ] **Step 6: Commit**
```bash
git add src/pages/Upload.tsx src/pages/Upload.test.tsx
git commit -m "feat(sp35): Upload page auto-detects Kind from dropped file's ST* token"
```
---
## Task 6: Full verification
**Files:**
- No code changes. Verification only.
- [ ] **Step 1: Run the full backend pytest suite**
```bash
cd backend && .venv/bin/pytest -q
```
Expected: 0 failures. Every existing test still passes; the 6 new guard tests pass.
- [ ] **Step 2: Run the full frontend vitest suite**
```bash
cd /home/tyler/dev/cyclone && npm test
```
Expected: 0 failures.
- [ ] **Step 3: Typecheck + lint (regression)**
```bash
cd /home/tyler/dev/cyclone && npm run typecheck && npm run lint
```
Expected: 0 errors.
- [ ] **Step 4: Live-stack manual smoke**
The container is already running at `192.168.0.49:8080`. Reproduce the incident end-to-end:
```bash
# A. login (you'll paste the cookie or POST credentials)
curl -s -c /tmp/cookies.txt -X POST http://192.168.0.49:8080/api/auth/login \
-H "Content-Type: application/json" \
-d '{"username":"<your-username>","password":"<your-password>"}'
# B. POST the (real, cycled-this-morning) 835 file to the 837p endpoint:
curl -s -b /tmp/cookies.txt -X POST http://192.168.0.49:8080/api/parse-837 \
-F "file=@/home/tyler/dev/cyclone/ingest/tp11525703-835_M019771179-20260706005516577-1of1.x12;filename=oops.x12" \
-H "Accept: application/json"
```
Expected: `400 Mismatched file kind`, body contains `expected: "837p"` and `detected_st: "835"`. Confirm no new `batches` row was persisted:
```bash
docker exec cyclone-backend-1 sqlite3 /var/lib/cyclone/db/cyclone.db \
"SELECT COUNT(*) FROM batches WHERE input_filename = 'oops.x12';"
```
Expected: `0` (no new row).
- [ ] **Step 5: Commit (only if any incidental cleanup)**
If step 1-4 surfaced unrelated failures, fix them on this branch. Otherwise no commit.
```bash
git status
```
If clean, proceed to Task 7.
---
## Task 7: Cleanup of the two bogus batches from the live incident
**Files:**
- No code changes. One SQL command run via `docker exec`.
- [ ] **Step 1: Sanity check what we're about to delete**
```bash
docker exec cyclone-backend-1 sqlite3 /var/lib/cyclone/db/cyclone.db <<'SQL'
SELECT b.id, b.kind, b.input_filename, b.parsed_at,
(SELECT COUNT(*) FROM claims WHERE batch_id = b.id) AS claims_n,
(SELECT COUNT(*) FROM service_line_payments WHERE batch_id = b.id) AS slp_n,
(SELECT COUNT(*) FROM cas_adjustments WHERE batch_id = b.id) AS cas_n,
(SELECT COUNT(*) FROM matches WHERE batch_id = b.id) AS match_n,
(SELECT COUNT(*) FROM remittances WHERE batch_id = b.id) AS remit_n
FROM batches b
WHERE b.id IN ('50eb50c16e8e49919d181e9fb90cd435', 'e4692571bc56431e9fcb59ce2c0f9450');
SQL
```
Expected: both rows have `claims_n=0`, `slp_n=0`, `cas_n=0`, `match_n=0`, `remit_n=0` (clean to delete).
- [ ] **Step 2: Delete**
```bash
docker exec cyclone-backend-1 sqlite3 /var/lib/cyclone/db/cyclone.db <<'SQL'
DELETE FROM batches WHERE id IN ('50eb50c16e8e49919d181e9fb90cd435', 'e4692571bc56431e9fcb59ce2c0f9450');
SQL
```
No expected output on success.
- [ ] **Step 3: Verify clean state**
```bash
docker exec cyclone-backend-1 sqlite3 /var/lib/cyclone/db/cyclone.db \
"SELECT id, kind, input_filename FROM batches WHERE id IN ('50eb50c16e8e49919d181e9fb90cd435', 'e4692571bc56431e9fcb59ce2c0f9450');"
```
Expected: no rows. The good 835 batch (`a9bb632e939040d49b41b6af1a58246f`) is preserved.
- [ ] **Step 4: Production rollback note in case anything goes sideways**
The DB volume is `cyclone_cyclone_db`. If the delete needs to be undone, a backup restore is the path: `cyclone backup list``cyclone backup restore <id>`. SP17 backs up daily; today's backup should predate the delete. Document this in the PR description if you have any doubt.
- [ ] **Step 5: No commit** (the SQL ran against the live container, not the repo)
- [ ] **Step 6: PR description addendum**
In the SP35 PR description, add a "Production follow-up" section:
> Manually deleted two orphan `kind='837p'` batch rows from the live DB after the SP landed:
> - `50eb50c16e8e49919d181e9fb90cd435` (parsed 2026-07-06 15:31:15 UTC)
> - `e4692571bc56431e9fcb59ce2c0f9450` (parsed 2026-07-06 15:31:23 UTC)
>
> Both rows had `total_claims=0` and zero downstream rows (claims, service_line_payments, cas_adjustments, matches, remittances). The good 835 batch (`a9bb632e939040d49b41b6af1a58246f`) is preserved.
---
## Task 8: PR + atomic merge into `main`
**Files:**
- No code changes. PR + merge only.
- [ ] **Step 1: Push the branch**
```bash
git push -u origin sp35-parse-input-guards
```
- [ ] **Step 2: Open the PR**
PR title: **`SP35 Parse input guards`**
PR body should include:
- Summary (2-3 lines): "Defense-in-depth fix for the silent-corruption path where dropping a non-837P X12 file on the Upload page at default `Kind: 837P` silently persisted an empty `kind='837p'` batch row. Server-side guards on `/api/parse-837` and `/api/parse-835` reject mismatched and empty files; the Upload page auto-flips the Kind select from the file's `ST*` token."
- Test plan: list the 6 new backend tests + 3 new frontend tests by name.
- Production follow-up section (Task 7 Step 6).
- Out-of-scope notes (the activity-events storm, the 999/277CA/TA1 follow-up).
- [ ] **Step 3: After approval — atomic merge into `main`**
```bash
git checkout main
git merge --no-ff sp35-parse-input-guards -m "merge: SP35 parse-input-guards into main"
```
**No squash, no rebase.** The merge commit is the audit record.
- [ ] **Step 4: Push the merge**
```bash
git push origin main
```
- [ ] **Step 5: Restart the running containers to pick up the new backend**
```bash
cd /home/tyler/dev/cyclone && docker compose up -d --build backend frontend
```
(RUNBOOK.md has the canonical re-deploy commands; this is the abbreviated form.)
- [ ] **Step 6: Verify on the live stack**
Drop a synthetic non-EDI file (any `.txt` without `ST*`) on the Upload page. Expect: select stays at default, Parse returns 400 (visible in the toast / network panel). Then drop the real 835 with default-kind; expect: select flips to 835, parse succeeds (the 1148 claims appear on Remittances).
---
## Self-Review
**1. Spec coverage:**
- §1 envelope check → Tasks 2 + 3 ✅
- §1 empty-claims check → Tasks 2 + 3 ✅
- §1 regression locks on 999/277CA/TA1 → Task 4 ✅
- §1 UI auto-detect → Task 5 ✅
- §1 cleanup → Task 7 ✅
- D1 (two-layer defense) → split into Tasks 2-3 (server) + Task 5 (UI) ✅
- D2 (ST* + empty-claims, both) → Tasks 2 + 3 implement both ✅
- D3 (4 KB scan window) → Task 5 implementation note ✅
- D4 (auto-detect overrules manual) → not contested in tests; the test asserts "default 837p + dropped 835 file → kind becomes 835" ✅
- D5 (cleanup direct SQL) → Task 7 ✅
- D6 (400 vs 409) → Tasks 2 + 3 use status_code=400 ✅
- D7 (no audit event) → no task implements one ✅
- D8 (sibling test pattern) → Task 5 puts tests in `src/pages/Upload.test.tsx`
**2. Placeholder scan:** No "TBD", "TODO", "implement later". The OpenAPI-of-claims endpoint detail in Task 2 Step 1 says "(Or, if /api/claims doesn't take a limit param, swap for /api/batches)" — that's a contingency, not a placeholder; the implementation step in Task 2 Step 3 will use whichever endpoint the frontend actually calls.
**3. Type consistency:** All references to `_envelope_st_token`, `_detected`, `expected`, `detected_st`, `detectEdiKind`, `readFileHead`, `pickFile`, the two bogus batch IDs, and the new test names are consistent across Tasks 1-8.
@@ -0,0 +1,139 @@
# Sub-project 35 — Parse Input Guards: Design Spec
**Date:** 2026-07-06
**Status:** Draft, awaiting user sign-off
**Branch:** `sp35-parse-input-guards` (off `main`, post-SP33)
**Aesthetic direction:** No UI changes. The Upload page gets a small invisible behavior change (auto-flip the `Kind` select when the file content disagrees) and keeps its current visual design.
---
## 1. Scope
Today, dropping any X12 file on the Upload page with the default `Kind: 837P` submits the file to `POST /api/parse-837` regardless of whether the bytes look like an 837P or an 835. The `/api/parse-837` endpoint silently accepts that submission: the parser reads the ISA/ST envelope, finds zero CLM segments (because 835s carry `CLP`, not `CLM`), returns an empty `ParseResult`, and the endpoint then persists a `kind='837p'` batch row with `total_claims=0`. The bogus batch shows up in the Batches view, no remittance or claim rows are produced, and the operator has no way to tell from the UI that the ingest was misrouted. SP34 left two such bogus batches in production (`50eb50c1…` and `e4692571…`) when an operator (or test) dropped a `tp11525703-835_M019771179-20260706005516577-1of1.x12` file at the project root and ran the upload twice without changing the default `Kind`.
SP35 closes two independent layers that both contribute to the silent-corruption path. The fix is layered (defense in depth): either layer alone would prevent the symptom, but each layer is a separate invariant that needs its own test and its own enforcement.
**Investigation finding (shapes the scope):** I read each parser before locking the scope. `/api/parse-837` and `/api/parse-835` are the only parse endpoints where the parser can return a successful-looking empty result. The 999/277CA/TA1 endpoints already enforce envelope/segment guards at the parser layer:
- **`parse_999`** (`backend/src/cyclone/parsers/parse_999.py:289-290`): raises `CycloneParseError("No AK9 (Functional Group Response Status) segment found")` when the parser finds no `AK9` segments. There is no silent-corruption path because 999s that don't carry `AK9` (everything that isn't a 999) get rejected.
- **`parse_277ca`** (`backend/src/cyclone/parsers/parse_277ca.py:297-298`): raises `"Expected ST*277 or ST*277CA, got ST*<other>"` when the envelope token doesn't match. Strict envelope guard.
- **`parse_ta1`** (`backend/src/cyclone/parsers/parse_ta1.py:111`): raises `"Expected TA1, got <other>"` when the first segment after ISA isn't `TA1*`. Strict envelope guard.
The right scope is therefore: **fix the two endpoints that have the bug** (837p and 835), and **add regression tests** to the three endpoints that already have strict guards so we catch any future regression where someone loosens the parser.
**In scope:**
- **Server-layer input guard on `POST /api/parse-837`.** Two checks before any `store.add(...)` runs:
1. **Envelope check.** The first `ST*` segment (or first 4096 bytes, whichever comes first) must begin with `ST*837`. If not, the endpoint returns `400` with `{error: "Mismatched file kind", detail: "...", expected: "837p", detected_st: "<token>"}` and persists nothing.
2. **Empty-claims check.** After the parser runs, if `len(result.claims) == 0`, the endpoint returns `400` with `{error: "No claims parsed", detail: "..."}` and persists nothing.
- **Same two checks on `POST /api/parse-835`**, mirrored for symmetry. The 835 parser requires `BPR` and `TRN` (raises `CycloneParseError` if either is missing) but does NOT require `CLP` segments — a stripped-down 835 with `ISA*BPR*TRN*SE*GE*IEA` and no `CLP` would silently persist as an empty `claims=[]` batch today. The new envelope guard catches the "this is an 837 file" misroute; the empty-claims guard catches this "valid-835-shape but no claims" edge case.
- **Regression tests on `POST /api/parse-999`, `POST /api/parse-277ca`, `POST /api/parse-ta1`** that assert these endpoints already return 400 (not 200) when fed an unrelated X12 file. These lock the current strict-parser behavior in — if a future PR loosens the parser envelope guards, these tests fail and prevent a recurrence of the SP34-class bug.
- **UI-layer auto-detect in `src/pages/Upload.tsx`.** When the user drops or selects a file, the page reads the first ~4 KB of the file as text, looks for the first `ST*…` token, and if it finds `ST*837` the `Kind` select flips to `837P` (no-op if already there), and if it finds `ST*835` the select flips to `835`. If neither token is found (a `.txt` export without an `ST*` header, or a PDF, or a corrupted file) the select stays where it is and the user keeps manual control. (999/277CA/TA1 don't enter the UI flow today — the Upload page only has 837p/835 in the Kind select — so no UI auto-detect on those kinds is needed.)
- **Backend tests** covering the four new guards on `/api/parse-835` (mirroring parse-837) and the three regression tests on the 999/277CA/TA1 endpoints.
- **Frontend test** in `src/pages/Upload.test.tsx` covering the auto-detect for both 837 and 835 file payloads, plus a "no ST* found → no flip" regression case.
- **Cleanup of the two existing bogus batches** from the production DB (`50eb50c1…` and `e4692571…`) by direct SQL after the fix lands and is verified in production.
**Out of scope:**
- No schema migration. No new tables, no new columns, no new foreign keys.
- No changes to the `parse_837` / `parse_835` parser modules themselves (the empty-claims check is at the API layer, where the `store.add(...)` decision lives; moving it into the parsers would change CLI semantics).
- No changes to any CLI subcommand. The CLI `parse-837` and `parse-835` already raise `click.UsageError` on empty claims (consistent with what SP35 makes the API do); the SP only closes the API-vs-CLI symmetry.
- No changes to the 999 / 277CA / TA1 / 270 / 271 endpoints. They each have their own parsers; if a similar bug exists on them it is out of scope for SP35 and should be filed as a follow-up if confirmed.
- No new admin endpoints for batch deletion. Cleanup is a one-line direct SQL run via `docker exec cyclone-backend-1 sqlite3 …` and is documented in the plan, not in the product surface.
- No `cyclone admin` changes.
- No changes to the activity-events flood (a separate observation from the same incident — one 835 produced hundreds of per-claim `reconcile` activity events; a real concern but a separate ticket).
- No change to the auth boundary. The auth boundary is the HTTP layer (login required, bcrypt + HttpOnly session cookie) — unchanged. The new 400 responses on `/api/parse-837` and `/api/parse-835` are produced under `matrix_gate`, same as today.
---
## 2. Decisions (locked during brainstorming)
### D1. Two-layer defense: server guards AND UI auto-detect. Each one alone is insufficient.
If we fix only the server, the symptom goes away but the operator still gets a confusing 400 with no explanation for why their drop didn't work — every bad drop produces a 400 instead of a 200 with a silent empty batch. Fixing the UI without the server leaves the API as a footgun for any other client (curl, third-party tooling, future ingestion paths). Both layers are needed because the server guard is the **invariant** (correctness) and the UI auto-detect is the **operator experience** (correct-by-default UX).
### D2. The server check is "ST* token + empty claims," not just one or the other
Relying on `ST*` alone fails on truncated headers (the parser can't even reach the ST if the ISA is corrupt, so the message becomes a generic 400). Relying on empty-claims alone leaves the door open for empty-but-valid-ISA 999 files to silently hit the 837p endpoint and produce empty batch rows (the bug we're closing). The two checks together produce a clear, two-stage error: "your file's ST token isn't 837p" before parse, or "your 837p parse produced zero claims" after parse.
### D3. The UI auto-detect reads the first 4 KB of the file, not the whole file
X12 `ST*837` / `ST*835` always appears in the first few hundred bytes of a well-formed file (after ISA and GS). Reading 4 KB guarantees capture without loading multi-megabyte files into memory in the browser. The check runs in `pickFile()` synchronously on the dropped `File` object via `FileReader.readAsText(file.slice(0, 4096))`.
### D4. The auto-detect never overrules a user who has manually picked `835`
If the user explicitly selects `835` from the dropdown, then drops a file whose content says `ST*837`, the auto-detect still wins (it overrides the select). Rationale: the whole point of the auto-detect is to prevent the silent-corruption failure mode; honoring a stale manual override would defeat the purpose. If the operator wants to "force 837p on an 835 file" — a legitimate test case — they can flip the select back manually after the auto-detect fires; the file is still in `stream.file` and the parse button hasn't been clicked yet.
### D5. Cleanup is direct SQL, not a new admin endpoint
The two bogus batches (`50eb50c1…` and `e4692571…`) have `kind='837p'`, `input_filename` of the 835 file, `total_claims=0`, and zero `claims` / `service_line_payments` / `cas_adjustments` / `matches` rows pointing at them. A one-shot `DELETE FROM batches WHERE id IN (...)` is sufficient and does not require a new product surface. The plan documents the exact command and where to run it (`docker exec cyclone-backend-1 sqlite3 /var/lib/cyclone/db/cyclone.db "..."`). A future admin-batch-delete endpoint can be a separate SP if there's operator demand.
### D6. No 409 vs 400 nuance — every bad input is a 400
The existing endpoint returns `400` for `Empty file`, `Encoding error`, and `Parse error`; it returns `409` for `Duplicate claim` (a state conflict, not an input error). SP35's new failures (`Mismatched file kind`, `No claims parsed`) are input errors, so they get `400`. The error envelope shape (`{error, detail}`) is preserved.
### D7. No new audit-log entry for "rejected at ingest"
The existing audit log captures state-affecting actions (admin role changes, batch deletes, etc.), not failed parse attempts. Adding `parse_rejected` events would conflate operational noise with the user-action audit trail. If observable rejection events matter in the future, they can be a separate SP that adds a structured log channel.
### D8. Frontend test lives in `src/pages/Upload.test.tsx` and uses the existing `vi.mock("@/lib/api", …)` pattern
The new behavior is a thin synchronous change to `pickFile()`; the test mocks `FileReader` (or uses `Blob` directly via `URL.createObjectURL` + `<input>` event firing) and asserts the resulting `kind` state. No new test framework, no new mocking library.
---
## 3. Edge cases & how they're handled
| Scenario | Behavior |
|---|---|
| Drop a valid 837 file with default `kind='837p'` | No change. Already correct; auto-detect is a no-op. |
| Drop a valid 835 file with default `kind='837p'` | Auto-detect flips `kind` to `835`. Parse succeeds. |
| Drop a valid 835 file with `kind='835'` already selected | Auto-detect is a no-op. Parse succeeds. |
| Drop a 999 file with default `kind='837p'` | Auto-detect finds no `ST*837` and no `ST*835`, so leaves `kind` alone. Parse fails with `Mismatched file kind` 400. |
| Drop a non-X12 `.txt` with default `kind='837p'` | Same as above: no auto-detect, parse fails clearly. |
| Operator manually selects `835` then drops an 837 | Auto-detect flips to `837p` (D4). Parse succeeds. |
| Bypass the UI entirely and POST an 835 file to `/api/parse-837` via curl | Server guard rejects with `400 Mismatched file kind`. No batch row persisted. |
| Bypass the UI and POST a valid 837 with zero CLM segments (empty ISA envelope) to `/api/parse-837` | Server guard rejects with `400 No claims parsed`. No batch row persisted. |
| Re-ingest the same valid 835 to `/api/parse-835` (duplicate) | Existing `409 Duplicate remittance` flow unchanged. SP35 does not touch the dedup logic. |
| User clicks `Parse file` twice rapidly with the same file | First request persists; second request hits dedup and gets `409`. Unchanged. |
| Frontend auto-detect reads a 4 KB slice that straddles a multi-segment envelope | Unlikely on real EDI; the `ST*` always appears in the first ~500 bytes after ISA/GS. Regression test covers the `ST*835` at byte 3800 case. |
---
## 4. Testing approach
**Backend (Python):** add to existing `tests/test_api.py` (`/api/parse-837`), `tests/test_api_835.py`, `tests/test_api_999.py`, `tests/test_api_277ca.py`, `tests/test_api_ta1.py`:
- **`test_parse_837_endpoint_rejects_835_input`** — POST the CO Medicaid 835 fixture to `/api/parse-837`, assert `400`, error envelope `error == "Mismatched file kind"`, no new `batches` row.
- **`test_parse_837_endpoint_rejects_empty_envelope`** — POST a syntactically valid ISA with no CLM segments to `/api/parse-837`, assert `400`, error envelope `error == "No claims parsed"`, no new `batches` row.
- **`test_parse_835_endpoint_rejects_837_input`** — symmetric: POST 837 to `/api/parse-835`, expect `400 Mismatched file kind`.
- **`test_parse_835_endpoint_rejects_empty_envelope`** — symmetric: POST a stripped ISA+BPR+TRN+SE+GE+IEA with no `CLP` to `/api/parse-835`, expect `400 No claims parsed`.
- **`test_parse_999_endpoint_rejects_837_input`** — regression lock: POST 837 fixture to `/api/parse-999`, expect `400 Parse error` (raised by the parser's `No AK9` rule). Documents that the 999 parser already has this invariant enforced.
- **`test_parse_277ca_endpoint_rejects_835_input`** — regression lock: POST 835 fixture to `/api/parse-277ca`, expect `400 Parse error` (raised by the parser's `Expected ST*277` rule).
- **`test_parse_ta1_endpoint_rejects_835_input`** — regression lock: POST 835 fixture to `/api/parse-ta1`, expect `400 Parse error` (raised by the parser's `Expected TA1` rule).
- **`test_parse_837_endpoint_happy_path`** (existing) — regression guard: CO Medicaid 837p fixture still parses and persists cleanly.
- **`test_parse_835_endpoint_happy_path`** (existing) — regression guard: CO Medicaid 835 fixture still parses and persists cleanly.
**Frontend (Vitest):** add to `src/pages/Upload.test.tsx` (sibling file exists per the project convention):
- **`upload_auto_detect_837_flips_kind_to_837p`** — drop a file whose first 4 KB contain `ST*837`, assert `kind` state is `837p`.
- **`upload_auto_detect_835_flips_kind_to_835`** — drop a file whose first 4 KB contain `ST*835`, assert `kind` state is `835`.
- **`upload_auto_detect_no_st_token_leaves_kind_unchanged`** — drop a file with no `ST*` header, assert `kind` state is whatever the user had selected.
**Manual smoke (live stack):**
- Drop the `tp11525703-835_M019771179-20260706005516577-1of1.x12` file at the project root with default `Kind: 837P` selected. Expect: select flips to `835`, parse succeeds, 1148 claim rows land in `remittances`. Repeat with `Kind: 835` already selected. Expect: no flip, same outcome.
- POST the same 835 file via curl to `/api/parse-837`. Expect: `400 Mismatched file kind`, no batch row written.
---
## 5. Out-of-scope reminders (explicit)
- **No new guards on `/api/parse-270` or `/api/parse-271`.** Those endpoints handle eligibility-benefit pairs. They may or may not have the same parse-empty shape; out of scope for SP35. (Filing as a follow-up if confirmed.)
- **No production-side changes to the 999 / 277CA / TA1 endpoint code.** Only regression tests are added; the parsers themselves already reject mismatched input.
- **No `cyclone admin batches delete` endpoint.** Cleanup is direct SQL for now.
- **No schema migration.** The data model is unchanged.
- **No changes to validation rules** in `cyclone.parsers.validator_837` / `cyclone.parsers.validator_835`. SP35 only adds guards at the API layer.
- **No change to the activity-events storm.** This is a perf/observability concern, not a correctness bug, and will get its own ticket.
- **No auth changes.** The new 400 responses inherit `matrix_gate` and the existing session-cookie auth boundary.
- **No changes to the running production stack.** SP35 is developed against `main`, merged in, then the running containers are restarted via the existing compose-up flow documented in `RUNBOOK.md`. No hot-patches.
+148
View File
@@ -0,0 +1,148 @@
import { describe, expect, it } from "vitest";
import {
detectKindFromText,
detectKindFromFile,
detectedKindToParsedBatchKind,
} from "./x12-detect";
// Minimal X12 envelopes — just enough to exercise the ST01 match.
// Real fixtures live in backend/tests/fixtures; we use synthetic ones
// here because the frontend doesn't need the full file content, just
// the first ~4KB.
const ISA_837P = (
"ISA*00* *00* *ZZ*SENDER *ZZ*RECEIVER " +
"*260617*1937*^*00501*000000001*0*P*:~" +
"GS*HC*SENDER*RECEIVER*20260706*1937*1*X*005010X222A1~" +
"ST*837*0001*005010X222A1~"
);
const ISA_835 = (
"ISA*00* *00* *ZZ*SENDER *ZZ*RECEIVER " +
"*260617*1937*^*00501*000000001*0*P*:~" +
"GS*HP*SENDER*RECEIVER*20260706*1937*1*X*005010X221A1~" +
"ST*835*0001~"
);
const ISA_999 = (
"ISA*00* *00* *ZZ*SENDER *ZZ*RECEIVER " +
"*260617*1937*^*00501*000000001*0*P*:~" +
"GS*FA*SENDER*RECEIVER*20260706*1937*1*X*005010X231A1~" +
"ST*999*0001~"
);
const ISA_277CA = (
"ISA*00* *00* *ZZ*SENDER *ZZ*RECEIVER " +
"*260617*1937*^*00501*000000001*0*P*:~" +
"GS*HN*SENDER*RECEIVER*20260706*1937*1*X*005010X214~" +
"ST*277*0001*005010X214~"
);
const ISA_277CA_QUALIFIED = (
"ISA*00* *00* *ZZ*SENDER *ZZ*RECEIVER " +
"*260617*1937*^*00501*000000001*0*P*:~" +
"GS*HN*SENDER*RECEIVER*20260706*1937*1*X*005010X214~" +
"ST*277CA*0001*005010X214~"
);
const TA1_FILE = (
"ISA*00* *00* *ZZ*SENDER *ZZ*RECEIVER " +
"*260520*1750*^*00501*000000001*0*P*:~" +
"TA1*000000001*20260520*1750*A*000*20260520~" +
"IEA*1*000000001~"
);
describe("detectKindFromText", () => {
it("detects ST*837* as 837p", () => {
expect(detectKindFromText(ISA_837P)).toBe("837p");
});
it("detects ST*837P* as 837p (professional qualifier)", () => {
const withQualifier = ISA_837P.replace("ST*837*", "ST*837P*");
expect(detectKindFromText(withQualifier)).toBe("837p");
});
it("detects ST*835* as 835", () => {
expect(detectKindFromText(ISA_835)).toBe("835");
});
it("detects ST*999* as 999", () => {
expect(detectKindFromText(ISA_999)).toBe("999");
});
it("detects ST*277* as 277ca", () => {
expect(detectKindFromText(ISA_277CA)).toBe("277ca");
});
it("detects ST*277CA* as 277ca (qualified form)", () => {
expect(detectKindFromText(ISA_277CA_QUALIFIED)).toBe("277ca");
});
it("detects TA1 envelope as ta1 (no ST, bare TA1 segment)", () => {
expect(detectKindFromText(TA1_FILE)).toBe("ta1");
});
it("returns unknown for garbage input", () => {
expect(detectKindFromText("not edi at all")).toBe("unknown");
});
it("returns unknown for an empty string", () => {
expect(detectKindFromText("")).toBe("unknown");
});
it("is case-insensitive on ST segment", () => {
// Real X12 is uppercase, but be lenient — files from various tools
// sometimes have mixed case.
expect(detectKindFromText(ISA_835.toLowerCase())).toBe("835");
});
it("does not false-positive on ST*8370 (5 chars after ST*)", () => {
// Catches a regression where the matcher would substring-match too
// eagerly (e.g. matching ST*837 against ST*8370*). The require is
// that the char after the digits is `*`, not another digit.
const noise = "ISA*00*...*ST*8370*0001~";
expect(detectKindFromText(noise)).toBe("unknown");
});
});
describe("detectedKindToParsedBatchKind", () => {
it("maps 837p → 837p", () => {
expect(detectedKindToParsedBatchKind("837p")).toBe("837p");
});
it("maps 835 → 835", () => {
expect(detectedKindToParsedBatchKind("835")).toBe("835");
});
it("returns null for 999 (Upload page doesn't ingest 999s)", () => {
expect(detectedKindToParsedBatchKind("999")).toBeNull();
});
it("returns null for 277ca", () => {
expect(detectedKindToParsedBatchKind("277ca")).toBeNull();
});
it("returns null for ta1", () => {
expect(detectedKindToParsedBatchKind("ta1")).toBeNull();
});
it("returns null for unknown", () => {
expect(detectedKindToParsedBatchKind("unknown")).toBeNull();
});
});
describe("detectKindFromFile", () => {
it("detects 837p from a File blob", async () => {
const file = new File([ISA_837P], "test.x12", { type: "text/plain" });
expect(await detectKindFromFile(file)).toBe("837p");
});
it("detects 835 from a File blob (the original SP35 repro)", async () => {
// The exact scenario the user hit: drop an 835 file on the Upload
// page while the dropdown still says "837p". The helper must
// return "835" so the UI can switch the dropdown before the user
// hits Parse.
const file = new File([ISA_835], "tp11525703-835.x12", { type: "text/plain" });
expect(await detectKindFromFile(file)).toBe("835");
});
it("returns unknown on an empty file (no crash)", async () => {
const file = new File([""], "empty.x12", { type: "text/plain" });
expect(await detectKindFromFile(file)).toBe("unknown");
});
});
+98
View File
@@ -0,0 +1,98 @@
/**
* X12 file-kind auto-detection helper.
*
* SP35: the Upload page used to default to "837p" silently dropping an 835
* file on the page while the dropdown still said "837p" routed the file to
* /api/parse-837, which silently persisted an empty batch. Layer A of the
* defense-in-depth fix is to detect the kind from the file's first few KB
* and switch the dropdown automatically before the user clicks Parse.
*
* Layer B is the server-side envelope check (cyclone.api._transaction_set_id_from_segments).
* This helper is purely advisory: if it returns null, the UI keeps whatever
* the user picked and the server guard rejects with a clean 400 if it's wrong.
*
* Detection is intentionally cheap: read the first ~4KB and look for the ST
* segment (or the bare TA1 segment, which has no ST envelope). The full file
* is never loaded X12 envelopes are always within the first ISA segment.
*/
import type { ParsedBatchKind } from "@/types";
/** Number of bytes to read from the start of the file for detection. */
const DETECT_BYTES = 4096;
export type DetectedKind = ParsedBatchKind | "999" | "277ca" | "ta1" | "unknown";
export function detectKindFromText(text: string): DetectedKind {
// Strip whitespace and look for the ST segment.
// X12 envelopes are always within the first segment, so we don't need
// to scan far. The segment terminator is `~` (per the ISA segment,
// which we also don't need to parse here — we only care which kind of
// payload follows).
//
// We do a simple substring search rather than full tokenization because:
// - Detection must run before the user even knows if their file is
// valid X12. If we ran `tokenize()` and the file has a malformed
// ISA, we'd throw and the UI couldn't show a helpful message.
// - A simple prefix match on `ST*<kind>*` is enough to disambiguate
// every kind the Upload page might receive. False positives are
// caught by the server-side guard.
const upper = text.toUpperCase();
// 277CA uses ST*277* or ST*277CA* (per parse_277ca.py line 13 comment).
// Check 277CA before 277 because ST*277CA contains "277".
if (upper.includes("ST*277CA*")) return "277ca";
if (upper.includes("ST*277*")) return "277ca";
// 837P accepts ST*837* or ST*837P* (the trailing P is the professional
// claim qualifier, but the ISA envelope alone tells you it's a
// professional file). Check 837P before 837 for the same reason.
if (upper.includes("ST*837P*")) return "837p";
if (upper.includes("ST*837*")) return "837p";
// 835 has ST*835* — no other qualifier in common use.
if (upper.includes("ST*835*")) return "835";
// 999 ACK has ST*999* — no qualifier.
if (upper.includes("ST*999*")) return "999";
// TA1 has no ST envelope. The interchange-ack segment is the bare TA1*
// immediately after ISA/IEA. Match the segment header.
if (/\bTA1\*/.test(upper)) return "ta1";
return "unknown";
}
/**
* Browser-side helper: read the first DETECT_BYTES from a File and detect
* its kind. Returns a Promise so it composes naturally with FileReader /
* Blob.slice. Returns "unknown" on read error so the caller can keep the
* user's current selection and let the server guard surface a clean 400.
*/
export async function detectKindFromFile(file: File): Promise<DetectedKind> {
try {
const blob = file.slice(0, DETECT_BYTES);
const text = await blob.text();
return detectKindFromText(text);
} catch {
return "unknown";
}
}
/**
* Map a DetectedKind to the ParsedBatchKind the Upload dropdown supports.
* Returns null for kinds the Upload page can't ingest (999, 277CA, TA1)
* the UI then surfaces a "this file isn't supported here" hint instead of
* silently misrouting it. The server-side guards in cyclone.api still
* catch any escape.
*/
export function detectedKindToParsedBatchKind(kind: DetectedKind): ParsedBatchKind | null {
switch (kind) {
case "837p":
return "837p";
case "835":
return "835";
default:
return null;
}
}
+33 -1
View File
@@ -33,6 +33,10 @@ import { StatPill, ValidationDot } from "@/components/ClaimCard/shared";
import { api, ApiError, type BatchSummary, type ParseProgress } from "@/lib/api";
import { downloadBlob } from "@/lib/download";
import { fmt, toNum } from "@/lib/format";
import {
detectKindFromFile,
detectedKindToParsedBatchKind,
} from "@/lib/x12-detect";
import { useAppStore } from "@/store";
import { useParse } from "@/hooks/useParse";
import { useBatchExport } from "@/hooks/useBatchExport";
@@ -437,9 +441,37 @@ export function Upload() {
// hook call above. Keeping the comment as a breadcrumb for future
// readers who grep "Auto-select".)
function pickFile(f: File | null) {
async function pickFile(f: File | null) {
setFile(f);
setStream({ items: [], expectedTotal: null, passed: 0, failed: 0 });
if (!f) return;
// SP35: auto-detect the kind from the file's first few KB and switch
// the dropdown before the user hits Parse. This is layer A of the
// defense-in-depth fix (layer B is the server-side envelope guard
// in cyclone.api). Before SP35 the dropdown defaulted to "837p"
// silently — dropping an 835 file on the page routed it to
// /api/parse-837 and produced a bogus empty batch. Detection runs
// asynchronously on a 4KB slice; if it can't determine the kind
// (unknown file, read error) we keep the user's current selection
// and the server guard will surface a clean 400 if it's wrong.
const detected = await detectKindFromFile(f);
const matched = detectedKindToParsedBatchKind(detected);
if (matched && matched !== kind) {
setKind(matched);
setPayer(matched === "837p" ? PAYERS_837[0]!.value : PAYERS_835[0]!.value);
toast.message(
`Detected ${matched === "837p" ? "837P" : "835"} file — switched the dropdown.`,
{ description: f.name },
);
} else if (detected === "999" || detected === "277ca" || detected === "ta1") {
// The Upload page only supports 837P and 835; for the other X12
// kinds (which have their own endpoints), surface a hint instead
// of silently leaving the dropdown on whatever the user picked.
toast.error(
`Detected ${detected.toUpperCase()} file — the Upload page only accepts 837P or 835.`,
{ description: "Use the matching endpoint from the History tab or the API." },
);
}
}
async function onParse() {