Repository navigation
fix(sources): refuse to synthesize session identity from unasserted ids - #3403
Conversation
… stem Problem: polylogue-b508 found 21% of claude-code-session index rows are *.meta.json/toolu_*/wf_* phantom sessions -- duplicate sidecar rows beside the real subagent transcript. Tracing the mechanism (not just inferring it) showed the specific shapes it names are already excluded by OriginSpec/ artifact-taxonomy path rules; a real-corpus ingest test (9 real files including 4 agent-*.meta.json sidecars, 0 phantom sessions produced) proves those specific rows are stale pre-existing data, not a live defect. But the structural gap the bead actually asks to close was real: dispatch.py's `_generic_messages_session` -- the one lowering branch with no provider-specific identity handling (reached both by truly unknown providers and by the Drive-like generic fallback) -- fell back to `fallback_id`, a filename stem the source-discovery walk invented, whenever a payload had a `messages` list but no `id` field. That is precisely the "session identity derived from a filename stem" pathology, still live and reachable by the next sidecar format that happens to carry a `messages` key, the same way the hook-event fix (PR #3265) didn't generalize. What changed: `_generic_messages_session` now requires the payload to assert its own `id`; absent that, it refuses to parse (returns None) instead of synthesizing an identity from `fallback_id`. Verification: `devtools test tests/unit/sources/test_source_laws.py` (130 passed). Anti-vacuity: reverted the `session_id is None: return None` guard back to `or fallback_id` and confirmed the new test_parse_payload_generic_messages_without_asserted_id_refuses_to_parse fails against both parametrized providers before restoring the fix. Ref polylogue-b508
Problem: polylogue-b508's phantom .meta.json sessions are not just stale historical data. The live daemon's ingest path (sources/live/batch.py + pipeline/services/ingest_worker.py) already consults OriginSpec/artifact- taxonomy classification before parsing and correctly refuses to session-parse declared "fact" artifacts (agent-*.meta.json sidecars, workflow run snapshots/journals, adopt.json manifests) -- confirmed empirically by ingesting 9 real Claude Code files (4 of them agent-*.meta.json) through LiveBatchProcessor: 0 phantom sessions. But sources/revision_backfill.py -- the SEPARATE parse chokepoint that `polylogue ops reset --index` (and the `devtools` rebuild-index path) drives via _parse_one/_parse_stream -- had no such gate: it calls dispatch.parse_payload/parse_stream_payload on every retained raw unconditionally. Reproduced live: rebuilding an index from the same 9-file real fixture corpus (bypassing the daemon path) recreated 4 `<agent>.meta` phantom sessions with the exact reported shape (0 messages, native_id `agent-<id>.meta`). The bead's suggested remediation -- `polylogue ops reset --index && polylogued run` -- would therefore have recreated the exact defect it was meant to fix on the live archive. What changed: `_parse_one`/`_parse_stream` now consult the same `artifact_rule_for_path` OriginSpec table batch.py already uses and refuse to parse (return []) when the declared artifact's parse_policy isn't "session" -- one rule table, enforced at both entry points, so a rebuild and a live ingest agree. Verification: `devtools test tests/unit/sources/test_revision_backfill.py` (50 passed). Anti-vacuity: reverted the two `_is_declared_non_session_artifact` guard calls and confirmed all 4 parametrized cases of test_parse_one_refuses_declared_fact_artifacts fail before restoring the fix. Also reproduced end-to-end outside the test suite: rebuilding a throwaway archive from the 9-file real fixture corpus produced 9 sessions (4 phantom `.meta`) before this fix and 5 (0 phantom) after, with the real subagent transcript and its messages fully retained in both cases. Ref polylogue-b508
…rocedure Ref polylogue-b508
|
Warning Review limit reached
Next review available in: 51 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Plus Run ID: 📒 Files selected for processing (3)
📝 WalkthroughWalkthroughChangesParser safeguards
Estimated code review effort: 3 (Moderate) | ~20 minutes Possibly related PRs
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
✨ 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: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In @.beads/issues.jsonl:
- Line 1: Update the issue record’s updated_at field so it is at least
2026-07-30T16:49:39Z, matching or exceeding the timestamp of the appended
comment; leave the comment and all other issue fields unchanged.
In `@polylogue/sources/dispatch.py`:
- Around line 1120-1122: Update the session ID validation around
optional_string(payload.get("id")) to reject empty or whitespace-only values,
returning None before constructing ParsedSession. Preserve valid non-blank IDs,
and add regression coverage for blank and whitespace asserted IDs.
🪄 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 Plus
Run ID: 36542adb-8c6e-4fc9-bafb-a55ecbae4211
📒 Files selected for processing (5)
.beads/issues.jsonlpolylogue/sources/dispatch.pypolylogue/sources/revision_backfill.pytests/unit/sources/test_revision_backfill.pytests/unit/sources/test_source_laws.py
| @@ -1,4 +1,4 @@ | |||
| {"_type":"issue","id":"polylogue-b508","title":"21% of index sessions are metadata sidecars materialized as conversations (agent-*.meta, toolu_*, wf_*)","description":"## What the data shows\n\nClassifying every `claude-code-session` session_id in the live index by the shape\nof its native_id:\n\n 8,586 (52.6%) parent:agent-* real subagent transcripts\n 4,945 (30.3%) \u003cagent\u003e.meta SIDECAR METADATA, not a conversation\n 2,762 (16.9%) uuid real top-level sessions\n 7 wf_* workflow ids\n 3 toolu_* TOOL-USE ids\n 16,312 total\n\nContent of the suspicious classes:\n\n .meta 4,945 sessions 0 with messages 4,286 with events\n toolu_ 3 sessions 0 with messages 0 with events\n wf_ 7 sessions 0 with messages 0 with events\n\nThe `.meta` rows originate from\n`~/.claude/projects/\u003cproject\u003e/\u003csession-uuid\u003e/subagents/agent-\u003cid\u003e.meta.json` --\na per-subagent metadata sidecar. 5,053 raws come from `*.meta.json` paths.\n\n**The real subagent transcript is separately and correctly ingested.** Sampled\n300 `.meta` sessions and looked for the corresponding `%:agent-\u003cid\u003e` session:\n300 of 300 found. So these are not the only record of anything; they are\nduplicate phantom rows standing beside the real session.\n\nNet effect: 4,945 of 23,230 index sessions -- **21% of the archive's session\ncount** -- are metadata sidecars materialized as conversations.\n\n## Why this matters beyond a wrong count\n\nThis is the same pathology as the hook-event inflation already fixed once\n(83,286 -\u003e 18,391 sessions, `write_hook_event`, PR #3265): a per-session sidecar\nrecord ingested as a standalone session. A different sidecar type, the identical\nbug class, and it survived that repair because the fix was specific to hook\nevents rather than to the category.\n\nConsequences that are not merely cosmetic:\n\n- Every per-session aggregate -- counts, cost rollups, activity timelines,\n \"how many sessions did I have\" -- is inflated by 21% for claude-code.\n- 659 of them carry neither messages nor events, so they are pure empty rows.\n- Search and read surfaces can return a `.meta` session that has no content to\n show.\n- `toolu_*` sessions mean a TOOL-USE id was promoted to a session identity,\n which indicates identity derivation falling back to whatever id it found\n rather than failing loudly.\n\n## Hypothesis for the mechanism (needs confirming before fixing)\n\nProvider detection / payload lowering treats any JSON document under a\n`subagents/` directory as a session-bearing payload, so a `.meta.json` sidecar\nis lowered into a `LoweredPayloadSpec` and parsed. `provider_session_id` then\nfalls back to the filename stem (`agent-\u003cid\u003e.meta`), producing a well-formed but\nmeaningless identity. The `toolu_*` and `wf_*` cases look like the same fallback\npicking up whichever id field is present in a fragment.\n\nThat should be verified in `sources/dispatch.py` and the Claude Code parser\nbefore any fix -- the shape above is inference from the data, not yet traced in\ncode.\n\n## Direction\n\nTwo candidate fixes, and the second is the one that matches\n`polylogue-aggz`'s spirit:\n\n1. Narrow: skip `*.meta.json` under `subagents/`, and attach its content to the\n subagent session it describes rather than to a session of its own.\n2. Structural: a payload may only become a session when it yields a session\n identity the PROVIDER asserted. A filename-derived or fragment-derived\n fallback identity should be a parse refusal, not a session. That kills\n `.meta`, `toolu_*` and `wf_*` in one rule, and prevents the next sidecar\n format from doing this again -- which is exactly what the hook-event fix\n failed to do.\n\nPrefer (2), with (1) only if (2) proves too broad. Under (2) this stops being a\ncategory anyone has to remember.\n\n## Acceptance criteria\n\n- No session exists whose identity was derived from a filename stem or a\n non-session fragment id.\n- The metadata carried by `*.meta.json` is still retained and attached to the\n subagent session it describes -- this must not become data loss.\n- Sampled `.meta` ids resolve to their real `%:agent-\u003cid\u003e` session, which keeps\n its content.\n- claude-code session count drops by roughly 4,945; verify against\n `.agent/scripts/corpus-fidelity-audit.py` that absences do NOT rise, i.e. that\n nothing real was removed.\n- Anti-vacuity: state the production line mutated and the resulting failure.\n\nRef polylogue-aggz\n","status":"open","priority":0,"issue_type":"bug","owner":"[email protected]","created_at":"2026-07-30T16:10:03Z","created_by":"Sinity","updated_at":"2026-07-30T16:10:03Z","labels":["area:ingest"],"dependency_count":0,"dependent_count":0,"comment_count":0} | |||
| {"_type":"issue","id":"polylogue-b508","title":"21% of index sessions are metadata sidecars materialized as conversations (agent-*.meta, toolu_*, wf_*)","description":"## What the data shows\n\nClassifying every `claude-code-session` session_id in the live index by the shape\nof its native_id:\n\n 8,586 (52.6%) parent:agent-* real subagent transcripts\n 4,945 (30.3%) \u003cagent\u003e.meta SIDECAR METADATA, not a conversation\n 2,762 (16.9%) uuid real top-level sessions\n 7 wf_* workflow ids\n 3 toolu_* TOOL-USE ids\n 16,312 total\n\nContent of the suspicious classes:\n\n .meta 4,945 sessions 0 with messages 4,286 with events\n toolu_ 3 sessions 0 with messages 0 with events\n wf_ 7 sessions 0 with messages 0 with events\n\nThe `.meta` rows originate from\n`~/.claude/projects/\u003cproject\u003e/\u003csession-uuid\u003e/subagents/agent-\u003cid\u003e.meta.json` --\na per-subagent metadata sidecar. 5,053 raws come from `*.meta.json` paths.\n\n**The real subagent transcript is separately and correctly ingested.** Sampled\n300 `.meta` sessions and looked for the corresponding `%:agent-\u003cid\u003e` session:\n300 of 300 found. So these are not the only record of anything; they are\nduplicate phantom rows standing beside the real session.\n\nNet effect: 4,945 of 23,230 index sessions -- **21% of the archive's session\ncount** -- are metadata sidecars materialized as conversations.\n\n## Why this matters beyond a wrong count\n\nThis is the same pathology as the hook-event inflation already fixed once\n(83,286 -\u003e 18,391 sessions, `write_hook_event`, PR #3265): a per-session sidecar\nrecord ingested as a standalone session. A different sidecar type, the identical\nbug class, and it survived that repair because the fix was specific to hook\nevents rather than to the category.\n\nConsequences that are not merely cosmetic:\n\n- Every per-session aggregate -- counts, cost rollups, activity timelines,\n \"how many sessions did I have\" -- is inflated by 21% for claude-code.\n- 659 of them carry neither messages nor events, so they are pure empty rows.\n- Search and read surfaces can return a `.meta` session that has no content to\n show.\n- `toolu_*` sessions mean a TOOL-USE id was promoted to a session identity,\n which indicates identity derivation falling back to whatever id it found\n rather than failing loudly.\n\n## Hypothesis for the mechanism (needs confirming before fixing)\n\nProvider detection / payload lowering treats any JSON document under a\n`subagents/` directory as a session-bearing payload, so a `.meta.json` sidecar\nis lowered into a `LoweredPayloadSpec` and parsed. `provider_session_id` then\nfalls back to the filename stem (`agent-\u003cid\u003e.meta`), producing a well-formed but\nmeaningless identity. The `toolu_*` and `wf_*` cases look like the same fallback\npicking up whichever id field is present in a fragment.\n\nThat should be verified in `sources/dispatch.py` and the Claude Code parser\nbefore any fix -- the shape above is inference from the data, not yet traced in\ncode.\n\n## Direction\n\nTwo candidate fixes, and the second is the one that matches\n`polylogue-aggz`'s spirit:\n\n1. Narrow: skip `*.meta.json` under `subagents/`, and attach its content to the\n subagent session it describes rather than to a session of its own.\n2. Structural: a payload may only become a session when it yields a session\n identity the PROVIDER asserted. A filename-derived or fragment-derived\n fallback identity should be a parse refusal, not a session. That kills\n `.meta`, `toolu_*` and `wf_*` in one rule, and prevents the next sidecar\n format from doing this again -- which is exactly what the hook-event fix\n failed to do.\n\nPrefer (2), with (1) only if (2) proves too broad. Under (2) this stops being a\ncategory anyone has to remember.\n\n## Acceptance criteria\n\n- No session exists whose identity was derived from a filename stem or a\n non-session fragment id.\n- The metadata carried by `*.meta.json` is still retained and attached to the\n subagent session it describes -- this must not become data loss.\n- Sampled `.meta` ids resolve to their real `%:agent-\u003cid\u003e` session, which keeps\n its content.\n- claude-code session count drops by roughly 4,945; verify against\n `.agent/scripts/corpus-fidelity-audit.py` that absences do NOT rise, i.e. that\n nothing real was removed.\n- Anti-vacuity: state the production line mutated and the resulting failure.\n\nRef polylogue-aggz\n","status":"in_progress","priority":0,"issue_type":"bug","assignee":"Sinity","owner":"[email protected]","created_at":"2026-07-30T16:10:03Z","created_by":"Sinity","updated_at":"2026-07-30T16:48:33Z","started_at":"2026-07-30T16:48:33Z","labels":["area:ingest"],"comments":[{"id":"019fb3ee-7eaf-71b8-8e5a-d1d66efffce1","issue_id":"polylogue-b508","author":"Sinity","text":"## Traced mechanism (not the original hypothesis)\n\nThe original hypothesis (\"provider detection treats any JSON under\nsubagents/ as session-bearing, provider_session_id falls back to the\nfilename stem\") was PARTLY wrong and PARTLY right, in a way that matters.\n\n**Live daemon ingest path (sources/live/batch.py + pipeline/services/\ningest_worker.py) already refuses this correctly**, and has since well\nbefore this session (classify_artifact_path's agent-*.meta.json branch\ndates to 82fc0e4ff2, 2026-03-27; the OriginSpec artifact_rule_for_path\nroute that shadows it is newer but agrees). Proved empirically: built a\nthrowaway archive and ingested 9 REAL files pulled from\n~/.claude/projects (1 top-level session, 3 real agent-*.jsonl subagent\ntranscripts, 4 real agent-*.meta.json sidecars, 1 standalone\nmeta+transcript pair) through LiveBatchProcessor (same primitives\npolylogued run wires up) -- result: exactly 5 real sessions, 0 phantom\n`.meta` rows.\n\n**The actual live bug is a second, separate parse chokepoint**:\n`sources/revision_backfill.py` (`_parse_one`/`_parse_stream`, driving\n`polylogue ops reset --index` / the offline rebuild-index path via\n`backfill_historical_revision_evidence`) calls\n`dispatch.parse_payload`/`parse_stream_payload` on every retained raw\nUNCONDITIONALLY -- no OriginSpec/artifact-taxonomy gate at all. Reproduced\nlive: rebuilding an index from the same 9-file real corpus through this\npath (bypassing the daemon) produced 9 sessions, 4 of them phantom\n`claude-code-session:agent-\u003cid\u003e.meta` rows with 0 messages/0 events --\nthe EXACT reported shape. `fallback_id = Path(source_path).stem` on\n`agent-\u003cid\u003e.meta.json` strips only the trailing `.json`, leaving\n`agent-\u003cid\u003e.meta` -- literally the observed native_id.\n\nThis means the bead's suggested remediation (\"index.db is rebuildable,\nprefer a rebuild\") would have RECREATED the defect it was meant to fix,\nnot eliminated it -- this is now fixed (see below), so the plan below is\nsafe.\n\nA structural gap also existed independent of both mechanisms:\n`dispatch.py:_generic_messages_session` (the one payload-lowering branch\nwith zero provider-specific identity handling, reached both by genuinely\nunknown providers and by the Drive-like generic fallback) fell back to\n`fallback_id` -- a filename stem the *source-discovery walk* invented --\nwhenever a payload had a `messages` list but no `id` field. Didn't\nreproduce with real `.meta.json`/`toolu_*`/`wf_*` fixtures (those are\ncovered by the OriginSpec/artifact-taxonomy path rules), but is exactly\nthe \"next sidecar format\" risk the bead is about, and closing it is what\nimplements the structural rule generically rather than per-shape.\n\n## Fixes shipped (PR, branch feature/fix/provider-asserted-session-identity)\n\n1. `polylogue/sources/dispatch.py`: `_generic_messages_session` now\n requires the payload to assert its own `id`; absent that it refuses to\n parse (returns None) instead of synthesizing an identity from\n `fallback_id`.\n2. `polylogue/sources/revision_backfill.py`: `_parse_one`/`_parse_stream`\n now consult `artifact_rule_for_path` (same OriginSpec table batch.py\n already uses) and refuse to parse (return `[]`) when the declared\n artifact's `parse_policy` isn't `\"session\"`. One rule table, enforced\n at both entry points -- a rebuild and a live ingest now agree.\n\nBoth fixes proven with:\n- Unit regression tests\n (`tests/unit/sources/test_source_laws.py::test_parse_payload_generic_messages_without_asserted_id_refuses_to_parse`,\n `tests/unit/sources/test_revision_backfill.py::test_parse_one_refuses_declared_fact_artifacts`)\n that fail before the fix and pass after (anti-vacuity verified by\n reverting each fix in isolation and re-running).\n- The real 9-file fixture-corpus rebuild: 9 sessions / 4 phantom before\n fix #2, 5 sessions / 0 phantom after, with the 3 real subagent\n transcripts' message counts (96, 120, 164, 31... unaffected across the\n run) identical in both states -- no data loss to real content.\n- `devtools test tests/unit/sources/test_source_laws.py\n tests/unit/sources/test_revision_backfill.py` -- 180 passed.\n\n## AC: metadata retention (not data loss)\n\nAlready satisfied by existing, pre-existing code, unaffected by this fix:\n`insights/claude_workflow_materializer.py` +\n`insights/claude_workflow_evidence.py` read `agent_sidecar_meta` facts\nfrom retained raw bytes (independent of whether a `sessions` row exists)\nand materialize them into the `claude-workflow:*` work-evidence graph\n(run/invocation/attempt nodes with sidecar-meta claims attached). This\nfix only removes the DUPLICATE phantom `sessions` row; the raw bytes stay\nin `raw_sessions` (admitted as \"fact\" artifacts) and the metadata content\nkeeps flowing into that graph exactly as before.\n\n## `toolu_*` / `wf_*` (10 rows total, not separately reproduced)\n\n`wf_*` (workflow_run_snapshot, `.json`) is covered by the same\nOriginSpec-declared-fact gate as `.meta.json` -- fix #2 covers it\nstructurally, same mechanism.\n\n`toolu_*` (3 rows) could not be reproduced with real fixture data: real\n`tool-results/*.txt` sidecars are excluded from the live discovery walk\nby suffix filtering (`artifact_suffixes_for_provider` only allows\n`.json`/`.jsonl`/`.ndjson` for claude-code) and are NOT declared in\nOriginSpec at all, so if a `raw_sessions` row for one of these 3 exists\nin the live archive it's very likely a relic of an older\nacquisition-scope bug already superseded by that suffix filtering. Given\nthere are only 3 (vs 4,945 `.meta`), recommend: after the rebuild below,\ncheck whether they're gone; if any survive, file a narrow follow-up bead\nwith their actual `source_path`/payload shape rather than guessing\nfurther blind.\n\n## Verified live-data remediation procedure\n\nindex.db is the rebuildable tier; source.db (raw bytes) is durable and\nuntouched by this fix. With both fixes merged and deployed:\n\n1. Stop anything writing to the live archive (already stopped per the\n session's safety rule).\n2. `polylogue ops reset --index` -- wipes only the index tier (new\n generation), source.db/user.db/ops.db untouched.\n3. `polylogued run` (or the offline `devtools`/maintenance rebuild-index\n path) -- replays EVERY `raw_sessions` row from source.db through the\n now-fixed `revision_backfill.py` path. Verified there is no\n `parsed_at_ms`-style skip: `all_index_rebuild_raw_ids` selects every\n raw unconditionally and `RebuildIndexRequest(only_missing=False)`\n forces a full non-incremental replay; content-hash idempotency only\n skips re-writing a session that ALREADY EXISTS in the target, which is\n moot against a freshly wiped, empty index.db. So no additional\n durable-tier invalidation beyond the code fix is needed -- the raws\n ARE the source of truth and will now be reparsed correctly.\n4. Verify with `.agent/scripts/corpus-fidelity-audit.py` (or equivalent\n session-count query) that: claude-code session count drops by\n approximately 4,945+7(+ up to 3), absences do NOT rise (nothing real\n removed), and the 300-sample `.meta -\u003e %:agent-\u003cid\u003e` resolution check\n from the original investigation still resolves (the real subagent\n sessions are untouched by this fix -- it only removes the duplicate).\n\nNot run against the live archive per the session's explicit\ninstruction -- this is the procedure to execute, not evidence that it was\nexecuted.\n","created_at":"2026-07-30T16:49:39Z"}],"dependency_count":0,"dependent_count":0,"comment_count":1} | |||
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win
Keep updated_at newer than the appended comment.
The new comment was created at 2026-07-30T16:49:39Z, but the issue still reports updated_at as 2026-07-30T16:48:33Z. Update updated_at to the comment timestamp or later so issue ordering, synchronization, and audit consumers do not observe stale metadata.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In @.beads/issues.jsonl at line 1, Update the issue record’s updated_at field so
it is at least 2026-07-30T16:49:39Z, matching or exceeding the timestamp of the
appended comment; leave the comment and all other issue fields unchanged.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 76584a4c59
ℹ️ 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".
Review on #3403 caught that the new provider-asserted-identity guard checks presence but not blankness. `optional_string` returns `""` for an empty value rather than `None`, so a payload carrying `"id": ""` or a whitespace-only id satisfies `is None` and produces a session keyed on nothing. That is the same filename-stem pathology the guard was written to prevent, arriving through the guard itself -- a session whose identity the provider did not actually assert. A blank string is not an assertion. Verification devtools test tests/unit/sources/test_source_laws.py -k generic_messages 11 passed New parametrized `..._blank_asserted_id_refuses_to_parse` covers "", " " and "\t\n". Reverting the guard to the presence-only form fails all three and no other test, so the strip-and-truthiness check is load-bearing and #3403's original refusal is untouched. mypy --strict clean on the changed module. Ref polylogue-b508 Co-Authored-By: Claude <[email protected]>
…nalysis polylogue-6kur classified repair_empty_sessions as a soon-to-be-no-op once #3403 fixes the .meta phantom cause. polylogue-ne6k, which already existed, records the opposite: that repair would DELETE the 832 genuinely-empty sessions the hook-inflation postmortem deliberately chose to retain. The target is not spent, it is destructive, and ne6k blocks any culling work rather than being a footnote. Method failure recorded alongside it: the verdict came from live measurement plus code reading without first checking whether an existing bead held the answer. 'bd list' silently caps output (50 of 1,234 records), so a survey trusting its default sees 4% of the backlog while reading as exhaustive. Co-Authored-By: Claude <[email protected]>
|
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. |
|
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
Fixes the mechanism behind polylogue-b508 (21% of claude-code-session index
rows being
agent-*.meta.json/toolu_*/wf_*phantom sessions): closes theone dispatch branch with no provider-specific identity handling, and gates
the offline index-rebuild replay path against the same OriginSpec
"fact-not-session" rule the live daemon already enforces.
Problem
The bead's hypothesis ("provider detection treats any JSON under
subagents/as session-bearing, session id falls back to the filenamestem") was traced in code rather than assumed, per the bead's own
instruction, and turned out to be partly wrong in an important way:
sources/live/batch.py+pipeline/services/ingest_worker.py) already refuses to session-parseagent-*.meta.json/workflow-run-snapshot/workflow-journal/adopt-manifestartifacts, via
classify_artifact_path's OriginSpec-driven rule table.Proved empirically: ingesting 9 real files pulled from a live
~/.claude/projectscorpus (1 top-level session, 3 real subagenttranscripts, 4 real
agent-*.meta.jsonsidecars, 1 standalonemeta+transcript pair) through
LiveBatchProcessorproduced exactly 5real sessions, 0 phantom
.metarows.sources/revision_backfill.py(_parse_one/_parse_stream, drivingpolylogue ops reset --index/ the offline rebuild-index path) calleddispatch.parse_payload/parse_stream_payloadon every retained rawunconditionally, with no OriginSpec/artifact-taxonomy awareness at
all. Reproduced live: rebuilding an index from the same 9-file corpus
through this path (bypassing the daemon) produced 4 phantom
claude-code-session:agent-<id>.metasessions (0 messages, 0 events) —the exact reported shape, because
fallback_id = Path(source_path).stemon
agent-<id>.meta.jsonstrips only.json. This means the bead'ssuggested remediation ("rebuild the index") would have recreated the
defect on every future rebuild, not eliminated it.
dispatch.py's_generic_messages_session— the one payload-lowering branch with zeroprovider-specific identity handling — fell back to a filename-stem
fallback_idwhenever a payload merely had amessageslist and noid. It didn't reproduce with real.meta.jsonfixtures (those arecovered by OriginSpec), but is exactly the "next sidecar format" risk
the bead is about (same pathology class as the hook-event inflation
fixed once by PR fix(sources): persist hook events as session-linked evidence, not standalone sessions #3265, which didn't generalize).
Solution
polylogue/sources/dispatch.py:_generic_messages_sessionnowrequires the payload to assert its own
id; absent that, it refuses toparse (
None) instead of synthesizing an identity fromfallback_id.polylogue/sources/revision_backfill.py:_parse_one/_parse_streamnow consult
artifact_rule_for_path(the same OriginSpec tablebatch.pyalready uses) and refuse to parse when the declaredartifact's
parse_policyisn't"session". One rule table enforcedat both entry points, so a rebuild and a live ingest can no longer
disagree.
Metadata retention (AC: no data loss): unaffected by this change.
insights/claude_workflow_materializer.py/claude_workflow_evidence.pyalready read
agent_sidecar_metafacts from retained raw bytesindependent of whether a
sessionsrow exists, and materialize them intothe
claude-workflow:*work-evidence graph. This fix only removes theduplicate phantom
sessionsrow; the raw bytes and the metadata graph areuntouched.
toolu_*/wf_*(10 rows total in the live archive):wf_*is coveredstructurally by fix #2 (same declared-fact mechanism as
.meta.json).toolu_*(3 rows) could not be reproduced with real fixture data — realtool-results/*.txtsidecars are excluded by suffix filtering and neverdeclared in OriginSpec, so any surviving
toolu_*rows are likely relicsof an older, already-superseded acquisition-scope bug; flagged as a
narrow follow-up if any survive the live remediation rebuild.
Live-archive remediation (not run by this PR — evidence-only, per
operator instruction):
polylogue ops reset --index && polylogued run.Verified there is no
parsed_at_ms-style skip in the rebuild path(
all_index_rebuild_raw_idsselects every raw unconditionally,RebuildIndexRequest(only_missing=False)forces a full replay, andcontent-hash idempotency is moot against a freshly wiped index.db) — no
additional durable-tier invalidation is needed beyond this code fix.
Full procedure recorded on polylogue-b508.
Verification
devtools test tests/unit/sources/test_source_laws.py— 130 passed(128 pre-existing + 2 new).
devtools test tests/unit/sources/test_revision_backfill.py— 50 passed(49 pre-existing + 1 new, parametrized ×4).
confirmed the new regression test(s) fail before restoring the fix.
Claude Code files (4
agent-*.meta.jsonsidecars among them) produced 9sessions / 4 phantom
.metarows before fix feat: unify Gemini export rendering and Drive sync in gmd #2, 5 sessions / 0 phantomafter — with identical message counts on the 3 real subagent
transcripts in both states (no data loss).
git pushran the pre-pushdevtools verify --quickgate (format +lint + mypy +
render all --check) — clean on both commits.devtools verify --all/broad testmon pass (background, willreport before merge); no mutation against the live archive
(
/realm/db/polylogue, explicitly out of scope for this session).Ref polylogue-b508
Summary by CodeRabbit
Bug Fixes
Tests