Repository navigation
refactor: rebuild storage and product runtime boundary contracts - #276
Conversation
📝 WalkthroughWalkthroughLarge refactoring that strengthens type contracts across storage/lib/product-runtime boundaries by introducing Protocol-based structural typing, typed query models for list operations, centralized JSON document handling with type-safe coercion, and standardized row mapping utilities. Replaces broad Changes
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 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: 12
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (4)
polylogue/storage/backends/query_store_product_timelines.py (1)
75-96:⚠️ Potential issue | 🟠 MajorForward the timeline search query for phases too.
SessionTimelineListQueryhas aqueryfield for full-text search, and work-event listing forwards it, butlist_session_phasesdrops that filter entirely. The lower-level query function checksif query.query:for work events but not for phases, preventing callers through this mixin from reaching the FTS capability.This same gap exists in the repository layer methods (
list_session_phasesandlist_session_phase_records).🐛 Proposed fix for query_store_product_timelines.py
async def list_session_phases( self, *, conversation_id: str | None = None, provider: str | None = None, since: str | None = None, until: str | None = None, kind: str | None = None, limit: int | None = 50, offset: int = 0, + query: str | None = None, ) -> list[SessionPhaseRecord]: return await self._list_session_phases_query( SessionTimelineListQuery( conversation_id=conversation_id, provider=provider, since=since, until=until, kind=kind, limit=limit, offset=offset, + query=query, ) )Apply the same fix to
list_session_phasesandlist_session_phase_recordsinpolylogue/storage/repository_product_timeline_reads.py.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@polylogue/storage/backends/query_store_product_timelines.py` around lines 75 - 96, list_session_phases currently builds a SessionTimelineListQuery but omits the full-text `query` field, so phase listing never receives the FTS filter; modify list_session_phases to accept and pass through the `query` parameter into the SessionTimelineListQuery (same symbol) and ensure the lower-level _list_session_phases_query will see query.query; apply the identical change to the repository-layer methods list_session_phases and list_session_phase_records in repository_product_timeline_reads.py so they also forward the SessionTimelineListQuery.query value.polylogue/storage/backends/queries/publications.py (1)
17-51: 🛠️ Refactor suggestion | 🟠 MajorDuplicate of
mappers._json_object; prefer importing the canonical helper.This is the same locally-redefined helper as in
polylogue/storage/backends/queries/runs.py. The mappers module already exposes a None-safe_json_object(value: JSONValue | None) -> JSONObject | None. SincePublicationRecord.manifestis typed as requiredJSONObject, using the mappers helper (which returnsNoneon empty/null) will also surface NULL/empty manifests clearly rather than relying onjson_documentto raise, and removes the cross-module duplication.♻️ Suggested fix
-from polylogue.lib.json import json_document -from polylogue.storage.backends.queries.mappers import _parse_json +from polylogue.storage.backends.queries.mappers import _json_object, _parse_json @@ -def _json_object(value: object) -> dict[str, object]: - document = json_document(value) - result: dict[str, object] = {} - for key, item in document.items(): - result[key] = item - return result - - async def get_latest_publication(Note: if
manifestmust remain non-optional, coerceNone -> {}explicitly at the call site so the invariant is visible.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@polylogue/storage/backends/queries/publications.py` around lines 17 - 51, The file redefines a local _json_object identical to mappers._json_object; remove the local helper and import and use mappers._json_object in get_latest_publication (and any other use sites) so you don't duplicate logic—call mappers._json_object around the result of _parse_json(row["manifest_json"], field="manifest_json", record_id=row["publication_id"]). If PublicationRecord.manifest must remain non-optional, explicitly coerce a None result to {} at the call site so the invariant is visible (e.g., manifest = mappers._json_object(...) or manifest = mappers._json_object(...) or {}).polylogue/storage/repository_product_thread_reads.py (1)
24-52: 🧹 Nitpick | 🔵 TrivialLGTM.
hydrate_optional/hydrate_sequencenicely replace the ad-hoc conditional and list-comprehension hydration. TheWorkThreadListQueryplumbing is duplicated verbatim inlist_work_threadsandlist_work_thread_records(lines 43–51 vs 63–71); if the argument lists drift, consider extracting a small_build_work_thread_query(...)helper, but it's fine as-is for a two-call-site duplication.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@polylogue/storage/repository_product_thread_reads.py` around lines 24 - 52, Duplicate construction of WorkThreadListQuery appears in list_work_threads and list_work_thread_records; extract a small helper (e.g., _build_work_thread_query) that accepts the parameters (since, until, limit, offset, query) and returns WorkThreadListQuery, then replace both sites (list_work_threads and list_work_thread_records/_list_work_thread_records_query callers) to call _build_work_thread_query(...) before passing the result to _list_work_thread_records_query or other query methods to remove verbatim duplication.polylogue/storage/repository_product_profile_reads.py (1)
51-145: 🧹 Nitpick | 🔵 TrivialCollapse duplicated
SessionProfileListQueryconstruction.
list_session_profiles,list_session_profile_records, andlist_session_enrichment_recordseach take the same keyword surface and build an identicalSessionProfileListQuery(onlytierdiffers for the enrichment variant). Extract a small helper to keep the three call sites in lock-step as fields are added to the query model.♻️ Proposed refactor
+ `@staticmethod` + def _build_profile_list_query( + *, + provider: str | None, + since: str | None, + until: str | None, + first_message_since: str | None, + first_message_until: str | None, + session_date_since: str | None, + session_date_until: str | None, + tier: str, + limit: int | None, + offset: int, + query: str | None, + ) -> SessionProfileListQuery: + return SessionProfileListQuery( + provider=provider, + since=since, + until=until, + first_message_since=first_message_since, + first_message_until=first_message_until, + session_date_since=session_date_since, + session_date_until=session_date_until, + tier=tier, + limit=limit, + offset=offset, + query=query, + )Then reuse it in all three call sites.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@polylogue/storage/repository_product_profile_reads.py` around lines 51 - 145, Multiple methods (list_session_profiles, list_session_profile_records, list_session_enrichment_records) duplicate construction of SessionProfileListQuery; extract a small helper like _build_session_profile_list_query(...) that accepts the shared parameters (provider, since, until, first_message_since, first_message_until, session_date_since, session_date_until, limit, offset, query) and returns a SessionProfileListQuery, then call that helper from each method and only override tier in list_session_enrichment_records (or allow tier as an optional param to the helper). Update usages of SessionProfileListQuery in those three methods to use _build_session_profile_list_query (and pass tier="enrichment" for get_session_enrichment_records) so all call sites remain in sync as fields change.
🤖 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/lib/action_events.py`:
- Around line 58-63: Change the ActionEventMessageLike protocol's id property
from object to str (i.e., def id(self) -> str) so it reflects the concrete
Message type; then remove the redundant str(...) coercions where message_id is
produced/assigned and where make_action_event_id is called (references:
ActionEventMessageLike, make_action_event_id, and the message_id / message.id
usages) so you rely on the typed string id directly.
In `@polylogue/lib/semantic_facts.py`:
- Around line 67-70: The Protocol type SemanticConversationMessagesLike is used
by the public contract (e.g., referenced by SemanticConversationLike.messages)
but is not exported; update the module exports by adding
"SemanticConversationMessagesLike" to the __all__ list(s) that export the public
Protocol types (the existing __all__ near the top and the similar __all__ block
around the later section), ensuring both declaration(s) include that symbol so
the public typed boundary is complete and consistent.
In `@polylogue/storage/backends/queries/mappers_archive.py`:
- Around line 107-111: Cache the result of _row_text(row, "payload_provider")
into a local variable (e.g., payload_provider_text) in the mapper where
payload_provider is built, then pass that local to Provider.from_string only
once and use it in the ternary
(payload_provider=Provider.from_string(payload_provider_text) if
payload_provider_text is not None else None); apply the same refactor in
_row_to_artifact_observation so both places follow the file's pattern of
extracting row text into a named local (matching how parent_conversation_id,
role, validation_status, etc. are handled).
In `@polylogue/storage/backends/queries/mappers_product_legacy.py`:
- Around line 291-345: The scalar coercion helpers (_legacy_text, _legacy_float,
_legacy_int, _legacy_bool) must tolerate bytes/bytearray and malformed strings
without raising: first detect bytes/bytearray and decode them (e.g.
value.decode('utf-8', errors='ignore')) before further processing; for
_legacy_float and _legacy_int wrap numeric conversion in try/except and return
the provided default on failure; for _legacy_bool, after decoding handle common
textual booleans ('0','1','false','true','no','yes') and numeric parsing in
try/except, falling back to False for unrecognized values; ensure _legacy_text
returns None for empty or whitespace-only decoded strings.
In `@polylogue/storage/backends/queries/mappers.py`:
- Around line 107-116: The helper _json_object currently treats an empty JSON
object as falsy and returns None, losing the distinction between an explicit {}
and null; change the logic in _json_object (and where it calls json_document) so
that only a None/absent document maps to None, while an empty dict is preserved
and returned as an empty JSONObject: call document = json_document(value), if
document is None return None, otherwise iterate document (or simply cast) to
build and return a JSONObject (including {}), referencing the _json_object
function and json_document/JSONObject types to locate the change.
In `@polylogue/storage/backends/queries/runs.py`:
- Around line 32-38: The code should validate that counts_payload is an object
before passing it to RunCounts.model_validate: after calling _parse_json for
"counts_json" (in the block constructing RunRecord), if counts_payload is None
keep counts=None, else if not isinstance(counts_payload, dict) raise a
DatabaseError (including field="counts_json" and record_id=row["run_id"]) to
match the other parsing errors, otherwise call
RunCounts.model_validate(counts_payload).to_payload(); update the counts=
assignment in the RunRecord construction accordingly to use these guards around
RunCounts.model_validate.
- Around line 18-38: The local helper _json_object used by get_latest_run is not
None-safe and duplicates the canonical function in mappers.py; replace the local
definition with an import from polylogue.storage.backends.queries.mappers (use
the existing mappers._json_object or exported name) and update get_latest_run to
call that imported _json_object for plan_snapshot and drift (ensuring it accepts
JSONValue | None as returned by _parse_json), removing the local function so
NULL JSON columns produce None instead of raising.
In `@polylogue/storage/backends/queries/session_product_summary_queries.py`:
- Around line 44-46: The tag search currently builds a LIKE pattern from
query.query without escaping SQL LIKE metacharacters, causing `%` and `_` in
user input to act as wildcards; update the code that appends to where and params
(the block that checks query.query and uses where.append("LOWER(tag) LIKE ?")
and params.append(...)) to first escape backslashes, percent and underscore in
the user string (e.g., s = query.query.strip().lower(); s = s.replace("\\",
"\\\\").replace("%", "\\%").replace("_", "\\_")), then build the pattern like
f"%{s}%" and append it to params, and change the SQL clause to include an ESCAPE
clause (e.g., where.append("LOWER(tag) LIKE ? ESCAPE '\\\\'")) so the escaped
characters are treated literally.
In `@polylogue/storage/repository_product_profile_reads.py`:
- Around line 45-49: The repository currently calls the private query helper
self.queries._list_session_profiles_query from
_list_session_profile_records_query, which crosses module boundaries and uses a
leading-underscore API; change this to use a public contract: either rename the
query-store method to list_session_profiles_query on SQLiteQueryStore and call
that, or route through the existing public list_session_profiles(...) API on
self.queries (accepting SessionProfileListQuery or expanded kwargs) so
_list_session_profile_records_query only invokes a non-underscored, public
method; update any sibling mixin timeline list usages the same way to remove
calls to _list_* helpers across modules.
In `@polylogue/storage/repository_product_summary_reads.py`:
- Around line 21-31: The wrapper methods _list_session_tag_rollup_rows_query and
_list_day_session_summary_records_query call module-private methods on
self.queries (_list_session_tag_rollup_rows_query and
_list_day_session_summaries_query) across mixin boundaries; either make the
query-store API public by renaming those target methods to remove the leading
underscore, or keep them private but add a short comment above these wrapper
methods stating that the cross-mixin access is intentional and these query
methods are treated as part of the typed contract; update whichever method
names/comments you choose consistently for both
_list_session_tag_rollup_rows_query and _list_day_session_summary_records_query
and their corresponding targets on the queries object.
In `@polylogue/storage/session_product_rebuild.py`:
- Around line 199-200: Normalize empty-string fields returned by _row_text to
None before any enum or typed construction: for both parent_conversation_id and
branch_type retrieved via _row_text, treat "" the same as NULL (set to None)
before passing to BranchType(branch_type) or any other constructor to avoid
ValueError on legacy/blank rows; apply the same blank-to-None normalization at
the analogous locations in polylogue/storage/backends/queries/mappers_archive.py
where branch_type and parent_conversation_id are hydrated.
In `@polylogue/storage/store_runtime_archive_records.py`:
- Around line 26-35: _coerce_json_object currently treats empty dicts as falsy
and returns None, collapsing {} to null; update it to preserve explicit empty
mappings by checking the original input type before coercion: if the incoming
value is None return None, if it's not a dict return None, otherwise coerce via
json_document(value) and return a shallow copy of the resulting mapping (use
dict(document) instead of the manual loop) so {} stays {} while non-dict inputs
map to None; refer to the _coerce_json_object function and json_document call to
locate the change.
---
Outside diff comments:
In `@polylogue/storage/backends/queries/publications.py`:
- Around line 17-51: The file redefines a local _json_object identical to
mappers._json_object; remove the local helper and import and use
mappers._json_object in get_latest_publication (and any other use sites) so you
don't duplicate logic—call mappers._json_object around the result of
_parse_json(row["manifest_json"], field="manifest_json",
record_id=row["publication_id"]). If PublicationRecord.manifest must remain
non-optional, explicitly coerce a None result to {} at the call site so the
invariant is visible (e.g., manifest = mappers._json_object(...) or manifest =
mappers._json_object(...) or {}).
In `@polylogue/storage/backends/query_store_product_timelines.py`:
- Around line 75-96: list_session_phases currently builds a
SessionTimelineListQuery but omits the full-text `query` field, so phase listing
never receives the FTS filter; modify list_session_phases to accept and pass
through the `query` parameter into the SessionTimelineListQuery (same symbol)
and ensure the lower-level _list_session_phases_query will see query.query;
apply the identical change to the repository-layer methods list_session_phases
and list_session_phase_records in repository_product_timeline_reads.py so they
also forward the SessionTimelineListQuery.query value.
In `@polylogue/storage/repository_product_profile_reads.py`:
- Around line 51-145: Multiple methods (list_session_profiles,
list_session_profile_records, list_session_enrichment_records) duplicate
construction of SessionProfileListQuery; extract a small helper like
_build_session_profile_list_query(...) that accepts the shared parameters
(provider, since, until, first_message_since, first_message_until,
session_date_since, session_date_until, limit, offset, query) and returns a
SessionProfileListQuery, then call that helper from each method and only
override tier in list_session_enrichment_records (or allow tier as an optional
param to the helper). Update usages of SessionProfileListQuery in those three
methods to use _build_session_profile_list_query (and pass tier="enrichment" for
get_session_enrichment_records) so all call sites remain in sync as fields
change.
In `@polylogue/storage/repository_product_thread_reads.py`:
- Around line 24-52: Duplicate construction of WorkThreadListQuery appears in
list_work_threads and list_work_thread_records; extract a small helper (e.g.,
_build_work_thread_query) that accepts the parameters (since, until, limit,
offset, query) and returns WorkThreadListQuery, then replace both sites
(list_work_threads and list_work_thread_records/_list_work_thread_records_query
callers) to call _build_work_thread_query(...) before passing the result to
_list_work_thread_records_query or other query methods to remove verbatim
duplication.
🪄 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: b25ddbf6-dd3b-44f7-99ce-b8171e9bcabb
📒 Files selected for processing (34)
polylogue/lib/action_events.pypolylogue/lib/semantic_fact_models.pypolylogue/lib/semantic_fact_support.pypolylogue/lib/semantic_facts.pypolylogue/pipeline/run_finalization.pypolylogue/schemas/verification_artifacts.pypolylogue/storage/artifact_queries.pypolylogue/storage/backends/queries/attachment_records.pypolylogue/storage/backends/queries/mappers.pypolylogue/storage/backends/queries/mappers_archive.pypolylogue/storage/backends/queries/mappers_product_aggregates.pypolylogue/storage/backends/queries/mappers_product_legacy.pypolylogue/storage/backends/queries/mappers_product_profiles.pypolylogue/storage/backends/queries/mappers_product_timelines.pypolylogue/storage/backends/queries/publications.pypolylogue/storage/backends/queries/raw_state.pypolylogue/storage/backends/queries/runs.pypolylogue/storage/backends/queries/session_product_profile_reads.pypolylogue/storage/backends/queries/session_product_summary_queries.pypolylogue/storage/backends/queries/session_product_thread_queries.pypolylogue/storage/backends/queries/session_product_timeline_reads.pypolylogue/storage/backends/query_store.pypolylogue/storage/backends/query_store_product_profiles.pypolylogue/storage/backends/query_store_product_timelines.pypolylogue/storage/product_read_support.pypolylogue/storage/query_models.pypolylogue/storage/repository_product_profile_reads.pypolylogue/storage/repository_product_summary_reads.pypolylogue/storage/repository_product_thread_reads.pypolylogue/storage/repository_product_timeline_reads.pypolylogue/storage/session_product_rebuild.pypolylogue/storage/store_runtime_archive_records.pytests/unit/site/test_builder.pytests/unit/storage/test_publications.py
| class ActionEventMessageLike(Protocol): | ||
| @property | ||
| def id(self) -> object: ... | ||
|
|
||
| @property | ||
| def timestamp(self) -> datetime | None: ... |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Confirm Message.id is str-typed and no caller passes a non-str id.
rg -nP -C2 '\bid\s*:\s*str\b' -g 'polylogue/**/message*.py'
ast-grep --pattern 'class Message($$$):
$$$
id: $_
$$$'Repository: Sinity/polylogue
Length of output: 2568
🏁 Script executed:
#!/bin/bash
# Check the complete action_events.py file to see lines 80-81 and context
wc -l polylogue/lib/action_events.py
head -n 100 polylogue/lib/action_events.py | tail -n 50Repository: Sinity/polylogue
Length of output: 1573
🏁 Script executed:
#!/bin/bash
# Search for all uses of message.id in action_events.py
rg -nP 'message\.id|make_action_event_id' polylogue/lib/action_events.py -A 2 -B 2Repository: Sinity/polylogue
Length of output: 467
🏁 Script executed:
#!/bin/bash
# Search for implementations/users of ActionEventMessageLike protocol
rg -nP 'ActionEventMessageLike' polylogue/Repository: Sinity/polylogue
Length of output: 276
🏁 Script executed:
#!/bin/bash
# Check if any code passes non-str values as message.id
rg -nP 'Message\(' polylogue/ -A 5 | grep -E 'id\s*[:=]'Repository: Sinity/polylogue
Length of output: 2286
🏁 Script executed:
#!/bin/bash
# See the function around line 111 that uses ActionEventMessageLike
sed -n '105,120p' polylogue/lib/action_events.pyRepository: Sinity/polylogue
Length of output: 421
🏁 Script executed:
#!/bin/bash
# Search for any other classes that might implement ActionEventMessageLike or use it
rg -nP 'class.*Protocol|implements.*ActionEventMessageLike' polylogue/ -A 3Repository: Sinity/polylogue
Length of output: 23722
🏁 Script executed:
#!/bin/bash
# Check if there are any test files or mocks that might use ActionEventMessageLike
find polylogue -name '*test*.py' -o -name '*mock*.py' | xargs rg -l 'ActionEventMessageLike' 2>/dev/null || echo "No test files found using ActionEventMessageLike"Repository: Sinity/polylogue
Length of output: 90
🏁 Script executed:
#!/bin/bash
# Check what make_action_event_id expects - find its definition
rg -nP 'def make_action_event_id' polylogue/ -A 3Repository: Sinity/polylogue
Length of output: 446
Tighten id to str in the protocol.
make_action_event_id (which expects message_id: str) and both message_id assignments wrap message.id in str(...) on lines 80–81. Since the concrete Message class already types id as str, narrowing the protocol from object to str eliminates the redundant coercions and prevents silent conversion of arbitrary objects to strings.
♻️ Suggested fix
class ActionEventMessageLike(Protocol):
`@property`
- def id(self) -> object: ...
+ def id(self) -> str: ...
`@property`
def timestamp(self) -> datetime | None: ...Then drop the str(...) coercions on lines 80–81.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@polylogue/lib/action_events.py` around lines 58 - 63, Change the
ActionEventMessageLike protocol's id property from object to str (i.e., def
id(self) -> str) so it reflects the concrete Message type; then remove the
redundant str(...) coercions where message_id is produced/assigned and where
make_action_event_id is called (references: ActionEventMessageLike,
make_action_event_id, and the message_id / message.id usages) so you rely on the
typed string id directly.
| class SemanticConversationMessagesLike(Protocol): | ||
| def __iter__(self) -> Iterator[SemanticConversationMessageLike]: ... | ||
|
|
||
| def __len__(self) -> int: ... |
There was a problem hiding this comment.
Export the message-collection protocol used by the public conversation contract.
SemanticConversationLike.messages exposes SemanticConversationMessagesLike, but __all__ omits it while exporting the other new Protocol types. Add it so the public typed boundary is complete and consistent.
Proposed fix
__all__ = [
"ProjectionAttachmentLike",
"ProjectionLike",
"ProjectionMessageLike",
"SemanticConversationLike",
+ "SemanticConversationMessagesLike",
"SemanticConversationMessageLike",
"SemanticSummaryLike",Also applies to: 388-394
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@polylogue/lib/semantic_facts.py` around lines 67 - 70, The Protocol type
SemanticConversationMessagesLike is used by the public contract (e.g.,
referenced by SemanticConversationLike.messages) but is not exported; update the
module exports by adding "SemanticConversationMessagesLike" to the __all__
list(s) that export the public Protocol types (the existing __all__ near the top
and the similar __all__ block around the later section), ensuring both
declaration(s) include that symbol so the public typed boundary is complete and
consistent.
| payload_provider=( | ||
| Provider.from_string(_row_get(row, "payload_provider")) | ||
| if _row_get(row, "payload_provider") is not None | ||
| Provider.from_string(_row_text(row, "payload_provider")) | ||
| if _row_text(row, "payload_provider") is not None | ||
| else None | ||
| ), |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Cache payload_provider text into a local, matching the pattern used elsewhere in this file.
_row_text(row, "payload_provider") is invoked twice in each branch. The rest of the file already extracts once into a named local (see parent_conversation_id, role, validation_status, validation_provider, validation_mode). Following the same convention avoids a second row lookup and makes the mapper uniform.
♻️ Proposed refactor
def _row_to_raw_conversation(row: sqlite3.Row) -> RawConversationRecord:
validation_status = _row_text(row, "validation_status")
validation_provider = _row_text(row, "validation_provider")
validation_mode = _row_text(row, "validation_mode")
+ payload_provider = _row_text(row, "payload_provider")
return RawConversationRecord(
raw_id=row["raw_id"],
provider_name=row["provider_name"],
- payload_provider=(
- Provider.from_string(_row_text(row, "payload_provider"))
- if _row_text(row, "payload_provider") is not None
- else None
- ),
+ payload_provider=(
+ Provider.from_string(payload_provider) if payload_provider is not None else None
+ ),Apply the analogous change in _row_to_artifact_observation.
Also applies to: 134-138
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@polylogue/storage/backends/queries/mappers_archive.py` around lines 107 -
111, Cache the result of _row_text(row, "payload_provider") into a local
variable (e.g., payload_provider_text) in the mapper where payload_provider is
built, then pass that local to Provider.from_string only once and use it in the
ternary (payload_provider=Provider.from_string(payload_provider_text) if
payload_provider_text is not None else None); apply the same refactor in
_row_to_artifact_observation so both places follow the file's pattern of
extracting row text into a named local (matching how parent_conversation_id,
role, validation_status, etc. are handled).
| def _legacy_text(value: JSONValue | bytes | bytearray) -> str | None: | ||
| if value is None: | ||
| return None | ||
| text = str(value) | ||
| return text if text else None | ||
|
|
||
|
|
||
| def _legacy_float(value: object, default: float = 0.0) -> float: | ||
| def _legacy_float(value: JSONValue | bytes | bytearray, default: float = 0.0) -> float: | ||
| if isinstance(value, bool): | ||
| return float(int(value)) | ||
| if isinstance(value, str | int | float): | ||
| return float(value or default) | ||
| return default | ||
|
|
||
|
|
||
| def _legacy_int(value: object, default: int = 0) -> int: | ||
| def _legacy_int(value: JSONValue | bytes | bytearray, default: int = 0) -> int: | ||
| if isinstance(value, bool): | ||
| return int(value) | ||
| if isinstance(value, str | int | float): | ||
| return int(value or default) | ||
| return default | ||
|
|
||
|
|
||
| def _legacy_text_tuple(value: object) -> tuple[str, ...]: | ||
| def _legacy_text_tuple( | ||
| value: JSONValue | bytes | bytearray | list[JSONValue] | tuple[JSONValue, ...], | ||
| ) -> tuple[str, ...]: | ||
| if not isinstance(value, Iterable) or isinstance(value, str | bytes | Mapping): | ||
| return () | ||
| return tuple(str(item) for item in value if item is not None) | ||
|
|
||
|
|
||
| def _legacy_dict_tuple(value: object) -> tuple[dict[str, object], ...]: | ||
| def _legacy_dict_tuple( | ||
| value: JSONValue | list[JSONValue] | tuple[JSONValue, ...] | bytes | bytearray, | ||
| ) -> tuple[LegacyPayload, ...]: | ||
| if not isinstance(value, Iterable) or isinstance(value, str | bytes | Mapping): | ||
| return () | ||
| items: list[dict[str, object]] = [] | ||
| items: list[LegacyPayload] = [] | ||
| for item in value: | ||
| if isinstance(item, Mapping): | ||
| items.append({str(key): val for key, val in item.items()}) | ||
| items.append(json_document(dict(item))) | ||
| return tuple(items) | ||
|
|
||
|
|
||
| def _legacy_int_dict(value: object) -> dict[str, int]: | ||
| def _legacy_int_dict(value: JSONValue | bytes | bytearray | Mapping[str, JSONValue]) -> dict[str, int]: | ||
| if not isinstance(value, Mapping): | ||
| return {} | ||
| return {str(key): int(item) for key, item in value.items() if item is not None} | ||
| return {str(key): _legacy_int(item) for key, item in value.items() if item is not None} | ||
|
|
||
|
|
||
| def _legacy_bool(value: JSONValue | bytes | bytearray) -> bool: | ||
| if isinstance(value, bool): | ||
| return value | ||
| if isinstance(value, str | int | float): | ||
| return bool(int(value or 0)) | ||
| return bool(value) |
There was a problem hiding this comment.
Make legacy scalar coercion actually tolerate bytes and malformed values.
These helpers now accept bytes | bytearray, but _legacy_int(b"12") returns the default, _legacy_bool(b"0") returns True, and invalid strings like "unknown" raise. A malformed legacy payload can abort hydration instead of falling back.
🐛 Proposed fix
+def _legacy_scalar_text(value: JSONValue | bytes | bytearray) -> str | None:
+ if value is None:
+ return None
+ if isinstance(value, bytes | bytearray):
+ return value.decode("utf-8", errors="replace")
+ if isinstance(value, str):
+ return value
+ return None
+
+
def _legacy_text(value: JSONValue | bytes | bytearray) -> str | None:
if value is None:
return None
- text = str(value)
+ text = _legacy_scalar_text(value) if isinstance(value, str | bytes | bytearray) else str(value)
return text if text else None
def _legacy_float(value: JSONValue | bytes | bytearray, default: float = 0.0) -> float:
if isinstance(value, bool):
return float(int(value))
- if isinstance(value, str | int | float):
- return float(value or default)
+ if isinstance(value, int | float):
+ try:
+ return float(value)
+ except (OverflowError, ValueError):
+ return default
+ text = _legacy_scalar_text(value)
+ if text is not None:
+ try:
+ return float(text or default)
+ except ValueError:
+ return default
return default
def _legacy_int(value: JSONValue | bytes | bytearray, default: int = 0) -> int:
if isinstance(value, bool):
return int(value)
- if isinstance(value, str | int | float):
- return int(value or default)
+ if isinstance(value, int | float):
+ try:
+ return int(value)
+ except (OverflowError, ValueError):
+ return default
+ text = _legacy_scalar_text(value)
+ if text is not None:
+ try:
+ return int(text or default)
+ except ValueError:
+ return default
return default
@@
def _legacy_text_tuple(
value: JSONValue | bytes | bytearray | list[JSONValue] | tuple[JSONValue, ...],
) -> tuple[str, ...]:
- if not isinstance(value, Iterable) or isinstance(value, str | bytes | Mapping):
+ if not isinstance(value, Iterable) or isinstance(value, str | bytes | bytearray | Mapping):
return ()
return tuple(str(item) for item in value if item is not None)
@@
def _legacy_bool(value: JSONValue | bytes | bytearray) -> bool:
if isinstance(value, bool):
return value
- if isinstance(value, str | int | float):
- return bool(int(value or 0))
- return bool(value)
+ if isinstance(value, int | float):
+ return bool(value)
+ text = _legacy_scalar_text(value)
+ if text is None:
+ return False
+ normalized = text.strip().lower()
+ if normalized in {"1", "true", "yes"}:
+ return True
+ if normalized in {"", "0", "false", "no"}:
+ return False
+ return False📝 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.
| def _legacy_text(value: JSONValue | bytes | bytearray) -> str | None: | |
| if value is None: | |
| return None | |
| text = str(value) | |
| return text if text else None | |
| def _legacy_float(value: object, default: float = 0.0) -> float: | |
| def _legacy_float(value: JSONValue | bytes | bytearray, default: float = 0.0) -> float: | |
| if isinstance(value, bool): | |
| return float(int(value)) | |
| if isinstance(value, str | int | float): | |
| return float(value or default) | |
| return default | |
| def _legacy_int(value: object, default: int = 0) -> int: | |
| def _legacy_int(value: JSONValue | bytes | bytearray, default: int = 0) -> int: | |
| if isinstance(value, bool): | |
| return int(value) | |
| if isinstance(value, str | int | float): | |
| return int(value or default) | |
| return default | |
| def _legacy_text_tuple(value: object) -> tuple[str, ...]: | |
| def _legacy_text_tuple( | |
| value: JSONValue | bytes | bytearray | list[JSONValue] | tuple[JSONValue, ...], | |
| ) -> tuple[str, ...]: | |
| if not isinstance(value, Iterable) or isinstance(value, str | bytes | Mapping): | |
| return () | |
| return tuple(str(item) for item in value if item is not None) | |
| def _legacy_dict_tuple(value: object) -> tuple[dict[str, object], ...]: | |
| def _legacy_dict_tuple( | |
| value: JSONValue | list[JSONValue] | tuple[JSONValue, ...] | bytes | bytearray, | |
| ) -> tuple[LegacyPayload, ...]: | |
| if not isinstance(value, Iterable) or isinstance(value, str | bytes | Mapping): | |
| return () | |
| items: list[dict[str, object]] = [] | |
| items: list[LegacyPayload] = [] | |
| for item in value: | |
| if isinstance(item, Mapping): | |
| items.append({str(key): val for key, val in item.items()}) | |
| items.append(json_document(dict(item))) | |
| return tuple(items) | |
| def _legacy_int_dict(value: object) -> dict[str, int]: | |
| def _legacy_int_dict(value: JSONValue | bytes | bytearray | Mapping[str, JSONValue]) -> dict[str, int]: | |
| if not isinstance(value, Mapping): | |
| return {} | |
| return {str(key): int(item) for key, item in value.items() if item is not None} | |
| return {str(key): _legacy_int(item) for key, item in value.items() if item is not None} | |
| def _legacy_bool(value: JSONValue | bytes | bytearray) -> bool: | |
| if isinstance(value, bool): | |
| return value | |
| if isinstance(value, str | int | float): | |
| return bool(int(value or 0)) | |
| return bool(value) | |
| def _legacy_scalar_text(value: JSONValue | bytes | bytearray) -> str | None: | |
| if value is None: | |
| return None | |
| if isinstance(value, bytes | bytearray): | |
| return value.decode("utf-8", errors="replace") | |
| if isinstance(value, str): | |
| return value | |
| return None | |
| def _legacy_text(value: JSONValue | bytes | bytearray) -> str | None: | |
| if value is None: | |
| return None | |
| text = _legacy_scalar_text(value) if isinstance(value, str | bytes | bytearray) else str(value) | |
| return text if text else None | |
| def _legacy_float(value: JSONValue | bytes | bytearray, default: float = 0.0) -> float: | |
| if isinstance(value, bool): | |
| return float(int(value)) | |
| if isinstance(value, int | float): | |
| try: | |
| return float(value) | |
| except (OverflowError, ValueError): | |
| return default | |
| text = _legacy_scalar_text(value) | |
| if text is not None: | |
| try: | |
| return float(text or default) | |
| except ValueError: | |
| return default | |
| return default | |
| def _legacy_int(value: JSONValue | bytes | bytearray, default: int = 0) -> int: | |
| if isinstance(value, bool): | |
| return int(value) | |
| if isinstance(value, int | float): | |
| try: | |
| return int(value) | |
| except (OverflowError, ValueError): | |
| return default | |
| text = _legacy_scalar_text(value) | |
| if text is not None: | |
| try: | |
| return int(text or default) | |
| except ValueError: | |
| return default | |
| return default | |
| def _legacy_text_tuple( | |
| value: JSONValue | bytes | bytearray | list[JSONValue] | tuple[JSONValue, ...], | |
| ) -> tuple[str, ...]: | |
| if not isinstance(value, Iterable) or isinstance(value, str | bytes | bytearray | Mapping): | |
| return () | |
| return tuple(str(item) for item in value if item is not None) | |
| def _legacy_dict_tuple( | |
| value: JSONValue | list[JSONValue] | tuple[JSONValue, ...] | bytes | bytearray, | |
| ) -> tuple[LegacyPayload, ...]: | |
| if not isinstance(value, Iterable) or isinstance(value, str | bytes | Mapping): | |
| return () | |
| items: list[LegacyPayload] = [] | |
| for item in value: | |
| if isinstance(item, Mapping): | |
| items.append(json_document(dict(item))) | |
| return tuple(items) | |
| def _legacy_int_dict(value: JSONValue | bytes | bytearray | Mapping[str, JSONValue]) -> dict[str, int]: | |
| if not isinstance(value, Mapping): | |
| return {} | |
| return {str(key): _legacy_int(item) for key, item in value.items() if item is not None} | |
| def _legacy_bool(value: JSONValue | bytes | bytearray) -> bool: | |
| if isinstance(value, bool): | |
| return value | |
| if isinstance(value, int | float): | |
| return bool(value) | |
| text = _legacy_scalar_text(value) | |
| if text is None: | |
| return False | |
| normalized = text.strip().lower() | |
| if normalized in {"1", "true", "yes"}: | |
| return True | |
| if normalized in {"", "0", "false", "no"}: | |
| return False | |
| return False |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@polylogue/storage/backends/queries/mappers_product_legacy.py` around lines
291 - 345, The scalar coercion helpers (_legacy_text, _legacy_float,
_legacy_int, _legacy_bool) must tolerate bytes/bytearray and malformed strings
without raising: first detect bytes/bytearray and decode them (e.g.
value.decode('utf-8', errors='ignore')) before further processing; for
_legacy_float and _legacy_int wrap numeric conversion in try/except and return
the provided default on failure; for _legacy_bool, after decoding handle common
textual booleans ('0','1','false','true','no','yes') and numeric parsing in
try/except, falling back to False for unrecognized values; ensure _legacy_text
returns None for empty or whitespace-only decoded strings.
| def _json_object(value: JSONValue | None) -> JSONObject | None: | ||
| if value is None: | ||
| return None | ||
| document = json_document(value) | ||
| if not document: | ||
| return None | ||
| result: JSONObject = {} | ||
| for key, item in document.items(): | ||
| result[key] = item | ||
| return result |
There was a problem hiding this comment.
Preserve empty JSON objects.
_json_object({}) currently returns None, which loses the distinction between an explicitly persisted empty object and a missing/null JSON value. That can break null-preserving hydration semantics.
🐛 Proposed fix
def _json_object(value: JSONValue | None) -> JSONObject | None:
if value is None:
return None
- document = json_document(value)
- if not document:
+ if not isinstance(value, dict):
return None
result: JSONObject = {}
- for key, item in document.items():
+ for key, item in json_document(value).items():
result[key] = item
return result🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@polylogue/storage/backends/queries/mappers.py` around lines 107 - 116, The
helper _json_object currently treats an empty JSON object as falsy and returns
None, losing the distinction between an explicit {} and null; change the logic
in _json_object (and where it calls json_document) so that only a None/absent
document maps to None, while an empty dict is preserved and returned as an empty
JSONObject: call document = json_document(value), if document is None return
None, otherwise iterate document (or simply cast) to build and return a
JSONObject (including {}), referencing the _json_object function and
json_document/JSONObject types to locate the change.
| if query.query: | ||
| where.append("LOWER(tag) LIKE ?") | ||
| params.append(f"%{query.strip().lower()}%") | ||
| params.append(f"%{query.query.strip().lower()}%") |
There was a problem hiding this comment.
User-provided tag query is interpolated into a LIKE pattern without escaping % / _.
A user searching for, say, "v1_0" or "50%" will hit unintended wildcard behavior. The query is still parameterized (no injection), but matches won't correspond to what users expect. Escape LIKE metacharacters and use an ESCAPE clause.
🛡️ Proposed fix
if query.query:
- where.append("LOWER(tag) LIKE ?")
- params.append(f"%{query.query.strip().lower()}%")
+ escaped = query.query.strip().lower().replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
+ where.append(r"LOWER(tag) LIKE ? ESCAPE '\'")
+ params.append(f"%{escaped}%")📝 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.
| if query.query: | |
| where.append("LOWER(tag) LIKE ?") | |
| params.append(f"%{query.strip().lower()}%") | |
| params.append(f"%{query.query.strip().lower()}%") | |
| if query.query: | |
| escaped = query.query.strip().lower().replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") | |
| where.append(r"LOWER(tag) LIKE ? ESCAPE '\'") | |
| params.append(f"%{escaped}%") |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@polylogue/storage/backends/queries/session_product_summary_queries.py` around
lines 44 - 46, The tag search currently builds a LIKE pattern from query.query
without escaping SQL LIKE metacharacters, causing `%` and `_` in user input to
act as wildcards; update the code that appends to where and params (the block
that checks query.query and uses where.append("LOWER(tag) LIKE ?") and
params.append(...)) to first escape backslashes, percent and underscore in the
user string (e.g., s = query.query.strip().lower(); s = s.replace("\\",
"\\\\").replace("%", "\\%").replace("_", "\\_")), then build the pattern like
f"%{s}%" and append it to params, and change the SQL clause to include an ESCAPE
clause (e.g., where.append("LOWER(tag) LIKE ? ESCAPE '\\\\'")) so the escaped
characters are treated literally.
| async def _list_session_profile_records_query( | ||
| self, | ||
| query: SessionProfileListQuery, | ||
| ) -> list[SessionProfileRecord]: | ||
| return await self.queries._list_session_profiles_query(query) |
There was a problem hiding this comment.
🛠️ Refactor suggestion | 🟠 Major
Avoid calling leading-underscore methods across module boundaries.
self.queries._list_session_profiles_query(...) invokes a name-mangled-by-convention "private" helper on SQLiteQueryStore from a different module. The same pattern appears for timeline list helpers in the sibling mixin. If the query-store method is part of the typed-query contract the repository layer relies on, rename it (e.g. list_session_profiles_query) and expose it as public API; otherwise route through the existing public list_session_profiles(**kwargs) path. As is, external use of underscored symbols invites future churn and weakens the "read-only contract / substrate-first boundary" intent of this PR.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@polylogue/storage/repository_product_profile_reads.py` around lines 45 - 49,
The repository currently calls the private query helper
self.queries._list_session_profiles_query from
_list_session_profile_records_query, which crosses module boundaries and uses a
leading-underscore API; change this to use a public contract: either rename the
query-store method to list_session_profiles_query on SQLiteQueryStore and call
that, or route through the existing public list_session_profiles(...) API on
self.queries (accepting SessionProfileListQuery or expanded kwargs) so
_list_session_profile_records_query only invokes a non-underscored, public
method; update any sibling mixin timeline list usages the same way to remove
calls to _list_* helpers across modules.
| async def _list_session_tag_rollup_rows_query( | ||
| self, | ||
| query: SessionTagRollupListQuery, | ||
| ) -> list[SessionTagRollupRecord]: | ||
| return await self.queries._list_session_tag_rollup_rows_query(query) | ||
|
|
||
| async def _list_day_session_summary_records_query( | ||
| self, | ||
| query: DaySessionSummaryListQuery, | ||
| ) -> list[DaySessionSummaryRecord]: | ||
| return await self.queries._list_day_session_summaries_query(query) |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Minor: calling _-prefixed methods across mixin boundaries.
_list_session_tag_rollup_rows_query / _list_day_session_summaries_query are module-private by convention on SQLiteQueryStore but are consumed from a different class here. Since this pattern is already adopted uniformly across the PR, it's consistent, but consider either dropping the underscore (these are de-facto part of the query-store's typed contract) or adding a brief comment noting the intentional cross-mixin coupling.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@polylogue/storage/repository_product_summary_reads.py` around lines 21 - 31,
The wrapper methods _list_session_tag_rollup_rows_query and
_list_day_session_summary_records_query call module-private methods on
self.queries (_list_session_tag_rollup_rows_query and
_list_day_session_summaries_query) across mixin boundaries; either make the
query-store API public by renaming those target methods to remove the leading
underscore, or keep them private but add a short comment above these wrapper
methods stating that the cross-mixin access is intentional and these query
methods are treated as part of the typed contract; update whichever method
names/comments you choose consistently for both
_list_session_tag_rollup_rows_query and _list_day_session_summary_records_query
and their corresponding targets on the queries object.
| parent_conversation_id = _row_text(row, "parent_conversation_id") | ||
| branch_type = _row_text(row, "branch_type") |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Expect to find either schema constraints/writer normalization that prevent empty
# branch_type values, or otherwise apply the mapper-side normalization above.
rg -n -C3 '\bbranch_type\b' --glob '!**/.venv/**' --glob '!**/node_modules/**'Repository: Sinity/polylogue
Length of output: 50372
🏁 Script executed:
#!/bin/bash
# Find _row_text definition to understand its behavior
rg -n "def _row_text" -A 3Repository: Sinity/polylogue
Length of output: 1159
🏁 Script executed:
#!/bin/bash
# Verify the fix applies to both session_product_rebuild.py and mappers_archive.py
# Check context around lines 199-200 and 39-40 respectively
echo "=== session_product_rebuild.py lines 195-220 ===" && \
sed -n '195,220p' polylogue/storage/session_product_rebuild.py && \
echo -e "\n=== mappers_archive.py lines 35-60 ===" && \
sed -n '35,60p' polylogue/storage/backends/queries/mappers_archive.pyRepository: Sinity/polylogue
Length of output: 2382
🏁 Script executed:
#!/bin/bash
# Complete the _row_text definition to see full implementation
sed -n '60,70p' polylogue/storage/backends/queries/mappers.pyRepository: Sinity/polylogue
Length of output: 459
🏁 Script executed:
#!/bin/bash
# Check if there are any test cases or references showing empty strings for branch_type
rg "branch_type.*=.*['\"]\"['\"]|branch_type.*=.*''" --type py -nRepository: Sinity/polylogue
Length of output: 421
🏁 Script executed:
#!/bin/bash
# Verify the imports in session_product_rebuild.py to see if it uses _row_text from the same module
head -50 polylogue/storage/session_product_rebuild.py | grep -E "^from|^import|_row_text"Repository: Sinity/polylogue
Length of output: 1125
🏁 Script executed:
#!/bin/bash
# Check if mappers_archive.py also imports _row_text from mappers.py (to confirm same function)
grep -n "from.*_row_text\|import.*_row_text" polylogue/storage/backends/queries/mappers_archive.pyRepository: Sinity/polylogue
Length of output: 205
🏁 Script executed:
#!/bin/bash
# Look for any test data or migration that might create empty branch_type values
rg "branch_type.*['\"]\"['\"]|INSERT.*branch_type.*['\"]\"['\"]" --type py --type sql -nRepository: Sinity/polylogue
Length of output: 173
Normalize blank parent/branch fields before enum hydration.
Line 215 casts any non-NULL value with BranchType(branch_type). Since _row_text can return "" (empty string), historical rows or legacy data with a blank branch_type will raise ValueError and abort session-product rebuild. Treat blank parent/branch fields as missing before casting.
🐛 Proposed fix
- parent_conversation_id = _row_text(row, "parent_conversation_id")
- branch_type = _row_text(row, "branch_type")
+ parent_conversation_id = _row_text(row, "parent_conversation_id") or None
+ branch_type = _row_text(row, "branch_type") or None
@@
- parent_conversation_id=ConversationId(parent_conversation_id) if parent_conversation_id is not None else None,
- branch_type=BranchType(branch_type) if branch_type is not None else None,
+ parent_conversation_id=ConversationId(parent_conversation_id) if parent_conversation_id else None,
+ branch_type=BranchType(branch_type) if branch_type else None,Also applies to polylogue/storage/backends/queries/mappers_archive.py:39-40, 55-56.
🤖 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 199 - 200,
Normalize empty-string fields returned by _row_text to None before any enum or
typed construction: for both parent_conversation_id and branch_type retrieved
via _row_text, treat "" the same as NULL (set to None) before passing to
BranchType(branch_type) or any other constructor to avoid ValueError on
legacy/blank rows; apply the same blank-to-None normalization at the analogous
locations in polylogue/storage/backends/queries/mappers_archive.py where
branch_type and parent_conversation_id are hydrated.
| def _coerce_json_object(value: object) -> JSONObject | None: | ||
| if value is None: | ||
| return None | ||
| document = json_document(value) | ||
| if not document: | ||
| return None | ||
| result: JSONObject = {} | ||
| for key, item in document.items(): | ||
| result[key] = item | ||
| return result |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Look for assertions or comparisons that could regress under the {} -> None coercion
rg -nP -C2 '\.(provider_meta|metadata|plan_snapshot|drift)\s*(==|is\s+None|is\s+not\s+None)'
rg -nP -C2 'assert(_equal)?\s*\(.*(provider_meta|plan_snapshot|drift|metadata)'Repository: Sinity/polylogue
Length of output: 17008
_coerce_json_object silently collapses empty JSON objects to None, breaking round-trip semantics.
if not document: return None treats {} as absent. Every time a record with stored provider_meta = {} / metadata = {} / plan_snapshot = {} / drift = {} (or attachment provider_meta = {}) is hydrated, the field becomes None. This is a semantic regression from "empty object" to "missing", and breaks tests like test_pipeline_ids.py:77 which explicitly assert attachment.provider_meta == {}.
The distinction between "explicitly empty" and "null/missing" is critical for equality/diff logic and field semantics. While PublicationRecord.manifest papers over this with or {}, other fields are exposed.
The fix should check the original input type before coercion: return None only for non-dict inputs, and preserve empty dicts as-is. Also, replace the hand-rolled shallow copy with idiomatic dict(...).
🐛 Proposed fix
def _coerce_json_object(value: object) -> JSONObject | None:
if value is None:
return None
document = json_document(value)
- if not document:
- return None
- result: JSONObject = {}
- for key, item in document.items():
- result[key] = item
- return result
+ # json_document() returns {} for non-dict/non-string-keyed inputs; distinguish
+ # those from a legitimately-empty dict by checking the original value first.
+ if not isinstance(value, dict):
+ return None
+ return dict(document)🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@polylogue/storage/store_runtime_archive_records.py` around lines 26 - 35,
_coerce_json_object currently treats empty dicts as falsy and returns None,
collapsing {} to null; update it to preserve explicit empty mappings by checking
the original input type before coercion: if the incoming value is None return
None, if it's not a dict return None, otherwise coerce via json_document(value)
and return a shallow copy of the resulting mapping (use dict(document) instead
of the manual loop) so {} stays {} while non-dict inputs map to None; refer to
the _coerce_json_object function and json_document call to locate the change.
## Summary - centralize typed storage query contracts for session-profile, timeline, thread, and artifact reads - tighten archive/run hydration around explicit row coercion helpers instead of loose row-value plumbing - normalize semantic-fact protocols so Conversation, MessageCollection, and action-event callers satisfy the intended read-only contracts ## Problem The storage/lib/product-runtime tranche still relied on repeated result-shape normalization, loose row hydration, and protocol contracts that were only mypy-clean because values flowed through weak helper types. That left duplicated coercion logic across repository/product mappers and made downstream semantic-fact callers depend on accidental mutability assumptions. ## Solution - add explicit query dataclasses and shared product-read hydration helpers for profile/timeline/thread/artifact reads - rebuild row-mapper support around typed JSON parsing, scalar coercion, JSON tuple/dict helpers, and null-preserving run hydration - tighten semantic action-event and semantic-fact protocols to model read-only properties and iterable message collections actually used by the domain models - update the small publication-manifest tests that index persisted JSON manifests through typed object boundaries ## Verification - `devtools verify` - `mypy polylogue/storage/backends/queries/mappers.py polylogue/storage/backends/queries/mappers_archive.py polylogue/storage/backends/queries/mappers_product_profiles.py polylogue/storage/backends/queries/mappers_product_timelines.py polylogue/storage/backends/queries/mappers_product_aggregates.py polylogue/storage/backends/queries/attachment_records.py polylogue/storage/session_product_rebuild.py polylogue/lib/action_events.py polylogue/lib/semantic_fact_support.py polylogue/lib/semantic_facts.py polylogue/lib/pricing.py polylogue/storage/action_event_rows.py polylogue/pipeline/services/ingest_worker.py polylogue/pipeline/run_finalization.py polylogue/cli/query_stats.py polylogue/cli/query_semantic.py polylogue/lib/query_retrieval_search.py polylogue/lib/session_profile_runtime.py polylogue/lib/phase_extraction.py polylogue/lib/attribution.py polylogue/lib/work_event_extraction.py tests/unit/storage/test_publications.py tests/unit/site/test_builder.py tests/unit/core/test_semantic_facts.py` - `pytest -q tests/unit/storage/test_query_mappers.py tests/unit/storage/test_publications.py tests/unit/site/test_builder.py tests/unit/core/test_semantic_facts.py` - `pytest -q tests/unit/cli/test_run_int.py -k latest_run_parsing` Closes #272
The storage/lib/product-runtime tranche relied on repeated result-shape normalization, loose row hydration, and protocol contracts that were only mypy-clean because values flowed through weak helper types. Coercion logic was duplicated across repository/product mappers, and downstream semantic-fact callers depended on accidental mutability assumptions. Adds explicit query dataclasses and shared product-read hydration helpers for profile / timeline / thread / artifact reads. Rebuilds row-mapper support around typed JSON parsing, scalar coercion, JSON tuple/dict helpers, and null-preserving run hydration. Tightens semantic action-event and semantic-fact protocols to model read-only properties and iterable message collections actually used by the domain models. Updates the small publication-manifest tests that index persisted JSON manifests through typed object boundaries. Verification: mypy + pytest over storage query mappers, publications, site builder, and semantic-facts suites; devtools verify green. Closes #272
The storage/lib/product-runtime tranche relied on repeated result-shape normalization, loose row hydration, and protocol contracts that were only mypy-clean because values flowed through weak helper types. Coercion logic was duplicated across repository/product mappers, and downstream semantic-fact callers depended on accidental mutability assumptions. Adds explicit query dataclasses and shared product-read hydration helpers for profile / timeline / thread / artifact reads. Rebuilds row-mapper support around typed JSON parsing, scalar coercion, JSON tuple/dict helpers, and null-preserving run hydration. Tightens semantic action-event and semantic-fact protocols to model read-only properties and iterable message collections actually used by the domain models. Updates the small publication-manifest tests that index persisted JSON manifests through typed object boundaries. Verification: mypy + pytest over storage query mappers, publications, site builder, and semantic-facts suites; devtools verify green. Closes #272
The storage/lib/product-runtime tranche relied on repeated result-shape normalization, loose row hydration, and protocol contracts that were only mypy-clean because values flowed through weak helper types. Coercion logic was duplicated across repository/product mappers, and downstream semantic-fact callers depended on accidental mutability assumptions. Adds explicit query dataclasses and shared product-read hydration helpers for profile / timeline / thread / artifact reads. Rebuilds row-mapper support around typed JSON parsing, scalar coercion, JSON tuple/dict helpers, and null-preserving run hydration. Tightens semantic action-event and semantic-fact protocols to model read-only properties and iterable message collections actually used by the domain models. Updates the small publication-manifest tests that index persisted JSON manifests through typed object boundaries. Verification: mypy + pytest over storage query mappers, publications, site builder, and semantic-facts suites; devtools verify green. Closes #272
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 973c15a45b
ℹ️ 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. |
Summary
Problem
The storage/lib/product-runtime tranche still relied on repeated result-shape normalization, loose row hydration, and protocol contracts that were only mypy-clean because values flowed through weak helper types. That left duplicated coercion logic across repository/product mappers and made downstream semantic-fact callers depend on accidental mutability assumptions.
Solution
Verification
devtools verifymypy polylogue/storage/backends/queries/mappers.py polylogue/storage/backends/queries/mappers_archive.py polylogue/storage/backends/queries/mappers_product_profiles.py polylogue/storage/backends/queries/mappers_product_timelines.py polylogue/storage/backends/queries/mappers_product_aggregates.py polylogue/storage/backends/queries/attachment_records.py polylogue/storage/session_product_rebuild.py polylogue/lib/action_events.py polylogue/lib/semantic_fact_support.py polylogue/lib/semantic_facts.py polylogue/lib/pricing.py polylogue/storage/action_event_rows.py polylogue/pipeline/services/ingest_worker.py polylogue/pipeline/run_finalization.py polylogue/cli/query_stats.py polylogue/cli/query_semantic.py polylogue/lib/query_retrieval_search.py polylogue/lib/session_profile_runtime.py polylogue/lib/phase_extraction.py polylogue/lib/attribution.py polylogue/lib/work_event_extraction.py tests/unit/storage/test_publications.py tests/unit/site/test_builder.py tests/unit/core/test_semantic_facts.pypytest -q tests/unit/storage/test_query_mappers.py tests/unit/storage/test_publications.py tests/unit/site/test_builder.py tests/unit/core/test_semantic_facts.pypytest -q tests/unit/cli/test_run_int.py -k latest_run_parsingCloses #272