Commit Graph
4 Commits
Author SHA1 Message Date
yetone 1fac66c06d usage: a log snapshot read inside its stamp's tick is checked once, when it settles (#4368)
Each request the gateway writes wakes several readers at once: the menu
bar, the pages, the Sessions list. They all read inside the change
stamp's tick (100ms on a fine clock, 1s on a whole-second one). The read
that built the snapshot hashed the whole log after its parse, each later
reader in the tick hashed it again, and the first read once it settled
hashed it once more. That was four times the log for one request with
three readers, the recordHash 3.08s in KaranocaVe's profile.

Now a snapshot read inside the tick is not hashed after its parse, and a
reader still inside the tick takes it as it is. The first read once the
tick settles hashes it and makes it settled, as before, so nothing
settled is made of an unchecked read. A snapshot continued from one that
never settled still hashes its prefix first, since trusted needs the old
one settled. The disk copy is checked against the file when it is
loaded, as before.

What changes: a same-size rewrite by another program inside the tick
reaches readers when the tick settles, up to 100ms or 1s later, not
within it. A read a moment earlier would have had the old bytes anyway.
TestUsageSameTickRewriteIsNotCached's case with no append and no settle
now settles before it checks; its other seven cases are as they were.

Run:
- TestUsageReadersOfOneAppendHashTheLogOnce (new): an append, three
  readers in the tick, one after it settles. 1.00x the log hashed per
  append, 4.00x on the old code (red there).
- TestUsageAppendReadHashesNoPreReadScan: 0.80x per append + read,
  1.80x before.
- go test ./internal/usage: ok on mote (macOS 27.2, 44s) and in WSL
  magpie-desktop (Ubuntu 24.04, 32s).
- GOOS=windows and GOOS=linux go vet ./internal/usage: ok. gofmt: clean.

Not tried: the reporter's log size, and a filesystem with whole-second
stamps (where the tick is 1s, the same path).
2026-11-01 17:57:15 +08:00
yetoneandggbdpq 3142a55594 usage: the fine-clock hash test times each read from the append's stamp, not the wall clock (#3511)
TestUsageReadAfterAppendHashesNothingOnAFineClock/whole-second_stamp was
red on CI on macOS and ubuntu at f02390544 (run 40802792343), and 2 to 3
of 20 with -count=20 on the Mac mini. It truncated the log's change time
to whole seconds and read at time.Now()+150ms, expecting every read to
fall inside the stamp's 1s settle. An append at x.86s or later has stamp
x.0 and its read at x+1.01s is past it, so the snapshot counted as
settled and nothing was hashed. Under load (#3551, WSL) the read's
time.Now() drifts later the same way.

The reader is right, not a bug: settledLogStamp takes the read's time
before the stat and calls a whole-second stamp c settled only when the
read is past c+1s. Any write at or after that read has a stamp of c+1s
or later, so an equal stamp can't hide a later write on a filesystem
with 1s mtimes. The test's assumption was wrong.

Each read is now stamp + tc.after, the stamp taken from the history log
and then from each append's stat (the one the fine case already took for
its skip). No wall clock is read on the path. A third case pins the
other side: a whole-second stamp read 1.15s later (the next second)
hashes nothing. ggbdpq's patch on #3511 proposed the same stamp-relative
read.

Run (mote = Mac mini, via mote-run; base f02390544):
- Old test, wall clock injected at x.95 of its second (logIndexNow =
  time.Now().Truncate(1s)+950ms+150ms), -count=10: 10 of 10 red with
  CI's "0 bytes hashed over 5 appends".
- New test, -count=50 -v: 150 of 150 subtests pass.
- Broken by hand: logStampSettle = 100ms turns whole-second_stamp red
  (3/3); logStampSettle = 2s turns the next-second case red (3/3, 54MB
  hashed). The next-second case first used logStampSettle+150ms and
  stayed green under the 2s break, so it is pinned to time.Second.
- mote: go vet ./internal/usage; -count=50 of the test; go test
  -count=1 -timeout 45m ./internal/usage/...: ok.
- Linux (wsl-run, magpie-desktop): go test ./internal/usage/...: ok.
- Windows (win-run, xiaomi-gpu): the three subtests pass (-count=3);
  the package is red only on TestDesktopSessionAccountMetadata ("Code
  tab account mapping"), which fails the same at untouched f02390544
  and is #1356.
- gofmt -l internal/usage: clean.

Not tried: a real filesystem with whole-second mtimes (HFS+/FAT); the
test fakes the truncation through logChangeTime as before.

Issues: #3511, #3551 (its duplicate)

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-10-29 10:13:06 +08:00
yetone f6a96b2f0b usage: a change time with a fraction settles in 100ms, so a read after an append hashes no log (#3394)
readLogSnapshot checks its snapshot against a SHA-256 of the log's whole
prefix whenever the log's change time is under a second old. Under steady
traffic every read came within a second of the gateway's last append, so
each one hashed the whole usage.jsonl again: 1.8 times the log for each
append and read. A stamp with a nonzero fraction of a second comes from a
clock that ticks in milliseconds (APFS in ns, Linux's coarse clock 1-10 ms,
NTFS ~15.6 ms), so it settles in logFineSettle = 100ms. A stamp in whole
seconds (HFS+, FAT, a share) keeps the one-second settle.

Run:
- go test -count=1 -timeout 45m ./internal/usage/ ./internal/budget/: ok.
- TestUsageReadAfterAppendHashesNothingOnAFineClock (20000-row log, 5
  appends, each followed by two reads): fine stamp 0 bytes hashed;
  whole-second stamp 50.7 MB. Broken by hand (logFineSettle = time.Second):
  54 MB hashed, red.
- Real account, sandbox HOME, a deepseek-only providers.json and a 98 MB
  usage.jsonl (the owner's own log, repeated 50 times). magpie serve took
  30 real /v1/responses calls with a Codex user agent to
  deepseek/deepseek-flash, all answered, while /v1/magpie/usage?period=today
  (the Usage page's read) was polled every second. Process CPU time, two
  runs each: before 3.11 s and 3.05 s, after 1.95 s and 2.25 s. The same
  calls with /v1/magpie/quotas polled cost 0.2 s on both binaries, since
  that path never reads the log.
- gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui
  ./internal/usage/ clean.

Not tried: an HFS+ or FAT volume (the test skips when the file system
gives whole-second stamps, and covers that case by truncating the stamp);
the full suite at this head runs after the push.
2026-10-24 21:00:05 +08:00
yetone 439cfc4ac4 usage: the parse is the log fingerprint, dropping the build's full re-read before it (#1357)
What changed. A usage-log snapshot's fingerprint is now produced by the
parse itself: each complete line read is fed into a SHA-256. When a build
continues the old snapshot's blocks, it continues the old snapshot's digest
too (crypto/sha256's state, kept on the snapshot as `digest`); otherwise the
digest starts fresh from byte 0 with the parse. The build's before-read
logRecordHash over the whole file is gone. The fingerprint covers the bytes
actually parsed (`off`), not info.Size(), so a half line another writer is
in the middle of appending is no longer counted as read; the unchanged
check, the prefix check and the after-read check all hash `off` bytes.

What stays, as #1328's tests require (ggbdpq's analysis on #1357): the
unsettled unchanged check, the prefix re-verification on a non-trusted
continuation, and the after-read check, which now compares the parse's own
digest against the file as it is after the read. A same-tick rewrite is
still caught at the build, not at a later read. On the trusted, settled
path nothing is re-read, as before; that snapshot now also carries a
fingerprint (the continued digest), so a later non-trusted append can
verify its prefix instead of rebuilding from byte 0.

Test changed: TestUsageRewriteBeforeFingerprintIsNotCached counted
logRecordHash calls and rewrote the file at call 1 (after the before-read
hash, before the parse) or call 2 (after the read). With the parse being
the fingerprint there is no call 1 any more, so the hash=2 case could no
longer fire. Its guarantee still holds and is still tested at both
boundaries: "before-read" rewrites at the build's first change-time look,
after its stat and before it opens and parses; "after-read" rewrites at the
after-read fingerprint check. Removing the after-read check makes
after-read fail. No other test changed.

New tests:
- TestUsageAppendReadHashesNoPreReadScan: 20,000-row settled log
  (2,760,615 bytes), 5 x Append + Summarize(Today), counts the bytes
  logRecordHash re-reads. origin/main: 7,728,984 bytes per cycle (2.80x the
  log), FAIL; this commit: 4,968,615 (1.80x), PASS. Wall time per cycle on
  an M-series Mac, 3 runs each: 3.43-3.52 ms before, 2.28-2.52 ms after
  (~32% less). The remaining two passes are the prefix check and the
  after-read check, which the same-tick guarantee needs.
- TestUsagePartialLineThenCompletion (settled and unsettled): another
  writer's half line, a read, then the line completed; the fingerprint
  covers the parsed bytes only and the completed record is counted. On
  origin/main it fails on the fingerprint check (it covered the half line).

Break checks: no after-read check -> RewriteBeforeFingerprint/after-read
fails; no prefix verification on a continuation -> SameSizeAndMtimeRewrite
append=true, SameTickRewrite append=true and LogGrowingRewriteThenAppend
fail; lines not fed into the digest -> SameTickRewrite fails.

Run: go test -tags nogui ./internal/usage/... ./internal/gateway/... (ok,
temp HOME, pinned caches, removed after); go test -race ./internal/usage/...
(ok); -race -count=10 on the rewrite/append tests (ok); gofmt -l (empty);
go vet, GOOS=linux and GOOS=windows go vet -tags nogui ./internal/usage/
(ok). Not tried on Windows or Linux hardware; the change is
platform-independent hashing over the same read.
2026-10-09 06:54:28 +08:00