Repository navigation
fix: run git maintenance and git-health stats on every auto-sync tick (#4000) - #4006
Conversation
… tick (#4000) Self-pushing agents (auto_sync_enabled=0) and agents whose push keeps failing never reaped, measured or repacked their .git: maintenance ran only after a successful push, and the base image disables git's own auto-maintenance. Their git-health columns stayed NULL, so the git_bloat alert could never fire. Agent server: - _run_git_maintenance_once owns git health and runs on every tick, auto-sync on or off, push ok or failed. The sync cycle no longer measures or repacks. - _record_git_health writes only the git stats, git_stats_at and the maintenance backoff; it never touches last_sync_*. Backoff bookkeeping is shared with the sync writer. - Loops are scheduled on every agent; the first tick is jittered by up to one interval so a fleet recreate does not start every repack in the same minute. - The disk preflight counts loose bytes as well as pack bytes. - The follow-up git gc is replaced by reflog expire + prune: a plain gc repacked a second time without the memory bound. Backend: - agent_sync_state.git_stats_at (SQLite migration + Alembic 0104), persisted by the sync-health poller through _coerce_agent_timestamp. - Canary RD-04 (git stats NULL or measured more than 24 h ago on a running agent) and RD-05 (loose > 3x6700 or packs > 3x20 on a running agent, level-triggered), with alert names, runbooks and renderers. Mutation checks: reverting the off-path return, the success-only maintenance call, the write-time re-read, the loose-byte preflight, the gc replacement, the RD-04 comparison/fallback/grace and the RD-05 running filter each turns tests in test_4000_* red. Fixes #4000 Co-Authored-By: Claude Opus 5.5 <[email protected]>
AndriiPasternak31
left a comment
There was a problem hiding this comment.
Reviewed at 0c34fd79c95fd2c0d9f64d5689462de91a149875.
This does what #4000 asks, and I found nothing that blocks.
- Decoupled maintenance.
run_one_cycleruns_run_git_maintenance_onceon every tick, after the sync cycle or in place of it. I ran an auto-sync-off tick against a real repo holding 7,000 reachable loose objects plus 500 unreachable ones aged 2 h. The result:count-objectswent from 7,503 loose objects to 0 loose and 1 pack, andgit fsck --connectivity-onlyis clean.sync-state.jsongotgit_stats_at,loose_objects=0,pack_count=1andmaintenance_status="repacked 0->1".last_sync_statusstayedneverandlast_sync_atstayed null.
git_bloatcan fire. The poller already covers auto-sync-off agents (list_git_enabled_agentsfilters onsync_enabled, notauto_sync_enabled). The first poll that carries stats crosses the byte edge from a NULL prior (read, not run).- RD-04 / RD-05. Both are there, both are gated on
collector_succeeded, and both are tested. - Invariant #9. The SQLite migration, the Alembic
0104revision (check_alembic_heads.py: 1 head), theschema.pyandtables.pyDDL,_COLUMNSand the upsert are all in place. - Background loops. No new backend loop. The collector runs inside the existing canary cycle, and sync-health is already leased.
- Tests. The three new files plus the touched suites give 472 passed and 2 skipped at this head. Merged locally with #4007, only
tests/registry.jsonanddocs/memory/requirements/github.mdconflict, both textually. On the combined tree the git, sync and canary suites pass (1547 passed, 4 skipped), and both PRs' own tests pass.
Beyond the issue. The issue says thresholds, backoff and timeout stay unchanged. This PR also counts loose bytes in the disk preflight, replaces the follow-up gc with reflog expire --all + prune --expire=1.hour.ago, and jitters the first tick. The body argues for each, and I'm fine with all three. One consequence deserves to be stated plainly: the issue's own repo, loose-heavy on a near-full host, now gets skipped_low_disk where the pack-only check would have gone ahead (routers/git.py:821). The rollout note and the RD-05 runbook already cover it.
Non-blocking
-
The first-tick jitter undoes the pull loop's offset.
- What changed:
docker/base-image/agent_server/auto_sync.py:158addsrandom.uniform(0, interval)to the push loop only. The pull loop still sleepsinterval + interval / 2(:266), and the comment at:263-265says why: the two loops start together and would otherwise reach the repo lock on the same tick. - Effect: on
devthe two first ticks are always half an interval apart. With this change the gap is uniform anywhere in ±0.5 × interval. Some agents now start with both loops on the same tick, and the second one to arrive skips asrepo_busy. The push tick also holds the lock longer now, because it covers sync plus maintenance. - Phases drift with cycle duration, so this is not permanent, but the protection the comment describes is gone. I worked this out from the code and did not reproduce it.
- Suggestion: draw the jitter once and add it to both loops' first sleep.
- What changed:
-
RD-04 goes red at deploy, not at recreate.
- What happens: the
last_sync_atstand-in (rd04_git_measurement_blind.py:66-67) applies only when stats are present. Self-pushing agents still on the old base image have NULL stats, so they hitnever_measured(:78) as soon as the backend ships. The rollout note says old-image agents don't page until recreated. - The signal is true, and it is what the issue wanted. But RD-04 then stays red until every one of those agents is recreated, and while it is red a new blindness on any other agent won't page. The ledger pages green→red per id, as the RD-05 docstring itself notes.
- Suggestion: correct the rollout note and list "recreate self-pushing agents" as an explicit rollout step.
- What happens: the
| # heartbeat happening before .git is even initialized. #4000: plus a | ||
| # random share of one interval — a fleet recreate otherwise starts | ||
| # every agent's repack in the same minute. | ||
| await asyncio.sleep(interval + random.uniform(0, interval)) |
There was a problem hiding this comment.
Non-blocking: the pull loop still sleeps interval + interval / 2 so that it lands half an interval after this loop (see the comment above run_pull_loop's first sleep). With the jitter applied here only, the gap between the two first ticks becomes uniform anywhere in ±0.5 × interval, and some agents start with both loops on the same tick. Drawing the jitter once and adding it to both first sleeps keeps the offset.
| continue | ||
| reason = "stale" | ||
| else: | ||
| reason = "never_measured" |
There was a problem hiding this comment.
Non-blocking: self-pushing agents still on the old base image have NULL stats, so they land here as soon as the backend deploys. The last_sync_at stand-in only applies when stats exist. That's a true signal, but it keeps RD-04 red, so no new episode can page, until those agents are recreated. Worth correcting the rollout note and listing the recreate as a rollout step.
Conflict in src/backend/db/migrations.py, at the tail dev and this branch both appended to: dev's _migrate_agent_sync_state_git_stats_at (#4006) and this branch's _migrate_platform_alert_subjects_resweep. Both kept, dev's first, so platform_alert_subjects_resweep stays the last MIGRATIONS entry. The Alembic fork this merge leaves (both 0104 revisions off 0103) is fixed in the next commit. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01HWna79vVmnezQdhpaGRKbw
…3254) dev gained 0104_agent_sync_state_git_stats_at (#4006), which also revised 0103_a2a_caller_identity. With both on dev the version line had two heads, and `alembic upgrade head` on PostgreSQL would apply nothing (#2068). The re-sweep becomes 0105_platform_alert_resweep, revising 0104_agent_sync_state_git_stats_at. The id is renamed everywhere it appears: the file, its Revision ID / Revises lines, the migrations.py docstring, the tests/registry.json row, requirements/security.md §26.14 and feature-flows/operating-room.md. The SQLite entry stays last in MIGRATIONS, after agent_sync_state_git_stats_at. The revision has never been applied anywhere (the branch is unmerged), so a re-chain is correct and a merge revision is not needed. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01HWna79vVmnezQdhpaGRKbw
…(closing slice) (#4022) * fix(operator-queue): run the platform-alert upgrade sweep a second time (#3254) The #3246 sweep (SQLite platform_alert_subjects / Alembic 0090) ran once, on the upgrade that carried it. Every emitter #3254 moves onto the seam kept filing rows with no subject until its move landed, and the seam cannot see such a row: observe files a second pending row beside it, clear cannot end it, and the snooze cannot see a person's ending of it. A data-only pair re-runs the unchanged run_platform_alert_sweep: SQLite platform_alert_subjects_resweep (appended to MIGRATIONS) and Alembic 0104_platform_alert_resweep (down_revision 0103). The subject's existing holder keeps the slot whatever its age (#3255's rule), else the newest pending row stays; the rest end as one superseded batch by the platform. Agent-raised and gate rows and the gitignore / problem-report rows are never touched. No DDL on either track; downgrade is a no-op, as in 0090. tests/unit/test_3254_second_sweep.py drives both halves against the real post-#3246 operator_queue DDL for 18 derivable families, the fresh-install lifecycle, idempotency, and the Alembic upgrade() on SQLite and (requires_postgres) on PostgreSQL. * docs(requirements): mark platform alerts done and name every kind (#3254) #3254 completes OPS-001-PLATFORM-ALERTS, so the lines that described the half-moved state become false on its merge: - requirements/security.md section 26.14: status Partially -> Implemented, the ratchet's real name EMITTERS_NOT_YET_ON_SEAM (empty), each lifetime class names its kinds, the upgrade sweep in the past tense plus its second run, and the Files list gains the moved emitters; the flood alert and the #1677 budget bullets name observe as the write path and the episode's subject alert_budget:<type>. - requirements/core-agent.md, github.md, scheduling.md: the problem report, gitignore, sync-diverged and poison write paths. - architecture/backend.md (platform_alerts.py), reliability.md (the two backup kinds), workspace.md (the problem report). Path tokens and status lines only; no requirement text changes meaning. * docs(feature-flows): the moved alarms report through platform_alerts (#3254) The flow lines that state the old direct-create write path or a minted request-id shape, now that every in-repo platform emitter reports through platform_alerts.observe / clear: - git-sync-health.md: the two queue rows and the poller tree (sync failing, sync diverged, the two git-bloat kinds; row types kept). - database-backup.md: two kinds keyed by backup_dir, 14-day lifetime, ended on the next ok. - operating-room.md: the flood alert, the #1677 exemption paragraph, poison, the seam section's "only four families" (plus the second sweep), the flood/episode side effects (operator_queue_sync), and a current-path note on the two #1677 revision-history rows. - effect-idempotency.md, github-sync.md, business-validation.md, system-manifest.md: the unguarded-effect, gitignore, validation and system-seed write paths. - user-docs/operations/operating-room.md: sync alerts now end on their own. * docs(git-sync): a divergence alert outlives a sync-failing freeze (#3254) The sync_diverged row is filed only while a divergence freeze is in force, but on the seam it stays for the whole episode: the platform ends it when diverged_since clears, not when sync_failing takes precedence over the freeze or the freeze stops. git-sync-health.md (the queue row) and requirements/github.md ("No item for red-but-not-frozen") now say both halves. * docs: seven more write-path statements the #3254 batch makes false (#3254) Found by review sweeps for the old write-path tokens (this slice's, and the backup/archive, retention and boot-housekeeping slices'), and folded into this slice because it is the one that carries the docs: - architecture/api-endpoints.md (ingestion caps): the third copy of the #1677 paragraph and of the flood-alert sentence now name observe as the write path, the kind's budgeted_type, the created-only notification and the episode's subject alert_budget:<type>. - architecture/reliability.md (the #1644 blast-radius guard): the retention alarm is a platform alert, one row per setting; "delivered" means observe returned created/updated/snoozed; the row's lifetime, 6-hour refresh, note_allowed clear and material keys are stated. The sentences that stay true are unchanged. - requirements/core-agent.md (problem report): a re-rate updates the day's pending item in place, the words reach it through observe's keep_text, and the click/comment order is decided inside the per-agent create lock (update_pending_problem_report and the second attach are gone). - requirements/roadmap.md: the system-seed alarms report through observe (subject system_seed:<kind>) and a later successful seed ends them. - requirements/infrastructure.md (BKUP-013): the backup alarms report through observe as two subjects, db_backup_failure and db_backup_stale, each ended by the platform on the next ok. - migrations/GIT_REMOTE_TOKEN_SCRUB_2026-09.md: the unreadable-workspace alarm is one row per agent, updated by each sweep and ended by the platform once a sweep can inspect the workspace (no longer one per day). Path tokens and status lines only. * docs: six more live lines that still stated the old alert write path (#3254) Fresh review of the closing slice, each line read against the merged code: - user-docs operating-room: every platform alert is now a condition (the "other platform alerts still file one card per event" sentence is gone), and the four kinds that need a person and never expire are named. - architecture agent-lifecycle and background-services: the divergence alert is the `sync_diverged:<agent>` subject on the seam, ended when its episode ends, not a `sync-diverged-{agent}-{diverged_since}` id collapsed by the request-id conflict target. - feature-flows operating-room: platform callers report through `platform_alerts.observe`; the five budgeted kinds are bounded inside its locked create (no `create_bounded_alert` route); the #3246 history row says the rest moved with #3254. - requirements security: the validation notifier is on the seam. - feature-flows git-sync-health: the maintenance alert ends only on the agent's own repack report, and a persisting condition is re-read every 6 h rather than filed once. * fix(migrations): chain the #3254 re-sweep after dev's head as 0105 (#3254) dev gained 0104_agent_sync_state_git_stats_at (#4006), which also revised 0103_a2a_caller_identity. With both on dev the version line had two heads, and `alembic upgrade head` on PostgreSQL would apply nothing (#2068). The re-sweep becomes 0105_platform_alert_resweep, revising 0104_agent_sync_state_git_stats_at. The id is renamed everywhere it appears: the file, its Revision ID / Revises lines, the migrations.py docstring, the tests/registry.json row, requirements/security.md §26.14 and feature-flows/operating-room.md. The SQLite entry stays last in MIGRATIONS, after agent_sync_state_git_stats_at. The revision has never been applied anywhere (the branch is unmerged), so a re-chain is correct and a merge revision is not needed. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01HWna79vVmnezQdhpaGRKbw * docs(operator-queue): the snooze silences one episode; the flood, budget, gitignore, backup and archive markers (#3254) dolho's I1 on this PR: these docs stated the platform-alert snooze as "the same reading files nothing for 7 days", which #4021's review fix (the flood, budget and gitignore kinds) and #4017's (the backup and log archive kinds) narrow to one episode. Each of those kinds now carries an episode marker that it lists as a material key, so a person's ending silences re-reads of that episode and a new episode files at once: queue_flood episode_started_at, alert_budget filled_by, gitignore_untracked push_id, db_backup_failure / db_backup_stale last_success_at, log_archive_unwritable last_writable_at. Also stated, as those branches implement it: - the flood cooldown is stamped before an episode's first reading only, and the 6-hour re-read is OPERATOR_QUEUE_FLOOD_REREAD_SECONDS; - a stale-backup re-alarm is stamped only when the reading landed, so a snoozed one is re-read daily; the weekly gate is not reset by an ok; - a keyless (pre-upgrade) ending of the inbox collision, a final-ending kind, files once more (#4020); for the snoozing kinds it counts as unchanged, which leaves an upgrade-day residual of at most 7 days. Lines: requirements security.md §26.14 (snooze, flood, budget), infrastructure.md BKUP-013, github.md; architecture reliability.md; flows operating-room.md, database-backup.md, github-sync.md; and user-docs operations/operating-room.md. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01HWna79vVmnezQdhpaGRKbw * fix(migrations): chain the #3254 re-sweep after dev's head as 0107 (#3254) dev gained 0105_idempotency_claim_token (#3921) and 0106_execution_chat_session_id (#3918) off 0104, so 0105_platform_alert_resweep forked the Alembic head again. Renamed to 0107_platform_alert_resweep with down_revision = "0106_execution_chat_session_id", in every place the id appears: the file and its Revision ID / Revises lines, the migrations.py "Mirrored by" docstring, the tests/registry.json row, requirements/security.md section 26.14 (2 lines) and feature-flows/operating-room.md. A re-chain, not a merge revision: the revision has never been applied anywhere. The upgrade body is unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01HWna79vVmnezQdhpaGRKbw * docs(approvals): every platform heads-up is on the one-row model now (#3254) approvals.md still said the other platform heads-ups file one row per event and move onto the model in a later release. With #3254's last slice every in-repo emitter is on the seam (EMITTERS_NOT_YET_ON_SEAM is empty), so the sentence now says that, and names the four person-only kinds that never expire, in the operating-room page's words. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01HWna79vVmnezQdhpaGRKbw * fix(migrations): chain the #3254 re-sweep after dev's head as 0111 (#3254) dev gained 0107_skill_sources_follow_bundled_pin (#4091) off 0106, then 0108_agent_memory_facts, 0109_agent_ownership_memory_opt_out and 0110_agent_memory_provenance (#4102) on top, so 0107_platform_alert_resweep forked the Alembic head again. Renamed to 0111_platform_alert_resweep with down_revision = "0110_agent_memory_provenance", in every place the id appears: the file and its Revision ID / Revises lines, the migrations.py "Mirrored by" docstring, the tests/registry.json row, requirements/security.md (2 lines) and feature-flows/operating-room.md. A re-chain, not a merge revision: the revision has never been applied anywhere. The upgrade body is unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01HWna79vVmnezQdhpaGRKbw * docs(operator-queue): a new divergence episode files after a person's ending (#3254) #4016 gives `sync_diverged` the material key `diverged_since`, so a person's ending snoozes re-reads of the episode they ended and a later episode files its own row inside the 7 days. Three lines said otherwise: - user-docs/operations/operating-room.md (Sync Health Alerts): drop "unless you dismissed the last one within the past 7 days". - requirements/github.md (one item per episode): drop "unless a person ended the last one inside the 7-day snooze" and name the material key. - requirements/security.md 26.14 (Snooze): add `sync_diverged` `diverged_since` to the episode markers. It stays out of the upgrade-day residual list: the pre-move emitter wrote `diverged_since` into every row's context, so a person-ended legacy row carries it. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01HWna79vVmnezQdhpaGRKbw * docs(operator-queue): name the sync_failing exception to the episode rule (#3254) The general rule says only the episode a person ended stays quiet. That holds for every kind with an episode marker, but `sync_failing` has none: its context (`last_sync_at`, `consecutive_failures`, the error excerpt) moves on every reading and the priority is always high, so after a person's ending, a new run of failures inside the 7-day snooze files nothing, even across a successful sync. The rule now says so, and that the sync-health dot still turns red. Kept as its own commit: drop it if #4016 gives `sync_failing` an episode marker. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01HWna79vVmnezQdhpaGRKbw --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
Summary
auto_sync_enabled=0) and agents with a failing push were never measured or repacked, so their git-health columns stayed NULL and thegit_bloatalert could not fire.agent_sync_state.git_stats_atcolumn (SQLite + Alembic0104).Changes
docker/base-image/agent_server/routers/git.py:_run_git_maintenance_onceand the health-only writer_record_git_health, which never toucheslast_sync_*.git gcis replaced bygit reflog expire --all+git prune --expire=1.hour.ago, because a plaingcrepacked a second time with no memory bound.docker/base-image/agent_server/auto_sync.py:run_one_cycleruns maintenance after every tick.src/backend/db/{migrations,schema,tables,sync_state}.py,migrations/versions/0104_agent_sync_state_git_stats_at.py,services/sync_health_service.py: the new column, coerced through_coerce_agent_timestamp.src/backend/canary/{snapshot.py,invariants/rd04_*,rd05_*},services/canary_alerts.py: the new collector (recorded incollectors_ranon every attempt; RD-04/RD-05 read it throughcollector_succeeded), the two invariants, and their alert names and runbooks.git-sync-health.mdflow,requirements/github.md,architecture/{agent-lifecycle,reliability,database}.md, the invariant catalog (§17), and one learnings fragment.Rollout notes
last_sync_atas the measurement time whilegit_stats_atis NULL, so agents still on the old base image do not page until they are recreated..git) needs one manualgit gcbefore the platform can keep it in shape.git reflog expire --allnow also runs on agents that never synced. It uses git's default expiry.GIT_MAINTENANCE_TIMEOUT_SECONDS. Until it finishes, operator git endpoints return 409agent_busy, and a pull tick skips asrepo_busy.Test Plan
cd tests && pytest unit/test_4000_git_maintenance_every_tick.py unit/test_4000_git_health_canary.py unit/test_4000_git_stats_at.py -vtest_4000_*red.payments_py.scripts/ci/check_alembic_heads.py: 1 head (0104).auto_sync_enabled=0, after one tickGET /api/git/status→sync_stateshowsgit_stats_at,loose_objectsandpack_count, andagent_sync_statecarries them.Out of scope, follow-ups in this sprint: #4001 (
--no-auto-maintenanceon platform fetches) and #4002 (setup.shvs the orphan sweeper, TMPDIR cleanup).Fixes #4000
🤖 Generated with Claude Code