From a5e141fb7c6cec4dcf027cdcd85a50eed0766d38 Mon Sep 17 00:00:00 2001 From: Aly Raffauf Date: Fri, 20 Nov 2026 01:27:21 -0500 Subject: [PATCH] refactor(quota): decide the poll schedule in a pure module The poller actor mixed its schedule with process plumbing, so cadence, backoff and retirement could be checked only by timing a daemon. The rules move to `quota_schedule` (tick, enumerated, polled, delay, wait_seconds), and the actor runs the discovery and polls each step answers. History filter parsing moves from the server into `quota.filter_from`, and `quota.record` becomes public for the history test. quota_schedule_test replays generated ticks, discoveries, finished and crashed polls and on/off switches against a model of quota.md's rules; quota_history_test checks paging, filters, `since` and the latest readings against a scan of what was recorded. Removed from e2e/quota_test.py, and what now catches each defect: - cadence, busy interval and backoff timed on wall clock -> quota_schedule_test (and quota_test's wait examples) - QuotaRetirementTest, a removed account's in-flight poll finishing once -> quota_schedule_test - history order, paging, filters, since, partial filters, latest without a recovered failure -> quota_history_test, a_history_filter_names_all_three_or_none The scenario keeps raw readings for every account, the Antigravity heal, a second poll of one account, and the filter-bound continuation (14.4 s -> 2.6 s). --- apps/albedo/src/albedo/accounts/quota.gleam | 351 ++++++++---------- .../src/albedo/accounts/quota_schedule.gleam | 200 ++++++++++ apps/albedo/src/albedo/lifecycle/server.gleam | 26 +- .../albedo/accounts/quota_history_test.gleam | 206 ++++++++++ .../albedo/accounts/quota_schedule_test.gleam | 253 +++++++++++++ .../test/albedo/accounts/quota_test.gleam | 3 +- e2e/quota_test.py | 327 ++-------------- robot-docs/quota.md | 12 +- 8 files changed, 842 insertions(+), 536 deletions(-) create mode 100644 apps/albedo/src/albedo/accounts/quota_schedule.gleam create mode 100644 apps/albedo/test/albedo/accounts/quota_history_test.gleam create mode 100644 apps/albedo/test/albedo/accounts/quota_schedule_test.gleam diff --git a/apps/albedo/src/albedo/accounts/quota.gleam b/apps/albedo/src/albedo/accounts/quota.gleam index e46da594e..59861c4c7 100644 --- a/apps/albedo/src/albedo/accounts/quota.gleam +++ b/apps/albedo/src/albedo/accounts/quota.gleam @@ -13,6 +13,7 @@ //// errors exactly as the feed reported them, never anything derived. Phase 2 //// derives what it needs from these rows. +import albedo/accounts/quota_schedule as schedule import albedo_clock import albedo_process import albedo_protect @@ -40,11 +41,10 @@ import sqlight pub type Fetch = fn(String, json.Json, Int) -> Result(Report, String) -pub type Settings { - Settings(poll_seconds: Int, busy_poll_seconds: Int, enabled: Bool) -} +pub type Settings = + schedule.Settings -const default_settings = Settings(600, 120, True) +const default_settings = schedule.Settings(600, 120, True) /// `$ALBEDO_HOME/extensions.json` under `"quota"`, read like any extension's /// settings, and re-read every round so changes apply without a restart. @@ -57,7 +57,7 @@ fn load_settings() -> Settings { decode.int, ) use enabled <- decode.optional_field("enabled", True, decode.bool) - decode.success(Settings(poll_seconds, busy_poll_seconds, enabled)) + decode.success(schedule.Settings(poll_seconds, busy_poll_seconds, enabled)) } settings.load("quota", decoder, default_settings) |> result.unwrap(default_settings) @@ -66,7 +66,7 @@ fn load_settings() -> Settings { fn clamped(settings: Settings) -> Settings { let poll_seconds = int.clamp(settings.poll_seconds, 1, 86_400) - Settings( + schedule.Settings( poll_seconds, int.clamp(settings.busy_poll_seconds, 1, poll_seconds), settings.enabled, @@ -130,22 +130,6 @@ pub type Message { Down(process.Down) } -type Account { - Account( - /// provider <> "/" <> label: one polled account, never two polls at once. - key: String, - watched: Watched, - /// Wall-clock milliseconds for this account's next poll. - next_due: Int, - /// Consecutive failed polls, for backoff. - failures: Int, - /// The process polling now, so a crash frees the slot. - polling: Option(process.Pid), - /// Whether the latest discovery still lists this account. - listed: Bool, - ) -} - type State { State( home: String, @@ -153,13 +137,17 @@ type State { fetch: Fetch, /// Every installed extension's quota source, with its extension's name. sources: List(#(String, usage_feed.Source)), - accounts: Dict(String, Account), + /// When each account polls; the rules live in `quota_schedule`. + schedule: schedule.Schedule, + /// What each scheduled account polls. + watched: Dict(String, Watched), + /// The process polling each account now, so a crash frees its slot. + polls: Dict(process.Pid, String), self: Subject(Message), /// A tick is already scheduled. ticking: Bool, /// The process listing accounts now, so a crash cannot wedge it. enumerating: Option(process.Pid), - last_enumerated: Int, /// The runtime's key environment, for sources that poll key accounts. keys: KeyEnvironment, ) @@ -183,11 +171,12 @@ pub fn start( database, fetch, sources, + schedule.new(), + dict.new(), dict.new(), self, True, None, - 0, keys, )) |> actor.returning(self) @@ -202,120 +191,63 @@ pub fn start( |> actor.start } +/// Runs the schedule's step for each message and starts what it asks for. fn handle(state: State, message: Message) -> actor.Next(State, Message) { - case message { - Tick -> retick(State(..on_tick(state), ticking: False)) - Enumerated(targets) -> - retick(merged( - State(..state, enumerating: None), - targets, - albedo_clock.system_ms(), - )) - Polled(key, failed, busy, attempted_at) -> - retick(finished(state, key, failed, busy, attempted_at)) - Down(process.ProcessDown(_, pid, _)) -> retick(fell(state, pid)) - // The poller monitors processes only; a port is never one of them. - Down(process.PortDown(_, _, _)) -> actor.continue(state) - } -} - -fn on_tick(state: State) -> State { - let config = load_settings() + let settings = load_settings() let now = albedo_clock.system_ms() - case config.enabled { - False -> State(..state, accounts: dict.new()) - True -> { - let state = case - state.enumerating, - now - state.last_enumerated >= config.poll_seconds * 1000 - { - None, True -> enumerate_now(state, now) - _, _ -> state + case message { + Tick -> { + let #(next, effects) = schedule.tick(state.schedule, settings, now) + let state = State(..state, schedule: next, ticking: False) + let state = case settings.enabled { + False -> State(..state, watched: dict.new()) + True -> state } - start_due(state, now) + list.fold(effects, state, fn(state, effect) { + run_effect(state, effect, now) + }) + |> retick(settings) } - } -} - -/// Account discovery runs off the poller: a refresh may wait on the network. -/// The attempt is what the cadence counts from, so a discovery that fails -/// fast never spins. -fn enumerate_now(state: State, now: Int) -> State { - let self = state.self - let home = state.home - let sources = state.sources - let keys = state.keys - let pid = - process.spawn_unlinked(fn() { - process.send(self, Enumerated(enumerate(home, sources, keys))) - }) - let _ = process.monitor(pid) - State(..state, enumerating: Some(pid), last_enumerated: now) -} - -/// New accounts poll at once; an account that is polling now finishes first, -/// so its readings stay even if the account has since gone. -fn merged(state: State, targets: List(Watched), now: Int) -> State { - let fresh = - list.fold(targets, dict.new(), fn(accounts, watched) { - let key = key_of(watched.target) - let account = case dict.get(state.accounts, key) { - Ok(existing) -> Account(..existing, watched:, listed: True) - Error(_) -> Account(key, watched, now, 0, None, True) - } - dict.insert(accounts, key, account) - }) - let accounts = - dict.fold(state.accounts, fresh, fn(accounts, key, account) { - case dict.has_key(accounts, key), account.polling { - False, Some(_) -> - dict.insert(accounts, key, Account(..account, listed: False)) - _, _ -> accounts - } - }) - State(..state, accounts: accounts) -} - -fn start_due(state: State, now: Int) -> State { - let fetch = state.fetch - let database = state.database - let self = state.self - dict.fold(state.accounts, state, fn(state, key, account) { - case account.next_due <= now, account.polling { - True, None -> { - let watched = account.watched - let home = state.home - let pid = - process.spawn_unlinked(fn() { - let #(failed, busy) = run(fetch, database, watched, home) - process.send(self, Polled(key, failed, busy, now)) - }) - let _ = process.monitor(pid) - State( - ..state, - accounts: dict.insert( - state.accounts, - key, - Account(..account, polling: Some(pid)), - ), + Enumerated(targets) -> { + let listed = + list.map(targets, fn(watched) { #(key_of(watched.target), watched) }) + let next = + schedule.enumerated( + state.schedule, + list.map(listed, fn(entry) { entry.0 }), + now, ) - } - _, _ -> state + // A gone account still polling keeps what it polls until it finishes. + let fresh = dict.from_list(listed) + let kept = + dict.filter(state.watched, fn(key, _) { + dict.has_key(next.slots, key) && !dict.has_key(fresh, key) + }) + let watched = dict.merge(kept, fresh) + State(..state, schedule: next, watched:, enumerating: None) + |> retick(settings) } - }) -} - -/// Seconds until an account's next poll: the busy cadence while any limit is -/// at or above 80 percent or resets within fifteen minutes, the ordinary -/// cadence otherwise, and after `failures` failed polls in a row a backoff -/// that doubles six times at most and never waits past an hour. -pub fn wait_seconds(settings: Settings, failures: Int, busy: Bool) -> Int { - case failures, busy { - 0, True -> settings.busy_poll_seconds - 0, False -> settings.poll_seconds - _, _ -> - settings.poll_seconds * int.bitwise_shift_left(1, int.min(failures, 6)) - |> int.min(3600) + Polled(key, failed, busy, attempted_at) -> + finished(state, key, failed, busy, attempted_at, settings) + |> retick(settings) + Down(process.ProcessDown(_, pid, _)) -> + case state.enumerating, dict.get(state.polls, pid) { + Some(enumerating), _ if enumerating == pid -> + State( + ..state, + schedule: schedule.enumeration_ended(state.schedule), + enumerating: None, + ) + |> retick(settings) + // A spawned poll that crashed never answers `Polled`: free its slot + // and back the account off, so a crashing feed cannot wedge the + // schedule. + _, Ok(key) -> + finished(state, key, True, False, now, settings) |> retick(settings) + _, Error(Nil) -> actor.continue(state) + } + // The poller monitors processes only; a port is never one of them. + Down(process.PortDown(_, _, _)) -> actor.continue(state) } } @@ -325,91 +257,73 @@ fn finished( failed: Bool, busy: Bool, attempted_at: Int, + settings: Settings, ) -> State { - case dict.get(state.accounts, key) { - Error(_) -> state - Ok(account) if !account.listed -> - State(..state, accounts: dict.delete(state.accounts, key)) - Ok(account) -> { - let failures = case failed { - True -> account.failures + 1 - False -> 0 - } - let wait = wait_seconds(load_settings(), failures, busy) - State( - ..state, - accounts: dict.insert( - state.accounts, - key, - Account( - ..account, - failures: failures, - polling: None, - next_due: attempted_at + wait * 1000, - ), - ), - ) - } - } + let next = + schedule.polled(state.schedule, key, failed, busy, attempted_at, settings) + State( + ..state, + schedule: next, + polls: dict.filter(state.polls, fn(_, polling) { polling != key }), + watched: case dict.has_key(next.slots, key) { + True -> state.watched + False -> dict.delete(state.watched, key) + }, + ) } -/// A spawned poll that crashed never answers `Polled`: free its slot and -/// back the account off, so a crashing feed cannot wedge the schedule. -fn fell(state: State, pid: process.Pid) -> State { - case state.enumerating { - Some(enumerating) if enumerating == pid -> State(..state, enumerating: None) - _ -> - case - dict.to_list(state.accounts) - |> list.find(fn(entry) { entry.1.polling == Some(pid) }) - { - Error(_) -> state - Ok(#(key, _)) -> - finished(state, key, True, False, albedo_clock.system_ms()) +/// Account discovery and each poll run off the poller: a refresh may wait on +/// the network. +fn run_effect(state: State, effect: schedule.Effect, now: Int) -> State { + let self = state.self + case effect { + schedule.Enumerate -> { + let home = state.home + let sources = state.sources + let keys = state.keys + let pid = + process.spawn_unlinked(fn() { + process.send(self, Enumerated(enumerate(home, sources, keys))) + }) + let _ = process.monitor(pid) + State(..state, enumerating: Some(pid)) + } + schedule.Poll(key) -> + case dict.get(state.watched, key) { + Error(Nil) -> finished(state, key, True, False, now, load_settings()) + Ok(watched) -> { + let fetch = state.fetch + let database = state.database + let home = state.home + let pid = + process.spawn_unlinked(fn() { + let #(failed, busy) = run(fetch, database, watched, home) + process.send(self, Polled(key, failed, busy, now)) + }) + let _ = process.monitor(pid) + State(..state, polls: dict.insert(state.polls, pid, key)) + } } } } /// One tick in flight at a time: the next is scheduled for whichever account -/// or enumeration is soonest, so the busy cadence is honoured exactly. -fn retick(state: State) -> actor.Next(State, Message) { +/// or discovery is soonest, so the busy cadence is honoured exactly. +fn retick(state: State, settings: Settings) -> actor.Next(State, Message) { case state.ticking { True -> actor.continue(state) False -> { - let _ = albedo_clock.send_after(state.self, tick_delay(state), Tick) + let delay = + schedule.delay(state.schedule, settings, albedo_clock.system_ms()) + let _ = albedo_clock.send_after(state.self, delay, Tick) actor.continue(State(..state, ticking: True)) } } } -fn tick_delay(state: State) -> Int { - let config = load_settings() - case config.enabled { - False -> config.poll_seconds * 1000 - True -> { - let now = albedo_clock.system_ms() - let due = - [ - list.map(dict.values(state.accounts), fn(account) { account.next_due }), - [state.last_enumerated + config.poll_seconds * 1000], - ] - |> list.flatten - let delay = case minimum(due) { - None -> config.poll_seconds * 1000 - Some(when) -> when - now - } - int.clamp(delay, 250, config.poll_seconds * 1000) - } - } -} - -fn minimum(values: List(Int)) -> Option(Int) { - list.fold(values, None, fn(best, value) { - case best { - Some(current) -> Some(int.min(current, value)) - None -> Some(value) - } - }) +/// Seconds until an account's next poll; see `quota_schedule.wait_seconds`. +pub fn wait_seconds(settings: Settings, failures: Int, busy: Bool) -> Int { + schedule.wait_seconds(settings, failures, busy) } /// One poll of one account, off the poller: whatever comes back is recorded @@ -511,7 +425,7 @@ pub fn initialise(database: store.Store) -> Result(Nil, String) { /// Only readings: one row per limit the report carried, or one row carrying /// the report's error when it carried none. -fn record( +pub fn record( database: store.Store, target: Target, plan: Option(String), @@ -671,6 +585,37 @@ fn erlang_rfc3339_to_system_time( options: List(#(atom.Atom, atom.Atom)), ) -> Int +/// The history filter a request's parameters name: every reading, or one +/// account's limit when provider, account and limit all are given, from +/// `quota_since` when that is given too. Anything else is refused. +pub fn filter_from( + parameters: List(#(String, String)), +) -> Result(Filter, String) { + case + list.key_find(parameters, "quota_provider"), + list.key_find(parameters, "quota_account"), + list.key_find(parameters, "quota_limit"), + list.key_find(parameters, "quota_since") + { + Ok(provider), Ok(account), Ok(limit_id), Ok(since) -> + case parse_rfc3339(since) { + Ok(since_ms) -> Ok(Trail(provider, account, limit_id, Some(since_ms))) + Error(_) -> Error("invalid quota_since") + } + Ok(provider), Ok(account), Ok(limit_id), Error(_) -> + Ok(Trail(provider, account, limit_id, None)) + Error(_), Error(_), Error(_), Error(_) -> Ok(Everything) + Error(_), Error(_), Error(_), Ok(_) -> + Error( + "quota_since requires quota_provider, quota_account, and quota_limit", + ) + _, _, _, _ -> + Error( + "quota_provider, quota_account, and quota_limit must all be provided together", + ) + } +} + pub fn parse_rfc3339(stamp: String) -> Result(Int, Nil) { let opts = [#(atom.create("unit"), atom.create("millisecond"))] case diff --git a/apps/albedo/src/albedo/accounts/quota_schedule.gleam b/apps/albedo/src/albedo/accounts/quota_schedule.gleam new file mode 100644 index 000000000..f9ca413a9 --- /dev/null +++ b/apps/albedo/src/albedo/accounts/quota_schedule.gleam @@ -0,0 +1,200 @@ +//// The quota poller's schedule, without processes or a clock: which accounts +//// are due, which poll is in flight, when discovery runs next, and how long +//// the poller sleeps. The poller in `quota` runs the effects this answers and +//// reports back what happened, with the time, so every rule here is a pure +//// step a test can replay against a model. + +import gleam/dict.{type Dict} +import gleam/int +import gleam/list +import gleam/option.{type Option, None, Some} +import gleam/string + +pub type Settings { + Settings(poll_seconds: Int, busy_poll_seconds: Int, enabled: Bool) +} + +/// One polled account, keyed by `provider <> "/" <> label`. +pub type Slot { + Slot( + /// Wall-clock milliseconds for this account's next poll. + next_due: Int, + /// Consecutive failed polls, for backoff. + failures: Int, + /// A poll of this account is running now. + polling: Bool, + /// The latest discovery still lists this account. + listed: Bool, + ) +} + +pub type Schedule { + Schedule( + slots: Dict(String, Slot), + /// A discovery is running now. + enumerating: Bool, + last_enumerated: Int, + ) +} + +/// What the poller must start. +pub type Effect { + /// List the accounts; answer with `enumerated`, or `enumeration_ended`. + Enumerate + /// Poll this account; answer with `polled`. + Poll(key: String) +} + +pub fn new() -> Schedule { + Schedule(dict.new(), False, 0) +} + +/// A tick at `now`: discovery when its cadence is due and none is running, +/// and a poll of every listed account that is due and not polling. Turned +/// off, the schedule forgets every account. +pub fn tick( + schedule: Schedule, + settings: Settings, + now: Int, +) -> #(Schedule, List(Effect)) { + case settings.enabled { + False -> #(Schedule(..schedule, slots: dict.new()), []) + True -> { + let #(schedule, discovery) = case + schedule.enumerating, + now - schedule.last_enumerated >= settings.poll_seconds * 1000 + { + False, True -> #( + Schedule(..schedule, enumerating: True, last_enumerated: now), + [Enumerate], + ) + _, _ -> #(schedule, []) + } + let due = + dict.to_list(schedule.slots) + |> list.filter(fn(entry) { + { entry.1 }.next_due <= now && !{ entry.1 }.polling + }) + |> list.map(fn(entry) { entry.0 }) + |> list.sort(string.compare) + let slots = + list.fold(due, schedule.slots, fn(slots, key) { + dict.upsert(slots, key, fn(slot) { + let assert Some(slot) = slot + Slot(..slot, polling: True) + }) + }) + #( + Schedule(..schedule, slots:), + list.append(discovery, list.map(due, Poll)), + ) + } + } +} + +/// Discovery listed `keys` at `now`. A new account is due at once; one that +/// is polling now finishes first even if it is gone, so its reading is kept. +pub fn enumerated( + schedule: Schedule, + keys: List(String), + now: Int, +) -> Schedule { + let fresh = + list.fold(keys, dict.new(), fn(slots, key) { + let slot = case dict.get(schedule.slots, key) { + Ok(existing) -> Slot(..existing, listed: True) + Error(_) -> Slot(now, 0, False, True) + } + dict.insert(slots, key, slot) + }) + let slots = + dict.fold(schedule.slots, fresh, fn(slots, key, slot) { + case dict.has_key(slots, key), slot.polling { + False, True -> dict.insert(slots, key, Slot(..slot, listed: False)) + _, _ -> slots + } + }) + Schedule(..schedule, slots:, enumerating: False) +} + +/// Discovery ended without a list, as when its process crashed. +pub fn enumeration_ended(schedule: Schedule) -> Schedule { + Schedule(..schedule, enumerating: False) +} + +/// A poll of `key` attempted at `attempted_at` finished. An account +/// discovery no longer lists is dropped; any other is due again after +/// `wait_seconds`. A crashed poll is a failed one. +pub fn polled( + schedule: Schedule, + key: String, + failed: Bool, + busy: Bool, + attempted_at: Int, + settings: Settings, +) -> Schedule { + case dict.get(schedule.slots, key) { + Error(_) -> schedule + Ok(slot) if !slot.listed -> + Schedule(..schedule, slots: dict.delete(schedule.slots, key)) + Ok(slot) -> { + let failures = case failed { + True -> slot.failures + 1 + False -> 0 + } + let wait = wait_seconds(settings, failures, busy) + Schedule( + ..schedule, + slots: dict.insert( + schedule.slots, + key, + Slot( + ..slot, + failures:, + polling: False, + next_due: attempted_at + wait * 1000, + ), + ), + ) + } + } +} + +/// Milliseconds until the next tick: the soonest due account or discovery, +/// at least 250 and at most the ordinary cadence. +pub fn delay(schedule: Schedule, settings: Settings, now: Int) -> Int { + case settings.enabled { + False -> settings.poll_seconds * 1000 + True -> { + let due = [ + schedule.last_enumerated + settings.poll_seconds * 1000, + ..list.map(dict.values(schedule.slots), fn(slot) { slot.next_due }) + ] + let soonest = minimum(due) |> option.unwrap(now) + int.clamp(soonest - now, 250, settings.poll_seconds * 1000) + } + } +} + +/// Seconds until an account's next poll: the busy cadence while any limit is +/// at or above 80 percent or resets within fifteen minutes, the ordinary +/// cadence otherwise, and after `failures` failed polls in a row a backoff +/// that doubles six times at most and never waits past an hour. +pub fn wait_seconds(settings: Settings, failures: Int, busy: Bool) -> Int { + case failures, busy { + 0, True -> settings.busy_poll_seconds + 0, False -> settings.poll_seconds + _, _ -> + settings.poll_seconds * int.bitwise_shift_left(1, int.min(failures, 6)) + |> int.min(3600) + } +} + +fn minimum(values: List(Int)) -> Option(Int) { + list.fold(values, None, fn(best, value) { + case best { + Some(current) -> Some(int.min(current, value)) + None -> Some(value) + } + }) +} diff --git a/apps/albedo/src/albedo/lifecycle/server.gleam b/apps/albedo/src/albedo/lifecycle/server.gleam index b905801d0..d37f37b18 100644 --- a/apps/albedo/src/albedo/lifecycle/server.gleam +++ b/apps/albedo/src/albedo/lifecycle/server.gleam @@ -1421,30 +1421,8 @@ fn protocol_server( 0, )) use filter <- result.try( - case - list.key_find(parameters, "quota_provider"), - list.key_find(parameters, "quota_account"), - list.key_find(parameters, "quota_limit"), - list.key_find(parameters, "quota_since") - { - Ok(provider), Ok(account), Ok(limit_id), Ok(since_str) -> - case quota.parse_rfc3339(since_str) { - Ok(since_ms) -> - Ok(quota.Trail(provider, account, limit_id, Some(since_ms))) - Error(_) -> Error(sdk_http_api.invalid("invalid quota_since")) - } - Ok(provider), Ok(account), Ok(limit_id), Error(_) -> - Ok(quota.Trail(provider, account, limit_id, None)) - Error(_), Error(_), Error(_), Error(_) -> Ok(quota.Everything) - Error(_), Error(_), Error(_), Ok(_) -> - Error(sdk_http_api.invalid( - "quota_since requires quota_provider, quota_account, and quota_limit", - )) - _, _, _, _ -> - Error(sdk_http_api.invalid( - "quota_provider, quota_account, and quota_limit must all be provided together", - )) - }, + quota.filter_from(parameters) + |> result.map_error(sdk_http_api.invalid), ) use samples <- result.try( quota.history(runtime.ledger(host), filter, before, limit + 1) diff --git a/apps/albedo/test/albedo/accounts/quota_history_test.gleam b/apps/albedo/test/albedo/accounts/quota_history_test.gleam new file mode 100644 index 000000000..edf82a00b --- /dev/null +++ b/apps/albedo/test/albedo/accounts/quota_history_test.gleam @@ -0,0 +1,206 @@ +//// Reading quota samples back (quota.md "Reading them back"), against a +//// linear scan of what was recorded. The defects: history out of newest-first +//// order, a page that skips or repeats a row, a filter or `since` that keeps +//// another limit's or an older row, the latest reading not the newest one, +//// and a failure kept as the latest after the account answered again. The +//// filter a request names is parsed by `filter_from`, whose refusals are +//// checked too. + +import albedo/accounts/quota +import albedo/runtime +import albedo_property +import albedo_sdk/store +import albedo_sdk/usage_feed +import gleam/json +import gleam/list +import gleam/option.{None, Some} +import gleam/order +import gleam/string +import qcheck.{type Generator} + +type Report { + Report( + provider: String, + account: String, + /// The limits it carried; none records one failure row. + limits: List(String), + observed_at: Int, + ) +} + +/// One recorded row, as the scan sees it. +type Row { + Row(provider: String, account: String, limit: String, observed_at: Int) +} + +pub fn history_and_latest_match_a_scan_of_what_was_recorded_test_() -> albedo_property.Timed { + use <- albedo_property.within(3600) + use #(reports, filter, page) <- albedo_property.run( + 100, + qcheck.tuple3(reports(), filter(), qcheck.bounded_int(1, 4)), + ) + let assert Ok(host) = runtime.start_with_extensions(":memory:", []) + let database = runtime.ledger(host) + let assert Ok(_) = quota.initialise(database) + list.each(reports, fn(report) { + quota.record( + database, + usage_feed.Target(report.provider, report.account, json.null()), + None, + list.map(report.limits, fn(id) { + usage_feed.Limit(id, id, Some(50.0), None, None, None, None, "ok") + }), + case report.limits { + [] -> Some("no quota") + _ -> None + }, + report.observed_at, + ) + }) + let rows = + list.flat_map(reports, fn(report) { + case report.limits { + [] -> [Row(report.provider, report.account, "", report.observed_at)] + limits -> + list.map(limits, fn(id) { + Row(report.provider, report.account, id, report.observed_at) + }) + } + }) + // Newest first, then paged by the last id each page returned. + let expected = list.reverse(rows) |> list.filter(matches(_, filter)) + let paged = pages(database, filter, page, 0, [], list.length(rows) + 1) + assert list.map(paged, row_of) == expected + assert list.all(list.window_by_2(paged), fn(pair) { pair.0.id > pair.1.id }) + let assert Ok(latest) = quota.latest(database) + assert list.sort(list.map(latest, row_of), compare_rows) + == list.sort(latest_of(rows), compare_rows) + runtime.stop(host) +} + +pub fn a_history_filter_names_all_three_or_none_test() -> Nil { + let trail = [ + #("quota_provider", "p"), + #("quota_account", "a"), + #("quota_limit", "x"), + ] + assert quota.filter_from([]) == Ok(quota.Everything) + assert quota.filter_from(trail) == Ok(quota.Trail("p", "a", "x", None)) + let assert Ok(quota.Trail("p", "a", "x", Some(_))) = + quota.filter_from([#("quota_since", "2026-01-01T00:00:00Z"), ..trail]) + let assert Error(_) = + quota.filter_from([#("quota_since", "not-a-timestamp"), ..trail]) + let assert Error(_) = quota.filter_from([#("quota_account", "a")]) + let assert Error(_) = + quota.filter_from([#("quota_since", "2026-01-01T00:00:00Z")]) + Nil +} + +fn pages( + database: store.Store, + filter: quota.Filter, + size: Int, + before: Int, + seen: List(quota.Sample), + left: Int, +) -> List(quota.Sample) { + assert left > 0 as "paging never ended" + let assert Ok(page) = quota.history(database, filter, before, size) + assert list.length(page) <= size + case list.last(page) { + Error(Nil) -> seen + Ok(last) -> + pages(database, filter, size, last.id, list.append(seen, page), left - 1) + } +} + +fn matches(row: Row, filter: quota.Filter) -> Bool { + case filter { + quota.Everything -> True + quota.Trail(provider, account, limit, since) -> + row.provider == provider + && row.account == account + && row.limit == limit + && case since { + None -> True + Some(since) -> row.observed_at >= since + } + } +} + +/// The newest row of each account, provider and limit, except a failure row +/// when a later row of a real limit shows the account answered. +fn latest_of(rows: List(Row)) -> List(Row) { + let indexed = list.index_map(rows, fn(row, index) { #(index, row) }) + list.filter_map(indexed, fn(entry) { + let #(index, row) = entry + let newer = + list.filter(indexed, fn(other) { + other.0 > index + && { other.1 }.provider == row.provider + && { other.1 }.account == row.account + }) + let superseded = + list.any(newer, fn(other) { { other.1 }.limit == row.limit }) + let answered = + row.limit == "" && list.any(newer, fn(other) { { other.1 }.limit != "" }) + case superseded || answered { + True -> Error(Nil) + False -> Ok(row) + } + }) +} + +fn row_of(sample: quota.Sample) -> Row { + Row(sample.provider, sample.account, sample.limit_id, sample.observed_at) +} + +fn compare_rows(a: Row, b: Row) -> order.Order { + let key = fn(row: Row) { + row.provider <> "/" <> row.account <> "/" <> row.limit + } + string.compare(key(a), key(b)) +} + +fn reports() -> Generator(List(Report)) { + qcheck.generic_list( + qcheck.map4( + one_of(["p", "q"]), + one_of(["a", "b"]), + qcheck.from_generators(qcheck.return([]), [ + qcheck.return(["x"]), + qcheck.return(["x", "y"]), + qcheck.return(["y"]), + ]), + qcheck.bounded_int(0, 5), + fn(provider, account, limits, step) { + Report(provider, account, limits, 1_000_000 + step * 1000) + }, + ), + qcheck.bounded_int(0, 12), + ) +} + +fn filter() -> Generator(quota.Filter) { + qcheck.from_generators(qcheck.return(quota.Everything), [ + qcheck.map4( + one_of(["p", "q"]), + one_of(["a", "b"]), + one_of(["x", "y", ""]), + qcheck.option_from(qcheck.bounded_int(0, 5)), + fn(provider, account, limit, since) { + quota.Trail( + provider, + account, + limit, + option.map(since, fn(step) { 1_000_000 + step * 1000 }), + ) + }, + ), + ]) +} + +fn one_of(values: List(String)) -> Generator(String) { + let assert [first, ..rest] = values + qcheck.from_generators(qcheck.return(first), list.map(rest, qcheck.return)) +} diff --git a/apps/albedo/test/albedo/accounts/quota_schedule_test.gleam b/apps/albedo/test/albedo/accounts/quota_schedule_test.gleam new file mode 100644 index 000000000..2af818ca4 --- /dev/null +++ b/apps/albedo/test/albedo/accounts/quota_schedule_test.gleam @@ -0,0 +1,253 @@ +//// The quota poller's schedule under generated histories of ticks, account +//// discoveries, finished and crashed polls, and the poller switched off and +//// on (quota.md "Polling"). The defects: two polls of one account at once, +//// a second discovery while one runs, an account polled before it is due or +//// never polled once due, a removed account polled again after its last poll +//// finished, a backoff other than the documented one, and a sleep outside +//// its bounds. A small model of the documented rules runs beside it. + +import albedo/accounts/quota_schedule.{type Effect, Enumerate, Poll, Settings} +import albedo_property +import gleam/dict.{type Dict} +import gleam/int +import gleam/list +import gleam/set.{type Set} +import gleam/string +import qcheck.{type Generator} + +const settings = Settings(10, 2, True) + +const off = Settings(10, 2, False) + +const keys = ["a", "b", "c", "d"] + +type Op { + /// Time passes, then the poller ticks. + Tick(advance_ms: Int) + /// The running discovery answers with these accounts. + Discovered(keys: List(String)) + /// The running discovery crashes. + DiscoveryCrashed + /// The `n`th poll in flight finishes, or crashes. + Finished(n: Int, failed: Bool, busy: Bool) + Crashed(n: Int) + Switch(enabled: Bool) +} + +type Model { + Model( + now: Int, + enabled: Bool, + listed: Set(String), + /// Each account's next due time and failures, while it is scheduled. + due: Dict(String, #(Int, Int)), + /// Polls running, with the time each was attempted. + flight: Dict(String, Int), + enumerating: Bool, + last_enumerated: Int, + ) +} + +pub fn the_schedule_polls_each_account_once_at_a_time_and_when_due_test_() -> albedo_property.Timed { + use <- albedo_property.within(3600) + use ops <- albedo_property.run( + 300, + qcheck.generic_list(op(), qcheck.bounded_int(1, 40)), + ) + let start = #( + quota_schedule.new(), + Model(1_000_000, True, set.new(), dict.new(), dict.new(), False, 0), + ) + let _ = + list.fold(ops, start, fn(state, op) { + let #(schedule, model) = state + step(schedule, model, op) + }) + Nil +} + +fn step( + schedule: quota_schedule.Schedule, + model: Model, + op: Op, +) -> #(quota_schedule.Schedule, Model) { + let config = case model.enabled { + True -> settings + False -> off + } + case op { + Tick(advance) -> { + let now = model.now + advance + let model = Model(..model, now:) + let #(schedule, effects) = quota_schedule.tick(schedule, config, now) + let model = check_tick(model, effects) + let delay = quota_schedule.delay(schedule, config, now) + assert delay >= 250 && delay <= config.poll_seconds * 1000 + #(schedule, model) + } + Discovered(found) if model.enumerating -> { + let found = list.unique(found) + let schedule = quota_schedule.enumerated(schedule, found, model.now) + let listed = set.from_list(found) + // A new account is due at once; one gone and idle leaves the schedule. + let due = + list.fold( + found, + dict.filter(model.due, fn(key, _) { + set.contains(listed, key) || dict.has_key(model.flight, key) + }), + fn(due, key) { + case dict.has_key(due, key) { + True -> due + False -> dict.insert(due, key, #(model.now, 0)) + } + }, + ) + #(schedule, Model(..model, listed:, due:, enumerating: False)) + } + DiscoveryCrashed if model.enumerating -> #( + quota_schedule.enumeration_ended(schedule), + Model(..model, enumerating: False), + ) + Finished(n, failed, busy) -> + finish(schedule, model, config, n, failed, busy) + Crashed(n) -> finish(schedule, model, config, n, True, False) + Switch(enabled) -> #(schedule, Model(..model, enabled:)) + _ -> #(schedule, model) + } +} + +/// What a tick must start, against the model, and the model after it. +fn check_tick(model: Model, effects: List(Effect)) -> Model { + case model.enabled { + False -> { + assert effects == [] as "a poller switched off started work" + Model(..model, due: dict.new(), listed: set.new()) + } + True -> { + let discovery = + !model.enumerating && model.now - model.last_enumerated >= 10_000 + assert list.contains(effects, Enumerate) == discovery + as "discovery started off its cadence, or twice at once" + let polled = + list.filter_map(effects, fn(effect) { + case effect { + Poll(key) -> Ok(key) + Enumerate -> Error(Nil) + } + }) + let expected = + dict.to_list(model.due) + |> list.filter(fn(entry) { + entry.1.0 <= model.now && !dict.has_key(model.flight, entry.0) + }) + |> list.map(fn(entry) { entry.0 }) + assert list.sort(polled, string.compare) + == list.sort(expected, string.compare) + as "the accounts polled are not exactly those due and idle" + let model = case discovery { + True -> Model(..model, enumerating: True, last_enumerated: model.now) + False -> model + } + Model( + ..model, + flight: list.fold(polled, model.flight, fn(flight, key) { + dict.insert(flight, key, model.now) + }), + ) + } + } +} + +fn finish( + schedule: quota_schedule.Schedule, + model: Model, + config: quota_schedule.Settings, + n: Int, + failed: Bool, + busy: Bool, +) -> #(quota_schedule.Schedule, Model) { + let flying = + dict.to_list(model.flight) + |> list.sort(fn(a, b) { string.compare(a.0, b.0) }) + case list.drop(flying, n % int.max(1, list.length(flying))) { + [] -> #(schedule, model) + [#(key, attempted_at), ..] -> { + let schedule = + quota_schedule.polled(schedule, key, failed, busy, attempted_at, config) + let flight = dict.delete(model.flight, key) + let due = case set.contains(model.listed, key), dict.get(model.due, key) { + True, Ok(#(_, failures)) -> { + let failures = case failed { + True -> failures + 1 + False -> 0 + } + dict.insert(model.due, key, #( + attempted_at + backoff(failures, busy) * 1000, + failures, + )) + } + _, _ -> dict.delete(model.due, key) + } + #(schedule, Model(..model, flight:, due:)) + } + } +} + +/// quota.md's cadence for `Settings(10, 2, _)`: the busy cadence while a +/// limit is close, the ordinary one otherwise, and after failures a wait +/// that doubles six times at most, never past an hour. +fn backoff(failures: Int, busy: Bool) -> Int { + case failures, busy { + 0, True -> 2 + 0, False -> 10 + _, _ -> int.min(3600, 10 * pow2(int.min(failures, 6))) + } +} + +fn pow2(n: Int) -> Int { + case n { + 0 -> 1 + _ -> 2 * pow2(n - 1) + } +} + +fn op() -> Generator(Op) { + qcheck.from_weighted_generators(#(5, qcheck.map(advance(), Tick)), [ + #( + 2, + qcheck.map( + qcheck.generic_list(key(), qcheck.bounded_int(0, 4)), + Discovered, + ), + ), + #(1, qcheck.return(DiscoveryCrashed)), + #( + 3, + qcheck.map3( + qcheck.small_non_negative_int(), + qcheck.bool(), + qcheck.bool(), + Finished, + ), + ), + #(1, qcheck.map(qcheck.small_non_negative_int(), Crashed)), + #(1, qcheck.map(qcheck.bool(), Switch)), + ]) +} + +/// Steps around the cadences, so accounts fall due, stay early, and wait +/// through backoff. +fn advance() -> Generator(Int) { + qcheck.from_generators(qcheck.return(0), [ + qcheck.return(1999), + qcheck.return(2000), + qcheck.return(10_000), + qcheck.bounded_int(1, 50_000), + ]) +} + +fn key() -> Generator(String) { + let assert [first, ..rest] = keys + qcheck.from_generators(qcheck.return(first), list.map(rest, qcheck.return)) +} diff --git a/apps/albedo/test/albedo/accounts/quota_test.gleam b/apps/albedo/test/albedo/accounts/quota_test.gleam index fcd41573b..65d9b1833 100644 --- a/apps/albedo/test/albedo/accounts/quota_test.gleam +++ b/apps/albedo/test/albedo/accounts/quota_test.gleam @@ -1,6 +1,7 @@ /// A failing account's backoff grows over hours before its caps apply, far /// past what an E2E poll can wait for. -import albedo/accounts/quota.{Settings} +import albedo/accounts/quota +import albedo/accounts/quota_schedule.{Settings} import gleam/list import gleeunit/should diff --git a/e2e/quota_test.py b/e2e/quota_test.py index 9bd48a5f5..bd518fd2e 100644 --- a/e2e/quota_test.py +++ b/e2e/quota_test.py @@ -1,30 +1,27 @@ -"""Quota readings land raw, each account keeps its own cadence, and failures back off. +"""Quota readings land raw for every account the poller can see. The daemon-wide poller maps every account it can see — an OAuth account from creds.json, an API-key profile whose base url names a feed — onto provide-usage -credentials and records each report as it came. This is the only place that -wiring is visible from outside, so it is E2E: the usage core itself is a fake -executable answering the `usage advance -` envelope (the real one needs +credentials, records each report as it came, and heals Antigravity's limit +marks from it. That wiring is visible only from outside: the usage core is a +fake executable answering the `usage advance -` envelope (the real one needs accounts), pointed at by ALBEDO_USAGE_CORE with short poll settings. -The cadence is asserted through the interval between one account's consecutive -readings, not through poll counts over wall time: counts race the machine, and -a hyper poll arriving a second late was read as "the busy cadence did not kick -in" when the schedule was exactly as configured. The intervals are what the -poller actually kept. +The schedule itself (cadence, backoff, one poll per account at a time, a +removed account's last poll) is quota_schedule_test's, and reading history +back is quota_history_test's. """ import json from datetime import datetime import os -from pathlib import Path import stat import tempfile import time import unittest import urllib.error -from harness import Albedo, Provider, exclusive, text, wait_until +from harness import Albedo, Provider, exclusive, text def milliseconds(timestamp): @@ -277,10 +274,6 @@ class QuotaTests(unittest.TestCase): } ) - def intervals(self, account): - times = self.observed(account) - return [later - earlier for earlier, later in zip(times, times[1:])] - def fake_errors(self): try: with open(os.path.join(self.core.name, "fake-error.txt")) as errors: @@ -296,7 +289,7 @@ class QuotaTests(unittest.TestCase): time.sleep(0.25) self.fail(message) - def test_readings_land_and_each_account_keeps_its_cadence(self): + def test_readings_land_raw_heal_marks_and_poll_again(self): # Readings land for every account: the OAuth account from creds.json, # the hyper-charm profile, and the deepseek profile. wanted = { @@ -416,224 +409,31 @@ class QuotaTests(unittest.TestCase): # Only the poll could mark gpt-oss: no legacy mark and no 429 named it. self.assertEqual(creds["limitedMeters"]["gpt-oss"], self.gpt_oss_reset) - # Enough polls of each account to read a cadence off the intervals. - self.wait_for( - lambda: len(self.observed("charm-hyper")) >= 5, - 60, - "the busy cadence never produced five polls: " - + json.dumps(self.intervals("charm-hyper")) - + self.fake_errors(), - ) - self.wait_for( - lambda: len(self.observed("fixture-account")) >= 3, - 60, - "the ordinary cadence never produced three polls: " - + json.dumps(self.intervals("fixture-account")) - + self.fake_errors(), - ) + # The poller keeps polling: a second reading of the busy account + # arrives on the schedule the poller set itself. Its cadence, backoff + # and retirement rules are quota_schedule_test's. self.wait_for( - lambda: len(self.observed("deepseek-fixture")) >= 2, - 60, - "the failure backoff never produced a second poll: " - + json.dumps(self.intervals("deepseek-fixture")) - + self.fake_errors(), - ) - - # The schedule as the poller kept it: one account's consecutive - # readings are one poll duration plus its wait, so each cadence shows - # up as an interval with generous bounds either side of its setting. - # The busy cadence (85 percent, resetting soon) is busyPollSeconds, - # the ordinary one is pollSeconds, and the failing account backs off - # past the ordinary cadence. - busy = self.intervals("charm-hyper") - ordinary = self.intervals("fixture-account") - backed_off = self.intervals("deepseek-fixture") - - def median(values): - return sorted(values)[len(values) // 2] - - message = ( - f"busy {busy}, ordinary {ordinary}, backed off {backed_off}, " - f"fake errors {self.fake_errors()!r}" + lambda: len(self.observed("charm-hyper")) >= 2, + 30, + "the busy account was never polled again: " + self.fake_errors(), ) - self.assertGreaterEqual(median(busy), BUSY_SECONDS * 900, message) - self.assertLess( - median(busy), - POLL_SECONDS * 900, - message + " — the busy account polled at the ordinary cadence", - ) - self.assertGreaterEqual(median(ordinary), POLL_SECONDS * 900, message) - self.assertLess(median(ordinary), POLL_SECONDS * 1700, message) - self.assertGreaterEqual( - min(backed_off), - POLL_SECONDS * 1800, - message + " — failures did not back off", - ) - - # The feed is the fake, so a driver failure ("usage is not built", the - # CLI crashing, the feed not finishing) is a bug in the host half, not - # weather. An exit-1 burst would surface here as readings carrying it. - failures = [ - row - for row in self.samples() - if milliseconds(row["observed_at"]) > self.since - and row["error"] - and "usage" in row["error"]["detail"] - ] - self.assertEqual(failures, [], "the usage driver failed against the fake") self.assertEqual(self.fake_errors(), "") - # The latest reading per account and limit is the newest sample, and - # history pages from it by row id, newest first. - latest = {(r["provider"], r["limit_id"]): r for r in self.readings()} - with self.app.api("/server?include=quota_history&limit=200") as response: - page = json.load(response)["quota_history"] - samples = page["items"] - ids = [sample["sequence"] for sample in samples] - self.assertTrue( - all(later < earlier for earlier, later in zip(ids, ids[1:])), - f"history is not newest first: {ids}", - ) - newest = max( - (s for s in samples if s["provider"] == "hyper"), - key=lambda s: s["sequence"], - ) - self.assertEqual( - newest["observed_at"], latest[("hyper", "primary")]["observed_at"] - ) - with self.app.api("/server?include=quota_history&limit=2") as response: - first = json.load(response)["quota_history"] - self.assertEqual(len(first["items"]), 2) - self.assertIsNotNone(first["next"]) - with self.app.api( - f"/server?include=quota_history&limit=2&next={first['next']}" - ) as response: - older = json.load(response)["quota_history"] - self.assertTrue(older["items"]) - self.assertTrue( - all( - sample["sequence"] < first["items"][-1]["sequence"] - for sample in older["items"] - ), - "quota continuation reached newer rows", - ) - - # An account that failed once and then answered has an old failure filed - # under the empty limit id. The latest readings drop it once a later - # reading of a real limit shows the account answering; deepseek, which - # never answers, keeps its failure. - self.wait_for( - lambda: any( - r["account_id"] != "fixture-account" - and r["provider"] == "anthropic" - and r["limit_id"] == "weekly" - for r in self.readings() - ), - 40, - "the recovering account never answered", - ) - recovered = [ - r - for r in self.readings() - if r["provider"] == "anthropic" and r["account_id"] != "fixture-account" - ] - self.assertEqual( - [r["limit_id"] for r in recovered], - ["weekly"], - f"a failure the account recovered from is still its latest reading: {recovered}", - ) - failures = [ - (r["provider"], r["limit_id"]) for r in self.readings() if r["error"] - ] - self.assertIn(("deepseek", ""), failures) - self.assertTrue( - any( - row["limit_id"] == "" and row["error"] - for row in self.samples() - if row["provider"] == "anthropic" - and row["account_id"] != "fixture-account" - ), - "the recovering account never recorded the failure this checks is dropped", - ) - - # Filtered history returns only that limit's rows newest-first. + # History pages through the server's signed continuation, which is + # bound to the filter it was issued for. Paging and filtering are + # quota_history_test's. hyper_filter = ( "quota_provider=hyper"a_account=charm-hyper"a_limit=primary" ) - with self.app.api( - f"/server?include=quota_history&limit=200&{hyper_filter}" - ) as response: - hyper_history = json.load(response)["quota_history"]["items"] - self.assertGreaterEqual(len(hyper_history), 5) - self.assertTrue( - all( - s["provider"] == "hyper" - and s["account_id"] == "charm-hyper" - and s["limit_id"] == "primary" - for s in hyper_history - ), - "filtered history returned observations from other limits", - ) - hyper_ids = [s["sequence"] for s in hyper_history] - self.assertTrue( - all(later < earlier for earlier, later in zip(hyper_ids, hyper_ids[1:])), - f"filtered history is not newest first: {hyper_ids}", - ) - - # quota_since in the future returns zero rows and next null. - future_since = "2099-01-01T00:00:00Z" - with self.app.api( - f"/server?include=quota_history&limit=200&{hyper_filter}"a_since={future_since}" - ) as response: - future_page = json.load(response)["quota_history"] - self.assertEqual(future_page["items"], []) - self.assertIsNone(future_page["next"]) - - # since between two readings drops the older. - cutoff = hyper_history[1]["observed_at"] - with self.app.api( - f"/server?include=quota_history&limit=200&{hyper_filter}"a_since={cutoff}" - ) as response: - bounded_items = json.load(response)["quota_history"]["items"] - self.assertTrue( - all( - milliseconds(s["observed_at"]) >= milliseconds(cutoff) - for s in bounded_items - ), - "quota_since kept observations older than cutoff", - ) - bounded_ids = [s["sequence"] for s in bounded_items] - self.assertIn(hyper_history[0]["sequence"], bounded_ids) - self.assertIn(hyper_history[1]["sequence"], bounded_ids) - self.assertNotIn(hyper_history[-1]["sequence"], bounded_ids) - - # Paging a filtered history with limit=1 follows next across all of that - # limit's rows with strictly decreasing sequence. - paged_seqs = [] - next_cursor = None - while True: - cursor_param = f"&next={next_cursor}" if next_cursor else "" - with self.app.api( - f"/server?include=quota_history&limit=1&{hyper_filter}{cursor_param}" - ) as response: - page_data = json.load(response)["quota_history"] - self.assertEqual(len(page_data["items"]), 1) - paged_seqs.append(page_data["items"][0]["sequence"]) - next_cursor = page_data["next"] - if not next_cursor: - break - self.assertEqual(paged_seqs, hyper_ids) - self.assertTrue( - all(later < earlier for earlier, later in zip(paged_seqs, paged_seqs[1:])), - "paged filtered sequence is not strictly decreasing", - ) - - # A cursor from one filter replayed on another is rejected 400. with self.app.api( f"/server?include=quota_history&limit=1&{hyper_filter}" ) as response: token = json.load(response)["quota_history"]["next"] self.assertIsNotNone(token) + with self.app.api( + f"/server?include=quota_history&limit=1&{hyper_filter}&next={token}" + ) as response: + self.assertEqual(len(json.load(response)["quota_history"]["items"]), 1) anthropic_filter = ( "quota_provider=anthropic"a_account=fixture-account"a_limit=weekly" ) @@ -642,86 +442,3 @@ class QuotaTests(unittest.TestCase): f"/server?include=quota_history&limit=1&{anthropic_filter}&next={token}" ) self.assertEqual(cm.exception.code, 400) - - # Partial filter (only quota_account) is 400. - with self.assertRaises(urllib.error.HTTPError) as cm: - self.app.api("/server?include=quota_history"a_account=charm-hyper") - self.assertEqual(cm.exception.code, 400) - - # quota_since without the trio is 400. - with self.assertRaises(urllib.error.HTTPError) as cm: - self.app.api(f"/server?include=quota_history"a_since={future_since}") - self.assertEqual(cm.exception.code, 400) - - # Bad since is 400. - with self.assertRaises(urllib.error.HTTPError) as cm: - self.app.api( - f"/server?include=quota_history&{hyper_filter}"a_since=not-a-timestamp" - ) - self.assertEqual(cm.exception.code, 400) - - # Filter parameters require include=quota_history. - with self.assertRaises(urllib.error.HTTPError) as cm: - self.app.api(f"/server?{hyper_filter}") - self.assertEqual(cm.exception.code, 400) - - -@exclusive -class QuotaRetirementTest(unittest.TestCase): - def test_a_removed_account_finishes_its_in_flight_poll_once(self): - with tempfile.TemporaryDirectory(prefix="quota-retirement-") as folder: - root = Path(folder) - core = root / "usage" - core.write_text(FAKE_USAGE) - core.chmod(0o700) - started = root / "retired-started" - release = root / "release-retired" - - def accounts(account): - return { - "anthropic": [ - { - "type": "oauth", - "access": "fixture-access", - "refresh": "fixture-refresh", - "expires": int(time.time() * 1000) + 3600000, - "accountId": account, - } - ] - } - - def prepare(app): - app.env["ALBEDO_USAGE_CORE"] = str(core) - app.write_extensions( - {"quota": {"pollSeconds": 3, "busyPollSeconds": 1}} - ) - app.store_secrets("accounts", accounts("retired-account")) - - def polls(app, account): - with app.api("/server?include=quota_history&limit=100") as response: - rows = json.load(response)["quota_history"]["items"] - return [row for row in rows if row["account_id"] == account] - - provider = Provider(lambda _: text("ok")) - with Albedo(provider, prepare=prepare) as app: - try: - wait_until(started.exists, 15, "first poll is in flight") - app.store_secrets("accounts", accounts("replacement-account")) - # A replacement sample proves discovery ran while the - # retired account's first poll was still blocked. - wait_until( - lambda: polls(app, "replacement-account"), - 15, - "discovery sees the replacement account", - ) - finally: - release.touch() - wait_until( - lambda: polls(app, "retired-account"), 15, "in-flight sample lands" - ) - wait_until( - lambda: len(polls(app, "replacement-account")) >= 3, - 15, - "poller advances through two more busy intervals", - ) - self.assertEqual(len(polls(app, "retired-account")), 1) diff --git a/robot-docs/quota.md b/robot-docs/quota.md index 6cbb358a1..71c755c3d 100644 --- a/robot-docs/quota.md +++ b/robot-docs/quota.md @@ -4,7 +4,11 @@ The daemon polls supported accounts for provider-reported quota readings. These readings are separate from the token usage recorded for [provider requests](provider-requests.md). [`quota.gleam`](../apps/albedo/src/albedo/accounts/quota.gleam) owns discovery, -scheduling, storage, and queries. +storage, and queries, and runs the schedule that +[`quota_schedule.gleam`](../apps/albedo/src/albedo/accounts/quota_schedule.gleam) +decides. The schedule is pure: the poller passes it each tick, discovery and +finished poll with the time, and starts the discovery and polls it answers. Keep +scheduling rules there, not in the actor. ## Accounts @@ -17,7 +21,7 @@ then asks the source of the extension each saved profile names for that profile's target. A target includes a provider, a non-secret account label, and credentials for the fetch. Discovery and individual polls run outside the poller actor. See -[`enumerate` and `start_due`](../apps/albedo/src/albedo/accounts/quota.gleam), +[`enumerate` and `run_effect`](../apps/albedo/src/albedo/accounts/quota.gleam), [provider contributions](plugins.md#provider-account-and-profile-contributions), and [authentication](auth.md). @@ -43,7 +47,9 @@ based on the ordinary interval, with the exponent capped at six and the wait capped at one hour. When discovery removes an account, its in-flight poll can finish and record its reading. Only accounts still listed by discovery are scheduled again. See -[`load_settings`, `wait_seconds`, and `is_busy`](../apps/albedo/src/albedo/accounts/quota.gleam). +[`load_settings` and `is_busy`](../apps/albedo/src/albedo/accounts/quota.gleam), +and +[`tick`, `polled`, and `wait_seconds`](../apps/albedo/src/albedo/accounts/quota_schedule.gleam). ## Readings -- knotmirror 0.0.1