Skip to content

perf(startup): cut CLI import tax + scrub nix wrapper env leaks - #3166

Merged
Sinity merged 4 commits into
masterfrom
feature/perf/cli-import-tax-lazy-inits
Jul 19, 2026
Merged

Sinity merged 4 commits into
masterfrom
feature/perf/cli-import-tax-lazy-inits

Conversation

@Sinity

@Sinity Sinity commented Jul 19, 2026

Copy link
Copy Markdown
Owner

Summary

Cuts import-time tax on three CLI paths via lazy parent-package inits (PEP
562 __getattr__, matching the existing pattern in polylogue/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

  • polylogue-h1wt: importing a single ArchiveTier enum
    (polylogue.storage.sqlite.archive_tiers.types) cost ~950ms-1.2s in a fresh
    process, because Python must run the parent packages'
    __init__.py first, and polylogue/storage/sqlite/__init__.py eagerly
    imported SQLiteBackend (the whole 10-mixin async backend) at module level.
  • polylogue-8s70: polylogue status/agents status --format json paid
    ~1.5-2s of command-body import tax beyond --help's ~0.4s budget, traced via
    cProfile to storage.repair's own heavy import list (in particular a direct
    sources.dispatch import that pulled in the entire Google Drive download
    subsystem) plus eager operations/insights package inits reached through
    readiness/capability.py.
  • polylogue-xikl (nix wrapper follow-up): the 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 this
    repo'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/--help short-circuit before
    hitting 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: defer SQLiteBackend via PEP 562
    __getattr__. archive_tiers.types import: ~1000ms → ~104ms.
  • polylogue/pipeline/ids.py: ParsedMessage/ParsedSession/etc are
    type-only here; moved to TYPE_CHECKING so this pure hashing module stops
    forcing the whole polylogue.sources package (incl. Drive subsystem) on
    every caller.
  • polylogue/storage/repair.py: deferred sources.dispatch.detect_provider/
    is_stream_record_provider into 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: same
    lazy-package-init pattern.
  • 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.
  • devtools/help_latency_probe.py + _migrate_tier.py: promoted
    ops-maintenance-migrate-tier from informational to required
    (~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_iso out of
insights/archive.py; TYPE_CHECKING-only ArchiveCoverageInsight in
cli/shared/helper_summary.py) — both callers need the heavy module anyway
via a separate real dependency (archive_rollups.py's
CostRollupInsight/etc).

Nix wrapper fix: bisected the free-threaded-build failure with env -i
(adding exactly one inherited var back at a time) — PYTHONPATH alone does
NOT reproduce it. The actual trigger 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), but a 3.13-devshell-derived
value of this env var (_sysconfigdata__linux_x86_64-linux-gnu, no t)
doesn't match it. Added --unset _PYTHON_SYSCONFIGDATA_NAME --unset _PYTHON_HOST_PLATFORM to all three wrapper sites in flake.nix.

Verification

  • devtools verify --quick: green (format/lint/mypy/render-all-check),
    including the repo's own pre-push hook run.
  • devtools test on 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 in
    tests/unit/pipeline/test_parsing_service.py (Mock(spec=Config) lacks
    drive_config — verified identical on the pre-change base commit via a
    disposable git worktree, unrelated: config.py is untouched here).
  • Caught + fixed a real mypy regression before landing: the initial
    sources/__init__.py lazy-export commit missed download_drive_files in
    the TYPE_CHECKING block, which devtools verify --quick caught
    ("object" not callable in test_drive_ops.py) — fixed in a follow-up
    commit.
  • Timing deltas (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.
  • Nix: nix build .#polylogue and .#polylogue-freethreaded both succeed;
    with this session's actual ambient devshell env still exported, both
    packages' polylogue demo seed + polylogue demo verify complete
    end-to-end (16 sessions/62 messages/4 query hits) — the exact real-ingest
    path that previously raised ModuleNotFoundError on the freethreaded build.

Acceptance-criteria honesty

  • polylogue-h1wt: satisfied — archive_tiers.types import lands at the
    same order of magnitude as the bead's own reference baseline (~104ms vs
    ~90ms target); ops-maintenance-migrate-tier promoted to required; no
    regression found.
  • polylogue-8s70: not fully satisfied. The bead's own AC (status/agents status under the 700ms cold-CLI budget) is not met — both commands are
    meaningfully faster (~28-30% cut) but still roughly 2x over budget. The
    remaining cost is insights.archive's own weight (pydantic
    CostRollupInsight/SessionCostInsight/ArchiveCoverageInsight models
    plus archive.semantic.pricing/content_projection), pulled in for real
    by session-tag-rollup computation
    (storage/insights/session/aggregates.py → archive_rollups.py) and
    archive-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.
  • polylogue-xikl (nix wrapper note): satisfied — reproduced, root-caused,
    fixed, and verified end-to-end for both packages.

Ref polylogue-h1wt, Ref polylogue-8s70, Ref polylogue-xikl

Co-Authored-By: Claude [email protected]

Sinity and others added 4 commits July 19, 2026 20:44
…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

gitguardian Bot commented Jul 19, 2026

Copy link
Copy Markdown

⚠️ GitGuardian has uncovered 1 secret following the scan of your pull request.

Please consider investigating the findings and remediating the incidents. Failure to do so may lead to compromising the associated services or software components.

🔎 Detected hardcoded secret in your pull request
GitGuardian id GitGuardian status Secret Commit Filename
34951478 Triggered Authentication Tuple a5b3220 polylogue/sources/init.py View secret
🛠 Guidelines to remediate hardcoded secrets
  1. Understand the implications of revoking this secret by investigating where it is used in your code.
  2. Replace and store your secret safely. Learn here the best practices.
  3. Revoke and rotate this secret.
  4. 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


🦉 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.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@coderabbitai

coderabbitai Bot commented Jul 19, 2026

Copy link
Copy Markdown

Warning

Review limit reached

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

Next review available in: 44 minutes

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

How can I continue?

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

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: f367ad94-fe6f-4d3a-9604-28f10c085c64

📥 Commits

Reviewing files that changed from the base of the PR and between 3b62835 and e4d76c0.

📒 Files selected for processing (14)
  • devtools/help_latency_probe.py
  • docs/plans/topology-target.yaml
  • docs/topology-status.md
  • flake.nix
  • polylogue/cli/commands/maintenance/_migrate_tier.py
  • polylogue/insights/__init__.py
  • polylogue/operations/__init__.py
  • polylogue/operations/operation_contract.py
  • polylogue/operations/operation_status.py
  • polylogue/pipeline/ids.py
  • polylogue/readiness/capability.py
  • polylogue/sources/__init__.py
  • polylogue/storage/repair.py
  • polylogue/storage/sqlite/__init__.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/perf/cli-import-tax-lazy-inits

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

❤️ Share

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

@Sinity

Sinity commented Jul 19, 2026

Copy link
Copy Markdown
Owner Author

GitGuardian false positive triage: the flagged "Authentication Tuple" at polylogue/sources/__init__.py (the "DriveAuthError": (".drive.types", "DriveAuthError") dict entry in the lazy __getattr__ re-export table) is a 2-tuple of (module_path, attr_name) strings, not a credential. The detector appears to be pattern-matching a 2-element tuple literal near the word "Auth" (from the real class name DriveAuthError). No secret present.

@Sinity
Sinity merged commit a46fc95 into master Jul 19, 2026
2 of 3 checks passed
@Sinity
Sinity deleted the feature/perf/cli-import-tax-lazy-inits branch July 19, 2026 18:50
Sinity added a commit that referenced this pull request Jul 27, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant