Skip to content

refactor: renew session product runtime and storage seams - #230

Merged
Sinity merged 6 commits into
masterfrom
feature/refactor/storage-lib-product-renewal-v2
Apr 19, 2026
Merged

Sinity merged 6 commits into
masterfrom
feature/refactor/storage-lib-product-renewal-v2

Conversation

@Sinity

@Sinity Sinity commented Apr 19, 2026 •

Copy link
Copy Markdown
Owner

Ref #225

Summary

  • move session-product payload surfaces onto shared typed models and direct query-model registry wiring
  • rewrite the session-product materialization runtime around typed batch, bundle, and refresh-observation contracts
  • collapse duplicated session-product sync/async write assembly and tighten provider-day aggregate refresh on top of the unified writer seam

Problem

The session-product layer was still split across path-dependent seams: archive product payloads were drifting between dict-shaped records and model-backed products, product registry dispatch still relied on dynamic query resolution, refresh/rebuild used tuple- and dict-shaped runtime plumbing, and the async writer/query modules were cloning the sync storage layer’s insert assembly. That left the storage/product runtime technically type-checked but still ambiguous and duplicated at the exact points where the archive materializes durable products.

Solution

  • extract shared archive product payload/base models into polylogue/archive_product_models.py and propagate those typed payloads through archive products, mappers, records, writers, and affected tests
  • rewrite polylogue/products/registry.py to use direct query-model references, immutable descriptor tuples, and typed nested field access, then adapt the CLI, MCP, and scenario surfaces to that contract
  • rebuild polylogue/storage/session_product_rebuild.py and polylogue/storage/session_product_refresh.py around SessionProductArchiveBatch, SessionProductRecordBundle, and SessionProductRefreshChunkObservation, and update polylogue/pipeline/services/ingest_batch.py to consume that typed refresh telemetry instead of dict-key probing
  • extract shared insert-column/value builders into polylogue/storage/session_product_storage.py, route the async profile/timeline/thread/summary writers through those helpers, and simplify polylogue/storage/session_product_aggregates.py so sync and async provider-day refresh paths apply the same prepared aggregate writes
  • absorb the direct fallout in affected tests, including the small compaction assertion update revealed by the repo-wide verify pass

Verification

  • ruff check polylogue/storage/session_product_rebuild.py polylogue/storage/session_product_refresh.py polylogue/pipeline/services/ingest_batch.py tests/unit/storage/test_session_product_refresh.py tests/unit/pipeline/test_ingest_batch.py
  • python -m mypy polylogue/storage/session_product_rebuild.py polylogue/storage/session_product_refresh.py polylogue/pipeline/services/ingest_batch.py tests/unit/storage/test_session_product_refresh.py tests/unit/pipeline/test_ingest_batch.py tests/unit/pipeline/test_run_sources.py tests/unit/storage/test_product_materialization_laws.py tests/unit/cli/test_products.py tests/unit/core/test_facade_api.py tests/unit/cli/test_check.py tests/unit/storage/test_backend.py tests/unit/sources/test_compaction.py
  • pytest -q tests/unit/storage/test_session_product_refresh.py tests/unit/pipeline/test_ingest_batch.py tests/unit/pipeline/test_run_sources.py
  • pytest -q tests/unit/storage/test_product_materialization_laws.py tests/unit/cli/test_products.py tests/unit/core/test_facade_api.py tests/unit/cli/test_check.py tests/unit/storage/test_backend.py tests/unit/sources/test_compaction.py
  • devtools verify

@coderabbitai

coderabbitai Bot commented Apr 19, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

A comprehensive refactoring introduces shared Pydantic-based archive product payload models in a new module, relocates model definitions from distributed files, and replaces untyped dict[str, Any] annotations throughout the storage, registry, and product layers with strongly-typed Pydantic models. SQL INSERT helpers are extracted to a centralized storage module, and record dataclasses are restructured to use typed bundles instead of tuple unpacking.

Changes

Cohort / File(s) Summary
New Shared Contract Module
polylogue/archive_product_models.py
Introduces ARCHIVE_PRODUCT_CONTRACT_VERSION = 4 and defines frozen Pydantic ArchiveProductModel base with extra="ignore". Declares provenance models (ArchiveProductProvenance, ArchiveInferenceProvenance, ArchiveEnrichmentProvenance) and typed payload models for evidence/inference/enrichment across sessions, work events, phases, threads, and day/week summaries with explicit defaults for counters, collections, and dict fields.
Core Model Imports & Type Updates
polylogue/archive_products.py, polylogue/products/registry.py
Removes local Pydantic model definitions and imports from archive_product_models. Updates ProductType from string-based descriptors (query_class_path, operations_method) to typed descriptors (query_model, operations_method_name). Narrows product field types: WorkThreadProduct.thread, DaySessionSummaryProduct.summary, WeekSessionSummaryProduct.summary from dict[str, Any] to specific typed payloads. Replaces dynamic query resolution with direct model instantiation in _build_query.
Storage Record Type Updates
polylogue/storage/store_product_session_records.py, polylogue/storage/store_product_timeline_records.py, polylogue/storage/store_product_aggregate_records.py
Updates record dataclass field annotations from dict[str, Any] to typed Pydantic models: SessionProfileRecord payload fields, WorkThreadRecord.payload, timeline record payloads (SessionWorkEventRecord, SessionPhaseRecord), and aggregate record payloads (DaySessionSummaryRecord).
Payload Construction & Validation
polylogue/storage/session_product_profiles.py, polylogue/storage/session_product_timeline_rows.py, polylogue/storage/session_product_threads.py
Changes payload construction to validate via *.model_validate(...) instead of returning raw dicts. Updates function signatures to return typed payloads (SessionEvidencePayload, SessionInferencePayload, SessionEnrichmentPayload, WorkEventEvidencePayload, WorkEventInferencePayload, SessionPhaseEvidencePayload, SessionPhaseInferencePayload, WorkThreadPayload). Updates payload access from dict .get(...) to model attributes.
Mapper & Query Updates
polylogue/storage/backends/queries/mappers_product_profiles.py, polylogue/storage/backends/queries/mappers_product_aggregates.py, polylogue/storage/backends/queries/mappers_product_timelines.py
Updates payload mapping by wrapping parsed JSON with typed model validation (*.model_validate(...)). Handles legacy fallback dict construction and validation for missing payloads. Ensures all stored payloads are validated/typed model objects rather than raw dicts.
SQL Helper Extraction
polylogue/storage/session_product_storage.py
Introduces centralized *_insert_columns(...) and *_insert_values(...) helpers for session profiles, work events, phases, and summary records. Handles legacy payload_json column detection and serialization via model_dump(mode="json") for Pydantic models. Exports new helpers for use across query modules.
Query Module Refactoring
polylogue/storage/backends/queries/session_product_profile_writes.py, polylogue/storage/backends/queries/session_product_timeline_writes.py, polylogue/storage/backends/queries/session_product_thread_queries.py, polylogue/storage/backends/queries/session_product_summary_queries.py
Delegates INSERT column/value construction to centralized helpers from session_product_storage. Removes inline JSON serialization and legacy payload merging logic. Simplifies per-table write operations while maintaining control flow and commit behavior.
Batch & Bundle Refactoring
polylogue/storage/session_product_rebuild.py, polylogue/storage/session_product_refresh.py
Introduces typed dataclasses: SessionProductArchiveBatch (replaces 4-tuple from batch loading), SessionProductRecordBundle (replaces (profile_record, work_event_records, phase_records) tuple with convenience properties), and SessionProductRefreshChunkObservation (replaces raw dict chunk observations). Updates hydration/build flow to work with bundle objects and typed chunk observations with to_observation() method.
Registry & Product Accessor Updates
polylogue/products/registry.py
Replaces inline lambda/hasattr/dict-guard accessor patterns with typed helpers (_formatted_float, _count_with_percentage, _attr, _nested, _id_with_provider, _list_preview). Changes _model_payload to use isinstance(item, BaseModel) instead of hasattr(model_dump). Updates field rendering to use variable field instead of f. Changes list/tuple types for fields and cli_options from list to tuple.
CLI & MCP Updates
polylogue/cli/commands/products.py, polylogue/mcp/server_product_tools.py
Removes Pydantic-based query resolution; uses pt.query_model directly. Tightens type annotations from Any to object. Simplifies click.Option construction. Updates offset sanitization for type coercion. Changes product serialization to always call model_dump(mode="json").
Scenario & Pipeline Updates
polylogue/scenarios/execution.py, polylogue/pipeline/services/ingest_batch.py
Updates product type indexing from operations_method to operations_method_name. Changes chunk handling from dict-like list to typed SessionProductRefreshChunkObservation objects with direct attribute access (chunk.total_ms, chunk.slow, etc.) and chunk.to_observation() method.
Summary & Archive Updates
polylogue/archive_product_summaries.py
Updates day/week summary payload construction to validate via typed models: DaySessionSummaryPayload.model_validate(...) and WeekSessionSummaryPayload.model_validate(...).
Test Updates
tests/unit/core/test_facade_api.py, tests/unit/core/test_repo_identity.py, tests/unit/mcp/test_tool_contracts.py, tests/unit/pipeline/test_ingest_batch.py, tests/unit/sources/test_compaction.py, tests/unit/storage/test_session_product_profiles.py, tests/unit/storage/test_session_product_refresh.py, tests/unit/storage/test_session_product_timeline_rows.py
Updates assertions and test data construction to use attribute access instead of dict indexing on typed payload models. Updates test mocks to construct typed payload objects instead of raw dicts. Updates chunk observation handling to use typed SessionProductRefreshChunkObservation.
Internal Utility Updates
polylogue/storage/store.py
Extends _json_or_none to accept pydantic.BaseModel or Mapping[str, object] and serializes BaseModel via model_dump(mode="json").

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested labels

area:storage, area:cli, area:pipeline, refactor, type-safety

Poem

🐰 Dicts gave way to Pydantic's grace,
Types now dance through every place,
Bundles bundled, payloads typed,
Storage helpers now standardized,
Stronger contracts, cleaner sight,
The rabbit's refactor feels just right! ✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 14.49% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and specifically describes the main refactoring objective: renewing session product runtime and storage seams by consolidating type contracts and materialization patterns.
Description check ✅ Passed The pull request description is well-structured, covering Summary, Problem, Solution, Verification, and Risks sections as required by the template. All critical sections are completed with sufficient detail.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/refactor/storage-lib-product-renewal-v2

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.

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 8

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
polylogue/storage/session_product_rebuild.py (1)

458-464: ⚠️ Potential issue | 🟠 Major

Treat an empty targeted rebuild as a no-op.

When conversation_ids=[], this currently clears global read models (work_threads, phases, rollups, summaries) while leaving unrelated session profiles/work events in place. That can corrupt the derived product state for a caller that intended to rebuild zero conversations.

🐛 Proposed fix
@@
     if conversation_ids is not None and not conversation_ids:
-        conn.execute("DELETE FROM work_threads")
-        conn.execute("DELETE FROM session_phases")
-        conn.execute("DELETE FROM session_tag_rollups")
-        conn.execute("DELETE FROM day_session_summaries")
-        conn.commit()
         return _empty_rebuild_counts()
@@
     elif not conversation_ids:
-        await conn.execute("DELETE FROM work_threads")
-        await conn.execute("DELETE FROM session_phases")
-        await conn.execute("DELETE FROM session_tag_rollups")
-        await conn.execute("DELETE FROM day_session_summaries")
         return _empty_rebuild_counts()

Also applies to: 557-562

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/storage/session_product_rebuild.py` around lines 458 - 464, The
current check "if conversation_ids is not None and not conversation_ids:" treats
an explicit empty list as a request to clear global read models; instead make an
explicit-empty-target a no-op by returning _empty_rebuild_counts() immediately
without executing the DELETEs or committing; update the same pattern at the
other occurrence (the second block with the same condition around
session_product_rebuild logic) so both places treat conversation_ids=[] as a
no-op and leave work_threads, session_phases, session_tag_rollups, and
day_session_summaries untouched.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@polylogue/archive_product_models.py`:
- Around line 10-18: The ArchiveProductModel is frozen at the top-level but
nested dict fields remain mutable; update the model so the listed mutable fields
(tool_categories, work_events, phases, tool_counts, input_band_summary,
work_event_breakdown, providers) are converted to immutable structures on
initialization (e.g., wrap dicts with types.MappingProxyType, convert nested
dicts to typed BaseModel mappings, or perform a recursive deep-freeze in a
model_post_init/model_validator) so consumers cannot mutate their contents;
implement the conversion in ArchiveProductModel (or per-field nested models) to
ensure deep immutability for those specific attributes.

In `@polylogue/mcp/server_product_tools.py`:
- Around line 54-61: The offset coercion block currently calls int(offset_value)
on str/bytes/bytearray and can raise ValueError for malformed inputs; update the
branch that handles (int, str, bytes, bytearray) to try converting with int(...)
inside a try/except (catching ValueError and TypeError) and on exception set
kwargs["offset"] = 0 (or clamp negative results to 0 as already done), so
malformed strings/bytes degrade to 0 instead of raising; locate and modify the
offset handling code that checks "if 'offset' in kwargs" and the branch setting
kwargs["offset"] accordingly.
- Around line 41-46: The loop over query_model.model_fields currently checks "if
finfo.default is not None" which misidentifies Pydantic-required fields
(PydanticUndefined) and can store that sentinel into field_defaults; change the
logic to use finfo.is_required() (call on the finfo object) so that when
finfo.is_required() is True you set field_defaults[fname] = None (not the
sentinel), otherwise use the existing finfo.default; keep field_annotations
assignment as-is using finfo.annotation or object to locate and update the block
that references fname, finfo, query_model.model_fields, field_defaults, and
field_annotations.

In `@polylogue/products/registry.py`:
- Around line 359-365: The ProductField currently uses
_nested("inference","kind") which is invalid because
SessionPhaseInferencePayload does not expose kind; update the accessor so the
kind is read from an actual stored attribute (or ensure SessionPhaseProduct
preserves record.kind and expose that) — either change the ProductField("kind",
...) to point at the real product attribute that holds the phase kind (e.g., the
top-level attribute name used on SessionPhaseProduct) or modify
SessionPhaseProduct to keep record.kind and then render that field; adjust the
ProductField declaration in the fields tuple accordingly (replace
_nested("inference","kind") with the correct attribute accessor or
preserve/forward kind in SessionPhaseProduct).

In `@polylogue/storage/backends/queries/mappers_product_aggregates.py`:
- Around line 58-65: The mapper currently calls
DaySessionSummaryPayload.model_validate(... ) with an empty dict fallback (the
"or {}") which causes pydantic ValidationError for NULL/empty payload_json;
change this to either (a) remove the "or {}" so model_validate receives None
failure explicitly if schema guarantees non-null, or (b) if payload_json may be
absent, capture the result of _parse_json(row["payload_json"],
field="payload_json", record_id=f"{row['provider_name']}:{row['day']}") into a
variable and if it is None raise a DatabaseError including the same record id
(f"{row['provider_name']}:{row['day']}") before calling
DaySessionSummaryPayload.model_validate(payload), so validation errors are
wrapped as DatabaseError consistently.

In `@polylogue/storage/backends/queries/mappers_product_profiles.py`:
- Around line 30-139: The current checks treat an empty dict JSON payload as
missing and rebuild defaults; change the three conditionals that inspect
raw_evidence_payload, raw_inference_payload, and raw_enrichment_payload to use
"is not None" (or "raw_... is not None") instead of truthiness so {} is accepted
as a present payload for SessionEvidencePayload.model_validate,
SessionInferencePayload.model_validate, and
SessionEnrichmentPayload.model_validate; keep using _parse_json and _row_get as
before and only fall back to the legacy construction when the parsed raw_* is
None.

In `@polylogue/storage/backends/queries/mappers_product_timelines.py`:
- Around line 28-68: When raw_*_payload exists, don’t pass it straight to
WorkEventEvidencePayload.model_validate or
WorkEventInferencePayload.model_validate; instead build the same defaults
currently used in the else-branch (using _row_get, legacy_payload, parsing JSON
for file_paths/tools_used, converting numeric fields) and merge the JSON dict on
top of those defaults (JSON values override defaults) before calling
model_validate; apply this change for raw_evidence_payload and
raw_inference_payload in _row_to_work_event_record (and mirror the same pattern
in _row_to_session_phase_record and the corresponding functions in
mappers_product_profiles.py) so partial JSON blobs are complemented by
column/legacy defaults before validation.

In `@polylogue/storage/session_product_threads.py`:
- Around line 128-134: The WorkThreadPayload schema is missing fields so
build_work_thread_record calls
WorkThreadPayload.model_validate(thread.to_dict()) and Pydantic drops thread_id,
root_id and provider_breakdown causing data loss; update the WorkThreadPayload
model to include thread_id: str, root_id: str, and provider_breakdown: dict[str,
int] with a default factory (e.g., Field(default_factory=dict)) so that
hydrate_work_thread and WorkThread.from_dict() receive the full payload and
identifiers are preserved.

---

Outside diff comments:
In `@polylogue/storage/session_product_rebuild.py`:
- Around line 458-464: The current check "if conversation_ids is not None and
not conversation_ids:" treats an explicit empty list as a request to clear
global read models; instead make an explicit-empty-target a no-op by returning
_empty_rebuild_counts() immediately without executing the DELETEs or committing;
update the same pattern at the other occurrence (the second block with the same
condition around session_product_rebuild logic) so both places treat
conversation_ids=[] as a no-op and leave work_threads, session_phases,
session_tag_rollups, and day_session_summaries untouched.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: c67fe6e2-c64e-4bf5-976c-e197b31c25eb

📥 Commits

Reviewing files that changed from the base of the PR and between 130c1fa and ba9a7b7.

📒 Files selected for processing (34)
  • polylogue/archive_product_models.py
  • polylogue/archive_product_summaries.py
  • polylogue/archive_products.py
  • polylogue/cli/commands/products.py
  • polylogue/mcp/server_product_tools.py
  • polylogue/pipeline/services/ingest_batch.py
  • polylogue/products/registry.py
  • polylogue/scenarios/execution.py
  • polylogue/storage/backends/queries/mappers_product_aggregates.py
  • polylogue/storage/backends/queries/mappers_product_profiles.py
  • polylogue/storage/backends/queries/mappers_product_timelines.py
  • polylogue/storage/backends/queries/session_product_profile_writes.py
  • polylogue/storage/backends/queries/session_product_summary_queries.py
  • polylogue/storage/backends/queries/session_product_thread_queries.py
  • polylogue/storage/backends/queries/session_product_timeline_writes.py
  • polylogue/storage/session_product_aggregates.py
  • polylogue/storage/session_product_profiles.py
  • polylogue/storage/session_product_rebuild.py
  • polylogue/storage/session_product_refresh.py
  • polylogue/storage/session_product_storage.py
  • polylogue/storage/session_product_threads.py
  • polylogue/storage/session_product_timeline_rows.py
  • polylogue/storage/store.py
  • polylogue/storage/store_product_aggregate_records.py
  • polylogue/storage/store_product_session_records.py
  • polylogue/storage/store_product_timeline_records.py
  • tests/unit/core/test_facade_api.py
  • tests/unit/core/test_repo_identity.py
  • tests/unit/mcp/test_tool_contracts.py
  • tests/unit/pipeline/test_ingest_batch.py
  • tests/unit/sources/test_compaction.py
  • tests/unit/storage/test_session_product_profiles.py
  • tests/unit/storage/test_session_product_refresh.py
  • tests/unit/storage/test_session_product_timeline_rows.py

Comment on lines +10 to +18
class ArchiveProductModel(BaseModel):
"""Shared base for public archive data product payloads."""

# extra="ignore" tolerates legacy fields from older materialized records
# (e.g. primary_work_kind, decisions removed in the March 2026 cleanup)
model_config = ConfigDict(extra="ignore", frozen=True)

def to_json(self, *, exclude_none: bool = False) -> str:
return self.model_dump_json(indent=2, exclude_none=exclude_none)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion | 🟠 Major

🧩 Analysis chain

🌐 Web query:

In Pydantic v2, does ConfigDict(frozen=True) prevent mutation of nested dict or list fields, or only prevent BaseModel attribute reassignment?

💡 Result:

In Pydantic v2, ConfigDict(frozen=True) prevents BaseModel attribute reassignment (i.e., direct mutation of model fields like model.field = new_value), but does not prevent mutation of nested dict or list fields. Nested containers like dicts and lists remain mutable because frozen only overrides setattr to block field-level assignments, not internal mutations of container objects.

Citations:


🏁 Script executed:

cat -n polylogue/archive_product_models.py | head -160

Repository: Sinity/polylogue

Length of output: 6171


Frozen Pydantic models do not deep-freeze nested dict fields.

ConfigDict(frozen=True) only prevents field reassignment (e.g., model.tool_categories = {}) but allows mutation of dict contents (e.g., model.tool_categories['key'] = 1). Since these are archive product contracts that should be immutable, replace mutable dicts with typed nested models, types.MappingProxyType, or explicitly deep-freeze on initialization. Applies to tool_categories (line 56), work_events/phases (lines 78–79), tool_counts (line 109), input_band_summary (line 128), work_event_breakdown (lines 142, 153), and providers (line 155).

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/archive_product_models.py` around lines 10 - 18, The
ArchiveProductModel is frozen at the top-level but nested dict fields remain
mutable; update the model so the listed mutable fields (tool_categories,
work_events, phases, tool_counts, input_band_summary, work_event_breakdown,
providers) are converted to immutable structures on initialization (e.g., wrap
dicts with types.MappingProxyType, convert nested dicts to typed BaseModel
mappings, or perform a recursive deep-freeze in a
model_post_init/model_validator) so consumers cannot mutate their contents;
implement the conversion in ArchiveProductModel (or per-field nested models) to
ensure deep immutability for those specific attributes.

Comment on lines +41 to +46
for fname, finfo in query_model.model_fields.items():
if finfo.default is not None:
field_defaults[fname] = finfo.default
else:
field_defaults[fname] = None
field_annotations[fname] = finfo.annotation if finfo.annotation is not None else object

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick | 🔵 Trivial

🧩 Analysis chain

🌐 Web query:

In Pydantic v2, what is the value of FieldInfo.default for a required field with no explicit default, and what is the recommended way to detect required fields?

💡 Result:

In Pydantic v2, for a required field with no explicit default (e.g., name: str), the value of FieldInfo.default is PydanticUndefined. The recommended way to detect required fields is to call the FieldInfo.is_required method, which returns True if both self.default is PydanticUndefined and self.default_factory is None.

Citations:


🏁 Script executed:

# First, locate and examine the file
fd "server_product_tools.py" --type f

Repository: Sinity/polylogue

Length of output: 97


🏁 Script executed:

# Read the file to examine the lines in question
wc -l polylogue/mcp/server_product_tools.py

Repository: Sinity/polylogue

Length of output: 101


🏁 Script executed:

# Read the specific lines and surrounding context
sed -n '30,55p' polylogue/mcp/server_product_tools.py

Repository: Sinity/polylogue

Length of output: 1145


🏁 Script executed:

# Check imports and Pydantic version
head -30 polylogue/mcp/server_product_tools.py

Repository: Sinity/polylogue

Length of output: 770


🏁 Script executed:

# Check for Pydantic imports and version usage in the file
rg "pydantic|FieldInfo" polylogue/mcp/server_product_tools.py

Repository: Sinity/polylogue

Length of output: 42


🏁 Script executed:

# Check the ProductType definition to understand query_model
fd "registry.py" polylogue/products/ --type f

Repository: Sinity/polylogue

Length of output: 90


🏁 Script executed:

# Check the ProductType definition
rg "query_model|FieldInfo|pydantic|PydanticUndefined" polylogue/products/registry.py -A 3

Repository: Sinity/polylogue

Length of output: 2648


🏁 Script executed:

# Find and examine one of the query model definitions to see if they have required fields
fd "SessionProfileProductQuery" -t f polylogue/

Repository: Sinity/polylogue

Length of output: 42


🏁 Script executed:

# Search for query model definitions across the codebase
rg "class.*ProductQuery|class.*Query" polylogue/ --type py -A 5 | head -100

Repository: Sinity/polylogue

Length of output: 6642


🏁 Script executed:

# Search for the specific query models used in the registry
rg "SessionProfileProductQuery|SessionEnrichmentProductQuery" polylogue/ --type py -B 2 -A 10

Repository: Sinity/polylogue

Length of output: 16041


🏁 Script executed:

# Examine the ArchiveProductModel base class and the query models more closely
sed -n '1,150p' polylogue/archive_products.py

Repository: Sinity/polylogue

Length of output: 4216


🏁 Script executed:

# Check the ArchiveProductModel base class
rg "class ArchiveProductModel" polylogue/ --type py -A 5

Repository: Sinity/polylogue

Length of output: 590


🏁 Script executed:

# Check the imports in archive_product_models.py to see if it's Pydantic v2
head -20 polylogue/archive_product_models.py

Repository: Sinity/polylogue

Length of output: 701


🏁 Script executed:

# Now let's see how field_defaults is used in the function
sed -n '41,80p' polylogue/mcp/server_product_tools.py

Repository: Sinity/polylogue

Length of output: 1747


🏁 Script executed:

# Continue reading to see how the parameters are constructed with field_defaults
sed -n '75,120p' polylogue/mcp/server_product_tools.py

Repository: Sinity/polylogue

Length of output: 1702


Use finfo.is_required() to properly detect required fields and avoid storing sentinel values in parameter defaults.

The current condition if finfo.default is not None: misclassifies required Pydantic v2 fields. Required fields carry FieldInfo.default = PydanticUndefined — which is not None — so required fields would be stored as field_defaults[fname] = PydanticUndefined and later passed to inspect.Parameter() and __kwdefaults__. While all current query models use | None = None defaults, the next required field added will silently expose the sentinel through the MCP surface. Fix by using finfo.is_required():

Suggested diff
-    for fname, finfo in query_model.model_fields.items():
-        if finfo.default is not None:
-            field_defaults[fname] = finfo.default
-        else:
-            field_defaults[fname] = None
+    for fname, finfo in query_model.model_fields.items():
+        if finfo.is_required():
+            field_defaults[fname] = None
+        else:
+            field_defaults[fname] = finfo.default
         field_annotations[fname] = finfo.annotation if finfo.annotation is not None else object
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/mcp/server_product_tools.py` around lines 41 - 46, The loop over
query_model.model_fields currently checks "if finfo.default is not None" which
misidentifies Pydantic-required fields (PydanticUndefined) and can store that
sentinel into field_defaults; change the logic to use finfo.is_required() (call
on the finfo object) so that when finfo.is_required() is True you set
field_defaults[fname] = None (not the sentinel), otherwise use the existing
finfo.default; keep field_annotations assignment as-is using finfo.annotation or
object to locate and update the block that references fname, finfo,
query_model.model_fields, field_defaults, and field_annotations.

Comment on lines 54 to +61
if "offset" in kwargs:
kwargs["offset"] = max(0, int(kwargs["offset"]))
offset_value = kwargs["offset"]
if isinstance(offset_value, bool):
kwargs["offset"] = 0
elif isinstance(offset_value, (int, str, bytes, bytearray)):
kwargs["offset"] = max(0, int(offset_value))
else:
kwargs["offset"] = 0

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Uncaught ValueError when offset arrives as a non-numeric string/bytes.

int("abc") and int(b"\xff\xfe") both raise ValueError. Since this branch exists specifically to tolerate loose input shapes (str/bytes/bytearray), a bad value will propagate up and fail the tool call rather than clamp to 0 as the else arm does. Wrap the coercion so malformed values degrade gracefully:

-            if "offset" in kwargs:
-                offset_value = kwargs["offset"]
-                if isinstance(offset_value, bool):
-                    kwargs["offset"] = 0
-                elif isinstance(offset_value, (int, str, bytes, bytearray)):
-                    kwargs["offset"] = max(0, int(offset_value))
-                else:
-                    kwargs["offset"] = 0
+            if "offset" in kwargs:
+                offset_value = kwargs["offset"]
+                if isinstance(offset_value, bool):
+                    kwargs["offset"] = 0
+                elif isinstance(offset_value, (int, str, bytes, bytearray)):
+                    try:
+                        kwargs["offset"] = max(0, int(offset_value))
+                    except (ValueError, TypeError):
+                        kwargs["offset"] = 0
+                else:
+                    kwargs["offset"] = 0
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/mcp/server_product_tools.py` around lines 54 - 61, The offset
coercion block currently calls int(offset_value) on str/bytes/bytearray and can
raise ValueError for malformed inputs; update the branch that handles (int, str,
bytes, bytearray) to try converting with int(...) inside a try/except (catching
ValueError and TypeError) and on exception set kwargs["offset"] = 0 (or clamp
negative results to 0 as already done), so malformed strings/bytes degrade to 0
instead of raising; locate and modify the offset handling code that checks "if
'offset' in kwargs" and the branch setting kwargs["offset"] accordingly.

Comment on lines +359 to +365
fields=(
ProductField("", _id_with_provider("phase_id"), group=0),
ProductField("kind", _nested("inference", "kind"), group=0),
ProductField("conv", _attr("conversation_id"), group=0),
ProductField("start", _nested("evidence", "start_time"), group=1),
ProductField("words", _nested("evidence", "word_count", "0"), group=1),
],
),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Fix the session phase kind accessor.

SessionPhaseInferencePayload does not expose kind, so this renders kind=- for every phase. Point the field at an actual product attribute, or preserve record.kind on SessionPhaseProduct and render that.

🛠️ Minimal local fix
-            ProductField("kind", _nested("inference", "kind"), group=0),
+            ProductField("kind", _attr("product_kind"), group=0),
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/products/registry.py` around lines 359 - 365, The ProductField
currently uses _nested("inference","kind") which is invalid because
SessionPhaseInferencePayload does not expose kind; update the accessor so the
kind is read from an actual stored attribute (or ensure SessionPhaseProduct
preserves record.kind and expose that) — either change the ProductField("kind",
...) to point at the real product attribute that holds the phase kind (e.g., the
top-level attribute name used on SessionPhaseProduct) or modify
SessionPhaseProduct to keep record.kind and then render that field; adjust the
ProductField declaration in the fields tuple accordingly (replace
_nested("inference","kind") with the correct attribute accessor or
preserve/forward kind in SessionPhaseProduct).

Comment on lines +58 to +65
payload=DaySessionSummaryPayload.model_validate(
_parse_json(
row["payload_json"],
field="payload_json",
record_id=f"{row['provider_name']}:{row['day']}",
)
or {}
),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Empty/NULL payload_json will raise ValidationError instead of a clean DatabaseError.

_parse_json returns None for empty/NULL input, and the or {} fallback then feeds an empty dict into DaySessionSummaryPayload.model_validate(...). Because DaySessionSummaryPayload.date is required (no default — see polylogue/archive_product_models.py:145-156), any legacy or corrupt row with a missing payload_json will surface as a pydantic ValidationError bubbling out of the row mapper, rather than the diagnostic DatabaseError the other _parse_json call sites produce.

If payload is guaranteed non-null by schema, consider removing the or {} fallback so the guarantee is explicit. Otherwise wrap validation to raise DatabaseError with the record id for consistency with the rest of this mapper.

Suggested tightening
-        payload=DaySessionSummaryPayload.model_validate(
-            _parse_json(
-                row["payload_json"],
-                field="payload_json",
-                record_id=f"{row['provider_name']}:{row['day']}",
-            )
-            or {}
-        ),
+        payload=DaySessionSummaryPayload.model_validate(
+            _parse_json(
+                row["payload_json"],
+                field="payload_json",
+                record_id=f"{row['provider_name']}:{row['day']}",
+            )
+        ),
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
payload=DaySessionSummaryPayload.model_validate(
_parse_json(
row["payload_json"],
field="payload_json",
record_id=f"{row['provider_name']}:{row['day']}",
)
or {}
),
payload=DaySessionSummaryPayload.model_validate(
_parse_json(
row["payload_json"],
field="payload_json",
record_id=f"{row['provider_name']}:{row['day']}",
)
),
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/storage/backends/queries/mappers_product_aggregates.py` around
lines 58 - 65, The mapper currently calls
DaySessionSummaryPayload.model_validate(... ) with an empty dict fallback (the
"or {}") which causes pydantic ValidationError for NULL/empty payload_json;
change this to either (a) remove the "or {}" so model_validate receives None
failure explicitly if schema guarantees non-null, or (b) if payload_json may be
absent, capture the result of _parse_json(row["payload_json"],
field="payload_json", record_id=f"{row['provider_name']}:{row['day']}") into a
variable and if it is None raise a DatabaseError including the same record id
(f"{row['provider_name']}:{row['day']}") before calling
DaySessionSummaryPayload.model_validate(payload), so validation errors are
wrapped as DatabaseError consistently.

Comment on lines +30 to +139
raw_evidence_payload = _parse_json(
_row_get(row, "evidence_payload_json"),
field="evidence_payload_json",
record_id=row["conversation_id"],
)
if not evidence_payload:
evidence_payload = {
"created_at": legacy_payload.get("created_at"),
"updated_at": legacy_payload.get("updated_at") or _row_get(row, "source_updated_at"),
"first_message_at": _row_get(row, "first_message_at") or legacy_payload.get("first_message_at"),
"last_message_at": _row_get(row, "last_message_at") or legacy_payload.get("last_message_at"),
"canonical_session_date": _row_get(row, "canonical_session_date")
or legacy_payload.get("canonical_session_date"),
"message_count": int(_row_get(row, "message_count", 0) or legacy_payload.get("message_count") or 0),
"substantive_count": int(
_row_get(row, "substantive_count", 0) or legacy_payload.get("substantive_count") or 0
),
"attachment_count": int(
_row_get(row, "attachment_count", 0) or legacy_payload.get("attachment_count") or 0
),
"tool_use_count": int(_row_get(row, "tool_use_count", 0) or legacy_payload.get("tool_use_count") or 0),
"thinking_count": int(_row_get(row, "thinking_count", 0) or legacy_payload.get("thinking_count") or 0),
"word_count": int(_row_get(row, "word_count", 0) or legacy_payload.get("word_count") or 0),
"total_cost_usd": float(
_row_get(row, "total_cost_usd", 0.0) or legacy_payload.get("total_cost_usd") or 0.0
),
"total_duration_ms": int(
_row_get(row, "total_duration_ms", 0) or legacy_payload.get("total_duration_ms") or 0
),
"wall_duration_ms": int(
_row_get(row, "wall_duration_ms", 0) or legacy_payload.get("wall_duration_ms") or 0
),
"cost_is_estimated": bool(
int(_row_get(row, "cost_is_estimated", 0) or 0) or legacy_payload.get("cost_is_estimated")
),
"tool_categories": legacy_payload.get("tool_categories") or {},
"repo_paths": tuple(
_parse_json(_row_get(row, "repo_paths_json")) or legacy_payload.get("repo_paths") or []
),
"cwd_paths": tuple(legacy_payload.get("cwd_paths") or ()),
"branch_names": tuple(legacy_payload.get("branch_names") or ()),
"file_paths_touched": tuple(legacy_payload.get("file_paths_touched") or ()),
"languages_detected": tuple(legacy_payload.get("languages_detected") or ()),
"tags": tuple(_parse_json(_row_get(row, "tags_json")) or legacy_payload.get("tags") or []),
"is_continuation": bool(legacy_payload.get("is_continuation", False)),
"parent_id": legacy_payload.get("parent_id"),
}
inference_payload = (
_parse_json(
_row_get(row, "inference_payload_json"),
field="inference_payload_json",
record_id=row["conversation_id"],
if raw_evidence_payload:
evidence_payload = SessionEvidencePayload.model_validate(raw_evidence_payload)
else:
evidence_payload = SessionEvidencePayload.model_validate(
{
"created_at": legacy_payload.get("created_at"),
"updated_at": legacy_payload.get("updated_at") or _row_get(row, "source_updated_at"),
"first_message_at": _row_get(row, "first_message_at") or legacy_payload.get("first_message_at"),
"last_message_at": _row_get(row, "last_message_at") or legacy_payload.get("last_message_at"),
"canonical_session_date": _row_get(row, "canonical_session_date")
or legacy_payload.get("canonical_session_date"),
"message_count": int(_row_get(row, "message_count", 0) or legacy_payload.get("message_count") or 0),
"substantive_count": int(
_row_get(row, "substantive_count", 0) or legacy_payload.get("substantive_count") or 0
),
"attachment_count": int(
_row_get(row, "attachment_count", 0) or legacy_payload.get("attachment_count") or 0
),
"tool_use_count": int(_row_get(row, "tool_use_count", 0) or legacy_payload.get("tool_use_count") or 0),
"thinking_count": int(_row_get(row, "thinking_count", 0) or legacy_payload.get("thinking_count") or 0),
"word_count": int(_row_get(row, "word_count", 0) or legacy_payload.get("word_count") or 0),
"total_cost_usd": float(
_row_get(row, "total_cost_usd", 0.0) or legacy_payload.get("total_cost_usd") or 0.0
),
"total_duration_ms": int(
_row_get(row, "total_duration_ms", 0) or legacy_payload.get("total_duration_ms") or 0
),
"wall_duration_ms": int(
_row_get(row, "wall_duration_ms", 0) or legacy_payload.get("wall_duration_ms") or 0
),
"cost_is_estimated": bool(
int(_row_get(row, "cost_is_estimated", 0) or 0) or legacy_payload.get("cost_is_estimated")
),
"tool_categories": legacy_payload.get("tool_categories") or {},
"repo_paths": tuple(
_parse_json(_row_get(row, "repo_paths_json")) or legacy_payload.get("repo_paths") or []
),
"cwd_paths": tuple(legacy_payload.get("cwd_paths") or ()),
"branch_names": tuple(legacy_payload.get("branch_names") or ()),
"file_paths_touched": tuple(legacy_payload.get("file_paths_touched") or ()),
"languages_detected": tuple(legacy_payload.get("languages_detected") or ()),
"tags": tuple(_parse_json(_row_get(row, "tags_json")) or legacy_payload.get("tags") or []),
"is_continuation": bool(legacy_payload.get("is_continuation", False)),
"parent_id": legacy_payload.get("parent_id"),
}
)
or {}
raw_inference_payload = _parse_json(
_row_get(row, "inference_payload_json"),
field="inference_payload_json",
record_id=row["conversation_id"],
)
if not inference_payload:
inference_payload = {
"repo_names": tuple(
_parse_json(_row_get(row, "repo_names_json")) or legacy_payload.get("repo_names") or []
),
"work_event_count": int(
_row_get(row, "work_event_count", 0) or legacy_payload.get("work_event_count") or 0
),
"phase_count": int(_row_get(row, "phase_count", 0) or legacy_payload.get("phase_count") or 0),
"engaged_duration_ms": int(
_row_get(row, "engaged_duration_ms", 0) or legacy_payload.get("engaged_duration_ms") or 0
),
"engaged_minutes": float(legacy_payload.get("engaged_minutes") or 0.0),
"support_level": str(legacy_payload.get("support_level") or "weak"),
"support_signals": tuple(legacy_payload.get("support_signals") or ()),
"engaged_duration_source": str(legacy_payload.get("engaged_duration_source") or "session_total_fallback"),
"repo_inference_strength": str(legacy_payload.get("repo_inference_strength") or "weak"),
"auto_tags": tuple(_parse_json(_row_get(row, "auto_tags_json")) or legacy_payload.get("auto_tags") or []),
"work_events": tuple(legacy_payload.get("work_events") or ()),
"phases": tuple(legacy_payload.get("phases") or ()),
}
enrichment_payload = (
_parse_json(
_row_get(row, "enrichment_payload_json"),
field="enrichment_payload_json",
record_id=row["conversation_id"],
if raw_inference_payload:
inference_payload = SessionInferencePayload.model_validate(raw_inference_payload)
else:
inference_payload = SessionInferencePayload.model_validate(
{
"repo_names": tuple(
_parse_json(_row_get(row, "repo_names_json")) or legacy_payload.get("repo_names") or []
),
"work_event_count": int(
_row_get(row, "work_event_count", 0) or legacy_payload.get("work_event_count") or 0
),
"phase_count": int(_row_get(row, "phase_count", 0) or legacy_payload.get("phase_count") or 0),
"engaged_duration_ms": int(
_row_get(row, "engaged_duration_ms", 0) or legacy_payload.get("engaged_duration_ms") or 0
),
"engaged_minutes": float(legacy_payload.get("engaged_minutes") or 0.0),
"support_level": str(legacy_payload.get("support_level") or "weak"),
"support_signals": tuple(legacy_payload.get("support_signals") or ()),
"engaged_duration_source": str(
legacy_payload.get("engaged_duration_source") or "session_total_fallback"
),
"repo_inference_strength": str(legacy_payload.get("repo_inference_strength") or "weak"),
"auto_tags": tuple(
_parse_json(_row_get(row, "auto_tags_json")) or legacy_payload.get("auto_tags") or []
),
"work_events": tuple(legacy_payload.get("work_events") or ()),
"phases": tuple(legacy_payload.get("phases") or ()),
}
)
or {}
raw_enrichment_payload = _parse_json(
_row_get(row, "enrichment_payload_json"),
field="enrichment_payload_json",
record_id=row["conversation_id"],
)
if not enrichment_payload:
enrichment_payload = {
"intent_summary": row["title"] or legacy_payload.get("title"),
"outcome_summary": None,
"blockers": (),
"confidence": 0.0,
"support_level": "weak",
"support_signals": tuple(inference_payload.get("support_signals") or ()),
"input_band_summary": {
"user_turns": 0,
"assistant_turns": 0,
"action_events": 0,
"touched_paths": len(_parse_json(_row_get(row, "repo_paths_json")) or []),
"repo_names": len(_parse_json(_row_get(row, "repo_names_json")) or []),
},
}
if raw_enrichment_payload:
enrichment_payload = SessionEnrichmentPayload.model_validate(raw_enrichment_payload)
else:
enrichment_payload = SessionEnrichmentPayload.model_validate(
{
"intent_summary": row["title"] or legacy_payload.get("title"),
"outcome_summary": None,
"blockers": (),
"confidence": 0.0,
"support_level": "weak",
"support_signals": inference_payload.support_signals,
"input_band_summary": {
"user_turns": 0,
"assistant_turns": 0,
"action_events": 0,
"touched_paths": len(_parse_json(_row_get(row, "repo_paths_json")) or []),
"repo_names": len(_parse_json(_row_get(row, "repo_names_json")) or []),
},
}
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Treat empty typed payload JSON as present.

{} is a valid input for these defaulted payload models, but Lines 35, 86, and 120 treat it as absent and rebuild from legacy columns. That can break round-tripping rows whose typed payload is intentionally empty. Use is not None so only missing/null payloads fall back.

Proposed fix
-    if raw_evidence_payload:
+    if raw_evidence_payload is not None:
         evidence_payload = SessionEvidencePayload.model_validate(raw_evidence_payload)
@@
-    if raw_inference_payload:
+    if raw_inference_payload is not None:
         inference_payload = SessionInferencePayload.model_validate(raw_inference_payload)
@@
-    if raw_enrichment_payload:
+    if raw_enrichment_payload is not None:
         enrichment_payload = SessionEnrichmentPayload.model_validate(raw_enrichment_payload)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
raw_evidence_payload = _parse_json(
_row_get(row, "evidence_payload_json"),
field="evidence_payload_json",
record_id=row["conversation_id"],
)
if not evidence_payload:
evidence_payload = {
"created_at": legacy_payload.get("created_at"),
"updated_at": legacy_payload.get("updated_at") or _row_get(row, "source_updated_at"),
"first_message_at": _row_get(row, "first_message_at") or legacy_payload.get("first_message_at"),
"last_message_at": _row_get(row, "last_message_at") or legacy_payload.get("last_message_at"),
"canonical_session_date": _row_get(row, "canonical_session_date")
or legacy_payload.get("canonical_session_date"),
"message_count": int(_row_get(row, "message_count", 0) or legacy_payload.get("message_count") or 0),
"substantive_count": int(
_row_get(row, "substantive_count", 0) or legacy_payload.get("substantive_count") or 0
),
"attachment_count": int(
_row_get(row, "attachment_count", 0) or legacy_payload.get("attachment_count") or 0
),
"tool_use_count": int(_row_get(row, "tool_use_count", 0) or legacy_payload.get("tool_use_count") or 0),
"thinking_count": int(_row_get(row, "thinking_count", 0) or legacy_payload.get("thinking_count") or 0),
"word_count": int(_row_get(row, "word_count", 0) or legacy_payload.get("word_count") or 0),
"total_cost_usd": float(
_row_get(row, "total_cost_usd", 0.0) or legacy_payload.get("total_cost_usd") or 0.0
),
"total_duration_ms": int(
_row_get(row, "total_duration_ms", 0) or legacy_payload.get("total_duration_ms") or 0
),
"wall_duration_ms": int(
_row_get(row, "wall_duration_ms", 0) or legacy_payload.get("wall_duration_ms") or 0
),
"cost_is_estimated": bool(
int(_row_get(row, "cost_is_estimated", 0) or 0) or legacy_payload.get("cost_is_estimated")
),
"tool_categories": legacy_payload.get("tool_categories") or {},
"repo_paths": tuple(
_parse_json(_row_get(row, "repo_paths_json")) or legacy_payload.get("repo_paths") or []
),
"cwd_paths": tuple(legacy_payload.get("cwd_paths") or ()),
"branch_names": tuple(legacy_payload.get("branch_names") or ()),
"file_paths_touched": tuple(legacy_payload.get("file_paths_touched") or ()),
"languages_detected": tuple(legacy_payload.get("languages_detected") or ()),
"tags": tuple(_parse_json(_row_get(row, "tags_json")) or legacy_payload.get("tags") or []),
"is_continuation": bool(legacy_payload.get("is_continuation", False)),
"parent_id": legacy_payload.get("parent_id"),
}
inference_payload = (
_parse_json(
_row_get(row, "inference_payload_json"),
field="inference_payload_json",
record_id=row["conversation_id"],
if raw_evidence_payload:
evidence_payload = SessionEvidencePayload.model_validate(raw_evidence_payload)
else:
evidence_payload = SessionEvidencePayload.model_validate(
{
"created_at": legacy_payload.get("created_at"),
"updated_at": legacy_payload.get("updated_at") or _row_get(row, "source_updated_at"),
"first_message_at": _row_get(row, "first_message_at") or legacy_payload.get("first_message_at"),
"last_message_at": _row_get(row, "last_message_at") or legacy_payload.get("last_message_at"),
"canonical_session_date": _row_get(row, "canonical_session_date")
or legacy_payload.get("canonical_session_date"),
"message_count": int(_row_get(row, "message_count", 0) or legacy_payload.get("message_count") or 0),
"substantive_count": int(
_row_get(row, "substantive_count", 0) or legacy_payload.get("substantive_count") or 0
),
"attachment_count": int(
_row_get(row, "attachment_count", 0) or legacy_payload.get("attachment_count") or 0
),
"tool_use_count": int(_row_get(row, "tool_use_count", 0) or legacy_payload.get("tool_use_count") or 0),
"thinking_count": int(_row_get(row, "thinking_count", 0) or legacy_payload.get("thinking_count") or 0),
"word_count": int(_row_get(row, "word_count", 0) or legacy_payload.get("word_count") or 0),
"total_cost_usd": float(
_row_get(row, "total_cost_usd", 0.0) or legacy_payload.get("total_cost_usd") or 0.0
),
"total_duration_ms": int(
_row_get(row, "total_duration_ms", 0) or legacy_payload.get("total_duration_ms") or 0
),
"wall_duration_ms": int(
_row_get(row, "wall_duration_ms", 0) or legacy_payload.get("wall_duration_ms") or 0
),
"cost_is_estimated": bool(
int(_row_get(row, "cost_is_estimated", 0) or 0) or legacy_payload.get("cost_is_estimated")
),
"tool_categories": legacy_payload.get("tool_categories") or {},
"repo_paths": tuple(
_parse_json(_row_get(row, "repo_paths_json")) or legacy_payload.get("repo_paths") or []
),
"cwd_paths": tuple(legacy_payload.get("cwd_paths") or ()),
"branch_names": tuple(legacy_payload.get("branch_names") or ()),
"file_paths_touched": tuple(legacy_payload.get("file_paths_touched") or ()),
"languages_detected": tuple(legacy_payload.get("languages_detected") or ()),
"tags": tuple(_parse_json(_row_get(row, "tags_json")) or legacy_payload.get("tags") or []),
"is_continuation": bool(legacy_payload.get("is_continuation", False)),
"parent_id": legacy_payload.get("parent_id"),
}
)
or {}
raw_inference_payload = _parse_json(
_row_get(row, "inference_payload_json"),
field="inference_payload_json",
record_id=row["conversation_id"],
)
if not inference_payload:
inference_payload = {
"repo_names": tuple(
_parse_json(_row_get(row, "repo_names_json")) or legacy_payload.get("repo_names") or []
),
"work_event_count": int(
_row_get(row, "work_event_count", 0) or legacy_payload.get("work_event_count") or 0
),
"phase_count": int(_row_get(row, "phase_count", 0) or legacy_payload.get("phase_count") or 0),
"engaged_duration_ms": int(
_row_get(row, "engaged_duration_ms", 0) or legacy_payload.get("engaged_duration_ms") or 0
),
"engaged_minutes": float(legacy_payload.get("engaged_minutes") or 0.0),
"support_level": str(legacy_payload.get("support_level") or "weak"),
"support_signals": tuple(legacy_payload.get("support_signals") or ()),
"engaged_duration_source": str(legacy_payload.get("engaged_duration_source") or "session_total_fallback"),
"repo_inference_strength": str(legacy_payload.get("repo_inference_strength") or "weak"),
"auto_tags": tuple(_parse_json(_row_get(row, "auto_tags_json")) or legacy_payload.get("auto_tags") or []),
"work_events": tuple(legacy_payload.get("work_events") or ()),
"phases": tuple(legacy_payload.get("phases") or ()),
}
enrichment_payload = (
_parse_json(
_row_get(row, "enrichment_payload_json"),
field="enrichment_payload_json",
record_id=row["conversation_id"],
if raw_inference_payload:
inference_payload = SessionInferencePayload.model_validate(raw_inference_payload)
else:
inference_payload = SessionInferencePayload.model_validate(
{
"repo_names": tuple(
_parse_json(_row_get(row, "repo_names_json")) or legacy_payload.get("repo_names") or []
),
"work_event_count": int(
_row_get(row, "work_event_count", 0) or legacy_payload.get("work_event_count") or 0
),
"phase_count": int(_row_get(row, "phase_count", 0) or legacy_payload.get("phase_count") or 0),
"engaged_duration_ms": int(
_row_get(row, "engaged_duration_ms", 0) or legacy_payload.get("engaged_duration_ms") or 0
),
"engaged_minutes": float(legacy_payload.get("engaged_minutes") or 0.0),
"support_level": str(legacy_payload.get("support_level") or "weak"),
"support_signals": tuple(legacy_payload.get("support_signals") or ()),
"engaged_duration_source": str(
legacy_payload.get("engaged_duration_source") or "session_total_fallback"
),
"repo_inference_strength": str(legacy_payload.get("repo_inference_strength") or "weak"),
"auto_tags": tuple(
_parse_json(_row_get(row, "auto_tags_json")) or legacy_payload.get("auto_tags") or []
),
"work_events": tuple(legacy_payload.get("work_events") or ()),
"phases": tuple(legacy_payload.get("phases") or ()),
}
)
or {}
raw_enrichment_payload = _parse_json(
_row_get(row, "enrichment_payload_json"),
field="enrichment_payload_json",
record_id=row["conversation_id"],
)
if not enrichment_payload:
enrichment_payload = {
"intent_summary": row["title"] or legacy_payload.get("title"),
"outcome_summary": None,
"blockers": (),
"confidence": 0.0,
"support_level": "weak",
"support_signals": tuple(inference_payload.get("support_signals") or ()),
"input_band_summary": {
"user_turns": 0,
"assistant_turns": 0,
"action_events": 0,
"touched_paths": len(_parse_json(_row_get(row, "repo_paths_json")) or []),
"repo_names": len(_parse_json(_row_get(row, "repo_names_json")) or []),
},
}
if raw_enrichment_payload:
enrichment_payload = SessionEnrichmentPayload.model_validate(raw_enrichment_payload)
else:
enrichment_payload = SessionEnrichmentPayload.model_validate(
{
"intent_summary": row["title"] or legacy_payload.get("title"),
"outcome_summary": None,
"blockers": (),
"confidence": 0.0,
"support_level": "weak",
"support_signals": inference_payload.support_signals,
"input_band_summary": {
"user_turns": 0,
"assistant_turns": 0,
"action_events": 0,
"touched_paths": len(_parse_json(_row_get(row, "repo_paths_json")) or []),
"repo_names": len(_parse_json(_row_get(row, "repo_names_json")) or []),
},
}
)
raw_evidence_payload = _parse_json(
_row_get(row, "evidence_payload_json"),
field="evidence_payload_json",
record_id=row["conversation_id"],
)
if raw_evidence_payload is not None:
evidence_payload = SessionEvidencePayload.model_validate(raw_evidence_payload)
else:
evidence_payload = SessionEvidencePayload.model_validate(
{
"created_at": legacy_payload.get("created_at"),
"updated_at": legacy_payload.get("updated_at") or _row_get(row, "source_updated_at"),
"first_message_at": _row_get(row, "first_message_at") or legacy_payload.get("first_message_at"),
"last_message_at": _row_get(row, "last_message_at") or legacy_payload.get("last_message_at"),
"canonical_session_date": _row_get(row, "canonical_session_date")
or legacy_payload.get("canonical_session_date"),
"message_count": int(_row_get(row, "message_count", 0) or legacy_payload.get("message_count") or 0),
"substantive_count": int(
_row_get(row, "substantive_count", 0) or legacy_payload.get("substantive_count") or 0
),
"attachment_count": int(
_row_get(row, "attachment_count", 0) or legacy_payload.get("attachment_count") or 0
),
"tool_use_count": int(_row_get(row, "tool_use_count", 0) or legacy_payload.get("tool_use_count") or 0),
"thinking_count": int(_row_get(row, "thinking_count", 0) or legacy_payload.get("thinking_count") or 0),
"word_count": int(_row_get(row, "word_count", 0) or legacy_payload.get("word_count") or 0),
"total_cost_usd": float(
_row_get(row, "total_cost_usd", 0.0) or legacy_payload.get("total_cost_usd") or 0.0
),
"total_duration_ms": int(
_row_get(row, "total_duration_ms", 0) or legacy_payload.get("total_duration_ms") or 0
),
"wall_duration_ms": int(
_row_get(row, "wall_duration_ms", 0) or legacy_payload.get("wall_duration_ms") or 0
),
"cost_is_estimated": bool(
int(_row_get(row, "cost_is_estimated", 0) or 0) or legacy_payload.get("cost_is_estimated")
),
"tool_categories": legacy_payload.get("tool_categories") or {},
"repo_paths": tuple(
_parse_json(_row_get(row, "repo_paths_json")) or legacy_payload.get("repo_paths") or []
),
"cwd_paths": tuple(legacy_payload.get("cwd_paths") or ()),
"branch_names": tuple(legacy_payload.get("branch_names") or ()),
"file_paths_touched": tuple(legacy_payload.get("file_paths_touched") or ()),
"languages_detected": tuple(legacy_payload.get("languages_detected") or ()),
"tags": tuple(_parse_json(_row_get(row, "tags_json")) or legacy_payload.get("tags") or []),
"is_continuation": bool(legacy_payload.get("is_continuation", False)),
"parent_id": legacy_payload.get("parent_id"),
}
)
raw_inference_payload = _parse_json(
_row_get(row, "inference_payload_json"),
field="inference_payload_json",
record_id=row["conversation_id"],
)
if raw_inference_payload is not None:
inference_payload = SessionInferencePayload.model_validate(raw_inference_payload)
else:
inference_payload = SessionInferencePayload.model_validate(
{
"repo_names": tuple(
_parse_json(_row_get(row, "repo_names_json")) or legacy_payload.get("repo_names") or []
),
"work_event_count": int(
_row_get(row, "work_event_count", 0) or legacy_payload.get("work_event_count") or 0
),
"phase_count": int(_row_get(row, "phase_count", 0) or legacy_payload.get("phase_count") or 0),
"engaged_duration_ms": int(
_row_get(row, "engaged_duration_ms", 0) or legacy_payload.get("engaged_duration_ms") or 0
),
"engaged_minutes": float(legacy_payload.get("engaged_minutes") or 0.0),
"support_level": str(legacy_payload.get("support_level") or "weak"),
"support_signals": tuple(legacy_payload.get("support_signals") or ()),
"engaged_duration_source": str(
legacy_payload.get("engaged_duration_source") or "session_total_fallback"
),
"repo_inference_strength": str(legacy_payload.get("repo_inference_strength") or "weak"),
"auto_tags": tuple(
_parse_json(_row_get(row, "auto_tags_json")) or legacy_payload.get("auto_tags") or []
),
"work_events": tuple(legacy_payload.get("work_events") or ()),
"phases": tuple(legacy_payload.get("phases") or ()),
}
)
raw_enrichment_payload = _parse_json(
_row_get(row, "enrichment_payload_json"),
field="enrichment_payload_json",
record_id=row["conversation_id"],
)
if raw_enrichment_payload is not None:
enrichment_payload = SessionEnrichmentPayload.model_validate(raw_enrichment_payload)
else:
enrichment_payload = SessionEnrichmentPayload.model_validate(
{
"intent_summary": row["title"] or legacy_payload.get("title"),
"outcome_summary": None,
"blockers": (),
"confidence": 0.0,
"support_level": "weak",
"support_signals": inference_payload.support_signals,
"input_band_summary": {
"user_turns": 0,
"assistant_turns": 0,
"action_events": 0,
"touched_paths": len(_parse_json(_row_get(row, "repo_paths_json")) or []),
"repo_names": len(_parse_json(_row_get(row, "repo_names_json")) or []),
},
}
)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/storage/backends/queries/mappers_product_profiles.py` around lines
30 - 139, The current checks treat an empty dict JSON payload as missing and
rebuild defaults; change the three conditionals that inspect
raw_evidence_payload, raw_inference_payload, and raw_enrichment_payload to use
"is not None" (or "raw_... is not None") instead of truthiness so {} is accepted
as a present payload for SessionEvidencePayload.model_validate,
SessionInferencePayload.model_validate, and
SessionEnrichmentPayload.model_validate; keep using _parse_json and _row_get as
before and only fall back to the legacy construction when the parsed raw_* is
None.

Comment on lines +28 to +68
raw_evidence_payload = _parse_json(
_row_get(row, "evidence_payload_json"),
field="evidence_payload_json",
record_id=row["event_id"],
)
if not evidence_payload:
evidence_payload = {
"start_index": int(_row_get(row, "start_index", 0) or legacy_payload.get("start_index") or 0),
"end_index": int(_row_get(row, "end_index", 0) or legacy_payload.get("end_index") or 0),
"start_time": _row_get(row, "start_time") or legacy_payload.get("start_time"),
"end_time": _row_get(row, "end_time") or legacy_payload.get("end_time"),
"canonical_session_date": _row_get(row, "canonical_session_date")
or legacy_payload.get("canonical_session_date"),
"duration_ms": int(_row_get(row, "duration_ms", 0) or legacy_payload.get("duration_ms") or 0),
"file_paths": tuple(
_parse_json(_row_get(row, "file_paths_json")) or legacy_payload.get("file_paths") or []
),
"tools_used": tuple(
_parse_json(_row_get(row, "tools_used_json")) or legacy_payload.get("tools_used") or []
),
}
inference_payload = (
_parse_json(
_row_get(row, "inference_payload_json"),
field="inference_payload_json",
record_id=row["event_id"],
if raw_evidence_payload:
evidence_payload = WorkEventEvidencePayload.model_validate(raw_evidence_payload)
else:
evidence_payload = WorkEventEvidencePayload.model_validate(
{
"start_index": int(_row_get(row, "start_index", 0) or legacy_payload.get("start_index") or 0),
"end_index": int(_row_get(row, "end_index", 0) or legacy_payload.get("end_index") or 0),
"start_time": _row_get(row, "start_time") or legacy_payload.get("start_time"),
"end_time": _row_get(row, "end_time") or legacy_payload.get("end_time"),
"canonical_session_date": _row_get(row, "canonical_session_date")
or legacy_payload.get("canonical_session_date"),
"duration_ms": int(_row_get(row, "duration_ms", 0) or legacy_payload.get("duration_ms") or 0),
"file_paths": tuple(
_parse_json(_row_get(row, "file_paths_json")) or legacy_payload.get("file_paths") or []
),
"tools_used": tuple(
_parse_json(_row_get(row, "tools_used_json")) or legacy_payload.get("tools_used") or []
),
}
)
or {}
raw_inference_payload = _parse_json(
_row_get(row, "inference_payload_json"),
field="inference_payload_json",
record_id=row["event_id"],
)
if not inference_payload:
inference_payload = {
"kind": row["kind"],
"summary": row["summary"],
"confidence": float(_row_get(row, "confidence", 0.0) or legacy_payload.get("confidence") or 0.0),
"evidence": tuple(legacy_payload.get("evidence") or ()),
}
if raw_inference_payload:
inference_payload = WorkEventInferencePayload.model_validate(raw_inference_payload)
else:
inference_payload = WorkEventInferencePayload.model_validate(
{
"kind": row["kind"],
"summary": row["summary"],
"confidence": float(_row_get(row, "confidence", 0.0) or legacy_payload.get("confidence") or 0.0),
"evidence": tuple(legacy_payload.get("evidence") or ()),
}
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Look for any migration / writer paths that could produce partial evidence/inference payload JSON,
# and existing tests exercising legacy rows.
rg -nP 'evidence_payload_json|inference_payload_json' --type=py -C2
rg -nP 'WorkEventEvidencePayload|WorkEventInferencePayload|SessionPhaseEvidencePayload|SessionPhaseInferencePayload' --type=py -C1

Repository: Sinity/polylogue

Length of output: 23851


🏁 Script executed:

cat -n polylogue/archive_product_models.py | sed -n '82,120p'

Repository: Sinity/polylogue

Length of output: 1451


🏁 Script executed:

# Check for any code that might write partial payloads
rg -n "model_dump|to_dict|json()" polylogue/storage/ --type=py | head -20

Repository: Sinity/polylogue

Length of output: 2064


🏁 Script executed:

# Check if there are any migrations or schema changes that might produce partial payloads
rg -n "UPDATE.*evidence_payload|UPDATE.*inference_payload" --type=py

Repository: Sinity/polylogue

Length of output: 504


🏁 Script executed:

# Check for any schema migrations or historical code that might write partial payloads
find . -name "*migrat*" -type f | head -10

Repository: Sinity/polylogue

Length of output: 42


🏁 Script executed:

# Look for any direct JSON construction in SQL or Python that might produce partial payloads
rg -n "INSERT.*evidence_payload|INSERT.*inference_payload" --type=py

Repository: Sinity/polylogue

Length of output: 42


🏁 Script executed:

# Check if mappers_product_profiles has the same issue (mentioned in review)
sed -n '29,90p' polylogue/storage/backends/queries/mappers_product_profiles.py

Repository: Sinity/polylogue

Length of output: 3703


Merge column/legacy defaults under JSON values to handle partial payloads gracefully.

The either/or branching (if raw_*_payload: / else:) is vulnerable to partial JSON. If evidence_payload_json or inference_payload_json contains a truthy but incomplete dict—e.g., {"start_index": 5} missing end_index—WorkEventEvidencePayload.model_validate() will fail because start_index and end_index are required fields. Similarly, WorkEventInferencePayload requires kind, summary, and confidence, so partial blobs will raise validation errors.

While current writers produce complete payloads via model_dump(mode="json"), the pattern is fragile during schema evolution or legacy data reads. Defend against this by merging column/legacy defaults under the JSON-provided values:

🛠️ Suggested merge pattern
-    if raw_evidence_payload:
-        evidence_payload = WorkEventEvidencePayload.model_validate(raw_evidence_payload)
-    else:
-        evidence_payload = WorkEventEvidencePayload.model_validate(
-            {
-                "start_index": int(_row_get(row, "start_index", 0) or legacy_payload.get("start_index") or 0),
-                ...
-            }
-        )
+    evidence_defaults = {
+        "start_index": int(_row_get(row, "start_index", 0) or legacy_payload.get("start_index") or 0),
+        "end_index": int(_row_get(row, "end_index", 0) or legacy_payload.get("end_index") or 0),
+        "start_time": _row_get(row, "start_time") or legacy_payload.get("start_time"),
+        "end_time": _row_get(row, "end_time") or legacy_payload.get("end_time"),
+        "canonical_session_date": _row_get(row, "canonical_session_date")
+        or legacy_payload.get("canonical_session_date"),
+        "duration_ms": int(_row_get(row, "duration_ms", 0) or legacy_payload.get("duration_ms") or 0),
+        "file_paths": tuple(_parse_json(_row_get(row, "file_paths_json")) or legacy_payload.get("file_paths") or []),
+        "tools_used": tuple(_parse_json(_row_get(row, "tools_used_json")) or legacy_payload.get("tools_used") or []),
+    }
+    evidence_payload = WorkEventEvidencePayload.model_validate(
+        {**evidence_defaults, **(raw_evidence_payload or {})}
+    )

Apply to both _row_to_work_event_record and _row_to_session_phase_record, and to the corresponding functions in mappers_product_profiles.py for consistency.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/storage/backends/queries/mappers_product_timelines.py` around lines
28 - 68, When raw_*_payload exists, don’t pass it straight to
WorkEventEvidencePayload.model_validate or
WorkEventInferencePayload.model_validate; instead build the same defaults
currently used in the else-branch (using _row_get, legacy_payload, parsing JSON
for file_paths/tools_used, converting numeric fields) and merge the JSON dict on
top of those defaults (JSON values override defaults) before calling
model_validate; apply this change for raw_evidence_payload and
raw_inference_payload in _row_to_work_event_record (and mirror the same pattern
in _row_to_session_phase_record and the corresponding functions in
mappers_product_profiles.py) so partial JSON blobs are complemented by
column/legacy defaults before validation.

Comment on lines +128 to +134
payload=WorkThreadPayload.model_validate(thread.to_dict()),
search_text=thread_search_text(thread),
)


def hydrate_work_thread(record: WorkThreadRecord) -> WorkThread:
return WorkThread.from_dict(record.payload)
return WorkThread.from_dict(record.payload.model_dump(mode="json"))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
ast-grep --pattern $'class WorkThreadPayload($_):
  $$$'
echo "---"
ast-grep --pattern $'def to_dict(self) -> $_:
  $$$' | rg -n -A 40 'class WorkThread\b' -B 0 || true
rg -nP -C2 '\bclass WorkThread\b|def to_dict|def from_dict' --type=py -g '!**/test*/**'

Repository: Sinity/polylogue

Length of output: 20879


🏁 Script executed:

# Get full WorkThread class definition
sed -n '22,75p' polylogue/lib/threads.py

Repository: Sinity/polylogue

Length of output: 2361


🏁 Script executed:

# Get full WorkThreadPayload class definition including parent class
head -200 polylogue/archive_product_models.py | tail -100

Repository: Sinity/polylogue

Length of output: 3036


🏁 Script executed:

# Verify ArchiveProductModel base class
grep -n "class ArchiveProductModel" polylogue/archive_product_models.py -A 5

Repository: Sinity/polylogue

Length of output: 392


Missing schema fields will silently cause data loss during roundtrip.

The WorkThreadPayload schema is missing three fields that WorkThread.to_dict() produces and WorkThread.from_dict() expects:

  • thread_id – critical identifier, will be lost
  • root_id – critical identifier, will be lost
  • provider_breakdown – will be reset to empty dict

When build_work_thread_record calls WorkThreadPayload.model_validate(thread.to_dict()), the extra fields are silently dropped by Pydantic's extra="ignore" configuration. Subsequently, hydrate_work_thread reconstructs a WorkThread from the incomplete payload, with missing identifiers and an empty provider breakdown dict.

Add these three fields to WorkThreadPayload:

thread_id: str
root_id: str
provider_breakdown: dict[str, int] = Field(default_factory=dict)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/storage/session_product_threads.py` around lines 128 - 134, The
WorkThreadPayload schema is missing fields so build_work_thread_record calls
WorkThreadPayload.model_validate(thread.to_dict()) and Pydantic drops thread_id,
root_id and provider_breakdown causing data loss; update the WorkThreadPayload
model to include thread_id: str, root_id: str, and provider_breakdown: dict[str,
int] with a default factory (e.g., Field(default_factory=dict)) so that
hydrate_work_thread and WorkThread.from_dict() receive the full payload and
identifiers are preserved.

@Sinity
Sinity merged commit 5f40756 into master Apr 19, 2026
14 checks passed
@Sinity
Sinity deleted the feature/refactor/storage-lib-product-renewal-v2 branch April 19, 2026 23:49
Sinity added a commit that referenced this pull request Apr 22, 2026
Ref #225

## Summary
- move session-product payload surfaces onto shared typed models and direct query-model registry wiring
- rewrite the session-product materialization runtime around typed batch, bundle, and refresh-observation contracts
- collapse duplicated session-product sync/async write assembly and tighten provider-day aggregate refresh on top of the unified writer seam

## Problem
The session-product layer was still split across path-dependent seams: archive product payloads were drifting between dict-shaped records and model-backed products, product registry dispatch still relied on dynamic query resolution, refresh/rebuild used tuple- and dict-shaped runtime plumbing, and the async writer/query modules were cloning the sync storage layer’s insert assembly. That left the storage/product runtime technically type-checked but still ambiguous and duplicated at the exact points where the archive materializes durable products.

## Solution
- extract shared archive product payload/base models into `polylogue/archive_product_models.py` and propagate those typed payloads through archive products, mappers, records, writers, and affected tests
- rewrite `polylogue/products/registry.py` to use direct query-model references, immutable descriptor tuples, and typed nested field access, then adapt the CLI, MCP, and scenario surfaces to that contract
- rebuild `polylogue/storage/session_product_rebuild.py` and `polylogue/storage/session_product_refresh.py` around `SessionProductArchiveBatch`, `SessionProductRecordBundle`, and `SessionProductRefreshChunkObservation`, and update `polylogue/pipeline/services/ingest_batch.py` to consume that typed refresh telemetry instead of dict-key probing
- extract shared insert-column/value builders into `polylogue/storage/session_product_storage.py`, route the async profile/timeline/thread/summary writers through those helpers, and simplify `polylogue/storage/session_product_aggregates.py` so sync and async provider-day refresh paths apply the same prepared aggregate writes
- absorb the direct fallout in affected tests, including the small compaction assertion update revealed by the repo-wide verify pass

## Verification
- `ruff check polylogue/storage/session_product_rebuild.py polylogue/storage/session_product_refresh.py polylogue/pipeline/services/ingest_batch.py tests/unit/storage/test_session_product_refresh.py tests/unit/pipeline/test_ingest_batch.py`
- `python -m mypy polylogue/storage/session_product_rebuild.py polylogue/storage/session_product_refresh.py polylogue/pipeline/services/ingest_batch.py tests/unit/storage/test_session_product_refresh.py tests/unit/pipeline/test_ingest_batch.py tests/unit/pipeline/test_run_sources.py tests/unit/storage/test_product_materialization_laws.py tests/unit/cli/test_products.py tests/unit/core/test_facade_api.py tests/unit/cli/test_check.py tests/unit/storage/test_backend.py tests/unit/sources/test_compaction.py`
- `pytest -q tests/unit/storage/test_session_product_refresh.py tests/unit/pipeline/test_ingest_batch.py tests/unit/pipeline/test_run_sources.py`
- `pytest -q tests/unit/storage/test_product_materialization_laws.py tests/unit/cli/test_products.py tests/unit/core/test_facade_api.py tests/unit/cli/test_check.py tests/unit/storage/test_backend.py tests/unit/sources/test_compaction.py`
- `devtools verify`
@Sinity Sinity added area:parser Parser area:storage Storage tool:claude Claude type:refactor Code restructuring labels Apr 22, 2026
Sinity added a commit that referenced this pull request Apr 22, 2026
The session-product layer was split across path-dependent seams:
archive product payloads drifting between dict-shaped records and
model-backed products, product registry dispatch relying on dynamic
query resolution, refresh/rebuild using tuple- and dict-shaped
runtime plumbing, and the async writer/query modules cloning the
sync storage layer's insert assembly. Technically type-checked, but
ambiguous and duplicated at the exact points where the archive
materializes durable products.

Extracts shared archive product payload/base models into
`polylogue/archive_product_models.py` and propagates typed payloads
through archive products, mappers, records, writers, and the
affected tests. Rewrites `products/registry.py` to use direct query-
model references, immutable descriptor tuples, and typed nested
field access; CLI, MCP, and scenario surfaces adapt. Rebuilds
`session_product_rebuild.py` and `session_product_refresh.py`
around `SessionProductArchiveBatch`, `SessionProductRecordBundle`,
and `SessionProductRefreshChunkObservation`, with
`pipeline/services/ingest_batch.py` consuming typed refresh
telemetry instead of dict-key probing. Extracts shared insert-
column/value builders into `session_product_storage.py`; async
profile/timeline/thread/summary writers and sync/async provider-day
refresh now share the same prepared aggregate writes.

Absorbs direct fallout in affected tests, including a small
compaction assertion update revealed by the repo-wide verify pass.

Verification: ruff + mypy + pytest over the touched storage,
pipeline, and product tests; devtools verify green.

Ref #225
Sinity added a commit that referenced this pull request Apr 22, 2026
The session-product layer was split across path-dependent seams:
archive product payloads drifting between dict-shaped records and
model-backed products, product registry dispatch relying on dynamic
query resolution, refresh/rebuild using tuple- and dict-shaped
runtime plumbing, and the async writer/query modules cloning the
sync storage layer's insert assembly. Technically type-checked, but
ambiguous and duplicated at the exact points where the archive
materializes durable products.

Extracts shared archive product payload/base models into
`polylogue/archive_product_models.py` and propagates typed payloads
through archive products, mappers, records, writers, and the
affected tests. Rewrites `products/registry.py` to use direct query-
model references, immutable descriptor tuples, and typed nested
field access; CLI, MCP, and scenario surfaces adapt. Rebuilds
`session_product_rebuild.py` and `session_product_refresh.py`
around `SessionProductArchiveBatch`, `SessionProductRecordBundle`,
and `SessionProductRefreshChunkObservation`, with
`pipeline/services/ingest_batch.py` consuming typed refresh
telemetry instead of dict-key probing. Extracts shared insert-
column/value builders into `session_product_storage.py`; async
profile/timeline/thread/summary writers and sync/async provider-day
refresh now share the same prepared aggregate writes.

Absorbs direct fallout in affected tests, including a small
compaction assertion update revealed by the repo-wide verify pass.

Verification: ruff + mypy + pytest over the touched storage,
pipeline, and product tests; devtools verify green.

Ref #225
Sinity added a commit that referenced this pull request Apr 22, 2026
The session-product layer was split across path-dependent seams:
archive product payloads drifting between dict-shaped records and
model-backed products, product registry dispatch relying on dynamic
query resolution, refresh/rebuild using tuple- and dict-shaped
runtime plumbing, and the async writer/query modules cloning the
sync storage layer's insert assembly. Technically type-checked, but
ambiguous and duplicated at the exact points where the archive
materializes durable products.

Extracts shared archive product payload/base models into
`polylogue/archive_product_models.py` and propagates typed payloads
through archive products, mappers, records, writers, and the
affected tests. Rewrites `products/registry.py` to use direct query-
model references, immutable descriptor tuples, and typed nested
field access; CLI, MCP, and scenario surfaces adapt. Rebuilds
`session_product_rebuild.py` and `session_product_refresh.py`
around `SessionProductArchiveBatch`, `SessionProductRecordBundle`,
and `SessionProductRefreshChunkObservation`, with
`pipeline/services/ingest_batch.py` consuming typed refresh
telemetry instead of dict-key probing. Extracts shared insert-
column/value builders into `session_product_storage.py`; async
profile/timeline/thread/summary writers and sync/async provider-day
refresh now share the same prepared aggregate writes.

Absorbs direct fallout in affected tests, including a small
compaction assertion update revealed by the repo-wide verify pass.

Verification: ruff + mypy + pytest over the touched storage,
pipeline, and product tests; devtools verify green.

Ref #225
@Sinity

Sinity 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. 2 finding(s) confirmed still present → tracked in #550.

@Sinity

Sinity commented May 1, 2026

Copy link
Copy Markdown
Owner Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🚀

ℹ️ 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 removed the request for review from Copilot May 1, 2026 01:05
@Sinity

Sinity commented May 1, 2026

Copy link
Copy Markdown
Owner Author

@codex review

@Sinity
Sinity requested a review from Copilot May 1, 2026 01:51

@chatgpt-codex-connector chatgpt-codex-connector Bot 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: 5f40756caa

ℹ️ 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 removed the request for review from Copilot May 1, 2026 02:15
@Sinity

Sinity 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.

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

area:parser Parser area:storage Storage tool:claude Claude type:refactor Code restructuring

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant