Repository navigation
refactor: renew session product runtime and storage seams - #230
Conversation
📝 WalkthroughWalkthroughA comprehensive refactoring introduces shared Pydantic-based archive product payload models in a new module, relocates model definitions from distributed files, and replaces untyped Changes
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Suggested labels
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
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 | 🟠 MajorTreat 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
📒 Files selected for processing (34)
polylogue/archive_product_models.pypolylogue/archive_product_summaries.pypolylogue/archive_products.pypolylogue/cli/commands/products.pypolylogue/mcp/server_product_tools.pypolylogue/pipeline/services/ingest_batch.pypolylogue/products/registry.pypolylogue/scenarios/execution.pypolylogue/storage/backends/queries/mappers_product_aggregates.pypolylogue/storage/backends/queries/mappers_product_profiles.pypolylogue/storage/backends/queries/mappers_product_timelines.pypolylogue/storage/backends/queries/session_product_profile_writes.pypolylogue/storage/backends/queries/session_product_summary_queries.pypolylogue/storage/backends/queries/session_product_thread_queries.pypolylogue/storage/backends/queries/session_product_timeline_writes.pypolylogue/storage/session_product_aggregates.pypolylogue/storage/session_product_profiles.pypolylogue/storage/session_product_rebuild.pypolylogue/storage/session_product_refresh.pypolylogue/storage/session_product_storage.pypolylogue/storage/session_product_threads.pypolylogue/storage/session_product_timeline_rows.pypolylogue/storage/store.pypolylogue/storage/store_product_aggregate_records.pypolylogue/storage/store_product_session_records.pypolylogue/storage/store_product_timeline_records.pytests/unit/core/test_facade_api.pytests/unit/core/test_repo_identity.pytests/unit/mcp/test_tool_contracts.pytests/unit/pipeline/test_ingest_batch.pytests/unit/sources/test_compaction.pytests/unit/storage/test_session_product_profiles.pytests/unit/storage/test_session_product_refresh.pytests/unit/storage/test_session_product_timeline_rows.py
| 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) |
There was a problem hiding this comment.
🛠️ 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:
- 1: https://pydantic.dev/docs/validation/2.0/api/pydantic/config/
- 2: https://docs.pydantic.dev/2.6/api/config/
- 3: https://pydantic.dev/docs/validation/2.4/concepts/models/
- 4: https://pydantic.dev/docs/validation/latest/concepts/models/
- 5: https://stackoverflow.com/questions/75396856/pydantic-does-not-validate-the-key-values-of-dict-fields
🏁 Script executed:
cat -n polylogue/archive_product_models.py | head -160Repository: 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.
| 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 |
There was a problem hiding this comment.
🧹 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:
- 1: https://docs.pydantic.dev/2.8/api/fields/
- 2: https://pydantic.dev/docs/validation/2.3/api/pydantic/fields/
- 3: https://docs.pydantic.dev/2.1/api/fields/
- 4: https://docs.pydantic.dev/2.5/api/fields/
- 5: https://docs.pydantic.dev/2.11/api/fields/
- 6: https://docs.pydantic.dev/2.3/api/fields/
- 7: https://docs.pydantic.dev/2.9/api/fields/
- 8: Introspection of fields during validation pydantic/pydantic#6429
- 9: How to validate a field directly in v2 pydantic/pydantic#7367
🏁 Script executed:
# First, locate and examine the file
fd "server_product_tools.py" --type fRepository: Sinity/polylogue
Length of output: 97
🏁 Script executed:
# Read the file to examine the lines in question
wc -l polylogue/mcp/server_product_tools.pyRepository: Sinity/polylogue
Length of output: 101
🏁 Script executed:
# Read the specific lines and surrounding context
sed -n '30,55p' polylogue/mcp/server_product_tools.pyRepository: Sinity/polylogue
Length of output: 1145
🏁 Script executed:
# Check imports and Pydantic version
head -30 polylogue/mcp/server_product_tools.pyRepository: 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.pyRepository: Sinity/polylogue
Length of output: 42
🏁 Script executed:
# Check the ProductType definition to understand query_model
fd "registry.py" polylogue/products/ --type fRepository: Sinity/polylogue
Length of output: 90
🏁 Script executed:
# Check the ProductType definition
rg "query_model|FieldInfo|pydantic|PydanticUndefined" polylogue/products/registry.py -A 3Repository: 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 -100Repository: 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 10Repository: 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.pyRepository: Sinity/polylogue
Length of output: 4216
🏁 Script executed:
# Check the ArchiveProductModel base class
rg "class ArchiveProductModel" polylogue/ --type py -A 5Repository: 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.pyRepository: 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.pyRepository: 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.pyRepository: 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.
| 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 |
There was a problem hiding this comment.
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.
| 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), | ||
| ], | ||
| ), |
There was a problem hiding this comment.
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).
| payload=DaySessionSummaryPayload.model_validate( | ||
| _parse_json( | ||
| row["payload_json"], | ||
| field="payload_json", | ||
| record_id=f"{row['provider_name']}:{row['day']}", | ||
| ) | ||
| or {} | ||
| ), |
There was a problem hiding this comment.
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.
| 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.
| 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 []), | ||
| }, | ||
| } | ||
| ) |
There was a problem hiding this comment.
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.
| 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.
| 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 ()), | ||
| } | ||
| ) |
There was a problem hiding this comment.
🧩 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 -C1Repository: 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 -20Repository: 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=pyRepository: 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 -10Repository: 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=pyRepository: 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.pyRepository: 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.
| 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")) |
There was a problem hiding this comment.
🧩 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.pyRepository: Sinity/polylogue
Length of output: 2361
🏁 Script executed:
# Get full WorkThreadPayload class definition including parent class
head -200 polylogue/archive_product_models.py | tail -100Repository: Sinity/polylogue
Length of output: 3036
🏁 Script executed:
# Verify ArchiveProductModel base class
grep -n "class ArchiveProductModel" polylogue/archive_product_models.py -A 5Repository: 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.
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`
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
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
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
|
@codex review |
|
Codex Review: Didn't find any major issues. 🚀 ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
@codex review |
There was a problem hiding this comment.
💡 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".
|
Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.
Only the rows listed above are dispositioned. Held findings remain open. |
Ref #225
Summary
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
polylogue/archive_product_models.pyand propagate those typed payloads through archive products, mappers, records, writers, and affected testspolylogue/products/registry.pyto use direct query-model references, immutable descriptor tuples, and typed nested field access, then adapt the CLI, MCP, and scenario surfaces to that contractpolylogue/storage/session_product_rebuild.pyandpolylogue/storage/session_product_refresh.pyaroundSessionProductArchiveBatch,SessionProductRecordBundle, andSessionProductRefreshChunkObservation, and updatepolylogue/pipeline/services/ingest_batch.pyto consume that typed refresh telemetry instead of dict-key probingpolylogue/storage/session_product_storage.py, route the async profile/timeline/thread/summary writers through those helpers, and simplifypolylogue/storage/session_product_aggregates.pyso sync and async provider-day refresh paths apply the same prepared aggregate writesVerification
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.pypython -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.pypytest -q tests/unit/storage/test_session_product_refresh.py tests/unit/pipeline/test_ingest_batch.py tests/unit/pipeline/test_run_sources.pypytest -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.pydevtools verify