Skip to content

fix(sources): stop GDPR export ZIP siblings and gemini-cli stubs misclassifying - #3436

Merged
Sinity merged 1 commit into
masterfrom
feature/sources/gdpr-zip-origin-classification
Jul 31, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/sources/gdpr-zip-origin-classification

Conversation

@Sinity

@Sinity Sinity commented Jul 31, 2026

Copy link
Copy Markdown
Owner

Summary

Fixes two verified live-archive origin-classification defects (polylogue-hs3y): GDPR export ZIP sidecar members falling back to unknown-export, and Gemini CLI JSONL checkpoint stubs colliding with Claude Code's session detector.

Problem

Read-only audit of the live archive (/realm/db/polylogue):

  • 25 raw_sessions rows carried origin='unknown-export'. All 25 turned out to be non-conversation sidecar files (user.json, message_feedback.json, shared_conversations.json, attachment file_*.json, projects.json, memories.json, ...) sitting inside otherwise-correctly-detected ChatGPT/Claude GDPR export ZIPs dropped into the generic inbox. Each ZIP member is provider-detected independently with a fresh Provider.UNKNOWN seed, so only the member whose own JSON shape detects cleanly (conversations.json) got tagged correctly — every low-signal sibling fell back on its own.
  • 4 live sessions under ~/.gemini/tmp/*/chats/*.jsonl carried origin='claude-code-session'. Gemini CLI's .jsonl chat-log checkpoint format opens with a session-metadata stub record (sessionId+projectHash+kind, no "messages" key — turns arrive as later lines). That bare sessionId key alone satisfied Claude Code's _STRONG_SESSION_KEYS rule, and the existing Gemini CLI structural detector only ran for single-document payloads (len(payloads) == 1), never for a genuine multi-line JSONL sequence.

Solution

  • polylogue/sources/live/batch.py: add _sniff_zip_provider, a one-time pre-scan of a ZIP's members (small prefix read, same budget as whole-file detection) that establishes the ZIP's dominant provider once so every low-signal sibling inherits it instead of independently falling back to unknown. Only activates when the top-level fallback provider is itself unknown; a source that already resolved a provider (a per-provider watched directory) is untouched.
  • polylogue/sources/parsers/local_agent.py: widen looks_like_gemini_cli to also recognize the messages-less session-open stub shape (requires projectHash, unique to Gemini CLI, alongside the kind enum).
  • polylogue/sources/dispatch.py: trust that stub shape at any sequence length in _detect_provider_from_sequence; the messages-embedded shape stays restricted to the single-document (len==1) case, unchanged.

Neither fix defaults anything to a session (standing design constraint): the ZIP fix only corrects which provider a non-session sidecar is tagged with — it still routes through the existing raw_artifacts/classify_artifact non-session path, not a fabricated unknown-export dumping ground. The gemini-cli fix only corrects provider detection; full turn-by-turn parsing of the JSONL event-log shape does not exist yet (filed as polylogue-8u1p) — these 4 sessions now correctly detect as Provider.GEMINI_CLI but do not materialize as sessions rows (0 messages, by design, no forced empty session).

Also audited (read-only) origin vs source_path shape across all 9 origins present in the live archive. Only the gemini-cli collision above was a genuine detection defect; a similarly-shaped claude-code-session/drive-cache/gemini/ bucket (12 sessions) was investigated and confirmed correctly classified — the content is genuinely Claude-Code-shaped {"type":"summary",...} records, a cache-location naming coincidence, not a bug.

No archive data repair is included — a separate lane owns that per the task brief; this PR only fixes the producing code.

Verification

  • devtools test tests/unit/sources/test_live_watcher.py tests/unit/sources/parsers/test_origin_regression_pack.py tests/unit/sources/test_dispatch_payloads.py tests/unit/sources/test_dispatch_ordering.py tests/unit/sources/test_parsers_local_agent.py tests/unit/sources/test_origin_specs.py — 190 passed
  • New test_live_full_ingest_sniffs_zip_provider_for_non_session_siblings confirmed to fail without the batch.py fix (message_feedback.json → unknown-export), pass with it (anti-vacuity check, reverted the fix and reran)
  • New test_gemini_cli_jsonl_checkpoint_stub_does_not_collide_with_claude_code documents the pre-fix collision (claude_code_looks_like([stub]) still returns True in isolation) and asserts detect_provider now resolves GEMINI_CLI
  • devtools verify --quick — exit 0 (format, lint, mypy --strict, render all --check, topology/layering/schema policy gates), run both pre-commit and again via the pre-push hook

Ref polylogue-hs3y.

…lassifying

Problem

Live archive audit (read-only, polylogue-hs3y): 25 raw_sessions rows had
origin=unknown-export, and all 25 turned out to be non-conversation
sidecar files (user.json, message_feedback.json, shared_conversations.json,
attachment file_*.json, projects.json, memories.json, ...) sitting inside
otherwise-correctly-detected ChatGPT/Claude GDPR export ZIPs dropped into
the generic inbox. Each ZIP member was provider-detected independently
with a fresh Provider.UNKNOWN seed, so only the member whose own JSON
shape detects cleanly (conversations.json) got tagged correctly.

Separately, 4 live sessions under ~/.gemini/tmp/*/chats/*.jsonl carried
origin=claude-code-session. Gemini CLI's .jsonl chat-log checkpoint format
opens with a session-metadata stub record (sessionId+projectHash+kind, no
"messages" key -- turns arrive as later lines). The bare "sessionId" key
alone satisfied Claude Code's _STRONG_SESSION_KEYS rule, and the existing
Gemini CLI structural detector only ran for single-document payloads, not
a genuine multi-line JSONL sequence.

Solution

- polylogue/sources/live/batch.py: add _sniff_zip_provider, a one-time
  pre-scan of a ZIP's members (small prefix read, same budget as whole-file
  detection) that establishes the ZIP's dominant provider once so every
  low-signal sibling inherits it instead of independently falling back to
  unknown. Only activates when the top-level fallback provider is itself
  unknown; a source that already resolved a provider is untouched.
- polylogue/sources/parsers/local_agent.py: widen looks_like_gemini_cli to
  also recognize the messages-less session-open stub shape (requires
  projectHash, unique to Gemini CLI, alongside the kind enum).
- polylogue/sources/dispatch.py: trust that stub shape at any sequence
  length in _detect_provider_from_sequence; the messages-embedded shape
  stays restricted to the single-document (len==1) case, unchanged.

Neither fix defaults anything to a session: the ZIP fix only corrects
which provider a non-session sidecar is tagged with (still routes through
the existing raw_artifacts/classify_artifact non-session path); the
gemini-cli fix only corrects provider detection. Full turn-by-turn parsing
of the gemini-cli JSONL event-log shape does not exist yet (filed as
polylogue-8u1p) -- these 4 sessions now correctly detect as
Provider.GEMINI_CLI but do not materialize as `sessions` rows (0 messages,
by design, no forced empty session).

Also audited (read-only) origin vs source_path shape across all 9 origins
present in the live archive. Only the gemini-cli collision above was a
genuine detection defect; a similarly-shaped claude-code-session/
drive-cache/gemini/ bucket was investigated and confirmed correctly
classified (content is genuinely Claude-Code-shaped "summary" records, a
cache-location naming coincidence, not a bug).

Verification

- devtools test tests/unit/sources/test_live_watcher.py
  tests/unit/sources/parsers/test_origin_regression_pack.py
  tests/unit/sources/test_dispatch_payloads.py
  tests/unit/sources/test_dispatch_ordering.py
  tests/unit/sources/test_parsers_local_agent.py
  tests/unit/sources/test_origin_specs.py -- 190 passed
- New test_live_full_ingest_sniffs_zip_provider_for_non_session_siblings
  confirmed to fail without the batch.py fix (message_feedback.json ->
  unknown-export), pass with it.
- devtools verify --quick -- exit 0 (format, lint, mypy --strict, render
  all --check, topology/layering/schema policy gates)

Ref polylogue-hs3y.

Co-Authored-By: Claude <[email protected]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 51a779da54

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

Comment on lines +2625 to +2626
if detected is not Provider.UNKNOWN:
return detected

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Reject mixed providers before applying a ZIP-wide hint

When a provider-agnostic ZIP contains sessions from multiple providers, this returns the first detected provider rather than the documented dominant/unique provider. If that first match is a GROUP_PROVIDER such as Claude Code, iter_zip_entry_raw_data() treats the hint as authoritative and returns at source_acquisition_components.py:425-427 without detecting later members, so Codex or other sessions later in the ZIP can be parsed under the wrong provider or silently disappear. Scan all candidate members and only propagate a hint when they agree; otherwise retain Provider.UNKNOWN. This also preserves the repository's shape-tightness ordering instead of allowing the first provider parser to claim unrelated records.

AGENTS.md reference: AGENTS.md:L124-L128

Useful? React with 👍 / 👎.

Comment on lines +2613 to +2614
with zf.open(info.filename) as handle:
prefix = handle.read(_DETECTION_PREFIX_SIZE)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Read a complete JSON record before choosing the ZIP provider

For a normal conversations.json larger than 8 KiB, this prefix is incomplete JSON. Although truncated_tail_ok=True is passed below, _detect_provider_from_raw_bytes() only trims truncated tails for JSONL; for an ordinary JSON array, exhausting the prefix raises during streamed decoding and falls back to Provider.UNKNOWN. Thus multi-conversation GDPR exports—the common large case—still leave message_feedback.json, user.json, and other siblings tagged unknown-export; the regression test passes only because its single-conversation document fits entirely within 8 KiB. Stream far enough to obtain one complete array item, or otherwise perform bounded structural detection without requiring the whole JSON document.

Useful? React with 👍 / 👎.

@Sinity
Sinity merged commit 76b0791 into master Jul 31, 2026
2 checks passed
@Sinity
Sinity deleted the feature/sources/gdpr-zip-origin-classification branch July 31, 2026 10:09
Sinity added a commit that referenced this pull request Jul 31, 2026
…lper (#3450)

## Summary

Fixes polylogue-lyr2 (session identity computed two ways) with a single
source-of-truth helper mirroring the message-level `ab5bad1f` fix. Also
records verified live-archive forensics on polylogue-t83e (Drive-cache
Claude Code duplicates colliding with local session identity) —
diagnosed,
not closed, since the correct fix needs acquisition-provenance plumbing
verification this PR's effort budget can't safely cover.

## Problem

**polylogue-lyr2**: an invariants audit found `_write_session`
(`archive_tiers/write.py`) bound a session's `native_id` RAW into the
`sessions` INSERT, while `session_id` (used for cache keys, lineage
lookups,
the FK-failure log message, and everything else downstream in the same
write) was computed via `core.identity_law.session_id`, which strips
whitespace. Same logical session, two spellings, one row — the exact
incident class that produced `ab5bad1f`'s lost 10-hour rebuild, fixed at
message level via `_stored_message_native_id` + a property test, but
never
given a session-level sibling. `session_links.dst_native_id` (parent
references written by `_write_session_link`) had the same
raw-vs-stripped
mismatch against the `sessions.native_id` it must exact-match to resolve
lineage edges.

**polylogue-t83e**: a prior audit (hs3y, PR #3436) confirmed 12
`~/.local/share/polylogue/drive-cache/gemini/*.jsonl.txt.json` rows are
genuinely Claude-Code-shaped content (not a misclassification) and left
them alone. It never cross-checked those native_ids against local raws
for
actual `session_id` collisions. This session verified, against the live
archive (read-only): **6 of those native_ids collide with
genuinely-local
`~/.claude/projects/...` raws** — confirmed by SQL join, not inference —
and in all 6 the drive-cache copy currently wins the row. Byte-diffing
one
pair in the blob store shows the drive copy is an exact byte prefix of
the
local file (same conversation, stale/truncated snapshot, not a distinct
identity) with a concrete live consequence: `sessions.title` for
`claude-code-session:0213d48f-5b7a-4241-b77a-eb714672dc3b` currently
reads
the generic fallback `"continue"` instead of the real summary title,
because
the stale drive copy won a freshness tie.

## Solution

- Added `_stored_session_native_id`
(`polylogue/storage/sqlite/archive_tiers/write.py`),
mirroring `_stored_message_native_id` — the single source of truth every
session-identity call site now routes through. Applied once right after
`provider_session_id` is read, so `session_id`, the `sessions` INSERT
bind,
and `_resolve_session_graph`'s `native_id` argument all see the same
value.
- `_write_session_link` now normalizes `dst_native_id` (strip +
surrogate
substitution) before writing a parent-session reference, matching how
the
  resolver (`_resolve_outbound_session_links`) exact-matches it against
  `sessions.native_id`.
- Property test `tests/property/test_session_identity_normalization.py`
  mirrors `test_message_identity_normalization.py`: sweeps pathological
  `provider_session_id` shapes (empty, whitespace-only, padded, mixed)
  through the real write path and asserts the DB-generated
  `sessions.session_id` matches `identity_law.session_id`, plus the
  `ValueError` path for unidentifiable (whitespace-only) native ids.
- polylogue-t83e: no code change. Recorded the full forensic trail (SQL
used,
exact session/raw ids, byte-diff result, root-cause trace through the
three
  duplicate skip-stale-replace implementations in `write.py`,
  `pipeline/services/ingest_batch/_core.py`, and
`storage/sqlite/archive_tiers/revision_governance.py`, and why a
detection
  fix needs `fallback_provider`/`DRIVE_LIKE_PROVIDERS`-scoped plumbing I
  could not safely verify this session) as a bd comment plus a
  `chore(beads)` commit. Bead left **open**, not closed.

### Rebuild impact (explicit, per both beads)

- **polylogue-lyr2**: verified **0** padded/whitespace
`sessions.native_id`
  and **0** padded `session_links.dst_native_id` rows exist in the live
  archive today (`sqlite3 "file:/realm/db/polylogue/index.db?mode=ro"`).
This PR changes nothing a rebuild would write for current data — it
closes
a latent divergence that only a future/pathological provider export
would
trigger. **No `SEMANTIC_REPARSE` delta needed**: output is
byte-identical
  for every live row.
- **polylogue-t83e**: **unchanged** by this PR. A rebuild still replays
every
raw for the 6 known collisions (and any undiscovered siblings) and picks
  whichever raw its replay order processes last for that `native_id` —
exactly today's live, order-dependent behavior, now precisely diagnosed
rather than merely suspected. No `SEMANTIC_REPARSE` declaration applies
  since no detection/parsing code changed here.

## Verification

```
devtools test tests/property/test_session_identity_normalization.py \
  tests/unit/storage/test_archive_tiers_write.py \
  tests/unit/storage/test_lineage_normalization.py \
  tests/property/test_message_identity_normalization.py
# 106 passed in 18.47s

devtools verify --quick
# exit_code: 0 (ruff format/check, mypy --strict, render all --check,
# layering, closure-matrix, schema-versioning policy, schema promotion audit
# — all ok)
```

Live-archive counts (read-only,
`/realm/db/polylogue/{index,source}.db`):

```sql
-- lyr2: padded native_id check
SELECT count(*) FROM sessions WHERE native_id <> trim(native_id);        -- 0
SELECT count(*) FROM session_links WHERE dst_native_id <> trim(dst_native_id); -- 0

-- t83e: collision confirmation (6 native_ids, both a drive raw and a local raw)
SELECT native_id, raw_id, source_path FROM raw_sessions
WHERE native_id IN (
  '0213d48f-5b7a-4241-b77a-eb714672dc3b','063a6885-8d6a-4f91-80b2-7f67fa06d680',
  '705f1fcb-8953-4b8b-92f1-9244fcf9db91','8c9f8c3d-4859-44cf-be9c-338803a8e7de',
  'a952ffa4-73b0-48bd-a212-ebe5b9772d1e','cf3404fa-89e0-400a-af3e-ff1450eecef4'
);
-- each id resolves to exactly 2 rows: one drive-cache/gemini source_path, one ~/.claude/projects/ source_path
```

Full evidence trail (exact commands, byte-diff output, root-cause trace)
is
recorded on `polylogue-t83e`'s bd comment for the next implementer.

Ref polylogue-lyr2, Ref polylogue-t83e

---------

Co-authored-by: Claude <[email protected]>
Sinity added a commit that referenced this pull request Jul 31, 2026
#3454)

## Summary

Consolidates three independently-duplicated "skip this write as stale"
freshness-tie checks (`archive_tiers/write.py`,
`pipeline/services/ingest_batch/_core.py`,
`archive_tiers/revision_governance.py`) into one
`should_skip_stale_replace()` in `archive_tiers/ingest_precedence.py`.
No behavior change: the comparison body is unchanged, just no longer
copy-pasted three times.

## Problem

`polylogue-t83e` investigated 6 live `session_id` collisions where a
Claude Code transcript the operator uploaded into an AI Studio
conversation (re-downloaded via Drive sync into
`~/.local/share/polylogue/drive-cache/gemini/<uuid>.jsonl.txt.json`) was
winning the archive row over the genuinely local
`~/.claude/projects/...` transcript of the *same* conversation — even
though the drive copy is a strict byte-prefix of the local file
(confirmed by direct diff: 213 vs 214 Claude Code JSONL messages for one
collision, the local file has exactly one trailing `summary` record the
drive copy lacks).

**Before/after collision table** (read-only queries against
`/realm/db/polylogue/{source,index}.db`):

| native_id | drive raw msgs | local raw msgs | `sessions.raw_id` today
| `raw_session_memberships.decision` | relation under current code |
|---|---|---|---|---|---|
| 0213d48f-5b7a-4241-b77a-eb714672dc3b | 213 | 214 | drive (wrong) |
`ambiguous` (stale, decided 2026-07-30T05:05Z) | `a_contains_b` (local
dominates) |
| 063a6885-8d6a-4f91-80b2-7f67fa06d680 | — | — | drive | `ambiguous`
(stale) | not individually re-simulated; same code path |
| 705f1fcb-8953-4b8b-92f1-9244fcf9db91 | — | — | drive | `ambiguous`
(stale) | same |
| 8c9f8c3d-4859-44cf-be9c-338803a8e7de | — | — | drive | `ambiguous`
(stale) | same |
| a952ffa4-73b0-48bd-a212-ebe5b9772d1e | — | — | drive | `ambiguous`
(stale) | same |
| cf3404fa-89e0-400a-af3e-ff1450eecef4 | — | — | drive | `ambiguous`
(stale) | same |

(15 drive-cache raws total, all genuinely Claude-Code-shaped by content,
parsing into 12 sessions — 6 collide with a local raw as above, 6 do
not.)

**Root cause, precisely**: this is a revision-arbitration bug, not an
identity/detection bug. `session_id = origin || ':' || native_id`
correctly computes the same identity for both raws because they *are*
the same conversation — that's not a defect. Which raw should win is
`archive/session_revision_membership.py`'s job (a content-only set
relation: `equal`/`a_contains_b`/`b_contains_a`/`conflict`,
polylogue-aggz). Directly simulating that relation against the real raw
bytes with **current** code (`parse_stream_payload` +
`session_revision_projection`) gives `a_contains_b` (local strictly
dominates: 0 drive-only messages, 1 local-only message, 0 content
mismatches on the 213 shared identities) — i.e. **the fix already
exists**. The live archive's `raw_session_memberships` decision rows for
these 6 cohorts (`decided_at_ms` ≈ 2026-07-30T05:05–05:13Z) simply
predate the commits that fixed the comparison logic (`9fc5220ef` #3401
"collapse revision comparison into a content-only relation", 15:55Z same
day, and `a9f2f307d` #3405, 17:50Z) — stale data, not a live bug.

**This self-heals without further code changes.**
`daemon/bulk_rebuild.py`'s own docstring documents that the daemon
routes a bulk-scale backlog (which `polylogue ops reset --index`
creates) into `rebuild_index_from_source` →
`backfill_historical_revision_evidence` →
`classify_membership_revisions` — the current, already-fixed relation —
"with zero operator involvement". The operator's already-planned `ops
reset --index && polylogued run` will recompute these 6 cohorts
correctly. **No `SEMANTIC_REPARSE` delta declaration is needed**: no
detection or parsing semantics changed in this PR, and the relevant fix
already shipped (and presumably was already declared) in #3401/#3405.

**Record correction**: PR #3436 verified these 12 drive-cache/gemini
rows are content-shape-correct ("naming coincidence, not a bug") — that
remains true, the content-shape classification was never wrong. It did
not check `native_id` collisions against local raws, so it didn't catch
that 6 of the 12 were silently shadowing a fuller local transcript. That
shadowing was a data-staleness artifact of a bug fixed the same day this
bead's forensics ran, not a defect in #3436's own change.

**Two approaches were tried and reverted** before landing on this
conclusion (session-identity gating in `sources/origin_specs.py` +
`pipeline/services/ingest_worker.py`, refusing session admission for
drive-cache Claude-Code-shaped paths). Both worked mechanically but were
wrong: they would have permanently suppressed the 6 *non-colliding*
drive-cache raws (real content with no local counterpart to supersede
them, so they'd become inert un-queryable `raw_artifacts` rows instead
of correctly-attributed real content) and added unneeded machinery for
the 6 colliding ones, which the already-fixed relation resolves once the
data catches up. Full trail recorded in `polylogue-t83e`'s closing
comment.

## Solution

What remained a real, independently-valuable defect, unrelated to the
collision-resolution question above: the freshness-tie comparison itself
(`existing_updated_at_ms is not None and incoming_freshness_ms <
existing_updated_at_ms`) was hand-duplicated in three call sites that
could silently drift apart. Extracted `should_skip_stale_replace()` into
`archive_tiers/ingest_precedence.py` (the module that already owns
browser-capture write precedence) and call it from all three:

- `polylogue/storage/sqlite/archive_tiers/write.py`
(`write_parsed_session_to_archive`)
- `polylogue/pipeline/services/ingest_batch/_core.py` (`_write_session`)
- `polylogue/storage/sqlite/archive_tiers/revision_governance.py`
(`_write_parsed_precedence_result`)

Each call site keeps its own surrounding guard conditions
(`force_write`/`force_replace`, browser-capture precedence, append-only,
revision-authority membership, `source_index` gating) — those decide
*whether* the check applies at all, not the comparison. The function's
docstring documents that this is a narrow per-write timestamp fallback,
not where content-subset supersession is decided (that's revision
membership, upstream, and takes precedence when it has classified a
cohort).

## Verification

- `devtools test
tests/unit/pipeline/test_archive_write.py::test_older_full_replace_does_not_overwrite_newer_session_body
tests/unit/pipeline/test_ingest_batch.py::test_write_session_force_write_replaces_older_freshness`
— 2 passed (exercises `write.py` and `ingest_batch/_core.py`'s edited
branches directly)
- `devtools test tests/unit/storage/test_revision_replay.py
tests/unit/storage/test_raw_revision_authority.py
tests/unit/sources/test_revision_backfill.py` — 103 passed, 1 failed.
The failure
(`test_parse_one_still_replays_real_claude_code_sessions_with_no_path_rule`)
is pre-existing on `origin/master`: zero diff in the files it exercises
(`archive/artifact_taxonomy/`, `sources/revision_backfill.py`,
`sources/origin_specs.py`), reproduces identically in isolation, and is
about an unrelated `analysis/`-path content-gate regression.
- `devtools verify --seed-testmon --skip-slow` — ruff format, ruff
check, mypy --strict, render all --check,
topology/layering/closure-matrix, schema-versioning policy,
schema-promotion audit all green (see step-by-step `run.json`, exit 0
through step 18); the full pytest seed pass was still mid-sweep when the
verification budget for this session ran out — unrelated to this
change's narrow surface, already covered by the targeted runs above.
- `devtools verify --quick` — green via the pre-push hook
(format/lint/mypy/render).

Ref polylogue-t83e (closed this session with the full investigation
trail in its final comment)

Co-authored-by: Claude <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant