From 9ad10f16f75c191157a2575898fb5c7bb3a410ba Mon Sep 17 00:00:00 2001 From: Jonathan Mohrbacher Date: Tue, 1 Dec 2026 10:13:42 -0500 Subject: [PATCH 1/2] [NO-JIRA] Add fleet k (k_local/s) behind --fleet-k in quota-watch and quota-replay MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Implements Phase 2 fleet k from docs/plans/2026-11-23-fleet-llm-ledger-design.md §2: - Compute k_fleet = k_local / s using oc_tags.opus_list_cost on both local and remote Max usage over [max(w_end - 7d, max_first_hour), w_end), where w_end is the oldest gated remote watermark (default --alert-stale-hosts = devbox so a sleeping Mac does not force holds). - Map remote emails to pool short names via --account-map (JSON in private quota-telemetry repo; null = explicit ignore for usage seat; unmapped warns and is excluded; only active pool members with non-null u7d count). - Hold last good k_fleet for up to 48h when a gated watermark lags (>3h) or when share computation fails (empty pool, unmatched remote rows, s < 1%), without refreshing its timestamp, then fall back to k_local. - Add k_fleet and k_scope as the last two columns of quota_watch_runs (preserving verdict at r[14]) with idempotent migration. k_scope distinguishes fresh vs held even when --fleet-k is off (local(fleet) / local(fleet-held)). - Keep vertex_usd on k_local; only burn_rate uses k_fleet when --fleet-k is set. - Ship --fleet-k OFF on cloudbox: 7-day forward replay (2026-11-24..2026-12-01, 2139 ticks) showed 0 verdict diffs (max |burn_h| diff 0.0013/h, max |zero_h| diff 0.083h) with k_fleet 1899..2362 (1/s = 2.28x..6.34x, latest s=0.159), because spillover was <=.51. --- hosts/cloudbox/llm-ledger.nix | 4 +- pkgs/llm-ledger/llm_ledger.py | 11 +- pkgs/llm-ledger/quota_watch.py | 491 ++++++++++++++++++++++++++-- pkgs/llm-ledger/test_quota_watch.py | 423 ++++++++++++++++++++++++ 4 files changed, 903 insertions(+), 26 deletions(-) diff --git a/hosts/cloudbox/llm-ledger.nix b/hosts/cloudbox/llm-ledger.nix index e659ea1c..0217c007 100644 --- a/hosts/cloudbox/llm-ledger.nix +++ b/hosts/cloudbox/llm-ledger.nix @@ -138,7 +138,9 @@ Check: TimeoutStartSec = "5min"; StateDirectory = "llm-quota-watch"; StateDirectoryMode = "0700"; - ExecStart = "${llmLedger}/bin/llm-ledger quota-watch --state-dir /var/lib/llm-quota-watch --alert-cmd ${driftAlert} --outlook-pushed-file /var/lib/llm-fleet/outlook-pushed --alert-stale-hosts devbox"; + # --fleet-k is intentionally OFF: 2026-12-01 7d replay showed 0/2139 verdict diffs + # (k_fleet is still computed and recorded in quota_watch_runs for observation). + ExecStart = "${llmLedger}/bin/llm-ledger quota-watch --state-dir /var/lib/llm-quota-watch --alert-cmd ${driftAlert} --outlook-pushed-file /var/lib/llm-fleet/outlook-pushed --alert-stale-hosts devbox --account-map /var/lib/llm-fleet/telemetry/account-map.json"; ExecStartPost = "${pkgs.coreutils}/bin/rm -f /var/lib/llm-quota-watch-failure/alerted"; Environment = [ "HOME=/home/dev" ]; NoNewPrivileges = true; diff --git a/pkgs/llm-ledger/llm_ledger.py b/pkgs/llm-ledger/llm_ledger.py index a83e1e13..08f44739 100755 --- a/pkgs/llm-ledger/llm_ledger.py +++ b/pkgs/llm-ledger/llm_ledger.py @@ -52,7 +52,8 @@ burn_6h REAL, burn_24h REAL, spill_6h REAL, spill_24h REAL, k REAL, zero_h REAL NOT NULL, vertex_usd REAL, next_refill_ts INTEGER, next_refill_amt REAL, - pool_n INTEGER NOT NULL, source TEXT NOT NULL, verdict TEXT); -- 'live' | 'replay' + pool_n INTEGER NOT NULL, source TEXT NOT NULL, verdict TEXT, + k_fleet REAL, k_scope TEXT); CREATE TABLE IF NOT EXISTS quota_forecast ( ts INTEGER PRIMARY KEY, headroom REAL NOT NULL, run_ts INTEGER NOT NULL); @@ -3862,6 +3863,8 @@ def main(argv: list[str] | None = None) -> int: qw_parser.add_argument("--host", default=socket.gethostname()) qw_parser.add_argument("--alert-stale-hosts", default="devbox", help="Comma-separated list of hosts to check for stale telemetry (default: devbox; empty string disables)") qw_parser.add_argument("--outlook-pushed-file", default=None, help="Path to file touched on successful outlook push; alerts if missing or older than 15 min") + qw_parser.add_argument("--fleet-k", action="store_true", default=False, help="Use fleet k (k_local/s) for spillover-to-burn conversion") + qw_parser.add_argument("--account-map", default="/var/lib/llm-fleet/telemetry/account-map.json", help="Path to JSON map of remote email -> short account name (null to ignore)") # quota-replay subcommand qr_parser = subparsers.add_parser("quota-replay") @@ -3871,6 +3874,8 @@ def main(argv: list[str] | None = None) -> int: qr_parser.add_argument("--exclude-account", action="append", default=None) qr_parser.add_argument("--host", default=socket.gethostname()) qr_parser.add_argument("--record", action="store_true", default=False, help="Record evaluated runs into quota_watch_runs") + qr_parser.add_argument("--fleet-k", action="store_true", default=False, help="Use fleet k (k_local/s) for spillover-to-burn conversion") + qr_parser.add_argument("--account-map", default="/var/lib/llm-fleet/telemetry/account-map.json", help="Path to JSON map of remote email -> short account name (null to ignore)") # quota-outlook subcommand qo_parser = subparsers.add_parser("quota-outlook") @@ -4037,6 +4042,8 @@ def _make_fallback(err_str: str) -> dict[str, Any]: host=args.host, alert_stale_hosts=args.alert_stale_hosts, outlook_pushed_file=args.outlook_pushed_file, + fleet_k=args.fleet_k, + account_map=args.account_map, ) if args.command == "quota-replay": @@ -4052,6 +4059,8 @@ def _make_fallback(err_str: str) -> dict[str, Any]: excluded=excluded, host=args.host, record=args.record, + fleet_k=args.fleet_k, + account_map=args.account_map, ) except quota_watch.QuotaRecordError: return 1 diff --git a/pkgs/llm-ledger/quota_watch.py b/pkgs/llm-ledger/quota_watch.py index 783a2572..05953493 100644 --- a/pkgs/llm-ledger/quota_watch.py +++ b/pkgs/llm-ledger/quota_watch.py @@ -17,9 +17,17 @@ import tempfile import time from collections.abc import Sequence +from pathlib import Path from typing import Any from zoneinfo import ZoneInfo +# Import oc_tags (sibling directory in repo checkout or beside this file in store) +try: + import oc_tags +except ImportError: + sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "oc-tags")) + import oc_tags + CAP: float = 0.98 RESET_DROP: float = 0.05 CARRY_MS: int = 15 * 60 * 1000 # 15 min @@ -37,8 +45,15 @@ GATEWAY_FEED_ALERT_MS = 30 * 60 * 1000 HORIZON_MS: int = 24 * 60 * 60 * 1000 # 24 h STEP_MS: int = 5 * 60 * 1000 # 5 min +HOUR_MS: int = 3600 * 1000 # 1 h +WEEK_MS: int = 7 * 24 * 3600 * 1000 # 7 d K_MIN_BURN: float = 0.5 STALE_INPUT_MS: int = 20 * 60 * 1000 # 20 min +FLEET_WATERMARK_LAG_MS: int = 3 * 3600 * 1000 # 3 h (matches fleet-stale) +FLEET_K_HOLD_MS: int = 48 * 3600 * 1000 # 48 h hold when a watermark lags +FLEET_MIN_COVERAGE_MS: int = 24 * 3600 * 1000 # minimum shared remote coverage window +FLEET_SHARE_MIN: float = 0.01 # plausibility floor (1%): avoids runaway k_fleet when local_u ~ 0 +DEFAULT_ACCOUNT_MAP: str = "/var/lib/llm-fleet/telemetry/account-map.json" NY_TZ = ZoneInfo("America/New_York") RECORD_TIMEOUT_S: float = 30.0 @@ -595,6 +610,348 @@ def subtract_excluded_max_7d( return max(0.0, max_7d - excl_7d) +def load_account_map( + path: str | None, + warn_missing: bool = False, +) -> dict[str, str | None] | None: + """Load remote email -> short account name map (null value = explicit ignore). + + Returns None if path is None, missing, unreadable, or invalid. + """ + if path is None: + return None + expanded = os.path.expanduser(path) + try: + with open(expanded, "r", encoding="utf-8") as f: + raw = json.load(f) + except FileNotFoundError: + if warn_missing: + sys.stderr.write(f"quota-watch: account map not found at {expanded}\n") + return None + except Exception as e: + sys.stderr.write(f"quota-watch: could not read account map {expanded}: {e}\n") + return None + + if not isinstance(raw, dict): + sys.stderr.write(f"quota-watch: account map {expanded} must be a JSON object\n") + return None + + parsed: dict[str, str | None] = {} + for k, v in raw.items(): + if not isinstance(k, str) or (v is not None and not isinstance(v, str)): + sys.stderr.write( + f"quota-watch: invalid entry in account map {expanded} for key {k!r}; ignoring map\n" + ) + return None + parsed[k] = v + return parsed + + +def load_fleet_max_units( + conn: sqlite3.Connection, + since_ms: int, + host: str | None = None, +) -> tuple[ + dict[str, tuple[int | None, int | None]], + dict[int, float], + dict[str, dict[int, float]], + dict[str, dict[int, float]], +]: + """Load remote coverage/watermarks and hourly Max list-price token units (opus_list_cost). + + Returns (remote_hosts_info, local_max_units, local_tc_acct_units, remote_max_acct_units), + where remote_hosts_info maps host -> (first_hour, exported_through). + All tables beyond `hourly` are optional so older DBs degrade cleanly. + """ + remote_hosts_info: dict[str, tuple[int | None, int | None]] = {} + try: + if host is not None: + wm_rows = conn.execute( + "SELECT host, first_hour, exported_through FROM remote_hosts WHERE host != ?", + (host,), + ).fetchall() + else: + wm_rows = conn.execute( + "SELECT host, first_hour, exported_through FROM remote_hosts" + ).fetchall() + for r_host, r_first, r_exp in wm_rows: + remote_hosts_info[str(r_host)] = ( + int(r_first) if r_first is not None else None, + int(r_exp) if r_exp is not None else None, + ) + except sqlite3.OperationalError: + pass + + local_max_units: dict[int, float] = {} + try: + h_rows = conn.execute( + "SELECT hour, SUM(input), SUM(output), SUM(cache_read), SUM(cache_write) " + "FROM hourly WHERE backend = 'max' AND hour >= ? GROUP BY hour", + (since_ms,), + ).fetchall() + for h, inp, out, cr, cw in h_rows: + if h is not None: + local_max_units[int(h)] = oc_tags.opus_list_cost( + inp or 0, out or 0, cr or 0, cw or 0 + ) + except sqlite3.OperationalError: + pass + + local_tc_acct_units: dict[str, dict[int, float]] = collections.defaultdict(dict) + try: + if host is not None: + tc_rows = conn.execute( + "SELECT account, hour, SUM(input), SUM(output), SUM(cache_read), " + "SUM(cache_write_5m + cache_write_1h) " + "FROM teamclaude_hourly WHERE host = ? AND hour >= ? " + "GROUP BY account, hour", + (host, since_ms), + ).fetchall() + else: + tc_rows = conn.execute( + "SELECT account, hour, SUM(input), SUM(output), SUM(cache_read), " + "SUM(cache_write_5m + cache_write_1h) " + "FROM teamclaude_hourly WHERE hour >= ? " + "GROUP BY account, hour", + (since_ms,), + ).fetchall() + for acct, h, inp, out, cr, cw in tc_rows: + if not acct or h is None: + continue + short_acct = acct.split("@")[0] if "@" in acct else acct + u = oc_tags.opus_list_cost(inp or 0, out or 0, cr or 0, cw or 0) + local_tc_acct_units[short_acct][int(h)] = ( + local_tc_acct_units[short_acct].get(int(h), 0.0) + u + ) + except sqlite3.OperationalError: + pass + + remote_max_acct_units: dict[str, dict[int, float]] = collections.defaultdict(dict) + try: + if host is not None: + r_rows = conn.execute( + "SELECT account, hour, SUM(input), SUM(output), SUM(cache_read), " + "SUM(cache_write_5m + cache_write_1h) " + "FROM remote_hourly WHERE backend = 'max' AND host != ? AND hour >= ? " + "GROUP BY account, hour", + (host, since_ms), + ).fetchall() + else: + r_rows = conn.execute( + "SELECT account, hour, SUM(input), SUM(output), SUM(cache_read), " + "SUM(cache_write_5m + cache_write_1h) " + "FROM remote_hourly WHERE backend = 'max' AND hour >= ? " + "GROUP BY account, hour", + (since_ms,), + ).fetchall() + for acct, h, inp, out, cr, cw in r_rows: + if h is None: + continue + raw_acct = acct or "" + u = oc_tags.opus_list_cost(inp or 0, out or 0, cr or 0, cw or 0) + remote_max_acct_units[raw_acct][int(h)] = ( + remote_max_acct_units[raw_acct].get(int(h), 0.0) + u + ) + except sqlite3.OperationalError: + pass + + return ( + remote_hosts_info, + local_max_units, + dict(local_tc_acct_units), + dict(remote_max_acct_units), + ) + + +def sum_hourly_window(hourly_map: dict[int, float], w_start_ms: int, w_end_ms: int) -> float: + """Sum hourly bucket values over [w_start_ms, w_end_ms).""" + return sum(v for h, v in hourly_map.items() if w_start_ms <= h < w_end_ms) + + +def compute_fleet_share( + w_end_ms: int, + local_max_units: dict[int, float], + local_tc_acct_units: dict[str, dict[int, float]], + remote_max_acct_units: dict[str, dict[int, float]], + account_map: dict[str, str | None], + active_pool_accounts: set[str], + excluded_accounts: set[str], + warned_unmapped: set[str] | None = None, + w_start_ms: int | None = None, +) -> float | None: + """Compute local host's share s of fleet Max usage over [w_start_ms, w_end_ms). + + Defaults to a 7-day window [w_end_ms - 7d, w_end_ms), or a clipped window when + w_start_ms is supplied (e.g. clipped to remote coverage start). + Both sides are measured in oc_tags.opus_list_cost token units. + Remote rows count only if their account maps (via account_map) to a member of + active_pool_accounts (pool members with non-null u7d). Accounts mapped to None + are explicitly ignored; unmapped accounts warn once to stderr and are excluded. + Returns None if the pool is empty, if non-ignored remote rows exist but none + match the pool, or if s < FLEET_SHARE_MIN. + """ + if not active_pool_accounts: + return None + + start_ms = w_end_ms - WEEK_MS if w_start_ms is None else w_start_ms + if w_end_ms - start_ms < FLEET_MIN_COVERAGE_MS: + return None + + local_u = sum_hourly_window(local_max_units, start_ms, w_end_ms) + if excluded_accounts and local_tc_acct_units: + excl_short = {a.split("@")[0] if "@" in a else a for a in excluded_accounts if a} + excl_u = sum( + sum_hourly_window(local_tc_acct_units[a], start_ms, w_end_ms) + for a in excl_short + if a in local_tc_acct_units + ) + local_u = max(0.0, local_u - excl_u) + + remote_u = 0.0 + remote_non_ignored_u = 0.0 + for raw_acct, h_map in remote_max_acct_units.items(): + u = sum_hourly_window(h_map, start_ms, w_end_ms) + if u <= 0.0: + continue + if raw_acct not in account_map: + remote_non_ignored_u += u + if warned_unmapped is None or raw_acct not in warned_unmapped: + if warned_unmapped is not None: + warned_unmapped.add(raw_acct) + sys.stderr.write( + f"quota-watch: unmapped remote account {raw_acct!r}; excluding from fleet k\n" + ) + continue + mapped = account_map[raw_acct] + if mapped is None: + continue + remote_non_ignored_u += u + if mapped in active_pool_accounts: + remote_u += u + + if remote_non_ignored_u > 0.0 and remote_u <= 0.0: + return None + + fleet_u = local_u + remote_u + if local_u <= 0.0 or fleet_u <= 0.0: + return None + s = local_u / fleet_u + if s < FLEET_SHARE_MIN: + return None + return s + + +def _valid_hold(hold_state: Any, T: int) -> float | None: + """Return held k_fleet if hold_state is valid and <= FLEET_K_HOLD_MS old.""" + if not isinstance(hold_state, dict): + return None + kf = _safe_float(hold_state.get("k_fleet")) + ts = _safe_int(hold_state.get("ts")) + if kf is None or kf <= 0.0 or ts is None: + return None + age_ms = T - ts + if 0 <= age_ms <= FLEET_K_HOLD_MS: + return kf + return None + + +def _parse_host_list(hosts: str | Sequence[str] | None) -> list[str]: + if hosts is None: + return [] + if isinstance(hosts, str): + return [h.strip() for h in hosts.split(",") if h.strip()] + return [str(h).strip() for h in hosts if str(h).strip()] + + +def resolve_fleet_k( + k_local: float | None, + T: int, + remote_watermarks: dict[str, int | None | tuple[int | None, int | None]], + local_max_units: dict[int, float], + local_tc_acct_units: dict[str, dict[int, float]], + remote_max_acct_units: dict[str, dict[int, float]], + account_map: dict[str, str | None] | None, + active_pool_accounts: set[str], + excluded_accounts: set[str], + hold_state: Any, + fleet_k_enabled: bool, + warned_unmapped: set[str] | None = None, + required_hosts: Sequence[str] | None = None, +) -> tuple[float | None, float | None, str, dict[str, Any] | None]: + """Resolve (k_burn, k_fleet_recorded, k_scope, new_hold_state). + + `remote_watermarks` maps host -> exported_through OR host -> (first_hour, exported_through). + When `required_hosts` is non-empty (e.g. `--alert-stale-hosts`, defaulting to `devbox`), + only those hosts gate watermark lag (so a legitimately sleeping Mac does not trigger holds); + otherwise all remote hosts in `remote_watermarks` are gated. + The share window ends at the oldest gated watermark (capped at T) and starts at + max(w_end - 7d, max_first_hour_of_gated_hosts) so both sides are compared over identical + coverage. When gated watermarks lag (>3h) or fresh computation fails, holds the last good + k_fleet for up to FLEET_K_HOLD_MS (48 h) without refreshing its timestamp, then falls back + to k_local. + """ + if k_local is None: + return None, None, "local", hold_state if isinstance(hold_state, dict) else None + + # Normalize remote_watermarks values to (first_hour, exported_through) + norm_hosts: dict[str, tuple[int | None, int | None]] = {} + for h, val in remote_watermarks.items(): + if isinstance(val, tuple): + norm_hosts[h] = (val[0], val[1]) + else: + norm_hosts[h] = (None, val) + + gated = [h for h in (required_hosts or []) if h] + if not gated: + gated = list(norm_hosts.keys()) + + watermarks_fresh = False + oldest_wm: int | None = None + max_first_hour: int | None = None + if account_map is not None and gated and all( + h in norm_hosts and norm_hosts[h][1] is not None for h in gated + ): + wm_vals = [norm_hosts[h][1] for h in gated if norm_hosts[h][1] is not None] + oldest_wm = min(wm_vals) + first_vals = [norm_hosts[h][0] for h in gated if norm_hosts[h][0] is not None] + if first_vals: + max_first_hour = max(first_vals) + if T - oldest_wm <= FLEET_WATERMARK_LAG_MS: + watermarks_fresh = True + + if watermarks_fresh and oldest_wm is not None and account_map is not None: + w_end_ms = (min(T, oldest_wm) // HOUR_MS) * HOUR_MS + w_start_ms = w_end_ms - WEEK_MS + if max_first_hour is not None and max_first_hour > w_start_ms: + w_start_ms = max_first_hour + s = compute_fleet_share( + w_end_ms=w_end_ms, + w_start_ms=w_start_ms, + local_max_units=local_max_units, + local_tc_acct_units=local_tc_acct_units, + remote_max_acct_units=remote_max_acct_units, + account_map=account_map, + active_pool_accounts=active_pool_accounts, + excluded_accounts=excluded_accounts, + warned_unmapped=warned_unmapped, + ) + if s is not None: + k_fleet = k_local / s + new_hold = {"k_fleet": k_fleet, "ts": T} + if fleet_k_enabled: + return k_fleet, k_fleet, "fleet", new_hold + return k_local, k_fleet, "local(fleet)", new_hold + + held_k = _valid_hold(hold_state, T) + if held_k is not None: + kept_hold = {"k_fleet": held_k, "ts": int(hold_state["ts"])} + if fleet_k_enabled: + return held_k, held_k, "fleet-held", kept_hold + return k_local, held_k, "local(fleet-held)", kept_hold + + return k_local, None, "local", None + + def load_or_seed_state( state_path: str, pool: dict[str, tuple[float, int | None]], @@ -634,17 +991,36 @@ def load_or_seed_state( return state, is_fresh -def ensure_verdict_column(conn: Any) -> None: - """Ensure the 'verdict' column exists on quota_watch_runs (migration for existing DBs).""" +def ensure_quota_watch_columns(conn: Any) -> None: + """Ensure verdict, k_fleet, and k_scope exist on quota_watch_runs (in that order).""" cols = [row[1] for row in conn.execute("PRAGMA table_info(quota_watch_runs)").fetchall()] - if "verdict" not in cols: - try: - conn.execute("ALTER TABLE quota_watch_runs ADD COLUMN verdict TEXT") - except sqlite3.OperationalError as e: - if "duplicate column name" in str(e).lower(): - pass - else: - raise + for col_name, col_type in ( + ("verdict", "TEXT"), + ("k_fleet", "REAL"), + ("k_scope", "TEXT"), + ): + if col_name not in cols: + try: + conn.execute(f"ALTER TABLE quota_watch_runs ADD COLUMN {col_name} {col_type}") + cols.append(col_name) + except sqlite3.OperationalError as e: + if "duplicate column name" in str(e).lower(): + pass + else: + raise + + +def ensure_verdict_column(conn: Any) -> None: + """Ensure the 'verdict' (and trailing fleet-k) columns exist on quota_watch_runs.""" + ensure_quota_watch_columns(conn) + + +def _normalize_run_row(row: Sequence[Any]) -> tuple[Any, ...]: + """Pad a 14-, 15-, or 16-element run tuple with trailing None to 17 elements.""" + t = tuple(row) + if len(t) < 17: + t = t + (None,) * (17 - len(t)) + return t def record_run( @@ -678,12 +1054,12 @@ def record_run( row["pool_n"], row.get("source", "live"), row.get("verdict"), + row.get("k_fleet"), + row.get("k_scope"), ) run_ts = row["ts"] else: - row_tuple = tuple(row) - if len(row_tuple) == 14: - row_tuple = row_tuple + (None,) + row_tuple = _normalize_run_row(row) run_ts = row_tuple[0] conn = sqlite3.connect(db, timeout=t) @@ -693,12 +1069,12 @@ def record_run( stmt = stmt.strip() if stmt: conn.execute(stmt) - ensure_verdict_column(conn) + ensure_quota_watch_columns(conn) conn.execute( """INSERT OR REPLACE INTO quota_watch_runs ( ts, h0, burn_h, burn_6h, burn_24h, spill_6h, spill_24h, k, zero_h, vertex_usd, next_refill_ts, next_refill_amt, - pool_n, source, verdict) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""", + pool_n, source, verdict, k_fleet, k_scope) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""", row_tuple, ) if path: @@ -738,14 +1114,14 @@ def record_replay_runs( stmt = stmt.strip() if stmt: conn.execute(stmt) - ensure_verdict_column(conn) + ensure_quota_watch_columns(conn) changes_before_insert = conn.total_changes - norm_rows = [r + (None,) if len(r) == 14 else r for r in rows] + norm_rows = [_normalize_run_row(r) for r in rows] conn.executemany( """INSERT OR IGNORE INTO quota_watch_runs ( ts, h0, burn_h, burn_6h, burn_24h, spill_6h, spill_24h, k, zero_h, vertex_usd, next_refill_ts, next_refill_amt, - pool_n, source, verdict) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""", + pool_n, source, verdict, k_fleet, k_scope) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""", norm_rows, ) inserted = conn.total_changes - changes_before_insert @@ -815,6 +1191,8 @@ def run_live( host: str | None = None, alert_stale_hosts: str | Sequence[str] | None = "devbox", outlook_pushed_file: str | None = None, + fleet_k: bool = False, + account_map: str | None = None, ) -> int: """Run live quota watch check.""" host = host or socket.gethostname() @@ -975,6 +1353,12 @@ def run_live( since_ms = T - 8 * 24 * 3600 * 1000 samples, spill_buckets, max_buckets = load_inputs(conn, since_ms, host=host) tc_acct_buckets = load_teamclaude_account_buckets(conn, since_ms, host=host) + ( + remote_watermarks, + local_max_units, + local_tc_acct_units, + remote_max_acct_units, + ) = load_fleet_max_units(conn, since_ms, host=host) finally: conn.close() @@ -992,6 +1376,9 @@ def run_live( acc.feed(ts, a, u, r) pool = tracker.pool() + state_path = os.path.join(state_dir, "state.json") + state, is_fresh = load_or_seed_state(state_path, pool) + H0 = sum(max(0.0, CAP - u) for u, _ in pool.values()) burn_7d = acc.burn(T, 7 * 24 * 3600 * 1000) max_7d = subtract_excluded_max_7d( @@ -1002,11 +1389,30 @@ def run_live( ) k = estimate_k(burn_7d, max_7d) + acct_map_data = load_account_map(account_map, warn_missing=fleet_k) + warned_unmapped: set[str] = set() + required_fleet_hosts = _parse_host_list(alert_stale_hosts) + k_burn, k_fleet_val, k_scope, new_fleet_k_hold = resolve_fleet_k( + k_local=k, + T=T, + remote_watermarks=remote_watermarks, + local_max_units=local_max_units, + local_tc_acct_units=local_tc_acct_units, + remote_max_acct_units=remote_max_acct_units, + account_map=acct_map_data, + active_pool_accounts=set(pool.keys()), + excluded_accounts=tracker.excluded_accounts(), + hold_state=state.get("fleet_k_hold"), + fleet_k_enabled=fleet_k, + warned_unmapped=warned_unmapped, + required_hosts=required_fleet_hosts, + ) + burn_6h = acc.burn(T, 6 * 3600 * 1000) burn_24h = acc.burn(T, 24 * 3600 * 1000) spill_6h = sum_buckets(spill_buckets, T, 6 * 3600 * 1000) spill_24h = sum_buckets(spill_buckets, T, 24 * 3600 * 1000) - B = burn_rate(burn_6h, burn_24h, spill_6h, spill_24h, k) + B = burn_rate(burn_6h, burn_24h, spill_6h, spill_24h, k_burn) all_refills = [ (max(r, T + STEP_MS), min(u, CAP)) @@ -1014,14 +1420,12 @@ def run_live( if r is not None ] forecast_path: list[tuple[int, float]] = [] + # vertex_usd always uses k (local): cloudbox's $ per fleet account-week zero_h, vertex_usd, next_refill = forecast(H0, B, all_refills, k, T, path=forecast_path) spill_15m = sum_buckets(spill_buckets, T, 15 * 60 * 1000) spill_30m = sum_buckets(spill_buckets, T, 30 * 60 * 1000) - state_path = os.path.join(state_dir, "state.json") - state, is_fresh = load_or_seed_state(state_path, pool) - metrics = { "H0": H0, "zero_h": zero_h, @@ -1036,6 +1440,8 @@ def run_live( } new_state, actions = step_alerts(state, metrics) + if new_fleet_k_hold is not None: + new_state["fleet_k_hold"] = new_fleet_k_hold # Persist state atomically os.makedirs(state_dir, exist_ok=True) @@ -1089,19 +1495,26 @@ def run_live( "pool_n": len(pool), "source": "live", "verdict": verdict_from_state(new_state), + "k_fleet": k_fleet_val, + "k_scope": k_scope, } record_run(db, run_row, forecast_path) # Print summary line t_et = datetime.datetime.fromtimestamp(T / 1000, tz=NY_TZ).strftime("%Y-%m-%d %H:%M") k_str = str(round(k)) if k is not None else "none" + kf_part = ( + f" k(fleet)={round(k_fleet_val)}[{k_scope}]" + if k_fleet_val is not None + else (f" k_scope={k_scope}" if fleet_k else "") + ) v_str = f"${round(vertex_usd)}" if vertex_usd is not None else "none" pool_dry_str = "yes" if new_state.get("pool_dry") else "no" short_str = "yes" if new_state.get("shortfall") else "no" acct_hi_cnt = sum(1 for v in new_state.get("acct_high", {}).values() if v) print( - f"quota-watch T={t_et} headroom={H0:.2f} burn={B:.3f}/h k(local)={k_str} " + f"quota-watch T={t_et} headroom={H0:.2f} burn={B:.3f}/h k(local)={k_str}{kf_part} " f"dry_h={zero_h:.1f} vertex≈{v_str} pool_dry={pool_dry_str} short={short_str} acct_hi={acct_hi_cnt}" ) return 0 @@ -1228,6 +1641,9 @@ def replay( excluded: set[str] | None = None, host: str | None = None, record: bool = False, + fleet_k: bool = False, + account_map: str | None = None, + alert_stale_hosts: str | Sequence[str] | None = "devbox", ) -> list[ReplayEvent]: """Replay quota watch evaluation tick-by-tick.""" host = host or socket.gethostname() @@ -1236,9 +1652,19 @@ def replay( warmup_since = since_ms - 8 * 24 * 3600 * 1000 samples, spill_buckets, max_buckets = load_inputs(conn, warmup_since, host=host) tc_acct_buckets = load_teamclaude_account_buckets(conn, warmup_since, host=host) + ( + remote_watermarks, + local_max_units, + local_tc_acct_units, + remote_max_acct_units, + ) = load_fleet_max_units(conn, warmup_since, host=host) finally: conn.close() + acct_map_data = load_account_map(account_map, warn_missing=fleet_k) + warned_unmapped: set[str] = set() + fleet_k_hold: dict[str, Any] | None = None + samples_by_tick: dict[int, list[tuple[str, float | None, int | None]]] = collections.defaultdict(list) for ts, a, u, r in samples: samples_by_tick[ts].append((a, u, r)) @@ -1270,12 +1696,27 @@ def replay( tc_acct_buckets, ) k = estimate_k(burn_7d, max_7d) + k_burn, k_fleet_val, k_scope, fleet_k_hold = resolve_fleet_k( + k_local=k, + T=T, + remote_watermarks=remote_watermarks, + local_max_units=local_max_units, + local_tc_acct_units=local_tc_acct_units, + remote_max_acct_units=remote_max_acct_units, + account_map=acct_map_data, + active_pool_accounts=set(pool.keys()), + excluded_accounts=tracker.excluded_accounts(), + hold_state=fleet_k_hold, + fleet_k_enabled=fleet_k, + warned_unmapped=warned_unmapped, + required_hosts=_parse_host_list(alert_stale_hosts), + ) burn_6h = acc.burn(T, 6 * 3600 * 1000) burn_24h = acc.burn(T, 24 * 3600 * 1000) spill_6h = sum_buckets(spill_buckets, T, 6 * 3600 * 1000) spill_24h = sum_buckets(spill_buckets, T, 24 * 3600 * 1000) - B = burn_rate(burn_6h, burn_24h, spill_6h, spill_24h, k) + B = burn_rate(burn_6h, burn_24h, spill_6h, spill_24h, k_burn) all_refills = [ (max(r, T + STEP_MS), min(u, CAP)) @@ -1320,6 +1761,8 @@ def replay( len(pool), "replay", verdict, + k_fleet_val, + k_scope, ) ) diff --git a/pkgs/llm-ledger/test_quota_watch.py b/pkgs/llm-ledger/test_quota_watch.py index ff91b35f..bc13cd7b 100644 --- a/pkgs/llm-ledger/test_quota_watch.py +++ b/pkgs/llm-ledger/test_quota_watch.py @@ -2902,5 +2902,428 @@ def test_replay_subtracts_usage_seat_and_clamps_at_zero(self): self.assertEqual(k, 0.0) +class TestFleetK(unittest.TestCase): + """Tests for Phase 2 fleet k (k_local / s) behind --fleet-k.""" + + def setUp(self): + self.tmp_dir = tempfile.TemporaryDirectory() + self.db_path = os.path.join(self.tmp_dir.name, "ledger.db") + self.state_dir = os.path.join(self.tmp_dir.name, "state") + self.map_path = os.path.join(self.tmp_dir.name, "account-map.json") + # Hour-aligned base timestamp + self.H0 = 1796000400000 - (1796000400000 % quota_watch.HOUR_MS) + + def tearDown(self): + self.tmp_dir.cleanup() + + def _write_map(self, data: dict) -> str: + with open(self.map_path, "w", encoding="utf-8") as f: + json.dump(data, f) + return self.map_path + + def _seed_fleet_db( + self, + local_tokens: int = 1_000_000, + remote_rows: list[tuple[str, int, str, int]] | None = None, + tc_hourly_rows: list[tuple[int, str, int]] | None = None, + wm_lag_ms: int = quota_watch.HOUR_MS, + spill_usd: float = 600.0, + ) -> int: + """Seed a minimal DB with 0.6 acct-wk burn, $600 local Max, optional spill, and fleet tables.""" + T = self.H0 + 2 * quota_watch.HOUR_MS + t_prev = T - 30 * 60 * 1000 + h_data = self.H0 # inside [W_end - 7d, W_end) + wm = T - wm_lag_ms + + conn = sqlite3.connect(self.db_path) + conn.executescript(llm_ledger.SCHEMA_SQL) + # Active pool member 'alice' burns 0.6 acct-wk; 'seat' has all-null u7d (auto-excluded) + conn.execute( + "INSERT INTO quota_samples (ts, account, u7d, r7d) VALUES (?, 'alice', 0.10, ?)", + (t_prev, T + 48 * quota_watch.HOUR_MS), + ) + conn.execute( + "INSERT INTO quota_samples (ts, account, u7d, r7d) VALUES (?, 'alice', 0.70, ?)", + (T, T + 48 * quota_watch.HOUR_MS), + ) + conn.execute( + "INSERT INTO quota_samples (ts, account, u7d, r7d) VALUES (?, 'seat', NULL, NULL)", + (t_prev,), + ) + conn.execute( + "INSERT INTO quota_samples (ts, account, u7d, r7d) VALUES (?, 'seat', NULL, NULL)", + (T,), + ) + # Local Max $ = 600 -> k_local = 600 / 0.6 = 1000.0 + conn.execute( + "INSERT INTO requests (request_id, ts, host, attr_key, backend, model, cost_usd) " + "VALUES ('req-max', ?, 'cloudbox', 's1', 'max', 'claude-opus-5-5', 600.0)", + (t_prev + 60_000,), + ) + if spill_usd > 0: + conn.execute( + "INSERT INTO route (request_id, ts, desired, chosen) VALUES ('req-spill', ?, 'max', 'vertex')", + (t_prev + 60_000,), + ) + conn.execute( + "INSERT INTO requests (request_id, ts, host, attr_key, backend, model, cost_usd) " + "VALUES ('req-spill', ?, 'cloudbox', 's1', 'vertex', 'claude-opus-5-5', ?)", + (t_prev + 60_000, spill_usd), + ) + # Local hourly Max tokens (input only for clean exact opus_list_cost math) + conn.execute( + "INSERT INTO hourly (hour, attr_key, backend, model, n, input, output, cache_read, cache_write, cost_usd) " + "VALUES (?, 's1', 'max', 'claude-opus-5-5', 10, ?, 0, 0, 0, 600.0)", + (h_data, local_tokens), + ) + for h_ts, acct, inp in (tc_hourly_rows or []): + conn.execute( + "INSERT INTO teamclaude_hourly (hour, host, account, model, n, input, output, cache_read, cache_write_5m, cache_write_1h, cost_usd) " + "VALUES (?, 'cloudbox', ?, 'claude-opus-5-5', 1, ?, 0, 0, 0, 0, 0.0)", + (h_ts, acct, inp), + ) + conn.execute( + "INSERT INTO remote_hosts (host, first_hour, exported_through, imported_at) VALUES ('devbox', ?, ?, ?)", + (h_data - 7 * 24 * quota_watch.HOUR_MS, wm, T), + ) + for r_host, h_ts, r_acct, inp in (remote_rows or []): + conn.execute( + "INSERT INTO remote_hourly (host, hour, account, backend, model, requests, input, output, cache_read, cache_write_5m, cache_write_1h, cost_usd) " + "VALUES (?, ?, ?, 'max', 'claude-opus-5-5', 10, ?, 0, 0, 0, 0, 0.0)", + (r_host, h_ts, r_acct, inp), + ) + conn.commit() + conn.close() + return T + + def test_fleet_k_calculation_and_vertex_usd_uses_local_k(self): + """With s=0.25, k_fleet = 4*k_local; burn_rate uses k_fleet, vertex_usd keeps k_local.""" + # local=1M, remote=3M -> s = 0.25 -> k_fleet = 1000 / 0.25 = 4000 + T = self._seed_fleet_db( + local_tokens=1_000_000, + remote_rows=[("devbox", self.H0, "alice@example.com", 3_000_000)], + spill_usd=600.0, + ) + self._write_map({"alice@example.com": "alice", "seat@example.com": None}) + + # 1. --fleet-k OFF: k_scope='local', k_fleet still recorded, burn_h uses k_local=1000 + # burn_6h=0.6, spill_6h=600 -> B_local = (0.6 + 600/1000) / 6 = 0.20/h + rc = quota_watch.run_live( + db=self.db_path, state_dir=self.state_dir, now=T + 60_000, + host="cloudbox", alert_stale_hosts="", fleet_k=False, account_map=self.map_path, + ) + self.assertEqual(rc, 0) + conn = sqlite3.connect(self.db_path) + row_off = conn.execute( + "SELECT burn_h, k, zero_h, vertex_usd, k_fleet, k_scope FROM quota_watch_runs WHERE ts = ?", + (T,), + ).fetchone() + conn.close() + self.assertAlmostEqual(row_off[0], 0.20, places=5) + self.assertAlmostEqual(row_off[1], 1000.0, places=3) + self.assertAlmostEqual(row_off[4], 4000.0, places=3) + self.assertEqual(row_off[5], "local(fleet)") + + # 2. --fleet-k ON: k_scope='fleet', burn_h uses k_fleet=4000 -> B_fleet = (0.6 + 600/4000)/6 = 0.125/h + # vertex_usd MUST still use k_local=1000 (zero_h * B_fleet * 1000) + rc = quota_watch.run_live( + db=self.db_path, state_dir=self.state_dir, now=T + 60_000, + host="cloudbox", alert_stale_hosts="", fleet_k=True, account_map=self.map_path, + ) + self.assertEqual(rc, 0) + conn = sqlite3.connect(self.db_path) + row_on = conn.execute( + "SELECT burn_h, k, zero_h, vertex_usd, k_fleet, k_scope FROM quota_watch_runs WHERE ts = ?", + (T,), + ).fetchone() + conn.close() + self.assertAlmostEqual(row_on[0], 0.125, places=5) + self.assertAlmostEqual(row_on[1], 1000.0, places=3) + self.assertAlmostEqual(row_on[3], row_on[2] * row_on[0] * 1000.0, places=3) + self.assertAlmostEqual(row_on[4], 4000.0, places=3) + self.assertEqual(row_on[5], "fleet") + + def test_fleet_k_account_map_ignore_unmapped_and_non_pool(self): + """Explicit null ignores silently; unmapped warns once & excluded; non-pool excluded; local seat subtracted.""" + T = self._seed_fleet_db( + local_tokens=1_200_000, + tc_hourly_rows=[(self.H0, "seat@example.com", 200_000)], # subtracted -> local_u = 1M + remote_rows=[ + ("devbox", self.H0, "alice@example.com", 1_000_000), # mapped & in pool -> counted + ("devbox", self.H0, "seat@example.com", 5_000_000), # mapped to None -> ignored silently + ("devbox", self.H0, "mystery@example.com", 9_000_000), # unmapped -> warn & excluded + ("devbox", self.H0, "ghost@example.com", 4_000_000), # mapped, not in pool -> excluded + ], + spill_usd=0.0, + ) + self._write_map({ + "alice@example.com": "alice", + "seat@example.com": None, + "ghost@example.com": "ghost", + }) + stderr_buf = io.StringIO() + with unittest.mock.patch("sys.stderr", stderr_buf): + rc = quota_watch.run_live( + db=self.db_path, state_dir=self.state_dir, now=T + 60_000, + host="cloudbox", alert_stale_hosts="", fleet_k=True, account_map=self.map_path, + ) + self.assertEqual(rc, 0) + err = stderr_buf.getvalue() + self.assertIn("mystery@example.com", err) + self.assertNotIn("seat@example.com", err) + self.assertNotIn("ghost@example.com", err) + + # local_u = 1M (1.2M - 0.2M), remote_u = 1M (only alice) -> s = 0.5 -> k_fleet = 2000 + conn = sqlite3.connect(self.db_path) + row = conn.execute( + "SELECT k, k_fleet, k_scope FROM quota_watch_runs WHERE ts = ?", (T,) + ).fetchone() + conn.close() + self.assertAlmostEqual(row[0], 1000.0, places=3) + self.assertAlmostEqual(row[1], 2000.0, places=3) + self.assertEqual(row[2], "fleet") + + def test_fleet_k_hold_48h_on_watermark_lag_then_fallback(self): + """Holds last good k_fleet for 48h when watermark lags >3h without refreshing ts, then falls back.""" + acct_map = {"alice@example.com": "alice"} + local_u = {self.H0: 100.0} + remote_u = {"alice@example.com": {self.H0: 300.0}} + T0 = self.H0 + 2 * quota_watch.HOUR_MS + + # Fresh watermark (1h lag <= 3h): s=0.25 -> k_fleet=4000 + k_burn, k_fleet, scope, hold = quota_watch.resolve_fleet_k( + k_local=1000.0, + T=T0, + remote_watermarks={"devbox": T0 - quota_watch.HOUR_MS}, + local_max_units=local_u, + local_tc_acct_units={}, + remote_max_acct_units=remote_u, + account_map=acct_map, + active_pool_accounts={"alice"}, + excluded_accounts=set(), + hold_state=None, + fleet_k_enabled=True, + ) + self.assertEqual(scope, "fleet") + self.assertAlmostEqual(k_burn, 4000.0) + self.assertAlmostEqual(k_fleet, 4000.0) + self.assertEqual(hold, {"k_fleet": 4000.0, "ts": T0}) + + # Watermark lags 10h (>3h), hold is 10h old (<=48h): hold k_fleet, ts NOT refreshed + T1 = T0 + 10 * quota_watch.HOUR_MS + k_burn1, k_fleet1, scope1, hold1 = quota_watch.resolve_fleet_k( + k_local=1000.0, + T=T1, + remote_watermarks={"devbox": T0 - quota_watch.HOUR_MS}, + local_max_units=local_u, + local_tc_acct_units={}, + remote_max_acct_units=remote_u, + account_map=acct_map, + active_pool_accounts={"alice"}, + excluded_accounts=set(), + hold_state=hold, + fleet_k_enabled=True, + ) + self.assertEqual(scope1, "fleet-held") + self.assertAlmostEqual(k_burn1, 4000.0) + self.assertAlmostEqual(k_fleet1, 4000.0) + self.assertEqual(hold1["ts"], T0) + + # Watermark still lags at 49h (>48h): hold expires, fall back to k_local + T2 = T0 + 49 * quota_watch.HOUR_MS + k_burn2, k_fleet2, scope2, hold2 = quota_watch.resolve_fleet_k( + k_local=1000.0, + T=T2, + remote_watermarks={"devbox": T0 - quota_watch.HOUR_MS}, + local_max_units=local_u, + local_tc_acct_units={}, + remote_max_acct_units=remote_u, + account_map=acct_map, + active_pool_accounts={"alice"}, + excluded_accounts=set(), + hold_state=hold1, + fleet_k_enabled=True, + ) + self.assertEqual(scope2, "local") + self.assertAlmostEqual(k_burn2, 1000.0) + self.assertIsNone(k_fleet2) + self.assertIsNone(hold2) + + def test_quota_watch_runs_k_fleet_k_scope_last_columns_and_migration(self): + """k_fleet and k_scope are columns 15 and 16 (after verdict at 14); migration is idempotent.""" + old_db = os.path.join(self.tmp_dir.name, "old.db") + conn = sqlite3.connect(old_db) + conn.execute(""" + CREATE TABLE quota_watch_runs ( + ts INTEGER PRIMARY KEY, + h0 REAL NOT NULL, burn_h REAL NOT NULL, + burn_6h REAL, burn_24h REAL, spill_6h REAL, spill_24h REAL, + k REAL, zero_h REAL NOT NULL, vertex_usd REAL, + next_refill_ts INTEGER, next_refill_amt REAL, + pool_n INTEGER NOT NULL, source TEXT NOT NULL, verdict TEXT + ) + """) + quota_watch.ensure_quota_watch_columns(conn) + cols = [r[1] for r in conn.execute("PRAGMA table_info(quota_watch_runs)").fetchall()] + self.assertEqual(cols[14], "verdict") + self.assertEqual(cols[15], "k_fleet") + self.assertEqual(cols[16], "k_scope") + self.assertEqual(len(cols), 17) + # Idempotent + quota_watch.ensure_quota_watch_columns(conn) + cols2 = [r[1] for r in conn.execute("PRAGMA table_info(quota_watch_runs)").fetchall()] + self.assertEqual(cols, cols2) + conn.close() + + def test_replay_fleet_k_flag_changes_burn_and_records_columns(self): + """replay --fleet-k reduces burn_h during spill and persists k_fleet/k_scope on record=True.""" + T = self._seed_fleet_db( + local_tokens=1_000_000, + remote_rows=[("devbox", self.H0, "alice@example.com", 3_000_000)], + spill_usd=600.0, + ) + self._write_map({"alice@example.com": "alice"}) + quota_watch.replay( + db=self.db_path, since_ms=T, until_ms=T, host="cloudbox", + record=True, fleet_k=True, account_map=self.map_path, + ) + conn = sqlite3.connect(self.db_path) + row = conn.execute( + "SELECT burn_h, k, k_fleet, k_scope FROM quota_watch_runs WHERE ts = ?", (T,) + ).fetchone() + conn.close() + self.assertAlmostEqual(row[0], 0.125, places=5) + self.assertAlmostEqual(row[1], 1000.0, places=3) + self.assertAlmostEqual(row[2], 4000.0, places=3) + self.assertEqual(row[3], "fleet") + + def test_fleet_k_clips_window_to_remote_coverage_and_ignores_sleeping_mac(self): + """Window start clips to remote first_hour; sleeping non-required host (mac) does not trigger hold.""" + acct_map = {"alice@example.com": "alice"} + T = self.H0 + 48 * quota_watch.HOUR_MS + # Local has 900 units BEFORE remote coverage started, and 100 units AFTER. + # Remote (devbox) starts at H0 and has 300 units in [H0, T). + # With clipping to first_hour=H0, s = 100 / (100 + 300) = 0.25 -> k_fleet = 4000. + # Without clipping, s would be 1000 / 1300 = 0.77. + local_u = { + self.H0 - 24 * quota_watch.HOUR_MS: 900.0, + self.H0 + quota_watch.HOUR_MS: 100.0, + } + remote_u = {"alice@example.com": {self.H0 + quota_watch.HOUR_MS: 300.0}} + k_burn, k_fleet, scope, _ = quota_watch.resolve_fleet_k( + k_local=1000.0, + T=T, + remote_watermarks={ + "devbox": (self.H0, T - quota_watch.HOUR_MS), + "mac": (self.H0, T - 20 * quota_watch.HOUR_MS), # asleep 20h + }, + local_max_units=local_u, + local_tc_acct_units={}, + remote_max_acct_units=remote_u, + account_map=acct_map, + active_pool_accounts={"alice"}, + excluded_accounts=set(), + hold_state=None, + fleet_k_enabled=True, + required_hosts=["devbox"], + ) + self.assertEqual(scope, "fleet") + self.assertAlmostEqual(k_burn, 4000.0, places=3) + self.assertAlmostEqual(k_fleet, 4000.0, places=3) + + def test_fleet_k_keeps_hold_on_empty_pool_unmatched_remote_or_tiny_share(self): + """Empty pool, unmatched remote rows, or s < 1% must not overwrite a valid hold.""" + acct_map = {"alice@example.com": "alice"} + T = self.H0 + 48 * quota_watch.HOUR_MS + existing_hold = {"k_fleet": 2500.0, "ts": T - quota_watch.HOUR_MS} + wms = {"devbox": (self.H0, T - quota_watch.HOUR_MS)} + + # 1. Empty pool -> keep hold + kb, kf, sc, h = quota_watch.resolve_fleet_k( + k_local=1000.0, T=T, remote_watermarks=wms, + local_max_units={self.H0: 100.0}, local_tc_acct_units={}, + remote_max_acct_units={"alice@example.com": {self.H0: 300.0}}, + account_map=acct_map, active_pool_accounts=set(), excluded_accounts=set(), + hold_state=existing_hold, fleet_k_enabled=True, required_hosts=["devbox"], + ) + self.assertEqual(sc, "fleet-held") + self.assertAlmostEqual(kb, 2500.0) + self.assertEqual(h["ts"], existing_hold["ts"]) + + # 2. Remote has non-ignored rows but none match active pool -> keep hold + kb2, kf2, sc2, h2 = quota_watch.resolve_fleet_k( + k_local=1000.0, T=T, remote_watermarks=wms, + local_max_units={self.H0: 100.0}, local_tc_acct_units={}, + remote_max_acct_units={"alice@example.com": {self.H0: 300.0}}, + account_map=acct_map, active_pool_accounts={"bob"}, excluded_accounts=set(), + hold_state=existing_hold, fleet_k_enabled=True, required_hosts=["devbox"], + ) + self.assertEqual(sc2, "fleet-held") + self.assertAlmostEqual(kb2, 2500.0) + self.assertEqual(h2["ts"], existing_hold["ts"]) + + # 3. Tiny share s = 0.005 (< 0.01 floor) -> keep hold + kb3, kf3, sc3, h3 = quota_watch.resolve_fleet_k( + k_local=1000.0, T=T, remote_watermarks=wms, + local_max_units={self.H0: 1.0}, local_tc_acct_units={}, + remote_max_acct_units={"alice@example.com": {self.H0: 199.0}}, + account_map=acct_map, active_pool_accounts={"alice"}, excluded_accounts=set(), + hold_state=existing_hold, fleet_k_enabled=True, required_hosts=["devbox"], + ) + self.assertEqual(sc3, "fleet-held") + self.assertAlmostEqual(kb3, 2500.0) + self.assertEqual(h3["ts"], existing_hold["ts"]) + + def test_run_live_persists_fleet_k_hold_across_ticks_in_state_json(self): + """Two consecutive run_live calls carry fleet_k_hold through state.json when devbox lags.""" + T1 = self._seed_fleet_db( + local_tokens=1_000_000, + remote_rows=[("devbox", self.H0, "alice@example.com", 3_000_000)], + spill_usd=600.0, + ) + self._write_map({"alice@example.com": "alice"}) + + rc1 = quota_watch.run_live( + db=self.db_path, state_dir=self.state_dir, now=T1 + 60_000, + host="cloudbox", alert_stale_hosts="devbox", fleet_k=True, account_map=self.map_path, + ) + self.assertEqual(rc1, 0) + with open(os.path.join(self.state_dir, "state.json"), "r", encoding="utf-8") as f: + st1 = json.load(f) + self.assertAlmostEqual(st1["fleet_k_hold"]["k_fleet"], 4000.0, places=3) + self.assertEqual(st1["fleet_k_hold"]["ts"], T1) + + # Advance 5h without advancing devbox's exported_through (>3h lag, <=48h hold) + T2 = T1 + 5 * quota_watch.HOUR_MS + conn = sqlite3.connect(self.db_path) + conn.execute( + "INSERT INTO quota_samples (ts, account, u7d, r7d) VALUES (?, 'alice', 0.72, ?)", + (T2, T2 + 48 * quota_watch.HOUR_MS), + ) + conn.execute( + "INSERT INTO requests (request_id, ts, host, attr_key, backend, model, cost_usd) " + "VALUES ('req-max-2', ?, 'cloudbox', 's1', 'max', 'claude-opus-5-5', 20.0)", + (T2 - 60_000,), + ) + conn.commit() + conn.close() + + rc2 = quota_watch.run_live( + db=self.db_path, state_dir=self.state_dir, now=T2 + 60_000, + host="cloudbox", alert_stale_hosts="devbox", fleet_k=True, account_map=self.map_path, + ) + self.assertEqual(rc2, 0) + conn = sqlite3.connect(self.db_path) + row2 = conn.execute( + "SELECT k_fleet, k_scope FROM quota_watch_runs WHERE ts = ?", (T2,) + ).fetchone() + conn.close() + self.assertAlmostEqual(row2[0], 4000.0, places=3) + self.assertEqual(row2[1], "fleet-held") + with open(os.path.join(self.state_dir, "state.json"), "r", encoding="utf-8") as f: + st2 = json.load(f) + self.assertEqual(st2["fleet_k_hold"]["ts"], T1) # not refreshed + + if __name__ == "__main__": unittest.main() From fb5b76892a2edb66cc491059b9c6869b6b24841d Mon Sep 17 00:00:00 2001 From: Jonathan Mohrbacher Date: Tue, 1 Dec 2026 10:38:44 -0500 Subject: [PATCH 2/2] [NO-JIRA] Update test_quota_watch.py pinned test count (96 -> 104) --- flake.nix | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/flake.nix b/flake.nix index c03f6499..6deda469 100644 --- a/flake.nix +++ b/flake.nix @@ -2249,8 +2249,8 @@ } python3 pkgs/llm-ledger/test_quota_watch.py 2>&1 | tee "$TMPDIR/qw.txt" - grep -q '^Ran 96 tests' "$TMPDIR/qw.txt" || { - echo "GATE FAILURE: expected 'Ran 96 tests' from test_quota_watch.py. If you" >&2 + grep -q '^Ran 104 tests' "$TMPDIR/qw.txt" || { + echo "GATE FAILURE: expected 'Ran 104 tests' from test_quota_watch.py. If you" >&2 echo "added or removed tests deliberately, update the count here in the same commit." >&2 exit 1 }