Skip to content

perf(daemon): bound live ingest memory - #1429

Merged
Sinity merged 8 commits into
masterfrom
feature/perf/daemon-memory-bounds
May 23, 2026
Merged

Sinity merged 8 commits into
masterfrom
feature/perf/daemon-memory-bounds

Conversation

@Sinity

@Sinity Sinity commented May 23, 2026 •

Copy link
Copy Markdown
Owner

Summary

Bounds daemon live-ingest memory retention and removes two verification paths that were wasting CPU/RAM in normal agent loops.

Problem

Live catch-up could still retain source payloads in groups much larger than the workload justified: full-ingest batches allowed 256 MiB / 256 files, append planning could accumulate many individually-bounded tail payloads before processing them, and large non-JSONL planning could materialize the whole file just to classify it. Separately, focused pytest inherited -n auto, and devtools wrapper execution could disagree with python -m devtools for generated-surface checks.

Solution

  • Cap live full-ingest progress groups at 64 MiB / 64 files.
  • Flush append-only plans in bounded 64 MiB / 64 file groups.
  • Avoid large non-JSONL full-file reads in daemon planning.
  • Release Python cycles and glibc arenas after heavy parse/convergence phases.
  • Split append ingest persistence out of sources/live/batch.py to keep the central processor under file budget.
  • Make plain focused pytest single-process by default; broad devtools verify modes still pass explicit workers.
  • Make render-all --check sequential and align the devtools script entrypoint with python -m devtools imports.

Verification

  • pytest tests/unit/core/test_memory.py tests/unit/sources/test_live_batch_support.py tests/unit/sources/test_live_watcher.py -q --tb=short -> 68 passed in 7.10s.
  • pytest tests/unit/devtools/test_render_all.py -q --tb=short -> 4 passed in 0.40s.
  • pytest tests/unit/devtools/test_devtools_main.py tests/unit/devtools/test_cli_wrapper.py -q --tb=short -> 10 passed in 0.15s.
  • python devtools/__main__.py render-all --check, devtools render-all --check, and python -m devtools render-all --check all passed.
  • Synthetic live ingest probe: 130 codex JSONL files converged in 0.789s, grouped 64 + 64 + 2, with rss_current_mb=80.8, rss_peak_self_mb=104.9, cgroup_memory_current_mb=525.6.
  • python -m devtools verify --quick -> pass in 39.0s.
  • Pre-push devtools verify --quick -> pass in 39.34s.

Summary by CodeRabbit

  • New Features

    • Added memory release helpers for long-running daemons to manage garbage collection and system memory.
    • Introduced append-only ingest functionality with intelligent batching and memory optimization.
  • Performance

    • Optimized large file handling to skip unnecessary full-file reads during provider detection.
    • Improved batch ingestion with incremental flushing to reduce memory pressure.
  • Documentation

    • Clarified testing behavior regarding parallel execution and explicit opt-in requirements.
  • Configuration

    • Removed pytest auto-parallelization default; parallel testing now requires explicit flags.
  • Tests

    • Added comprehensive tests for memory management and batch ingestion improvements.

Review Change Stack

Sinity added 3 commits May 23, 2026 11:14
Problem: live catch-up could retain source payloads and parsed batch structures well beyond the tiny workload being ingested. Focused pytest invocations also inherited repo-wide xdist auto-parallelism, which made small agent checks spawn a worker pool and waste CPU/RAM.\n\nWhat changed: reduce live full-ingest group ceilings to 64 MiB / 64 files, flush append tails in bounded groups, avoid large non-JSONL planning reads, release Python/glibc memory after heavy daemon phases, and make plain pytest single-process by default while keeping devtools broad gates explicitly parallel.\n\nVerification: ruff check on touched files passed; mypy on touched files passed; pytest tests/unit/core/test_memory.py tests/unit/sources/test_live_batch_support.py tests/unit/sources/test_live_watcher.py -q --tb=short passed with 68 tests; synthetic live ingest of 130 codex JSONL files converged in 0.789s with 80.8 MiB current RSS.
Problem: the live batch processor was already over its file budget, and adding bounded append flushing made the central daemon file harder to keep below the enforced ceiling. The generated-surface aggregate check also reported stale docs under python -m devtools even when individual checks passed.\n\nWhat changed: move append-only ingest persistence into polylogue.sources.live.append_ingest, keep the LiveBatchProcessor as the orchestration surface, refresh topology/agent generated files, and make render-all check mode sequential so verification is deterministic.\n\nVerification: pytest tests/unit/core/test_memory.py tests/unit/sources/test_live_batch_support.py tests/unit/sources/test_live_watcher.py -q --tb=short passed with 68 tests; pytest tests/unit/devtools/test_render_all.py -q --tb=short passed with 4 tests; python -m devtools verify --quick passed in 39.92s.
Problem: running devtools through the wrapper executed devtools/__main__.py as a script, leaving the devtools package directory ahead of the repository root on sys.path. That made wrapper output diverge from python -m devtools for generated documentation checks.\n\nWhat changed: insert the repository root before importing devtools.click_dispatch so script, wrapper, and module entrypoints resolve the same checkout.\n\nVerification: python devtools/__main__.py render-all --check, devtools render-all --check, and python -m devtools render-all --check all passed; pytest tests/unit/devtools/test_devtools_main.py tests/unit/devtools/test_cli_wrapper.py -q --tb=short passed; python -m devtools verify --quick passed in 39.0s.
@coderabbitai

coderabbitai Bot commented May 23, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

@Sinity, we couldn't start this review because you've used your available PR reviews for now.

Your plan currently allows 1 review/hour. Refill in 29 minutes and 7 seconds.

Your organization has run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

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

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than trial, open-source, and free plans. In all cases, review capacity refills continuously over time.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: f057926f-34a7-4aaa-9f03-0ce287903210

📥 Commits

Reviewing files that changed from the base of the PR and between db438ee and 95b0a75.

📒 Files selected for processing (11)
  • devtools/verify.py
  • polylogue/daemon/convergence.py
  • polylogue/pipeline/services/ingest_batch/_core.py
  • polylogue/sources/live/append_ingest.py
  • polylogue/sources/live/batch_support.py
  • polylogue/storage/insights/session/rebuild.py
  • polylogue/storage/insights/session/refresh.py
  • tests/unit/daemon/test_catch_up_observability.py
  • tests/unit/daemon/test_daemon_convergence.py
  • tests/unit/devtools/test_verify.py
  • tests/unit/sources/test_live_batch_support.py
📝 Walkthrough

Walkthrough

This PR reduces memory pressure during live ingestion by introducing memory-release utilities, refactoring append-plan batching with bounded group flushing, disabling pytest parallelism by default, and updating devtools infrastructure for sequential validation of generated documentation.

Changes

Testing & Devtools Infrastructure

Layer / File(s) Summary
Testing parallelism documentation and configuration
AGENTS.md, TESTING.md, pyproject.toml
Pytest configuration removes -n auto default parallelism. Documentation clarifies that focused runs are single-process, with explicit opt-in required via devtools verify --all, devtools verify --seed-testmon, or pytest -n <workers>.
Devtools CLI entrypoint and sys.path setup
devtools/__main__.py
Repository root is inserted into sys.path at runtime before importing the CLI dispatcher, ensuring imports resolve correctly.
Sequential surface validation for --check mode
devtools/render_all.py, tests/unit/devtools/test_render_all.py
Render_all now executes surface checks sequentially and returns aggregated exit codes immediately, bypassing the parallel rendering path when --check is enabled.
Generated topology projection and status dashboard
docs/plans/topology-target.yaml, docs/topology-status.md
Topology metadata adds new polylogue/core/memory.py and polylogue/sources/live/append_ingest.py entries with updated line counts, and status dashboard reflects corresponding cell and total count changes.

Live Batch Ingestion with Memory Management

Layer / File(s) Summary
Memory release utility for long-running processes
polylogue/core/memory.py, tests/unit/core/test_memory.py
New module provides release_process_memory() for garbage collection and Linux malloc_trim via ctypes, with full test coverage validating collected object count and trim invocation.
Append-plan batching constants and large-file detection guards
polylogue/sources/live/batch_support.py
Introduces tuning constants for small-file progress grouping and append-plan group sizing; adds early-exit guards in provider detection and artifact parsing to skip full file reads when input exceeds streaming threshold.
Append-only ingestion persistence module
polylogue/sources/live/append_ingest.py
New ingest_append_plans() function orchestrates blob writes, raw record persistence, owner callbacks, and synchronous batch processing, with exception handling and failure reconciliation mapped back to original plans.
Batch processor with grouped append flushing and memory management
polylogue/sources/live/batch.py
Batch processor now accumulates append plans incrementally and flushes via _append_plan_group_ready thresholds; calls release_process_memory() after append ingestion and convergence stages; full-path result construction pre-computes and clears intermediate structures.
Batch ingestion tests: file-size optimization and grouping validation
tests/unit/sources/test_live_batch_support.py, tests/unit/sources/test_live_watcher.py
New tests validate that large files bypass full reads during planning and that append-plan grouping flushes in bounded batches with correct partitioning and metrics counters.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • Sinity/polylogue#455: Updates the generated-surface render_all --check flow to validate docs/topology-status.md freshly.

Suggested labels

type:refactor

🐰 Memory whispers gently to the batch processor,
"Let's shed our load in bounded groups,
Trim the heap when burdens grow,
And run our checks one by one—
So daemons may run long and light!" ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 15.63% 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 pull request title clearly summarizes the main objective: bounding daemon live-ingest memory.
Description check ✅ Passed The pull request description comprehensively covers all required template sections with sufficient detail about the problem, solution, verification steps, and risks.
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/perf/daemon-memory-bounds

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: db438eed55

ℹ️ 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 polylogue/sources/live/batch_support.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 `@polylogue/sources/live/append_ingest.py`:
- Around line 73-80: The current logic builds succeeded with "succeeded = [plan
for plan in plans if plan.path not in failed_paths and summary.parse_failures ==
0]", which drops successful plans whenever any parse failures exist; change the
succeeded comprehension to "succeeded = [plan for plan in plans if plan.path not
in failed_paths]" so successful append plans are preserved even when
summary.parse_failures > 0, and keep the existing branch that returns
_AppendResult(succeeded=[], failed=plans, ...) only when summary.parse_failures
and not failed (i.e., parse failures exist but no attributable failed_raw_ids);
this ensures failed, failed_paths, succeeded, raw_by_id, and the _AppendResult
return behavior align with the full-ingest path.

In `@polylogue/sources/live/batch_support.py`:
- Around line 344-345: The current size-only fallback makes unclassified paths
(classify_artifact_path returning None) eligible for full streaming ingest;
update the logic in batch_support.py so you first call
classify_artifact_path(path) and if it returns None you do NOT treat the file as
a streaming/full-ingest candidate (return False), but if it returns a
known/expected class then apply the _path_size(path) >
_STREAMING_FULL_INGEST_BYTES check to allow the memory-safe fast path; reference
classify_artifact_path, _path_size, and _STREAMING_FULL_INGEST_BYTES so the
condition gating large-file fast-path only applies to classified artifact types.
🪄 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: 0594da23-0483-4df5-9a07-5b6f503b743a

📥 Commits

Reviewing files that changed from the base of the PR and between 1110956 and db438ee.

📒 Files selected for processing (15)
  • AGENTS.md
  • TESTING.md
  • devtools/__main__.py
  • devtools/render_all.py
  • docs/plans/topology-target.yaml
  • docs/topology-status.md
  • polylogue/core/memory.py
  • polylogue/sources/live/append_ingest.py
  • polylogue/sources/live/batch.py
  • polylogue/sources/live/batch_support.py
  • pyproject.toml
  • tests/unit/core/test_memory.py
  • tests/unit/devtools/test_render_all.py
  • tests/unit/sources/test_live_batch_support.py
  • tests/unit/sources/test_live_watcher.py

Comment thread polylogue/sources/live/append_ingest.py Resolved
Comment thread polylogue/sources/live/batch_support.py Outdated
Comment on lines +344 to +345
if _path_size(path) > _STREAMING_FULL_INGEST_BYTES:
return True

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 | 🏗️ Heavy lift

Avoid auto-ingesting every large unclassified non-JSONL file.

If classify_artifact_path() returns None, this now returns True purely because the file is larger than _STREAMING_FULL_INGEST_BYTES. That turns unknown large *.json sidecars into ingest candidates, so they get blob-copied and pushed through the parser instead of being excluded. The memory optimization makes sense, but this size-only fallback changes the classification contract and can create repeated parse failures / raw-row churn for unrelated files. Please keep the large-file fast path memory-safe without making unclassified paths implicitly parseable.

🤖 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 `@polylogue/sources/live/batch_support.py` around lines 344 - 345, The current
size-only fallback makes unclassified paths (classify_artifact_path returning
None) eligible for full streaming ingest; update the logic in batch_support.py
so you first call classify_artifact_path(path) and if it returns None you do NOT
treat the file as a streaming/full-ingest candidate (return False), but if it
returns a known/expected class then apply the _path_size(path) >
_STREAMING_FULL_INGEST_BYTES check to allow the memory-safe fast path; reference
classify_artifact_path, _path_size, and _STREAMING_FULL_INGEST_BYTES so the
condition gating large-file fast-path only applies to classified artifact types.

Sinity added 5 commits May 23, 2026 11:37
Problem: the long-running daemon created a convergence process pool even though all production stages are IO-bound today, and batch convergence retained successful per-file/per-conversation state indefinitely after callers had already consumed the returned batch result.

What changed: convergence startup now creates the worker pool only when a registered stage is CPU-bound and uses the shared process-pool factory. Batch convergence now evicts converged file and conversation states after returning them, while failed states remain retained for diagnostics.

Verification: pytest tests/unit/daemon/test_daemon_convergence.py tests/unit/daemon/test_catch_up_observability.py tests/unit/sources/test_live_batch_convergence.py tests/unit/sources/test_live_watcher.py -q --tb=short (69 passed in 8.36s). ruff check and mypy passed for the touched convergence/test files.
Problem: session insight refresh and rebuild are chunked, but heavy chunks could keep hydrated conversations, record bundles, and SQL batch lists referenced until the loop advanced or the function exited, leaving RSS inflated during catch-up.

What changed: refresh and rebuild now explicitly drop chunk-local heavy structures and release process memory after chunks at or above the 1,000-message threshold. Small routine chunks avoid the GC/allocator-trim cost.

Verification: pytest tests/unit/storage/test_session_insight_refresh.py tests/unit/daemon/test_convergence_stages.py -q --tb=short (22 passed in 0.52s). ruff check and mypy passed for the touched insight modules.
Problem: the async ingest batch wrapper retained raw artifact records and batch summary structures until return, even after the sync worker/write path and raw-state updates had consumed them. Live ingest is now grouped, but the generic ingest path still needed a defensive release point for heavy batches.

What changed: raw artifact records are cleared immediately after the sync ingest worker returns, and batches with at least 16 MiB of source blobs or 1,000 parsed messages release process memory after the parse observation is built. RSS telemetry is still captured before release.

Verification: pytest tests/unit/pipeline/test_ingest_batch.py tests/unit/sources/test_live_watcher.py -q --tb=short (86 passed in 6.78s). ruff check and mypy passed for the touched ingest/insight modules.
Problem: append ingest treated any parse failure as if every append plan failed, even when failed_raw_ids identified only a subset. The large-file planning guard also allowed any unclassified huge non-JSONL path to enter the streaming full-ingest path solely because of size.

What changed: append result attribution now marks only paths mapped from failed_raw_ids as failed, preserving other successes. Large non-JSONL planning now streams only known provider JSON exports and rejects unclassified large paths without materializing them.

Verification: pytest tests/unit/sources/test_live_batch_support.py tests/unit/sources/test_live_watcher.py -q --tb=short (69 passed in 6.85s). ruff check and mypy passed for the touched live modules and tests.
Problem: running devtools verify from a linked worktree could inherit POLYLOGUE_ROOT, POLYLOGUE_REPO_ROOT, and PYTHONPYCACHEPREFIX from the main checkout. The broad testmon seed then mixed current worktree code with stale checkout paths and produced unrelated failures.

What changed: verify subprocesses now force those environment variables to the checkout containing devtools/verify.py. The quick verify step-order test was refreshed to match the current static gate list.

Verification: pytest tests/unit/devtools/test_verify.py -q --tb=short (31 passed in 5.15s). ruff check and mypy passed for devtools/verify.py and tests/unit/devtools/test_verify.py.
@Sinity
Sinity merged commit bdc1d72 into master May 23, 2026
7 checks passed
@Sinity
Sinity deleted the feature/perf/daemon-memory-bounds branch May 23, 2026 10:04
Sinity added a commit that referenced this pull request May 23, 2026
Reduce live daemon catch-up amplification found during production deployment of #1429.\n\nThe daemon now keeps live full-ingest parsing in-process by default unless POLYLOGUE_LIVE_FULL_INGEST_WORKERS explicitly opts into process workers, accepts append tails up to 64 MiB so large Codex appends stay append-only, and avoids COUNT(*) on the FTS5 virtual table in direct status fallback. Daemon HTTP handlers also treat client disconnects during response writes as normal disconnects instead of logging internal-error tracebacks.\n\nVerification:\n- pytest tests/unit/daemon/test_daemon_http_security.py tests/unit/cli/test_status.py tests/unit/sources/test_live_watcher.py -q --tb=short -> 258 passed\n- ruff format/check on touched files -> passed\n- mypy on touched files -> passed\n- devtools verify --quick -> passed\n- PR CI -> passed
@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.

  • 70.F066 / P1: fixed-already at the checked revision: The size-only conversation predicate has been replaced by raw acquisition followed by typed parse outcomes. A large unrelated JSON that produces no session is recorded as terminal unsupported/no-session evidence and entered into settled_exclusions at polylogue/sources/live/batch.py:4901, preventing repeated failed-conversation retry churn.

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