Skip to content

fix(plugins): close BQAA fail-open privacy, GCS concurrency, and startup-loss gaps (#6356) - #6360

Closed
caohy1988 wants to merge 6 commits into
google:mainfrom
caohy1988:fix/bqaa-6356
Closed

caohy1988 wants to merge 6 commits into
google:mainfrom
caohy1988:fix/bqaa-6356

Conversation

@caohy1988

@caohy1988 caohy1988 commented Jul 10, 2026 •

Copy link
Copy Markdown

Addresses the four P1 findings and the mechanical P2s from #6356 (BigQuery Agent Analytics: fail-open privacy, GCS concurrency, and startup-loss gaps).

P1 fixes

1. content_formatter failure now fails closed. A raising formatter replaces content with a [FORMATTER_FAILED] sentinel instead of falling back to the unformatted payload; the exception is logged without the payload and counted as formatter_failed in get_drop_stats(). The existing test that codified fail-open (asserting the original "Secret message" was written) now asserts fail-closed.

2. Final sanitizer pass over the complete attributes tree. _log_event now runs _recursive_smart_truncate over the fully assembled attributes immediately before json.dumps, covering the producers that copied values in directly (state_delta via extra_attributes, custom_tags, labels, nested structures, temp:-scoped keys). Truncation from this pass propagates into is_truncated. New: _sanitize_json_blob redacts sensitive keys inside JSON-encoded string blobs (e.g. cached credential JSON) — the #5112-adjacent gap. It decodes container-shaped ({/[) strings FIRST (raw-substring prefilters are bypassable via JSON escapes), enforces max_content_length before json.loads, and fails closed to [UNPARSEABLE_JSON_BLOB] for anything container-shaped it cannot parse and verify (malformed/trailing-garbage/over-limit/too-deep blobs, duplicate members always reserialized). Producer-local sanitization is kept as an optimization; the final pass is the mandatory boundary.

3. GCS offload paths are call-local. HybridContentParser.parse() and _parse_content_object() take trace_id/span_id as keyword arguments and build every object path from those call-local values. _log_event passes them per call instead of mutating the shared parser. The constructor fields remain only as a backward-compatible default. Regression test: two overlapping two-part parses with a forced interleave assert 4 unique object paths with correct per-event ownership (previously: event A resumed with event B's identity and both wrote trace-b/span-b_p1, the later upload overwriting the earlier).

4. Table readiness is a startup requirement with bounded retry. _ensure_schema_exists now raises on table get/create failures (preserving NotFound → create and Conflict → concurrent-creation handling) instead of logging and returning. _ensure_started records the failure, keeps _started=False, and retries on a later event after exponential backoff (2s → 60s cap). Setup is coalesced ACROSS event loops and threads via a concurrent.futures.Future claimed under a briefly-held threading.Lock (waiters asyncio.wrap_future it from their own loops), so exactly one _lazy_setup runs per attempt and a persistent outage costs one setup RPC per backoff window, not one per event. Rows arriving while setup is unavailable are counted as setup_unavailable.

P2 hardening included

  • enabled=False is a hard no-op at the single choke point (_ensure_started), covering before_run_callback, __aenter__, and _log_event: no ADC lookup, client creation, table RPCs, or background tasks. Test asserts zero side effects.
  • Runtime settings validated at construction (_validate_runtime_config): batch_size, batch_flush_interval, shutdown_timeout, queue_max_size, max_content_length, and all RetryConfig fields. Notably max_retries < 0 used to skip the write loop entirely, dropping every batch without one attempt.
  • Loss accounting before/outside the BatchProcessor: plugin-level drop counters (formatter_failed, setup_unavailable) merged into get_drop_stats(); they survive shutdown and loop cleanup.

Acceptance tests from #6356 covered here

  • A raising content_formatter never writes the original content.
  • Final attributes sanitization covers state deltas, custom tags, nested structures, temp: keys, and JSON-encoded secret blobs.
  • Concurrent two-part GCS offloads retain call-local trace/span paths and never share an object name.
  • Failed table get/create leaves _started=False, records loss, and succeeds on a later retry (coalesced, backed off).
  • enabled=False causes zero auth/client/table/writer/background side effects through Runner callbacks and async context-manager use.
  • Invalid batch, queue, duration, and retry settings fail during plugin construction.
  • Drop stats remain queryable after shutdown and include pre-processor failure reasons.
  • Bounding/decoupling first-use setup latency from agent callbacks (P2) — intentionally deferred; the retry/backoff change bounds the failure path, but the cold-start await is a larger design choice (explicit preflight vs. async readiness) best done as a follow-up.

Verification

  • New TestIssue6356Hardening class (config validation, final-pass redaction incl. JSON blobs, concurrent-offload path isolation, setup retry, disabled-mode no-op, drop-stat persistence) + the rewritten formatter-failure test. Full-suite local run in progress — draft until it and CI confirm green.
  • mypy (repo config) on the plugin file: no new errors vs. main baseline; pyink --check / isort --check-only clean.

Refs #6356 (kept open: the deferred cold-start latency P2 remains tracked there; closing is the maintainers' call on merge).

…tup-loss gaps

Addresses the four P1 findings and mechanical P2s from google#6356:

- content_formatter failure fails closed: content is replaced with a
  [FORMATTER_FAILED] sentinel, never the unformatted payload; counted
  as formatter_failed in get_drop_stats().
- Final sanitizer pass over the complete assembled attributes tree
  immediately before serialization (covers state_delta, custom_tags,
  labels, nested keys, temp: scope), with truncation propagated into
  is_truncated. JSON-encoded string blobs are parsed and redacted when
  they mention a sensitive key.
- HybridContentParser.parse()/_parse_content_object() take call-local
  trace_id/span_id; GCS object paths can no longer be overwritten by a
  concurrent event mutating the shared parser.
- _ensure_schema_exists raises on table get/create failure (NotFound ->
  create and Conflict handling preserved); _ensure_started keeps
  _started=False, retries after bounded exponential backoff coalesced
  behind the setup lock, and rows lost meanwhile are counted as
  setup_unavailable.
- enabled=False short-circuits _ensure_started (zero auth/client/table/
  writer side effects from any entry point).
- Runtime settings validated at construction (batch, flush, shutdown,
  queue, max_content_length, RetryConfig; max_retries < 0 previously
  skipped the write loop entirely).
- Plugin-level drop counters merged into get_drop_stats(), surviving
  shutdown.
@caohy1988

Copy link
Copy Markdown
Author

Fresh review at exact head 257c51b0 against base 9d306f5d.

Verdict: FAIL. Keep this draft. I found four P1 production issues, three P2 issues, and one deterministic red test.

  1. [P1] Startup retry skips table readiness. _lazy_setup() caches _schema before _ensure_schema_exists() succeeds. On retry, the cache causes the table check to be skipped, then _started=True. Repro: after recovery, get_table.call_count remained 1. Run readiness on every startup attempt until it succeeds, and strengthen the test to assert the second RPC.

  2. [P1] GCS keys still collide inside multi-message requests. idx restarts for each Content, while every message shares the same trace/span in the LlmRequest.contents loop. Two images at part 0 produced the same path, so the second overwrites the first. Add a per-parse unique ID plus content and part ordinals.

  3. [P1] Formatter failures can leak the protected payload into application logs. The handler uses exc_info=True. If the formatter raises with content in its exception message, the traceback logs it. My repro printed TOPSECRET. Log only a generic message or the exception class, without its message or traceback.

  4. [P1] Valid JSON encoding bypasses blob redaction. The raw substring prefilter runs before JSON decoding. {"access\u005ftoken":"SECRET"} remains unchanged, as do arrays containing credential objects. Parse {/[ candidates first, then inspect and sanitize decoded keys recursively.

  5. [P2] Existing processor drop counters disappear during shutdown. get_drop_stats() reads active processors, but shutdown() clears every loop state. Repro: {"queue_full": 2} became {}. Fold processor totals into persistent plugin counters before clearing states.

  6. [P2] Legacy pickles lack the new runtime fields. __setstate__() backfills only _init_pid. Pre-change state makes get_drop_stats() raise AttributeError for _local_drop_counts. Backfill all three new fields and reset retry-only state during pickling.

  7. [P2] Runtime validation accepts non-finite and wrong-type values. Ordered comparisons in _validate_runtime_config() do not reject NaN. max_retries=float("nan") skips the write loop entirely, silently losing batches. Enforce integral count fields and finite real-valued durations/multipliers.

  8. [P1/CI] The current test file is red. test_views_not_created_after_table_creation_failure still expects the now-intentional exception to be swallowed. Focused result: 7 passed, 1 failed. Update it to expect the propagated error while still asserting that views were not attempted.

Verification:

  • pyink, isort, and git diff --check: clean.
  • mypy: independently confirmed 64 errors on base and 64 on head.
  • New/rewritten hardening tests pass.
  • Independent adversarial and structured reviews confirmed the retry, JSON-redaction, pickle, GCS, formatter-log, and non-finite-config findings.

The cold-start latency deferral is reasonable and accurately disclosed. It is not part of this fail gate.

…als, log leak, blob decode-first

All eight findings from the PR google#6360 review at 257c51b:

- P1-1: _ensure_schema_exists now runs on every setup attempt until one
  succeeds; the cached _schema no longer gates it. Retry test asserts the
  second get_table RPC.
- P1-2: GCS object names gain a per-parse uid and content ordinal, so
  multiple messages in one request (same trace/span, restarting part
  index) can no longer collide. New multi-message regression test.
- P1-3: the formatter-failure log carries only the exception class — no
  message, no exc_info — so a formatter that embeds content in its
  exception cannot leak it into application logs. Test asserts caplog.
- P1-4: _sanitize_json_blob decodes FIRST ({ or [ prefixes), inspecting
  decoded keys recursively — JSON string escapes (access\u005ftoken) and
  arrays of credential objects are covered; unchanged strings return
  byte-for-byte. New escape/array regression test.
- P2-5: shutdown() folds processor drop counters into the persistent
  plugin counters before clearing loop state.
- P2-6: __setstate__ backfills _local_drop_counts/_setup_failures/
  _setup_retry_at for pre-change pickles; __getstate__ resets retry state.
- P2-7: _validate_runtime_config enforces integral counts and finite
  reals (NaN previously passed every ordered comparison; max_retries=NaN
  silently skipped the write loop).
- CI: test_views_not_created_after_table_creation_failure updated to the
  intentional raise; parser-reuse test now pins the no-mutation contract.

Also adds a recursion depth cap to _recursive_smart_truncate: id()-based
cycle detection cannot catch graphs that manufacture new objects per
duck-typed access (Mock-like), which the new final sanitizer pass exposed
as an unbounded recursion.
@caohy1988

Copy link
Copy Markdown
Author

Pushed 75967014 addressing all eight findings from the review:

  1. P1 retry readiness — _ensure_schema_exists now runs on every setup attempt until one succeeds; the cached _schema no longer gates it. The retry test asserts the second get_table RPC (call_count == failed_calls + 1).
  2. P1 GCS key collisions within a request — object names now include a per-parse() uid plus a content ordinal alongside the part index (…/{span}_{uid}_c{n}_p{idx}). New regression: two single-image messages in one LlmRequest produce two unique paths.
  3. P1 formatter log leak — the warning logs only the exception class (no message, no exc_info). New test: a formatter raising ValueError(f"…{content}") leaves no payload in caplog.text.
  4. P1 blob redaction bypass — _sanitize_json_blob decodes first for {/[ prefixes and inspects decoded keys recursively; \u005f escapes and credential arrays are covered, and strings needing no redaction return byte-for-byte (no cosmetic re-serialization). New escape/array regression test.
  5. P2 shutdown counter loss — shutdown() folds processor drop stats into the persistent plugin counters before clearing loop state; {"queue_full": 2} now survives shutdown (tested).
  6. P2 legacy pickles — __setstate__ backfills _local_drop_counts/_setup_failures/_setup_retry_at; __getstate__ resets retry-only state. Tested by round-tripping a state dict with the new keys removed.
  7. P2 non-finite/wrong-type config — _validate_runtime_config now enforces integral counts (bools rejected) and finite reals via math.isfinite; NaN/inf/str/float-typed values all raise at construction (tested, including max_retries=NaN).
  8. CI red test — test_views_not_created_after_table_creation_failure updated to expect the intentional raise while still asserting views are skipped; the parser-reuse test now pins the no-mutation contract.

One additional fix the final sanitizer pass surfaced: _recursive_smart_truncate gained a recursion depth cap (_MAX_SANITIZE_DEPTH) — id()-based cycle detection can't catch object graphs that manufacture new objects per duck-typed access (model_dump() returning fresh wrappers, Mock-like), which previously recursed unboundedly.

Verification at 75967014: full BQAA suite 324 passed (~23s, faulthandler-guarded); mypy vs 9d306f5d baseline: 0 new errors (64→64); pyink/isort/git diff --check clean.

@caohy1988

Copy link
Copy Markdown
Author

Fresh review at exact head 75967014 against base 9d306f5d.

Verdict: FAIL. Keep this draft. The eight findings from the previous review are addressed and their regressions are green, but this fresh pass found three P1 and five P2 gaps.

  1. [P1] Duplicate JSON keys bypass credential redaction. _sanitize_json_blob() infers safety from sanitized == parsed, but json.loads() discards earlier duplicate members. Repro: {"access_token":"SECRET","access_token":"[REDACTED]"} was returned unchanged with SECRET still present. Track whether any sensitive member was encountered, or preserve duplicate pairs while parsing, and always reserialize that blob.

  2. [P1] Schema-upgrade failures still mark setup ready. _maybe_upgrade_schema() swallows update_table() errors, after which _ensure_started() sets _started=True. If the remote table is missing required fields, every later row can fail with a non-retryable schema mismatch and readiness is never retried. The existing test explicitly pins “logged, not raised”. Propagate upgrade failures whenever fields are actually missing.

  3. [P1] Non-dict mappings bypass the mandatory sanitizer. The walker recognizes only concrete dict containers, then stringifies unknown objects. Repros with MappingProxyType({"access_token": "SECRET-PROXY"}) and UserDict({"refresh_token": "SECRET-USERDICT"}) both retained the secret in output. Handle collections.abc.Mapping recursively and emit a plain sanitized dict.

  4. [P2] Shutdown timeouts lose rows without a drop count. BatchProcessor.shutdown() cancels the worker without counting its in-flight batch or remaining queued rows; plugin shutdown then persists only the unchanged processor counters. In a two-row hung-writer repro, both rows were unwritten while every reported counter remained zero. Count a shutdown_timeout/shutdown-race reason for the in-flight batch and all non-sentinel queued rows before cancellation/cleanup.

  5. [P2] Deep JSON defeats the sanitizer depth cap. json.loads() executes before the bounded traversal, while only TypeError and ValueError are caught. A 10,000-level nested array of roughly 20 KB raised RecursionError, despite fitting under the default 500 KB content limit; the callback wrapper then drops the entire analytics row. Bound/preflight JSON nesting or fail closed to a sentinel on parser resource errors, and add a regression test.

  6. [P2] Closed-loop cleanup still erases drop statistics. _cleanup_stale_loop_states() deletes processor state directly. Repro: a closed-loop processor reporting {"write_failed": 7} became {} immediately after cleanup, so later shutdown cannot recover it. Fold processor counters into _local_drop_counts before deletion, just as shutdown now does.

  7. [P2] Legacy pickles bypass the new runtime validation. __setstate__() restores configuration without calling _validate_runtime_config(). A pre-change state containing retry_config.max_retries = NaN restores successfully; the write-loop comparison is then false immediately, so every batch is skipped without a write or drop count. Validate restored configuration after backfilling compatibility fields.

  8. [P2] GCS collision protection has only 32 random bits. uuid.uuid4().hex[:8] reaches about 50% birthday-collision probability around 77,000 parses sharing a date/trace/span prefix. Uploads overwrite without a generation precondition, so a collision makes an older BigQuery row resolve to another event’s bytes. Use the full UUID and preferably if_generation_match=0.

Scope note: the cold-start latency deferral remains reasonable and is not part of this fail gate. However, the PR body says Fixes #6356; merging into main will automatically close #6356, contradicting the statement that the deferred item remains tracked there. Change this to Refs #6356 or create and link a dedicated follow-up issue before merge.

Verification at the unchanged head:

  • Full BQAA test file: 318 passed, 6 skipped in 26.86s, so 324 tests were collected; the exact result is not 324 passed.
  • All prior review regressions are green.
  • mypy: 64 errors on base, 64 on head, zero new.
  • pyink --check, isort --check-only, and git diff --check: clean.
  • GitHub currently shows only check-changes/CLA/header results, not the Python suite.
  • Independent adversarial and structured reviews both confirmed the duplicate-key privacy bypass; the adversarial pass also independently confirmed schema-upgrade readiness, shutdown loss accounting, deep-JSON failure, closed-loop counter loss, legacy-pickle validation, and truncated-UUID collision risk.

…ss, Mapping redaction, loss accounting

All eight findings from the round-2 review at 7596701:

- P1-1: _sanitize_json_blob tracks duplicate JSON members via an
  object_pairs_hook; blobs with duplicates are always reserialized, so an
  earlier duplicate secret member can no longer ride through the
  sanitized == parsed shortcut.
- P1-2: _maybe_upgrade_schema re-raises update_table failures — a table
  verifiably missing required fields no longer lets _ensure_started mark
  the plugin ready with no readiness retry. Both pinned logged-not-raised
  tests updated to the new contract.
- P1-3: the sanitizer walks collections.abc.Mapping (MappingProxyType,
  UserDict, ...) and emits plain sanitized dicts instead of stringifying
  them past key redaction.
- P2-4: shutdown-timeout losses are counted — the cancelled worker counts
  its in-flight batch and shutdown() drains and counts queued rows under
  a new shutdown_timeout drop reason.
- P2-5: RecursionError/MemoryError while parsing a JSON blob fails closed
  to [UNPARSEABLE_JSON_BLOB] instead of passing the row through
  unexamined (or dropping the whole row via the callback wrapper).
- P2-6: _cleanup_stale_loop_states folds the dead processor's drop
  counters into the persistent plugin counters before deletion.
- P2-7: __setstate__ validates the restored config; a legacy pickle with
  retry_config.max_retries=NaN now fails at restore instead of silently
  skipping the write loop.
- P2-8: GCS object names use the full 128-bit uuid, and uploads pass
  if_generation_match=0 (create-only) so a collision fails loudly instead
  of rebinding an existing row to another event's bytes.
@caohy1988

Copy link
Copy Markdown
Author

Pushed 9b799403 addressing all eight round-2 findings from the review:

  1. P1 duplicate-key bypass — _sanitize_json_blob parses with an object_pairs_hook that flags duplicate members; any blob containing duplicates is always reserialized from the sanitized (last-wins) structure, so {"access_token":"SECRET","access_token":"[REDACTED]"} can no longer ride through the sanitized == parsed shortcut. Regression test asserts the secret is gone.
  2. P1 schema-upgrade readiness — _maybe_upgrade_schema re-raises update_table failures (fields are verifiably missing at that point), so _ensure_started keeps _started=False and the backoff/retry path re-runs readiness. Both pinned "logged, not raised" tests updated to the new contract.
  3. P1 Mapping bypass — the walker now recurses collections.abc.Mapping (covering MappingProxyType, UserDict, …) and emits a plain sanitized dict; regression test pins both repros from the review.
  4. P2 shutdown-timeout loss — new shutdown_timeout drop reason: the cancelled worker counts its in-flight batch, and shutdown() drains and counts remaining non-sentinel queued rows. The hung-writer repro is now a test (stats["shutdown_timeout"] == 2 for one in-flight + one queued row).
  5. P2 deep-JSON resource errors — RecursionError/MemoryError during blob parsing fail closed to [UNPARSEABLE_JSON_BLOB] (the row keeps flowing); the 10k-nesting repro is the regression test.
  6. P2 closed-loop counter loss — _cleanup_stale_loop_states folds the dead processor's counters into the persistent plugin counters before deletion, mirroring shutdown(); tested with the {"write_failed": 7} repro.
  7. P2 legacy-pickle validation — __setstate__ runs _validate_runtime_config after backfilling; a restored max_retries=NaN now raises at unpickle instead of silently skipping the write loop. Tested.
  8. P2 GCS collision margin — object names carry the full 128-bit uuid, and _upload_sync passes if_generation_match=0 so the (now astronomically unlikely) collision fails the upload — surfaced as [UPLOAD FAILED] — rather than rebinding an existing row to another event's bytes. Tested on both counts.

Scope note taken: PR body now says Refs #6356 instead of Fixes, so merging won't auto-close the issue while the cold-start latency P2 is still tracked there.

On the verification-count discrepancy you flagged: agreed — my "324 passed" was this env (no optional-dep skips); your 318+6 skipped is the same 324 collected. At 9b799403 this env reports 331 passed (7 new round-2 regressions), mypy 64→64 (0 new; the initially-untyped _pairs_hook was caught and annotated), pyink/isort/git diff --check clean.

@adk-bot adk-bot added the tracing [Component] This issue is related to OpenTelemetry tracing label Jul 11, 2026
@caohy1988

Copy link
Copy Markdown
Author

Fresh review, round 3 (9b799403)

Verdict: 2 P1s, 3 P2s, 1 P3. All behavioral findings below were reproduced against the exact PR head.

P1 — JSON sanitizer still fails open on ValueError

_sanitize_json_blob() returns the original string for every ValueError. Python raises one when parsing integers over its digit limit, even though the input is syntactically valid JSON.

Repro: {"access_token":"SECRET","n":<5000 digits>} returns byte-for-byte unchanged and still contains SECRET. An inspection failure at this privacy boundary needs to produce a sentinel or otherwise guarantee redaction.

P1 — A label-only update failure disables a write-compatible table

_maybe_upgrade_schema() re-raises update_table failures even when new_fields and updated_records are both empty and only the governance label is stale.

Reproduced with an identical table schema and a forbidden label update: setup enters backoff and subsequent events become setup_unavailable, although writes could succeed. Only failures required to install missing schema fields should block readiness; label-only failures should be handled separately.

P2 — Setup coalescing is unsafe across supported event loops/threads

_ensure_started() shares one asyncio.Lock across all loops. Such locks are loop-bound and cannot safely wake waiters belonging to another thread's loop.

A deterministic two-loop startup produced RuntimeError: Non-thread-safe operation invoked on an event loop other than the current one in one caller while the other remained stuck. Setup needs a cross-thread-safe coalescing mechanism or appropriately isolated per-loop initialization.

P2 — Concurrent stale-loop cleanup double-counts and raises

_cleanup_stale_loop_states() snapshots stale keys, then separately reads, folds, and deletes them without synchronization.

Two concurrent cleanups of one processor reporting seven drops produced {"write_failed": 14} and a KeyError. Claim ownership atomically before folding counters.

P2 — BatchProcessor.close() still loses queued rows silently

close() cancels the worker but neither drains nor counts remaining queued rows.

With one in-flight and one queued row, close() reported one shutdown_timeout drop while leaving queue size one. It should share the corrected shutdown() drain/accounting path.

P3 — Duplicate unreachable cancellation handler

_batch_writer() has two consecutive except asyncio.CancelledError blocks. The second is unreachable and should be removed or consolidated.

Verification

  • 325 passed, 6 skipped for the complete BQAA test module.
  • mypy baseline unchanged: 64 -> 64.
  • pyink, isort, and git diff --check clean.
  • Current upstream main does not modify either changed file.
  • The duplicate-key bypass, escaped-key/array redaction, schema-field upgrade failure, Mapping handling, shutdown accounting, stale-state persistence, pickle validation, and full-UUID/create-only GCS changes were specifically rechecked and otherwise held up.

…abel-only readiness, cross-loop setup

All six findings from the round-3 review at 9b79940:

- P1-1: json.JSONDecodeError (not JSON) passes through; every OTHER
  ValueError from json.loads — e.g. integers over the interpreter digit
  limit on syntactically valid JSON — now fails closed to the
  [UNPARSEABLE_JSON_BLOB] sentinel, alongside RecursionError/MemoryError.
- P1-2: _maybe_upgrade_schema re-raises update_table failures only when
  schema fields are actually missing; a label-only refresh failure logs
  and continues, since the table is write-compatible and the stale label
  retries next run.
- P2: _ensure_started uses per-event-loop asyncio locks (dict guarded by
  a threading.Lock) — one shared asyncio.Lock is loop-bound and raised
  'Non-thread-safe operation' with waiters stranded on other loops.
  Pickle/reset/fork paths updated for the new fields.
- P2: _cleanup_stale_loop_states claims each state atomically via
  dict.pop before folding counters — read-fold-delete raced under
  concurrent cleanup, double-counting and raising KeyError.
- P2: BatchProcessor.close() shares shutdown()'s drain/accounting, so
  rows stranded in the queue are counted under shutdown_timeout instead
  of silently discarded.
- P3: the duplicate CancelledError handler is consolidated. The kept
  handler must RE-RAISE: asyncio.wait_for treats suppressed cancellation
  as normal completion, so a swallow-and-break variant silently disabled
  shutdown()'s drain branch (caught by the round-2 regression test).

Six new regression tests, including a two-thread/two-loop startup test
and the reviewer's big-int and label-only repros.
@caohy1988

Copy link
Copy Markdown
Author

Pushed 5c5521d1 addressing all six round-3 findings from the review:

  1. P1 blob ValueError fail-open — json.JSONDecodeError (genuinely not JSON) still passes through to normal string handling, but every other ValueError from json.loads — your big-int repro raises one on syntactically valid JSON — now fails closed to [UNPARSEABLE_JSON_BLOB], joining RecursionError/MemoryError. The 5000-digit repro is the regression test.
  2. P1 label-only readiness block — _maybe_upgrade_schema re-raises only when new_fields or updated_records is non-empty; a label-only update_table failure logs and continues (table is write-compatible; the un-stamped label retries next run). Tested with an identical-schema table and a forbidden label update.
  3. P2 cross-loop setup lock — _ensure_started now takes a per-event-loop asyncio.Lock from a threading.Lock-guarded dict; each loop coalesces independently and _lazy_setup re-checks _started inside, so a rare cross-loop overlap costs at most one duplicate idempotent RPC. Regression: two threads with fresh loops start concurrently with zero errors. Pickle/fork/reset paths updated for the new fields.
  4. P2 cleanup race — _cleanup_stale_loop_states claims each state atomically with dict.pop before folding, making the fold exactly-once (no double count, no KeyError).
  5. P2 close() loss — close() shares shutdown()'s drain/accounting; the one-in-flight + one-queued repro now reports shutdown_timeout == 2 with an empty queue (tested).
  6. P3 duplicate handler — consolidated to a single CancelledError handler. One subtlety your finding surfaced: the kept handler must re-raise, not swallow-and-break — asyncio.wait_for treats suppressed cancellation as normal completion, so the swallow variant silently disabled shutdown()'s timeout-drain branch. The round-2 regression test caught this immediately when I first consolidated the wrong way.

Verification at 5c5521d1: 336 passed in this env (6 new round-3 regressions; your env should read 330 passed + 6 skipped), mypy 64→64 (0 new), pyink/isort/git diff --check clean.

@caohy1988

Copy link
Copy Markdown
Author

Fresh review, round 4 (5c5521d1)

Verdict: 3 P1s, 5 P2s. All behavioral findings below were reproduced against the exact PR head. The six round-3 repros themselves now pass.

P1 — Malformed JSON-shaped credentials still leak

JSONDecodeError is passed through unchanged. Appending one character to valid credential JSON bypasses redaction, including with an escaped key:

{"access\u005ftoken":"SECRET"} trailing

Recommended fix: treat every container-shaped ({ / [) parse failure as unverified and replace it with [UNPARSEABLE_JSON_BLOB]. A raw sensitive-substring fallback is insufficient because JSON escapes recreate the same bypass. Add malformed-object, trailing-garbage, and escaped-key regressions.

P1 — JSON is materialized before applying max_content_length

json.loads() runs synchronously before the configured content limit is enforced. A user-controlled multi-megabyte attribute can block the callback loop and allocate far beyond the limit.

Recommended fix: pass the configured limit into _sanitize_json_blob and reject oversized container strings before json.loads. Fail closed to a fixed sentinel rather than truncating the raw JSON prefix, which could retain a secret and produce invalid JSON. Add a test that patches json.loads and proves it is never called for an over-limit blob.

P1 — Per-loop locks allow unsafe concurrent shared setup

_ensure_started() gives each loop a different lock, so two loops both enter _lazy_setup. Reproduced setup_calls == 2; a controlled success/failure race left _started=True and _startup_error=RuntimeError simultaneously.

_lazy_setup mutates shared clients, executor, parser, schema, views, and retry state across awaits, so the duplicate call is not idempotent.

Recommended fix: split setup into (1) process-wide shared initialization and (2) loop-local writer creation. Coalesce shared initialization with a concurrent.futures.Future or equivalent cross-loop future guarded by a short-held threading.Lock, then await it from each loop with asyncio.wrap_future. Do not hold a threading lock across an await. Keep loop-local _get_loop_state() separate. The regression test should assert setup_calls == 1, every thread terminated, and shared readiness invariants remain consistent when one participant fails.

P2 — Namedtuple attributes now drop the entire event

type(obj)(new_list) cannot reconstruct tuple subclasses whose constructors require positional fields. A namedtuple in custom_tags serialized as an array before the final pass; it now raises TypeError, and the safe callback drops the row.

Recommended fix: normalize tuple subclasses to plain lists. If preserving plain tuples matters internally, use tuple(new_list) only when type(obj) is tuple; JSON does not preserve tuple identity anyway. Add a row-level namedtuple regression.

P2 — _setup_locks permanently retains closed loops

_get_setup_lock() stores loops as strong keys. Neither stale cleanup nor normal shutdown removes them. Four fresh-loop start/shutdown cycles retained four closed loops.

Recommended fix: the shared-setup redesign above should remove the per-loop setup-lock map entirely. If the map remains, explicitly claim and remove closed-loop locks under _setup_locks_guard, and clear the map during shutdown. Do not rely only on weak keys if the lock value can itself retain its loop. Add a repeated asyncio.run() regression asserting no closed loops remain reachable.

P2 — Stale-state cleanup still races concurrent dictionary mutation

_cleanup_stale_loop_states() iterates the shared dictionary without synchronization before reaching the atomic pop. Inserting another loop during is_closed() reproduced RuntimeError: dictionary changed size during iteration.

The new "concurrent" regression invokes cleanup twice sequentially, so it does not exercise the race.

Recommended fix: guard _loop_state_by_loop ownership changes with a threading lock. Snapshot keys under the lock, evaluate closed state outside it, then reacquire the lock to pop each state exactly once. Fold counters after claiming, with synchronized updates to _local_drop_counts. Add the actual two-thread mutation repro and assert no exception or double fold.

P2 — Depth-based replacement reports is_truncated=False

[MAX_DEPTH_EXCEEDED] returns False. A finite 50-level mapping discards its remaining payload but the emitted row says it was not truncated.

Recommended fix: return True when inserting the sentinel, or expose a separate observable replacement/loss reason and set the row flag consistently. Add a row-level test, not only a direct helper assertion.

P2 — Validation rejects previously supported zero-delay retries

initial_delay and max_delay must now be strictly positive. Existing BQAA tests explicitly use max_retries=0, initial_delay=0, max_delay=0, and the write loop supports it. The same RetryConfig works with BatchProcessor but raises during plugin construction.

Recommended fix: validate retry delays as finite and non-negative. At minimum, allow zero delays when max_retries == 0; preserving zero-delay immediate retries is also backward-compatible because asyncio.sleep(0) is valid. Pin construction and write behavior with the existing zero-delay configuration.

Verification

  • 330 passed, 6 skipped for the complete BQAA test module.
  • mypy: no new errors, 64 at the pinned base versus 61 at the head in this fresh environment.
  • pyink, isort, and git diff --check clean.
  • Current upstream main does not modify either changed file.

The PR body should also be refreshed: it still describes a removed "cheap hint check" and claims one setup RPC per backoff window, which the per-loop-lock implementation does not provide.

…ize-gated parsing, cross-loop setup future

All eight findings from the round-4 review at 5c5521d:

- P1-1: every container-shaped ({ or [) parse failure now fails closed
  to [UNPARSEABLE_JSON_BLOB] — trailing garbage on valid credential JSON
  (incl. escaped keys) can no longer bypass redaction. Malformed-object,
  trailing-garbage, and escaped-key regressions added.
- P1-2: _sanitize_json_blob enforces max_content_length BEFORE
  json.loads; over-limit container blobs fail closed without being
  materialized (test patches json.loads to prove it is never called).
- P1-3: shared setup is coalesced across event loops/threads with a
  concurrent.futures.Future claimed under a briefly-held threading.Lock
  (never across an await); waiters await it via asyncio.wrap_future from
  their own loops. Exactly one _lazy_setup runs (regression asserts
  setup_calls == 1 across two threads); a failing owner leaves consistent
  _started/_startup_error/backoff state for all participants. This also
  removes the per-loop _setup_locks map entirely (P2: it retained every
  closed loop forever).
- P2: tuple subclasses (namedtuples) normalize to plain lists in the
  sanitizer instead of raising TypeError and dropping the row. Duck-typed
  conversions (model_dump/dict/to_dict) now require progress to a real
  dict/list before recursing, so Mock-like graphs settle at the stringify
  fallback instead of churning to the depth cap.
- P2: _loop_state_by_loop ownership changes are guarded by a
  threading.Lock; cleanup snapshots keys under the guard, evaluates
  is_closed() outside it, and claims each state atomically (regression:
  insertion during is_closed() no longer raises 'dictionary changed size
  during iteration').
- P2: the [MAX_DEPTH_EXCEEDED] replacement now reports is_truncated=True
  — it discards real payload, unlike [CIRCULAR_REFERENCE]. Row-level test
  included.
- P2: retry delays are validated as finite and NON-negative; the
  long-supported max_retries=0/initial_delay=0/max_delay=0 config
  constructs again (pinned by test).
@caohy1988

Copy link
Copy Markdown
Author

Pushed 100e17ed addressing all eight round-4 findings from the review:

  1. P1 malformed-blob leak — every container-shaped parse failure now fails closed to [UNPARSEABLE_JSON_BLOB] (the JSONDecodeError pass-through is gone; as you noted, a raw-substring fallback is escape-bypassable so there is none). Regressions: malformed object, trailing garbage on valid credential JSON, and the escaped-key variant.
  2. P1 pre-parse size gate — _sanitize_json_blob takes max_content_length and rejects over-limit container strings before json.loads, failing closed to the sentinel (never a raw-prefix truncation). The regression patches json.loads with an AssertionError side effect to prove it is not called.
  3. P1 cross-loop shared setup — redesigned per your recommendation: shared init is coalesced with a concurrent.futures.Future claimed under a briefly-held threading.Lock (never across an await); waiters asyncio.wrap_future it from their own loops; loop-local writer state stays in _get_loop_state(). Regressions: two threads/loops → setup_calls == 1, all threads terminate, _started/_setup_future consistent; a failing owner leaves _started=False + recorded error + cleared future for the next backoff window.
  4. P2 namedtuples — tuple/list subclasses normalize to plain lists (type(obj)(new_list) only for exact tuple/list). Row-level regression: a namedtuple in extra_attributes lands as [1, 2] instead of dropping the row.
  5. P2 _setup_locks retention — the map is gone entirely (absorbed by we need typescript version #3); regression runs four fresh-loop startups and asserts no per-loop structures remain (not hasattr(plugin, "_setup_locks"), _setup_future is None).
  6. P2 cleanup iteration race — _loop_state_by_loop ownership changes are guarded by a threading.Lock; cleanup snapshots keys under the guard, evaluates is_closed() outside it, then claims each state atomically. Regression uses your repro shape: is_closed() inserting a new entry mid-scan — no RuntimeError, fold exactly once.
  7. P2 depth-cap flag — [MAX_DEPTH_EXCEEDED] now reports is_truncated=True (it discards real payload, unlike [CIRCULAR_REFERENCE]), with a row-level test (60-deep real mapping → row flag set). To keep Mock-like graphs from falsely tripping it, duck-typed conversions (model_dump/dict/to_dict) now require progress to an actual dict/list before recursing — non-progressing objects settle at the stringify fallback.
  8. P2 zero-delay retries — delays validated as finite and non-negative; the long-supported max_retries=0, initial_delay=0, max_delay=0 config constructs again (pinned).

PR body refreshed as requested: the removed "cheap hint check" description is replaced with the decode-first/fail-closed contract, and the coalescing claim now describes the cross-loop future (and is accurate again).

Verification at 100e17ed: 345 passed in this env (9 new round-4 regressions; expect 339 + 6 skipped in yours), mypy 0 new errors vs base, pyink/isort/git diff --check clean.

@caohy1988

Copy link
Copy Markdown
Author

Fresh review, round 5 (100e17ed)

Verdict: 4 P1s, 5 P2s. The round-4 fixes themselves hold, but the new cross-loop setup rendezvous is cancellation-unsafe and the wider lifecycle still has shutdown/public-close gaps. All P1 mechanisms below were reproduced against the exact PR head.

P1: shared setup cancellation poisons the rendezvous

At _ensure_started(), waiters directly await asyncio.wrap_future(setup_future), while the owner catches only Exception.

Two deterministic repros:

  1. Cancel the owner inside _lazy_setup. asyncio.CancelledError bypasses the handler, _setup_future remains pending, and every later _ensure_started() waits forever.
  2. Cancel one non-owner waiter. Cancellation propagates through wrap_future into the shared ConcurrentFuture; the owner then completes setup, sets _started=True, and raises InvalidStateError from set_result().

Recommended fix: shield each waiter wrapper so its cancellation cannot cancel the shared future. Handle owner cancellation explicitly: atomically clear/finalize the claimed rendezvous on every exit, wake unrelated waiters with an ordinary setup-aborted error, then re-raise cancellation in the owner. Guard publication against an already-completed future. Add exact owner-cancel and waiter-cancel regressions.

P1: shutdown can return and then be undone

shutdown() is not coordinated with setup or callbacks already inside _log_event().

Reproduced:

  • Block setup, call shutdown(), then release setup. _started becomes True after shutdown returned.
  • Insert a loop state while shutdown iterates the live dictionary. It raises RuntimeError: dictionary changed size during iteration, aborting state cleanup and counter folding.
  • A callback that passed the initial _is_shutting_down check can resume after parsing, create a new writer state, and append after shutdown.

Recommended fix: use a guarded lifecycle state/generation (STOPPED / STARTING / STARTED / STOPPING). Shutdown should invalidate the active generation, claim a stable loop-state snapshot under _loop_states_guard, and reject later state publication/appends with a shutdown_race loss count. Perform async draining outside the threading lock and make terminal cleanup cancellation-safe in finally.

P1: normal Runner.close() never reaches BQAA shutdown

Runner.close() calls PluginManager.close(), which calls plugin.close(). BQAA does not override BasePlugin.close(), so normal Runner ownership invokes the inherited no-op instead of shutdown().

Direct repro: set _started=True, await plugin.close(), and _started remains True. Queues, clients, executors, and the new shutdown accounting are bypassed.

Recommended fix: implement BigQueryAgentAnalyticsPlugin.close() using the cancellation-safe shutdown path and add a PluginManager/Runner-level regression. Note that PluginManager's default outer close timeout is 5 seconds while BQAA's default shutdown_timeout is 10 seconds; outer cancellation must still leave consistent state and counters.

P1: the mandatory sanitizer retains credential bypasses

At _recursive_smart_truncate(), converter and fallback results do not consistently re-enter the string/blob sanitizer.

Exact current-head leaks:

  • to_dict() returning UserDict({"access_token": "SECRET-MAPPING"})
  • b'{"access_token":"SECRET-BYTES"}' and the equivalent bytearray
  • \ufeff{"access_token":"SECRET-BOM"} with a leading BOM
  • An unsupported object's __str__() returning credential JSON

Recommended fix: accept all collections.abc.Mapping converter results, explicitly decode and inspect bytes/bytearray, recognize an optional leading BOM, and run fallback strings through the same JSON-blob/length path. If an object cannot produce a verified supported value, use a fixed unsupported-object sentinel instead of arbitrary str(). Add final-row regressions for each shape, including escaped sensitive keys.

P2: restart retains a GCS offloader bound to a dead executor

shutdown() terminates and clears _executor but retains parser and offloader. On restart, _lazy_setup() skips parser/offloader reconstruction, so the next GCS upload uses the shut-down executor and raises RuntimeError: cannot schedule new futures after shutdown.

Recommended fix: clear/rebuild parser and offloader during shutdown/restart, or atomically replace their executor. Add an enter/exit/re-enter GCS regression.

P2: closed-loop cleanup silently loses queued rows

_cleanup_stale_loop_states() folds only already-recorded processor counters. A closed-loop state with one queued row and zero counters was removed while the queue remained size one and every reported counter stayed zero; its writer client was not closed.

Recommended fix: before discarding a closed-loop state, drain and count non-sentinel queued rows under a stale_loop reason and release its client/resource state. Add a regression for a closed loop with queued data and zero prior drops.

P2: the synchronous sanitizer has no total work budget

Depth and per-string size are bounded, but collection width is not. The mapping/list walks at lines 636-664 run synchronously from _log_event. A one-million-scalar list took about 0.95 seconds in the walker alone and allocated another million-element list.

Recommended fix: carry a shared per-event node/entry budget through recursion, replace the remainder with a sentinel, and set is_truncated=True. Add a wide-payload regression that proves traversal stops at the budget.

P2: cross-loop regressions do not pin the dangerous cases

The success regression uses sleep(0.3) as coordination and does not assert joined threads terminated. The failure regression has no deterministic owner/waiter rendezvous and does not assert setup_calls == 1, so it can pass an implementation where both loops independently run and fail setup.

Recommended fix: replace sleeps with events/barriers, hold the owner until the waiter has entered, assert exactly one setup call and every thread terminated in success and failure cases, then add the cancellation and setup-vs-shutdown cases above.

P2: drop-stat semantics and documentation disagree

get_drop_stats() is documented as dropped-row counts, but formatter_failed increments while the row is still written with a sentinel. Monitoring that sums these counters therefore overstates missing rows.

Recommended fix: either document the API as loss incidents with per-reason semantics (formatter_failed means payload replaced, setup_unavailable means row dropped), or expose formatter replacement separately. Also document shutdown_timeout and correct the stale sanitizer/cancellation docstrings.

Answer to the open cold-start question

Recommendation: add an explicit, fail-fast process-wide preflight(). Do not use fire-and-forget asynchronous readiness as the default.

Preflight should resolve credentials and verify the BigQuery table/schema/views, Arrow schema, parser, and other process-wide resources. It should raise on failure so application startup and health checks fail visibly. It must not create BigQueryWriteAsyncClient or BatchProcessor, because those are event-loop-bound.

Why this choice:

  • on_user_message_callback runs before before_run_callback, so background readiness necessarily loses the first user/invocation rows.
  • Synchronous Runner.run() creates and destroys a fresh event loop per invocation, making background setup/writer ownership brittle.
  • Preflight gives production services bounded request latency without silently changing existing lazy-start behavior.

Keep the current synchronous lazy await as the backward-compatible fallback for callers that do not preflight. Pair preflight with a real close() -> shutdown() implementation. An optional bounded lazy-start timeout can be added later, but changing the default to async/drop-first-events would be a backward-compatibility and data-integrity regression.

Deferring this API addition to a separate PR remains reasonable. Keep #6356 open and continue using Refs #6356. The four P1s above, especially cancellation safety and lifecycle/close integration, should be fixed before this PR merges.

Verification

  • Complete BQAA module: 339 passed, 6 skipped in this environment.
  • mypy: zero new errors versus the pinned base (64 base, 61 head here).
  • pyink, isort, and git diff --check: clean.
  • Current GitHub checks show repository automation and CLA only, not a Python test job.
  • Independent structured and adversarial passes confirmed the setup-cancellation, lifecycle, sanitizer, and metrics-contract findings.

…ycle generation, close(), sanitizer shapes

All nine findings from the round-5 review at 100e17e:

- P1: the setup rendezvous is cancellation-safe. Waiters await
  asyncio.shield(wrap_future(...)) so their cancellation cannot cancel
  the shared future; a cancelled owner clears the rendezvous, fails
  waiters with an ordinary aborted error, and re-raises; publication is
  guarded by future.done(). Owner-cancel and waiter-cancel regressions.
- P1: lifecycle generation. shutdown() bumps _generation under
  _setup_guard and forces _started=False; an in-flight setup completing
  afterwards observes the stale generation, aborts (shutdown_race), and
  cannot resurrect the plugin. shutdown() iterates a guarded snapshot of
  loop states (concurrent publication raised 'dictionary changed size
  during iteration'); _get_loop_state and the append path reject work
  during shutdown with shutdown_race accounting.
- P1: BigQueryAgentAnalyticsPlugin.close() overrides the BasePlugin
  no-op and runs the full shutdown path, so Runner.close() ->
  PluginManager.close() actually releases queues/clients/executors.
- P1: sanitizer credential shapes — bytes/bytearray decode and re-enter
  the sanitizer; BOM-prefixed JSON is detected and parsed; Mapping
  results from model_dump/dict/to_dict are accepted; the unknown-object
  fallback re-enters the string sanitizer so __str__-returned credential
  JSON is redacted (repr truncation does not flip is_truncated).
- P2: shutdown clears parser/offloader so a restart rebuilds them
  instead of scheduling GCS uploads on the terminated executor.
- P2: stale-loop cleanup drains and counts queued rows (stale_loop
  reason) and best-effort releases the dead state's transport.
- P2: the sanitizer carries a total node budget (_MAX_SANITIZE_NODES);
  a million-scalar list now stops at the budget with a sentinel and
  is_truncated=True.
- P2: cross-loop regressions use event/barrier rendezvous, assert
  exactly one setup call in success AND failure modes, and assert thread
  termination.
- P2: get_drop_stats() documents loss-incident semantics per reason
  (formatter_failed = replaced-but-written; others = dropped).
@caohy1988

Copy link
Copy Markdown
Author

Pushed 70dee9b9 addressing all nine round-5 findings from the review:

  1. P1 rendezvous cancellation — waiters now asyncio.shield the wrapped future (waiter cancel can no longer cancel the shared future → no InvalidStateError on publish); a cancelled owner clears the rendezvous, fails waiters with an ordinary setup-aborted error, and re-raises; both publications are done()-guarded. Owner-cancel and waiter-cancel regressions included — the owner-cancel test also proves a later startup is not stuck.
  2. P1 shutdown vs in-flight setup — new lifecycle generation: shutdown() bumps _generation and forces _started=False under _setup_guard; a setup completing afterwards observes the stale generation, aborts with a shutdown_race count, and cannot resurrect the plugin (regression: gated setup released after shutdown → _started stays False). shutdown() iterates a guarded snapshot (no more "dictionary changed size"), and _get_loop_state/append reject post-shutdown work with shutdown_race accounting.
  3. P1 close() — BigQueryAgentAnalyticsPlugin.close() now overrides the inherited no-op and runs the full shutdown path, so Runner.close() → PluginManager.close() actually tears down queues/clients/executors. Regression asserts _started flips and counters stay queryable. (Noted re the 5s vs 10s timeout mismatch: shutdown's terminal cleanup is cancellation-tolerant and counters persist.)
  4. P1 sanitizer shapes — all four leaks closed and regression-tested in one payload: bytes/bytearray decode and re-enter the sanitizer, BOM-prefixed JSON is detected and parsed (stripped feeds json.loads), Mapping converter results are accepted, and the unknown-object fallback re-enters the string sanitizer so __str__-returned credential JSON is redacted (repr length-truncation deliberately does not flip is_truncated, matching prior str(obj) semantics).
  5. P2 restart executor — shutdown() clears parser/offloader; restart rebuilds them instead of scheduling GCS uploads on the terminated executor (tested).
  6. P2 stale-loop queued rows — cleanup drains and counts non-sentinel rows under a new stale_loop reason and best-effort releases the dead transport (tested with one queued row / zero prior counters).
  7. P2 work budget — _MAX_SANITIZE_NODES (100k) is carried through recursion; a 200k-scalar list stops at the budget with [SANITIZE_BUDGET_EXCEEDED] and is_truncated=True (tested).
  8. P2 test rigor — both cross-loop tests now use event rendezvous (owner held until entry observed), assert exactly one setup call in success and failure modes, and assert thread termination.
  9. P2 metrics contract — get_drop_stats() documents loss-incident semantics per reason (formatter_failed = written with sentinel; setup_unavailable/shutdown_race/shutdown_timeout/stale_loop = never written).

Cold-start answer: agreed on all points — explicit fail-fast preflight() (no loop-bound client/processor creation), lazy await kept as fallback, no async/drop-first-events default. Will do it as the follow-up PR under #6356 now that close() exists to pair with it.

Verification at 70dee9b9: 353 passed in this env (8 new round-5 regressions; expect 347 + 6 skipped in yours), mypy 0 new vs base, pyink/isort/git diff --check clean.

@caohy1988

Copy link
Copy Markdown
Author

Fresh review, round 6 (70dee9b9)

Verdict: FAIL. I treated every finding from rounds 1-5 as a denylist and reviewed the full diff again from base 9d306f5d to the unchanged final head. This pass found 4 P1s and 2 P2s that are still reproducible at the final commit.

1. [P1] PluginManager cancellation permanently wedges shutdown

shutdown() sets _is_shutting_down=True, then awaits cleanup inside a try that catches only Exception. asyncio.CancelledError is a BaseException, so PluginManager's outer timeout bypasses the handler and the final flag reset.

Deterministic repro: block the current loop's batch_processor.shutdown(), start plugin.close(), then cancel it as PluginManager does. The result was:

is_shutting_down=True
state_retained_before_retry=True
state_retained_after_retry=True

The second shutdown() returns immediately at line 3476, so cleanup can never be retried and later events are silently ignored. The new test cannot catch this because assert plugin._is_shutting_down is False or True is always true.

Put the lifecycle reset in a cancellation-safe finally, preserve and re-raise cancellation, and keep incomplete states retryable (or coalesce close callers on a shared shutdown future). Add a test that cancels a blocked close(), verifies the guard is released, then proves a second close removes the retained state.

2. [P1] A writer can still be published after shutdown returns

_get_loop_state() checks shutdown only before awaited credential/client/processor creation. Publication at lines 3051-3053 does not recheck _is_shutting_down or the lifecycle generation. Meanwhile, shutdown() takes an earlier snapshot and later clears only the shared dictionary.

I gated BatchProcessor.start(), completed shutdown() while its snapshot was empty, then released startup. The result was:

published_after_shutdown=True
transport_close_awaits=0

Because _is_shutting_down is false again when _get_loop_state() returns, the original event can also append to this post-close processor. Capture the lifecycle generation before construction, recheck generation and shutdown state under the publication guard, and close the newly built processor/client instead of publishing it when invalidated.

3. [P1] Scalar and quoted JSON still bypass the privacy boundary

Two final-head scalar paths preserve access_token values:

Both values can arrive through extra_attributes, custom tags, metadata, or state and are serialized by the mandatory final pass. Recursively inspect scalar converter results that make progress, and decode bounded JSON string layers so a decoded string that becomes a container re-enters the same redaction path. Keep the existing depth and node bounds and fail closed when a nested value cannot be inspected safely.

4. [P1] Concurrent table creation skips readiness verification

When the first get_table() returns NotFound and create_table() returns Conflict, setup immediately treats the table as usable. It never re-fetches the concurrently created table or runs schema compatibility/upgrade checks.

With a second get_table() response prepared as an incompatible table, the exact-head repro completed successfully with get_table_calls=1 and create_table_calls=1. The plugin can therefore mark itself started against a table missing required fields, after which writes fail without re-entering startup readiness. After Conflict, re-fetch and validate/upgrade the resulting table through the normal existing-table path; propagate verification failures so startup retries.

5. [P2] The 100k node budget still does O(input) work and allocation

After the budget returns a sentinel, the mapping and list loops keep iterating and appending. A 200,000-item list produced a 200,000-item output with 100,002 sentinel elements. A 200,000-entry temp: mapping produced all 200,000 entries with truncated=False, because direct redaction does not consume the budget.

The regression only asserts len(output) <= len(input), which permits unchanged full width. Consume budget per container entry, including direct-redaction entries, stop iteration when exhausted, and emit one remainder sentinel. Assert a bounded visit/output count rather than merely the presence of a sentinel.

6. [P2] Depth-truncated JSON blobs are reported as complete

_sanitize_json_blob() discards the recursive truncation flag, and the caller returns False for reserialized blobs unless length truncation also happens. A JSON string containing 60 nested arrays was rewritten with [MAX_DEPTH_EXCEEDED], but the function returned truncated=False. The BigQuery row therefore claims completeness after discarding payload content. Propagate the nested truncation bit through the blob-sanitizer result and add a JSON-encoded depth regression at the final row boundary.

Verification

  • Pinned commits rechecked immediately before posting: base 9d306f5d322eccbc5022ac72407fa8a994f64cf6, head 70dee9b918415fa48416f10d37ca5f80569dcf5b.
  • Full affected test file: 347 passed, 6 skipped. New hardening class alone: 41 passed. These failures are uncovered branches, not existing red tests.
  • pyink --check, isort --check-only, and git diff --check: clean.
  • Same mypy command: 45 errors on base, 42 on head, so zero new type errors in this diff.
  • Independent testing, maintainability, security, performance, red-team, Codex adversarial, and Codex structured passes converged on the lifecycle and work-budget failures.

The cold-start preflight deferral remains reasonable and is not part of this fail gate.

@caohy1988

Copy link
Copy Markdown
Author

Pushed b0b77c7f addressing all six round-6 findings from the review:

  1. P1 cancellation wedge — shutdown() now resets _is_shutting_down/_started in a finally, so a PluginManager timeout cancellation (a BaseException the except Exception never saw) can no longer leave the guard latched and turn every later close() into a silent no-op. The cancellation itself re-raises, and undrained loop states stay in _loop_state_by_loop so a second close re-snapshots and finishes cleanup. The always-true assert ... is False or True is replaced with a real assertion, and a new test cancels a close() blocked mid-drain, verifies the guard is released, then proves a second close removes the retained state.

  2. P1 post-shutdown publication — _get_loop_state() captures the lifecycle generation before any await and rechecks _is_shutting_down and the generation under _loop_states_guard at publication. If a shutdown() started (or completed — the flag is False again, but the generation moved) during construction, the fresh processor is shut down and its transport closed instead of being published, and the caller gets the same RuntimeError → shutdown_race drop accounting. Regression: gate BatchProcessor.start(), complete shutdown() on an empty snapshot, release startup — nothing is published, the new processor is closed, transport.close() is awaited.

  3. P1 scalar/quoted JSON bypass — _sanitize_json_blob() now decodes JSON-encoded string layers: a value starting with " is parsed and, when it decodes to a string, re-enters the sanitizer, so json.dumps(json.dumps({...})) (any nesting depth, bounded by the depth cap) reaches the container redaction path; changed layers are re-encoded. Over-limit quoted values whose escaped payload is container-shaped fail closed to [UNPARSEABLE_JSON_BLOB]; ordinary quoted prose is untouched. The model_dump()/dict()/to_dict() progress check now includes scalar results (str/bytes/tuple), so RootModel[str] dumps recurse through blob redaction instead of falling to str(obj)'s root='...' wrapper. Regressions cover double- and triple-encoded blobs, a real pydantic.RootModel[str], and quoted prose passing through unchanged.

  4. P1 Conflict readiness — after create_table() raises Conflict, setup re-fetches the concurrently created table and runs the same readiness path as a pre-existing table (_maybe_upgrade_schema under auto_schema_upgrade); any failure propagates so _ensure_started keeps _started=False and retries. The old test_create_table_conflict_is_ignored (which codified blind trust) is replaced by three tests: re-fetch happens (get_table called twice), an incompatible concurrent table goes through update_table, and a failing post-Conflict fetch propagates.

  5. P2 budget does O(input) work — the mapping and list loops now stop when the node budget is exhausted, emitting exactly one [SANITIZE_BUDGET_EXCEEDED] remainder sentinel, and directly-redacted entries (sensitive/temp: keys) consume budget too. The regression asserts a bounded output (<= budget + 1) with exactly one sentinel, and a new test proves a 2×-budget temp: mapping is bounded and flagged truncated — both shapes previously produced full-width output.

  6. P2 depth-truncated blobs claim completeness — _sanitize_json_blob returns (value, changed, truncated) and the nested truncation bit from the decoded container propagates through the string branch into the row's is_truncated. Regression: a JSON string of 60 nested arrays is rewritten with [MAX_DEPTH_EXCEEDED] and reports truncated=True.

Verification at b0b77c7f: full affected test file 354 passed, 6 skipped (up from 347 — the seven new regressions); pyink --check and isort --check-only clean on both changed files; mypy on the plugin file: 61 errors on prior head, 59 on this one (the Conflict re-fetch initially added one Optional[client] error; an assert at the top of _ensure_schema_exists removes it plus a pre-existing one), so zero new type errors.

@caohy1988

Copy link
Copy Markdown
Author

Fresh review, round 7 (b0b77c7f)

Verdict: FAIL. I treated every finding from rounds 1–6 as a denylist and reviewed the complete diff again from base 9d306f5d through the current fork tip b0b77c7f. Because the PR is closed, GitHub's PR object is frozen at 70dee9b9; the immutable links below therefore point to the reviewed fork commit. I found 6 P1s and 3 P2s that are independently reproducible at b0b77c7f.

1. [P1] Quoted JSON layers still fail open in two bounded-parser branches

The new quoted-string branch recognizes an over-limit encoded container only when the character immediately after the opening quote is a literal { or [. At three encoding layers that character is a backslash, so the original value is returned and the caller truncates it after the credential has already appeared. Separately, any json.loads() failure is classified as ordinary prose, even when the input has a valid quoted credential-JSON prefix followed by garbage.

Deterministic exact-head repros:

triple-encoded + padded + low max_len: secret_leaked=True, truncated=True
json.dumps(json.dumps({"access_token": secret})) + " trailing": secret_leaked=True, truncated=False

The new triple-encoding test uses a generous max_len, so it never enters the first branch. Fail closed for over-limit quoted JSON that cannot be safely classified, and use bounded prefix decoding (for example raw_decode) so a valid string layer that unwraps to a container cannot become “prose” merely because it has a suffix. Add both low-limit and trailing-garbage regressions.

2. [P1] Namedtuple normalization erases the sensitive field name before redaction

Tuple subclasses are deliberately converted to a plain list. That avoids the older constructor TypeError, but for a namedtuple it also discards _fields, so the sanitizer never sees access_token:

Cred = namedtuple("Cred", ["access_token"])
input:  {"named": Cred("ROUND7-NAMED-SECRET")}
output: {"named": ["ROUND7-NAMED-SECRET"]}, truncated=False

This shape survives in state_delta/other Any attribute values and is serialized to BigQuery. Detect namedtuples before the generic tuple branch and recurse through _asdict() so field-name redaction runs; add a row-boundary regression asserting the token is absent.

3. [P1] Non-native payload objects can still disclose secrets or suppress the audit row

There are three fail-open object-protocol paths in the mandatory privacy boundary:

At a fail-closed telemetry boundary, do not publish arbitrary object representations or invoke payload-controlled properties outside a guard. Normalize string subclasses to exact built-in strings, fetch each converter once with guarded getattr, recursively sanitize a safe structural representation such as vars(obj) where supported, and otherwise emit a sentinel. Add an end-to-end test that proves the row is still emitted and neither the row nor application logs contain the canary.

4. [P1] Cancelling a real BatchProcessor.shutdown() still makes every retry fail

The plugin-level finally correctly releases _is_shutting_down, but external cancellation while BatchProcessor.shutdown() awaits its worker cancels that worker. A second close awaits the already-cancelled task and raises the historical CancelledError again; queued rows and the loop state remain forever.

Exact-head repro with the real processor and a blocked writer:

first close=CancelledError
second close=CancelledError
worker_cancelled=True, state_retained=True, queue_size=3

The new regression hides this because it replaces the mocked processor's blocking shutdown() with a fresh no-op before retrying. Make BatchProcessor.shutdown() cancellation-aware: account/drain queued work when the worker is externally cancelled, preserve the caller's cancellation, and let a later call treat a cancelled worker as terminal rather than re-raise it. Exercise the real processor in the regression.

5. [P1] Setup can cross a completed shutdown by sampling the new generation too late

_ensure_started() records the old lifecycle generation, but _lazy_setup() does not pass it into _get_loop_state(). If setup is blocked creating the shared BigQuery client, shutdown() can finish and increment the generation; after release, _get_loop_state() captures that already-new generation, publishes the new writer, and returns. The outer owner later notices its stale generation, but only fails the rendezvous/counts shutdown_race; it does not roll back resources.

Gating real client construction until after shutdown() returned produced:

started=False, client_leaked=True, executor_leaked=True,
parser_leaked=True, loop_states=1, shutdown_race=1

Carry the owner's claimed generation through _lazy_setup() and _get_loop_state(), and tear down every resource created by an aborted setup attempt (not only the per-loop writer). Add a regression that blocks before _get_loop_state(), not inside BatchProcessor.start().

6. [P1] Concurrent shutdown callers are both admitted and tear down/fold the same states twice

The _is_shutting_down admission check occurs before _setup_guard and is not repeated inside it. Two loop threads can both observe False, increment the generation, snapshot the same state set, close the same processors/transports, and fold identical counters twice.

With two states reporting one queue_full loss each and a barrier after the unguarded check:

errors=[], generation=2, expected queue_full=2, actual queue_full=4

Make shutdown ownership an atomic in-lock transition or coalesce callers on one shared shutdown future, so exactly one caller snapshots, tears down, and folds a generation's resources. Add a two-thread/two-loop admission regression.

7. [P2] Plugin-level loss counters are not thread-safe and underreport incidents

_count_local_drop() is an unlocked dictionary read-modify-write; cleanup and shutdown perform the same unsynchronized folding, while get_drop_stats() copies/aggregates concurrently. The plugin explicitly supports event loops in different threads.

Four threads performing 50,000 increments each, with a short switch interval, repeatedly undercounted; one run reported 105175 instead of 200000. Protect all local-counter writes, folds, and snapshots with one dedicated threading.Lock, and add a deterministic interleaving or stress regression.

8. [P2] A non-JSON mapping key still drops the complete telemetry row

The final sanitizer preserves non-string mapping keys unchanged. Both serialization attempts then raise for a tuple key because default=str applies to values, not dictionary keys:

{"bad_key": {(1, 2): "value"}} -> TypeError:
keys must be str, int, float, bool or None, not tuple

The callback wrapper swallows the error, so the row disappears without drop accounting. Normalize/fail closed unsupported keys before insertion into new_dict (with an explicit collision policy), and add a final-row regression.

9. [P2] Discarding non-UTF-8 bytes does not mark the row truncated

On decode failure, the sanitizer replaces the complete byte payload with [BINARY_DATA] but returns False:

{"blob": b"\xff\xfe"} -> {"blob": "[BINARY_DATA]"}, truncated=False

That makes the BigQuery row claim completeness after content loss. Return True when bytes are discarded (or preserve them reversibly) and assert the row-level is_truncated value.

Verification

  • Fork ref rechecked immediately before posting: fix/bqaa-6356 = b0b77c7f71dc0d6bd65482ccaef8be691ff7eafa; base = 9d306f5d322eccbc5022ac72407fa8a994f64cf6.
  • Complete affected test file: 354 passed, 6 skipped. These findings are uncovered branches, not existing red tests.
  • pyink --check, isort --check-only, and git diff --check: clean.
  • Same focused mypy invocation under this review venv: 45 errors on base, 40 on head, so zero new type errors in the diff.
  • Independent testing, maintainability, security, performance, red-team, Codex adversarial, and Codex structured passes converged on the sanitizer, setup/shutdown, and accounting failures.

The deferred cold-start/preflight follow-up remains reasonable and is not part of this fail gate.

@caohy1988

Copy link
Copy Markdown
Author

Pushed dd7db733 addressing all nine round-7 findings from the review:

  1. P1 quoted-layer fail-opens — the over-limit quoted branch now classifies from the character after the opening quote (whitespace-tolerant): {, [, \, and " all fail closed, so triple-and-deeper encodings (whose next char is an escape, not a brace) can no longer reach the caller's raw truncation. For within-limit values, a ValueError from json.loads no longer means "prose": the leading string layer is bounded-decoded with json.JSONDecoder().raw_decode; if it unwraps toward a container and carries a non-whitespace suffix the value fails closed, otherwise the decoded layer re-enters the sanitizer and any redaction is re-encoded with the suffix preserved. Regressions cover the low-max_len triple-encoded repro, the + " trailing" repro, and quoted prose (with and without suffixes) passing through unchanged.

  2. P1 namedtuple field erasure — tuples exposing a well-formed _fields (validated: tuple of str, length-matched) are rebuilt as dict(zip(fields, obj)) — class metadata, not the overridable _asdict() — and recursed, so Cred(access_token=...) hits key redaction. The round-4 test that codified the plain-list shape is updated to the mapping contract, and the new row-boundary test asserts the token is absent from the written row.

  3. P1 object-protocol fail-opens — three closures: (a) the stringify fallback no longer publishes arbitrary repr/str output; known-safe stdlib scalars (datetime/date/timedelta, Decimal, UUID, PurePath, Enum, complex) keep their canonical string form, objects with public __dict__ state are structurally sanitized through the normal mapping path (so SimpleNamespace(access_token=...) gets redacted), and everything else fails closed to [UNSUPPORTED_OBJECT] with truncation reported. (b) model_dump/dict/to_dict are fetched exactly once via a guarded _safe_getattr — a property raising RuntimeError can no longer escape the sanitizer, so the row is emitted and the secret never reaches the logs. (c) str subclasses (values and mapping keys) are normalized with str.__str__ before any lstrip/startswith/lower inspection. The end-to-end regression logs all four canary shapes through _log_event and asserts the row is written and no canary appears in the row or in caplog.

  4. P1 cancelled processor shutdown unretryable — BatchProcessor.shutdown() is cancellation-aware: a worker task that is already done() is treated as terminal (its historical CancelledError is never re-awaited), with remaining queue contents drained into shutdown_cancelled/shutdown_timeout; external cancellation of a live wait_for drains and accounts queued rows as shutdown_cancelled and then re-raises, preserving the caller's cancellation. The regression uses the real processor with a blocked writer: first close cancels with rows queued, second close completes, queue empty, 3 rows in shutdown_cancelled + 1 in-flight in shutdown_timeout.

  5. P1 setup crossing a completed shutdown — _ensure_started now passes its claimed_generation through _lazy_setup into _get_loop_state, which fails immediately when the generation moved (before creating any writer). Both abort paths — the exception path and the stale-generation path after a successful setup — run a new _teardown_aborted_setup() that closes and removes the published loop state, transport, shared client, executor, and parser/offloader; the abort no longer records a poisoned backoff window. Regression blocks setup inside the shared bigquery.Client factory (before _get_loop_state), completes shutdown(), releases it, and asserts client is None, _executor is None, parser/offloader cleared, zero loop states, shutdown_race counted, and _startup_error is None.

  6. P1 concurrent shutdown double-fold — the _is_shutting_down admission check moved inside _setup_guard, making the claim atomic: exactly one caller per generation snapshots, tears down, and folds. Two-thread regression with a barrier and two states reporting one queue_full each asserts the folded total is exactly 2.

  7. P2 counter thread-safety — every _local_drop_counts read-modify-write (_count_local_drop, shutdown fold, stale-loop fold and stale_loop count) and the get_drop_stats snapshot now go through a dedicated threading.Lock, wired through __getstate__/__setstate__/_reset_runtime_state. Stress regression: 4 threads × 5,000 increments at a 10µs switch interval must total exactly 20,000.

  8. P2 non-JSON mapping keys — non-str keys that json.dumps cannot serialize (anything but int/float/bool/None) fail the KEY closed to numbered [UNSUPPORTED_KEY]/[UNSUPPORTED_KEY_N] sentinels (explicit collision policy: a genuine attribute with the sentinel name is overwritten — only ever payload-to-sentinel), keep the sanitized value, consume budget, and flag truncation. The key's repr is never published. Row-boundary regression asserts {(1, 2): "value"} reaches BigQuery as {"[UNSUPPORTED_KEY]": "value"} instead of vanishing.

  9. P2 binary discard not reported — the [BINARY_DATA] replacement returns truncated=True, and the row-boundary test asserts row-level is_truncated is set.

Verification at dd7db733: full affected test file 360 passed, 6 skipped (up from 354 — six new regressions plus the extended row-boundary test); pyink --check / isort --check-only clean; same focused mypy invocation: identical error set before/after (59/59 under this venv's mypy), so zero new type errors.

@caohy1988

Copy link
Copy Markdown
Author

Fresh review, round 8 (dd7db733)

Verdict: FAIL. I treated every finding from rounds 1–7 as a denylist and reviewed the complete diff again from base 9d306f5d through the current fork tip dd7db733. Because the PR is closed, GitHub's PR object is frozen at 70dee9b9; the immutable links below therefore point to the reviewed fork commit. I found 6 P1s and 8 P2s that are independently reproducible at dd7db733.

1. [P1] Inconsistent JSON-prefix normalization still leaks credentials

_sanitize_json_blob() recognizes only BOM plus ASCII whitespace at its outer boundary, and the new over-limit quoted-layer classifier omits BOM as well. That leaves two exact-head bypasses:

json.dumps("\u00a0" + json.dumps({"access_token": secret}))
  -> secret_leaked=True, truncated=False

json.dumps("\ufeff" + padded_credential_json, ensure_ascii=False), max_len=120
  -> secret_leaked=True, truncated=True

U+2003 behaves like NBSP. Normalize the same bounded set of BOM/Unicode-whitespace prefixes after every decoded string layer and before every container-shape check, or fail closed for every over-limit quoted value. Add quoted-layer regressions for BOM, NBSP, and EM SPACE at both under-limit and over-limit sizes.

2. [P1] A harmless decoded prefix can smuggle credential JSON in the suffix

When json.loads() reports extra data, the new raw_decode fallback preserves the suffix, but it fails closed only when the decoded leading string points toward a container. If the leading string is prose, an arbitrary credential object in the suffix is returned unchanged:

{"blob": '"note" {"access_token":"ROUND8-SUFFIX-SECRET"}'}
  -> unchanged, truncated=False

{"blob": '"note" blah {"refresh_token":"ROUND8-SUFFIX-SECRET-2"}'}
  -> unchanged, truncated=False

Once a quoted value required raw_decode, do not append an unverified non-whitespace suffix back to the published value. Fail closed, or parse and sanitize a deliberately supported multi-document grammar with bounded work. Add both prose-prefix suffix-smuggling regressions.

3. [P1] The trusted-scalar allowlist still invokes payload-controlled __str__

_SAFE_STR_TYPES includes base classes such as enum.Enum and PurePath, then uses isinstance() followed by polymorphic str(obj). A normal application enum can therefore reopen the arbitrary-string leak that round 7 intended to close:

class Credential(Enum):
  access_token = "ROUND8-ENUM-SECRET"
  def __str__(self): return self.value

{"credential": Credential.access_token}
  -> {"credential": "ROUND8-ENUM-SECRET"}, truncated=False

Require exact safe scalar types and use non-overridable base conversions where available; handle Enum structurally or fail subclasses closed. Add a final-row test proving the canary is absent.

4. [P1] Hostile container protocols still escape the mandatory privacy boundary

Mapping traversal calls payload-controlled items() without a guard; sequence iteration and dataclass field access have the same gap. A valid collections.abc.Mapping whose items() raises RuntimeError("ROUND8-MAPPING-SECRET") propagates out of the sanitizer. The real _safe_callback then logs the exception and traceback and drops the complete audit row.

Put a fail-closed exception boundary around mapping/sequence/dataclass traversal. On protocol failure, retain the row with an unsupported sentinel and is_truncated=True, without logging a payload-controlled exception message. Test the real callback boundary and assert the canary is absent from both the row and captured logs.

5. [P1] An aborted setup teardown can destroy a successful restart

When an owner loses the generation race, _ensure_started() clears _setup_future before awaiting teardown. A new-generation setup can therefore claim the now-free rendezvous and finish while the old owner is paused. The old _teardown_aborted_setup() then pops the current loop state and unconditionally clears/closes the plugin's current parser, client, and executor, regardless of which generation created them.

A deterministic two-loop interleaving left:

started=True, client=None, parser=None, loop_states=0,
new_client_closed=True

Subsequent events permanently skip because _ensure_started() fast-returns on _started=True. Keep the setup rendezvous owned until aborted-generation cleanup completes, and make teardown close only attempt-owned/generation-tagged resources. Add a gated old-setup/shutdown/new-setup regression.

6. [P1] Normal Runner close blocks the event loop and defeats PluginManager's timeout

The newly wired close() -> shutdown() path reaches future.result(timeout=t) inside an async coroutine. That synchronous wait blocks the current event loop, so PluginManager's outer asyncio.timeout(5) cannot cancel the plugin while another loop is slow or stopped; the delay is also paid serially per remote loop.

With a non-running remote loop, an outer 50 ms asyncio.timeout() around shutdown(timeout=0.25) returned normally only after 252 ms, not with TimeoutError. Await wrapped cross-loop futures asynchronously under one global deadline, cancel unfinished remote futures, and do not clear/close state that still has a pending remote shutdown. Add a real two-loop test asserting the host timeout remains effective.

7. [P2] Loop-state ownership and counter folding are not one atomic transition

shutdown() snapshots states but leaves them live until after it folds their counters. Two observable races result:

Atomically claim/remove each state before folding it, with one consistent lock order and explicit retry ownership for cancellation. Test reads during folding and cleanup racing shutdown.

8. [P2] Generic-object sanitization does unbounded work before charging the node budget

The round-7 fallback materializes every public __dict__ entry into a new dict before re-entering the budgeted traversal. Plain objects are also not marked seen, so obj.self = obj repeats the full copy until the depth cap.

On the exact head, a one-million-attribute object took 2.53 s / 44 MiB peak versus 0.88 s / 5.5 MiB for the equivalent dict; a leading self-reference plus 100k attributes peaked near 97 MiB. Traverse instance attributes directly through a budget-checked loop, count filtered entries too, and mark the source object seen so self-references terminate immediately. Add a tiny-budget counting-map regression.

9. [P2] One setup/shutdown race records two lost rows for one event

Both aborted-generation paths increment shutdown_race inside _ensure_started(), even though _ensure_started() is also used by non-row calls. The waiting _log_event() then sees _started=False and increments setup_unavailable.

One gated event produced {"shutdown_race": 1, "setup_unavailable": 1}; a direct startup call produced a phantom shutdown_race despite no row existing. Return a structured setup outcome and let the row owner count exactly one loss. Add both event and direct-start regressions.

10. [P2] Scalar mapping keys can collapse into duplicate JSON members

The new key policy preserves int/float/bool/None keys alongside string keys, but JSON stringifies all object keys. For example:

sanitized: {1: "numeric", "1": "string"}, truncated=False
serialized: {"1": "numeric", "1": "string"}
parsed downstream: {"1": "string"}

This silently loses one value. Normalize keys before insertion and apply a deterministic fail-closed collision policy, with regressions for 1/"1", True/"true", and None/"null".

11. [P2] Safe-scalar truncation drops the truncation flag

The trusted-scalar branch discards the recursive return flag and always reports False. An exact built-in-safe value already demonstrates the bug:

_recursive_smart_truncate(PurePath("x" * 40), 8)
  -> ("xxxxxxxx...[TRUNCATED]", False)

Propagate the nested flag and assert the final BigQuery row has is_truncated=True.

12. [P2] External cancellation performs an unbounded synchronous queue drain

_drain_queue_and_count() dequeues every remaining row without an await, and the new cancellation handler runs it before re-raising CancelledError. queue_max_size has no upper bound, and asyncio.timeout() waits for cancellation cleanup, so this extends host-close latency and blocks unrelated tasks after the deadline. Exact-head timings scale linearly: 100k = 20 ms, 1m = 208 ms, 5m = 1.03 s.

Maintain queued-row accounting incrementally so cancellation can fold the remaining loss in O(1), or release/drain storage outside the cancellation-critical event-loop path. Add a counting-queue test that requires bounded operations before cancellation surfaces.

13. [P2] Unlimited mode materializes arbitrary JSON before the node budget applies

The size gate is disabled when max_content_length=-1, after which json.loads() materializes the complete blob before _MAX_SANITIZE_NODES is consulted. A multi-million-element encoded array therefore consumes unbounded event-loop time and memory even though the recursive output is capped at 100k nodes.

Keep a separate hard inspection-byte ceiling even when emitted content is configured as unlimited; beyond it, fail closed or parse off-loop with a streaming/bounded parser. Add an unlimited-mode regression that asserts parsing work and peak materialization stay bounded.

14. [P2] Cancelling executor-backed setup can orphan the eventual client and executor

_lazy_setup() assigns the BigQuery client only after awaiting its executor future. Cancelling the owner does not stop the underlying thread; when the constructor later returns, its client result is discarded because the assignment never runs. The cancellation branch only resets the rendezvous, and shutdown tears down the executor only when self.client is truthy. The constructed client is never closed and the executor survives close.

Retain/shield the construction future so cancellation cleanup can close an eventual result, invoke partial-resource teardown from the cancellation path, and shut down _executor independently of self.client. Add a blocked-constructor/cancel/release/close regression that asserts both resources terminate.

Verification

  • Fork ref rechecked: fix/bqaa-6356 = dd7db733c9fd953813ff0863719ab21a76694837; base = 9d306f5d322eccbc5022ac72407fa8a994f64cf6.
  • Complete affected test file: 360 passed, 6 skipped. These failures are uncovered branches, not existing red tests.
  • pyink --check, isort --check-only, and git diff --check: clean.
  • The focused mypy logical error set is unchanged from b0b77c7f to dd7db733; no new type errors were introduced by round 7.
  • The isolated concurrent-shutdown regression emits two unawaited-AsyncMock warnings because fake loops never schedule the created coroutines; that test should use real loops, mark the fakes closed, or explicitly close the coroutines.
  • Independent testing, maintainability, security, performance, red-team, Codex adversarial, and Codex structured passes converged on the privacy, lifecycle, shutdown, and bounded-work failures.

@caohy1988

Copy link
Copy Markdown
Author

Pushed 6a51237f addressing all fourteen round-8 findings from the review:

  1. P1 Unicode/BOM prefix bypasses — a new _strip_bom_ws() (default str.lstrip for every Unicode whitespace, plus U+FEFF, iterated to a fixed point) normalizes before EVERY shape check: the sanitizer entry, the over-limit quoted-layer classifier, and (via the entry) each recursively decoded layer. Both repros — json.dumps(" " + credential_json) and the over-limit raw-BOM quoted value — now fail closed/redact. Regressions cover NBSP, EM SPACE, and BOM at under- and over-limit sizes.

  2. P1 suffix smuggling — once raw_decode was needed, a suffix containing a literal { or [ fails the whole value closed. The scan is sound precisely here (unlike inside JSON documents): the suffix is published verbatim with no later decode step that escapes could exploit. Container-free suffixes remain quoted prose ('"hello" she said' unchanged); a redactable prefix with a clean suffix is redacted in place with the suffix preserved. Both prose-prefix repros regress; the round-7 trailing-garbage test is updated to the refined contract (in-place redaction, not wholesale discard).

  3. P1 safe-scalar __str__ — stringification goes through _base_str(safe_base, obj), an explicit base-class __str__ call that no subclass override can intercept: the Credential(Enum) repro now serializes as "Credential.access_token" (member name, never the value), and a PurePath subclass yields the real path. This also fixes P2-11: the recursive truncation flag propagates, so PurePath("x"*40) at max_len=8 reports truncated=True.

  4. P1 hostile container protocols — the entire sanitizer dispatch now has a fail-closed except Exception boundary: a Mapping whose items() raises, a list subclass whose iteration raises, or raising field access becomes [UNSUPPORTED_OBJECT] with truncated=True, without logging the payload-controlled message. A real-callback regression drives _log_event with a raising items() canary and asserts the row is written and the canary appears in neither the row nor caplog.

  5. P1 aborted teardown destroying a restart — both abort paths keep the setup rendezvous (_setup_future) claimed until _teardown_aborted_setup() completes (cleared in a finally, then the aborted future resolves), so no new-generation setup can start — let alone publish resources for the old owner's teardown to destroy. Teardown also gained a _started guard as a second line of defense. The regression spies on teardown to assert the rendezvous was held throughout, then proves a fresh _ensure_started() fully restarts ("ok", _started=True, live client).

  6. P1 blocking cross-loop drain — remote processors are drained by awaiting asyncio.wrap_future(...) under one shared asyncio.wait(timeout=t) deadline instead of future.result(timeout=t) blocking the event loop; unfinished drains are cancelled and their states retained for a retried close. Regression: a never-running remote loop plus asyncio.wait_for(shutdown(timeout=5), 0.1) raises TimeoutError in well under 2s (previously the host timeout was dead until the full serial wait elapsed) and the undrained state stays claimable.

  7. P2 non-atomic claim/fold — each drained state is claimed out of the live dict and folded in one transition under _loop_states_guard + _drop_counts_guard (canonical order), in shutdown(), stale-loop cleanup, and get_drop_stats() (which now reads both under the same guards). Regression samples get_drop_stats() continuously while a gated shutdown folds a queue_full=2 state: the total reads exactly 2 before, during, and after.

  8. P2 unbounded __dict__ work — objects traversed via __dict__ are cycle-marked (obj.self = obj terminates as [CIRCULAR_REFERENCE] immediately), and attribute collection charges the node budget per entry — filtered/private entries included — stopping at exhaustion with a remainder sentinel. The million-attribute repro drops from ~2.5s/44MiB to ~0.02s bounded. Tiny-budget regression: 200 attributes at budget 50 yields ≤51 entries, truncated.

  9. P2 double loss counting — _ensure_started() returns a structured outcome ("ok"/"disabled"/"failed"/"aborted", with _SetupAbortedError distinguishing aborts for waiters) and never counts losses itself. The row owner in _log_event records exactly one loss: shutdown_race for aborts, setup_unavailable otherwise. Regressions: one raced event → {shutdown_race: 1, setup_unavailable: 0}; direct starts → zero phantom counts (the two older tests asserting the phantom are updated to the new contract).

  10. P2 scalar key collapse — int/float/bool/None keys normalize to their exact JSON form ("1", "true", "null", json.dumps(k) for numbers) before insertion; a collision keeps the first writer's key and stores the collider's sanitized value under [KEY_COLLISION_n]<key> with truncated=True. Regressions round-trip 1/"1", True/"true", None/"null" through json.dumps/loads and assert both values survive.

  11. P2 safe-scalar truncation flag — folded into fix 3.

  12. P2 unbounded cancellation drain — BatchProcessor tracks outstanding shutdown sentinels; external cancellation accounts remaining rows in O(1) (qsize() - sentinels) as shutdown_cancelled and swaps in a fresh queue (storage reclaimed off the cancellation-critical path) before re-raising. The counting-queue regression asserts zero per-item get_nowait calls during cancellation while all 3 queued rows are counted.

  13. P2 unlimited-mode materialization — a hard _MAX_JSON_INSPECT_CHARS = 4_000_000 ceiling applies to json.loads in both the container and quoted branches even when max_content_length=-1; over-ceiling container-shaped blobs fail closed. Regression: an over-ceiling encoded array in unlimited mode returns the sentinel with truncated=True.

  14. P2 orphaned client/executor on cancellation — client construction uses executor.submit + asyncio.wrap_future; on cancellation a done-callback (running in the worker thread, immune to loop teardown) closes the eventual client, and the cancellation branch releases the executor/parser/offloader. shutdown() now releases the executor independently of self.client, non-blocking (shutdown(wait=False, cancel_futures=True)) so a blocked constructor can no longer stall close. Regression: blocked-constructor/cancel/release/close proves the eventual client is closed and the executor terminated.

Also per the verification note: the concurrent-shutdown regression now uses closed fake loops, so no unawaited-AsyncMock coroutine warnings are emitted.

Verification at 6a51237f: full affected test file 375 passed, 6 skipped (up from 360 — fourteen new regressions plus updated contracts); pyink --check / isort --check-only / git diff --check clean; focused mypy: 59 errors on dd7db733, 58 here — one pre-existing run_in_executor arg-type error disappeared with the executor.submit rewrite, and no new error of any class was introduced.

@caohy1988

Copy link
Copy Markdown
Author

Fresh review round 9 — 6a51237f

I reviewed the complete 9d306f5d...6a51237f diff and then the focused dd7db733...6a51237f delta. I treated every round-1 through round-8 item as a denylist and only included distinct failing paths below. This pass was performed solo, without subagents.

I found 11 new issues: 7 P1, 4 P2.

1. [P1] A formatter can still fail open through its return value

The fail-closed try only surrounds the formatter invocation. content_formatter is typed to return Any, and a non-native result later reaches the parser's unconditional str(content) fallback, outside that privacy guard. A result whose __str__ returns a canary produced:

formatter_object ROUND9-FORMATTER-SECRET False

If __str__ raises RuntimeError("...SECRET"), the exception escapes to _safe_callback, which logs the traceback, reopening the log leak that the formatter catch was designed to close. Validate/normalize formatter results inside the same fail-closed boundary; unsupported shapes should become the formatter sentinel and only the exception class should be logged. Add regressions for both a secret-returning object and a raising __str__.

2. [P1] str/bytes-backed Enums bypass the new safe Enum conversion

enum.Enum is in the safe-base allowlist, but scalar dispatch happens first: a StrEnum or class Credential(str, Enum) enters the str branch and is normalized with str.__str__, which returns its underlying value. The safe Enum.__str__ path at L1038-L1045 is never reached:

class Credential(str, Enum): access_token = "ROUND9-STR-ENUM-SECRET"
-> {"credential": "ROUND9-STR-ENUM-SECRET"}, truncated=False

Handle enum.Enum before primitive/mixin branches and stringify through enum.Enum.__str__. Cover StrEnum, str + Enum, and bytes-backed Enum variants.

3. [P1] The Unicode/BOM normalizer is quadratic on an allowed prefix

_strip_bom_ws() repeatedly allocates and rescans the remaining suffix. An alternating prefix (" \ufeff" * n) removes only one whitespace/BOM pair per iteration. Exact-head timings show the expected ~4x increase per doubling:

n=8,000   0.0056s
n=16,000  0.0244s
n=32,000  0.1028s

This runs synchronously on the callback path, with a 512 KiB default content limit and a 4M-character inspection ceiling, so a legal attribute can pin the event loop for seconds or worse before any size decision. Replace the fixed-point slicing loop with one index scan using char.isspace() or char == "\ufeff", then slice once. Add an alternating-prefix complexity regression.

4. [P1] Failed/cancelled remote drains are treated as successful

After asyncio.wait, every non-pending wrapper is appended to drained; the code never calls f.result() or checks f.cancelled(). A remote shutdown() raising RuntimeError therefore emitted Future exception was never retrieved, yet its state was removed and folded as if the drain succeeded:

remote_failure state_retained=False stats={'queue_full': 1}

Any queued rows that the failed drain did not account are now unretryable. Retrieve every done result; only a clean completion should enter drained. Cancelled/failed futures must log without payload, retain the state, and be retried. Add real remote-loop regressions for exception and cancellation.

5. [P1] A concurrent shutdown() caller returns before shutdown completes

The atomic admission guard returns immediately when another close owns the generation. With the first caller blocked in its current-loop processor, the second awaited shutdown() returned in ~2 microseconds while the first task was unfinished and the loop state was still live:

second_elapsed=0.000002s first_done=False state_live=True

This makes await plugin.close() lie to any concurrent owner and is especially dangerous if the original owner is later cancelled. Coalesce shutdown callers on a shared, shielded completion future (parallel to setup), so non-owners await the active teardown rather than returning.

6. [P1] shutdown() silently loses rows owned by an already-closed loop

Closed loops are marked drained without invoking stale-loop accounting, then their states are removed after folding only existing processor counters. The comment's claim that rows were already counted by stale cleanup is not guaranteed: a closed state can be present in the shutdown snapshot before _cleanup_stale_loop_states() ever runs. With one queued row:

after shutdown: stats={} states=0 abandoned_queue_size=1

Claim closed states through the same stale-loss path, counting qsize - sentinels before removal. Add a shutdown() regression with a closed loop and queued rows.

7. [P1] The cancelled-constructor callback can still block the event loop

The new cancellation path assumes ConcurrentFuture.add_done_callback will run _close_eventual in the worker. That is only true while the future is pending; if construction completed just before cancellation but its wrapped asyncio result has not been delivered, add_done_callback invokes the callback immediately in the caller's thread. A deterministic completed-future race with client.close() sleeping 200 ms showed:

cancel await=0.203s close_thread=event_loop_thread

So the host close timeout can again be extended by synchronous cleanup. Ensure client.close() is always dispatched off-loop even when the concurrent future is already done. Add the completed-before-cancel interleaving to the existing blocked-constructor test.

8. [P2] A stopped-but-open remote loop leaks the created shutdown coroutine

run_coroutine_threadsafe(state.batch_processor.shutdown(...), other_loop) creates the coroutine before its callback can run. If the loop is stopped, the host timeout cancels the wrapper and a later loop.close() discards the queued callback while still holding the never-awaited coroutine. The complete affected suite consistently reports:

RuntimeWarning: coroutine 'BatchProcessor.shutdown' was never awaited

from the new never-running-loop regression. Schedule coroutine creation inside the remote-loop callback, or retain and explicitly close it when the callback can no longer execute. Make the test warning-clean under PytestUnraisableExceptionWarning.

9. [P2] Collision-marker keys can overwrite real user keys

On a normalized-key collision, the code constructs one [KEY_COLLISION_n]... key but never rechecks whether that generated key already exists. A legitimate key in that namespace is silently overwritten:

input:  {"[KEY_COLLISION_1]1": "reserved", "1": "string", 1: "numeric"}
output: {"[KEY_COLLISION_1]1": "numeric", "1": "string"}

The output is marked truncated, but the stated contract was to preserve both values explicitly. Allocate markers in a loop until the key is unique, or use a reserved collision envelope that cannot alias user keys. Test pre-existing marker keys and repeated collisions.

10. [P2] Closed-loop cleanup still performs unbounded synchronous queue work

_cleanup_stale_loop_states() dequeues every remaining row synchronously, and queue_max_size has no upper bound. This method runs on the callback event loop from _get_loop_state(). A counting queue measured 100,001 / 500,001 / 1,000,001 get_nowait() calls and 13 / 64 / 126 ms respectively before the callback could proceed. Reuse the O(1) qsize - sentinel_count accounting introduced for cancellation and discard the dead queue without per-item draining. Add a counting-queue regression requiring bounded operations.

11. [P2] Normal shutdown discards the shared BigQuery client without closing it

Normal teardown shuts down the executor and then sets self.client = None, but never calls the synchronous BigQuery client's close(). The aborted-setup path correctly closes the same resource off-loop, so normal close is now the leaking path. A live mock client produced client.close.call_count == 0 after await plugin.shutdown(). Detach the client, close it off-loop under the shutdown budget, then release the executor/reference; add a normal-close assertion alongside the write-transport test.

Verification

  • Fork ref rechecked for review scope: fix/bqaa-6356 = 6a51237f93291a584bc2a576ff42c40d98ea5d06; original PR base = 9d306f5d322eccbc5022ac72407fa8a994f64cf6.
  • Complete affected test file: 375 passed, 6 skipped in 20.71s. It is functionally green, but emits the unawaited-BatchProcessor.shutdown warning described in finding 8.
  • pyink --check, isort --check-only, and git diff --check: clean.
  • Focused mypy count improved from 59 errors at dd7db733 to 58 at 6a51237f, matching the reported baseline; no new type-error count regression.
  • No Greptile comments exist on this PR. Production source was not modified during this report-only review.

@caohy1988

Copy link
Copy Markdown
Author

Pushed 086569c7 addressing all eleven round-9 findings from the review:

  1. P1 formatter return-value fail-open — formatter results are validated inside the same fail-closed try: str results are normalized to the exact built-in (str.__str__), types.Content/None pass through, and anything else becomes _FORMATTER_FAILED_SENTINEL with a formatter_failed count — logging only the result's type. A secret-returning __str__ never reaches the parser's str() fallback, and a raising __str__ never reaches _safe_callback's traceback log. The regression drives both shapes through _log_event and asserts the row carries the sentinel, both canaries are absent from row and caplog, and formatter_failed == 2.

  2. P1 value-backed Enums — enum.Enum now dispatches FIRST, before the scalar branches, through the non-overridable Enum.__str__: class Credential(str, Enum) serializes as "Credential.access_token", never the value. Regressions cover (str, Enum), bytes-backed members, and native StrEnum (3.11+). The dead enum.Enum entry in _SAFE_STR_TYPES is replaced with a pointer comment.

  3. P1 quadratic normalizer — _strip_bom_ws() is one linear index scan (char.isspace() or char == "", then a single slice). The alternating-prefix regression strips a 400k-character " " prefix (25ms measured vs. minutes quadratic) under a generous CI bound.

  4. P1 failed remote drains claimed as success — every done wrapper's result is retrieved: cancelled or raising drains log the exception class only and RETAIN the state for a retried close; only clean completions enter drained and get claimed/folded. Regression runs a real remote loop in a thread with a RuntimeError-raising drain and asserts the state is retained, its live counters stay visible, and the payload-controlled message stays out of the logs.

  5. P1 concurrent shutdown returns early — non-owning shutdown() callers now coalesce on a shared _shutdown_future (shielded, parallel to the setup rendezvous), resolved in the cancellation-safe finally and wired through pickling/fork-reset. Regression: with the owner gated mid-drain, a second shutdown() task is still pending 100ms in, and completes only after the owner finishes.

  6. P1 closed-loop rows silently lost in shutdown — closed-loop states in the shutdown snapshot now account qsize - sentinels as stale_loop (O(1)) before being claimed, closing the "snapshot before stale-cleanup ever ran" window. Regression: a closed loop with one queued row on a real processor yields stale_loop == 1 and the state removed.

  7. P1 done-callback runs synchronously — _close_eventual dispatches the orphan client's close() to a fresh daemon thread, so even when add_done_callback fires inline (future completed just before cancellation) the event loop is not blocked. The deterministic completed-before-cancel regression (via a patched wrap_future that waits for construction then delivers cancellation) shows a 200ms close() running on a non-loop thread while the cancellation await returns in <150ms.

  8. P2 leaked remote-shutdown coroutine — the eagerly created coroutine is explicitly closed on every path where its loop callback can no longer run: scheduling failure, a successfully cancelled concurrent future after the drain deadline, and host cancellation mid-asyncio.wait (a new except CancelledError handler releases all remote handles before re-raising). The full suite is now free of coroutine ... was never awaited warnings, and the never-running-loop regression runs under filterwarnings("error::RuntimeWarning") + error::pytest.PytestUnraisableExceptionWarning.

  9. P2 collision-marker overwrite — markers re-allocate ([KEY_COLLISION_n] with incrementing n) until the generated key is unique. Regression: {"[KEY_COLLISION_1]1": "reserved", "1": "string", 1: "numeric"} preserves all three values with the reserved key untouched.

  10. P2 unbounded stale-queue drain — _cleanup_stale_loop_states() uses the same O(1) qsize - sentinel_count accounting as cancellation and drops the dead queue with the state. Counting-queue regression: 1,000 queued rows are accounted with zero get_nowait() calls.

  11. P2 shared client leak on normal close — shutdown() detaches self.client and closes it off-loop (run_in_executor) bounded by the shutdown budget. Regression asserts client.close() was called and the reference cleared.

Verification at 086569c7: full affected test file 384 passed, 6 skipped (up from 375 — eleven new/extended regressions), with zero never-awaited warnings; pyink --check / isort --check-only / git diff --check clean; focused mypy: byte-identical 58-error set before and after, so no new type errors.

@caohy1988

Copy link
Copy Markdown
Author

Fresh review round 10 — 086569c7

I reviewed the complete 9d306f5d...086569c7 diff independently, then inspected the focused round-9 delta and converted suspected edge cases into deterministic repros. The eleven reported round-9 regressions are covered and pass, but I found 7 distinct remaining issues: 4 P1, 3 P2.

1. [P1] An unterminated encoded JSON string still fails open

When a quoted JSON layer cannot be decoded, _sanitize_json_blob() classifies it as prose and returns it unchanged. That is unsafe when the quoted layer visibly begins an encoded container but is merely missing its final quote.

This value:

'"{\\"access_token\\":\\"R10-SECRET\\"}'

survives the mandatory final attributes pass unchanged:

{"state_delta": {"cache": "\"{\\\"access_token\\\":\\\"R10-SECRET\\\"}"}}
truncated=False

The direct {/[ path already fails closed for malformed/trailing JSON; malformed quoted container layers need the same treatment. A raw_decode() failure should return the sentinel when the post-quote prefix can represent an encoded container, rather than assuming quoted prose.

2. [P1] Formatter validation rejects previously supported native parser shapes

The new result gate accepts only str, types.Content, or None, but content_formatter remains typed Callable[[Any, str], Any], and the parser explicitly supports LlmRequest, types.Part, dict, and list.

Consequently, a normal identity/conditional formatter now destroys content for events it does not transform:

content_formatter=lambda content, event_type: content
raw_content={"response": "safe"}

produces:

parser_received=[FORMATTER_FAILED]
formatter_failed=1

LLM_REQUEST is affected particularly directly because its raw value is an LlmRequest. Preserve the parser's known-safe native shapes (at least dict/list, LlmRequest, and types.Part) while rejecting only values that would reach the arbitrary str(content) fallback, or explicitly narrow and document the formatter contract as a breaking change.

3. [P1] A coalesced shutdown caller falsely succeeds after owner cancellation

Non-owner callers correctly wait on _shutdown_future, but the owner unconditionally resolves that future successfully from finally, including when teardown was cancelled.

A deterministic owner-cancel interleaving produced:

waiter_returned=True
state_still_live=True
shutdown_flag=False

The uncancelled waiter therefore returns from await plugin.close() while the processor remains live. The shared completion needs to distinguish successful teardown from abort/cancellation; an uncancelled waiter should retry ownership or receive an incomplete-shutdown error, not return success.

4. [P1] Remote coroutine cleanup closes a coroutine after ownership was transferred

Both remote cancellation paths assume that ConcurrentFuture.cancel() returning true means the remote callback never ran, then call coro.close() from the caller thread: host cancellation and drain timeout.

That premise is false: the concurrent future can still be cancellable after the remote task has started. Two deterministic outcomes:

# Suspended remote coroutine
cancel_returned=True
cleanup_on_caller_thread=True

# Currently executing remote coroutine
cancel_returned=True cr_running=True
close_error=ValueError coroutine already executing

The latter can replace host cancellation or abort the remaining shutdown cleanup; the former runs coroutine finalization on the wrong event-loop thread. Create the coroutine inside the remote-loop callback so no coroutine exists if the callback never runs, or use an explicit ownership handoff. Once run_coroutine_threadsafe() succeeds, caller-side code must not directly close its coroutine.

5. [P2] Stale-loop rows can be double-counted by concurrent cleanup and shutdown

Stale cleanup claims the state under the guards but counts its queue afterwards. Meanwhile, shutdown may hold an earlier snapshot and count the same queue independently, even though cleanup already removed the live state.

A deterministic one-row interleaving produced:

1 queued row(s) lost with closed loop ...
1 queued row(s) lost with closed loop ...
stale_loop_count=2

Queue-loss accounting must belong to the same single-winner claim as state removal/folding. Shutdown should only count a snapshotted state if it still owns that exact live state.

6. [P2] Normal shutdown still leaks the GCS storage client

Setup creates a plugin-owned storage.Client, but normal shutdown drops offloader and parser without calling offloader.client.close().

The direct shutdown repro produced:

storage_client_close_calls=0
offloader_released=True

Close the owned storage client off-loop under the shutdown budget before releasing the offloader. The aborted-setup teardown path also clears the offloader without closing this client.

7. [P2] “Type-only” formatter logging is still formatter-controlled

The privacy log path includes type(formatted).__name__ / type(e).__name__. Python class names are not guaranteed to be static metadata; a formatter can construct a result or exception class whose name derives from the payload.

These two cases:

SecretResult = type("R10_RESULT_SECRET", (), {})
SecretError = type("R10_ERROR_SECRET", (Exception,), {})

produce:

Content formatter returned unsupported type R10_RESULT_SECRET ...
Content formatter (R10_ERROR_SECRET) failed ...

For a strict fail-closed boundary, use a constant warning with no formatter-controlled class metadata.

Verification and merge state

  • Complete affected test file at 086569c7: 384 passed, 6 skipped in 21.97s. There were no never-awaited warnings; the eight emitted warnings were unrelated existing deprecation/experimental warnings.
  • pyink --check, isort --check-only, and git diff --check: clean.
  • Production source was not modified during this report-only review.
  • The closed PR currently still records 70dee9b9 as its head, while the fork branch points to 086569c7. A three-way merge against current upstream main reports three conflicts in the plugin file, all around the intervening strict-typing change (BatchProcessor task annotation, _lazy_setup, and _ensure_started).

@caohy1988

Copy link
Copy Markdown
Author

Pushed 9aaa0c01 addressing all seven round-10 findings from the review:

  1. P1 unterminated encoded layer — when raw_decode fails on a quoted value, the post-quote prefix is classified with the same rule as the over-limit branch: {, [, \, or " (BOM/whitespace-tolerant) means a malformed encoded container and fails closed to [UNPARSEABLE_JSON_BLOB]; anything else remains quoted prose. The exact repro '"{\"access_token\":\"R10-SECRET\"}' now yields the sentinel with truncated=True, while '"unterminated prose' passes through. Both regress.

  2. P1 formatter gate destroying native shapes — the result gate now accepts every shape the parser handles natively: str (normalized to exact str), types.Content, types.Part, LlmRequest, dict, list, and None. Only results that would reach the parser's arbitrary str(content) fallback fail closed. Regression: an identity formatter with dict content writes the content, no sentinel, formatter_failed == 0.

  3. P1 coalesced caller claiming success after owner cancellation — the owner's finally resolves the shared completion successfully only when teardown ran to completion (teardown_completed set at the end of the try, and on the logged-and-swallowed error path, which is not retryable); a cancelled owner resolves it with a new _ShutdownIncompleteError, and waiters catch it and retry ownership (the admission flag was already released). Regression: the owner is cancelled while gated in a processor drain — the waiter does not return success, retries, completes the teardown (the drain mock is called exactly twice), and the state is removed.

  4. P1 caller-side coro.close() after ownership transfer — remote drains go through a new _schedule_remote_drain(): a plain ConcurrentFuture is returned immediately, and the drain coroutine and Task are created inside the remote loop's callback, entered only after set_running_or_notify_cancel() succeeds. If the callback never runs, nothing was ever created (a successful cf.cancel() prevents creation); if the drain is already running, cf.cancel() fails and the task simply continues remotely, bounded by its own timeout, with the state retained. No caller-side coro.close() exists anymore, eliminating both the wrong-thread finalization and the coroutine already executing failure. run_coroutine_threadsafe is no longer used; the multi-loop drain test was rewritten against a real second loop and asserts the drain executed on the remote loop's thread. A new regression leaves a drain running past the deadline: the state is retained, shutdown returns cleanly, and the drain finishes remotely afterwards.

  5. P2 stale-loop double counting — queue-loss accounting moved inside the single-winner claim on both sides: stale cleanup counts qsize - sentinels under the same guarded pop+fold transition, and shutdown()'s closed-loop path claims/folds/counts in one guarded transition keyed on still owning the exact snapshotted state. The interleaving repro (cleanup claims first, shutdown runs with its stale snapshot) now yields stale_loop == 1.

  6. P2 GCS storage client leak — both normal shutdown() and _teardown_aborted_setup() detach the offloader and close its plugin-owned storage.Client off-loop (bounded by the shutdown budget in the normal path) before releasing the reference. Regression asserts storage_client.close() was called and the offloader detached.

  7. P2 payload-derived class names in logs — both formatter log lines are now CONSTANT (no type(...).__name__ of formatter-controlled objects or exceptions). Regression uses type("R10_RESULT_SECRET", (), {}) and type("R10_ERROR_SECRET", (Exception,), {}) and asserts neither name reaches caplog while both incidents count as formatter_failed. The older test asserting "ValueError" appeared in the log is updated to the constant-message contract.

On the merge-state note: acknowledged — the PR object is frozen at 70dee9b9 and the branch will need a rebase over upstream's strict-typing change (three conflicts in this file) if it is ever reopened; happy to prepare that rebase on request, but I kept this round free of upstream syncing to keep the review diff stable.

Verification at 9aaa0c01: full affected test file 389 passed, 6 skipped (up from 384 — five new regressions plus two updated contracts), no never-awaited warnings; pyink --check / isort --check-only / git diff --check clean; focused mypy: byte-identical 58-error set before and after.

@caohy1988

Copy link
Copy Markdown
Author

Fresh review of 9aaa0c01: the seven round-10 fixes are present and their direct regressions pass, but I found four additional issues (three P1s and one P2).

P1 — Unicode-escaped trailing JSON document bypasses redaction

The suffix check at _sanitize_json_blob only searches for literal { or [. This malformed multi-document value passes unchanged with truncated=False:

"note" "\u007b\"access_token\":\"R11-SECRET\"\u007d"

The second quoted document encodes a credential container, but Unicode-escaped braces evade the literal scan and R11-SECRET is republished. The suffix should fail closed when its BOM/whitespace-stripped prefix begins with ", \, {, or [, or all trailing JSON values should be decoded under the existing bounds.

P1 — Shutdown ownership release is not atomic with the completion-future swap

At shutdown finalization, _is_shutting_down is reset before _setup_guard is acquired. This permits the following cross-thread interleaving:

  1. Owner A sets _is_shutting_down = False.
  2. Caller B acquires _setup_guard, claims shutdown, and installs future B.
  3. A acquires the guard, clears _shutdown_future, and resolves future B using A's result.
  4. Caller C then sees _is_shutting_down=True but _shutdown_future=None; because waiter is None, it falls through into the owner teardown path too.

That reintroduces overlapping teardown and lets B's waiters return before B finishes. Reset _is_shutting_down, _started, and _shutdown_future in one guarded transition, retaining A's completion future in a local variable.

P1 — Ordinary teardown exceptions still report successful coalesced completion

The outer handler sets teardown_completed = True after an exception. In a deterministic repro where the current-loop processor drain raises, both the owner and an already-coalesced waiter return normally while the loop state remains live (live_states=1).

This contradicts the new "success only when teardown actually completed" contract. Keep teardown_completed false on this path so the shared future receives _ShutdownIncompleteError and waiters retry ownership.

P2 — create_task() failure still leaks the remote-drain coroutine

At _schedule_remote_drain, processor.shutdown(...) is evaluated before target_loop.create_task(...). If a custom task factory rejects task creation, the exception is transferred to the concurrent future but the newly created coroutine is never closed. A rejecting task-factory repro emits:

RuntimeWarning: coroutine 'Processor.shutdown' was never awaited

Create the coroutine into a local variable inside the remote callback and close it there if create_task() raises.

Verification

  • Complete affected test module: 389 passed / 6 skipped
  • No never-awaited warning in the committed suite
  • pyink, isort, and git diff --check clean
  • Independent deterministic repros for findings 1, 3, and 4

@caohy1988

Copy link
Copy Markdown
Author

Pushed 03e7eb06 addressing all four round-11 findings from the review:

  1. P1 Unicode-escaped trailing document — a suffix that is itself a quoted JSON document is now RECURSED through _sanitize_json_blob under the same depth/size bounds, so escaped containers inside it get fully decoded and redacted: the exact repro '"note" "{\"access_token\":\"R11-SECRET\"}"' now serializes with [REDACTED] in place of the token. A suffix whose stripped prefix is a stray \ cannot be classified and fails closed. Raw-prose suffixes ('"hello" she said', '"a" and then "b" happened') and quoted-prose trailing documents ('"note" "just more prose"') still pass through unchanged. The literal {/[ scan remains for raw (never-decoded) suffix text.

  2. P1 non-atomic ownership release — the shutdown finally now resets _is_shutting_down, _started, and swaps out the completion future in ONE _setup_guard transition (the future is resolved after the guard is released, from the local). The interleaving where caller B installs its own future in the gap, gets it resolved with owner A's result, and caller C observes flag-set/future-None and falls into overlapping teardown is structurally closed: no state where the admission flag and the rendezvous disagree is observable anymore.

  3. P1 teardown exceptions reporting success — the logged-and-swallowed exception path no longer sets teardown_completed; the shared future resolves with _ShutdownIncompleteError and coalesced waiters retry ownership. Regression: the current-loop drain raises on its first call while a waiter is coalesced — the waiter does not accept the failed teardown, retries, the second drain succeeds (called exactly twice), and the state is claimed. Retry depth is bounded: only waiters retry, and a retry that fails again simply returns like any owner.

  4. P2 task-factory rejection leak — _schedule_remote_drain's callback creates the coroutine into a local and closes it when create_task() raises, transferring the exception to the concurrent future as before. Regression: a remote loop with a rejecting custom task factory runs under filterwarnings("error::RuntimeWarning") — no never-awaited warning, and the failed drain retains the state.

Verification at 03e7eb06: full affected test file 392 passed, 6 skipped (up from 389 — three new regressions; finding 2 is a lock-ordering change whose broken interleaving requires a cross-thread pause inside the finally, so it is covered structurally plus by the existing two-thread admission and coalescing tests rather than a dedicated race test), no never-awaited warnings; pyink --check / isort --check-only / git diff --check clean; focused mypy: byte-identical 58-error set before and after.

@caohy1988

Copy link
Copy Markdown
Author

Fresh review of 03e7eb06: the four round-11 fixes are present and their direct regressions pass, but three additional P1 issues remain.

P1 — Trailing encoded document still bypasses after ordinary prose

At _sanitize_json_blob, recursion only happens when the suffix's first non-whitespace character is ". An encoded credential document later in the suffix still passes unchanged:

"note" then "\u007b\"access_token\":\"R12-SECRET\"\u007d"

Deterministic repro:

secret_republished=True
truncated=False

The raw-prose allowance therefore remains a prefix that can hide a later quoted document. Inspect every bounded quoted JSON fragment in the suffix and recurse through each one, or conservatively fail closed when escapes occur anywhere in unverified trailing text. Add the prose-before-document case alongside the immediate-document regression.

P1 — Parser-native subclasses escape the formatter boundary and leak through traceback logs

The formatter gate uses isinstance for native shapes at lines 5114–5123. A subclass of LlmRequest, Content, or Part can therefore pass the gate while overriding a property that the parser evaluates outside that fail-closed boundary. For example, an LlmRequest subclass whose contents accessor raises a payload-bearing exception reaches the unguarded access at line 2534; _safe_callback then logs the exception and traceback.

Deterministic repro:

accepted_native_shape=True
secret_in_log=True

Require exact native classes, canonicalize subclasses inside the formatter's constant-log try, or bring parser failures from formatter results inside the same sentinel boundary. The regression should return a hostile native subclass from the formatter and assert both that the log excludes its secret and that the row contains the sentinel.

P1 — The owning shutdown caller still reports success after teardown failure

The round-11 change correctly resolves the shared future with _ShutdownIncompleteError, but the owner still swallows the underlying exception at lines 4277–4282. With no waiter, shutdown() returns success immediately over live state. With a waiter, the waiter retries at lines 4071–4076, becomes the next owner, and also returns success if that attempt fails.

Persistent-failure repro:

owner result=None
waiter result=None
drain_calls=2
live_states=1

Capture the teardown error, complete the rendezvous in finally, then raise the error to the owning caller. PluginManager.close() already catches and aggregates plugin close failures. A loop-based ownership retry would also avoid recursive retry depth under many coalesced callers.

Verification

  • Complete affected test module: 392 passed / 6 skipped
  • pyink, isort, and git diff --check clean
  • Independent deterministic repros for all three findings
  • The acknowledged upstream rebase was not counted as a finding

@caohy1988

Copy link
Copy Markdown
Author

Pushed ae81be50 addressing all three round-12 findings from the review:

  1. P1 prose-before-document bypass — the suffix walk now recurses from the FIRST " anywhere in the trailing text, not only when the suffix begins with one: the prose gap before the quote is kept verbatim (fail-closed if it contains an escape, which could shift a consumer's parse boundaries), and the tail from the quote re-enters _sanitize_json_blob, whose own suffix handling walks prose/document chains to the depth cap. The exact repro '"note" then "{…access_token…}"' now redacts, as does a longer prose → plain document → prose → credential document chain. Quote-free prose and multi-quote dialogue ('"a" and then "b" happened') still pass unchanged.

  2. P1 native-subclass escape — the formatter gate requires the EXACT class for the model shapes (type(formatted) in (types.Content, types.Part, LlmRequest)), so a subclass can no longer pass the gate and detonate a payload-bearing property in parser attribute accesses outside the boundary. dict/list deliberately stay isinstance-based: the parser routes them through _recursive_smart_truncate, whose round-8 protocol boundary already fails hostile subclasses closed. Regression: a formatter returning an LlmRequest subclass produces the sentinel row, one formatter_failed, and no subclass name (or anything else) in the logs.

  3. P1 owner reporting success over live state — the teardown exception is captured, the rendezvous resolves with _ShutdownIncompleteError in the finally, and the OWNER then re-raises the captured error to its caller (PluginManager.close() aggregates plugin close failures). The coalesced-waiter retry was converted from recursion to a loop, so retry depth no longer grows with the number of coalesced callers. Regressions: the persistent-failure repro now raises to both the owner and the retrying waiter (drain called exactly twice, state retained for a later close), and the transient-failure test asserts the owner raises while the retrying waiter completes the claim.

Verification at ae81be50: full affected test file 395 passed, 6 skipped (up from 392 — three new regressions plus the updated round-11 contract), no never-awaited warnings; pyink --check / isort --check-only / git diff --check clean; focused mypy: byte-identical 58-error set before and after.

@caohy1988

Copy link
Copy Markdown
Author

Fresh full review of ae81be50 found three release-blocking P1s:

  1. P1 — exact top-level formatter gate still admits nested hostile subclasses

    The exact-class check at type(formatted) in (types.Content, types.Part, LlmRequest) only validates the root object. Pydantic preserves nested subclasses during normal construction, so this needs no model_construct bypass:

    class EvilPart(types.Part):
      def __getattribute__(self, name):
        if name == "file_data":
          raise RuntimeError("R13-NESTED-SECRET")
        return super().__getattribute__(name)
    
    formatted = types.Content(parts=[EvilPart()])
    assert type(formatted) is types.Content

    The formatter gate accepts this value, after which _parse_content_object() evaluates hasattr(part, "file_data") outside the formatter boundary. The exception reaches _safe_callback, whose logger.exception republishes R13-NESTED-SECRET in the traceback and drops the row. The formatter result must either be parsed inside the same constant-log fail-closed boundary, or its full nested model graph must be normalized to exact native types. A regression should assert a sentinel row and absence of the exception payload from logs.

  2. P1 — prose inside a single encoded JSON string hides a credential container

    This is one complete, valid JSON string document rather than a trailing second document:

    raw = '"note \\u007b\\"access\\u005ftoken\\":\\"R13-SECRET\\"\\u007d"'
    out, truncated = _recursive_smart_truncate({"blob": raw}, 10000)

    Current result retains R13-SECRET byte-for-byte with truncated is False. json.loads decodes the value to note {"access_token":"R13-SECRET"}, but the recursive call only recognizes a container at the beginning of the decoded string, so the prose prefix returns unchanged. The decoded string needs the same anywhere-in-text document handling as the new suffix walk, or must fail closed when decoded container tokens occur after prose.

  3. P1 — failed remote drains still resolve shutdown successfully over live state

    The remote result loop logs a failed/cancelled/timed-out drain and retains its state, but then continues to the unconditional teardown_completed = True. Deterministic repro with a remote future completed by RuntimeError, plus a coalesced waiter:

    results [None, None]
    live_state True
    

    Thus both the owner and waiter report successful shutdown even though the remote processor remains owned and may still contain queued rows. This is the same honest-completion contract fixed for current-loop teardown errors in round 12. Any remote drain that does not complete cleanly must keep teardown incomplete, surface failure to the owner, and make the shared completion cause a waiter retry rather than resolve successfully.

Independent verification at ae81be50: affected test file 395 passed / 6 skipped, never-awaited warnings checked as errors; pyink --check, isort --check-only, and git diff --check clean.

@caohy1988

Copy link
Copy Markdown
Author

Pushed 1cc4adcf addressing all three round-13 findings from the review:

  1. P1 nested hostile subclasses — parser.parse() for row content now runs inside its own fail-closed, constant-log boundary: any exception (including a payload-bearing one raised from a nested EvilPart.__getattribute__ during parser attribute access) is caught, the row is written with [CONTENT_PARSE_FAILED] content and is_truncated=True, a new content_parse_failed counter records the incident (documented in get_drop_stats alongside formatter_failed as "row WAS written with a sentinel"), and only the event type is logged. This closes the whole class — the top-level exact-type gate stays as the first line, and anything it cannot see (pydantic preserves nested subclass instances through normal construction) is contained at parse time. Regression: a formatter returning types.Content(parts=[EvilPart()]) (which passes the exact-type gate, asserted) produces the sentinel row with R13-NESTED-SECRET absent from both the row and caplog.

  2. P1 prose inside a decoded string — the suffix walk and decoded-layer handling now share one _sanitize_free_text() helper: text with machine-encoded provenance that contains a literal container token anywhere after prose fails closed (escapes are gone after the decode, so the literal scan is sound), and quoted fragments are walked from the first quote. The exact repro '"note {\"access_token\":\"R13-SECRET\"}"' now fails closed with truncated=True. Ordinary quoted prose — including strings that decode to prose with inner quoted fragments (json.dumps('he said "hi"')) — passes unchanged, and all prior rounds' repros (double-encoding, immediate and prose-separated trailing documents) remain closed.

  3. P1 remote drains resolving success over live state — every retained remote drain (timed out, cancelled, or failed) is counted, and a non-zero count raises _ShutdownIncompleteError before teardown_completed can be set: the owner surfaces the failure to its caller, the rendezvous resolves incomplete, and coalesced waiters retry ownership — the same honest-completion contract round 12 established for current-loop errors. The three existing remote-drain tests (failed, slow, rejecting-task-factory) are updated to the raising contract, and a new regression drives a persistent remote failure with a coalesced waiter: both callers raise, the drain state stays retained.

Verification at 1cc4adcf: full affected test file 398 passed, 6 skipped (up from 395 — three new regressions plus three updated contracts), never-awaited warnings checked; pyink --check / isort --check-only / git diff --check clean; focused mypy: byte-identical 58-error set before and after.

@caohy1988

Copy link
Copy Markdown
Author

Fresh full review of 1cc4adcf found three release-blocking P1s:

  1. P1 — over-limit prose-prefixed encoded strings still leak

    The quoted-string size branch classifies only the first character after the opening quote. If that character is ordinary prose, it returns before the new _sanitize_free_text() path runs, and the caller then raw-truncates the uninspected value. Deterministic repro:

    raw = (
        '"note \\u007b\\"access\\u005ftoken\\":'
        '\\"R14-OVERLIMIT-SECRET\\"\\u007d'
        + "x" * 10050
        + '"'
    )
    out, truncated = _recursive_smart_truncate({"blob": raw}, 10000)

    Current result: R14-OVERLIMIT-SECRET remains in out["blob"] and truncated is True. The same reproduces at the default 500 KiB limit by increasing the padding. The bounded prefix that will actually be emitted must be classified for encoded containers instead of relying only on its first character.

  2. P1 — nested subclasses can defer failure until Arrow serialization and escape the new parse boundary

    The new boundary catches only exceptions raised by parser.parse(). An exact top-level LlmRequest can preserve a nested model subclass that returns a hostile object without raising during parsing:

    class LateBomb:
      def __repr__(self):
        raise RuntimeError("R14-LATE-SERIALIZE-SECRET")
    
    class EvilContent(types.Content):
      def __getattribute__(self, name):
        if name == "role":
          return LateBomb()
        return super().__getattribute__(name)
    
    formatted = LlmRequest(contents=[EvilContent(parts=[])])
    assert type(formatted) is LlmRequest

    parser.parse() succeeds and places the LateBomb in content_json["prompt"][0]["role"], so the new catch never runs. During Arrow preparation, json.dumps(value) raises TypeError; the existing str(value) fallback then invokes the hostile __repr__. _write_rows_with_retry() logs R14-LATE-SERIALIZE-SECRET with the full traceback and drops the row as arrow_prep_failed. Parser output (content_json and content_parts) must be recursively normalized/validated inside the constant-log boundary before it is released downstream. The regression needs to exercise batch preparation, not only an eager parser exception.

  3. P1 — remote scheduling exceptions still resolve shutdown successfully over live state

    When _schedule_remote_drain() itself raises, the exception branch logs and retains the state but does not increment retained_remote_drains. This is a real race when a target loop closes between the preceding is_closed() check and call_soon_threadsafe().

    Owner-only deterministic repro with _schedule_remote_drain raising RuntimeError:

    returned None
    live_state True
    

    I also held another remote drain open so a waiter could coalesce; after completing that drain, both callers returned success while the scheduling-failure state remained:

    results [None, None]
    failed_state_live True
    

    The scheduling-exception branch must count the state as retained (or atomically reclaim it if the loop is now closed), keeping teardown incomplete so the owner raises and coalesced waiters retry.

Independent verification at 1cc4adcf: affected test file 398 passed / 6 skipped, never-awaited warnings checked as errors; pyink --check, isort --check-only, and git diff --check clean; worktree clean.

@caohy1988

Copy link
Copy Markdown
Author

Pushed d31c24a2 addressing all three round-14 findings from the review:

  1. P1 over-limit prose-prefixed encoded strings — the over-limit quoted branch now classifies the bounded prefix that will actually be EMITTED after the caller's raw truncation (stripped[:max_len], or the inspection ceiling in unlimited mode): any {, [, or \ inside that window fails closed, since the truncated output could retain escaped credential material. This subsumes the old first-character check. The exact repro (escaped container after "note , padded past the limit) now yields the sentinel; escape-free, container-free over-limit quoted prose still raw-truncates normally. Both regress.

  2. P1 late-detonating nested subclasses — parser output (content_json and content_parts) is normalized to strictly JSON-native values inside the same constant-log parse boundary via a new _normalize_json_native() helper: exact-typed scalars pass, str subclasses are canonicalized, dict/list are rebuilt under the usual depth/node budgets with a fail-closed except, and anything else — including the LateBomb planted in prompt[0]["role"] — becomes [UNSUPPORTED_OBJECT] with the truncation flag set. The helper deliberately does NOT re-inspect strings: parser output is already truncated/redacted, and re-running blob inspection corrupted sentinels and bracketed prose (caught while developing the fix — the first cut used the full sanitizer and broke [FORMATTER_FAILED] itself). The regression exercises real Arrow batch preparation: the row is captured post-serialization, arrow_prep_failed stays 0, and R14-LATE-SERIALIZE-SECRET appears in neither the row nor caplog.

  3. P1 scheduling-failure honesty — an exception from _schedule_remote_drain() itself (the loop closing between is_closed() and call_soon_threadsafe() being the real-world race) now increments retained_remote_drains, so teardown stays incomplete: the owner raises _ShutdownIncompleteError and coalesced waiters retry, instead of both returning success while the unscheduled state remains live. Regression patches the scheduler to raise against a live remote loop and asserts the raise plus state retention.

Verification at d31c24a2: full affected test file 401 passed, 6 skipped (up from 398 — three new regressions), never-awaited warnings checked; pyink --check / isort --check-only / git diff --check clean; focused mypy: byte-identical 58-error set before and after.

@caohy1988

Copy link
Copy Markdown
Author

Fresh full review of d31c24a2 found three remaining release-blocking P1s:

  1. P1 — unlimited mode still leaks credentials after the 4M inspection window

    In the over-limit quoted branch, max_len=-1 scans only _MAX_JSON_INSPECT_CHARS, but the caller emits the ENTIRE value in unlimited mode. A valid quoted string can therefore put its encoded credential document immediately after the inspected prefix:

    raw = (
        '"'
        + "a" * 4_000_010
        + '\\u007b\\"access\\u005ftoken\\":'
        + '\\"R15-UNLIMITED-SECRET\\"\\u007d"'
    )
    out, truncated = _recursive_smart_truncate({"blob": raw}, -1)

    Current result:

    leaked True
    truncated False
    unchanged True
    

    The comment that this classifies the prefix that will actually be emitted is therefore false in unlimited mode. That mode must classify the entire emitted value with a bounded linear scan, or fail closed for quoted strings beyond the hard inspection ceiling.

  2. P1 — JSON-native normalization does not preserve sensitive-key redaction

    Parser output is not universally pre-redacted. A nested model property can return a JSON-native mapping directly through a field copied by the parser:

    class EvilContent(types.Content):
      def __getattribute__(self, name):
        if name == "role":
          return {"access_token": "R15-NATIVE-SECRET"}
        return super().__getattribute__(name)
    
    formatted = LlmRequest(contents=[EvilContent(parts=[])])
    assert type(formatted) is LlmRequest

    parser.parse() places that mapping in prompt[0]["role"]; _normalize_json_native() copies its string key and value unchanged. The resulting serialized content contains R15-NATIVE-SECRET, with replaced=False and truncated=False. The same mapping is correctly redacted when supplied through the parser's direct dict/list path, so normalized nested output needs the same sensitive-key / temp: value-redaction policy while still avoiding blob re-inspection of ordinary string values.

  3. P1 — parser-produced strings can bypass max_content_length entirely

    _normalize_json_native() assumes every parser-produced string has already been bounded, but several model fields are copied directly. The simplest is LlmRequest.contents[*].role:

    role = "R15-ROLE-" + "x" * 1_000_000
    request = LlmRequest(contents=[types.Content(role=role, parts=[])])
    parsed, _, parser_truncated = await HybridContentParser(
        None, "trace", "span", 10
    ).parse(request)
    normalized, replaced = _normalize_json_native(parsed)

    Current result:

    role_len 1000009
    parser_truncated False
    normalizer_replaced False
    

    The one-million-character value then goes through synchronous json.dumps and Arrow serialization despite max_content_length=10. This reopens the event-loop/memory availability boundary for native strings copied from model metadata. The normalizer needs the configured length bound and should truncate strings without re-running JSON-blob inspection, preserving sentinels and ordinary bracketed prose.

Independent verification at d31c24a2: affected test file 401 passed / 6 skipped, never-awaited warnings checked as errors; pyink --check, isort --check-only, and git diff --check clean; worktree clean.

@caohy1988

Copy link
Copy Markdown
Author

Pushed 5aa9c003 addressing all three round-15 findings from the review:

  1. P1 unlimited-mode leak past the inspection window — the over-limit quoted classifier now scans exactly what will be emitted: the max_len prefix in bounded mode, or the entire value in unlimited mode (one linear in pass over text already in memory). The repro — a valid quoted string with the escaped credential document placed just past the 4M window — now fails closed; an escape-free giant quoted prose value still passes whole. Both regress, sized against _MAX_JSON_INSPECT_CHARS so the test tracks the constant.

  2. P1 normalizer missing sensitive-key redaction — _normalize_json_native() applies the same sensitive-key/temp: value-redaction policy as the main sanitizer: a nested model property handing the parser a raw {"access_token": ...} mapping through a verbatim-copied field now lands as [REDACTED]. Regressions at both the unit level and the row boundary (the EvilContent.role repro through _log_event and Arrow preparation).

  3. P1 unbounded parser-copied strings — the normalizer takes the configured max_content_length and bounds strings by plain prefix truncation (...[TRUNCATED]), with no blob re-inspection, so sentinels and bracketed prose are preserved. The million-character role now serializes as a 24-character truncated string. One scoping decision surfaced by the full suite: content_parts are normalized shape-only (max_len=-1) — they carry parser-BUILT metadata (GCS URIs, object_ref.details JSON) whose strings must stay intact, and their payload text was already truncated by the parser itself; bounding them corrupted GCS object references (caught by the existing offload test before commit).

Verification at 5aa9c003: full affected test file 404 passed, 6 skipped (up from 401 — three new regressions), never-awaited warnings checked; pyink --check / isort --check-only / git diff --check clean; focused mypy: byte-identical 58-error set before and after.

@caohy1988

Copy link
Copy Markdown
Author

Real-traffic end-to-end validation at 5aa9c003 — finalized

To close the loop on rounds 1–15, I validated the fixes with a real agent under real traffic: a live LlmAgent (gemini-3.5-flash on Vertex AI) driven through Runner with this branch's BigQueryAgentAnalyticsPlugin, writing to a real BigQuery dataset over the Storage Write API, with real GCS offload — then queried the written rows back and asserted on what actually landed. Two phases, six scenarios, all checks passing.

Phase 1 — privacy boundary under real state deltas

A tool planted every review-round credential shape into session state; the STATE_DELTA row as actually written to BigQuery:

planted payload as stored in BigQuery
plain credential blob {"access_token": "[REDACTED]"}
double-encoded blob (round 6) redacted in place, double-encoding preserved
unicode-escaped trailing document (round 11) "note" "{\"access_token\": \"[REDACTED]\"}"
prose-then-document (round 12) redacted the same way
prose inside the encoded string (round 13) [UNPARSEABLE_JSON_BLOB] (fail-closed)
unterminated encoded container (round 10) [UNPARSEABLE_JSON_BLOB] (fail-closed)
refresh_token, temp: keys [REDACTED]
benign note untouched

13 rows across 11 event types, all 8 secret markers absent from every row, is_truncated set exactly on sentinel-bearing rows, zero drops, clean close().

Phase 2 — lifecycle, failure, and offload scenarios

  • S1 enabled=False (round 1 P2): pointed at a nonexistent dataset — the agent turn completed, no client/table/writer state was ever created, close() clean.
  • S2 setup failure → recovery (rounds 1–2 P1, round 9 P2-9): with the dataset missing, the plugin stayed unstarted and counted 8 rows as setup_unavailable (exactly once each — no double counting) while the agent was unharmed; after provisioning the dataset, the backoff retry recovered and 8 real rows landed.
  • S3 formatter + hostile objects (rounds 7–14): a raising formatter and a non-native formatter result produced [FORMATTER_FAILED] sentinel rows (formatter_failed=3); namedtuple / SimpleNamespace / (str, Enum) secrets in state were [REDACTED]; a Mapping whose items() raises and a late-detonating __repr__ bomb landed as [UNSUPPORTED_OBJECT] with arrow_prep_failed=0 — all six canaries absent from rows and logs.
  • S4 truncation + GCS offload (rounds 1, 15): a large state value was truncated inline with the flag set; two large message parts were offloaded with unique per-part object paths (the round-1 call-local identity fix) and every offloaded GCS object verified to hold the full untruncated payload.
  • S5 multi-loop + coalesced close (rounds 4–14): agent turns on two live event loops produced two per-loop writers; two concurrent close() calls coalesced and both succeeded; the remote drain executed via _schedule_remote_drain on the second loop's own thread; all states were claimed and both turns' rows landed.

Scope notes

  • Unreachable in a clean real run and therefore covered by the deterministic unit regressions only: cancellation timing windows (host-timeout mid-drain, O(1) cancel accounting), the create_table Conflict race, counter thread-safety stress, fork/pickle resets, and the 4M-char inspection-ceiling extremes.
  • Two harness artifacts encountered were platform/test issues, not plugin defects: offload-bearing LLM_REQUEST rows are legitimately is_truncated=True from their inline prompt summaries (the offloaded parts themselves are full-fidelity references), and BigQuery's known recreated-table lag stalls the _default write stream for same-name tables (worked around with fresh table names).

Environment: project-owned test GCP project, ADC auth, dataset bqaa_6360_validation, real Storage Write API appends verified by SQL readback.

With rounds 1–15 addressed at 5aa9c003 (404 unit tests passing, lint clean, zero mypy regressions) plus this real-traffic validation, I'm treating the branch as finalized unless further findings surface.

@caohy1988

Copy link
Copy Markdown
Author

Fresh full review of 5aa9c003 found two release-blocking P1s and one P2:

  1. P1 — JSON-encoded credentials in parser-copied strings still bypass redaction

    _normalize_json_native() deliberately skips blob inspection for strings, but parser output is not universally pre-sanitized at the string level. A normally constructed exact request is sufficient:

    role = json.dumps({"access_token": "R16-ENCODED-ROLE-SECRET"})
    request = LlmRequest(contents=[types.Content(role=role, parts=[])])
    parsed, _, parser_truncated = await HybridContentParser(
        None, "trace", "span", 10000
    ).parse(request)
    normalized, replaced = _normalize_json_native(parsed, 10000)

    Current result: R16-ENCODED-ROLE-SECRET remains in the serialized prompt, with parser_truncated=False and replaced=False. The same credential mapping is redacted when it arrives as a native mapping, so an opaque JSON string copied through role (or another verbatim model field) reopens the encoded-blob privacy bypass. Targeted sanitation is needed for untrusted parser-copied fields while explicitly preserving known sentinels and legitimate prose.

  2. P1 — the serialization length boundary still excludes mapping keys and all content_parts metadata

    The new bound only applies to dictionary VALUES in bounded normalization. Keys are copied verbatim, and content_parts deliberately invoke _normalize_json_native(..., -1) even though several of their fields are user-controlled rather than generated GCS metadata.

    Deterministic results with max_content_length=10:

    one-million-character mapping key:
      key_len 1000008
      replaced False
    
    one-million-character external file_uri:
      uri_len 1000024
      parser_truncated False
      normalizer_replaced False
    
    one-million-character function-call name:
      text_len 1000023
      attrs_len 1000034
      parser_truncated False
      normalizer_replaced False
    

    All of these continue into synchronous json.dumps and Arrow serialization, reopening the event-loop/memory boundary despite the configured limit. Generated GCS URI/object-ref metadata can remain intact, but user-derived external URIs, MIME types, function metadata, and mapping keys need field-specific bounds. Key truncation also needs the collision-safe allocation policy already used by the full sanitizer.

  3. P2 — small configured limits corrupt the fail-closed sentinels

    The new plain string bound does not exempt known sentinels:

    _normalize_json_native("[FORMATTER_FAILED]", 5)
    # ('[FORM...[TRUNCATED]', True)

    The row path already truncates the formatter sentinel similarly through HybridContentParser._truncate; upstream [UNPARSEABLE_JSON_BLOB] and related markers are also altered when they pass through bounded normalization. The preservation regression only uses max_len=10000, so it misses the allowed small-limit configurations. Known security/failure sentinels should remain exact regardless of max_content_length, preserving downstream classification.

Independent verification at 5aa9c003: affected test file 404 passed / 6 skipped, never-awaited warnings checked as errors; pyink --check, isort --check-only, and git diff --check clean; worktree clean.

caohy1988 added a commit to caohy1988/adk-python that referenced this pull request Jul 16, 2026
…als, log leak, blob decode-first

All eight findings from the PR google#6360 review at 257c51b:

- P1-1: _ensure_schema_exists now runs on every setup attempt until one
  succeeds; the cached _schema no longer gates it. Retry test asserts the
  second get_table RPC.
- P1-2: GCS object names gain a per-parse uid and content ordinal, so
  multiple messages in one request (same trace/span, restarting part
  index) can no longer collide. New multi-message regression test.
- P1-3: the formatter-failure log carries only the exception class — no
  message, no exc_info — so a formatter that embeds content in its
  exception cannot leak it into application logs. Test asserts caplog.
- P1-4: _sanitize_json_blob decodes FIRST ({ or [ prefixes), inspecting
  decoded keys recursively — JSON string escapes (access\u005ftoken) and
  arrays of credential objects are covered; unchanged strings return
  byte-for-byte. New escape/array regression test.
- P2-5: shutdown() folds processor drop counters into the persistent
  plugin counters before clearing loop state.
- P2-6: __setstate__ backfills _local_drop_counts/_setup_failures/
  _setup_retry_at for pre-change pickles; __getstate__ resets retry state.
- P2-7: _validate_runtime_config enforces integral counts and finite
  reals (NaN previously passed every ordered comparison; max_retries=NaN
  silently skipped the write loop).
- CI: test_views_not_created_after_table_creation_failure updated to the
  intentional raise; parser-reuse test now pins the no-mutation contract.

Also adds a recursion depth cap to _recursive_smart_truncate: id()-based
cycle detection cannot catch graphs that manufacture new objects per
duck-typed access (Mock-like), which the new final sanitizer pass exposed
as an unbounded recursion.
@caohy1988

Copy link
Copy Markdown
Author

Branch rebased onto current upstream main

fix/bqaa-6356 has been rebased onto upstream main at 221bad92 and force-pushed: old head 5aa9c003 → new head 965a2ac2 (the pre-rebase head is preserved at backup/fix-bqaa-6356-pre-rebase locally; all previously reviewed SHAs remain reachable via the comment links).

Details:

  • All 16 review-round commits replayed linearly onto main (77 upstream commits since the original base 9d306f5d). The only upstream change touching the plugin was fd8fa3b8 ("chore: fix mypy strict type errors in adk plugins"), producing exactly 4 conflict hunks across 3 commits — the three sites called out in the round-10 merge-state note (BatchProcessor task annotation, _lazy_setup, _ensure_started). Each was resolved by keeping this branch's logic with upstream's annotations (**kwargs: Any, asyncio.Task[None]).
  • Post-rebase diff against the pre-rebase tree contains only upstream's type annotations — no logic drift; the test file is byte-identical.
  • Verification at 965a2ac2 (deps reinstalled for the new base): full affected test file 404 passed, 6 skipped, no never-awaited warnings; pyink --check / isort --check-only / git diff --check clean; focused mypy: 36 errors on this branch vs 43 on the new upstream baseline — 7 net fewer, zero new errors (upstream's strict-typing pass plus this branch's earlier annotation cleanups compose).

The branch now applies cleanly on top of current main for anyone reopening or resubmitting this work.

@caohy1988

Copy link
Copy Markdown
Author

Pushed 64fca7a8 resolving the one branch-only mypy diagnostic from the rebase verification follow-up: executor creation is hoisted to the top of _lazy_setup, so GCSOffloader (argument 3, non-optional ThreadPoolExecutor) and the schema-RPC run_in_executor call always receive a live, non-optional local. This was more than a typing nit — with a pre-set client the executor branch was skipped entirely, leaving _executor=None on the offload path at runtime. The cancellation branch's conditional executor release is unchanged.

Verification at 64fca7a8: full affected test file 404 passed, 6 skipped; pyink --check / isort --check-only clean; focused mypy 35 errors vs 43 on current upstream main — the GCSOffloader arg-type diagnostic is gone and the branch's error set is now a strict subset of main's, so a CI error-set comparison against main should pass cleanly on reopen/resubmission.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

tracing [Component] This issue is related to OpenTelemetry tracing

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants