Skip to content

feat(retention): execution_log + health_check retention sweeps (#772) - #776

Merged
vybe merged 2 commits into
devfrom
feature/772-execution-log-retention
May 11, 2026
Merged

vybe merged 2 commits into
devfrom
feature/772-execution-log-retention

Conversation

@dolho

@dolho dolho commented May 11, 2026

Copy link
Copy Markdown
Contributor

Summary

  • Two-stage retention on schedule_executions: null execution_log past execution_log_retention_days (default 30) preserves row + metadata; DELETE row past execution_row_retention_days (default 90) for deeper retention.
  • Wire agent_health_checks cleanup (previously orphaned) into the 5-min cleanup tick, configurable via health_check_retention_days (default 7).
  • All sweeps chunked (5000 rows/cycle budget) so a multi-GB backfill spans hours rather than holding the write lock end-to-end; iso_cutoff() cutoffs per Architectural Invariant #16 (issue spec's datetime('now', '-N days') would have silently broken lex compare on ISO-Z columns, bug(SUB-003): rate-limit events never age out due to SQLite string-compare bug; retries amplify outages #476).
  • New partial index idx_executions_completed_terminal + PRAGMA wal_checkpoint(TRUNCATE) after sweeps that reclaim rows.
  • New db_vacuum_service.py runs full VACUUM daily at 04:30 UTC (autocommit connection, accepts BUSY rather than retry).
  • Admin-tunable via GET/PUT /api/settings/ops/config; 0 disables a sweep.

Related to #772.

Production motivation

Pre-fix observation: schedule_executions ~3.3 GB / ~9k rows (driven by 150–190 KB/row JSONL transcripts), agent_health_checks ~200 MB / ~750k rows. Growth was unbounded — no TTL, no pruning hook in cleanup_service.

Test plan

  • 9 unit tests in tests/unit/test_execution_retention_prune.py (cutoff correctness, non-terminal not touched, chunked drain, retention_days=0 disables, empty-table 0, health-check delete) — all pass
  • tests/test_cleanup_service.py updated for new report fields + dynamic total sum
  • Local smoke against running stack:
    • Backend boots with DB vacuum scheduler started: daily at 04:30 UTC
    • Startup cleanup tick deleted 2820 stale agent_health_checks rows
    • 3 new ops keys exposed via GET /api/settings/ops/config
    • POST /api/monitoring/cleanup-trigger returns report with execution_logs_pruned / execution_rows_pruned / health_checks_pruned
    • End-to-end: PUT execution_log_retention_days=1 → inject old terminal row with 200KB log → trigger → row preserved with execution_log IS NULL
    • End-to-end: PUT execution_row_retention_days=1 → trigger → 1510 stale terminal rows deleted in one tick (budget cap held)
    • Partial index idx_executions_completed_terminal present on real DB after migration
    • WAL file truncated to 0 / absent post-sweep
  • Run full test suite via /validate-pr
  • Reviewer pass

Files

Area Change
services/cleanup_service.py §4c retention sweeps, §4d WAL checkpoint, new report fields, 5000-row/cycle budget
services/db_vacuum_service.py (new) Daily VACUUM APScheduler job (env-tunable hour/minute/enable)
db/schedules.py prune_execution_logs() + prune_execution_rows() — chunked SELECT-id → UPDATE/DELETE-id-in
db/monitoring.py cleanup_old_records() upgraded to chunked + iso_cutoff(), chunk_size param
db/schema.py + db/migrations.py Partial index idx_executions_completed_terminal ON (completed_at) WHERE status IN (...)
services/settings_service.py 3 new ops keys + descriptions
database.py Facade methods
main.py Wire db_vacuum_service.start()/.stop() into lifespan
docs/memory/architecture.md + requirements.md Update Cleanup Service row, add DB Vacuum row, new §12.10 RETENTION-001

🤖 Generated with Claude Code

Bounded growth for schedule_executions (driven by per-run JSONL transcripts
in execution_log, ~150-190KB/row) and agent_health_checks so active fleets
don't hit disk pressure within weeks. Production observation pre-fix:
~3.3GB / ~9k rows on schedule_executions, ~200MB / ~750k rows on
agent_health_checks.

- Two-stage retention on schedule_executions: null execution_log past
  execution_log_retention_days (default 30, preserves row + metadata),
  DELETE row past execution_row_retention_days (default 90).
- Reuse cleanup_old_records on agent_health_checks
  (health_check_retention_days, default 7). Was orphaned; now wired.
- All sweeps chunked (5000 rows/cycle budget) so the first post-deploy
  backfill spans hours rather than holding a multi-minute write lock.
- iso_cutoff() cutoffs per Architectural Invariant #16 — prior issue spec
  used datetime('now', '-N days') which silently breaks lex comparison
  against ISO-Z TEXT columns (#476).
- Partial index idx_executions_completed_terminal on (completed_at)
  WHERE status IN ('completed','failed','terminated').
- PRAGMA wal_checkpoint(TRUNCATE) per cycle that reclaims rows.
- New db_vacuum_service.py runs full VACUUM daily at 04:30 UTC
  (autocommit connection, accepts BUSY rather than retry).
- Admin-tunable via GET/PUT /api/settings/ops/config — 0 disables a sweep.

Verified on local stack: startup sweep deleted 2820 stale health_check
rows; retention=1 + trigger nulled the test execution_log payload while
preserving row metadata; row-retention=1 deleted 1510 stale terminal
rows in one tick within the budget cap.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@dolho
dolho force-pushed the feature/772-execution-log-retention branch from 8ec569d to eddeaa2 Compare May 11, 2026 09:46
@dolho
dolho changed the base branch from main to dev May 11, 2026 09:48
Adds steps 7 (retention sweeps) and 8 (WAL checkpoint) to the cleanup
cycle in docs/memory/feature-flows/cleanup-service.md, matching the
behavior added by #772. Updates the section header from "Seven" to
"Nine sequential operations".

Related to #772.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@dolho

dolho commented May 11, 2026

Copy link
Copy Markdown
Contributor Author

PR Validation Report (/validate-pr)

Category Status Notes
Issue link ✅ "Related to #772" — non-closing per new policy (issues close on merge to main)
Commit Messages ✅ 2 commits, conventional format (feat(retention):, docs(cleanup-service):)
Base Branch ✅ Targets dev (after retarget — initially missed and rebased onto origin/dev)
PR Size ✅ 14 files, +850/-32, well under 50
Issue priority ✅ P1 / type-feature — appropriate scrutiny applied
Requirements ✅ New §12.10 RETENTION-001 in docs/memory/requirements.md
Architecture ✅ Cleanup Service row updated + new DB Vacuum row in Background Services table
Feature Flow ✅ cleanup-service.md updated with new steps 7 + 8 (after warning surfaced + fixed)
Security Check ✅ No API keys, real emails, public IPs, .env files, hardcoded secrets, or credential files
Code Quality ✅ Mirrors audit_retention_service.py for VACUUM job; follows §4/§4b cleanup-tick shape; chunked SQL pattern identical to other prune sites
Requirements Trace ✅ Issue #772 explicitly referenced; acceptance criteria covered
Unit tests ✅ 9/9 pass in tests/unit/test_execution_retention_prune.py
Live smoke ✅ Backend boots; startup tick deleted 2820 stale agent_health_checks rows; PUT + trigger end-to-end works

Issues Found

Critical: none.

Warnings (resolved during validation):

  • Targeted main instead of dev — rebased onto origin/dev, force-pushed, retargeted. Migration conflict resolved (kept dev's slack_bot_token_encryption + canary_violations_table plus ours).
  • cleanup-service.md feature flow not updated — added steps 7 (retention sweeps) + 8 (WAL checkpoint), bumped count from "Seven" to "Nine sequential operations".

Suggestions (non-blocking):

  • EXPLAIN QUERY PLAN on a real DB showed the planner picked the existing idx_executions_status over our new partial index idx_executions_completed_terminal. Not a correctness issue (smoke pruned 1510 rows fast). ANALYZE schedule_executions may improve the plan if perf becomes a problem on much larger tables — worth a follow-up issue, not a blocker.

Recommendation

APPROVE — ready for human review + merge to dev.

PR adds bounded growth for schedule_executions (production-observed at 3.3 GB) and agent_health_checks (~750k rows). Two-stage retention (null → delete), per-cycle row budget (5000) caps backfill blast radius, partial index, WAL checkpoint per tick, daily VACUUM service. Admin-tunable via existing /api/settings/ops/config; 0 disables any sweep. All Architectural Invariants respected (esp. #16 iso_cutoff()); reuses three-layer router → service → DB pattern. Reuses orphaned cleanup_old_records() (was dead code; now wired). Security clean, unit tests pass, live smoke confirms end-to-end behavior. Issue #772 stays open per new policy.

🤖 Generated with Claude Code

@vybe vybe left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM — solid P1 implementation. All architectural invariants respected (iso_cutoff, schema+migration, service lifecycle). Chunked-commit approach is correct; minor doc framing on 'per-cycle budget' is non-blocking.

@vybe
vybe merged commit 40d1fba into dev May 11, 2026
9 checks passed
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.

2 participants