Skip to content

fix(devtools): bound workload diagnostics and cleanup pytest temps - #2163

Merged
Sinity merged 2 commits into
masterfrom
feature/fix/memory-diagnostics-cleanup
Jun 19, 2026
Merged

Sinity merged 2 commits into
masterfrom
feature/fix/memory-diagnostics-cleanup

Conversation

@Sinity

@Sinity Sinity commented Jun 19, 2026 •

Copy link
Copy Markdown
Owner

Summary

Bound the default daemon workload diagnostic path and made pytest temp cleanup supervisor-owned after managed runs. The default workload probe now returns promptly on the real archive instead of hanging on full SQLite/FTS scans, while expensive integrity and exact reconciliation checks remain available through explicit flags.

Problem

Two memory/runtime issues were observable locally:

  • polylogue ops diagnostics workload --json could sit resident around a few hundred MiB and emit no JSON on the live archive. Stack dumps showed it blocked in default table-count/integrity/readiness scans: messages_fts_data, PRAGMA quick_check, generated blocks.search_text reconciliation, and actions counts.
  • Broad pytest seed/full lanes can use tmpfs for speed, but xdist runs intentionally skipped pytest_sessionfinish cleanup. A successful run could leave a multi-GiB /dev/shm/pytest-polylogue-* basetemp until another pytest startup sweep or manual cleanup.

Solution

  • Removed FTS internal messages_fts_data from workload boundary/tier counts and reports messages_fts_docsize instead.
  • Changed archive tier integrity from implicit PRAGMA quick_check to default integrity: not_checked, with --integrity-check for explicit expensive runs.
  • Changed derived readiness to use cheap default FTS/action evidence and added --exact-derived-counts for full reconciliation scans.
  • Exposed both flags through polylogue ops diagnostics workload.
  • Added cleanup_managed_pytest_basetemp() in the verify supervisor so managed per-run basetemps are reclaimed after pytest exits, including xdist seed/full runs.
  • Updated docs and generated AGENTS.md for the new diagnostic contract.

Verification

  • devtools test tests/unit/devtools/test_daemon_workload_probe.py tests/unit/devtools/test_verify.py::test_cleanup_managed_pytest_basetemp_removes_run_root tests/unit/devtools/test_verify.py::test_cleanup_managed_pytest_basetemp_keeps_seed_cache tests/unit/test_pytest_temp_policy.py -q — 23 passed.
  • polylogue ops diagnostics workload --help — shows --integrity-check and --exact-derived-counts.
  • Live archive probe: timeout 30s nix develop --command python -m devtools.daemon_workload_probe --json returned status 0 in 3.132s, emitted 18,524 bytes, ok=True, integrity=not_checked, no messages_fts_data counts.
  • devtools render all --check — clean after refreshing .cache/site.
  • devtools verify --quick — exit 0.
  • devtools verify --seed-testmon --skip-slow — 11,507 passed, 1 xfailed; peak pytest PSS 3,089.6 MiB; /dev/shm returned to seeded caches only afterward.
  • devtools verify — 7 affected tests passed; peak pytest PSS 122.4 MiB.

Summary by CodeRabbit

  • New Features

    • Added --integrity-check and --exact-derived-counts flags to the diagnostics workload CLI command for optional deep integrity validation and exact derived-counts reconciliation.
  • Documentation

    • Clarified that expensive integrity and reconciliation checks are opt-in via new command flags.
  • Tests

    • Added test coverage for new diagnostic flags and cleanup behavior.

Problem: workload diagnostics could hang on large archives by running unbounded SQLite counts and integrity checks before emitting any JSON. Broad xdist test runs could also leave managed tmpfs basetemps resident until a later pytest startup sweep, pinning GiBs in /dev/shm after successful runs.

What changed: the workload probe no longer counts FTS internal segment tables, skips SQLite quick_check and exact derived reconciliation by default, and exposes --integrity-check / --exact-derived-counts for explicit expensive diagnostics. The verify supervisor now removes managed per-run pytest basetemps after pytest exits, including xdist seed/full lanes.

Verification: devtools test tests/unit/devtools/test_daemon_workload_probe.py tests/unit/devtools/test_verify.py::test_cleanup_managed_pytest_basetemp_removes_run_root tests/unit/devtools/test_verify.py::test_cleanup_managed_pytest_basetemp_keeps_seed_cache tests/unit/test_pytest_temp_policy.py -q; devtools verify --quick; devtools verify --seed-testmon --skip-slow; devtools verify. Live workload probe against the real archive returned ok JSON in 3.1s; /dev/shm returned to seeded caches only after the tmpfs seed run.
github-actions Bot pushed a commit that referenced this pull request Jun 19, 2026
@coderabbitai

coderabbitai Bot commented Jun 19, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

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

More reviews will be available in 50 minutes and 56 seconds. Learn how PR review limits work.

Your organization has used up its prepaid credits, and credit purchases are no longer available. Enable the review add-on in the billing tab to keep reviews running — you're only billed for reviews past your plan's rate limits ($0.25/file).

⌛ How to resolve this issue?

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

🚦 How do rate limits work?

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

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, the refill rate gradually slows as usage increases. The highest same-day bursts are limited more strictly.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 8a390a40-5870-4c32-b0d1-90c2c98e37b4

📥 Commits

Reviewing files that changed from the base of the PR and between 1f9bd5f and e4ff032.

📒 Files selected for processing (1)
  • tests/baselines/showcase/help-ops-diagnostics-workload.txt
📝 Walkthrough

Walkthrough

Two independent changes: (1) the daemon workload probe gains optional --integrity-check and --exact-derived-counts flags that gate expensive PRAGMA quick_check and exact FTS/derived-count reconciliation, adding new evidence fields to archive-tier snapshots; (2) a cleanup_managed_pytest_basetemp helper is added to delete the managed per-run pytest basetemp directory after each verify run.

Changes

Daemon workload probe optional integrity and exact-counts modes

Layer / File(s) Summary
Boundary and observability table list adjustments
devtools/daemon_workload_probe.py
Removes messages_fts_data from _BOUNDARY_TABLES and inserts messages_fts_docsize into archive-tier observable tables.
Core probe helpers: presence count, integrity, exact derived counts
devtools/daemon_workload_probe.py
Adds _presence_count helper; updates _archive_single_tier_state to conditionally run PRAGMA quick_check; updates _archive_derived_readiness and _archive_derived_counts to optionally compute exact text_block_count, messages_fts_count, action_count_exact, and messages_fts_exact_counts.
Surface readiness and evidence payload updates
devtools/daemon_workload_probe.py
Widens _archive_surface_readiness counts typing to dict[str, Any]; updates search surface blocker and evidence to use messages_fts_exact_counts; adds action_count_exact to tool_usage evidence.
_archive_tier_state and probe() public API wiring
devtools/daemon_workload_probe.py
Updates _archive_tier_state signature and threads integrity_check / exact_derived_counts through to sub-functions; extends public probe() to accept and forward these parameters.
CLI flags, docs, and tests
polylogue/cli/commands/diagnostics.py, AGENTS.md, docs/internals.md, tests/unit/devtools/test_daemon_workload_probe.py
Adds --integrity-check and --exact-derived-counts Click flags wired into argv; updates AGENTS.md and docs/internals.md; extends unit tests to assert default False and expensive True values for new evidence fields and updated FTS table coverage.

Managed pytest basetemp cleanup

Layer / File(s) Summary
cleanup_managed_pytest_basetemp implementation and invocation
devtools/verify_runs.py, devtools/verify.py
Adds cleanup_managed_pytest_basetemp (validates pytest-polylogue- prefix, excludes -seeded- dirs, deletes via shutil.rmtree); imports and calls it in verify.py after _run_pytest_with_heartbeat returns.
Unit tests and renamed temp-policy test
tests/unit/devtools/test_verify.py, tests/unit/test_pytest_temp_policy.py
Adds two unit tests validating run-scoped deletion and seed-cache preservation; updates import block; renames test_sessionfinish_leaves_xdist_basetemp_for_startup_sweep to _for_supervisor_cleanup.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • Sinity/polylogue#1785: Directly connected at the basetemp/directory cleanup layer — both PRs implement cleanup of pytest per-run basetemp directories keyed by POLYLOGUE_PYTEST_RUN_ID, with this PR adding cleanup_managed_pytest_basetemp in devtools/verify_runs.py.

Poem

🐇 Hop! The probe now checks integrity,
Exact counts bloom when you ask it true,
Old temp folders vanish after the suite,
messages_fts_docsize joins the view,
And seeded caches stay safely put —
A tidy warren, root by root! 🌿

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.93% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately captures the main focus of the PR: bounding workload diagnostics and cleaning up pytest temps.
Description check ✅ Passed The PR description follows the template with all major sections completed: Summary, Problem, Solution, Verification, Changelog, and Risks/Follow-ups appropriately addressed.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/fix/memory-diagnostics-cleanup

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 and usage tips.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 1f9bd5fb93

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread devtools/daemon_workload_probe.py Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@devtools/daemon_workload_probe.py`:
- Around line 1155-1159: The change to action_count at line 1155 alters its
semantics from an exact count to a presence bit (0 or 1) when exact_counts is
false, which breaks the contract for downstream consumers relying on the numeric
field shape. Either increment REPORT_VERSION to signal the format change to
downstream systems, or refactor by keeping action_count as the exact count and
creating a separate new key (like action_present) for the presence indicator
when exact_counts is false. Choose the approach that best fits your versioning
strategy and downstream consumer requirements.

In `@devtools/verify.py`:
- Line 727: The cleanup_managed_pytest_basetemp function call is executed
unconditionally but depends on the POLYLOGUE_PYTEST_RUN_ID environment variable
being set by env_for_pytest_step, which only occurs when both run and artifacts
are not None. When these conditions are false, the empty string from
env.get("POLYLOGUE_PYTEST_RUN_ID", "") creates an invalid path that could delete
unintended directories. Move the cleanup_managed_pytest_basetemp call inside the
conditional block that checks if run is not None and artifacts is not None,
ensuring the cleanup only executes when env_for_pytest_step has properly
populated the environment variable.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: a362b33a-7045-43d5-8469-4848522d21f9

📥 Commits

Reviewing files that changed from the base of the PR and between 2ad1fe0 and 1f9bd5f.

📒 Files selected for processing (9)
  • AGENTS.md
  • devtools/daemon_workload_probe.py
  • devtools/verify.py
  • devtools/verify_runs.py
  • docs/internals.md
  • polylogue/cli/commands/diagnostics.py
  • tests/unit/devtools/test_daemon_workload_probe.py
  • tests/unit/devtools/test_verify.py
  • tests/unit/test_pytest_temp_policy.py

Comment on lines +1155 to 1159
"action_count": _scalar_int(conn, "SELECT COUNT(*) FROM actions")
if exact_counts
else _presence_count(conn, "actions"),
"action_count_exact": exact_counts,
"cost_profile_count": _scalar_int(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Preserve count semantics or bump REPORT_VERSION for compatibility

Line 1155 changes action_count to a presence bit in default mode (0/1), while the key name and numeric shape still look like an exact count. That is a contract break for downstream compare/automation consumers unless REPORT_VERSION is incremented (or the approximate metric is moved to a new key like action_present).

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@devtools/daemon_workload_probe.py` around lines 1155 - 1159, The change to
action_count at line 1155 alters its semantics from an exact count to a presence
bit (0 or 1) when exact_counts is false, which breaks the contract for
downstream consumers relying on the numeric field shape. Either increment
REPORT_VERSION to signal the format change to downstream systems, or refactor by
keeping action_count as the exact count and creating a separate new key (like
action_present) for the presence indicator when exact_counts is false. Choose
the approach that best fits your versioning strategy and downstream consumer
requirements.

Comment thread devtools/verify.py
if run is not None and artifacts is not None:
env = env_for_pytest_step(env, run=run, artifacts=artifacts)
result = _run_pytest_with_heartbeat(cmd, cwd=cwd, env=env, t0=t0, run=run, artifacts=artifacts)
cleanup_managed_pytest_basetemp(root=ROOT, run_id=env.get("POLYLOGUE_PYTEST_RUN_ID", ""), env=env)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Check that env_for_pytest_step sets POLYLOGUE_PYTEST_RUN_ID

ast-grep --pattern $'def env_for_pytest_step($$$) {
  $$$
}'

Repository: Sinity/polylogue

Length of output: 42


🏁 Script executed:

# Search for env_for_pytest_step function
rg "env_for_pytest_step" -n

Repository: Sinity/polylogue

Length of output: 346


🏁 Script executed:

# Read the devtools/verify.py file around line 727 to see context
sed -n '700,750p' devtools/verify.py

Repository: Sinity/polylogue

Length of output: 2441


🏁 Script executed:

# Find the cleanup_managed_pytest_basetemp function definition
rg "def cleanup_managed_pytest_basetemp" -A 15

Repository: Sinity/polylogue

Length of output: 1268


🏁 Script executed:

# Read env_for_pytest_step implementation in verify_runs.py starting at line 186
sed -n '186,250p' devtools/verify_runs.py

Repository: Sinity/polylogue

Length of output: 3039


🏁 Script executed:

# Also check pytest_basetemp_path to understand the impact of empty run_id
rg "def pytest_basetemp_path" -A 20

Repository: Sinity/polylogue

Length of output: 1596


Fix missing environment variable guard in cleanup call.

The cleanup is called unconditionally within the pytest block, but env_for_pytest_step (which sets POLYLOGUE_PYTEST_RUN_ID) is only called if run is not None and artifacts is not None. If this condition is false, env.get("POLYLOGUE_PYTEST_RUN_ID", "") returns an empty string, constructing a basetemp path like pytest-polylogue-{checkout_hash}-, which passes the validation check in cleanup_managed_pytest_basetemp and would be deleted if it exists. Either ensure the cleanup is only called when env_for_pytest_step was applied, or guarantee POLYLOGUE_PYTEST_RUN_ID is always set in the environment before reaching this point.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@devtools/verify.py` at line 727, The cleanup_managed_pytest_basetemp function
call is executed unconditionally but depends on the POLYLOGUE_PYTEST_RUN_ID
environment variable being set by env_for_pytest_step, which only occurs when
both run and artifacts are not None. When these conditions are false, the empty
string from env.get("POLYLOGUE_PYTEST_RUN_ID", "") creates an invalid path that
could delete unintended directories. Move the cleanup_managed_pytest_basetemp
call inside the conditional block that checks if run is not None and artifacts
is not None, ensuring the cleanup only executes when env_for_pytest_step has
properly populated the environment variable.

Problem: PR #2163 added explicit workload diagnostic flags but did not update the tier-0 showcase help baseline, causing showcase-verify to fail in CI.

What changed: refreshed the help-ops-diagnostics-workload baseline to include --integrity-check and --exact-derived-counts.

Verification: devtools lab scenario verify-baselines --update; devtools lab scenario verify-baselines.
@Sinity
Sinity merged commit 3e8ebc2 into master Jun 19, 2026
14 checks passed
@Sinity
Sinity deleted the feature/fix/memory-diagnostics-cleanup branch June 19, 2026 13:58
@Sinity

Sinity commented Oct 1, 2026

Copy link
Copy Markdown
Owner Author

Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.

Only the rows listed above are dispositioned. Held findings remain open.

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