Explore / Programming Implement the following plan: Phase 2: Expression Tree + Normalized Tables Context Phase… Save Share Download ▾ ReportImplement the following plan:
Phase 2: Expression Tree + Normalized Tables
Context
Phase 1 (dual grounding) is complete and verified. Entities now carry OMOP concept IDs, field mappings include concept IDs, criterion_id threading and accumulation work. The gap closure plan requires Phase 1b to be in QA before Phase 2 begins — that gate is passed.
Phase 2 builds the next layer: structured expression trees that capture AND/OR/NOT logic from criteria text, backed by normalized atomic_criteria/composite_criteria tables that enable direct SQL joins for cohort evaluation and CIRCE export.
Files to Create
File Description services/api-service/alembic/versions/42_01_add_expression_tree_tables.pyMigration: 3 new tables + structured_criterion column on criteria services/protocol-processor-service/src/protocol_processor/schemas/structure.pyPydantic schemas: LogicNode, LogicDetectionResponse, ExpressionNode, StructuredCriterionTree services/protocol-processor-service/src/protocol_processor/tools/structure_builder.pyGemini-based logic detection + tree builder (follows field_mapper.py pattern) services/protocol-processor-service/src/protocol_processor/nodes/structure.pyPipeline node: reads persisted criteria from DB, builds trees, writes normalized tables services/protocol-processor-service/tests/test_phase2_structure.pyTests: schemas, logic detection, tree building, node behavior
Files to Modify
File Change libs/shared/src/shared/models.pyAdd AtomicCriterion, CompositeCriterion, CriterionRelationship models + Criteria.structured_criterion column services/protocol-processor-service/src/protocol_processor/graph.pyAdd structure node, change persist→END to persist→structure→END services/protocol-processor-service/src/protocol_processor/nodes/__init__.py
Show full message · 153 lines AssistantCopy response I'll implement Phase 2: Expression Tree + Normalized Tables. Let me start by reading the existing code to understand the patterns.
AssistantCopy response Let me start by reading the key existing files to understand patterns.
AssistantCopy response Now let me read the existing patterns in parallel.
AssistantCopy response Now let me read the remaining files I need for context.
AssistantCopy response Now let me read the existing migration files and state to understand the patterns.
AssistantCopy response Now let me also check the schemas directory and the tracing module.
AssistantCopy response Now I have a good understanding of the patterns. Let me also check the tracing module used by nodes.
AssistantCopy response Good. Now I have all the context I need. Let me start implementing.
AssistantCopy response
Step 1: Database Models AssistantCopy response Now add structured_criterion to the Criteria class:
AssistantCopy response Now add the three new model classes at the end of the file:
AssistantCopy response
Step 2: Alembic Migration AssistantCopy response
Step 3: Pydantic Schemas AssistantCopy response
Step 4: Structure Builder Tool AssistantCopy response
Step 5: Structure Pipeline Node Assistant· <synthetic> Copy response
You've hit your limit · resets 6pm (Europe/Paris)
Copy first prompt
Details
Provider anthropic
Model provenance As recorded by source dataset
Turns 1 (17 messages)
Language Not recorded
Added to archive Nov 23, 2026
ID 01m83b3wzv7gvratvmcqcf17xbSource & license Imported from SALT-NLP/SWE-chat (source ). Imported records earn no Research Points.
Upstream record: 5f6d9351-5590-48de-9d5c-589a3d513288
SALT-NLP/SWE-chat, revision 202b071f18e03c79df5a7287565ce2ebc5ee7756.
License: ODC-BY-1.0
Dataset releases Not yet included in a published release.
services/protocol-processor-service/tests/test_graph.pyUpdate node count 5→6, add structure edge assertion
Implementation Steps (in order)
Step 1: Database Models (libs/shared/src/shared/models.py) Add structured_criterion JSONB column to existing Criteria class:
python Copy code
structured_criterion: Dict[str, Any] | None = Field(default=None, sa_column=Column(JSON))
Add three new SQLModel classes:
AtomicCriterion (table atomic_criteria) — leaf nodes:
id (PK), criterion_id (FK→criteria, indexed), protocol_id (FK→protocol, indexed)
inclusion_exclusion ("inclusion"/"exclusion")
entity_concept_id, entity_concept_system, omop_concept_id (all indexed)
entity_domain (Condition/Measurement/Drug/Procedure)
relation_operator (>=, <=, =, has, is, NOT, within)
value_numeric (float), value_text (string) — one populated based on parsing
unit_text, negation (bool), temporal_constraint (JSON)
original_text, confidence_score, human_verified, human_modified
Composite index: (protocol_id, inclusion_exclusion)
CompositeCriterion (table composite_criteria) — branch nodes:
id (PK), criterion_id (FK→criteria, indexed), protocol_id (FK→protocol, indexed)
inclusion_exclusion, logic_operator ("AND"/"OR"/"NOT")
parent_criterion_id (nullable, indexed — NULL = root)
original_text, human_verified
CriterionRelationship (table criterion_relationships) — edges:
parent_criterion_id (FK→composite_criteria, PK part 1)
child_criterion_id (PK part 2) — polymorphic FK (atomic OR composite)
child_type ("atomic"/"composite") — discriminator
child_sequence (int) — preserves operand order
Step 2: Alembic Migration (42_01_add_expression_tree_tables.py)
Revision: 42_01_expression_tree, down_revision: 41_01_entity_omop_cols
Add structured_criterion column to criteria (with idempotency guard)
Create all three tables with indexes
Use batch_alter_table pattern and inspector.get_table_names() guards
Step 3: Pydantic Schemas (schemas/structure.py)
LogicNode: node_type (AND/OR/NOT/ATOMIC), field_mapping_index (for ATOMIC), children
LogicDetectionResponse: root (LogicNode tree), reasoning (string)
ExpressionNode: type, atomic_criterion_id, entity, relation, value, unit, omop_concept_id, children
StructuredCriterionTree: root (ExpressionNode), structure_confidence (llm/fallback), structure_model
Step 4: Structure Builder Tool (tools/structure_builder.py) Follows field_mapper.py pattern exactly.
detect_logic_structure(criterion_text, field_mappings) → LogicDetectionResponse | None
Skip LLM call if only 1 field_mapping (just return ATOMIC)
Use ChatGoogleGenerativeAI.with_structured_output(LogicDetectionResponse)
Validate all field_mapping_index values are in range
Return None on any failure (triggers fallback)
build_expression_tree(criterion_text, field_mappings, criterion_id, protocol_id, inclusion_exclusion, session) → StructuredCriterionTree
Call detect_logic_structure() — Pass 1 (LLM)
If None, fall back to AND-of-all-atomics — Pass 2 (fallback)
Parse values: try float() → value_numeric, else → value_text
Create AtomicCriterion records (one per field_mapping)
Create CompositeCriterion + CriterionRelationship records from tree
Return StructuredCriterionTree for JSONB storage
Step 5: Structure Node (nodes/structure.py) Pipeline node that runs after persist. Reads from DB, writes to DB.
Early exit if state["error"] is set
Query all Criteria in batch_id that have non-empty field_mappings in conditions
For each qualifying criterion:
Extract field_mappings from criterion.conditions["field_mappings"]
Call build_expression_tree() with DB session
Set criterion.structured_criterion to the tree JSONB
On failure: accumulate error, continue
Commit all records, write AuditLog
Return {"status": "completed", "errors": accumulated_errors}
Error handling: Same accumulation pattern as ground node. Individual criterion failures don't block others. Uses asyncio.Semaphore(4) for parallel LLM calls.
Step 6: Graph Wiring (graph.py) python Copy code
workflow.add_node("structure", structure_node)
# Change: persist→END becomes persist→structure→END
workflow.add_edge("persist", "structure")
workflow.add_edge("structure", END)
No conditional edges needed — structure uses error accumulation like ground→persist.
Step 7: Tests (test_phase2_structure.py) TestLogicDetectionSchemas — Pydantic roundtrip tests for tree shapes
TestDetectLogicStructure — Mock Gemini, test AND/OR/NOT detection + failure→None
TestBuildExpressionTree — Mock session, verify AtomicCriterion/CompositeCriterion creation, value parsing, fallback behavior
TestStructureNode — Mock DB queries, verify error accumulation, audit logging, skip-on-error
Update test_graph.py: node count 5→6, verify persist→structure and structure→END edges.
Key Design Decisions
Structure node goes after persist — it reads criteria from DB (already committed by persist), writes to new tables. Clean separation of concerns.
AND/OR/NOT from day one — not AND-only. ~20% of criteria contain OR/NOT logic; building correctly once is cheaper than rewriting.
Polymorphic FK in criterion_relationships — child_type discriminator ("atomic"/"composite") avoids complex multi-table FK constraints. Standard pattern for tree structures.
Single field_mapping → skip LLM — no point asking Gemini about logic structure when there's only one atom.
PipelineState unchanged — structure node reads/writes DB, doesn't need new state fields.
Verification
uv run alembic upgrade head — tables and column exist
uv run ruff check . — clean
uv run mypy . — clean
uv run pytest — all pass (existing 182 + new ~20)
E2E: re-process a protocol, verify atomic_criteria and criteria.structured_criterion populated
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
Copy first response