Repository navigation
refactor: rebuild schema extraction and synthetic boundary contracts - #265
Conversation
|
Caution Review failedThe pull request is closed. ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (17)
📝 WalkthroughWalkthroughSystematic type-tightening and structural refactoring across the schema layer, replacing generic Changes
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related issues
Possibly related PRs
Poem
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 366a87f46b
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if sample is None or isinstance(sample, (str, int, float, bool)): | ||
| return sample | ||
| return None |
There was a problem hiding this comment.
Preserve original sample shape in cluster payload
This fallback now maps any non-scalar sample that is not a non-empty document/list-of-documents to None, so valid JSON sample shapes (for example arrays of scalars or mixed arrays) lose their structure before hashing. That can collapse distinct samples into the same schema_cluster_id, reducing clustering accuracy whenever such payloads are passed to cluster_samples.
Useful? React with 👍 / 👎.
…265) Ref #261 ## Summary - rebuild schema extraction around explicit resolved-message records instead of loose body/usage/timestamp plumbing - renew synthetic generation so `SyntheticCorpus` owns real runtime state and explicit methods rather than rebinding imported helpers - tighten schema observation and sampling feed paths so record-stream and document sampling flow through cleaner typed boundaries ## Problem The schema-side core was strict-type-clean, but several high-churn seams were still path-dependent and weakly modeled. Extraction mixed JSON-path walking, body fallback, timestamp/model/usage resolution, and harmonization through broad `object` values. Synthetic generation centered on a `SyntheticCorpus` shell that rebound imported helper functions and spread runtime state across loose helper protocols. DB/session sampling still duplicated record-stream versus envelope logic instead of owning an explicit raw-row boundary. That left the code semantically underspecified even though mypy was green. ## Solution - introduced explicit extraction and observation records in: - `polylogue/schemas/extraction.py` - `polylogue/schemas/observation_models.py` - `polylogue/schemas/observation_runtime.py` - renewed the synthetic center of gravity in: - `polylogue/schemas/synthetic/core.py` - `polylogue/schemas/synthetic/runtime.py` - `polylogue/schemas/synthetic/relation_solver_runtime.py` - `polylogue/schemas/synthetic/relations.py` - followed the new contracts through the mechanical helper surfaces in: - `polylogue/schemas/synthetic/build_batch.py` - `polylogue/schemas/synthetic/build_records.py` - `polylogue/schemas/synthetic/build_wire_formats.py` - `polylogue/schemas/synthetic/selection.py` - normalized schema sampling and cluster-payload handling in: - `polylogue/schemas/sampling_db.py` - `polylogue/schemas/sampling_sessions.py` - `polylogue/schemas/observation_identity.py` - `polylogue/schemas/tooling_registry.py` - added focused extraction/observation tests in `tests/unit/core/test_schema_extraction_runtime.py` ## Verification - `mypy polylogue/schemas/extraction.py polylogue/schemas/observation_models.py polylogue/schemas/observation_runtime.py polylogue/schemas/synthetic/core.py polylogue/schemas/synthetic/models.py polylogue/schemas/synthetic/relations.py polylogue/schemas/synthetic/relation_solver_runtime.py polylogue/schemas/synthetic/runtime.py polylogue/schemas/synthetic/build_batch.py tests/unit/core/test_schema_extraction_runtime.py` - `pytest -q tests/unit/core/test_schema_extraction_runtime.py tests/unit/core/test_sampling.py tests/unit/core/test_schema_generation.py tests/unit/core/test_synthetic_relations.py tests/unit/core/test_synthetic_semantics.py tests/unit/core/test_synthetic_semantic_wiring.py` - `mypy polylogue/schemas/observation_identity.py polylogue/schemas/sampling_db.py polylogue/schemas/sampling_sessions.py` - `pytest -q tests/unit/core/test_sampling.py tests/unit/core/test_schema_generation.py -k 'sampling or schema_generation'` - `mypy polylogue/schemas/tooling_registry.py tests/unit/core/test_schema_registry.py tests/unit/core/test_schema_cluster_assignment.py tests/integration/test_schema_operator_workflow.py` - `devtools verify` - push hook: `devtools verify --quick`
…265) The schema-side core was strict-type-clean, but high-churn seams were path-dependent and weakly modeled. Extraction mixed JSON-path walking, body fallback, timestamp / model / usage resolution, and harmonization through broad `object` values. Synthetic generation centered on a `SyntheticCorpus` shell that rebound imported helper functions and spread runtime state across loose helper protocols. DB/session sampling duplicated record-stream vs envelope logic instead of owning an explicit raw-row boundary. Mypy was green; the code was semantically underspecified. Introduces explicit extraction and observation records in `schemas/extraction.py`, `observation_models.py`, and `observation_runtime.py`. Renews the synthetic center of gravity in `schemas/synthetic/core.py`, `runtime.py`, `relation_solver_runtime.py`, and `relations.py` so `SyntheticCorpus` owns real runtime state and explicit methods rather than rebinding imported helpers. Follows the contracts through mechanical helpers (`build_batch.py`, `build_records.py`, `build_wire_formats.py`, `selection.py`). Normalizes schema sampling and cluster-payload handling in `sampling_db.py`, `sampling_sessions.py`, `observation_identity.py`, and `tooling_registry.py`. Adds focused extraction/observation tests in `test_schema_extraction_runtime.py`. Verification: mypy + pytest over schema extraction, sampling, synthetic, and tooling-registry suites; devtools verify green. Ref #261
…265) The schema-side core was strict-type-clean, but high-churn seams were path-dependent and weakly modeled. Extraction mixed JSON-path walking, body fallback, timestamp / model / usage resolution, and harmonization through broad `object` values. Synthetic generation centered on a `SyntheticCorpus` shell that rebound imported helper functions and spread runtime state across loose helper protocols. DB/session sampling duplicated record-stream vs envelope logic instead of owning an explicit raw-row boundary. Mypy was green; the code was semantically underspecified. Introduces explicit extraction and observation records in `schemas/extraction.py`, `observation_models.py`, and `observation_runtime.py`. Renews the synthetic center of gravity in `schemas/synthetic/core.py`, `runtime.py`, `relation_solver_runtime.py`, and `relations.py` so `SyntheticCorpus` owns real runtime state and explicit methods rather than rebinding imported helpers. Follows the contracts through mechanical helpers (`build_batch.py`, `build_records.py`, `build_wire_formats.py`, `selection.py`). Normalizes schema sampling and cluster-payload handling in `sampling_db.py`, `sampling_sessions.py`, `observation_identity.py`, and `tooling_registry.py`. Adds focused extraction/observation tests in `test_schema_extraction_runtime.py`. Verification: mypy + pytest over schema extraction, sampling, synthetic, and tooling-registry suites; devtools verify green. Ref #261
…265) The schema-side core was strict-type-clean, but high-churn seams were path-dependent and weakly modeled. Extraction mixed JSON-path walking, body fallback, timestamp / model / usage resolution, and harmonization through broad `object` values. Synthetic generation centered on a `SyntheticCorpus` shell that rebound imported helper functions and spread runtime state across loose helper protocols. DB/session sampling duplicated record-stream vs envelope logic instead of owning an explicit raw-row boundary. Mypy was green; the code was semantically underspecified. Introduces explicit extraction and observation records in `schemas/extraction.py`, `observation_models.py`, and `observation_runtime.py`. Renews the synthetic center of gravity in `schemas/synthetic/core.py`, `runtime.py`, `relation_solver_runtime.py`, and `relations.py` so `SyntheticCorpus` owns real runtime state and explicit methods rather than rebinding imported helpers. Follows the contracts through mechanical helpers (`build_batch.py`, `build_records.py`, `build_wire_formats.py`, `selection.py`). Normalizes schema sampling and cluster-payload handling in `sampling_db.py`, `sampling_sessions.py`, `observation_identity.py`, and `tooling_registry.py`. Adds focused extraction/observation tests in `test_schema_extraction_runtime.py`. Verification: mypy + pytest over schema extraction, sampling, synthetic, and tooling-registry suites; devtools verify green. Ref #261
There was a problem hiding this comment.
Pull request overview
Note
Copilot was unable to run its full agentic suite in this review.
Refactors schema extraction/observation and synthetic generation around explicit typed “record” boundaries, reducing loose object plumbing and consolidating runtime state in SyntheticCorpus.
Changes:
- Introduces resolved extraction/observation record models and routes payload sampling through typed cluster payload boundaries.
- Re-centers synthetic generation around
SyntheticCorpusruntime state instead of rebinding helper functions. - Normalizes sampling from DB and session JSONL sources to share clearer raw-row / record-stream boundaries.
Reviewed changes
Copilot reviewed 17 out of 17 changed files in this pull request and generated 5 comments.
Show a summary per file
| File | Description |
|---|---|
| tests/unit/core/test_schema_extraction_runtime.py | Adds focused unit coverage for message extraction and schema-unit observation. |
| polylogue/schemas/tooling_registry.py | Normalizes cluster payload input before computing schema cluster IDs. |
| polylogue/schemas/synthetic/selection.py | Tightens synthetic schema selection typing around SchemaVersionPackage and SchemaRecord. |
| polylogue/schemas/synthetic/runtime.py | Aligns runtime helper typing with SchemaValue / SchemaRecord and runtime protocols. |
| polylogue/schemas/synthetic/relations.py | Narrows relation solver schema parameter type to SchemaRecord. |
| polylogue/schemas/synthetic/relation_solver_runtime.py | Refactors annotation parsing into typed dataclass records and helpers. |
| polylogue/schemas/synthetic/models.py | Adds SyntheticGenerationState to hold relation/semantic generation runtime state. |
| polylogue/schemas/synthetic/core.py | Moves SyntheticCorpus away from rebinding helpers; adds explicit forwarding methods + state accessors. |
| polylogue/schemas/synthetic/build_wire_formats.py | Adds _record_field helper and simplifies wire-format record shaping. |
| polylogue/schemas/synthetic/build_records.py | Centralizes semantic generator reset/advance and tightens schema coercion typing. |
| polylogue/schemas/synthetic/build_batch.py | Tightens protocol return types and semantic generator typing. |
| polylogue/schemas/sampling_sessions.py | Factors session JSONL reading into a shared iterator used by both unit and sample iterators. |
| polylogue/schemas/sampling_db.py | Introduces typed DB row boundary and envelopes/record-stream unit extraction helpers. |
| polylogue/schemas/observation_runtime.py | Introduces explicit observation context + observed-unit records and a cleaner extraction flow. |
| polylogue/schemas/observation_models.py | Tightens ProviderConfig / SchemaUnit typing and exports cluster payload/granularity aliases. |
| polylogue/schemas/observation_identity.py | Narrows schema_cluster_id signature to typed SchemaClusterPayload. |
| polylogue/schemas/extraction.py | Refactors message extraction to a resolved-fields pipeline with explicit records. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| def _cluster_payload(sample: object) -> SchemaClusterPayload: | ||
| document = json_document(sample) | ||
| if document: | ||
| return document | ||
| documents = json_document_list(sample) | ||
| if documents: | ||
| return cast(SchemaClusterPayload, documents) | ||
| if sample is None or isinstance(sample, (str, int, float, bool)): | ||
| return sample | ||
| return None |
There was a problem hiding this comment.
json_document() / json_document_list() results are checked using truthiness (if document: / if documents:), which causes valid but empty payloads ({} / []) to be treated as “no payload” and coerced to None. That changes clustering behavior (empty object/list will now fingerprint as null/None instead of an empty structure). Prefer checking for is not None (or otherwise explicitly preserving empty dict/list) so empty-but-valid JSON values remain clusterable; adding a small unit test for {} and [] here would help prevent regressions.
| artifact_kinds[index] if artifact_kinds is not None and index < len(artifact_kinds) else "unspecified" | ||
| ) | ||
| cluster_id = schema_cluster_id(sample, artifact_kind) | ||
| cluster_id = schema_cluster_id(_cluster_payload(sample), artifact_kind) |
There was a problem hiding this comment.
json_document() / json_document_list() results are checked using truthiness (if document: / if documents:), which causes valid but empty payloads ({} / []) to be treated as “no payload” and coerced to None. That changes clustering behavior (empty object/list will now fingerprint as null/None instead of an empty structure). Prefer checking for is not None (or otherwise explicitly preserving empty dict/list) so empty-but-valid JSON values remain clusterable; adding a small unit test for {} and [] here would help prevent regressions.
| def _annotation_records(schema: SchemaRecord, key: str) -> tuple[SchemaRecord, ...]: | ||
| value = schema.get(key) | ||
| if not isinstance(value, list | tuple): | ||
| if not isinstance(value, list): | ||
| return () | ||
| return tuple(item for item in value if isinstance(item, dict)) | ||
|
|
||
|
|
||
| def _string_tuple(value: object) -> tuple[str, ...]: | ||
| if not isinstance(value, list | tuple): | ||
| if not isinstance(value, list): | ||
| return () | ||
| return tuple(str(item) for item in value) |
There was a problem hiding this comment.
This fixes the invalid isinstance(value, list | tuple) pattern (Python doesn’t allow unions in isinstance), but it also drops support for tuples entirely. If tuple-valued annotations can appear (e.g., constructed in Python rather than JSON-loaded), use isinstance(value, (list, tuple)) to preserve prior behavior while keeping the runtime check valid.
| msg = _record_field(data, "message") | ||
| msg.setdefault("id", str(uuid.UUID(int=rng.getrandbits(128), version=4))) | ||
|
|
||
| author = _record_field(msg, "author") | ||
| author.setdefault("role", role) | ||
|
|
||
| content = _record_field(msg, "content") | ||
| if "parts" not in content or not content["parts"]: | ||
| content["parts"] = [_text_for_role(rng, role, turn_index=index, theme=theme)] | ||
| content.setdefault("content_type", "text") | ||
|
|
||
| msg.setdefault("create_time", ts) | ||
| msg.setdefault("id", str(uuid.UUID(int=rng.getrandbits(128), version=4))) |
There was a problem hiding this comment.
msg.setdefault("id", ...) is executed twice, and the second call also burns additional RNG bits / UUID construction even though it won’t overwrite the first value. Removing the duplicate setdefault reduces redundant work and avoids subtle “why is this here?” confusion for future readers.
| records_by_path: dict[Path, list[JSONDocument]] = {} | ||
| for path, record in _iter_session_json_documents(session_dir, max_sessions=max_sessions): | ||
| records_by_path.setdefault(path, []).append(record) | ||
|
|
||
| for path, records in records_by_path.items(): |
There was a problem hiding this comment.
This refactor now accumulates all parsed JSONL records for all selected session files in memory before yielding any schema units. Previously, each file was processed independently (memory bounded to one file at a time). Consider iterating file-by-file (e.g., have _iter_session_json_documents yield per-file iterators, or have _iter_schema_units_from_sessions re-open and process each chosen file directly) to keep peak memory bounded and improve latency for large session corpora.
|
Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.
Only the rows listed above are dispositioned. Held findings remain open. |
Ref #261
Summary
SyntheticCorpusowns real runtime state and explicit methods rather than rebinding imported helpersProblem
The schema-side core was strict-type-clean, but several high-churn seams were still path-dependent and weakly modeled. Extraction mixed JSON-path walking, body fallback, timestamp/model/usage resolution, and harmonization through broad
objectvalues. Synthetic generation centered on aSyntheticCorpusshell that rebound imported helper functions and spread runtime state across loose helper protocols. DB/session sampling still duplicated record-stream versus envelope logic instead of owning an explicit raw-row boundary.That left the code semantically underspecified even though mypy was green.
Solution
polylogue/schemas/extraction.pypolylogue/schemas/observation_models.pypolylogue/schemas/observation_runtime.pypolylogue/schemas/synthetic/core.pypolylogue/schemas/synthetic/runtime.pypolylogue/schemas/synthetic/relation_solver_runtime.pypolylogue/schemas/synthetic/relations.pypolylogue/schemas/synthetic/build_batch.pypolylogue/schemas/synthetic/build_records.pypolylogue/schemas/synthetic/build_wire_formats.pypolylogue/schemas/synthetic/selection.pypolylogue/schemas/sampling_db.pypolylogue/schemas/sampling_sessions.pypolylogue/schemas/observation_identity.pypolylogue/schemas/tooling_registry.pytests/unit/core/test_schema_extraction_runtime.pyVerification
mypy polylogue/schemas/extraction.py polylogue/schemas/observation_models.py polylogue/schemas/observation_runtime.py polylogue/schemas/synthetic/core.py polylogue/schemas/synthetic/models.py polylogue/schemas/synthetic/relations.py polylogue/schemas/synthetic/relation_solver_runtime.py polylogue/schemas/synthetic/runtime.py polylogue/schemas/synthetic/build_batch.py tests/unit/core/test_schema_extraction_runtime.pypytest -q tests/unit/core/test_schema_extraction_runtime.py tests/unit/core/test_sampling.py tests/unit/core/test_schema_generation.py tests/unit/core/test_synthetic_relations.py tests/unit/core/test_synthetic_semantics.py tests/unit/core/test_synthetic_semantic_wiring.pymypy polylogue/schemas/observation_identity.py polylogue/schemas/sampling_db.py polylogue/schemas/sampling_sessions.pypytest -q tests/unit/core/test_sampling.py tests/unit/core/test_schema_generation.py -k 'sampling or schema_generation'mypy polylogue/schemas/tooling_registry.py tests/unit/core/test_schema_registry.py tests/unit/core/test_schema_cluster_assignment.py tests/integration/test_schema_operator_workflow.pydevtools verifydevtools verify --quick