Skip to content

refactor: rebuild schema, source, and ingestion boundary contracts - #275

Merged
Sinity merged 5 commits into
masterfrom
feature/refactor/schema-source-ingestion-boundaries
Apr 20, 2026
Merged

Sinity merged 5 commits into
masterfrom
feature/refactor/schema-source-ingestion-boundaries

Conversation

@Sinity

@Sinity Sinity commented Apr 20, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • centralize runtime schema resolution around package catalogs and payload observations
  • rebuild source dispatch and Drive ingestion boundaries around shared typed helpers
  • collapse ingest worker and batch runtime argument threading into explicit plan/request contracts

Problem

The oldest schema/source/ingestion stratum still carried the strongest path dependence in the archive substrate: dict-shaped payload flow, duplicated source helper logic, repeated schema resolution across validation and parsing, and loose runtime seams around Drive and ingest-worker dispatch. That made the code harder to reason about and left behavior spread across too many small branches.

Closes #271.

Solution

  • rebuilt polylogue/schemas/runtime_registry.py to resolve payloads across observed schema units instead of whichever element happened to be first, with explicit candidate ranking and richer resolution metadata
  • strengthened polylogue/schemas/observation_runtime.py, polylogue/schemas/packages.py, polylogue/schemas/unified.py, polylogue/schemas/validator_resolution.py, and polylogue/storage/artifact_inspection.py so schema loading, payload extraction, and artifact inspection all consume the same runtime resolution contract
  • rewrote polylogue/sources/dispatch.py as an explicit lowering pipeline for bundle, grouped, stream, and Drive-like payloads instead of a path-dependent chain of special cases
  • introduced an explicit retry-policy boundary for Drive runtime construction in polylogue/sources/drive_gateway.py, polylogue/sources/drive_types.py, and polylogue/sources/drive_source_factory.py
  • collapsed repeated Drive cursor/failure bookkeeping into shared helpers in polylogue/sources/drive.py, polylogue/sources/drive_source_client.py, and polylogue/sources/drive_source_support.py
  • moved the ingest runtime onto explicit parse-plan and worker-request contracts in polylogue/pipeline/services/ingest_worker.py and polylogue/pipeline/services/ingest_batch.py, so schema resolution is computed once and reused instead of being rediscovered deeper in the parse path
  • restored validator fallback compatibility for lightweight/latest-only registries while keeping the new package-backed resolution path in place

Verification

  • pytest -q tests/unit/core/test_schema_extraction_runtime.py tests/unit/core/test_schema_validation.py tests/unit/core/test_schema_registry.py
  • mypy polylogue/schemas/packages.py polylogue/schemas/observation_runtime.py polylogue/schemas/runtime_registry.py
  • ruff check polylogue/schemas/packages.py polylogue/schemas/observation_runtime.py polylogue/schemas/runtime_registry.py
  • pytest -q tests/unit/sources/test_source_laws.py -k 'parse_payload or parse_drive_payload or detect_provider or conversation_emitter_resolves_schema_for_payloads'
  • mypy polylogue/sources/dispatch.py polylogue/schemas/validator_resolution.py polylogue/storage/artifact_inspection.py polylogue/schemas/unified.py
  • pytest -q tests/unit/sources/test_source_laws.py tests/unit/core/test_synthetic_semantics.py tests/unit/core/test_verification.py
  • mypy polylogue/pipeline/services/ingest_worker.py polylogue/sources/drive_types.py polylogue/sources/drive_gateway.py polylogue/sources/drive_source_factory.py polylogue/sources/drive.py
  • pytest -q tests/unit/pipeline/test_resilience.py -k 'schema_resolution or streams_codex_jsonl or ingest_worker'
  • pytest -q tests/unit/sources/test_drive_gateway.py tests/unit/sources/test_drive_source_client.py tests/unit/sources/test_drive_ops.py tests/unit/sources/test_source_laws.py -k 'iter_drive_conversations or iter_drive_raw_data or download_drive_files or resolve_retries or retry_base or retry_policy or call_with_retry or service_handle or download_file or resolve_folder_id or download_json_payload or download_to_path'
  • pytest -q tests/unit/pipeline/test_ingest_batch.py -k 'iter_ingest_results_sync or select_ingest_worker_count'
  • pytest -q tests/unit/core/test_schema_validation.py -k 'missing_provider_raises or prefers_registry_latest'
  • devtools verify
  • git push -u origin feature/refactor/schema-source-ingestion-boundaries (pre-push hook runs devtools verify --quick)

@coderabbitai

ghost commented Apr 20, 2026

Copy link
Copy Markdown

Warning

Rate limit exceeded

@Sinity has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 8 minutes and 2 seconds before requesting another review.

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 8 minutes and 2 seconds.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 2498088f-e6aa-4223-adaf-97a41ee053d9

📥 Commits

Reviewing files that changed from the base of the PR and between 046d6eb and 7b07ae0.

📒 Files selected for processing (20)
  • polylogue/pipeline/services/ingest_batch.py
  • polylogue/pipeline/services/ingest_worker.py
  • polylogue/schemas/observation_runtime.py
  • polylogue/schemas/packages.py
  • polylogue/schemas/runtime_registry.py
  • polylogue/schemas/unified.py
  • polylogue/schemas/validator_resolution.py
  • polylogue/sources/dispatch.py
  • polylogue/sources/drive.py
  • polylogue/sources/drive_gateway.py
  • polylogue/sources/drive_source.py
  • polylogue/sources/drive_source_client.py
  • polylogue/sources/drive_source_factory.py
  • polylogue/sources/drive_source_support.py
  • polylogue/sources/drive_types.py
  • polylogue/storage/artifact_inspection.py
  • tests/unit/core/test_schema_annotation_contracts.py
  • tests/unit/core/test_schema_registry_versions.py
  • tests/unit/pipeline/test_ingest_batch.py
  • tests/unit/sources/test_drive_gateway.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/refactor/schema-source-ingestion-boundaries

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7b07ae08c4

ℹ️ 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".

@Sinity
Sinity merged commit 90fef43 into master Apr 20, 2026
@Sinity
Sinity deleted the feature/refactor/schema-source-ingestion-boundaries branch April 20, 2026 12:32
@Sinity

ghost commented Apr 28, 2026

Copy link
Copy Markdown
Owner Author

🤖 Post-hoc audit note: this PR received bot review feedback verified against current HEAD as part of #544. 1 finding(s) confirmed still present → tracked in #550.

ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Note

Copilot was unable to run its full agentic suite in this review.

Refactors schema resolution, source dispatch, and ingestion boundaries to use shared typed contracts, reducing duplicated logic and making runtime behavior more explicit and reusable.

Changes:

  • Introduces package-backed schema resolution with ranked candidates and richer SchemaResolution metadata.
  • Rebuilds Drive ingestion retry and cursor bookkeeping around explicit policy/helpers.
  • Threads schema resolution and ingest runtime arguments through explicit parse-plan / worker-request contracts.

Reviewed changes

Copilot reviewed 20 out of 20 changed files in this pull request and generated 4 comments.

Show a summary per file
File Description
tests/unit/sources/test_drive_gateway.py Updates Drive gateway tests for the new retry-policy contract.
tests/unit/pipeline/test_ingest_batch.py Adapts ingest batch tests to the new worker-request contract.
tests/unit/core/test_schema_registry_versions.py Makes registry version tests more type/shape defensive.
tests/unit/core/test_schema_annotation_contracts.py Broadens schema annotation walking to accept Mapping and updates schema type.
polylogue/storage/artifact_inspection.py Replaces tuple return with SchemaResolution contract for inspection/support checks.
polylogue/sources/drive_types.py Adds DriveRetryPolicy dataclass to formalize retry configuration.
polylogue/sources/drive_source_support.py Extracts shared Drive response/record helpers for client parsing.
polylogue/sources/drive_source_factory.py Uses the new resolve_drive_retry_policy helper when constructing the gateway.
polylogue/sources/drive_source_client.py Consumes shared Drive helpers instead of local static methods.
polylogue/sources/drive_source.py Re-exports the new retry policy resolver from the Drive source API surface.
polylogue/sources/drive_gateway.py Introduces DriveRetryPolicy and centralized policy resolution; updates retry usage.
polylogue/sources/drive.py Consolidates cursor/failure bookkeeping into _DriveCursorTracker helpers.
polylogue/sources/dispatch.py Reworks payload lowering into explicit pipeline helpers; improves Drive-like handling.
polylogue/schemas/validator_resolution.py Rebuilds schema loading around package elements with a fallback for “latest-only” registries.
polylogue/schemas/unified.py Switches schema extraction to resolve_payload_schema instead of re-resolving via registry calls.
polylogue/schemas/runtime_registry.py Rebuilds runtime payload resolution: multi-observation candidate ranking + metadata.
polylogue/schemas/packages.py Extends SchemaResolution with typed reason and optional profile score; adds bundle-scope helper.
polylogue/schemas/observation_runtime.py Enriches profile token generation and bounds token growth.
polylogue/pipeline/services/ingest_worker.py Moves schema resolution into parse-plan construction and reuses it during validation/parsing.
polylogue/pipeline/services/ingest_batch.py Introduces _IngestWorkerRequest and uses a shared helper for worker execution submission.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines 117 to +139
registry = _registry_for(registry_cls)
resolution = schema_resolution
if resolution is None:
resolution = (
registry.resolve_payload(
str(canonical),
payload,
source_path=source_path,
)
if hasattr(registry, "resolve_payload")
else None
)
package_version = resolution.package_version if resolution is not None else "latest"
element_kind = resolution.element_kind if resolution is not None else "default"

if hasattr(registry, "get_element_schema"):
schema = registry.get_element_schema(
resolution = registry.resolve_payload(
str(canonical),
version=package_version,
element_kind=None if element_kind == "default" else element_kind,
payload,
source_path=source_path,
)

if resolution is None:
package = _load_package(registry, canonical, version="default")
package_version = package.version
element_kind = package.default_element_kind
else:
schema = registry.get_schema(str(canonical), version=package_version)
if schema is None:
raise FileNotFoundError(
"No schema found for provider: "
f"{provider} (canonical: {canonical}, package: {package_version}, element: {element_kind})"
)
package_version = resolution.package_version
element_kind = resolution.element_kind

schema = _load_schema(
registry,
canonical,
package_version=package_version,
element_kind=element_kind,
)

Copilot AI May 1, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

resolve_payload_schema no longer guards for registries that don’t implement resolve_payload / package element APIs. This will raise AttributeError for “latest-only/lightweight” registries (which the PR description says should remain compatible). Fix by mirroring the defensive checks used in resolve_provider_schema: if resolve_payload is missing, skip resolution; if get_package / get_element_schema are missing, fall back to get_schema(..., version='latest'/'default') and return consistent metadata.

Copilot uses AI. Check for mistakes.
Comment on lines +91 to +95
if not hasattr(registry, "get_package"):
schema = _load_latest_schema(registry, canonical)
if schema is None:
raise FileNotFoundError(f"No schema found for provider: {canonical}")
return canonical, schema, (str(canonical), "latest", "conversation_document")

Copilot AI May 1, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When _load_latest_schema falls back to version='default', the returned metadata still hard-codes ('latest', 'conversation_document'), which can mislabel the resolved schema (and may confuse downstream logging/telemetry). Consider having _load_latest_schema report which version key was used (latest vs default) and propagate that into the returned tuple; similarly, avoid hard-coding conversation_document if the fallback registry doesn’t provide element-kind semantics.

Copilot uses AI. Check for mistakes.
Comment on lines +415 to 424
return _build_parse_plan(
provider=detected_provider,
payload_provider=str(detected_provider),
artifact=artifact,
source_path=context.raw_record.source_path,
mode="stream",
schema_payload=sample_payloads if artifact.schema_eligible else None,
schema_payload_source=sample_payloads,
stream_name=stream_name,
malformed_jsonl_lines=malformed_lines,
malformed_jsonl_detail=malformed_detail,

Copilot AI May 1, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The stream parse plan construction no longer passes the actual stream payload into the plan (payload=...). Since _parse_plan_conversations dispatches based on plan.mode and uses plan.payload for parsing, this risks parse_stream_payload(..., plan.payload, ...) receiving None or stale data. Fix by explicitly threading the decoded stream payload into _build_parse_plan(..., payload=<stream payload>) and keeping schema_payload_source reserved for validation samples if that’s the intent.

Copilot uses AI. Check for mistakes.
Comment on lines +514 to +519
def _package_rank(self, catalog: SchemaPackageCatalog) -> dict[str, int]:
ranked = sorted(catalog.packages, key=lambda package: _package_rank_key(catalog, package))
return {package.version: index for index, package in enumerate(ranked)}

def _ranked_packages(self, catalog: SchemaPackageCatalog) -> list[SchemaVersionPackage]:
return sorted(catalog.packages, key=lambda package: _package_rank_key(catalog, package))

Copilot AI May 1, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Package ordering is computed twice (once for _package_rank and again for _ranked_packages) using the same sort key. This adds avoidable overhead on every resolve_payload call. Consider computing the ranked list once in resolve_payload and deriving the rank mapping from it, or having _package_rank return both (ranked_packages, rank_map).

Copilot uses AI. Check for mistakes.
@Sinity

ghost commented Oct 1, 2026

Copy link
Copy Markdown
Owner Author

Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.

  • 71.F026 / P2: fixed-already at the checked revision: polylogue/schemas/validator_resolution.py:147 detects registries without resolve_payload and loads their named schema instead. It returns that schema at line 152, so a get_schema-only injected registry no longer raises AttributeError on the payload-resolution route.

Only the rows listed above are dispositioned. Held findings remain open.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

refactor: rebuild schema, source, and ingestion boundary contracts

2 participants