Skip to content

perf(cli): cut cold-start import tax on drift-marker and query paths - #3507

Merged
Sinity merged 1 commit into
masterfrom
feature/perf/cli-import-tax
Aug 1, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/perf/cli-import-tax

Conversation

@Sinity

@Sinity Sinity commented Aug 1, 2026

Copy link
Copy Markdown
Owner

Summary

Removes three eager-import chains that taxed every cold polylogue invocation: the polylogue.schemas package init (whole provider-parser universe + jsonschema, ~0.9s), revision_governance's module-level sources.dispatch import (write-path helper taxing read paths), and the root-callback drift marker's import of cli.commands.status (readiness/repair stack, ~1.2s) for what is a self-contained ops.db read.

Problem

Measured 2026-08-01 (warm pyc, empty archive, so numbers are pure fixed overhead, python -X importtime + cProfile attribution): polylogue find 2.87s, import --help 1.78s, config show 1.78s, vs --help 0.55s. Attribution:

  • polylogue.schemas/__init__ eagerly imported validator → archive.raw_payload.decode → sources.dispatch (every provider parser + pydantic models) + jsonschema: ~0.9s, paid by anything importing any archive_tiers submodule (the package init chains through ops.py → drift_sentinel, which itself is pure stdlib).
  • storage/sqlite/archive_tiers/revision_governance.py imported sources.dispatch at module top for merge_parsed_session_chunks, used only in three raw-replay write paths.
  • click_app._emit_schema_drift_marker (runs in the root callback for every command, including nested --help) imported cli.commands.status (~1.2s readiness/repair stack) to call _schema_drift_status, whose real dependencies are sqlite3 + one lazy ops_write function.

Solution

  • polylogue/schemas/__init__.py: PEP 562 lazy __getattr__; public names (SchemaValidator, ValidationResult, validate_provider_export) unchanged.
  • revision_governance.py: function-local merge_parsed_session_chunks imports at the three write-path call sites; ParsedSession under TYPE_CHECKING (annotation-only).
  • schema_drift_status extracted (hard move, no shim) from cli/commands/status.py to new polylogue/insights/schema_drift.py — insights because CLI must route through insights/operations/api per docs/plans/layering.yaml; click_app, daemon/health.py, status.py, and the three test files repointed. Three stale layering-baseline entries pruned (ratchet down 308→305). Degrade-loudly allowlist entries moved with the function (same already-typed {"available": False, "reason": …} signal, unchanged behavior).
  • core/dates.py: dateparser (~0.26s, timezone tables) deferred to first parse_date call.
  • New contract test test_drift_marker_import_path_stays_light asserts (in a subprocess) that importing insights.schema_drift + schemas.drift_sentinel + revision_governance never loads sources.dispatch / schemas.validator / readiness / storage.repair / cli.commands.status.

Anti-vacuity: the contract test exercises the real production import graph; re-adding any of the removed eager imports (verified by simulating import polylogue.cli.commands.status in the probe: detects readiness, storage.repair, cli.commands.status) fails it. The moved schema_drift_status is exercised by the existing drift-status/marker/health tests against real ops.db fixtures.

Measured results (min of 3, warm pyc, same host)

command before after
import --help 1.78s 0.64s
config show 1.78s 0.58s
demo --help 2.57s 2.08s
find <q> --limit 5 2.87s 2.63s
polylogue.api import 2.36s 1.70s

The residual find cost is polylogue.api's diffuse pydantic model construction, imported before the daemon fast-path attempt — deferring that is a structural follow-up (bead filed from this lane).

Verification

  • devtools verify --quick — all steps exit 0 (format, lint, mypy, render-check, layering, degrade-loudly, closure-matrix, hash-boundary-census, schema-versioning, promotion audit).
  • devtools test tests/unit/cli/test_schema_drift_marker.py tests/unit/cli/test_schema_drift_status.py tests/unit/daemon/test_schema_drift_health_check.py — 15 passed (incl. new contract test).
  • devtools test tests/unit/schemas/test_drift_sentinel.py tests/unit/cli/test_click_app.py tests/unit/cli/commands/test_status.py — 190 passed.
  • devtools test tests/unit/storage/test_revision_replay.py tests/unit/core/test_dates.py — 34 passed; test_source_laws.py::test_claude_code_stream_chunk_merge_preserves_git_branch_from_either_chunk passed.
  • Not run: full suite (per-PR CI skips heavy tests; testmon unseeded in this worktree — affected files covered by the focused runs above).

🤖 Generated with Claude Code

https://claude.ai/code/session_01P7dQJSbhvx7LSu5PW9Ns9S

@coderabbitai

coderabbitai Bot commented Aug 1, 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: 37 minutes

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

How can I continue?

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

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

How do review limits work?

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

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

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 85c494d1-08fe-45d7-9ca3-ea1cec8aefce

📥 Commits

Reviewing files that changed from the base of the PR and between 5b0014c and ae57b91.

📒 Files selected for processing (13)
  • docs/plans/degrade-loudly-allowlist.yaml
  • docs/plans/layering-surface-baseline.json
  • docs/plans/topology-target.yaml
  • polylogue/cli/click_app.py
  • polylogue/cli/commands/status.py
  • polylogue/core/dates.py
  • polylogue/daemon/health.py
  • polylogue/insights/schema_drift.py
  • polylogue/schemas/__init__.py
  • polylogue/storage/sqlite/archive_tiers/revision_governance.py
  • tests/unit/cli/test_schema_drift_marker.py
  • tests/unit/cli/test_schema_drift_status.py
  • tests/unit/daemon/test_schema_drift_health_check.py

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

❤️ Share

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

Problem: every polylogue invocation paid heavy imports before doing any
work (measured 2026-08-01, warm pyc, empty archive so numbers are pure
overhead): `polylogue find` 2.87s, `import --help` 1.78s, `config show`
1.78s, vs `--help` 0.55s. Three eager-import chains dominated:
- polylogue.schemas/__init__ eagerly imported validator, dragging the
  whole provider-parser universe (raw_payload.decode -> sources.dispatch)
  plus jsonschema (~0.9s) into anything touching an archive-tier module.
- revision_governance imported sources.dispatch at module level for one
  write-path-only helper (merge_parsed_session_chunks), taxing read paths.
- the root-callback drift marker imported cli.commands.status (readiness/
  repair stack, ~1.2s) just to run a self-contained ops.db read.

What changed:
- polylogue/schemas/__init__.py: PEP 562 lazy attribute resolution.
- revision_governance: merge_parsed_session_chunks imported at the three
  write-path call sites; ParsedSession moved under TYPE_CHECKING.
- schema_drift_status extracted from cli/commands/status.py into new
  light module polylogue/insights/schema_drift.py (CLI routes through
  insights per layering rules); click_app, daemon/health, status and
  tests repointed. Three stale layering-baseline entries pruned (ratchet).
- core/dates.py: dateparser (0.26s timezone tables) deferred to first
  parse_date call.
- New import-weight contract test asserts the drift-marker path never
  pulls sources.dispatch/schemas.validator/readiness/storage.repair.

Measured after (min of 3, warm pyc): import --help 1.78s -> 0.64s,
config show 1.78s -> 0.58s, demo --help 2.57s -> 2.08s, find 2.87s ->
2.63s (the residual find cost is polylogue.api's pydantic model
construction, 2.36s -> 1.70s here; deferring api until the daemon
fast-path misses is filed as follow-up).

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01P7dQJSbhvx7LSu5PW9Ns9S
@Sinity
Sinity force-pushed the feature/perf/cli-import-tax branch from 01cdad4 to ae57b91 Compare August 1, 2026 12:01
@Sinity
Sinity merged commit 055549b into master Aug 1, 2026
3 checks passed
@Sinity
Sinity deleted the feature/perf/cli-import-tax branch August 1, 2026 12:02
Sinity added a commit that referenced this pull request Aug 1, 2026
## Summary

Wires `devtools/checkout_guard.py`'s worktree-import protection into the
installed `polylogue`/`plg` console scripts, which were the one entry
point a cold agent (or an MCP/daemon launcher shelling out to
`polylogue`) is most likely to invoke directly, and the one entry point
the guard didn't cover.

## Problem

`devtools/checkout_guard.py`'s `assert_polylogue_matches_checkout`
closes the shared-venv worktree-import hazard (2026-07-30/31: a linked
git worktree without its own `.venv` reuses the main checkout's editable
install, so `import polylogue` silently resolves to a *different*
checkout's code) for `devtools/__main__.py`, `devtools verify`/`devtools
test`, and `tests/conftest.py`. It was never wired into
`polylogue/cli/click_app.py`.

Confirmed live: an audit lane running `polylogue --version` from inside
a `.claude/worktrees/<id>` linked worktree reported the *main
checkout's* dirty commit, while `git rev-parse HEAD` in that same
worktree showed a different commit — every `polylogue
find/status/demo/...` command in that session had silently exercised the
wrong checkout's code and schema expectations, with nothing in the CLI's
own output flagging the mismatch.

## Solution

- `devtools/checkout_guard.py`: new `find_git_worktree_root(start)` — a
pure filesystem `.git`-entry walk up from `start`, no subprocess, cheap
enough for every invocation. Documented in the module docstring
alongside the existing wiring list, explaining why this entry point
needs a different anchor than the others.
- `polylogue/cli/click_app.py`: new `_guard_checkout_or_exit()`, called
first thing in `main()`. Unlike the existing call sites (whose own
`__file__` is a trustworthy anchor because they're only ever reached via
a real path on `sys.path`), `click_app.py`'s own `__file__` *is* the
resolved `polylogue` package — if the hazard already occurred, this file
is already the wrong checkout's copy, so it can't self-certify. The
trustworthy anchor is the process's cwd instead:
`find_git_worktree_root(Path.cwd())` names the checkout the operator
actually intended (they `cd`'d into the worktree and ran `polylogue ...`
there). No-ops when cwd has no git ancestry (a real installed-tool
invocation) or `POLYLOGUE_ALLOW_WORKTREE_ESCAPE=1` is set — reusing the
existing bypass convention from the worktree-escape pre-commit hook.
- `tests/unit/cli/test_click_app_main.py`: three regression tests —
guard fires on mismatch (exit 125, no stdout produced), no-ops with no
git ancestry, bypassed by `POLYLOGUE_ALLOW_WORKTREE_ESCAPE=1`.

Cold-start cost: `python -X importtime -m polylogue --help` shows
`devtools.checkout_guard` at 508us cumulative against a ~580ms total
`--help` invocation — negligible, relevant because #3507 (merged the
same day) specifically cut CLI cold-start import tax and I rebased onto
it before finishing this change.

## Verification

- `devtools test tests/unit/cli/test_click_app_main.py
tests/unit/devtools/test_checkout_guard.py` — 15 passed (8 + 7,
including the 3 new tests).
- `devtools verify --quick` — exit 0 (format, lint, mypy, render-check,
layering, degrade-loudly, closure-matrix, hash-boundary-census,
schema-versioning, promotion audit); also ran again automatically via
the pre-push hook after rebasing onto origin/master.
- `devtools verify` (testmon default) refused: pytest-testmon is
unseeded in this worktree (fresh checkout that never ran
`--seed-testmon`). Not run given the seeding cost for a two-file change;
the focused runs above cover every line touched.
- Manual repro check: ran the (unpatched, main-checkout) installed
console script from this worktree's cwd and confirmed it still silently
resolves to the main checkout's code — matches the bug report exactly,
and is exactly the case this PR's `click_app.py:main()` now catches once
the fix is on the running checkout.

## AC matrix

- "Wire assert_polylogue_matches_checkout (or equivalent) into polylogue
CLI's entry point" — satisfied (`click_app.py:main()` →
`_guard_checkout_or_exit()`).
- "Match the existing guard's error/exit-code contract" — satisfied:
same `CheckoutImportMismatchError` type, same stderr message shape, same
exit code 125.
- "Gate so it only fires when a `.git` worktree is detected and
`POLYLOGUE_ALLOW_WORKTREE_ESCAPE` is unset" — satisfied.
- "Regression test proving the guard fires (mock/simulate)" — satisfied,
following `tests/unit/devtools/test_checkout_guard.py`'s own monkeypatch
pattern.
- "Verify no meaningful cold-start regression" — satisfied, measured
negligible (~0.5ms of ~580ms).

## Anti-vacuity

Production entry point exercised: `polylogue.cli.click_app.main()`, the
function bound to the `polylogue`/`plg` console-script entry points in
`pyproject.toml`. Mutation that breaks the test: removing the
`_guard_checkout_or_exit()` call from `main()` (or removing the
`assert_polylogue_matches_checkout` call from inside that helper) makes
`test_main_refuses_on_checkout_mismatch` fail — `SystemExit(125)` would
never be raised and the (mocked) mismatch would go undetected, silently
falling through to normal command dispatch.

Ref polylogue-6mgg

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

* **New Features**
* Added a safety check to ensure the `polylogue` command runs from the
same Git checkout where it was installed.
* Commands now stop with a clear error and exit status 125 when a
checkout mismatch is detected.
* The check is skipped outside Git repositories and can be explicitly
bypassed with `POLYLOGUE_ALLOW_WORKTREE_ESCAPE=1`.

* **Bug Fixes**
* Prevents commands from unintentionally running against a different
working tree.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude <[email protected]>
Sinity added a commit that referenced this pull request Aug 1, 2026
…tore

Problem: a daemon-served `find` paid the full ~1.7-2.8s polylogue.api
import cost (pydantic viewport/surface models, storage repository
mixins) even though the daemon served the request over UDS and the CLI
never touched ArchiveStore, the Polylogue facade, or any local-execution
renderer. Three eager-import sources compounded:

1. cli/query.py imported `polylogue.api.sync.bridge.run_coroutine_sync`
   at module scope. Importing any submodule of `polylogue.api` forces
   Python to execute polylogue/api/__init__.py first, even though the
   sync bridge itself only needs asyncio/threading.
2. cli/archive_query.py imported ArchiveStore, surfaces.payloads,
   search_providers, archive.stats, and the attached-units/unit-results
   helpers at module top -- all local-execution-only, but paid on every
   import of the module regardless of whether the daemon fast path
   (_try_emit_daemon_session_page) ever reaches the local-execution
   fallback.
3. AppEnv.config/.runtime routed through AppEnv.services (_lazy_services
   -> polylogue.services -> storage.repository -> storage.sqlite),
   which imports the full repository/backend stack merely to hand back
   a Config projection RuntimeServices.__post_init__ already computed
   from runtime.as_config(). load_effective_config(env) is the first
   thing archive_query.py's main function calls, before the daemon-try.

Solution:
- New polylogue/core/async_bridge.py holds the actual run_coroutine_sync
  implementation (dependency-free). polylogue/api/sync/bridge.py now
  re-exports it for existing callers that already depend on the
  Polylogue facade; cli/query.py imports the light module directly.
- archive_query.py's local-execution-only imports move under
  TYPE_CHECKING (annotation-only uses, safe under `from __future__
  import annotations`) plus function-local imports at each real call
  site (mutation emitters, vector search, unit-source rows, attached
  units, cursor encode/decode, session-detail rendering).
- AppEnv.config/.runtime return `self._runtime`/`self._runtime.as_config()`
  directly when `.services` was never built, instead of forcing it.
  click_app.py already constructs `AppEnv(runtime=runtime, ...)`, so
  this is the real production shape, not a synthetic corner case.

Verification (in-process harness driving execute_query_request through a
mocked daemon-success response, since this workstation's live
`polylogued` daemon and archive make CLI-subprocess timing unsafe to
reproduce here -- see PR body):
  before: total 2.88s, heavy modules imported: polylogue.api=True,
    archive_tiers.archive=True, archive_tiers.write=True,
    surfaces.payloads=True, search_providers=True
  after:  total 1.31s, heavy modules imported: polylogue.api=False,
    archive_tiers.archive=False, archive_tiers.write=False,
    surfaces.payloads=False, search_providers=True (structural
    dependency of archive.query.expression, shared by both paths,
    out of scope here)

New tests:
- tests/unit/cli/test_daemon_fastpath_import_cost.py: subprocess-based
  behavioral contract (pattern from #3507's
  test_drift_marker_import_path_stays_light) asserting the forbidden
  modules never land in sys.modules after a mocked daemon-success query.
- tests/unit/cli/test_app_env_config_fastpath.py: AppEnv.config/.runtime
  fast-path + explicit-services backward-compat + no-runtime-no-services
  error path.

Ref polylogue-g3jk

Co-Authored-By: Claude <[email protected]>
Sinity added a commit that referenced this pull request Aug 1, 2026
…tore (#3517)

## Summary

A daemon-served `find` (or any query command the daemon can serve) paid
the
full cold-start import cost of `polylogue.api`, `ArchiveStore`,
`surfaces.payloads`, and `search_providers` even though the daemon
served the
request over UDS and none of those modules were ever touched. This PR
defers
all of them to the local-execution fallback path, and fixes a related
`AppEnv.config`/`.runtime` inefficiency that forced the same cost via a
different route.

## Problem

Evidence (bead polylogue-g3jk, filed from PR #3507's perf audit — #3507
was
still open/unmerged at the time of this work, so this branch targets
current
`master` directly and does not depend on it):

- Cold `polylogue find <q>` paid ~2s beyond `--help`'s baseline even
when a
  daemon served the request over UDS in ~50ms — the daemon fast path
(`_try_emit_daemon_session_page` in `cli/archive_query.py`) saved query
  *execution* but not *import tax*.
- Three compounding eager-import sources, found by tracing the actual
call
  graph (not guessing):
1. `cli/query.py` imported
`polylogue.api.sync.bridge.run_coroutine_sync` at
module scope. Importing any submodule of `polylogue.api` forces Python
to
execute `polylogue/api/__init__.py` first (the whole `Polylogue` facade
—
pydantic viewport/surface models, storage repository mixins), even
though
     the sync bridge itself only needs `asyncio`/`threading`.
2. `cli/archive_query.py` imported `ArchiveStore`, `surfaces.payloads`,
`search_providers`, `archive.stats`, and the attached-units/unit-results
     helpers at module top — all exclusively used by the local-execution
fallback, but paid on every *import* of the module regardless of whether
     the daemon fast path ever reaches that fallback.
  3. `AppEnv.config`/`.runtime` routed through `AppEnv.services`
     (`_lazy_services` → `polylogue.services` → `storage.repository` →
`storage.sqlite`), which imports the full repository/backend stack
merely
to hand back a `Config` projection `RuntimeServices.__post_init__` had
already computed from `runtime.as_config()`.
`load_effective_config(env)`
is the *first* thing `_execute_archive_query_stdout` calls, before the
daemon-try — this was actually the single largest remaining cost after
fixing (1) and (2), found by tracing `sys.modules` deltas through a
mocked
     daemon-success call.

## Solution

- New `polylogue/core/async_bridge.py` holds the real
`run_coroutine_sync`
  implementation (dependency-free: only `asyncio`/`threading`).
`polylogue/api/sync/bridge.py` now re-exports it for existing callers
that
  already depend on the `Polylogue` facade (Lynchpin, MCP, etc. are
  unaffected); `cli/query.py` imports the light module directly.
- `archive_query.py`'s local-execution-only imports move under
  `TYPE_CHECKING` (safe because they're annotation-only under `from
__future__ import annotations`) plus function-local imports at each real
  call site: mutation emitters (`_emit_mutation`/`_emit_user_mutations`/
  `_emit_delete`), vector search (`_query_hits`), unit-source rows
(`_emit_unit_source_rows`/`_unit_source_session_filters`), attached
units
  (`_inject_attached_units`), cursor encode/decode (`_decode_cursor`/
  `_build_cursor`), session-detail rendering (`_emit_stream`,
  `_session_summary_text`), and list/search row payloads
  (`_summary_payload`/`_hit_payload`).
- `AppEnv.config`/`.runtime` (`cli/shared/types.py`) return
`self._runtime`/`self._runtime.as_config()` directly when `.services`
was
  never built, instead of forcing it. `click_app.py` already constructs
`AppEnv(runtime=runtime, ...)` with no explicit `services=`, so this is
the
real production shape every CLI invocation hits, not a synthetic corner
  case — verified by grepping every `AppEnv(` construction site.

**Non-goals / residual cost**:
`archive.query.expression`/`archive.query.spec`
(the query DSL compiler) still cost real import time (`dateparser`,
`polylogue.archive.viewport.models` pydantic classes,
`polylogue.storage.search_providers`)
— these are used identically by both the daemon and local-execution
paths to
compile the query before either path runs, so deferring them wouldn't be
daemon-fast-path-specific and is out of scope here. This is the "diffuse
pydantic model construction, no single lazy-import fix left" the bead
already
flagged for the query-compilation layer specifically (as opposed to the
local-execution layer this PR addresses).

## Verification

**Measurement method note**: this workstation runs a live production
`polylogued` daemon against a real personal archive (`systemd --user
polylogued.service`). Two attempts at live-CLI/live-daemon E2E timing
during
this work both leaked real archive content into command output because
(a)
the daemon UDS socket path (`$XDG_RUNTIME_DIR/polylogue/daemon.sock`) is
machine-wide, not archive-root-scoped, so a second daemon on a custom
archive
root never actually gets used — the CLI always finds the live daemon's
socket; and (b) even explicit `--no-daemon` local execution through the
real
`polylogue` binary did not honor `POLYLOGUE_ARCHIVE_ROOT` and hit the
live
archive. Both are pre-existing, separate bugs (matching/extending the
already-tracked polylogue-z9gh / polylogue-tas4 "two surfaces disagree
about
FTS readiness" finding — worth a dedicated follow-up, since (b) is worse
than
previously documented: it reproduces even without a daemon involved). No
writes occurred (`find` is read-only) and the live daemon/archive were
unaffected (verified via `systemctl --user status polylogued.service`
before/after — same PID, same start time throughout). All further
measurement in this PR uses an in-process harness
(`execute_query_request` driven directly against a `tmp_path` archive
with a
monkeypatched `_fetch_daemon_sessions_payload`) plus the existing
`tests/unit/cli/test_daemon_golden_parity.py`
real-UDS-daemon-in-a-thread
pattern — never the live daemon or a shell subprocess against ambient
env
vars.

**Before/after** (in-process harness, `git apply -R`/`git apply`
roundtrip on
this exact diff to get a clean A/B on identical hardware):

| | before | after |
|---|---|---|
| total wall time | 2.88s | 1.31s |
| `polylogue.api` imported | True | **False** |
| `archive_tiers.archive` imported | True | **False** |
| `archive_tiers.write` imported | True | **False** |
| `surfaces.payloads` imported | True | **False** |
| `search_providers` imported | True | True (unavoidable, see Non-goals)
|

**Commands run:**
- `python -m mypy polylogue tests` → `Success: no issues found in 2263
source files`
- `python -m ruff check polylogue tests` / `ruff format --check` → clean
- `python -m devtools test
tests/unit/cli/test_daemon_fastpath_import_cost.py
tests/unit/cli/test_app_env_config_fastpath.py
tests/unit/cli/test_archive_query.py tests/unit/api/test_sync_bridge.py`
→ `111 passed`
- `python -m devtools test tests/unit/cli/test_daemon_golden_parity.py`
(real UDS daemon in a background thread, byte-identical
direct-vs-daemon-proxied output contract) → `3 passed`
- `python -m devtools render topology-projection` (required: new
`polylogue/core/async_bridge.py` module) → committed
`docs/plans/topology-target.yaml`
- `python -m devtools verify --quick` → `exit_code: 0` (ran twice, once
locally and once via the pre-push hook)

**Anti-vacuity**: reverted this exact diff (`git apply -R`) and reran
both new
tests — all three assertions fail as expected:
- `test_daemon_served_query_does_not_import_heavy_local_execution_stack`
→
`heavy modules leaked into the daemon fast path:
polylogue.api,polylogue.services,polylogue.storage.repository,polylogue.storage.sqlite.archive_tiers.archive,polylogue.storage.sqlite.archive_tiers.write,polylogue.surfaces.payloads`
- `test_config_returns_runtime_projection_without_building_services` /

`test_runtime_property_returns_the_same_object_without_building_services`
→
`AssertionError: assert RuntimeServices(...) is None` (i.e. `.services`
got
  built when it shouldn't have)

The production caller exercised is the real dispatch chain:
`click_app.py`'s
`_handle_query_mode` → `cli/query.py:execute_query_request` →
`cli/archive_query.py:execute_archive_query` →
`_try_emit_daemon_session_page`, with `AppEnv` constructed exactly as
`click_app.py` constructs it (`runtime=`, no explicit `services=`).

## AC matrix

| Acceptance criterion | Status |
|---|---|
| Investigate exact import chain for `polylogue.api` eager import |
Satisfied — traced to `cli/query.py`'s module-level
`polylogue.api.sync.bridge` import |
| Defer `polylogue.api` import until after the daemon fast-path decision
| Satisfied — `core/async_bridge.py` split, `query.py` no longer touches
`polylogue.api` |
| Restructure query-mode dispatch (light preflight module vs. full local
executor) | Partially satisfied via a different mechanism — rather than
physically splitting `archive_query.py` into two modules, its
local-execution-only imports were converted to `TYPE_CHECKING` +
function-local imports at their call sites. Same runtime effect (heavy
modules never load unless the miss path executes) without the larger
risk of a structural file split mid-function (the fast-path check is
threaded through a 700-line function that also does shared query-spec
compilation). |
| Target ~0.7-0.9s daemon-served cold `find` | Not fully met — measured
1.31s in the in-process harness. The residual cost is
`archive.query.expression`/`archive.query.spec` (dateparser, viewport
pydantic models), used identically by both daemon and local paths for
query-DSL compilation, out of scope for a daemon-fast-path-specific fix.
Filing a follow-up for that layer (see below). |
| Real before/after timing | Satisfied, via the safe in-process harness
described above (live-CLI/live-daemon timing was unsafe on this host —
see Verification) |
| Import-graph contract test, anti-vacuity proof | Satisfied —
`test_daemon_fastpath_import_cost.py` +
`test_app_env_config_fastpath.py`, both verified to fail when the fix is
reverted |

## Follow-ups (not filed as beads from this lane — bd is read-only here;
reporting to the coordinator)

- The `--no-daemon` / real-archive-root env-var-precedence bug
reproduced
  during this work (real archive content served even with an explicit
`--no-daemon` flag and a different `POLYLOGUE_ARCHIVE_ROOT`) deserves a
  dedicated investigation — it's more severe than the previously tracked
  polylogue-z9gh/polylogue-tas4 daemon-only finding.
- `archive.query.expression`/`archive.query.spec`'s own import cost
(dateparser, viewport pydantic models) is a separate, larger effort
(would
  need `polylogue.core.dates`/`archive.viewport.viewports` to defer
`dateparser`/pydantic construction) if the ~0.7-0.9s target is still
wanted.

Ref polylogue-g3jk

---------

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