Files
magpie/internal/provider/key_allowance_started_test.go
T
Edward4226 4d0bb7aeb7 provider: a key's elapsed reset is measured from its last good reading, not the read in flight (#2718)
readKeyAllowance sets e.at to now before it calls keep, and keep took
e.at as the time the old allowance was read. So on the key path every
"started again" check compared against now, and a reset that passed
between two readings was never told: the rest a vendor timed stayed
until it ran out, which is the half of #2718 the account path already
fixed. keep now measures from aAt, the time the kept allowance was
read, which only a successful reading moves; a failed read in between
leaves it alone. noteKeyAllowance (the card's reading) sets e.at after
keep for the same reason.

Edward4226's fix (codex/issue-2718-elapsed-reset, d132dacb4 with
f302d9312's deterministic test), which ggbdpq's comment on #2718
asked to carry with the rest-paths change. Their EVIDENCE.md is left
out.

Reviewed and landed as one batch of 12 commits (gua's #4593, #3269,
#3881, #2887, #3289, #2718, #2855, Edward4226's #2718 key-path
sibling, and four review follow-ups). Run for the batch, whose last
commit's tree is 5d58a75f3:
- Full suite before the rebase (base d307aa648, wsl-run magpie-desktop,
  go test -tags nogui -count=1 -timeout 45m ./...): 81 packages ok. Reds,
  all with issues and none in code this batch touches: internal/agent
  TestInstalledVersion, TestGrokInstalled, TestOmpDetectedWithPiDir
  (#4033, #3548, #3141); gateway TestUnroutedHeldReportSaved (#4300);
  gui TestSettingsSaveKeepsWhatItDoesNotSend (#4514) and
  TestColdTurnsTaken (#4510); provider
  TestClaudeAccountServesModelsListedSinceItsFetch (#3174). Run alone at
  origin/main 573b21f4b, TestGrokInstalled, TestOmpDetectedWithPiDir
  and TestSettingsSaveKeepsWhatItDoesNotSend are red there too. The
  other four pass there alone.
- After the rebase onto origin/main 573b21f4b, at this tree:
  internal/usage, update, gateway and provider ok. In internal/agent,
  the #4033/#3141 install-detection reds plus TestCopilotFolderFrom-
  AnIDEPluginIsNotTheCLI and TestZedAppPath. Those two are flaky the
  same way at origin/main (-count=10 alone: 4 and 5 of 10 red) and are
  already listed in #4033. The #3269 tests (TestCopilotLauncher*) pass
  5 of 5.
- Rebased onto origin/main ef63ef4a2. The #2855 commit met 0b9727ec9
  (#2974) in responses.go: the streamed item's done now takes both, the
  upstream's own id (thinkUp) and the made-over item; and in
  gateway-routing.md main's paragraph is kept with #2855's clause. That
  matches gua's latest head (range-diff: context only). At tree d7c76c6fa:
  internal/gateway, provider, usage, redact and update ok; vet
  GOOS=linux -tags nogui ./internal/..., darwin and GOOS=windows for
  gateway and provider.
- Rebased last onto origin/main d8f7d089f (5 commits: internal/agent
  and GUI files only). At tree 0d4bfd8c8, the pushed one: internal/agent's
  TestCopilotLauncher*, TestClaude*, TestOwn* and TestVSCode* ok, -count=3;
  TestCopilotFolderFromAnIDEPluginIsNotTheCLI red once there, as it is at
  main (#4033). Vet of internal/agent: darwin, linux and windows.
- gofmt -l clean. On mote: go vet darwin, GOOS=linux -tags nogui and
  GOOS=windows.
- Broken by hand, each turning its guard red: the lift gate
  (TestReadingKeepsARefusalsRest, TestAutoVisionKeepsOffARefusedAccount);
  the named-time condition (TestNamedQuotaTimeReplacesAGuess); the
  filter-chain hop (WholeReply/glm-5.3-flash); Edward's aAt
  (TestKeyAllowanceElapsedResetStartsAgain); and the old
  magpieMadeReasoning, which panics in TestMadeReasoningSaysItsTextOnce/
  no_summary. Every new test of gua's is red at base d307aa648.
Not tried: real OpenAI, DeepSeek, GLM or ChatGPT accounts; a real VS Code
1.144 install on Windows; a GUI run (no GUI files are touched).
2026-11-01 07:06:19 +08:00

99 lines
2.5 KiB
Go

package provider
import (
"sync/atomic"
"testing"
"time"
)
// A key's background reading measures a window started again from the last
// successful reading, not from a later failure or the current read. A
// reset that passed between those successful readings is therefore told
// on the successful read after it, even when a failed read came between.
func TestKeyAllowanceElapsedResetStartsAgain(t *testing.T) {
keyLimitsHome(t)
reset := time.Now().Add(time.Hour).Truncate(time.Second)
full := weekUsed(t, "800", reset)
var down atomic.Bool
srv, asked := sub2apiServer(t, func() ([]byte, int) {
if down.Load() {
return nil, 503
}
return full, 200
})
p := sub2apiKey(t, srv)
if err := Save(p); err != nil {
t.Fatal(err)
}
startedHooks.Lock()
hooks := startedHooks.fs
startedHooks.Unlock()
t.Cleanup(func() {
startedHooks.Lock()
startedHooks.fs = hooks
startedHooks.Unlock()
})
id := KeyAllowanceID(p)
if id == "" {
t.Fatal("the key has no allowance id")
}
started := make(chan string, 8)
OnStarted(func(agent, user string) {
if user == id {
select {
case started <- agent + "/" + user:
default:
}
}
})
read := func() {
keyAllowances.Lock()
gen := keyAllowances.gen
keyAllowances.Unlock()
readKeyAllowance(p, id, gen)
}
// Seed a successful reading whose reset passed before the next
// successful reading, without making the test wait for wall time.
wasAt := time.Now().Add(-2 * time.Hour)
passed := wasAt.Add(time.Hour)
noteKeyAllowance(p, []QuotaWindow{{
Name: "7 days", Span: 7 * 24 * time.Hour, Used: 100,
ResetsAt: &passed, Amount: 800, Limit: 800, Unit: "USD",
}}, wasAt)
keyAllowances.Lock()
first := keyAllowances.m[id]
if first == nil || !first.aAt.Equal(wasAt) {
t.Fatalf("the first successful reading was not kept: %+v", first)
}
firstAt := first.aAt
keyAllowances.Unlock()
select {
case got := <-started:
t.Fatalf("the first reading told started: %s", got)
default:
}
down.Store(true)
read()
down.Store(false)
keyAllowances.Lock()
failed := keyAllowances.m[id]
if failed == nil || !failed.aAt.Equal(firstAt) {
t.Fatalf("a failed reading moved the last successful reading: %+v", failed)
}
keyAllowances.Unlock()
read()
select {
case got := <-started:
if got != "/"+id {
t.Fatalf("told %q, want %q", got, "/"+id)
}
case <-time.After(2 * time.Second):
t.Fatal("the reset passed since the last successful reading: OnStarted was told nothing")
}
if n := asked.Load(); n != 2 {
t.Fatalf("asked %d times, want the failed and elapsed-reset readings", n)
}
}