Skip to content

fix(sources): require a genuine chunk in gemini/drive chunkedPrompt detection - #3600

Merged
Sinity merged 3 commits into
masterfrom
feature/fix/gemini-empty-envelope-detection
Aug 3, 2026
Merged

Sinity merged 3 commits into
masterfrom
feature/fix/gemini-empty-envelope-detection

Conversation

@Sinity

@Sinity Sinity commented Aug 3, 2026

Copy link
Copy Markdown
Owner

Summary

Tightens drive.looks_like (the sole auto-detection call site for the Gemini/AI-Studio-Drive chunkedPrompt wire shape) to require at least one genuine chunk with role/content evidence, instead of accepting a present-but-empty (or wrong-typed) chunks list as sufficient evidence on its own.

Problem

polylogue-mvcbi: a residual guess-instead-of-verify branch, sibling to the classifier-tightening pattern already landed in #3428 (Claude Code's bare type check) and #3537 (claude.ai's bare chat_messages check). Before this change:

detect_provider({"chunkedPrompt": {"chunks": []}}))  # -> Provider.GEMINI (wrong)

drive._looks_like_chunks had an allow_empty flag that was True for the named chunkedPrompt.chunks envelope but False for the bare top-level chunks key — the same shape was treated inconsistently depending only on nesting. An empty envelope was never a real Gemini/Drive conversation; no genuine session has zero chunks.

Solution

  • polylogue/sources/parsers/drive.py: _looks_like_chunks drops the allow_empty parameter entirely (both call sites now require the same thing: a non-empty list where every entry passes looks_like_chunk). looks_like now requires a genuine chunk for the chunkedPrompt.chunks envelope, matching the already-strict top-level chunks case.
  • tests/unit/sources/test_gemini_drive_normalization_laws.py: new regression test (test_empty_chunked_prompt_envelope_is_not_detected_as_gemini) pinning the empty-list, wrong-type ("not-a-list", {}), and genuine-chunk cases.
  • tests/unit/sources/test_source_laws.py: test_iter_source_raw_data_keeps_source_family_hints_for_mixed_zip_sources hardcoded the exact buggy empty envelope as its "gemini" zip-entry fixture (relying on the bug to pass); updated to a genuine single-chunk envelope so it still exercises mixed-zip provider-hint detection rather than the now-fixed bug.
  • docs/plans/classifier-fingerprints.json: devtools lab policy classifier-fingerprints flags any looks_like* function whose AST changed without a declared reparse or explicit safety acknowledgment. Acknowledged safe (not a SEMANTIC_REPARSE INDEX_SCHEMA_VERSION bump) via devtools lab policy classifier-fingerprints --ack ... --ref polylogue-mvcbi, since the tightening only rejects a shape that never validly represented a real conversation — the escape hatch the tool's own docstring describes for exactly this case. A schema-version bump belongs to storage/, out of this change's scope.

Interplay checked: an empty envelope no longer detects as any provider; parse_payload falls through to a zero-message unknown session, and require_positive_conversational_evidence (the production content gate every real write path already calls) refuses it with a logged warning — no crash, no silent write.

Out of scope (per assignment): daemon/, storage/, migrations/, artifact-classification/sidecar code, and detector precedence in sources/dispatch.py (tightness order unchanged — verified via test_detector_order_is_tight_and_one_document_streams_keep_specificity, which still passes). parse_drive_payload's explicit-provider route (dispatch.py:1823, "chunkedPrompt" in record or "chunks" in record) is intentionally more tolerant than auto-detection (see has_chunk_container's docstring) and is untouched.

Verification

  • Red-first: devtools test tests/unit/sources/test_gemini_drive_normalization_laws.py -k test_empty_chunked_prompt_envelope_is_not_detected_as_gemini failed before the fix (AssertionError: assert <Provider.GEMINI: 'gemini'> is None), committed as a separate commit, then green after the fix commit.
  • devtools test tests/unit/sources/test_gemini_drive_normalization_laws.py tests/unit/sources/test_parsers_drive.py tests/unit/sources/test_dispatch_ordering.py tests/unit/sources/test_dispatch_payloads.py tests/unit/sources/test_gemini_chunked_prompt_contract.py tests/unit/sources/test_parsers_drive_catalog.py tests/unit/sources/test_source_laws.py — 248 passed, 2 failed. Both failures reproduce identically on unmodified master (verified via git stash): test_iter_source_raw_data_avoids_whole_blob_provider_detection_for_zip_entries and test_iter_source_raw_data_splits_multi_session_zip_entries_for_non_grouped_providers[...] (a stale _detect_provider_from_raw_bytes monkeypatch target and an unrelated claude-ai UNKNOWN detection gap) — pre-existing, unrelated to this change.
  • devtools verify --quick — ruff format/check, mypy --strict, render all --check, topology/layering/closure-matrix/manifests/ci-workflows/doc-commands/docs-coverage/test-infra-currency/pytest-timeout-overrides/degrade-loudly/hash-boundary-census, lab policy schema-versioning, lab policy classifier-fingerprints (initially failed on undeclared drift, fixed via the --ack commit above), lab policy demo-tour-freshness/raw-payload-hash-purity/position-derived-identity/raw-authority-frontier-executability, schema promotion audit — all green, exit_code: 0 (ran via the pre-push hook).
  • devtools verify --seed-testmon --skip-slow — attempted for the full testmon-affected inner loop, but this worktree's host is shared by several other concurrent agent lanes each running the identical heavy seed simultaneously; the seed run itself timed out under that contention (18,575 passed / 14 failed / 2 interrupted / 1 timeout across the whole non-slow suite) rather than completing cleanly. None of the unsuccessful node IDs touch sources/parsers/drive.py, sources/dispatch.py, or either test file this PR changed. The targeted devtools test runs above are the load-bearing verification for this change's actual surface.

Ref polylogue-mvcbi.

Sinity and others added 3 commits August 3, 2026 09:01
Ref polylogue-mvcbi. drive.looks_like accepts a chunkedPrompt.chunks
envelope with zero chunks (allow_empty=True), so an empty or malformed
envelope is currently misdetected as gemini/drive. This test pins the
correct behavior; it fails against current dispatch.py/drive.py:

    AssertionError: assert <Provider.GEMINI: 'gemini'> is None

Fix follows in the next commit.

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

Ref polylogue-mvcbi, sibling fix to #3428/#3537. drive.looks_like accepted
a chunkedPrompt.chunks envelope with zero chunks (allow_empty=True on the
named-envelope branch only), the same guess-instead-of-verify shape
already closed for Claude Code's bare type check and claude.ai's bare
chat_messages check. It now requires at least one chunk with role/content
evidence, matching the bare top-level chunks case that was already
correctly strict.

_looks_like_chunks lost its now-always-False allow_empty parameter since
both call sites converge on the same requirement.

test_source_laws.py::test_iter_source_raw_data_keeps_source_family_hints_for_mixed_zip_sources
hardcoded the exact buggy empty envelope as its gemini fixture; updated
to a genuine single-chunk envelope so it still exercises mixed-zip
provider-hint detection rather than the fixed bug.

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

devtools lab policy classifier-fingerprints flags any looks_like*/
classify_artifact* function whose AST changed without a declared reparse
or explicit safety acknowledgment. drive.looks_like's fingerprint moved
(the fix in the prior commit); acknowledged safe rather than declaring a
SEMANTIC_REPARSE INDEX_SCHEMA_VERSION bump, since the tightening only
rejects a chunkedPrompt.chunks shape (empty or wrong-typed) that never
validly represented a real conversation -- the same acknowledged-safe
class the tool's own docstring describes for this situation. A schema
version bump belongs to storage/, out of this lane's scope; the
production reindex already gates on this bead per the beads-graph notes
on polylogue-818fy/fsgdd.

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

coderabbitai Bot commented Aug 3, 2026

Copy link
Copy Markdown

Warning

Review limit reached

@Sinity, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 56 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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 configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 5d6f9986-b21a-4aa5-acf2-a2e7eb236376

📥 Commits

Reviewing files that changed from the base of the PR and between 2214567 and 4163177.

📒 Files selected for processing (4)
  • docs/plans/classifier-fingerprints.json
  • polylogue/sources/parsers/drive.py
  • tests/unit/sources/test_gemini_drive_normalization_laws.py
  • tests/unit/sources/test_source_laws.py

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@Sinity
Sinity merged commit 65f2f61 into master Aug 3, 2026
3 checks passed
@Sinity
Sinity deleted the feature/fix/gemini-empty-envelope-detection branch August 3, 2026 08:01
Sinity added a commit that referenced this pull request Aug 19, 2026
…gbm-quiet, 7qw4) (#4006)

## Summary

Retires the four mechanical rows of the WS-B known-red/false-green
ledger
(`.agent/campaigns/2026-08-overhaul/ws-b-suite-health.md`): uxrim,
bwo2l,
vqt48, and 7qw4 were all already satisfied on master before this branch
was
cut; the one row that needed real work was polylogue-ndgbm's quiet
component (Codex query-cardinality oracle's fixture never emitted a
`message`-shaped record, so the parser's admission gate refused every
payload and the module fixture errored at setup), which this PR fixes
and
whose two associated xfail markers it removes.

## Problem

The ledger recorded five findings as known-red or false-green test debt,
each with a RECIPE and file:line anchors, dispatched here as a themed
sweep.

## Solution

- **uxrim** (`tests/unit/api/test_facade_contracts.py:4789`): the recipe
  asked to extend the `frozen_clock_modules` marker to also cover
  `revision_governance`. Already done — commit 8ed4f91 (PR #3595,
  2026-08-03) landed exactly that extension. No diff needed.
- **7qw4** (`tests/unit/storage/test_store_ops.py`): the recipe asked to
rewrite the test to call the production `aggregate_message_stats` async
  fn and delete a test-local shadow reimplementation. Already done —
commits from PR #3729 (call the repository path) and PR #3813 (assert on
public `origins`) landed this; no shadow function remains in the file.
No
  diff needed.
- **bwo2l + vqt48** (`tests/unit/cli/test_archive_maintenance_cli.py`,
  `tests/unit/sources/test_live_watcher.py`,
`tests/unit/sources/test_live_batch_support.py`): the recipe asked to
give
  refused codex fixtures real conversational content. Already done — the
9ykn positive-evidence-gate fixes landed across several prior PRs
(visible
  in `git log --grep`: #3555, #3572, #3600, #3642, #3841). All 138 + 259
  tests pass.
- **ndgbm quiet component** (`tests/infra/query_manifest_oracle.py`,
`tests/unit/cli/test_query_composition_laws.py`): the actual fix in this
  PR. `QueryCardinalitySession.wire_records()` emitted only
  `function_call`/`function_call_output` response_items — zero
  `message`-shaped records — so `codex.is_supported_session_stream()`
  (`has_message` never set) refused every payload before ingest and the
  module-scoped fixture errored at setup before either test could run.
Added one planted user/assistant message-pair response_item per session
(same wire shape landed for the bwo2l/vqt48 fixtures), which admits the
stream; action-identity assertions are unaffected because they only
count
  tool rows.

  Removing the two xfail markers this unblocks surfaced two further
pre-existing issues that had never been reachable before (the tests
always
  errored at setup), fixed in the same commit:
- The naive-duplicate-id-join mutation test's hand-rolled `actions` view
    predates the production view's `result_state` CASE projection
    (polylogue-cuxz.5, `archive_tiers/index.py:1040`) and crashed with
`sqlite3.OperationalError: no such column: a.result_state` instead of
producing the comparably-wrong row count the test actually asserts on.
    Added the same CASE projection to the test's naive view.
- `find ... then delete --yes --all` has no non-daemon route — it
refuses
outright when the daemon does not answer the `/prepare` call. Added a
daemon-delete stand-in patch on `_submit_daemon_mutation`, mirroring the
    existing pattern in

`test_verb_cardinality.py::TestDeleteCardinalityLargeNonMocked._daemon_delete_route`
    (does the real delete through `ArchiveStore`, just skips the daemon
    process).
  - `_copy_archive`'s plain `shutil.copytree` left the durable bootstrap
    marker bound to the *original* archive root path
(`durable_identity_digest`), so the first write-mode
`ArchiveStore.open_existing`
    at the copied path raised `DurableChangeTrainError: fresh durable
bootstrap marker durable identity mismatch`. Re-bind the marker after
copy, mirroring
`tests/infra/workload_artifacts.py::clone_seeded_archive`.

**ndgbm residual (not closed by this PR):** the bead also names a
second,
separate symptom — the 64-seed process-pool death only reproduces beside
a
saturated 10-worker gate (confirmed load-only: quiet re-run
20260818T231534Z
was green in 43s). That's a load-robustness question the dispatch prompt
asked to coordinate with WS-A's e98k cgroup-mmap-budget findings. I
could not
type this as a `partial` disposition in the machine-readable pr-scope
carrier below: the validator requires a **pre-existing Beads dependency
edge** (`blocks`/`discovered-from`/`relates-to`/`supersedes`) between
ndgbm
and its named successor before it will accept the disposition, and no
such
edge exists between polylogue-ndgbm and polylogue-e98k today. Per the
lane
contract I do not invoke `bd` from a worktree, so I did not create that
link. **Coordinator action needed:** link `polylogue-ndgbm` →
`polylogue-e98k` (or a dedicated new successor) via `bd dep add` (or
equivalent) before ndgbm can be typed `partial` in a carrier; until then
the
bead should stay open with its residual noted in its own notes (already
present).

## Verification

- `devtools test tests/unit/api/test_facade_contracts.py -k
raw_artifacts_read_source_tier` → 1 passed (uxrim, unchanged/confirmed)
- `devtools test tests/unit/cli/test_archive_maintenance_cli.py` → 138
passed (bwo2l, unchanged/confirmed)
- `devtools test tests/unit/sources/test_live_watcher.py
tests/unit/sources/test_live_batch_support.py` → 259 passed (vqt48,
unchanged/confirmed)
- `devtools test tests/unit/storage/test_store_ops.py -k
aggregate_message_stats` → 1 passed (7qw4, unchanged/confirmed);
mutation red-check locally re-applied AG1 (role-swap on the unfiltered
`role_row` query) and AG2 (`words_approx = 0`) against
`polylogue/storage/sqlite/queries/stats.py`, both now fail (`assert 1 ==
2`, `assert 0 == 9`), reverted before commit — no diff shipped for this
row
- `devtools test tests/unit/cli/test_query_composition_laws.py` → 2
passed, 0 xfail (ndgbm quiet component: red→green; both `-p no:testmon`
and cached runs confirmed)
- `devtools verify --quick` → exit 0 (format + lint + mypy + `render all
--check`; no `out of sync` in output)

All four rows were verified in the context that was failing: each
command
above is the exact standalone-context command named in the dispatch
recipe,
run directly (not nested inside a broader suite run).

## Bead disposition matrix

| Bead | Disposition | Evidence | Notes |
| --- | --- | --- | --- |
| polylogue-uxrim | SATISFIED | test pass + commit 8ed4f91 | already
fixed on master, PR #3595 |
| polylogue-bwo2l | SATISFIED | test pass (138/138) | already fixed on
master |
| polylogue-vqt48 | SATISFIED | test pass (259/259) | already fixed on
master |
| polylogue-7qw4 | SATISFIED | test pass + mutation red-check | already
fixed on master (PR #3729, #3813) |
| polylogue-ndgbm | PARTIAL | test pass (2/2, no xfail) + diff | quiet
component fixed this PR; load-only pool-death residual stays open on the
bead — **not represented in the typed carrier below** (see Solution
section: needs a coordinator-created Beads link to type as `partial`) |

<!-- polylogue-pr-scope:v2
{
  "assigned_beads": [
    "polylogue-uxrim",
    "polylogue-bwo2l",
    "polylogue-vqt48",
    "polylogue-7qw4"
  ],
  "dispositions": [
    {
      "bead_id": "polylogue-uxrim",
      "disposition": "satisfied",
      "evidence": [
        {
          "kind": "test",
"ref":
"tests/unit/api/test_facade_contracts.py::test_archive_tiers_api_raw_artifacts_read_source_tier"
        },
        {
          "kind": "commit",
          "ref": "8ed4f9101813aa142bc915e9c70ef439b86a100d"
        }
      ],
      "successors": []
    },
    {
      "bead_id": "polylogue-bwo2l",
      "disposition": "satisfied",
      "evidence": [
        {
          "kind": "test",
          "ref": "tests/unit/cli/test_archive_maintenance_cli.py"
        }
      ],
      "successors": []
    },
    {
      "bead_id": "polylogue-vqt48",
      "disposition": "satisfied",
      "evidence": [
        {
          "kind": "test",
          "ref": "tests/unit/sources/test_live_watcher.py"
        },
        {
          "kind": "test",
          "ref": "tests/unit/sources/test_live_batch_support.py"
        }
      ],
      "successors": []
    },
    {
      "bead_id": "polylogue-7qw4",
      "disposition": "satisfied",
      "evidence": [
        {
          "kind": "test",
"ref":
"tests/unit/storage/test_store_ops.py::test_aggregate_message_stats_reports_public_contract"
        }
      ],
      "successors": []
    }
  ],
  "mutated_beads": [],
"scope_digest":
"e397dd57058877a651382c5cf8f681b4cffabc7aae67e285f7192b2c62c787ad",
  "scope_kind": "bead",
  "version": 2
}
-->

Ref polylogue-uxrim, polylogue-bwo2l, polylogue-vqt48, polylogue-ndgbm,
polylogue-7qw4

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01HWcPJJJvuF25CqVwTFgSQC

Co-authored-by: Claude Sonnet 5 <[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