Repository navigation
perf(startup): cut CLI import tax + scrub nix wrapper env leaks - #3166
Conversation
…ge inits Problem: polylogue-h1wt found importing a single ArchiveTier enum forced ~950ms-1.2s of eager DDL/backend imports through archive_tiers/__init__.py and its parent polylogue.storage.sqlite/__init__.py. polylogue-8s70 found `polylogue status`/`agents status` paid ~1.5-2s of command-body import tax beyond --help's budget, dominated by storage.repair's own heavy import list and the eager operations/insights package inits it reaches through. What changed (each verified with isolated python -c / -X importtime timing): - polylogue/storage/sqlite/__init__.py: defer SQLiteBackend import via PEP 562 __getattr__, matching the existing polylogue/storage/__init__.py pattern. `archive_tiers.types` import: ~1000ms -> ~104ms. - polylogue/pipeline/ids.py: ParsedMessage/ParsedSession/etc. are type-only here; move to TYPE_CHECKING so this pure hashing module stops forcing the whole `polylogue.sources` package (incl. Drive download subsystem) onto every caller. - polylogue/storage/repair.py: defer `sources.dispatch.detect_provider` / `is_stream_record_provider` into the ~6 functions that actually call them (matching the file's existing local-import convention for sources.revision_backfill). `import polylogue.storage.repair`: ~670ms -> ~270ms. - polylogue/sources/__init__.py: lazy re-exports (PEP 562) so importing a submodule (e.g. parsers.base) no longer forces the Drive subsystem (tenacity, drive.auth, drive.gateway, ...) to load. - polylogue/operations/__init__.py, polylogue/insights/__init__.py: same lazy-package-init pattern, so importing one submodule doesn't force every sibling submodule (and the ~20-model insight registry) to load. - polylogue/operations/operation_status.py (new): split OperationStatus (a plain str Enum) out of operation_contract.py, whose other export (OperationFollowUp) subclasses a pydantic SurfacePayloadModel that pulls in ~280ms of archive/semantic pricing machinery. readiness/capability.py only ever needed the enum. Net result on this host (empty archive root, cold subprocess, 3 runs): `polylogue status --format json` ~2.05s -> ~1.47s; `agents status --format json` ~1.8s -> ~1.3s; `ops maintenance migrate-tier --help` ~1.04s -> ~0.40s (promoted from informational to required in help_latency_probe.py). Not fully closed: 8s70's own <700ms budget is not yet met for status/agents-status. The remaining ~1s is insights.archive's own weight (pydantic cost/coverage models), pulled in for real by session-tag-rollup computation (archive_rollups.py) and ArchiveCoverageInsight reporting -- not an eager-import artifact, so left alone rather than restructuring those model definitions in this pass. Two zero-benefit micro-fixes (insights.archive date-helper extraction, ArchiveCoverageInsight TYPE_CHECKING-only in helper_summary.py) were tried, measured as no-change, and reverted rather than landed, per this bead's own established "no-measured-benefit PR" discipline. Ref polylogue-h1wt, Ref polylogue-8s70 Co-Authored-By: Claude <[email protected]>
polylogue/operations/operation_status.py (new in the prior commit) needs a topology-projection entry or `devtools render all --check` fails per the repo's own module-addition rule. Ref polylogue-h1wt, Ref polylogue-8s70 Co-Authored-By: Claude <[email protected]>
…LI wrappers Problem: polylogue-xikl reproduced the polylogue-freethreaded (python3.14t) package failing under a caller's ambient devshell environment (e.g. this repo's own 3.13 devshell) even though the existing wrapper already unset PYTHONPATH/PYTHONHOME/PYTHONBREAKPOINT/PYTHONUSERBASE/VIRTUAL_ENV. Bisected with `env -i` (adding one var back at a time): PYTHONPATH alone was NOT the trigger. The actual cause is `_PYTHON_SYSCONFIGDATA_NAME`, a nixpkgs-set env var that Python's own `sysconfig._get_sysconfigdata_name()` trusts over its own computation when present. The free-threaded build's real sysconfigdata module carries a `t` abiflag segment (`_sysconfigdata_t_linux_x86_64-linux-gnu`, confirmed via `find .../lib/python3.14t -iname '_sysconfigdata*'`), but a 3.13-derived value of this env var (`_sysconfigdata__linux_x86_64-linux-gnu`, no `t`) does not match it, so any command doing real work (not just --version/--help, which short-circuit before this path) fails with `ModuleNotFoundError`. `_PYTHON_HOST_PLATFORM` is the sibling nixpkgs var for the same class of leak; added defensively even though it did not reproduce the failure alone in this session's bisection. Solution: add `--unset _PYTHON_SYSCONFIGDATA_NAME --unset _PYTHON_HOST_PLATFORM` to all three CLI/API-python wrapper sites in flake.nix (`mkPolylogue`'s postFixup, shared by both `polylogue` and `polylogue-freethreaded` since they call the same function; and `polylogueApiPythonWrapped`'s raw-interpreter wrapper, for the same class of leak on the scripting/notebook python). Verification: `nix build .#polylogue-freethreaded` and `nix build .#polylogue` both succeed; with this session's actual ambient devshell environment (PYTHONPATH pointing at the 3.13 venv site-packages, plus _PYTHON_SYSCONFIGDATA_NAME/_PYTHON_HOST_PLATFORM as nixpkgs sets them) still exported in the invoking shell, both packages' `polylogue demo seed` + `polylogue demo verify` complete successfully (16 sessions/62 messages/4 query hits) -- the exact real-ingest path that previously raised `ModuleNotFoundError: No module named '_sysconfigdata__linux_x86_64-linux-gnu'` on the freethreaded build. Ref polylogue-xikl Co-Authored-By: Claude <[email protected]>
The lazy re-export commit missed download_drive_files in the TYPE_CHECKING import block (only added it to the runtime __getattr__ dict), so mypy treated `from polylogue.sources import download_drive_files` as having the __getattr__ fallback's `object` return type -- caught by `devtools verify --quick`: tests/unit/sources/test_drive_ops.py:108: error: "object" not callable [operator]. Ref polylogue-h1wt, Ref polylogue-8s70 Co-Authored-By: Claude <[email protected]>
|
| GitGuardian id | GitGuardian status | Secret | Commit | Filename | |
|---|---|---|---|---|---|
| 34951478 | Triggered | Authentication Tuple | a5b3220 | polylogue/sources/init.py | View secret |
🛠 Guidelines to remediate hardcoded secrets
- Understand the implications of revoking this secret by investigating where it is used in your code.
- Replace and store your secret safely. Learn here the best practices.
- Revoke and rotate this secret.
- If possible, rewrite git history. Rewriting git history is not a trivial act. You might completely break other contributing developers' workflow and you risk accidentally deleting legitimate data.
To avoid such incidents in the future consider
- following these best practices for managing and storing secrets including API keys and other credentials
- install secret detection on pre-commit to catch secret before it leaves your machine and ease remediation.
🦉 GitGuardian detects secrets in your source code to help developers and security teams secure the modern development process. You are seeing this because you or someone else with access to this repository has authorized GitGuardian to scan your pull request.
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
|
Warning Review limit reached
Next review available in: 44 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (14)
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
|
GitGuardian false positive triage: the flagged "Authentication Tuple" at |
…3321) ## Summary Fixes a real, measured slice of `polylogue-8s70`'s command-body import tax. ## Problem `polylogue status`/`agents status` pay an import tax that `polylogue --help` never reaches (`--help` short-circuits before the command callback runs). Prior work (PR #3166) cut `status` from ~2.05s to ~1.47s by localizing `storage.repair`/`sources.dispatch` imports, but a fresh `python -X importtime` pass on `polylogue status --format json` against an empty archive root showed it had regressed back to ~1.84-1.90s, tracing a distinct, previously unnoticed 300-400ms branch: `polylogue.ui` → `polylogue.ui.facade` → `questionary` → `prompt_toolkit`, plus a smaller `pygments`/`rich.markdown`/`rich.syntax` branch in `facade_rendering.py`. Both are imported unconditionally at module top level even though: - `questionary` is only called inside `ConsoleFacade.confirm`/`choose`/`input`'s non-plain (interactive TTY) branches — `--format json` output never reaches them. - `pygments`/`rich.markdown.Markdown`/`rich.syntax.Syntax` are only used inside `render_markdown`/`render_code`/`render_diff`, not by plain status printing. ## Solution Moved both import sets from module top level into the specific methods/functions that use them, matching this repo's existing local-import convention. No behavior change — confirmed via `tests/unit/ui` (which monkeypatches `questionary` attributes directly on the shared module object; imports are idempotent). ## Verification - `python -X importtime -m polylogue status --format json`: `polylogue.ui` cumulative import cost 408ms → 92ms; questionary/prompt_toolkit/pygments/rich.markdown/rich.syntax now show 0 occurrences on this command's trace (994 → 716 modules imported total). - `time polylogue status --format json` (empty archive root, cold subprocess, `POLYLOGUE_DAEMON_URL` forced to a closed port, 3+ runs): ~1.84-1.90s → ~1.52-1.54s. - `polylogue --help`: unaffected, ~0.45-0.46s; `devtools bench help-latency`: all 14 required targets still green. - `polylogue agents status --format json`: unaffected (~1.48-1.50s) — that command's import trace never touched questionary/prompt_toolkit, confirming this is a targeted fix, not a blanket sweep. - `ruff check`/`format --check` clean; `mypy --strict` clean on both files. - `devtools test tests/unit/ui`: 115 passed. - `devtools test tests/unit/cli/test_status.py tests/unit/cli/commands/test_status.py tests/unit/cli/test_status_diagnostics.py tests/unit/cli/test_embed_status_fast.py`: 1 pre-existing failure (`test_archive_facade_route_catalog_covers_public_async_facade`), independently re-confirmed identical on `origin/master` before merging this PR — unrelated async facade route-catalog coverage gap, not touched by this change. ## AC honesty The bead's original AC (<700ms cold-CLI budget) is still not met. Remaining ~1.1s is dominated by the readiness/capability → `storage.repair` and `insights.archive`/`archive_rollups` chains, which prior investigation (recorded on the bead) already found to be a genuine, non-trivially-fixable pydantic-model-construction cost rather than an eager-import artifact — unchanged by this PR. This PR closes a previously undiscovered, cleanly avoidable slice (the interactive UI stack) found via a fresh importtime pass. Ref polylogue-8s70 Co-authored-by: Claude <[email protected]>
Summary
Cuts import-time tax on three CLI paths via lazy parent-package inits (PEP
562
__getattr__, matching the existing pattern inpolylogue/storage/__init__.py),plus a nix wrapper fix for a free-threaded-build environment leak found while
verifying the epic's own follow-up note.
Problem
ArchiveTierenum(
polylogue.storage.sqlite.archive_tiers.types) cost ~950ms-1.2s in a freshprocess, because Python must run the parent packages'
__init__.pyfirst, andpolylogue/storage/sqlite/__init__.pyeagerlyimported
SQLiteBackend(the whole 10-mixin async backend) at module level.polylogue status/agents status --format jsonpaid~1.5-2s of command-body import tax beyond
--help's ~0.4s budget, traced viacProfile to
storage.repair's own heavy import list (in particular a directsources.dispatchimport that pulled in the entire Google Drive downloadsubsystem) plus eager
operations/insightspackage inits reached throughreadiness/capability.py.polylogue-freethreaded(python3.14t) package's own PR (build: add python3.14t free-threaded package variant (-orjson +msgspec) #3162) already unset
PYTHONPATH/PYTHONHOME/etc in its wrapper, but verifying it under thisrepo's own ambient 3.13 devshell environment still reproduced
ModuleNotFoundError: No module named '_sysconfigdata__linux_x86_64-linux-gnu'on any command doing real work (
--version/--helpshort-circuit beforehitting the failing path, which is why the existing fix looked sufficient).
Solution
Import-tax fixes (each measured individually, isolated
python -c/-X importtime/ cProfile on this host):polylogue/storage/sqlite/__init__.py: deferSQLiteBackendvia PEP 562__getattr__.archive_tiers.typesimport: ~1000ms → ~104ms.polylogue/pipeline/ids.py:ParsedMessage/ParsedSession/etc aretype-only here; moved to
TYPE_CHECKINGso this pure hashing module stopsforcing the whole
polylogue.sourcespackage (incl. Drive subsystem) onevery caller.
polylogue/storage/repair.py: deferredsources.dispatch.detect_provider/is_stream_record_providerinto the 6 functions that actually call them(matching the file's own existing local-import convention for
sources.revision_backfill).import polylogue.storage.repair:~670ms → ~270ms.
polylogue/sources/__init__.py: lazy re-exports so importing a submodule(e.g.
parsers.base) no longer forces the Drive subsystem (tenacity,drive.auth,drive.gateway, ...) to load.polylogue/operations/__init__.py,polylogue/insights/__init__.py: samelazy-package-init pattern.
polylogue/operations/operation_status.py(new): splitOperationStatus(a plain
strEnum) out ofoperation_contract.py, whose other export(
OperationFollowUp) subclasses a pydanticSurfacePayloadModelthat pullsin ~280ms of archive/semantic pricing machinery.
readiness/capability.pyonly ever needed the enum.devtools/help_latency_probe.py+_migrate_tier.py: promotedops-maintenance-migrate-tierfrominformationaltorequired(~400ms, was ~1.04s against the 700ms budget).
Two additional micro-fixes were tried, measured as zero benefit, and
reverted rather than landed (extracting
date_from_isoout ofinsights/archive.py;TYPE_CHECKING-onlyArchiveCoverageInsightincli/shared/helper_summary.py) — both callers need the heavy module anywayvia a separate real dependency (
archive_rollups.py'sCostRollupInsight/etc).Nix wrapper fix: bisected the free-threaded-build failure with
env -i(adding exactly one inherited var back at a time) —
PYTHONPATHalone doesNOT reproduce it. The actual trigger is
_PYTHON_SYSCONFIGDATA_NAME, anixpkgs-set env var that Python's own
sysconfig._get_sysconfigdata_name()trusts over its own computation when present. The free-threaded build's real
sysconfigdata module carries a
tabiflag segment(
_sysconfigdata_t_linux_x86_64-linux-gnu), but a 3.13-devshell-derivedvalue of this env var (
_sysconfigdata__linux_x86_64-linux-gnu, not)doesn't match it. Added
--unset _PYTHON_SYSCONFIGDATA_NAME --unset _PYTHON_HOST_PLATFORMto all three wrapper sites inflake.nix.Verification
devtools verify --quick: green (format/lint/mypy/render-all-check),including the repo's own pre-push hook run.
devtools teston all touched files + their existing test coverage(
test_repair.py,test_archive_debt.py,test_specs.py,test_operation_contract.py,test_readiness_capability.py,test_drive_ops.py,pipeline/*,test_archive_query.py,test_insight_registry_runtime.py): 702 passed, 6 pre-existing failures intests/unit/pipeline/test_parsing_service.py(Mock(spec=Config)lacksdrive_config— verified identical on the pre-change base commit via adisposable
git worktree, unrelated:config.pyis untouched here).sources/__init__.pylazy-export commit misseddownload_drive_filesinthe
TYPE_CHECKINGblock, whichdevtools verify --quickcaught(
"object" not callableintest_drive_ops.py) — fixed in a follow-upcommit.
polylogue status --format json~2.05s → ~1.47s;agents status --format json~1.8s → ~1.3s;ops maintenance migrate-tier --help~1.04s→ ~0.40s.
nix build .#polylogueand.#polylogue-freethreadedboth succeed;with this session's actual ambient devshell env still exported, both
packages'
polylogue demo seed+polylogue demo verifycompleteend-to-end (16 sessions/62 messages/4 query hits) — the exact real-ingest
path that previously raised
ModuleNotFoundErroron the freethreaded build.Acceptance-criteria honesty
archive_tiers.typesimport lands at thesame order of magnitude as the bead's own reference baseline (~104ms vs
~90ms target);
ops-maintenance-migrate-tierpromoted torequired; noregression found.
status/agents statusunder the 700ms cold-CLI budget) is not met — both commands aremeaningfully faster (~28-30% cut) but still roughly 2x over budget. The
remaining cost is
insights.archive's own weight (pydanticCostRollupInsight/SessionCostInsight/ArchiveCoverageInsightmodelsplus
archive.semantic.pricing/content_projection), pulled in for realby session-tag-rollup computation
(
storage/insights/session/aggregates.py→archive_rollups.py) andarchive-coverage reporting — not an eager-import artifact fixable by moving
an import statement. Closing the remaining gap needs either restructuring
those pydantic model definitions or splitting session-tag-rollup
computation out of the status command's default path, which is a bigger,
riskier architectural change than this PR's scope. Recorded on the bead;
recommend a follow-up scoped specifically to that remaining cost.
fixed, and verified end-to-end for both packages.
Ref polylogue-h1wt, Ref polylogue-8s70, Ref polylogue-xikl
Co-Authored-By: Claude [email protected]