Skip to content

API verification: declared empty search shape, and the 50-plant rerun on Medplum and Gitea - #2525

Merged
abrichr merged 8 commits into
mainfrom
claude/api-scoped-rerun-2026-11-22
Nov 22, 2026
Merged

abrichr merged 8 commits into
mainfrom
claude/api-scoped-rerun-2026-11-22

Conversation

@abrichr

@abrichr abrichr commented Nov 22, 2026

Copy link
Copy Markdown
Member

Reruns resource-scoped API verification (#2437) on Medplum 5.2.8 and Gitea 1.24.6. Each system gets 400 clean writes and 50 plants per fault class, with synthetic data on loopback containers. It also fixes a fail-closed break the rerun found on main.

The fix

Since #2437, a marker search whose answer lacks its items field is an error, not an empty result. That rule is a fail-open fix, and it stays. But Medplum answers an empty search with a Bundle that leaves entry out, so on main every Medplum create now fails its pre-send marker search.

  • New optional pack setting search_empty (ScopedCollection) declares what an empty answer looks like. Medplum's pack sets {path: resourceType, equals: Bundle}. Any other answer missing its items field is still an error, including an OperationOutcome.
  • Tests are in test_txplan_scoped.py, and the setting is documented in API_VERIFICATION.md.
  • The Medplum lab's compose file raises the per-user FHIR quota and rate limit for this loopback lab only. Audit-log reads spent the 50,000-units-a-minute default within seconds, and a 429 stopped the bench.

Results (22 November 2026)

Medplum Gitea
Clean writes stopped 0 of 400 0 of 400
Log-exposed faults stopped (wrong value create/update, duplicate, partial write, same-actor collateral) 50 of 50 per class 50 of 50 per class (100 of 100 collateral)
Missed: title edit the feed doesn't record not applicable 0 of 50
Missed: another caller's change 0 of 50 0 of 50
Same-payload retries replayed / regenerated refused 50 / 50 50 / 50
Kill criterion not met not met

The two missed classes are known misses outside the check's scope, which is the resource and the credentials it holds. Every planted fault landed, and the server accepted every side write.

Stripe was not run: no Stripe test-mode key is available, and live keys are never used.

RESULTS.md, CAPABILITIES.md and llms-full.txt are updated. The raw rows are in benchmark/api_scoped/results/. Ran headless on a local Docker host.

…plants per class

- missing-evidence class, kept: a marker search without its items field is
  still an error, unless it reports total 0 or matches the pack's new
  search_empty shape. Medplum's empty search Bundle leaves entry out, which
  made #2437's rule fail closed on every create; its pack now declares
  search_empty: {path: resourceType, equals: Bundle}.
- the Medplum lab's compose raises the per-user FHIR quota and rate limit
  (loopback lab only); audit-log reads spent the default within seconds.
- rerun on Medplum 5.2.8 and Gitea 1.24.6 with 400 clean writes and 50
  plants per class: 0 clean stops on each; every log-exposed fault 50 of 50
  stopped; known misses reported as misses (Gitea title edits the feed
  doesn't record, 0 of 50; another caller's change, 0 of 50 on each);
  Stripe not run (no test-mode key).
search_empty counts only when the answer reports no total or total 0; a
Bundle that says it matched something but carries no entries is partial
and raises.
@abrichr

abrichr commented Nov 22, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: REQUEST CHANGES

From: Gemini
Reviewed-Head: 5680f81

Gemini run on 5680f81 (gemini-3.1-pro-preview via the API). It reviewed the PR's diff against its base, with the earlier findings and the filed follow-ups given as context. It was asked to report only fail-open items, since this PR is past its two-round cap. Posted as Gemini returned it.

The documentation updates accurately reflect the benchmark results without overclaiming. The 100 stopped collateral changes on Gitea correspond to two fault classes (comments and close/reopen events) with 50 plants each, which aligns perfectly with "50 of 50 per class," and the known misses are correctly disclosed.

However, the implementation of search_empty introduces a fail-open path for partial search responses.

  1. Fail-open on partial search: If a search response matches the search_empty shape (e.g., resourceType: Bundle) but explicitly reports a non-zero total (e.g., total: 1) while missing its items field, the and not declared_empty condition unconditionally suppresses the missing-items error. The verifier will extract an empty list, read the search as empty, and authorize a duplicate create. declared_empty should only bypass the error if total is missing (or 0).

…tial

Missing-evidence class: any search answer whose total is above zero but
that yields no usable record raises, whether the items field is missing or
present and empty.
@abrichr

abrichr commented Nov 22, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: REQUEST CHANGES

From: Gemini
Reviewed-Head: 9230ef4

Gemini run on 9230ef4 (gemini-3.1-pro-preview via the API). It reviewed the PR's diff against its base, with the earlier findings and the filed follow-ups given as context. It was asked to report only fail-open items, since this PR is past its two-round cap. Posted as Gemini returned it.

An analysis of the delta and the resulting _search function reveals that while the commit correctly prevents search_empty from suppressing errors when total > 0, it leaves a fail-open path for partial responses that explicitly include an empty items list.

When a server returns a response like {"resourceType": "Bundle", "type": "searchset", "total": 1, "entry": []}, the head ("entry") is present in got. Because head in got evaluates to True, the missing-evidence check (if head and head not in got...) is bypassed entirely. The function then extracts the empty list via pick, skips any further validation of total, and returns [].

This violates the premise of the commit ("a Bundle that says it matched something but carries no entries is partial and raises") and results in a fail-open where existing records are missed because the total > 0 claim is ignored if the empty field is explicitly present.

  1. The function returns [] (fail-open) if the response includes the items field as an empty list (e.g., {"total": 1, "entry": []}) because the missing-evidence check head not in got is bypassed, ignoring the total > 0 claim.

@abrichr

abrichr commented Nov 22, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: REQUEST CHANGES

From: Claude
Reviewed-Head: 20cc59b

Two independent reviewers (fail-open lens, correctness and tests lens) probed this head. Both found the same blocker.

Blocker (fail-open): the "reports matches it did not return" guard in txplan/scoped.py (~line 300) fires only when total is an int above 0. A search answer that has items, but none with a usable id, and no total (FHIR leaves total out unless _total is requested) still returns [].

  • {"resourceType":"Bundle","entry":[{"resource":{"resourceType":"Patient"}}]} returns [], so the pre-send check sends the create again (duplicate write), and recovery reads the write as not landed.
  • Duplicate counting has the same gap: with two entries where one lacks an id, len(found) == 1, so the duplicate_write check misses it.
  • Fix: raise whenever pick() returned items but found is empty, and count items rather than usable ids for duplicate detection.

Should fix in the same pass:

  1. A total that isn't exactly 0 or None (for example "1" or 1.0) with no usable records reads as empty. Reject a non-int total, or raise for any nonzero total.
  2. search_empty checks only resourceType == Bundle:
    • Wrong-type Bundles (type: history or batch-response) and a first page with a next link read as an empty search.
    • entry: null is also accepted as empty.
    • Fix: require type: searchset and no next link, and treat entry: null as an error.
  3. With search_empty set and search_items empty, a list answer raises AttributeError, so the run ends with no verdict. Reject that combination when the pack is validated.
  4. Tests:
    • The {total:1, entry:[]} case runs on an items collection and is caught by the older guard, so the new guard on the FHIR path is never tested.
    • Removing total in (None, 0) from declared_empty still passes every test.
    • Add pack-shaped (entry.*.resource) cases for each item above.
  5. The comment, PR body and RESULTS.md say the quota raise in fhir_medplum/compose.yml is lab-only for this bench. That compose file is shared by every Medplum bench, including openadapt bench medplum, the leaderboard and shadow runs. Use a compose override for api_scoped, or correct the claim.

Not blocking: a search.mode: outcome OperationOutcome entry is returned as a match. This predates the PR; please file an issue for it.

… shape; bench-only quota override

Review round 1 on #2525, missing-evidence class:
- a search that returns items without a usable id raises (never reads as
  absent), and every item counts toward a duplicate;
- a total that isn't a non-negative int raises; an answer reporting matches
  it doesn't return raises; an items field that isn't a list raises;
- search_empty is now {equals: {...}, absent: [...]}: Medplum's pack needs
  resourceType Bundle, type searchset and no next link; a pack with
  search_empty but no search_items is refused at load.
- the Medplum quota raise moves from the shared fhir_medplum compose file
  into benchmark/api_scoped/medplum.compose.override.yml, layered by this
  bench only; other Medplum benches keep the defaults.
Pack-shaped tests for each case; a 40-write smoke on real Medplum passed
with the new rules (0 stops, every planted fault stopped).
@abrichr

abrichr commented Nov 22, 2026

Copy link
Copy Markdown
Member Author

Round-1 items from the independent Claude review (comment 7075918800) are fixed at 6dc7f631:

Item Fix
Blocker: items with no usable id and no total read as empty _search raises when any returned item lacks a usable id, so such an answer never reads as absent and never authorizes a create.
Duplicate counting It now counts every item: since an id-less item raises, the count is always over items.
1. Non-count total A total that isn't a non-negative int raises. An answer reporting matches it doesn't return raises, whether the items field is missing or empty.
2. search_empty too loose It is now {equals: {...}, absent: [...]}. Medplum's pack requires resourceType: Bundle and type: searchset, with no link[relation=next]. entry: null (any non-list items field) raises.
3. search_empty without search_items Refused when the pack loads (model validator).
4. Tests The search test was rewritten with pack-shaped (entry.*.resource) cases for every item above, plus the undeclared and items shapes.
5. Quota claim The raise moved out of the shared fhir_medplum/compose.yml into benchmark/api_scoped/medplum.compose.override.yml, which only this bench layers (MedplumFixture(overrides=...)). Other Medplum benches keep the defaults, and RESULTS.md says so.

A 40-write smoke on real Medplum passes with the stricter rules: 0 stops, every planted fault stopped. That confirms the declared empty shape matches Medplum's real empty answer. The OperationOutcome-as-match item is filed as #2526.

@abrichr

abrichr commented Nov 22, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: REQUEST CHANGES

From: Claude
Reviewed-Head: 6dc7f63

Round 2. Two independent reviewers probed _search at this head against the real Medplum pack config.

Confirmed fixed:

  • an id-less resource now raises;
  • a non-int total and total>0 with no items both raise;
  • entry: null raises;
  • a wrong-type Bundle or next link with entry absent raises;
  • search_empty without search_items is refused when the pack loads;
  • the quota override is scoped to this bench;
  • legitimate empty searches still return [].

Blocking: the guards are still piecemeal, and each remaining hole is a shape that skips them.

  1. P1: pick() drops entries that have no resource, so the usable-id check never sees them. entry:[{fullUrl:x}], entry:[{resource:null}] and entry:[null] all return [], so the create is resent. A mixed answer undercounts, so duplicate_write is missed.
  2. P1: a Mapping is accepted where the * step needs a list. entry:{resource:{id:p1}} and entry:{} return [].
  3. P2: search_empty checks run only when entry is absent. A history Bundle with entry:[], a searchset with a next link and entry:[], and any answer with total:0 (including an OperationOutcome) all read as empty.
  4. P2: an int total larger than the records returned (a partial page) is accepted, so duplicates past page 1 are missed.
  5. P3: a non-scalar or bool id ({}, False) is turned into a string and accepted.
  6. P3: four new guards can be removed and the test file still passes, including the total-type guard, which re-opens a probed fail-open.
  7. P2 (claims): results/*.json and RESULTS.md come from 5680f81. That run used the old pack shape and the shared compose file, and was not repeated at the final shape. Rerun Medplum at the final head, or say this in RESULTS.md.

Suggested single fix, which covers this whole class instead of adding more guards: when a pack declares a search shape, parse every answer strictly against it, closed by default.

  • Apply the shape's equals and absent checks to every answer, not only empty ones.
  • The fan-out head must be a list.
  • Every element must yield exactly one Mapping resource whose id is a non-empty str or a non-bool int.
  • An int total, when present, must equal the number of records.
  • Anything else raises AdapterError.

Then add a mutation test: remove each clause and check that a test fails.

Replaces the piecemeal guards (review round 2 on #2525, missing-evidence
class). A declared search_empty shape is checked on every answer; every
step of search_items must resolve (a * step needs a list, each element one
object, no null or missing step); every record needs a non-empty str or a
non-bool int id; a total, when present, must be an int equal to the records
returned; the items field may be absent only on total 0 or, with a declared
shape, an answer matching it. Each of the 11 clauses is tagged in source and
a mutation test removes each one in turn and checks its refusal stops.
400 clean writes and 50 plants per class on Medplum 5.2.8 at the final
code: 0 clean stops; every log-exposed fault 50 of 50; another caller's
change 0 of 50 (known miss); retries 50/50. RESULTS.md records which commit
produced each results file.
@abrichr

abrichr commented Nov 22, 2026

Copy link
Copy Markdown
Member Author

Round-2 items (independent Claude review at 6dc7f631) are handled at new head 0bacd223.

One strict parser instead of guards (6ad9f6fb, txplan/scoped.py _strict_items and _search), closed by default. Anything else raises AdapterError.

  • A declared search_empty shape is checked on every answer.
  • Every step of search_items must resolve: a * step needs a list, each element yields exactly one object, and no step may be null or missing.
  • Every record needs a non-empty str or non-bool int id.
  • A total, when present, must be an int equal to the records returned.
  • The items field may be absent only on total: 0 or, with a declared shape, an answer matching it.
Item Now
1. pick() dropped entries without a resource entry:[{fullUrl}], [{resource:null}] and [null] raise. A mixed answer can't undercount.
2. A Mapping in place of a list entry:{...} and entry:{} raise.
3. Shape checks only when entry was absent The shape is checked on every answer. A history Bundle with entry:[], a next link with entry:[] and an OperationOutcome with total:0 all raise.
4. Partial page An int total that differs from the records returned raises.
5. Non-scalar or bool id {} and False raise.
6. Removable guards Each of the 11 clauses is tagged # search-clause: <tag>. test_each_search_clause_is_load_bearing deletes each one in turn and checks its refusal stops. All 11 are load-bearing.
7. Results from an older shape Medplum was rerun live at 6ad9f6fb: 0 of 400 clean stops, every log-exposed fault 50 of 50, another caller's change 0 of 50 (known miss), retries 50/50. RESULTS.md now says which commit produced each results file. Gitea's rows stay from 5680f814, because its pack declares no marker search and its path is unchanged.

@abrichr

abrichr commented Nov 22, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: REQUEST CHANGES

From: Claude
Reviewed-Head: 0bacd22

Round 3. Two independent reviewers re-probed every round-1 and round-2 scenario at this head, and every one now raises.

  • New shapes: null, float, bool and container ids; negative or bool totals; a total with a next link; non-Mapping entries; and non-object answers all raise.
  • No regressions: empty searchsets return [], one or two matches return their ids, and duplicate ids trigger duplicate_write. Packs that declare no search shape behave as before.
  • Mutation test: it rewrites the source for real. Medplum rerun provenance and the RESULTS.md and CAPABILITIES.md counts match the JSON. The compose override is scoped to api_scoped only.

Two narrow holes remain, both outside the tagged clauses:

  1. Fail-open (P1): _strict_items flattens a single list at the end of the path, even after a * fan-out.
    • entry:[{resource:[]}], with or without total:0, returns []. An entry that is present reads as "not found", so the create is resent and recovery reads the write as not landed.
    • entry:[{resource:[{id:a},{id:b}]}] turns one entry into two records.
    • Fix: flatten only on paths with no *, require each fan-out element to resolve to exactly one Mapping, tag that clause, and add both shapes as tests.
  2. P3: the search_empty absent check uses the lenient pick(), so a non-list link, a non-str relation, or "Next" reads as absent. Resolve absent paths strictly: a present parent that isn't a list of Mappings with str relations raises.
  3. P3 (test): in test_each_search_clause_is_load_bearing, a mutant that crashes, or is refused by another clause, still counts as load-bearing. Require that, with the clause removed, the probe input is accepted: it returns a value and doesn't raise.

Not blocking, carried over: an OperationOutcome search.mode: outcome entry is still returned as a match. This is #2526.

…st requires acceptance

Review round 3 on #2525, missing-evidence class:
- after a * fan-out each element is one record: entry:[{resource:[]}] and
  a resource list no longer flatten into zero or several records (they
  raise as items without a usable id); the guard is tagged
  no-flatten-after-fanout.
- a name[key=value] absent path resolves strictly: a present parent that
  isn't a list of objects with string keys raises; the value matches
  without regard to case.
- every tagged clause is now the only check for its probe, and the mutation
  test requires the probe to be accepted (return ids, no exception) once its
  clause alone is removed.
@abrichr

abrichr commented Nov 22, 2026

Copy link
Copy Markdown
Member Author

Round-3 items (independent Claude review at 0bacd223) are fixed at 9a2fda7a.

  1. No flatten after a fan-out (P1). _strict_items flattens a final list only on paths without *, and that guard is tagged no-flatten-after-fanout. entry:[{resource:[]}] (with or without total:0) and entry:[{resource:[{id:a},{id:b}]}] now raise, because the item has no usable id. One entry can't read as empty or as two records.
  2. Strict absent paths. A name[key=value] path (link[relation=next]) is now resolved strictly by _present. A present link that isn't a list of objects with string relation raises (absent-shape), and the value matches case-insensitively, so Next counts. Plain dotted paths still use pick.
  3. The mutation test requires acceptance. For each tagged clause, test_each_search_clause_is_load_bearing removes only that clause and requires its probe to return ids without raising. A refusal by another check or a crash fails the test. To make each clause the only guard, I dropped the two checks that were redundant with later ones (top-level object type and leaf object type); a non-object item now fails as an item without a usable id. There are 11 clauses, and all are load-bearing.

The Medplum pack is unchanged, so this needed no live rerun. test_txplan_scoped.py and test_txplan.py pass (68).

@abrichr

abrichr commented Nov 22, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: APPROVE

From: Claude
Reviewed-Head: 9a2fda7

This is the final check, diffed against round 3 (0bacd22). I probed _search at this head with the Medplum-shaped pack, a FHIR pack with no declared shape, the items pack and the root pack.

Round-3 items, all fixed:

  • Fan-out records: list-valued resources after a fan-out raise ("no usable id").
  • Malformed links: Mapping, str, int and {} links, non-str relations, and link entries without a relation all raise. Next/NEXT match case-insensitively.
  • Mutation test: it now requires the probe to be accepted once its clause is removed. The flatten guard has its own mutant.

Dropped checks: the two dropped clauses are object-answer and leaf-object. The inputs they caught now raise from other clauses:

  • items-field catches non-Mapping answers;
  • shape-equals catches non-object FHIR answers;
  • usable-id catches non-Mapping records.

All 59 scenarios from rounds 1-3 still raise.

No regressions:

  • empty searchsets (entry absent, [], total 0, self link only);
  • one and two matches, with and without total;
  • duplicate ids, which still trip duplicate_write;
  • int ids;
  • packs that declare no search shape;
  • items and root packs.

Tests: tests/test_txplan_scoped.py has 32 passed and 2 failed locally. The two receipt-signing tests (out['receipt'] is False) fail the same way at round 3 in the same local environment, so the cause is the local signing setup, not this diff. CI is authoritative.

Non-blocking:

@abrichr
abrichr merged commit 6c95686 into main Nov 22, 2026
56 of 57 checks passed
@abrichr
abrichr deleted the claude/api-scoped-rerun-2026-11-22 branch November 22, 2026 08:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant