Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 17 additions & 4 deletions Sources/QuotaCore/ResetAlarmTracker.swift
Original file line number Diff line number Diff line change
Expand Up @@ -462,14 +462,23 @@ public struct ResetAlarmTracker: Sendable {
}
if window.identity == nil { window.identity = observation.identity }
window.lastSeenAt = now
if let period = observation.periodSeconds { window.periodSeconds = period }

// A reading older than one already processed cannot say anything new.
if let observed = observedAt, let last = window.lastObservedAt, observed < last {
state.windows[key] = window
return nil
}

// A producer may reuse a window ID while switching its cadence.  Its reset time and remaining percentage no longer share the old baseline.  Keep the new reading as a baseline instead of comparing across periods.
if let observedPeriod = observation.periodSeconds,
let previousPeriod = window.periodSeconds,
abs(observedPeriod - previousPeriod) > ResetAlarmPolicy.resetDriftTolerance {
state.windows[key] = firstReading()
return nil
}
Comment on lines +472 to +478

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

kody code-review Bug medium

Cadence rebaseline drops known window identity on unstamped reading

The rebaseline discards the stored account binding because firstReading() carries nil for observation.identity, letting a later different account merge into the same window. Preserve window.identity when observation.identity is nil.

Prompt for LLM
File Sources/QuotaCore/ResetAlarmTracker.swift, lines 472-478:

Cadence rebaseline drops known window identity on unstamped reading

Cadence rebaseline replaces the window with firstReading() carrying observation.identity, wiping a known window.identity when the new reading is unstamped. Loses the account binding the identity branch preserves and lets a later different account be folded into the same window. Preserve window.identity when observation.identity is nil during the rebaseline.

Suggested code:

// A producer may reuse a window ID while switching its cadence. Its reset time and remaining percentage no longer share the old baseline. Keep the new reading as a baseline instead of comparing across periods.
if let observedPeriod = observation.periodSeconds,
   let previousPeriod = window.periodSeconds,
   abs(observedPeriod - previousPeriod) > ResetAlarmPolicy.resetDriftTolerance {
    var baseline = firstReading()
    if baseline.identity == nil { baseline.identity = window.identity }
    state.windows[key] = baseline
    return nil
}

Talk to Kody by mentioning @kody

Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.

​

​


if let period = observation.periodSeconds { window.periodSeconds = period }

let readAt = observedAt ?? now
var isReset = false
var isMidWindow = false
Comment on lines +474 to 484

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.

Bug: Timestamp-derived cadence changes across varying-length periods (such as 30 vs 31-day months) trigger window rebaselining, dropping genuine rollover alerts.
Severity: MEDIUM

Suggested Fix

Allow tolerance for expected calendar variations or normalize timestamp-derived periods into standard calendar-month intervals before comparing cadence changes against resetDriftTolerance.

Prompt for AI Agent
Review the code at the location below. A potential bug has been identified by an AI
agent. Verify if this is a real issue. If it is, propose a fix; if not, explain why it's
not valid.

Location: Sources/QuotaCore/ResetAlarmTracker.swift#L462-L484

Potential issue: The cadence-change guard rebaselines the window and returns nil
whenever `observation.periodSeconds` differs from stored `periodSeconds` by more than 15
minutes. Some quota readers, such as Grok subscriptions, dynamically calculate period
tokens and durations from start and end timestamps (e.g. 30 days vs 31 days). When month
lengths change across consecutive periods, the difference exceeds `resetDriftTolerance`.
This causes `advance()` to reset the baseline via `firstReading()` instead of processing
a rollover transition, permanently dropping genuine `.newPeriod` rollover alerts and
resetting `minimumRemaining`.

Did we get this right? 👍 / 👎 to inform future reviews.

Expand All @@ -487,13 +496,17 @@ public struct ResetAlarmTracker: Sendable {
: max(ResetAlarmPolicy.resetDriftTolerance,
window.periodSeconds.map { $0 * ResetAlarmPolicy.earlyResetShareOfPeriod }
?? ResetAlarmPolicy.earlyResetUnknownPeriod)
// A provider that resets early may move the reset time by less
// than `required`; the percentage jumping back up settles it.
// A correction is not proof of restored quota when a readable percentage stays flat or falls; allow an unmeasured scheduled rollover only after the old end passes.
var climbed = false
if let reading, let last = window.lastRemaining {
climbed = reading >= last + ResetAlarmPolicy.earlyResetRiseMargin
}
if jump > required || (jump > ResetAlarmPolicy.resetDriftTolerance && climbed) {
let rose = reading.flatMap { current in
window.lastRemaining.map { current > $0 + ResetAlarmPolicy.riseEpsilon }
} ?? false
let resetHasQuotaEvidence = rose || (hasPassed && reading == nil)
if (jump > required && resetHasQuotaEvidence)
|| (jump > ResetAlarmPolicy.resetDriftTolerance && climbed) {
Comment on lines +504 to +509

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

kody code-review Bug medium

Scheduled rollover missed with first measured reading after nil history

The check suppresses genuine resets because rose stays false when window.lastRemaining is nil, so resetHasQuotaEvidence blocks the hasPassed path. Treat missing window.lastRemaining as quota evidence when reading is present.

Prompt for LLM
File Sources/QuotaCore/ResetAlarmTracker.swift, lines 504-509:

Scheduled rollover missed with first measured reading after nil history

Scheduled rollover with first measured percentage after nil history never fires because rose is false when lastRemaining is nil. Genuine hasPassed jump with reading set but no prior baseline is suppressed, missing the reset the old jump>required caught. Treat missing lastRemaining as quota evidence for the hasPassed jump path, e.g. rose when window.lastRemaining is nil and reading is non-nil.

Talk to Kody by mentioning @kody

Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.

​

​

isReset = true
Comment on lines +504 to 510

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.

Bug: Genuine period rollovers without quota increases or with nil lastRemaining fail resetHasQuotaEvidence, silently shifting the window without triggering .newPeriod.
Severity: MEDIUM

Suggested Fix

Refine resetHasQuotaEvidence so that a passed window deadline (hasPassed) with a forward jump can still qualify as a reset when lastRemaining is nil or when usage is already at maximum (e.g., reading == 100), or separate stale deadline corrections from period rollover detection.

Prompt for AI Agent
Review the code at the location below. A potential bug has been identified by an AI
agent. Verify if this is a real issue. If it is, propose a fix; if not, explain why it's
not valid.

Location: Sources/QuotaCore/ResetAlarmTracker.swift#L504-L510

Potential issue: In `ResetAlarmTracker.swift`, `resetHasQuotaEvidence` is set to `rose
|| (hasPassed && reading == nil)`, where `rose` requires `reading > lastRemaining +
riseEpsilon` (with `riseEpsilon = 1`) and is false when `lastRemaining` is `nil`. For a
window whose period has ended (`hasPassed`), if the remaining quota remained unchanged
(e.g., 100% to 100%), increased by <= 1 point (due to rounding), or if `lastRemaining`
was `nil`, the rollover is not detected as a reset. It silently updates the window end
date without firing `.newPeriod` or re-baselining `minimumRemaining`.

// When the window had *not* reached its own scheduled end,
// any reset is an early / mid-cycle vendor restore rather than
Expand Down
53 changes: 45 additions & 8 deletions Tests/QuotaCoreTests/ResetAlarmPlanChangeTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -194,17 +194,54 @@ final class ResetAlarmPlanChangeTests: XCTestCase {
func testAMidCycleEventThatFellIsNeitherARefillNorAPlanChange() {
var tracker = ResetAlarmTracker()
let weekEnd = t0 + 7 * self.day
_ = tracker.process(weekly(at: t0, resetAt: weekEnd, remaining: 90), now: t0)
_ = tracker.process(weekly(at: t0, resetAt: weekEnd, remaining: 74), now: t0)

// The reported end jumps forward by more than half the period, which is
// how the tracker sees a period that ended early, and the quota falls.
// The saved MiniMax alerts held at 74%, then fell to 73% while the reported end moved forward.
let later = t0 + 2 * self.hour
let events = tracker.process(weekly(at: later, resetAt: t0 + 11 * self.day, remaining: 40), now: later)
let events = tracker.process(weekly(at: later, resetAt: t0 + 11 * self.day, remaining: 73), now: later)

XCTAssertTrue(events.isEmpty, "a future-end correction with falling quota is not a reset")

// Adopt the corrected end, then still report its actual scheduled rollover.
let scheduled = t0 + 11 * self.day + 60
let rollover = tracker.process(weekly(at: scheduled, resetAt: scheduled + 7 * self.day,
remaining: 100), now: scheduled)
XCTAssertEqual(rollover.map(\.windowId), ["7d"])
XCTAssertEqual(rollover.first?.reason, .newPeriod)
XCTAssertEqual(rollover.first?.endedPeriodResetAt, t0 + 11 * self.day)
XCTAssertFalse(rollover.first?.isVendorReset ?? true)
XCTAssertFalse(rollover.first?.isPlanChange ?? true)
}

/// The live MiniMax history recorded a stale 9:00 AM deadline, then a correction to Nov 8 at 6:00 PM with the weekly balance unchanged at 73%.
func testPassedMiniMaxDeadlineCorrectionWithUnchangedQuotaDoesNotAlertAndValidRolloverDoes() {
var tracker = ResetAlarmTracker()
func minimax(at observedAt: Date, resetAt: Date, remaining: Double) -> ResetAlarmObservation {
ResetAlarmObservation(scope: "local", providerId: "minimax", providerTitle: "MiniMax",
windowId: "local-mac:minimax:general:weekly", windowLabel: "7d", periodSeconds: 7 * day,
resetAt: resetAt, remainingPercent: remaining, observedAt: observedAt)
}

XCTAssertEqual(events.count, 1, "the early period end still has to be reported")
XCTAssertFalse(events[0].isVendorReset, "a quota that fell is not a refill")
XCTAssertFalse(events[0].isPlanChange, "a quota that fell is not a plan change")
XCTAssertNotEqual(events[0].reason, .planChange, "no event may claim the quota rose")
let firstRead = t0
let staleDeadline = firstRead + 25 * 60
_ = tracker.process([minimax(at: firstRead, resetAt: staleDeadline, remaining: 73)], now: firstRead)

let correctedRead = firstRead + 32 * 60
let correctedDeadline = staleDeadline + 5 * day + 9 * hour
let correction = tracker.process(
[minimax(at: correctedRead, resetAt: correctedDeadline, remaining: 73)], now: correctedRead)

XCTAssertTrue(correction.isEmpty, "a passed stale deadline corrected forward without quota restoration is not a new week")
let key = ResetAlarmTracker.windowKey(scope: "local", providerId: "minimax", windowId: "local-mac:minimax:general:weekly")
XCTAssertEqual(tracker.state.windows[key]?.periodResetAt, correctedDeadline)
XCTAssertEqual(tracker.state.windows[key]?.lastRemaining, 73)

let scheduled = correctedDeadline + 60
let rollover = tracker.process(
[minimax(at: scheduled, resetAt: scheduled + 7 * day, remaining: 100)], now: scheduled)
XCTAssertEqual(rollover.map(\.windowId), ["local-mac:minimax:general:weekly"])
XCTAssertEqual(rollover.first?.reason, .newPeriod)
XCTAssertEqual(rollover.first?.endedPeriodResetAt, correctedDeadline)
}

// MARK: The words
Expand Down
54 changes: 54 additions & 0 deletions Tests/QuotaCoreTests/ResetAlarmTrackerTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -452,6 +452,60 @@ final class ResetAlarmTrackerTests: XCTestCase {
XCTAssertEqual(events.first?.isVendorReset, false)
}

func testReusedWindowIdWithChangedCadenceStartsANewBaseline() {
var tracker = ResetAlarmTracker()
let intervalEnd = t0 + 3 * hour
_ = tracker.process(
[reading("general", period: 5 * hour, resetAt: intervalEnd, remaining: 80,
observedAt: t0, provider: "minimax", label: "5h")],
now: t0)

let switchedAt = t0 + hour
let weeklyEnd = t0 + 6 * day
let switched = tracker.process(
[reading("general", period: 7 * day, resetAt: weeklyEnd, remaining: 75,
observedAt: switchedAt, provider: "minimax", label: "7d")],
now: switchedAt)

XCTAssertTrue(switched.isEmpty, "A reused ID with a new cadence is a new baseline, not a reset.")
let key = ResetAlarmTracker.windowKey(scope: "local", providerId: "minimax", windowId: "general")
XCTAssertEqual(tracker.state.windows[key]?.periodSeconds, 7 * day)
XCTAssertEqual(tracker.state.windows[key]?.periodResetAt, weeklyEnd)
XCTAssertEqual(tracker.state.windows[key]?.minimumRemaining, 75)
XCTAssertEqual(tracker.state.windows[key]?.lastRemaining, 75)

let scheduledAt = weeklyEnd + hour
let scheduled = tracker.process(
[reading("general", period: 7 * day, resetAt: weeklyEnd + 7 * day, remaining: 100,
observedAt: scheduledAt, provider: "minimax", label: "7d")],
now: scheduledAt)
XCTAssertEqual(scheduled.map(\.reason), [.newPeriod], "A later weekly rollover with quota restored remains a scheduled reset.")
}

func testPreEndResetTimeCorrectionWithoutQuotaRiseIsNotAnAlarm() {
for remaining in [75.0, 65.0] {
var tracker = ResetAlarmTracker()
let initialEnd = t0 + 7 * day
_ = tracker.process(
[reading("weekly", period: 7 * day, resetAt: initialEnd, remaining: 75,
observedAt: t0, provider: "minimax", label: "7d")],
now: t0)

let correctedAt = t0 + day
let correctedEnd = initialEnd + 4 * day
let events = tracker.process(
[reading("weekly", period: 7 * day, resetAt: correctedEnd, remaining: remaining,
observedAt: correctedAt, provider: "minimax", label: "7d")],
now: correctedAt)

XCTAssertTrue(events.isEmpty, "A forward time correction without quota restoration must not announce a reset.")
let key = ResetAlarmTracker.windowKey(scope: "local", providerId: "minimax", windowId: "weekly")
XCTAssertEqual(tracker.state.windows[key]?.periodResetAt, correctedEnd)
XCTAssertEqual(tracker.state.windows[key]?.minimumRemaining, min(75, remaining))
XCTAssertEqual(tracker.state.windows[key]?.lastRemaining, remaining)
}
}

/// A rise is only new evidence when the period end holds still. When the
/// end moves too, the earlier rule already calls it an early reset — a
/// provider resetting a limit early moves its reset time and the quota
Expand Down
Loading