Phase 3b static lookup is complete — ECOG, Karnofsky, and NYHA are recognized from the YAML config and get unit_concept_id=8527. But unknown ordinal scales (Child-Pugh, GCS, APACHE II, MELD, mRS, SOFA, etc.) silently pass through with unit_concept_id=None. Per the "Lookup → Agent → Approve → Persist" design, unknown ordinal entities should trigger an LLM agent node that proposes a mapping for human review.
Design
Add a 7th LangGraph node ordinal_resolve after structure:
Identify candidates: Query AtomicCriterion records from the batch where unit_concept_id IS NULL, value_numeric IS NOT NULL, and unit_text IS NULL. This combination (numeric value + no unit) is a strong signal for unrecognized ordinal scales. Categorical values (HIV status = "positive") are excluded because they have value_text not value_numeric.
Batch LLM call: Send all candidate entities to Gemini in a single structured-output call. Prompt asks: "For each entity, is this a clinical ordinal scoring system? If yes, propose YAML config." Uses Pydantic schema for structured output (same pattern as detect_logic_structure()).
Immediate update: For entities the LLM confirms as ordinal, set unit_concept_id=8527 on the AtomicCriterion record. This is safe — {score} is always the correct UCUM unit for ordinal scales.
Store proposals: Write an AuditLog entry with event_type="ordinal_scale_proposed" containing the full proposed YAML mapping (entity aliases, LOINC codes, value ranges). This feeds the human approval workflow.
Graceful degradation: If GOOGLE_API_KEY is missing or the LLM fails, skip silently (same pattern as detect_logic_structure()). Records stay with unit_concept_id=None — no worse than before.
Files to Create/Modify
File
Change
src/protocol_processor/schemas/ordinal.py
NEW — Pydantic schemas for Gemini structured output
src/protocol_processor/tools/ordinal_resolver.py
NEW — resolve_ordinal_candidates() LLM tool
src/protocol_processor/nodes/ordinal_resolve.py
NEW — LangGraph node function
src/protocol_processor/state.py
Add `ordinal_proposals_json: str
src/protocol_processor/graph.py
Add node + edge: structure → ordinal_resolve → END
Prompt: "You are a clinical terminology expert. For each entity below, determine if it is a clinical ordinal scoring system..." with indexed entity list + context (value, relation)
Validation: Filter proposals where is_ordinal_scale=True and confidence >= 0.7
test_successful_resolution — mock Gemini returns Child-Pugh as ordinal → unit_concept_id=8527 set on AtomicCriterion
test_non_ordinal_rejected — mock Gemini says "HIV status" is NOT ordinal → no update
test_low_confidence_rejected — confidence < 0.7 → no update
test_llm_failure_graceful — exception → no update, error accumulated
E2E tests (DB integration):
test_child_pugh_gets_resolved — Child-Pugh criterion through full backend with mocked LLM → unit_concept_id updated to 8527
test_known_scales_not_rechecked — ECOG (already 8527 from YAML) is NOT sent to LLM
test_mixed_batch — batch with ECOG + Child-Pugh + HbA1c → only Child-Pugh sent to LLM
test_audit_log_written — AuditLog entry with proposals is created
test_proposals_in_state — ordinal_proposals_json populated in returned state
Graph tests update:
test_graph.py: Update test_graph_has_six_user_nodes → 7 nodes, add "ordinal_resolve" to expected set
Step 6: Delete Test File
Remove tests/test_phase3b_unknown_scales.py — its assertions (unknown scales get None) will no longer be true since the new node resolves them.
Verification
uv run pytest tests/test_ordinal_resolve.py -v — all new tests pass
uv run pytest tests/test_graph.py -v — updated node count passes
uv run pytest tests/ -v — full suite green (192+ tests)
uv run ruff check . — clean
Manual: Child-Pugh, GCS, APACHE II criteria now get unit_concept_id=8527 when LLM confirms they're ordinal scales
AuditLog contains full YAML proposals for human review
If you need specific details from before exiting plan mode (like exact code snippets, error messages, or content you generated), read the full transcript at: /Users/noahdolevelixir/.REDACTED.jsonl
Assistant
I'll start by exploring the existing codebase to understand the patterns I need to follow, then implement all the changes.
Assistant
Now let me read the exact files I need for implementation details.
Assistant
Now let me read the test files and check the existing schemas directory structure.
Assistant
Let me also check the tracing module and the __init__.py files.
Assistant
Step 1: Create Pydantic schemas
Assistant
Step 2: Create LLM tool
Assistant
Step 3: Create LangGraph node
Assistant
Step 4: Update state.py and graph.py
Assistant
Now update graph.py:
Assistant
Also update the __init__.py files to document the new node and tool:
Assistant
Step 5: Create tests and update test_graph.py
First, update test_graph.py:
Assistant
Also update the _make_initial_state helper and test_state_has_required_fields to include the new field:
Assistant
Now create the main test file:
Assistant
Step 6: Delete test_phase3b_unknown_scales.py
Assistant
Step 7: Run lint and tests
Assistant
Let me fix all the lint issues.
Assistant
Good, the import sorting is fixed. Now fix the line length issues. Let me fix graph.py first:
Assistant
Now fix the ordinal_resolve.py complexity and line length:
Assistant
I need to refactor the node to reduce complexity and fix the line length. Let me extract the DB work into a helper function:
Assistant
Now fix the test file line lengths:
Assistant
Now fix the remaining long lines in the test file:
Assistant
Now run lint again to check:
Assistant
Lint is clean. Now run the new tests:
Assistant
The issue is that ChatGoogleGenerativeAI is imported lazily inside the function, so patching it at the module level doesn't work. I need to use create=True or patch at the langchain_google_genai level. Let me fix the mock approach — I need to patch langchain_google_genai.ChatGoogleGenerativeAI since it's the import source:
Assistant
The issue is that ChatGoogleGenerativeAI is lazily imported inside the function body. I need to patch langchain_google_genai.ChatGoogleGenerativeAI instead. Let me check how existing tests handle this:
Assistant
The existing tests use @patch("langchain_google_genai.ChatGoogleGenerativeAI"). I need to replace all occurrences in my test file.
Assistant
13/14 passing. The last failure is because "ECOG" appears in the prompt template as an example, not as a candidate entity. The test assertion is too strict. Let me fix it to check the entity list section rather than the entire prompt:
Assistant
All 14 tests pass. Now run graph tests and the full suite:
Assistant
Now run the full test suite:
Assistant
Just one failure — there's another test in test_phase2_e2e.py that also checks node count. Let me fix it:
Assistant
All 206 tests pass. Let me run a final ruff check on all files:
Assistant
All done. Here's a summary of everything implemented:
Assertions that unknown scales get None are no longer valid
Verification
uv run ruff check . — clean
uv run pytest tests/ -v — 206 passed (14 new + 192 existing)
User
Now let's check end to end by running the free text of a criteria with an ordinal scale through. The first time, the node should be triggered and the outcome hardcoded. The next time we run the same criteria through it should trigger the hardcoding. (let's assume it is approved).
Assistant
Let me understand the current YAML config and ordinal normalization flow to design this E2E test properly.
Assistant
Now I have a clear picture of the full cycle. Let me write an E2E test that demonstrates:
Run 1: Child-Pugh → static lookup misses → ordinal_resolve_node fires LLM → resolves it
Simulate approval: Add Child-Pugh to YAML config
Run 2: Child-Pugh → static lookup hits → already resolved, no LLM call
Assistant
Now I'll write the full-cycle E2E test:
Assistant
Full cycle passes. Now let me run the entire suite to make sure nothing is broken:
Assistant
207 passed, 0 failed. Full suite green including the new full-cycle test.
Here's what the test_full_cycle_child_pugh test demonstrates:
Phase
What happens
Verified
1. Static Lookup (MISS)
normalize_ordinal_value("6", "Child-Pugh score") returns None — not in YAML. build_expression_tree creates AtomicCriterion with unit_concept_id=None
atomic1.unit_concept_id is None
2. Agent Resolve
ordinal_resolve_node queries unresolved candidates, sends to Gemini (mocked), gets confirmation → updates unit_concept_id=8527, writes AuditLog with proposal
atomic1.unit_concept_id == 8527, AuditLog has child_pugh proposal
3. Approval
Simulated by patching _load_ordinal_scales() to include Child-Pugh config (equivalent to adding to YAML after human review)
normalize_ordinal_value("6", "Child-Pugh score") is not None
4. Static Lookup (HIT)
New Child-Pugh criterion through build_expression_tree → unit_concept_id=8527 at creation time from YAML
atomic2.unit_concept_id == 8527
5. No LLM Needed
ordinal_resolve_node on the new batch finds zero candidates (already resolved) → resolve_ordinal_candidates never called
mock_resolve.assert_not_called()
User
Run the test and report?
Assistant
1 passed in 3.26s — the full Lookup → Agent → Approve → Persist cycle works end-to-end.
User
Show me the results
Assistant
Here's what the logs show for each phase:
Phase 1 — Static Lookup (MISS): build_expression_tree runs for "Child-Pugh score <= 6". No log from the ordinal resolver — the YAML lookup silently returns None. AtomicCriterion created with unit_concept_id=None.
The node found 1 unresolved candidate (Child-Pugh), sent it to the (mocked) LLM, got confirmation, updated unit_concept_id to 8527, and wrote the AuditLog proposal.
Phase 3 — Approval: Simulated by injecting Child-Pugh into the ordinal scales config.
Phase 4 — Static Lookup (HIT): build_expression_tree runs for "Child-Pugh score <= 7". Now normalize_ordinal_value() matches from the config — AtomicCriterion created with unit_concept_id=8527 at creation time.
Phase 5 — No LLM Needed:
code
No ordinal candidates found for protocol dda25c85...
The node queries for unresolved atomics, finds zero (Child-Pugh already has 8527), skips the LLM entirely.
User
No no, no mocking. Let's test for real. With our medgemma node and access to tooluniverse and OMOP, let's see if it works.
Assistant
Let me check what we have available — API keys, database, and existing data.
Assistant
Good — API key and DB are both available. Let me check what's in the database.
Assistant
The DB schema is behind — unit_concept_id and value_concept_id columns don't exist yet on the live Postgres. I need to run a migration first.
Assistant
Missing unit_concept_id and value_concept_id. Let me add them.
Assistant
Good. Now let me check the existing data and run a real protocol through the full pipeline.
Assistant
No existing atomics — we need to feed a protocol through the pipeline first. Let me write a real end-to-end script that creates a protocol with ordinal criteria, runs build_expression_tree to create atomics, then runs ordinal_resolve_node with the real Gemini API.
Assistant
Continuing with the real E2E test. The last blocker was missing DB columns. Let me check what columns the models need and sync the database.
Assistant
Now let me check what columns actually exist in the live database.
Assistant
No psql available locally. Let me use Python to check the DB schema.
Assistant
The criteria table is missing only the structured_criterion column. Everything else looks good — atomic_criteria already has unit_concept_id and value_concept_id. Let me add the missing column and run the real E2E.
Assistant
Good. Now let me run the real E2E script.
Assistant
It works end-to-end with real Gemini and real Postgres. Here's what happened:
Phase 1 — Static lookup (build_expression_tree):
ECOG → recognized from YAML config → unit_concept_id=8527 immediately
Child-Pugh, GCS, MELD → not in YAML → unit_concept_id=None (candidates for LLM)
HbA1c → physical unit % → unit_concept_id=8554
CrCl → physical unit mL/min → unit_concept_id=8795
Gemini correctly identified all 3 unknown ordinal scales with 100% confidence
Returned LOINC codes: Child-Pugh (35676-5), GCS (72178-9), MELD (47012-4)
Provided aliases and value descriptions for each scale
All 3 got unit_concept_id=8527 ({score})
Phase 3 — DB verification:
All 6 AtomicCriteria have correct unit_concept_id values
ECOG and the 3 LLM-resolved scales all show {score}
Lab values kept their physical units
AuditLog entry written with all 3 proposals for human review
The full Lookup → Agent → Approve → Persist pipeline is working live.
User
Fix ruff, mypy and pytest. Commit and then proceed to the next phase.
Assistant
Let me fix the ruff errors first, then run mypy and pytest.
Assistant
I need to split main() into smaller functions and add a docstring. Let me refactor the script.
Assistant
Now let me also remove the unused sys import that was there before (I already dropped it in the rewrite). Let me run all three checks.
Assistant
Ruff is clean. Mypy has pre-existing errors across many files, but let me focus on the errors in my new files. Let me check which mypy errors are from files I created/modified.
Assistant
All 207 tests pass. Now let me fix the mypy errors in my files. The import-untyped errors for api_service/shared.models are pre-existing across all node files — same pattern. Let me fix the ones I can:
Let me check if the state.py:48 error is pre-existing (i.e. it existed before my changes).
Assistant
The state.py:48 error (list[dict]) is pre-existing — line 48 hasn't changed. Now let me fix the errors in ordinal_resolve.py that are mine:
Assistant
Now fix the unused type: ignore comments. Since shared.models is untyped (mypy can't check it), the SQLAlchemy .is_() / .isnot() methods resolve to Any and don't need union-attr ignores. But the arg-type on the join is also unnecessary when the model is untyped. Let me remove them all:
Assistant
Now run all three checks again.
Assistant
All clean:
Ruff: All checks passed
Mypy: Only pre-existing import-untyped errors (same as every other node file)
Pytest: 207 passed
Now let me commit.
Assistant
I notice tests/test_phase3b_unknown_scales.py was supposed to be deleted (per the plan) but it shows as untracked ?? rather than deleted. Let me check — it might have already been untracked (never committed).
Assistant
It was never committed. Also test_phase3b_e2e.py is untracked. Let me check what these are — they might be leftover from the earlier phase 3b work that got superseded.
Assistant
test_phase3b_unknown_scales.py was already deleted. test_phase3b_e2e.py is a valid Phase 3b test for known ordinal scales. Let me include it in the commit. Now let me stage everything properly.
Assistant
Committed. Now let me figure out what the "next phase" is. Let me check the project plan/roadmap.
Assistant
All checks pass and committed. Looking at the gap closure plan, the completed phases are:
Phase 1a: Dual grounding (OMOP mapper)
Phase 1b: Concept IDs in field mappings
Phase 2: Expression tree + normalized tables (atomic_criteria, composite_criteria, criterion_relationships)
The remaining phases from the plan are independent of each other and can be parallelized:
Assistant
Let me evaluate each code review item and fix the ones that are warranted. I'll read the relevant files first.
Assistant
Now let me check the _entity_to_response function and the dead code line in ground.py.
Assistant
Good, I have a clear picture now. Let me evaluate each item:
#
Issue
Verdict
Reason
1.1
Dead code ground.py:516
Fix
Genuine dead code
1.2
Persist batch validation
Fix
Real safety issue
1.3
Unit normalizer unused
Skip
Review is wrong — normalize_unit, normalize_ordinal_value, and normalize_value are all called at lines 194, 201, 208 of structure_builder.py
1.4
Integrity check
Skip
File doesn't exist in codebase (likely removed/renamed)
2.1
GEMINI_MODEL_NAME
Fix
Standardize defaults
2.2
Outdated docstrings
Fix
Now 7 nodes, not 5
2.3
EntityResponse OMOP fields
Fix
UI needs these fields
3.1
Repeated Gemini init
Skip
Premature abstraction — each tool may need different params
3.2
Structured result handling
Skip
Same, premature abstraction
4.1
_find_last_composite_id
Skip
Low priority, medium effort per review's own assessment
4.2
Unused entity param
Skip
Parameter serves as documentation/context at call site
4.3
Exception handling
Fix
Too broad, hides real errors
Let me fix the 6 items in parallel.
Assistant
Now let me apply all 6 fixes.
Assistant
Now fix GEMINI_MODEL_NAME defaults — standardize all to gemini-2.5-flash:
Assistant
Need to read the files I haven't read yet.
Assistant
Now fix EntityResponse to add OMOP fields:
Assistant
Now run all checks:
Assistant
The test_get_graph_singleton test is failing because narrowing to OSError doesn't catch psycopg.OperationalError. Let me check the exception hierarchy.
Assistant
psycopg.OperationalError inherits from Exception, not OSError. The original except (KeyError, Exception) was there for a reason — it needs to catch database connection failures too. The review's suggestion to narrow the catch is valid in principle, but the right scope is KeyError (env var missing) + psycopg.Error (DB connection issues), not OSError. However, importing psycopg just for this would add a dependency. The simplest correct fix is except Exception with a clear comment:
Assistant
Good — the linter also fixed ordinal_resolve.py to use table columns for SQL expressions (resolving the mypy issues). Now let me re-run the tests:
Assistant
The linter's auto-fix put the import after module-level code. Let me fix the ordering.
Assistant
Let me also check mypy for my changed files:
Assistant
All pre-existing errors, nothing new from my changes. Ruff clean, 207 tests pass. Now let me commit.
Assistant
Committed. Now let me proceed to Phase 4: Patient Matching. Let me first understand what's needed by reading the plan more carefully and exploring what patient data infrastructure exists.
Assistant
Now let me understand the practical constraints before designing the plan.
Assistant
Here's my assessment of each code review item:
Fixed (6 items)
#
Issue
Fix
1.1
Dead code ground.py:516 — entity.get("criterion_text") or entity.get("text", "") evaluated and discarded
Removed the dead line
1.2
Persist batch validation — criterion_id lookup doesn't verify it belongs to the batch
Added if criterion and criterion.batch_id != batch_id: criterion = None so it falls through to substring search
2.1
GEMINI_MODEL_NAME defaults inconsistent (mix of gemini-2.0-flash and gemini-2.5-flash)
Standardized all 7 occurrences to gemini-2.5-flash (matching .env.example)
2.2
Outdated docstrings — state.py says "5-node", persist.py says "final node"
Updated to "7-node" and listed full pipeline flow
2.3
EntityResponse missing OMOP fields
Added omop_concept_id and reconciliation_status to both EntityResponse model and _entity_to_response() helper
4.3
Exception handling except (KeyError, Exception) too broad
Changed to except Exception with a comment explaining the two failure modes (KeyError for missing env var, psycopg.OperationalError for DB unreachable). Kept Exception because psycopg.OperationalError inherits from Exception, not OSError — narrowing to OSError broke the test.
Discarded (8 items)
#
Issue
Reason for skipping
1.3
Unit normalizer imported but never used
Review is wrong. All three imports (normalize_unit, normalize_ordinal_value, normalize_value) are actively called at structure_builder.py lines 194, 201, and 208 respectively.
Assistant
Good question — let me clarify. Looking at the gap closure plan, "Phase 4: Patient Matching Infrastructure" is specifically about evaluating structured criteria against patient data to find eligible patients. That's the end goal (the "join" in "join-ready"), but it requires patient records.
However, there are phases that come before patient matching that don't need patient data at all:
What can be done without patient data:
CIRCE export — translate our atomic_criteria/composite_criteria into CIRCE JSON (the standard OHDSI cohort definition format). This is the portable output that OHDSI Atlas can execute against any OMOP CDM database to find patients.
FHIR Group export — same idea, different standard.
Eligibility query SQL generation — generate the SQL that would evaluate the criteria, ready to run against any OMOP CDM.
What needs patient data:
Actually running the evaluation (populating patient_criterion_matches)
Returning matched patient lists
Given this distinction, I'd recommend we do CIRCE/FHIR export first — it's the natural "Phase 4" output that makes structured criteria usable by external systems. Then patient matching becomes a separate integration step.
Assistant
Now I understand. The goal is to make the structured criteria output join-ready — optimally organized for future patient matching. This means:
Schema/index optimization for efficient future joins
File doesn't exist. No integrity.py found anywhere in the codebase — it was likely removed or renamed.
3.1
Repeated Gemini initialization across tools
Premature abstraction. Each tool has different error handling, model params, and structured output schemas. A shared helper would couple unrelated tools and make per-tool customization harder.
3.2
Structured result handling pattern duplicated
Same reasoning. 4 lines of dict-vs-object handling isn't worth an abstraction. Each tool handles the fallback differently.
4.1
_find_last_composite_id may be ambiguous with same timestamp
Low priority, medium effort per the review's own assessment. The ambiguity requires two composites with identical created_at in PostgreSQL (microsecond resolution), which is unlikely in practice. Would require restructuring _build_tree_from_logic to pass IDs — a riskier refactor.
4.2
_log_grounding_auditentity parameter unused
Serves as documentation. The parameter is passed at every call site and documents what data is available. Removing it would just obscure the interface. Harmless to keep.
5.1
Persist all_failed logic
Review itself says no change needed.
5.2
system_field_map simplification in persist.py
Cosmetic. The existing if/elif chain is readable and maps field names correctly. A getattr/setattr approach would be marginally shorter but less obvious.