Skip to content

fix(batch): uncommitted-age proxy skips durable allowance policy holds - #23638

Merged
Git-on-my-level merged 5 commits into
mainfrom
lane/guardfix3-batchhold
Oct 26, 2026
Merged

Git-on-my-level merged 5 commits into
mainfrom
lane/guardfix3-batchhold

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Oct 25, 2026 •

Copy link
Copy Markdown
Member

What (lead task 20:47Z, bramp2 census 20:42Z)

The in-cluster guard's uncommitted_job_age_over_30m trip has read TRIP continuously: database/batch_pipeline_store.py:oldest() returned the oldest merge_pending job with no classification, and 131 historical allowance_exhausted policy holds (~26h old, durable compute_decision outcome=held recorded by scheduler.defer) pinned the fresh/recent oldest-age gauges at ~93,000s forever - masking any real admitted-but-stuck wedge behind a permanent false positive. Blocks the batch 10% gate.

Fix

oldest() walks a bounded 500-row FIFO prefix (early return keeps the healthy case a one-document read) and skips jobs whose durable compute_decision is outcome=held reason=allowance_exhausted. Everything else - unevaluated, admitted, or held for transient capacity reasons - is still measured, so a genuine 31-minute uncommitted commitment trips exactly as before. Review r1 P1 fix: a scan truncated at the bound with holds in every row returns the oldest scanned hold's age - failing toward tripping, never a fresh zero over an unmeasured commitment - while a naturally exhausted all-holds FIFO (fewer rows than the bound, the actual 131-hold census case) truthfully reads 0. Retiring the holds themselves stays with the BSTUCK custody track. The guard chart is unchanged (the trip semantics live in the producer); its README paragraph now states the exclusion.

Lead expansion (21:06Z) - same PR

(a) Rollback expiry + explicit clear: a guard rollback now expires after one full 15-minute lookback window of consecutive clean readings while rolled back - the Job keeps evaluating readings in the rolled-back state, tracks the clean streak in the persisted state ConfigMap, then clears itself by restoring workload-only metrics (floor stays 12; the arming/usable gates from #23601 own any scheduled reduction). Any trip/blind/unmeasured/low-sample reading restarts the streak; a real regression keeps re-tripping so its rollback never expires. Fixes the live state: the 13:50Z rollback has kept the floor schedule deferred_guard_rollback every hour with a clean fleet and no in-band clear. Also fixes the parked-reading path resetting the loaded state (which wiped the clock every run). The operator clear (remove the latency metric by HPA patch) stays documented in the README.

(b) Batch evidence isolation: batch trips/unknowns are still logged (ERROR) and recorded in the state ConfigMap but no longer fail the Job - every guard Job since 20:55Z ended Failed on the batch proxy while Parakeet was clean. Only a Parakeet TRIP/BLIND exits nonzero; floor-schedule errors still exit 2.

Chart 0.3.0 -> 0.3.1.

Tests (all lead-required cases)

backend/test.sh over metrics/scheduler/guards files: 310 passed locally, including the proxy pair (held 26h old -> no trip; admitted stuck 1860s -> trip), the r1/r2 boundary cases, expiry after exactly one clean window (not at 899s), streak restart on a blind reading, and batch TRIP with a clean Parakeet section exiting 0 while still logging the TRIP verdict.

Deploy note

The metric is produced by the batch pipeline workers: the fix rides the next batch worker rollout (op1's train), not the guard chart deploy. After it lands, the guard's batch_safety verdict should read PARTIAL/CLEAN instead of TRIP while the 131 holds remain parked.

Failure-Class: none

The in-cluster guard's uncommitted_job_age_over_30m trip has been reading
TRIP continuously: database/batch_pipeline_store.py oldest() returned the
oldest merge_pending job with no classification, and 131 historical
allowance_exhausted policy holds (~26h old, durable compute_decision
outcome=held recorded by scheduler.defer) made the fresh/recent oldest-age
gauges read ~93,000s forever. That masks any real admitted-but-stuck wedge
behind a permanent false positive (bramp2 census 2026-10-25 20:42Z).

oldest() now walks a bounded 500-row FIFO prefix and skips jobs whose
durable compute_decision is outcome=held reason=allowance_exhausted;
every other merge_pending job - unevaluated, admitted, or held for
transient capacity reasons - is still measured, so a genuine 31-minute-old
uncommitted commitment trips exactly as before. The healthy case stays a
one-document read via early return. A hold population beyond the bound
leaves nothing measurable and the gauge reads 0; retiring the holds
themselves stays with the BSTUCK custody track.

Tests: a policy-held job 26h old reads age 0 (no trip); the same fleet
plus an admitted job stuck 1860s reads 1860 (trip); the Firestore walk
skips a hold prefix, returns None when only holds exist, and
is_allowance_policy_hold accepts only the exact durable hold shape.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 25, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-25T21:59:00.446730Z e8d8f3f New commits
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@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: 597f516ff1

ℹ️ 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".

][:limit]

def oldest(self, priority, *, ready_only):
from database.batch_pipeline_store import is_allowance_policy_hold

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Move the new test imports to module scope

backend/AGENTS.md explicitly requires “All imports at module top level — never inside functions.” This new import inside MemoryStore.oldest() violates that convention, as does the import inside test_firestore_oldest_walks_past_policy_holds() in test_batch_pipeline_metrics.py. Move both imports to their respective module-level import blocks.

AGENTS.md reference: backend/AGENTS.md:L165-L165

Useful? React with 👍 / 👎.

Review r1 P1: when the oldest 500 pending rows are all allowance holds,
oldest() returned None, the metric published a fresh zero, and the guard
could read clean while a real admitted-but-stuck commitment sat unmeasured
just past the bound - a fail-open direction the pre-fix proxy never had.

The walk now distinguishes a naturally exhausted FIFO (every pending row is
a hold: zero is truthful) from a scan truncated at the bound with holds in
every row (an unmeasured commitment may exist beyond it): the truncated
case returns the oldest scanned hold's enqueued_at, failing toward tripping
and alerting, exactly the direction the proxy had before the exclusion.
…t fit

Review r2 P1: a FIFO of exactly 500 allowance holds also filled the scan
bound, so the fail-toward-tripping fallback fired on a complete scan and
the guard tripped with no unmeasured commitment anywhere.

The scan now fetches one sentinel row beyond the bound (limit + 1) and
applies the fallback only when that row exists: truncation means a row
past the bound, not a FIFO that happens to be exactly as long as the
bound. The healthy one-document early return is preserved.
…dence

Lead expansion 21:06Z on the proxy fix (both in this PR):

(a) A guard rollback expires after one full 15-minute lookback window of
    consecutive clean readings while rolled back: the Job keeps evaluating
    readings in the rolled-back state, tracks the clean streak in the
    persisted state, and then clears itself - restoring workload-only
    metrics with the floor still at 12, after which the arming/usable
    gates own any scheduled reduction. Any trip, blind, unmeasured or
    low-sample reading restarts the streak; a real regression keeps
    re-tripping, so its rollback never expires. Without this, the 13:50Z
    rollback kept the time-of-day floor deferred every hour with a healthy
    fleet and no in-band clear path. The parked-reading path also stopped
    resetting the loaded state, which wiped the clock every run. The
    explicit operator clear (remove the latency metric by HPA patch)
    stays documented in the README.

(b) The batch observer is isolated evidence (21:06Z ruling): batch trips
    and unknown inputs are still logged and recorded in the state
    ConfigMap but no longer fail the Job - every guard Job since 20:55Z
    ended Failed on the batch proxy while the Parakeet section was clean.
    Only a Parakeet TRIP/BLIND exits nonzero; a floor-schedule error
    still exits 2.

Chart 0.3.0 -> 0.3.1. Tests: expiry after exactly one clean window, no
expiry at 899s, streak restart on a blind reading, batch TRIP with a
clean Parakeet section exits 0 while still logging the TRIP verdict.

@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: 23d563bf04

ℹ️ 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 on lines +691 to +692
if hpa is not None and verdict != 'BLIND':
rollback_expires = advance_rollback_state(state, rolled_back(hpa['spec']), reading, now)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve the rollback clock through scheduled decision passes

With floorSchedule.enabled: true in the production values, every rolled-back run calls decide(), whose advance() returns a new state dictionary containing only the arming fields and discards state['rollback']. Consequently, this call initializes since and clean_since to the current time on every reading, so rollback expiry never fires and the scheduled floor remains deferred indefinitely. Using the existing FakeClient with the schedule enabled and clean readings at 1000, 1900, and 2800 reproduces both clocks resetting each time without any HPA clear. Preserve the rollback bookkeeping through advance() and cover expiry with the production schedule enabled.

Useful? React with 👍 / 👎.

… passes

Review r3 P1: with the schedule installed (the production shape), a
rolled-back HPA takes decide()'s parked path, and advance() rebuilds the
state dict from scratch - dropping the rollback streak keys every run, so
the clean clock restarted on every Job and the rollback could never reach
the 900-second expiry; the floor schedule stayed deferred indefinitely.

The parked path now carries the 'rollback' entry across advance()'s
rebuild when the arming identity is unchanged, so the streak survives Job
restarts and five-minute cadence; a spec change (different identity)
deliberately restarts it.

@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: e8d8f3fb9f

ℹ️ 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 on lines +700 to +703
elif hpa is not None and state.get('rollback'):
# An unreadable section never counts as clean: keep the clock, restart
# the clean streak.
state['rollback']['clean_since'] = None

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Reset the rollback clean streak when the HPA read fails

If the HPA GET fails during a rollback, hpa remains None, so this condition preserves rollback.clean_since even though the run records a BLIND reading. With the production schedule enabled, clean readings at 1000 and 1900 separated by an HPA read failure at 1600 still apply the rollback-clear patch at 1900. This counts the unreadable interval toward the required consecutive-clean window and removes the safety latch prematurely. Reset an existing clean streak on every BLIND run, including failures before the HPA is loaded.

Useful? React with 👍 / 👎.

Comment on lines +698 to +699
if hpa is not None and verdict != 'BLIND':
rollback_expires = advance_rollback_state(state, rolled_back(hpa['spec']), reading, now)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Include Kubernetes health checks in rollback-expiry readings

While rolled back, decide() returns through its parked branch before adding scheduling failures, HPA_not_ScalingActive, or ready_shortfall to the reading, so passing that reading into the new expiry logic treats these ongoing failures as clean. With the production schedule enabled, desired replicas at 12, ready replicas at 8, and ScalingActive=False, otherwise healthy Prometheus values still clear the rollback after 900 seconds. Run the Kubernetes health checks before the parked return, or include them explicitly in expiry eligibility, so the guard cannot automatically release its safety latch while those rollback conditions remain active.

Useful? React with 👍 / 👎.

@Git-on-my-level
Git-on-my-level merged commit a0ffe88 into main Oct 26, 2026
64 of 66 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/guardfix3-batchhold branch October 26, 2026 01:08
Git-on-my-level added a commit that referenced this pull request Oct 27, 2026
…ted re-evaluation (#23767)

## What (lead ruling 0e021b, follow-up to #23638)

#23638 made the batch uncommitted-age proxy
(`database/batch_pipeline_store.py:oldest()` ->
`omi_batch_pipeline_oldest_age_seconds` -> in-cluster guard
`uncommitted_job_age_over_30m`) skip durable allowance policy holds. In
prod the proxy still flaps: 0 at most samples, ~54h at some. The source
is priority-1 allowance holds (enqueued 10-24) that, at the flap moment,
read `state=retry attempt=0 merge_pending=true` with **no**
`compute_decision`, and a minute later carry `held/allowance_exhausted`
again.

Mechanism: `Scheduler.defer()` on `admission_refused=True` with no
`held_reason` (an unevaluated admission RPC) deliberately pops
`compute_decision` ("Preserve BLIND instead of a false hold"). So a held
job whose re-evaluation comes back unevaluated loses its hold marker
until the next evaluation re-holds it; during that gap `oldest()`
measures it as a real commitment and the guard trips falsely.

## Fix

- `defer()` records a separate durable `last_policy_hold = {reason, at}`
alongside every held `compute_decision`. The unevaluated path is
unchanged: `compute_decision` is still popped, so outside readers still
see BLIND, never a false hold.
- `admission.authorize()` pops `last_policy_hold` in the same
transaction that seals an `allowed` decision; a later hold with a
different reason overwrites it.
- Luna review P2: `Scheduler.pull()` pops `last_policy_hold` when it
issues a lease the pump will dispatch **without** admission (same
predicate as the pump's `required` gate: `requires_compute_admission`
false and `offline_admission_enabled(owner, 'batch')` false, e.g. after
offline enforcement is turned off). That lease is a real commitment, so
a stale parked hold can never hide it from the proxy.
- `is_allowance_policy_hold()` keeps the current decision authoritative
whenever one is recorded; only when the decision is absent does it fall
back to `last_policy_hold.reason == 'allowance_exhausted'`. An admitted
job that later hits an unevaluated dispatch recheck has no marker and is
still measured, so a genuine stuck commitment trips exactly as before.
- The #23638 scan bound, truncation sentinel, and oldest-hold fallback
are untouched.

## Tests

New regression tests (`tests/unit/test_batch_pipeline_metrics.py`, plus
case 2 in `test_batch_pipeline_admission.py` where the admission imports
already live, keeping the metrics file under the fast-unit CPU guard):
1. A held allowance job that goes through an unevaluated defer (decision
popped, BLIND preserved) still reads proxy age 0 ~54h later.
2. A hold replaced by a sealed `allowed` decision clears the marker; a
subsequent unevaluated defer leaves the job measured (1860s -> trip).
3. A lease that bypasses admission (enforcement off, unit not requiring
admission) clears the marker; the job is measured again (1900s -> trip).
4. Firestore `oldest()` walk with marker-only holds: skips them, returns
the commitment, and the truncation sentinel / exact-bound cases behave
as in #23638; the current decision wins over a stale marker.

Tests 1 and 4 fail on main and pass with the fix. Local runs: `test.sh`
over all 78 `tests/unit/test_batch_*.py` files plus
`test_incluster_guards.py` and `test_stt_cap_dispatch.py` - all passed
(exit 0).

## CI shard rebalance (lead ruling cca63f)

Touching `batch_pipeline_store.py` selects the full backend unit suite
(2332 files). `backend/scripts/run-unit-ci.sh` assigned files to the six
shards round-robin over the sorted list, so one inserted file shifts
every later file to the next shard. On this PR that left shard walls at
433-754s: shard 4 went over the 720s budget three times (754s, 740s,
725s) with every test passing.

- **Which file controls sharding:** `backend/scripts/run-unit-ci.sh`
(the workflow only passes `--shard 6/N`; `.github` is unchanged).
- **Change:** the runner gives each file a weight from the new
`backend/scripts/backend_unit_shard_weights.tsv`: the mean measured
pytest time per file over three full-suite runs (main 40433411631 and PR
runs 40435691671 and 40442350301), for the 1293 files at 2s or more.
Unlisted files weigh 1.1s, the mean of the rest. Files are dealt
heaviest-first to the least loaded shard. The deal is deterministic, so
every shard computes the same partition and their union is still exactly
the selection. With no weights table every file ties and the deal falls
back to round-robin.
- **Why / evidence:** shard wall tracks the shard's summed per-file test
time (wall ~ 0.45 x test-seconds). In leave-one-run-out checks,
round-robin's worst projected shard was 725-757s; the weighted deal's
worst was 653-708s. A first version weighted from a single run (611
files at 5s or more) measured 512-722s on CI. That showed single-run
weights are too noisy, so the table now uses the three-run mean.
Size-based weights without data were tried and rejected: small edits
reshuffled them up to ~701s.
- **Remaining margin:** the mean shard wall is ~620-680s depending on
runner speed, against the 720s budget, so a hot runner can still push
one shard near the line even with balanced shards (main's own shards ran
681-682s).
- **Tests:** `test_backend_unit_ci_runner.py` adds a weighted-deal case
(heavy files land one per shard, each shard keeps selection order, the
partition is exact). The existing round-robin partition test still
passes because unweighted files tie. The `test_workflow_contracts.py`
sharding contract now pins the weighted deal and the weights file
instead of the awk slice.
- No budget raise, no skip.

## Deploy note

Ships after the batch 5% soak (lead 0e021b); not during the deploy
exclusion hold. Rides the batch worker rollout like #23638. Jobs already
decisionless today gain the marker on their next held defer.

Failure-Class: none

🤖 Generated with [Claude Code](https://claude.com/claude-code)
YinkaAdepoju pushed a commit to YinkaAdepoju/omi that referenced this pull request Oct 27, 2026
…ted re-evaluation

Scheduler.defer pops compute_decision when an admission re-evaluation comes
back unevaluated (preserve BLIND, never a false hold). An allowance-held job
then read as a decisionless commitment until the next re-hold, so the
uncommitted-age proxy from BasedHardware#23638 flapped to ~54h and tripped the in-cluster
guard falsely.

defer now records last_policy_hold {reason, at} with every held decision;
admission clears it when it seals an allow, and a later hold overwrites it.
is_allowance_policy_hold keeps the current decision authoritative and falls
back to last_policy_hold only when no decision is recorded. The BLIND
contract, scan bound and truncation sentinel are unchanged.

Co-Authored-By: Claude Opus 5.5 <[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