* usage: the usage tests pass at any time of day, midnight included The usage tests stamped their calls with the machine's time and then asked for today, 7 or 30 days, or a cached answer, which the code worked out from its own time.Now a moment later. A minute after midnight a call made "a minute ago" was yesterday's, and when midnight fell between the test's read and the code's, the call and the period were of two days. magpie usage, the TUI's Usage page, the two Codex cache-write tests and the computers' shared days failed in the first minutes after midnight (the TUI's after midnight UTC, the zone its package's tests run in since1caea638), and 28 more failed when midnight fell inside them. usage.Clock is now the time every period is read by: the start of today, 7 days and 30 days (LedgerOf, Summarize, Direct, QueryPage), the hours or days of the chart (LedgerSeries, QueryPage), the day a cached summary or page is for, the time Append gives a call that has none, the days davsync shares and the date in an exported CSV's name. It is time.Now, as before, and a variable for the tests, like LogCalls. Each test that built its calls from the time now holds Clock at noon on 2026-09-30 (holdClock; holdUsageClock in gui and the CLI; three lines in tui and davsync) and stamps its calls from that instant, among them TestReasoningReplyTimedByItsAnswer, whose timeline rows117b6c7fmade at time.Now. TestPeriodsReadTheClock checks that every one of these reads goes through Clock. TestQueryPageSourceAndIdentityInvalidation is held too; that it fails when run alone is fixed apart from this, in #1045. Seven held tests could not fail at midnight before, and are held so that the tests read one clock: TestUsageSameSizeAndMtimeRewrite (All's totals), TestDirectCountsOnlySessionFileCalls (30 days around its own noon), TestQueryPageIOOutsideCacheLock (a file two days old), gui's TestUsageLedgerDayRoutes (7 days hold its calls from either day), TestLedgerSingleSnapshotAndLocalSession and TestLedgerNamesModelAtProvider (their calls are stamped after the code reads the time), and TestUsageRawAndPricedChunksShareBudget, which fails only when the midnight in it starts a new week of All's chart, on a Sunday night; at.sh sets the time of day and not the weekday, so that one was not shown. Verified with at.sh, a scratch script that runs a test binary under a zone made with zic, so that the local time of day is the one asked for as the run starts (HOME in a sandbox, Go's caches pinned). The runs were first made onc5a54bc7, and those marked (698da36f) again on698da36f, with the same results. The tui package runs in UTC since1caea638, a zone at.sh doesn't move, so its runs on698da36fused copies of both trees whose TestMain keeps the zone TZ sets. Before, at 00:00:30, 00:01:30 and 12:00:00 (698da36f): TestUsageShowsCallsNotThroughMagpie, 00:00:30: usage_cli_test.go:95: no calls today · route an agent through magpie and its usage shows up here 00:01:30: "5 tokens today · 1 call · no price", without the calls not through magpie; TestUsagePageShowsCallsNotThroughMagpie (tui) fails the same two ways at usage_test.go:138 --- FAIL: TestCodexCacheWriteNotInInput (00:00:30) codex_cache_write_test.go:104: rows [] --- FAIL: TestCodexCacheWriteMatchesGatewayCall (00:01:30) codex_cache_write_test.go:73: filter {...}: 0 rows, 0 calls, want the gateway's 2: [] --- FAIL: TestUsageSharedBetweenComputers (00:01:30) usage_share_test.go:134: a's days on the server: [...-2026-10-05 ...-2026-10-06 ...-2026-10-07] 12:00:00: PASS Midnight inside a test, in scratch copies of the head. Started at 23:59:59.3 with the code's first period read held 1.5s, so that it reads after midnight what the test stamped before it, 16 usage tests, 3 gui tests and TestUsageCSV FAIL, among them ledger_test.go:257: today: 0 review_test.go:69: chart counted 0 incremental_log_test.go:202: concurrent append lost TestCachedSummaryRemainsCallerOwned: panic: runtime error: index out of range [0] with length 0 usage_test.go:121: second page: {... Period:today Rows:[] ... Total:0 ...} usage_test.go:311: "": magpie-requests-7d-2026-10-06 Started at 23:59:55 with the test waiting past midnight between two of its reads, 7 more FAIL: request_day_test.go:45: selecting a day changed the chart or its legend cache_bounds_test.go:84: uncached today summary stale growing_rewrite_test.go:71: today summary stale cache_bounds_test.go:153: page key changed instead of exercising the same cache priced_blocks_test.go:55, caller_provider_test.go:129 and :172: page differs TestReasoningReplyTimedByItsAnswer, with a scratch 1.5s sleep before its LedgerSeries, started at 23:59:59.3 (698da36f): usage_test.go:255: part: {Calls:0 Tokens:0 Cost:0 Timed:0 TTFT:0 DecodeMs:0 DecodeOut:0} After: the same at.sh runs PASS at 00:00:30, 00:01:30 and 12:00:00 (698da36f); the same scratch copies made of this change PASS, each test taking 1.5s or 5.2s, so midnight did fall inside it (698da36ffor TestReasoningReplyTimedByItsAnswer's); and every changed test PASS at 23:59:59.9, 00:00:30 and 12:00:00 (698da36f). Without the change (698da36f): with the reads put back on time.Now, 21 usage tests, 6 gui, 2 CLI, the tui and the davsync test fail, among them --- FAIL: TestPeriodsReadTheClock clock_test.go:55: Direct(Today): 0 calls since 2026-10-06 00:00:00 -0700 PDT, want 1 since 2026-09-30 00:00:00 -0700 PDT clock_test.go:63: Summarize(Today) the next day: 1 calls, want 0 --- FAIL: TestReasoningReplyTimedByItsAnswer usage_test.go:255: part: {Calls:0 Tokens:0 ...} Each of the eleven reads put back alone fails a test: TestPeriodsReadTheClock for the nine in usage (LedgerSeries: "clock_test.go:52: LedgerSeries(Today): 0 calls, want 2"; the page's cache key: "clock_test.go:66: QueryPage(Today) the next day: 1 rows, want 0"), TestCSVStamp for the CSV's name (usage_test.go:325: "": magpie-requests-7d-2026-10-06) and TestUsageSharedBetweenComputers for davsync (usage_share_test.go:224: all computers: 4 rows, 707 in; want 5, 737). On this commit: go test -tags nogui -count=1 . ./internal/usage ./internal/tui ./internal/davsync ./internal/gui ok; -race -count=20 over the changed tests of each of these packages ok; gofmt -l prints nothing, and go vet -tags nogui on the five packages finds nothing. * usage: pages, CSVs and magpie usage asked at midnight show one day An answer about usage read the time more than once. The Requests page read it for the day it is kept for, for the period its log and session files are read over, for the period of its rows and for its chart's hours; the page from the ledger (QueryPage's path when LogCalls is set, as in the tests) for its rows and for its chart; Direct for its period and for its rows; a CSV for its rows and for its name; magpie usage and the TUI's Usage page for Summarize and then for Direct. Most of these reads have the log and the session files read between them, seconds on a large log, and when midnight fell between two of them the answer was of two days: yesterday's calls listed over today's empty chart, Direct starting yesterday and counting none of yesterday's calls, the calls not through magpie left out of magpie usage and the Usage page (they were the new day's, none yet), and yesterday's calls saved as magpie-requests-today-<the new day>.csv. Each answer now reads Clock once and passes that moment down. queryPage reads it for its key, its sources, its rows and its chart (buildRequestBlocks takes it); the page from the ledger reads its rows and its chart at it (LedgerOfAt, ledgerSeriesAt); Direct reads the ledger at the moment of its period. usage.Summaries(p) is Summarize(p) and Direct(p) at one moment, and magpie usage and the TUI's Usage page, when a period is picked and when it is read again, ask for it: one exported name, the clock left inside usage and one line changed at each caller, where SummarizeAt and DirectAt would be two names and each caller would read the clock itself. The CSV download and export read their rows with the new usage.LedgerOfAt at the moment their file is named for, which csvStamp now takes; the rows and the name are read in two packages, so LedgerOfAt is exported. LedgerOf, LedgerSeries, Summarize, Direct and QueryPage keep their signatures, each reading Clock once. The new tests set Clock to read a tenth of a second before midnight the first time and a tenth of a second after it from then on, set again for each answer. The midnight is the one that starts 2026-10-01, local time: a past instant, at midnight because that is what is tested, and the day before it is the 2026-09-30 the held tests use. TestAnswerReadsTheClockOnce asks QueryPage(Today) from the indexed log and from the ledger: its 3 rows, one from a session file written that day at 23:00, are under that day's chart, and asked again after midnight the page is the next day's, not the one kept for the day before; Direct(Today) counts the call and starts that day. TestUsageAskedAtMidnight (magpie usage today), TestUsagePageAtMidnight (the TUI's Usage page, today picked and read again) and TestUsageCSVAtMidnight (download and export) check that the calls through magpie and those not through it, or the rows and the file's name, are of the day asked on. TestCSVStamp passes its time. Verified on the previous commit, at.sh as there. The runs were first made onc5a54bc7, when the tui package's tests still ran in the local zone, and those marked (698da36f) again on698da36f, with the same results. Before: the new tests on the previous commit, at any time of day (at.sh at 12:00:00 too) (698da36f): --- FAIL: TestAnswerReadsTheClockOnce clock_test.go:131: QueryPage(Today): 0 rows, 0 in a chart from 2026-10-01 00:00:00 -0700 PDT; want 3 under one from 2026-09-30 00:00:00 -0700 PDT clock_test.go:141: QueryPage(Today): 3 rows, 0 in a chart from 2026-10-01 ...; want 3 under one from 2026-09-30 ... clock_test.go:145: Direct(Today): 0 calls since 2026-09-30 00:00:00 -0700 PDT, want 1 since 2026-09-30 00:00:00 -0700 PDT --- FAIL: TestUsageAskedAtMidnight usage_cli_test.go:154: 5 tokens today · 1 call · no price ..., with no part for the calls not through magpie --- FAIL: TestUsagePageAtMidnight usage_test.go:184: today picked: ... (the same) usage_test.go:187: read again: ... --- FAIL: TestUsageCSVAtMidnight usage_test.go:367: download: 200, attachment; filename="magpie-requests-today-2026-10-01.csv" with 2 rows (<nil>), want magpie-requests-today-2026-09-30.csv with 2 usage_test.go:378: export: 200 {"path":"~/Downloads/magpie-requests-today-2026-10-01.csv", "rows":1}, want magpie-requests-today-2026-09-30.csv with 1 row With the real clock, in scratch copies of both trees: scratch tests held one of Clock's reads 1.5s after it was made, as reading a large log does (the first; for one of them the page's third, its chart's), and at.sh started each at 23:59:59.3. Before, all 9 FAIL, among them asked 23:59:59.564, answered 00:00:01.068 Direct(Today): 0 calls since 2026-10-05 00:00:00 -0940 MID, want 1 since 2026-10-05 00:00:00 -0940 MID QueryPage(Today): 2 rows, 0 in a chart from 2026-10-06 ...; want 2 under one from 2026-10-05 ... download: attachment; filename="magpie-requests-today-2026-10-06.csv" with a call of 2026-10-05 23:59 After, all 9 PASS, answered at 00:00:00.9 to 00:00:01.0, so midnight fell inside each, except the chart's: its held read is gone with the change. A scratch sleep before the chart shows that one: before "2 rows, 0 in a chart from 2026-10-06", after PASS, asked 23:59:59.344 and answered 00:00:00.941. At 12:00:00 all of them PASS in both trees. After: every changed test PASS with at.sh at 23:59:59.9, 00:00:30 and 12:00:00 (698da36f). Without the change (698da36f): with the production put back to the previous commit's (gui/usage.go only so far that TestCSVStamp compiles: csvStamp takes the time, read apart from the rows as before), go test -count=1 . ./internal/usage ./internal/tui ./internal/gui fails the four new tests and no other, with the lines above. Each of the 16 places put back alone fails one of them: the page's key (clock_test.go:134: "3 rows, 3 in a chart from 2026-09-30 ...; want 0 under one from 2026-10-01 ..."), its sources (:131: "2 rows"), its rows (:131: "0 rows"), its chart (:131), the ledger page's rows and chart (:141), LedgerOfAt (:141, :145), ledgerSeriesAt (:141), Direct (:145); Summaries, indexedSummary and magpie usage (usage_cli_test.go:154); Summaries and the TUI's period key and reload (usage_test.go:184, :187); the CSV's download and export (usage_test.go:367, :378). On this commit: go test -tags nogui -count=1 . ./internal/usage ./internal/gui ./internal/tui ./internal/davsync ./internal/gateway ok; -race -count=20 over the changed tests of each package ok; gofmt -l prints nothing, and go vet -tags nogui finds nothing. * gateway: the key-limit tests pass when a run crosses local midnight A go test run that crossed local midnight could fail the gateway's key-limit tests. keyLimited and the /v1/magpie/limit endpoint each read time.Now() when they check a key, and access.Window turns that into a calendar window (a day from midnight, a week from Monday, a month from the 1st). The tests seed "yesterday" from their own time.Now() and then make several calls, so a run that crossed midnight saw its calls split over two windows: the second call of a 350-token day was let in, or a restart counted nothing. The gateway's key-limit path now reads limitClock, a variable for the tests like ruleClock and idClock, and production behaviour is unchanged (it is time.Now). TestKeyLimitRefusesBeforeUpstream, TestKeyLimitHoldsParallelRequests and TestKeyLimitWindowResets pin it at 2026-09-30 12:00 local and seed "yesterday" from that instant. Calls are still recorded at the real time, after the pinned one, and a window counts every call from its start, so they all count in the pinned window; the "tomorrow's window" check in TestKeyLimitWindowResets stays on the real now, the first window with none of those calls in it. No other test sets a key limit with records in its window (the gateway-key CLI test and the GUI caller-key tests count 0 calls or have no limit). TestKeyLimitRefusesBeforeUpstream now also checks that the 429's Retry-After and X-Magpie-Limit-Reset name the next midnight after the check, and that the limit endpoint's week starts on the pinned Monday. Verified with at.sh, a scratch script that runs the test binary under a zone made with zic, so that the local time of day is the one asked for as the run starts: - before, at.sh at 23:59:59 with COUNT=500/300 and FRAC 0.3/0.6/0.8: 3 of 6 runs of each test failed with key_limit_test.go:217: spent key let in key_limit_test.go:117: a restart forgot what the key used 200 key_limit_test.go:121: status &{Period:day Start:2026-10-06 ... Calls:0 Tokens:0 ...} - after, the same 6 runs (COUNT=500, both tests) print PASS, and so do ^TestKeyLimit at 12:00:00 and 00:00:00 with COUNT=20. - go test -tags nogui -count=1 ./internal/gateway: ok (79.5s); -race -count=20 -run '^TestKeyLimit' ./internal/gateway: ok. - gofmt -l prints nothing; go vet -tags nogui ./internal/gateway is clean. The month boundary (TestKeyLimitHoldsParallelRequests) and Monday can't be reproduced by changing the time of day; the pinned clock covers them the same way. Fails without the change (tests pinned, keyLimited back on time.Now): --- FAIL: TestKeyLimitRefusesBeforeUpstream key_limit_test.go:107: headers map[... Retry-After:[80228] X-Magpie-Limit-Reset:[2026-10-07T00:00:00-07:00] ...] and with only the limit endpoint back on time.Now: --- FAIL: TestKeyLimitRefusesBeforeUpstream key_limit_test.go:159: limit endpoint {... "period":"week", "start":"2026-10-05T00:00:00-07:00" ...} * gateway: the routing history tests pass when a run crosses midnight TestHistoryKeepsDaysAndDropsOld and TestRemoteMagpieGroupHistory took now := time.Now() and saved routes at now and now+1s. saveRoute files a route by its own day (r.Time.Local()), so a test started at 23:59:59 put the +1s route in tomorrow's file and History(today) found one route less. TestHistoryKeepsSessionAndTokenTiers raced the other clock: saveRoute prunes by time.Now(), so when the day turned between the test's time.Now() and the first saveRoute, the prune gzipped "today" after the first route, the second went to a new .jsonl, and the test's own pruneHistory gzipped that over the first .gz, losing route 1. saveRoute now prunes by historyClock (time.Now outside the tests). The three tests take historyNoon(t), which holds that clock at 2026-09-30 12:00 local and returns it as their now, restored with t.Cleanup. Every route, day file and prune is then on that one past day. The fixture can't be a fixed past day without the clock: pruning by the real today gzips that day's file at once (and, a month on, drops it as too old). The other history tests keep the real clock: TestHistoryRouteOutsideDayLimit writes its day files itself from one now and the code under test reads no clock, and TestHistoryRouteDayAndNoLock already uses a fixed day. Verified with at.sh, a scratch script that sets the local time of day through a zone made with zic as the run starts: - before, at.sh ./internal/gateway at 23:59:59: --- FAIL: TestHistoryKeepsDaysAndDropsOld history_test.go:50: days [{2026-10-06 1} {2026-10-05 1} {2026-10-04 1}] --- FAIL: TestRemoteMagpieGroupHistory remote_group_served_test.go:144: routes [... only ID 1 ...] and, with a 2s sleep after now := time.Now() standing in for the turn of the day, --- FAIL: TestHistoryKeepsSessionAndTokenTiers history_test.go:22: compressed history lost accounting: [only ID 2] 12:00:00 control: PASS. - after: the three tests PASS at 23:59:59, 23:59:59.9 (FRAC=0.9), 12:00:00, and 23:59:59 with the same 2s sleep; all TestHistory* and TestRemoteMagpieGroupHistory PASS at 23:59:59 with -test.count=3. - with saveRoute pruning by time.Now() again (the fixtures still pinned), at any time of day: --- FAIL: TestHistoryKeepsSessionAndTokenTiers history_test.go:32: compressed history lost accounting: [only ID 2] - go test -tags nogui -count=1 ./internal/gateway: ok; -race -count=20 on the three tests: ok; gofmt -l and go vet -tags nogui ./internal/gateway print nothing. * gateway, davsync: the request archive tests pass when a run crosses UTC midnight The archive names a call "<date>/<id>" from the call's own start, in UTC (archiving in archive.go). TestArchiveOn read time.Now().UTC() before posting and TestRequestArchiveToS3 read it before post(), and each expected that read's date. A run where UTC midnight (17:00 PDT) fell between the test's read and the request's start expected the day before the one the archive used, and failed. Both tests now take the date from the Time the call carries (s.Recent()[0].Time, the same start the archive's name is made from), in UTC, so nothing is read from the clock a second time. No production code changes. The other archive tests already go by the call's Archive name, and internal/gui's archive test uses a fixed name; no other test in internal/gateway, internal/davsync or internal/gui predicts an archive key or a UTC-dated name from its own clock. Verified: at.sh only moves the local time of day, and this is a UTC crossing (UTC midnight was ~16h away), so it was shown in a scratch copy whose serve starts each request 0.2s after the next UTC midnight, as a request does when the test read the clock just before it. There the old tests fail: archive_test.go:115: call archive "2026-10-07/000000-f4690de23ee8a859", want "2026-10-06/000000-f4690de23ee8a859" archive_test.go:93: nothing at "team x+y/magpie/archive/2026-10-06/000000-0e74a87816ef6a56.json" and the new ones pass. Unshifted, under at.sh at local 23:59:59, 00:00:00 and 12:00:00, both pass, as the old ones do at 23:59:59 and 00:00:00 (local time doesn't enter the name). With archiving naming by start.Format (local) instead of start.UTC().Format, both new tests fail under at.sh at local 23:00:00, where the local date is a day behind UTC's: --- FAIL: TestArchiveOn ... archive_test.go:116: call archive "2026-10-05/082500-7322712bd89f71da", want "2026-10-06/082500-7322712bd89f71da" --- FAIL: TestRequestArchiveToS3 ... archive_test.go:95: nothing at "team x+y/magpie/archive/2026-10-06/082500-3587ab4192da2cd5.json" and pass at 12:00:00. go test -tags nogui -count=1 ./internal/gateway ./internal/davsync passes in a sandbox HOME; -race -count=20 -run '^(TestArchiveOn|TestRequestArchiveToS3)$' passes; gofmt -l and go vet -tags nogui on both packages are clean. * gui: TestWhatsNewTodayRoute passes when the run crosses local midnight TestWhatsNewTodayRoute posts {"on":true} to /api/whatsnew/today, which writes today() to whatsnew-quiet-day, then checks quietToday(), which compares the file with a second today(). A run that crossed local midnight between the two read different days and failed with "on: 204 false". The neighbouring TestWhatsNewQuietAfterRestartToUpdate already pins today; this test didn't. The test now pins today to 2026-09-30 (restored with t.Cleanup), so the post and the check read the same day. The other What's new tests start from an empty folder, so quietToday finds no file and never reads today(). Verified: with a temporary 1s sleep between the post and the check, the unpinned test under at.sh (local time of day set by a zone) started at local 23:59:59.5 failed with "whatsnew_test.go:237: on: 204 false" and passed at 12:00:00; pinned, it passes at 23:59:59.5 (same sleep), and, without the sleep, at 23:59:59, 00:00:00 and 12:00:00. With setQuietToday writing time.Now().Format("2006-01-02") instead of today(), the test fails: "--- FAIL: TestWhatsNewTodayRoute ... whatsnew_test.go:239: on: 204 false". go test -tags nogui -count=1 ./internal/gui passes in a sandbox HOME; -race -count=20 -run '^TestWhatsNewTodayRoute$' passes; gofmt -l and go vet -tags nogui ./internal/gui are clean. * provider: TestZCodeStartSentAsTheApp passes when the run crosses midnight A ZCode Start Plan request opens with a context prefix that says "Today's date is <day>" (zcodeDateReminder), the day zcodeStartRequest took from its own time.Now(). TestZCodeStartSentAsTheApp sent the request, then built the expected prefix from a second time.Now(). A run that crossed midnight between the two failed on "the context prefix", the request holding the day before. zcodeStartRequest now takes the time from zcodeClock (a package variable, time.Now outside tests, as gateway's ruleClock), and the test pins it to 2026-09-30 12:00 local, restored with t.Cleanup, and expects "Today's date is 2026-09-30." The test sets TZ=Asia/Shanghai, which moves time.Local only when nothing has read it yet; a mid-day instant in time.Local formats to the same day either way. The other calls to zcodeStartBody in the test check shaping only, not the day. No other provider test builds a day string from a second clock: the WorkBuddy credits, daily warm-up and check-in tests pass fixed times to code that takes now as an argument, and TestQoderCheckinOnTheCard's day is only carried, not compared. Verified with at.sh (local time of day set by a zone, run as -run '^(TestDailyCredits|TestZCodeStartSentAsTheApp)$' so that time.Local is read before the test's t.Setenv("TZ"), as in a full run; alone, Local becomes Asia/Shanghai): with a temporary 1s sleep after the request, the unpinned test started at local 23:59:59.5 failed with "zcode_client_test.go:195: the context prefix: ... Today's date is 2026-10-05." and passed at 12:00:00; pinned, it passes at 23:59:59.5 (same sleep) and, without the sleep, at 23:59:59, 00:00:00 and 12:00:00. With zcodeStartRequest back on time.Now(), the pinned test fails: "--- FAIL: TestZCodeStartSentAsTheApp ... zcode_client_test.go:196: the context prefix: ... Today's date is 2026-10-06." go test -tags nogui -count=1 ./internal/provider passes in a sandbox HOME; -race -count=20 -run '^TestZCodeStartSentAsTheApp$' passes; gofmt -l and go vet -tags nogui ./internal/provider are clean. * accounts, quota: a window's reset reads against one time per listing; TestQuotaCell passes across midnight quotaCell, a window in `magpie accounts` and `magpie quota`, read the clock three times: whether the reset had passed, how long until it, and ResetClock's label, which names the calendar day ("tomorrow 02:13" or "02:13"). TestQuotaCell set the reset 2h13m30s from time.Now() and built the expected label from yet another time.Now(); a run that crossed local midnight between quotaCell's read and the test's got "tomorrow 02:13" from one and "02:13" from the other and failed. quotaCell now takes now. accountsCmd and quotaCmd take one time.Now() just before printing and pass it to every window's cell, so a listing's windows agree on what "today" is. The test passes a fixed 2026-09-30 12:00 local and expects "↻2h13m 14:13", and for a reset the next day "↻14h13m tomorrow 02:13"; no zone in tzdata 2026c changes its clock between those instants, so both read the same in any TZ. resetsCell's label, quotaReadingCell's expired check and quotaResetCmd's prompt still read time.Now(); no test compares them against a second clock. internal/tui's quotaCell and quotaLines already take now, and their tests pass a fixed one. Verified with at.sh (local time of day set by a zone): with a temporary 1s sleep between quotaCell and the check, the old test started at local 23:59:59.5 failed with "accounts_cli_test.go:128: \"5h 42% ↻2h13m tomorrow 02:13\"" and passed at 12:00:00; the new one passes at 23:59:59.5 (same sleep) and, without the sleep, at 23:59:59, 00:00:00 and 12:00:00. Putting any of quotaCell's three reads back on the wall clock fails the test ("--- FAIL: TestQuotaCell"). ResetClock's now alone fails the next-day case: "accounts_cli_test.go:134: tomorrow: \"7d 42% ↻14h13m 02:13\"". The passed check alone, or all three: "accounts_cli_test.go:129: \"5h 42% · reset time passed Sep 30 14:13\"". untilShort alone: "accounts_cli_test.go:129: \"5h 42% ↻now 14:13\"". go test -tags nogui -count=1 . passes in a sandbox HOME; -race -count=20 -run '^TestQuotaCell$' passes; gofmt -l and go vet -tags nogui . are clean.
1132 lines
32 KiB
Go
1132 lines
32 KiB
Go
package usage
|
|
|
|
// The request page keeps compact per-source records, not a second full ledger.
|
|
// Unchanged sources are never decoded again. Aggregation streams those records;
|
|
// only the requested page is materialized/sorted. Export can still ask for the
|
|
// complete ledger explicitly. This cache is disposable and bounded.
|
|
|
|
import (
|
|
"container/heap"
|
|
"crypto/sha256"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"maps"
|
|
"os"
|
|
"path/filepath"
|
|
"slices"
|
|
"sort"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
"unsafe"
|
|
|
|
"github.com/yetone/magpie/internal/catalog"
|
|
"github.com/yetone/magpie/internal/provider"
|
|
"github.com/yetone/magpie/internal/sessions"
|
|
"github.com/yetone/magpie/internal/settings"
|
|
)
|
|
|
|
type RequestPage struct {
|
|
Rows []Row
|
|
Sum Totals
|
|
Total int
|
|
Agents, Providers []string
|
|
Purposes []string // all purposes in the period, independent of the selected filter
|
|
CallerKeys []Group
|
|
// Accounts are the subscription accounts that answered calls in the
|
|
// period, by provider and account, for the Account filter (#557)
|
|
Accounts []Group
|
|
Bucket string
|
|
Series []SeriesPoint
|
|
By map[string][]Share
|
|
ChartBy map[string][]Share // the whole period's legend while a day is selected
|
|
// Computers are the rows told apart by the computer they were made on,
|
|
// ThisComputer's and each other's by id, of the rows without the
|
|
// filter's computer, and Names what the others are called: none when no
|
|
// other computer's calls were brought here by sync (#542)
|
|
Computers []Share
|
|
Names map[string]string
|
|
}
|
|
|
|
type packedRow struct {
|
|
Time time.Time
|
|
Text [28]uint32
|
|
Tokens [6]int64
|
|
Millis, TTFT, FirstText, Order int64
|
|
Sent int64
|
|
RouteID int64
|
|
Cost float64
|
|
Status int32
|
|
Flags uint8
|
|
}
|
|
type rowChunk struct {
|
|
Archive []byte
|
|
Locations []*time.Location
|
|
Rows []packedRow
|
|
Strings []string
|
|
dict map[string]uint32
|
|
Source sessions.CallSource
|
|
Bytes int64
|
|
Used uint64
|
|
Count int
|
|
Latest time.Time
|
|
// Computer is the other computer whose day this is (#542), by id
|
|
Computer string
|
|
}
|
|
|
|
// rowMsg is the Text of a row's Claude message id, after rowText's
|
|
const rowMsg = 27
|
|
|
|
func rowText(r *Row) [27]*string {
|
|
return [27]*string{&r.Agent, &r.Provider, &r.Host, &r.SessionProvider, &r.SessionAccount, &r.Model, &r.Requested, &r.Served, &r.Effort, &r.Error, &r.ErrType, &r.RequestID, &r.Endpoint, &r.Session, &r.NativeSession, &r.Kind, &r.Source, &r.Via, &r.ProviderKeyID, &r.ProviderKeyName, &r.CallerKeyID, &r.CallerKeyName, &r.Archive, &r.Operation, &r.ProviderAccount, &r.ResponseID, &r.Upstream}
|
|
}
|
|
func (c *rowChunk) add(r Row, msg string, order int64, failed bool) {
|
|
if c.dict == nil {
|
|
c.dict = map[string]uint32{"": 0}
|
|
c.Strings = []string{""}
|
|
}
|
|
intern := func(s string) uint32 {
|
|
if id, ok := c.dict[s]; ok {
|
|
return id
|
|
}
|
|
id := uint32(len(c.Strings))
|
|
c.dict[s] = id
|
|
c.Strings = append(c.Strings, s)
|
|
c.Bytes += int64(len(s) + 48)
|
|
return id
|
|
}
|
|
p := packedRow{Time: r.Time, Tokens: [6]int64{int64(r.Input), int64(r.Output), int64(r.CacheRead), int64(r.CacheWrite), int64(r.Reasoning), int64(r.CacheWrite1h)}, Millis: r.Millis, TTFT: r.TTFT, FirstText: r.FirstText, Sent: r.Sent, Order: order, RouteID: r.RouteID, Cost: r.Cost, Status: int32(r.Status)}
|
|
for i, s := range rowText(&r) {
|
|
p.Text[i] = intern(*s)
|
|
}
|
|
p.Text[rowMsg] = intern(msg)
|
|
if r.Priced {
|
|
p.Flags |= 1
|
|
}
|
|
if r.Swapped {
|
|
p.Flags |= 2
|
|
}
|
|
if r.Rejected {
|
|
p.Flags |= 4
|
|
}
|
|
if r.SessionOfficialLogin {
|
|
p.Flags |= 8
|
|
}
|
|
if r.Routed {
|
|
p.Flags |= 32
|
|
}
|
|
if failed {
|
|
p.Flags |= 16
|
|
}
|
|
c.Rows = append(c.Rows, p)
|
|
c.Count = len(c.Rows)
|
|
if r.Time.After(c.Latest) {
|
|
c.Latest = r.Time
|
|
}
|
|
c.Bytes += int64(unsafe.Sizeof(packedRow{}))
|
|
}
|
|
func (c *rowChunk) row(i int) Row {
|
|
p := &c.Rows[i]
|
|
r := Row{Record: Record{RouteID: p.RouteID, Time: p.Time, Input: int(p.Tokens[0]), Output: int(p.Tokens[1]), CacheRead: int(p.Tokens[2]), CacheWrite: int(p.Tokens[3]), CacheWrite1h: int(p.Tokens[5]), Reasoning: int(p.Tokens[4]), Millis: p.Millis, TTFT: p.TTFT, FirstText: p.FirstText, Sent: p.Sent, Status: int(p.Status), Rejected: p.Flags&4 != 0, SessionOfficialLogin: p.Flags&8 != 0}, Cost: p.Cost, Priced: p.Flags&1 != 0, Swapped: p.Flags&2 != 0, Routed: p.Flags&32 != 0}
|
|
for i, s := range rowText(&r) {
|
|
*s = c.Strings[p.Text[i]]
|
|
}
|
|
if r.Swapped && SameSpelled(r.Model, r.Served) {
|
|
r.Swapped = false // kept before a name spelled otherwise was the same
|
|
}
|
|
r.Computer = c.Computer
|
|
return r
|
|
}
|
|
|
|
type rowRef struct {
|
|
Chunk *rowChunk
|
|
Index int
|
|
}
|
|
|
|
func (r rowRef) row() Row { return r.Chunk.row(r.Index) }
|
|
func (r rowRef) at() time.Time { return r.Chunk.Rows[r.Index].Time }
|
|
func refNewer(a, b rowRef) bool {
|
|
if !a.at().Equal(b.at()) {
|
|
return a.at().After(b.at())
|
|
}
|
|
if (a.Chunk.Source.Path == "") != (b.Chunk.Source.Path == "") {
|
|
return a.Chunk.Source.Path == ""
|
|
}
|
|
if a.Chunk.Source.Path != b.Chunk.Source.Path {
|
|
return a.Chunk.Source.Path > b.Chunk.Source.Path
|
|
}
|
|
return a.Chunk.Rows[a.Index].Order > b.Chunk.Rows[b.Index].Order
|
|
}
|
|
|
|
type newestHeap []rowRef
|
|
|
|
func (h newestHeap) Len() int { return len(h) }
|
|
func (h newestHeap) Less(i, j int) bool { return refNewer(h[j], h[i]) }
|
|
func (h newestHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
|
|
func (h *newestHeap) Push(v any) { *h = append(*h, v.(rowRef)) }
|
|
func (h *newestHeap) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v }
|
|
|
|
type pageKey struct {
|
|
Period Period
|
|
Filter Filter
|
|
Offset, Limit int
|
|
}
|
|
type requestIndex struct {
|
|
sync.Mutex
|
|
root, meta, key string
|
|
chunks map[string]*rowChunk
|
|
gateways map[*rowChunk]*rowChunk // immutable raw block -> priced block
|
|
pages map[pageKey]RequestPage
|
|
tick uint64
|
|
}
|
|
|
|
var requestCache requestIndex
|
|
|
|
var requestCacheBytes int64 = 24 << 20
|
|
|
|
func statKey(path string) string {
|
|
s, e := os.Stat(path)
|
|
if e != nil {
|
|
return path + ":missing"
|
|
}
|
|
return fmt.Sprintf("%s:%d:%d", path, s.Size(), s.ModTime().UnixNano())
|
|
}
|
|
func recordHash(path string, n int64) string {
|
|
f, e := os.Open(path)
|
|
if e != nil {
|
|
return ""
|
|
}
|
|
defer f.Close()
|
|
h := sha256.New()
|
|
if _, e = io.CopyN(h, f, n); e != nil {
|
|
return ""
|
|
}
|
|
return fmt.Sprintf("%x", h.Sum(nil))
|
|
}
|
|
|
|
func QueryPage(p Period, f Filter, offset, limit int) RequestPage {
|
|
return queryPage(p, f, offset, limit, sessions.ReadCallSource)
|
|
}
|
|
func queryPage(p Period, f Filter, offset, limit int, readSource func(sessions.CallSource) []sessions.Call) RequestPage {
|
|
if limit <= 0 {
|
|
limit = 100
|
|
}
|
|
limit = min(limit, 500)
|
|
offset = max(0, offset)
|
|
// The time is read once, so that the rows, the chart and the day the page
|
|
// is kept for are of one day when midnight falls while it is worked out.
|
|
now := Clock()
|
|
// A replacement reader remains useful to callers supplying synthetic logs.
|
|
if LogCalls != nil {
|
|
return pageFromLedgerAt(p, f, offset, limit, LedgerOfAt(p, Filter{}, now), now)
|
|
}
|
|
sources := sessions.CallSources()
|
|
slices.SortFunc(sources, func(a, b sessions.CallSource) int {
|
|
if n := a.Modified.Compare(b.Modified); n != 0 {
|
|
return n
|
|
}
|
|
return strings.Compare(a.Path, b.Path)
|
|
})
|
|
ids, _ := json.Marshal(provider.SessionIdentities(sessions.CodexDir()))
|
|
renamed, _ := json.Marshal(provider.Renamed())
|
|
cfg := settings.Load()
|
|
prices, _ := json.Marshal(cfg.ModelPrices)
|
|
wires, _ := json.Marshal(cfg.ModelWires)
|
|
meta := fmt.Sprintf("%s|%s|%s|%s|%s|%s", ids, renamed, prices, wires, statKey(provider.Path()), statKey(catalog.CachePath()))
|
|
h := sha256.New()
|
|
for _, current := range provider.All() {
|
|
fmt.Fprintf(h, "%q:%q:%v:%t:%t:%t;", current.ID, current.Where(), current.Catalogs(), current.IsPlugin(), current.Account == nil, current.Key != "")
|
|
fmt.Fprint(h, statKey(catalog.LivePath(current.ID)))
|
|
}
|
|
for _, root := range sessions.DesktopDataDirs() {
|
|
for _, kind := range []string{"local-agent-mode-sessions", "claude-code-sessions"} {
|
|
files, _ := sessions.SessionGlob(filepath.Join(root, kind, "*", "*", "local_*.json"))
|
|
for _, path := range files {
|
|
fmt.Fprint(h, statKey(path))
|
|
}
|
|
}
|
|
}
|
|
meta += fmt.Sprintf("|%x|%s", h.Sum(nil), statKey(catalog.LivePath("antigravity")))
|
|
h.Reset()
|
|
snapshot := logSnapshotFor(true)
|
|
version := snapshot.version
|
|
fmt.Fprint(h, meta, version, now.Format("2006-01-02 MST"))
|
|
for _, s := range sources {
|
|
fmt.Fprintf(h, "%s:%d:%d;", s.Path, s.Size, s.Modified.UnixNano())
|
|
}
|
|
days, someShared := sharedSources(time.Time{})
|
|
for _, s := range days {
|
|
fmt.Fprintf(h, "%s:%d:%d;", s.path, s.size, s.mod.UnixNano())
|
|
}
|
|
key := fmt.Sprintf("%x", h.Sum(nil))
|
|
root := Path() + "|" + catalog.CachePath()
|
|
idx := &requestCache
|
|
idx.Lock()
|
|
|
|
if idx.root != root || idx.meta != meta {
|
|
idx.root, idx.meta = root, meta
|
|
idx.chunks = map[string]*rowChunk{}
|
|
idx.gateways = map[*rowChunk]*rowChunk{}
|
|
idx.pages = nil
|
|
idx.key = ""
|
|
}
|
|
if idx.key != key {
|
|
idx.pages = map[pageKey]RequestPage{}
|
|
idx.key = key
|
|
}
|
|
q := pageKey{p, f, offset, limit}
|
|
if page, ok := idx.pages[q]; ok {
|
|
idx.Unlock()
|
|
return page
|
|
}
|
|
idx.tick++
|
|
// Copy only metadata while holding the lock. Published chunks are immutable;
|
|
// reading, decoding, pricing and aggregation use a private snapshot.
|
|
shared := idx
|
|
idx = &requestIndex{root: idx.root, meta: idx.meta, key: idx.key, tick: idx.tick,
|
|
chunks: maps.Clone(idx.chunks), gateways: maps.Clone(idx.gateways)}
|
|
shared.Unlock()
|
|
if snapshot.uncached && len(snapshot.blocks) == 0 {
|
|
snapshot = readLogSnapshot()
|
|
}
|
|
price := pricer()
|
|
priceRow := func(r Record, source string) Row {
|
|
sent := r.Model
|
|
if source == "" {
|
|
sent = provider.SentNameIn(cfg.ModelWires, r.Provider, r.Model, r.Effort)
|
|
}
|
|
row := Row{Record: r, Source: source, Swapped: r.Served != "" && Swapped(sent, r.Served), Routed: GroupRouted(sent, r.Served)}
|
|
if pr := price(r); pr != nil && r.Input+r.Output > 0 {
|
|
row.Priced = true
|
|
row.Cost = r.CostAt(*pr)
|
|
}
|
|
row.Agent = AgentOf(r.Agent)
|
|
return row
|
|
}
|
|
since := p.Since(now)
|
|
gatewaySince := since
|
|
if !since.IsZero() {
|
|
gatewaySince = since.Add(-24 * time.Hour)
|
|
}
|
|
var gateways []*rowChunk
|
|
aliases := provider.Renamed()
|
|
live := make(map[*rowChunk]bool, len(snapshot.blocks))
|
|
for _, packed := range snapshot.blocks {
|
|
live[packed] = true
|
|
if !gatewaySince.IsZero() && packed.Latest.Before(gatewaySince) {
|
|
continue
|
|
}
|
|
cached := idx.gateways[packed]
|
|
c := cached.unpack()
|
|
if c == nil {
|
|
raw := packed.unpack()
|
|
if raw == nil {
|
|
continue
|
|
}
|
|
c = &rowChunk{}
|
|
// Cache the entire block: another period can reuse the same prices.
|
|
// Only the append tail changes; a tariff change clears all blocks.
|
|
for i, pr := range raw.Rows {
|
|
r := raw.row(i).Record
|
|
if id, ok := aliases[r.Provider]; ok {
|
|
r.Provider = id
|
|
}
|
|
c.add(priceRow(r, ""), "", pr.Order, false)
|
|
}
|
|
cached = c.freeze()
|
|
}
|
|
kept := *cached
|
|
kept.Used = idx.tick
|
|
idx.gateways[packed] = &kept
|
|
gateways = append(gateways, c)
|
|
}
|
|
for raw := range idx.gateways {
|
|
if !live[raw] {
|
|
delete(idx.gateways, raw)
|
|
}
|
|
}
|
|
on := map[string]bool{}
|
|
var chunks []*rowChunk
|
|
var resolver *sessionResolver
|
|
read := prefetchSources(sources, func(s sessions.CallSource) bool {
|
|
if !since.IsZero() && s.Modified.Before(since) {
|
|
return false
|
|
}
|
|
c := idx.chunks[s.Path]
|
|
return c == nil || c.Source.Size != s.Size || !c.Source.Modified.Equal(s.Modified)
|
|
}, readSource)
|
|
for i, s := range sources {
|
|
on[s.Path] = true
|
|
if !since.IsZero() && s.Modified.Before(since) {
|
|
continue
|
|
}
|
|
cached := idx.chunks[s.Path]
|
|
c := cached.unpack()
|
|
reused := c != nil && c.Source.Size == s.Size && c.Source.Modified.Equal(s.Modified)
|
|
if !reused {
|
|
if resolver == nil {
|
|
resolver = newSessionResolver([]sessions.Call{{}})
|
|
}
|
|
cs := read(i)
|
|
c = &rowChunk{Source: s, Rows: make([]packedRow, 0, len(cs))}
|
|
for _, call := range cs {
|
|
r := logRecord(call)
|
|
r.SessionAccount = resolver.resolve(call)
|
|
r.SessionOfficialLogin = resolver.officialLogin(call, r.SessionAccount)
|
|
r.SessionProvider = call.Upstream
|
|
c.add(priceRow(r, "log"), call.Msg, call.To, call.Error != "")
|
|
}
|
|
c.Bytes -= int64(32 * len(c.Strings))
|
|
c.dict = nil // local chunks are immutable until the source changes
|
|
idx.chunks[s.Path] = c
|
|
}
|
|
next := *c
|
|
c = &next
|
|
c.Used = idx.tick
|
|
if reused {
|
|
kept := *cached
|
|
kept.Used = idx.tick
|
|
idx.chunks[s.Path] = &kept
|
|
} else {
|
|
idx.chunks[s.Path] = c.pack()
|
|
}
|
|
chunks = append(chunks, c)
|
|
}
|
|
// the other computers' days (#542), a chunk each, read again only when
|
|
// sync brought a new copy
|
|
var others []*rowChunk
|
|
var renames map[string]string
|
|
from := ""
|
|
if !since.IsZero() {
|
|
from = since.AddDate(0, 0, -1).Format(time.DateOnly)
|
|
}
|
|
for _, s := range days {
|
|
on[s.path] = true
|
|
if s.day < from {
|
|
continue
|
|
}
|
|
cached := idx.chunks[s.path]
|
|
c := cached.unpack()
|
|
reused := c != nil && c.Source.Size == s.size && c.Source.Modified.Equal(s.mod)
|
|
if !reused {
|
|
d, _ := readShared(s.path)
|
|
if renames == nil {
|
|
renames = provider.Renamed()
|
|
}
|
|
c = &rowChunk{Source: sessions.CallSource{Path: s.path, Size: s.size, Modified: s.mod}, Computer: s.computer, Rows: make([]packedRow, 0, len(d.Calls))}
|
|
for i, call := range d.Calls {
|
|
r := call.Record
|
|
r.Computer = ""
|
|
if id, ok := renames[r.Provider]; ok {
|
|
r.Provider = id
|
|
}
|
|
c.add(priceRow(r, call.Source), "", int64(i), false)
|
|
}
|
|
c.Bytes -= int64(32 * len(c.Strings))
|
|
c.dict = nil
|
|
}
|
|
next := *c
|
|
c = &next
|
|
c.Used = idx.tick
|
|
if reused {
|
|
kept := *cached
|
|
kept.Used = idx.tick
|
|
idx.chunks[s.path] = &kept
|
|
} else {
|
|
idx.chunks[s.path] = c.pack()
|
|
}
|
|
others = append(others, c)
|
|
}
|
|
for path := range idx.chunks {
|
|
if !on[path] {
|
|
delete(idx.chunks, path)
|
|
}
|
|
}
|
|
var names map[string]string
|
|
if someShared {
|
|
names = sharedNames()
|
|
}
|
|
page := buildRequestBlocks(p, f, offset, limit, now, gateways, chunks, others, names)
|
|
shared.Lock()
|
|
defer shared.Unlock()
|
|
// A query for an older filesystem snapshot may finish after a newer one.
|
|
if shared.root != idx.root || shared.meta != idx.meta || shared.key != idx.key || snapshot.version != version {
|
|
return page
|
|
}
|
|
for path, c := range idx.chunks {
|
|
if prev := shared.chunks[path]; prev == nil || prev.Used <= c.Used {
|
|
shared.chunks[path] = c
|
|
}
|
|
}
|
|
for path := range shared.chunks {
|
|
if !on[path] {
|
|
delete(shared.chunks, path)
|
|
}
|
|
}
|
|
for raw, c := range idx.gateways {
|
|
if prev := shared.gateways[raw]; prev == nil || prev.Used <= c.Used {
|
|
shared.gateways[raw] = c
|
|
}
|
|
}
|
|
for raw := range shared.gateways {
|
|
if !live[raw] {
|
|
delete(shared.gateways, raw)
|
|
}
|
|
}
|
|
if len(shared.pages) >= 16 {
|
|
shared.pages = map[pageKey]RequestPage{}
|
|
}
|
|
if !snapshot.uncached {
|
|
shared.pages[q] = page
|
|
}
|
|
// Raw blocks are also retained by gateway-map keys: charge their bytes once.
|
|
bytes := snapshot.bytes
|
|
budget := int64(requestCacheBytes)
|
|
if snapshot.uncached {
|
|
budget = 0
|
|
shared.pages = map[pageKey]RequestPage{}
|
|
}
|
|
|
|
type cachedChunk struct {
|
|
path string
|
|
raw *rowChunk
|
|
row *rowChunk
|
|
}
|
|
var kept []cachedChunk
|
|
for path, c := range shared.chunks {
|
|
bytes += c.Bytes
|
|
kept = append(kept, cachedChunk{path: path, row: c})
|
|
}
|
|
for raw, c := range shared.gateways {
|
|
bytes += c.Bytes
|
|
kept = append(kept, cachedChunk{raw: raw, row: c})
|
|
}
|
|
slices.SortFunc(kept, func(a, b cachedChunk) int {
|
|
if a.row.Used < b.row.Used {
|
|
return -1
|
|
}
|
|
if a.row.Used > b.row.Used {
|
|
return 1
|
|
}
|
|
return strings.Compare(a.path, b.path)
|
|
})
|
|
for _, c := range kept {
|
|
if bytes <= budget {
|
|
break
|
|
}
|
|
if c.raw != nil {
|
|
delete(shared.gateways, c.raw)
|
|
} else {
|
|
delete(shared.chunks, c.path)
|
|
}
|
|
bytes -= c.row.Bytes
|
|
}
|
|
return page
|
|
}
|
|
|
|
// localRefs visits first occurrences of Claude message IDs. It stores only
|
|
// references for matches, never a full hydrated row for every call.
|
|
func visibleLocal(chunks []*rowChunk) map[rowRef]bool {
|
|
duplicates := map[rowRef]bool{}
|
|
seen := map[string]bool{}
|
|
for _, c := range chunks {
|
|
for i, p := range c.Rows {
|
|
msg := c.Strings[p.Text[rowMsg]]
|
|
if msg == "" {
|
|
continue
|
|
}
|
|
if seen[msg] {
|
|
duplicates[rowRef{c, i}] = true
|
|
} else {
|
|
seen[msg] = true
|
|
}
|
|
}
|
|
}
|
|
return duplicates
|
|
}
|
|
|
|
// matchKey narrows candidates before comparing their end times. Request IDs
|
|
// are consumed first; fallback matching still requires uniqueness both ways.
|
|
// The agent isn't in it: a session's id names the one conversation, and a
|
|
// client built on Codex (miyi-helper, say) is logged under its own name by
|
|
// the gateway while its Codex session file names Codex, so its calls were
|
|
// counted twice, once through magpie and once as not.
|
|
type matchKey struct {
|
|
session string
|
|
tokens [3]int64
|
|
failed, hasID bool
|
|
}
|
|
|
|
// matchTokens is what a call's tokens are matched by: its input with what it
|
|
// wrote to the cache in it, its output and what it read from the cache. The
|
|
// two logs needn't split a cache write out of the input alike (#589): a
|
|
// Codex that names cache_write_input_tokens beside a gateway record that
|
|
// didn't, an older Codex that doesn't beside one that does; the sum is the
|
|
// same either way.
|
|
func matchTokens(t [6]int64) [3]int64 { return [3]int64{t[0] + t[3], t[1], t[2]} }
|
|
|
|
type matchEnd struct {
|
|
at time.Time
|
|
index rowRef
|
|
}
|
|
type matchGroup struct {
|
|
ends []matchEnd
|
|
counts []int
|
|
}
|
|
|
|
func matchedLocal(gateway *rowChunk, chunks []*rowChunk, skip map[rowRef]bool, since time.Time) map[rowRef]bool {
|
|
return matchedBlocks([]*rowChunk{gateway}, chunks, skip, since, true)
|
|
}
|
|
|
|
func matchedBlocks(gateways []*rowChunk, chunks []*rowChunk, skip map[rowRef]bool, since time.Time, newestIDs bool) map[rowRef]bool {
|
|
gatewaySince := since
|
|
if !since.IsZero() {
|
|
gatewaySince = since.Add(-24 * time.Hour)
|
|
}
|
|
byID := map[string][]rowRef{}
|
|
for _, gateway := range gateways {
|
|
for i, p := range gateway.Rows {
|
|
if (p.Flags&4 != 0 || p.Text[1] == 0 && p.Status >= 400) || p.Time.Before(gatewaySince) {
|
|
continue
|
|
}
|
|
if id := gateway.Strings[p.Text[11]]; id != "" {
|
|
byID[id] = append(byID[id], rowRef{gateway, i})
|
|
}
|
|
}
|
|
}
|
|
byRequest := map[string][]rowRef{}
|
|
for _, c := range chunks {
|
|
for i, p := range c.Rows {
|
|
ref := rowRef{c, i}
|
|
if skip[ref] || p.Time.Before(since) {
|
|
continue
|
|
}
|
|
if id := c.Strings[p.Text[11]]; len(byID[id]) > 0 {
|
|
byRequest[id] = append(byRequest[id], ref)
|
|
}
|
|
}
|
|
}
|
|
matched, used := map[rowRef]bool{}, map[rowRef]bool{}
|
|
for id, refs := range byRequest {
|
|
if newestIDs {
|
|
slices.SortFunc(refs, func(a, b rowRef) int {
|
|
if refNewer(a, b) {
|
|
return -1
|
|
}
|
|
if refNewer(b, a) {
|
|
return 1
|
|
}
|
|
return 0
|
|
})
|
|
}
|
|
for j, ref := range refs {
|
|
if j >= len(byID[id]) {
|
|
break
|
|
}
|
|
matched[ref], used[byID[id][j]] = true, true
|
|
}
|
|
}
|
|
groups := map[matchKey]*matchGroup{}
|
|
for _, gateway := range gateways {
|
|
for i, p := range gateway.Rows {
|
|
if used[rowRef{gateway, i}] || (p.Flags&4 != 0 || p.Text[1] == 0 && p.Status >= 400) || p.Time.Before(gatewaySince) {
|
|
continue
|
|
}
|
|
session := gateway.Strings[p.Text[14]]
|
|
if session == "" {
|
|
session = gateway.Strings[p.Text[13]]
|
|
}
|
|
if session == "" {
|
|
continue
|
|
}
|
|
key := matchKey{session, matchTokens(p.Tokens), p.Status >= 400 || p.Text[9] != 0, p.Text[11] != 0}
|
|
g := groups[key]
|
|
if g == nil {
|
|
g = &matchGroup{}
|
|
groups[key] = g
|
|
}
|
|
g.ends = append(g.ends, matchEnd{p.Time.Add(time.Duration(p.Millis) * time.Millisecond), rowRef{gateway, i}})
|
|
}
|
|
}
|
|
for _, g := range groups {
|
|
slices.SortFunc(g.ends, func(a, b matchEnd) int { return a.at.Compare(b.at) })
|
|
g.counts = make([]int, len(g.ends)+1)
|
|
}
|
|
candidates := map[rowRef]rowRef{}
|
|
for _, c := range chunks {
|
|
for j, p := range c.Rows {
|
|
ref := rowRef{c, j}
|
|
if skip[ref] || matched[ref] || p.Time.Before(since) {
|
|
continue
|
|
}
|
|
failed := p.Flags&16 != 0
|
|
if p.Tokens[0]+p.Tokens[1]+p.Tokens[2]+p.Tokens[3] == 0 && !failed {
|
|
continue
|
|
}
|
|
key := matchKey{session: c.Strings[p.Text[13]], tokens: matchTokens(p.Tokens), failed: failed}
|
|
count, candidate := 0, (rowRef{})
|
|
// Without a local ID either gateway partition can match. With an ID,
|
|
// only an unnamed gateway call can match (different IDs stay distinct).
|
|
for _, hasID := range []bool{false, true} {
|
|
if hasID && p.Text[11] != 0 {
|
|
continue
|
|
}
|
|
key.hasID = hasID
|
|
g := groups[key]
|
|
if g == nil {
|
|
continue
|
|
}
|
|
lo := sort.Search(len(g.ends), func(i int) bool { return !g.ends[i].at.Before(p.Time.Add(-2 * time.Second)) })
|
|
hi := sort.Search(len(g.ends), func(i int) bool { return g.ends[i].at.After(p.Time.Add(2 * time.Second)) })
|
|
if hi > lo {
|
|
count += hi - lo
|
|
candidate = g.ends[lo].index
|
|
// Range counts preserve ambiguity even for thousands of identical
|
|
// retries, without enumerating their Cartesian product.
|
|
g.counts[lo]++
|
|
g.counts[hi]--
|
|
}
|
|
}
|
|
if count == 1 {
|
|
candidates[ref] = candidate
|
|
}
|
|
}
|
|
}
|
|
unique := map[rowRef]bool{}
|
|
for _, g := range groups {
|
|
count := 0
|
|
for i, end := range g.ends {
|
|
count += g.counts[i]
|
|
if count == 1 {
|
|
unique[end.index] = true
|
|
}
|
|
}
|
|
}
|
|
for ref, i := range candidates {
|
|
if unique[i] {
|
|
matched[ref] = true
|
|
}
|
|
}
|
|
return matched
|
|
}
|
|
func sharesOf(m map[string]*Share) []Share {
|
|
out := make([]Share, 0, len(m))
|
|
for _, s := range m {
|
|
out = append(out, *s)
|
|
}
|
|
slices.SortFunc(out, func(a, b Share) int {
|
|
if a.AllTokens() != b.AllTokens() {
|
|
return b.AllTokens() - a.AllTokens()
|
|
}
|
|
if a.Calls != b.Calls {
|
|
return b.Calls - a.Calls
|
|
}
|
|
return strings.Compare(a.ID, b.ID)
|
|
})
|
|
return out
|
|
}
|
|
func buildRequestPage(p Period, f Filter, offset, limit int, gateway *rowChunk, chunks []*rowChunk) RequestPage {
|
|
return buildRequestBlocks(p, f, offset, limit, Clock(), []*rowChunk{gateway}, chunks, nil, nil)
|
|
}
|
|
|
|
// Shared days are never matched to this computer's gateway or session calls.
|
|
// now is the moment the page is asked at: its period and its chart's hours or
|
|
// days are read from it.
|
|
func buildRequestBlocks(p Period, f Filter, offset, limit int, now time.Time, gateways, chunks, others []*rowChunk, names map[string]string) RequestPage {
|
|
skip := visibleLocal(chunks)
|
|
since := p.Since(now)
|
|
matched := matchedBlocks(gateways, chunks, skip, since, true)
|
|
all := append(append(slices.Clone(gateways), chunks...), others...)
|
|
visit := func(fn func(rowRef, Row)) {
|
|
for _, c := range all {
|
|
for i, pr := range c.Rows {
|
|
ref := rowRef{c, i}
|
|
if pr.Time.Before(since) || skip[ref] || matched[ref] {
|
|
continue
|
|
}
|
|
fn(ref, c.row(i))
|
|
}
|
|
}
|
|
}
|
|
out := RequestPage{Rows: []Row{}, Agents: []string{}, Providers: []string{}, Purposes: []string{}, By: map[string][]Share{}}
|
|
agents, providers := map[string]bool{}, map[string]bool{}
|
|
purposes := map[string]bool{}
|
|
callers := map[string]*Group{}
|
|
accounts := map[string]*Group{}
|
|
computers := map[string]*Share{}
|
|
groups := map[string]map[string]*Share{}
|
|
chartGroups := map[string]map[string]*Share{}
|
|
seriesGroups := map[string]map[string]*Share{}
|
|
keys := keyer{}
|
|
for _, d := range Dimensions {
|
|
groups[d] = map[string]*Share{}
|
|
chartGroups[d] = map[string]*Share{}
|
|
seriesGroups[d] = map[string]*Share{}
|
|
}
|
|
// Bound the requested prefix before adding limit: external offsets can
|
|
// reach MaxInt, and a page beyond all sources needs no heap at all.
|
|
maxRows := 0
|
|
for _, c := range all {
|
|
maxRows += len(c.Rows)
|
|
}
|
|
take := 0
|
|
if offset < maxRows {
|
|
take = offset + min(limit, maxRows-offset)
|
|
}
|
|
selected := newestHeap{}
|
|
chartFilter := f
|
|
chartFilter.Day = ""
|
|
var first time.Time
|
|
visit(func(ref rowRef, r Row) {
|
|
agents[r.Agent] = true
|
|
purposes[PurposeOf(r.Kind)] = true
|
|
if r.Provider != "" {
|
|
providers[r.Provider] = true
|
|
}
|
|
addCallerRow(callers, r)
|
|
addAccountRow(accounts, r)
|
|
keep := f.keeps(r.Record)
|
|
if keep {
|
|
out.Total++
|
|
if take > 0 && len(selected) < take {
|
|
heap.Push(&selected, ref)
|
|
} else if take > 0 && refNewer(ref, selected[0]) {
|
|
selected[0] = ref
|
|
heap.Fix(&selected, 0)
|
|
}
|
|
if !r.IsRejected() {
|
|
out.Sum.addRow(r)
|
|
}
|
|
}
|
|
if r.IsRejected() {
|
|
return
|
|
}
|
|
if keep || f.Day != "" && chartFilter.keeps(r.Record) {
|
|
for _, d := range Dimensions {
|
|
k := keys.key(r, d)
|
|
s := seriesGroups[d][k]
|
|
if s == nil {
|
|
s = &Share{ID: k}
|
|
seriesGroups[d][k] = s
|
|
}
|
|
s.addRow(r)
|
|
}
|
|
if first.IsZero() || r.Time.Before(first) {
|
|
first = r.Time
|
|
}
|
|
}
|
|
if g := f; names != nil {
|
|
g.Computer = ""
|
|
g.Day = ""
|
|
if g.keeps(r.Record) {
|
|
k := r.key("computer")
|
|
if computers[k] == nil {
|
|
computers[k] = &Share{ID: k}
|
|
}
|
|
computers[k].addRow(r)
|
|
}
|
|
}
|
|
for _, d := range Dimensions {
|
|
g := f
|
|
if d == "provider" {
|
|
g.Provider = ""
|
|
}
|
|
if d == "agent" {
|
|
g.Agent = ""
|
|
}
|
|
if d == "model" || d == "modelAt" {
|
|
g.Model = ""
|
|
}
|
|
if d == "modelAt" {
|
|
g.Provider = ""
|
|
}
|
|
if f.Day != "" {
|
|
g.Day = ""
|
|
if g.keeps(r.Record) {
|
|
k := keys.key(r, d)
|
|
if chartGroups[d][k] == nil {
|
|
chartGroups[d][k] = &Share{ID: k}
|
|
}
|
|
chartGroups[d][k].addRow(r)
|
|
}
|
|
g.Day = f.Day
|
|
}
|
|
if !g.keeps(r.Record) {
|
|
continue
|
|
}
|
|
k := keys.key(r, d)
|
|
s := groups[d][k]
|
|
if s == nil {
|
|
s = &Share{ID: k}
|
|
groups[d][k] = s
|
|
}
|
|
s.addRow(r)
|
|
}
|
|
})
|
|
slices.SortFunc(selected, func(a, b rowRef) int {
|
|
if refNewer(a, b) {
|
|
return -1
|
|
}
|
|
if refNewer(b, a) {
|
|
return 1
|
|
}
|
|
return 0
|
|
})
|
|
for _, ref := range selected[min(offset, len(selected)):] {
|
|
out.Rows = append(out.Rows, ref.row())
|
|
}
|
|
for a := range agents {
|
|
out.Agents = append(out.Agents, a)
|
|
}
|
|
slices.Sort(out.Agents)
|
|
for a := range providers {
|
|
out.Providers = append(out.Providers, a)
|
|
}
|
|
slices.Sort(out.Providers)
|
|
for purpose := range purposes {
|
|
out.Purposes = append(out.Purposes, purpose)
|
|
}
|
|
slices.Sort(out.Purposes)
|
|
out.CallerKeys = callerGroups(callers)
|
|
out.Accounts = callerGroups(accounts)
|
|
for _, d := range Dimensions {
|
|
out.By[d] = sharesOf(groups[d])
|
|
}
|
|
if f.Day != "" {
|
|
out.ChartBy = map[string][]Share{}
|
|
for _, d := range Dimensions {
|
|
out.ChartBy[d] = sharesOf(chartGroups[d])
|
|
}
|
|
}
|
|
out.Computers, out.Names = computerShares(computers, names)
|
|
var base []Point
|
|
chartSince := since
|
|
chartSince, out.Bucket, base = timeline(p, now, first)
|
|
out.Series = make([]SeriesPoint, len(base))
|
|
for i := range base {
|
|
out.Series[i] = SeriesPoint{Point: base[i], By: map[string]map[string]Part{}}
|
|
for _, d := range Dimensions {
|
|
out.Series[i].By[d] = map[string]Part{}
|
|
}
|
|
}
|
|
visit(func(_ rowRef, r Row) {
|
|
if !chartFilter.keeps(r.Record) || r.IsRejected() {
|
|
return
|
|
}
|
|
t := r.Time.In(time.Local)
|
|
if t.Before(chartSince) {
|
|
return
|
|
}
|
|
i := bucketIndex(out.Bucket, chartSince, t)
|
|
if i < 0 || i >= len(out.Series) {
|
|
return
|
|
}
|
|
pt := &out.Series[i]
|
|
pt.addRow(r)
|
|
for _, d := range Dimensions {
|
|
k := keys.key(r, d)
|
|
part := pt.By[d][k]
|
|
part.add(r)
|
|
pt.By[d][k] = part
|
|
}
|
|
})
|
|
// Match LedgerSeries's top-24 selection on the filtered data, not facets.
|
|
for _, d := range Dimensions {
|
|
kept := map[string]bool{}
|
|
for i, s := range sharesOf(seriesGroups[d]) {
|
|
if i < seriesKeep {
|
|
kept[s.ID] = true
|
|
}
|
|
}
|
|
for i := range out.Series {
|
|
for k := range out.Series[i].By[d] {
|
|
if !kept[k] {
|
|
delete(out.Series[i].By[d], k)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
func pageFromLedger(p Period, f Filter, offset, limit int, all Ledgered) RequestPage {
|
|
return pageFromLedgerAt(p, f, offset, limit, all, Clock())
|
|
}
|
|
|
|
// pageFromLedgerAt is the page of a ledger read at now, its chart over the
|
|
// period read at the same moment.
|
|
func pageFromLedgerAt(p Period, f Filter, offset, limit int, all Ledgered, now time.Time) RequestPage {
|
|
l := all.Filtered(f)
|
|
out := RequestPage{Sum: l.Sum, Total: len(l.Rows), Agents: l.Agents, Providers: l.Providers, Purposes: []string{}, By: map[string][]Share{}}
|
|
callers, accounts := map[string]*Group{}, map[string]*Group{}
|
|
purposes := map[string]bool{}
|
|
for i := len(all.Rows) - 1; i >= 0; i-- {
|
|
purposes[PurposeOf(all.Rows[i].Kind)] = true
|
|
addCallerRow(callers, all.Rows[i])
|
|
addAccountRow(accounts, all.Rows[i])
|
|
}
|
|
for purpose := range purposes {
|
|
out.Purposes = append(out.Purposes, purpose)
|
|
}
|
|
slices.Sort(out.Purposes)
|
|
out.CallerKeys = callerGroups(callers)
|
|
out.Accounts = callerGroups(accounts)
|
|
offset = min(offset, len(l.Rows))
|
|
out.Rows = l.Rows[offset:min(len(l.Rows), offset+limit)]
|
|
chartRows := l.Rows
|
|
if f.Day != "" {
|
|
chartFilter := f
|
|
chartFilter.Day = ""
|
|
chartRows = all.Filtered(chartFilter).Rows
|
|
out.ChartBy = map[string][]Share{}
|
|
}
|
|
out.Bucket, out.Series = ledgerSeriesAt(p, chartRows, now)
|
|
for _, d := range Dimensions {
|
|
g := f
|
|
if d == "provider" {
|
|
g.Provider = ""
|
|
}
|
|
if d == "agent" {
|
|
g.Agent = ""
|
|
}
|
|
if d == "model" || d == "modelAt" {
|
|
g.Model = ""
|
|
}
|
|
if d == "modelAt" {
|
|
g.Provider = ""
|
|
}
|
|
out.By[d] = Breakdown(all.Filtered(g).Rows, d)
|
|
if f.Day != "" {
|
|
g.Day = ""
|
|
out.ChartBy[d] = Breakdown(all.Filtered(g).Rows, d)
|
|
}
|
|
}
|
|
if names := sharedNames(); len(names) > 0 {
|
|
g := f
|
|
g.Computer = ""
|
|
g.Day = ""
|
|
computers := map[string]*Share{}
|
|
for _, s := range Breakdown(all.Filtered(g).Rows, "computer") {
|
|
computers[s.ID] = &s
|
|
}
|
|
out.Computers, out.Names = computerShares(computers, names)
|
|
}
|
|
return out
|
|
}
|
|
|
|
// computerShares are the computers' shares, this one and every other kept
|
|
// here among them though it made no call in the period; none without names.
|
|
func computerShares(m map[string]*Share, names map[string]string) ([]Share, map[string]string) {
|
|
if names == nil {
|
|
return nil, nil
|
|
}
|
|
for _, id := range append([]string{ThisComputer}, slices.Collect(maps.Keys(names))...) {
|
|
if m[id] == nil {
|
|
m[id] = &Share{ID: id}
|
|
}
|
|
}
|
|
return sharesOf(m), names
|
|
}
|
|
|
|
// Caller choices cover the period, not just the current page or selected key.
|
|
func addCallerRow(groups map[string]*Group, r Row) {
|
|
if r.CallerKeyID == "" || r.IsRejected() {
|
|
return
|
|
}
|
|
g := groups[r.CallerKeyID]
|
|
if g == nil {
|
|
g = &Group{ID: r.CallerKeyID, CallerKeyID: r.CallerKeyID}
|
|
groups[r.CallerKeyID] = g
|
|
}
|
|
g.CallerKeyName = r.CallerKeyName
|
|
g.addRow(r)
|
|
}
|
|
|
|
// Account choices cover the period too: each account that answered a call,
|
|
// by provider, for the Account filter, whatever else is picked.
|
|
func addAccountRow(groups map[string]*Group, r Row) {
|
|
who := r.Account()
|
|
if who == "" || r.IsRejected() {
|
|
return
|
|
}
|
|
id := r.Provider + "@" + who
|
|
g := groups[id]
|
|
if g == nil {
|
|
g = &Group{ID: id, Provider: r.Provider, Account: who}
|
|
groups[id] = g
|
|
}
|
|
g.addRow(r)
|
|
}
|
|
|
|
func callerGroups(groups map[string]*Group) []Group {
|
|
out := make([]Group, 0, len(groups))
|
|
for _, g := range groups {
|
|
out = append(out, *g)
|
|
}
|
|
slices.SortFunc(out, func(a, b Group) int {
|
|
if a.Tokens() != b.Tokens() {
|
|
return b.Tokens() - a.Tokens()
|
|
}
|
|
if a.Calls != b.Calls {
|
|
return b.Calls - a.Calls
|
|
}
|
|
return strings.Compare(a.ID, b.ID)
|
|
})
|
|
return out
|
|
}
|
|
|
|
// prefetchSources reads the session files a query has to parse a few at a
|
|
// time, ahead of the loop that takes them in order. The first All after
|
|
// magpie starts parses every one of them, and one by one that was a wait on
|
|
// the disk for each: Requests stayed a skeleton for 40 s over 12k Codex
|
|
// sessions. read(i) gives source i's calls; at most a window of them waits
|
|
// to be taken, so the history is never all held at once. A source that
|
|
// wasn't wanted is read when it is asked for.
|
|
func prefetchSources(sources []sessions.CallSource, want func(sessions.CallSource) bool, readSource func(sessions.CallSource) []sessions.Call) func(int) []sessions.Call {
|
|
type slot struct {
|
|
done chan struct{}
|
|
calls []sessions.Call
|
|
}
|
|
slots := map[int]*slot{}
|
|
var order []int
|
|
for i, s := range sources {
|
|
if want(s) {
|
|
slots[i] = &slot{done: make(chan struct{})}
|
|
order = append(order, i)
|
|
}
|
|
}
|
|
if len(order) < 2 {
|
|
return func(i int) []sessions.Call { return readSource(sources[i]) }
|
|
}
|
|
workers := min(8, len(order))
|
|
window := make(chan struct{}, 4*workers)
|
|
next := make(chan int)
|
|
go func() {
|
|
for _, i := range order {
|
|
window <- struct{}{}
|
|
next <- i
|
|
}
|
|
close(next)
|
|
}()
|
|
for range workers {
|
|
go func() {
|
|
for i := range next {
|
|
s := slots[i]
|
|
s.calls = readSource(sources[i])
|
|
close(s.done)
|
|
}
|
|
}()
|
|
}
|
|
return func(i int) []sessions.Call {
|
|
s := slots[i]
|
|
if s == nil {
|
|
return readSource(sources[i])
|
|
}
|
|
<-s.done
|
|
<-window
|
|
cs := s.calls
|
|
s.calls = nil
|
|
return cs
|
|
}
|
|
}
|