Reset-aware quota state + Z.ai reset plausibility (Slice A, #151) #153
No reviewers
Labels
No labels
accessibility
bug
documentation
duplicate
enhancement
good first issue
help wanted
invalid
P1
P2
P3
question
wontfix
No milestone
No project
No assignees
2 participants
Notifications
Due date
No due date set.
Dependencies
No dependencies set.
Reference
Creatidy/scarcity-router!153
Loading…
Add table
Add a link
Reference in a new issue
No description provided.
Delete branch "reuse/reset-aware-quota-state"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Closes #151 (Slice A of the reuse-first reconstruction program, #150). Branch
reuse/reset-aware-quota-state, single commit422b04d, based ondevelop@f574e51c.What and why
Stage A of the reuse audit (#150) found that the perishable-quota state layer treats
resets_atas explanation-only data: freshness is TTL-only, so an observation taken before a window reset keeps presenting obsolete quota facts as fresh until the next poll — including a 0%-exhausted window whose reset has already passed. The upstream comparison (weave-os/routerusagepackage @e5133a6, Apache-2.0) treats a reset-crossed window as no-longer-exhausted/no-longer-trustworthy at the reset instant (ExhaustedAsOf); this PR ports that state mechanic into Scarcity Router's snapshot/registry model.Change (state mechanics only — no ranking-policy change)
resource_state.py— reset-crossing freshness.classify_freshnessgains optionalearliest_reset_at: when the evaluation instant has reached the earliest observed window reset, the observation isstaleregardless of TTL age.refresh_due(registry method and entry evaluation) additionally report a reset-crossed observation as due even when younger than the poll interval. No new vocabulary (stalealready exists), no health-status change, no scoring change; windows withoutresets_atbehave exactly as before.providers/zai.py— reset plausibility. For windows with an evidenced duration (five-hour, weekly), a claimed reset beyond duration + 60 s ahead of the retrieval instant is implausible drift:resets_atis omitted with the existingreset_unknownwindow diagnostic — never corrected. Resets at or before retrieval are preserved verbatim (obsolescence is the state layer's rule); existing fixtures with past-dated resets are untouched and still pass.docs/capacity-model.md(freshness amendment, dated),docs/providers.md(reset plausibility + CodexBar provenance),docs/codex-adapter-stage1-evidence.md(dated revalidation note: every adapter-consumed app-server surface unchanged throughrust-v0.157.1@36650394; client-owned dynamic-tool finding recorded in #150 for #132 child E).BEFORE / AFTER (per program rule 13)
classify_freshness(observed_at, now, ttl)— age-only;refresh_due— age-vs-interval only; Z.ai parser accepted any 13-digit reset for evidenced windows.stale/due; implausible far-future resets degrade toreset_unknown. No parallel path remains; no code deleted (pure extension of two functions + one parser rule).Tests
24 new deterministic tests (full gate green:
uv sync --only-dev,make check,uv run basedpyright0 errors,git diff --check; CI run #2035 success on the reviewed head):tests/test_resource_state.py::TestClassifyFreshnessResetCrossing(6): crossed → stale inside TTL; reset == now → stale; future → fresh; no reset → TTL-only semantics pinned; TTL staleness independent of future reset; malformed reset rejected.tests/test_resource_state.py::TestRegistryResetCrossing(9): exhausted (0%) window past reset reads stale; multi-window earliest-reset governance; both future → fresh; refresh-due on crossed reset despite young interval; not due when reset future; no-cadence → never due but still stale; worker-report path; no-resets shape unaffected end to end.tests/test_zai_parser.py::TestResetPlausibility(9): five-hour horizon (+5h+60s) boundary/just-over/far-future; weekly horizon; unknown-kind (TIME_LIMIT) exempt; past reset preserved; rest-of-window intact on omission; malformedretrieved_atstill rejected by the constructor.Reset-crossing test invariants correspond to weave-os
usage_test.go'sTestObserver_ResetAtExpiresBeforeWindowLength/TestSnapshot_ExhaustedAsOfHonorsResetWindowssemantics, re-specified against this repository's contract (no Go code vendored; Apache-2.0 attribution recorded in #151; no NOTICE change required — no code copied).Review record
Independent exact-head review of
422b04dposted as PR comment: APPROVED, zero MERGE_BLOCKERs, four DEFER findings (test-count arithmetic in this body — corrected; registry-level boundary pin; refresh-due ordering pin; informational trust-on-record note on the upstream SHA evidence).UX impact: none. Security classification (not security-critical) confirmed by the reviewer. Human merge gate remains open.UX impact
Assessed: positive, no regression. Operators see resources flip to
stale/refresh-due at window reset instead of serving stale quota numbers (state-aware remediation surfaces already renderstalehonestly); Z.ai reset values that cannot be trusted degrade to an explicit unknown-reset diagnostic instead of showing a misleading reset time. No new configuration, no new concepts, no error-text changes beyond the existing diagnostic.Security classification
Not security-critical: no credentials, no transport, no execution surface, no parsing of untrusted beyond quota JSON already bounded by the strict parser. Independent exact-head review completed; security gate not triggered per #151 classification (reviewer confirmed).
Review notes
_DIAGNOSTIC_CODESare untouched (git diff origin/develop..HEAD -- scarcity_router/capacity.py scarcity_router/scarcity.pyis empty).CREDIT_LIMIT, 30-day window,TIME_LIMIT (5,1)) — deliberately NOT in this PR.Verdict: APPROVED
UX impact: none — the change only makes displayed state more honest: reset-crossed resources now read
stale/refresh-due instead of serving quota numbers past their window reset, and an untrustable Z.ai reset degrades to the pre-existingreset_unknowndiagnostic rather than a misleading reset time. No new vocabulary, no new configuration, no new concepts, no error-text changes.Exact head reviewed:
422b04da6d0cf9f70bf9c80f16cd33bdb4c52d84onreuse/reset-aware-quota-state(worktree HEAD verified identical; Forgejo PR head sha verified identical; basedevelop@f574e51c). Targeted modules re-run read-only:tests.test_zai_parser+tests.test_resource_state= 166 tests, OK.Contract conformance — verified
f574e51c..422b04d; commit message accurate.git diff f574e51c..422b04d -- scarcity_router/capacity.py scarcity_router/scarcity.pyis empty;FRESHNESS_STATES(resource_state.py:187),RESOURCE_HEALTH_STATUSES(resource_state.py:170) and_DIAGNOSTIC_CODES(capacity.py:55) are byte-identical to base; no selector/ranking file touched (D-026/D-037 untouched).classify_freshness(resource_state.py:1516) gains only an optional keyword parameterearliest_reset_at=None; the sole internal caller (registry_snapshot, resource_state.py:1758) passesmin(resets) if resets else None; both refresh-due paths (refresh_dueresource_state.py:1732,_entry_refresh_dueresource_state.py:1813) share_reset_crossedso registry and per-entry evaluation cannot diverge. No other production callers exist (only__init__.pyre-exports).Correctness — verified
now→ stale:_age_seconds(now, reset) >= 0(resource_state.py:337, :1561); age 0 → stale. One second past the +duration+60s horizon → omitted, exactly at horizon → kept:_reset_implausibleuses strict>(zai.py:245); tests pin 18060s (kept) vs 18061s (omitted) againstRETRIEVED_AT(test_zai_parser.py:795+), arithmetic checked by hand._age_secondsreturns a negative float for a futureearlier(resource_state.py:294 — it does not raise;_age_or_rejectis the raising variant and is deliberately not used here), so_reset_crossedis False for future resets. Correct._CANONICAL_TS_RE, resource_state.py:180), so lexicographicmin(resets)is the chronological minimum. Correct.resets_atabsent: windows without a reset contribute nothing (_window_reset_instantsresource_state.py:320); TTL-only semantics pinned by tests (test_resource_state.pytest_no_reset_keeps_ttl_only_semantics,test_windows_without_resets_are_unaffected)._age_or_rejectruns before the reset disjunct in bothrefresh_due(resource_state.py:1727) and_entry_refresh_due(resource_state.py:1807); no-cadence resources still never due (poll_interval_seconds is None: continueprecedes the reset check).test_worker_report_path_honors_reset_crossing.test_parser_module_has_no_io_surfacestill passes; the new parser code uses onlydatetime.fromisoformat/timedelta— no clock, no I/O._parse_canonical_ts(zai.py:206) mirrors the existing_v_ts/_ts_to_datetimeZ-strip pattern and returns None unless the value parses as an aware timestamp; unparsable input fails safe to "keep" (prior behavior), and true input validation remains the snapshot constructor (tested). Timezone handling: only Z-form canonical values parse; both sides are aware UTC, so the subtraction is absolute-time correct. The UTC-only contract makes DST/week-boundary shifts not applicable.resets_atomitted + existingreset_unknown; parse failure → keep verbatim, never toward optimistic capacity). Exhausted (0%) windows stop pinning scarcity via obsolete facts, pertest_exhausted_window_past_reset_reads_stale.Test adequacy — all six required groups present
(1) classify_freshness: crossed/future/exactly-now/no-reset/malformed —
TestClassifyFreshnessResetCrossing(tests/test_resource_state.py:1223, 6 tests). (2) registry_snapshot incl. multi-window weekly-future + five-hour-crossed —TestRegistryResetCrossing(tests/test_resource_state.py:1301). (3) both refresh-due forms, young interval + no-cadence — same class. (4) exhaustion case — same class. (5) worker-report path — same class. (6) parser horizons, unknown-kind exemption, near-future kept, past kept, rest-of-window intact, malformedretrieved_atrejected —TestResetPlausibility(tests/test_zai_parser.py:795, 9 tests).Findings
nowboundary is pinned atclassify_freshnesslevel only; the two refresh-due paths use the identical>= 0comparison via shared_reset_crossed(resource_state.py:337) and are tested at crossed-1s, so divergence risk is negligible, but a one-line boundary case inTestRegistryResetCrossingwould pin it end to end.refresh_due(the ordering is structural —_age_or_rejectat resource_state.py:1727 precedes the disjunct — and future-observation rejection is covered by existing tests, so this is hardening, not a gap in #151's required groups).docs/codex-adapter-stage1-evidence.mdrevalidation note records external upstream facts (rust-v0.157.1@36650394…, per-surface delta list) that cannot be verified inside this review; the note is dated, attributed to #150 as the slice scope requires, and internally consistent with the pin (rust-v0.155.1) — no action needed for this PR.Security classification — supported
The diff contains no credential, transport, endpoint, or execution-surface change; the parser gains no I/O or clock surface (purity test green); the state layer gains no storage or network exposure. "Not security-critical" per #151 is supported; no reclassification needed and the additional security gate is correctly not triggered.
Docs amendments (capacity-model.md freshness paragraph, providers.md reset-plausibility paragraph, zai.py module docstring) match the implemented horizon math (duration + 60s margin, strict
>, evidenced five-hour/weekly windows only, past resets preserved, state layer owns obsolescence).Closing note: I am an independent reviewer; I did not merge and did not push. The PR remains open and the human merge gate remains open.