archive: the request archive in an S3 bucket is kept under a GiB, oldest calls removed

An R2 user on X: the sync bucket grew by 18 GB in under a month. The
backup and usage files are small and rewritten in place; what grew was
the request archive, every call written whole (bodies up to 32 MiB) as
archive/<date>/<id>.json and never removed. The archive on this computer
is capped at a GiB; the one in the bucket had no cap.

Now the bucket's archive is held to RequestArchiveMB (a GiB unless set,
carried by sync), down to a tenth under it past the cap, oldest first:
- only keys of ArchiveName's own shape under <prefix>/magpie/archive/
  are counted or removed; the backup, usage, other prefixes and anything
  else in the bucket are never touched (a test seeds seven such keys);
- uploads are counted as they go, and the bucket is listed again only
  after a tenth of the cap more is uploaded: one LIST for ~1000 calls,
  never one per call;
- the serving magpie lists once two minutes after it starts, archive on
  or off, so a bucket grown before this update is brought under the cap
  without the user doing anything (auto-cleanup chosen over a button:
  the objects are magpie's own, already capped locally, and a removal
  is logged);
- the Usage page's switch tooltip says the size ("…in <bucket>, up to
  1.1 GB"), in every language; the core script budget is kept, not
  raised: the two tooltips share one options object and the switch's
  aria-checked is set from a boolean.

The Nov 3 rise in Class B reads has no code cause found: archive reads
are click-driven only, and the backup's conditional GET runs every 3
minutes per computer online.

Red on the old logic (bucketAdded and KeepBucketArchiveBounded made
no-ops by hand, on mica): TestRequestArchiveKeptUnderItsSize "after 200
calls the archive holds 248 calls, 7629310 bytes, over its 1048576 (48
from 2020 left); 0 LISTs, 0 DELETEs"; TestBucketArchiveBroughtUnderIts
SizeAtStart keeps 30 calls / 3000 bytes; TestBucketArchiveListedPer
TenthUploaded "0 LISTs". With the fix: "200 calls: 44 kept, 986389
bytes; 4461157 bytes uploaded, 39 LISTs, 203 DELETEs".

Run at this tree (rebased on c6a67dd41):
- mote: gofmt -l internal clean; go test -timeout 45m -count=1
  ./internal/davsync ./internal/gateway ./internal/settings
  ./internal/settingsapi ./internal/cli: all ok (gateway 897s).
- mica: go test ./internal/gui ok (TestCoreScriptBudget included);
  GOOS=windows go vet of the six touched packages ok; GOOS=linux go vet
  of davsync, gateway, settings, settingsapi ok (gui and cli need
  WebKitGTK's cgo, not vetted for Linux).
- mica GUI, Chromium and WebKit, every language: request-archive,
  request-archive-usage, i18n-keys, i18n-en-no-cjk 22/22 at this tree;
  with call-headers, context-text, routing-bodies, routing-side-calls,
  usage-ledger-search and web-page 114/114 before the tooltip's last
  wording change.

Not tried: a real R2 or S3 bucket (fake S3 only), and the reporter's
own bucket contents.
This commit is contained in:
yetone
2026-11-16 11:25:30 +08:00
parent c6a67dd412
commit 9dcec67513
18 changed files with 734 additions and 19 deletions
+13 -1
View File
@@ -478,7 +478,19 @@ switch that anyone with the file and the passphrase can use those accounts.
responses stay actionable errors. Authentication, permission and branch
failures remain distinct from missing files. Rate limits use sync backoff.
- The request archive goes to S3 only when sync has a bucket. Its objects are
separate from the encrypted setup and usage files. With no bucket the same
separate from the encrypted setup and usage files. In the bucket it is kept
to `RequestArchiveMB` (1 GiB unless set; synced, as every computer writes
the one bucket) by `gateway/archive_bucket.go`: the oldest calls past it
are removed, down to a tenth under it. Only names of `ArchiveName`'s shape
under `<prefix>/magpie/archive/` are counted or removed, never the backup,
usage or another key. The serving magpie lists the archive once, two
minutes after it starts, whether the archive is on or off, so a bucket
grown before the cap (18 GB in a month for an R2 user on X) is brought
under it on update. After that uploads are counted, and the bucket is
listed again only once a tenth of the size has been uploaded since
(`TestRequestArchiveKeptUnderItsSize`,
`TestBucketArchiveBroughtUnderItsSizeAtStart`,
`TestBucketArchiveListedPerTenthUploaded`). With no bucket the same
files are kept on this computer instead (`gateway.DiskArchive`, in
`<settings.Dir()>/request-archive/<date>/<id>.json`, written through a
temporary file and renamed, 0600), under its own switch,
+3
View File
@@ -528,6 +528,9 @@ func run(args []string) error {
}
return nil, false
}
// and kept there under its size, a bucket grown before that brought
// under it once the gateway starts
gateway.WhileServing = append(gateway.WhileServing, gateway.KeepBucketArchiveBounded)
if len(args) == 0 {
if hasGUI {
return runGUI(true, "")
+71
View File
@@ -2,9 +2,12 @@ package davsync
import (
"context"
"encoding/xml"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
)
@@ -86,3 +89,71 @@ func (b *Bucket) Open(ctx context.Context, name string) (io.ReadCloser, int64, e
}
return res.Body, res.ContentLength, nil
}
// Each calls f with every object under prefix, a name as Put takes it
// ("archive/"), its name as Put takes it and its size, a page of a
// thousand at a time.
func (b *Bucket) Each(ctx context.Context, prefix string, f func(name string, size int64)) error {
s := b.at(prefix)
base := strings.TrimSuffix(b.s.key, file)
token := ""
seen := map[string]bool{}
for {
q := url.Values{"list-type": {"2"}, "prefix": {s.key}}
if token != "" {
q.Set("continuation-token", token)
}
u := s.bucketURL()
u.RawQuery = strings.ReplaceAll(q.Encode(), "+", "%20")
res, err := s.sendTo(ctx, http.MethodGet, u, nil, nil)
if err != nil {
return err
}
if res.StatusCode != http.StatusOK {
e := readError(res)
res.Body.Close()
return s.explain("list", e)
}
var l struct {
Contents []struct {
Key string `xml:"Key"`
Size int64 `xml:"Size"`
} `xml:"Contents"`
Truncated bool `xml:"IsTruncated"`
Next string `xml:"NextContinuationToken"`
}
err = xml.NewDecoder(io.LimitReader(res.Body, 16<<20)).Decode(&l)
res.Body.Close()
if err != nil {
return err
}
for _, c := range l.Contents {
if name, ok := strings.CutPrefix(c.Key, base); ok && strings.HasPrefix(c.Key, s.key) {
f(name, c.Size)
}
}
if !l.Truncated {
return nil
}
if l.Next == "" || seen[l.Next] {
return fmt.Errorf("listing %s: incomplete listing (missing or repeated continuation token)", s.where())
}
seen[l.Next] = true
token = l.Next
}
}
// Delete removes what is at name; nothing there is no error.
func (b *Bucket) Delete(ctx context.Context, name string) error {
s := b.at(name)
res, err := s.send(ctx, http.MethodDelete, nil, nil)
if err != nil {
return err
}
defer res.Body.Close()
if res.StatusCode >= 200 && res.StatusCode < 300 || res.StatusCode == http.StatusNotFound {
io.Copy(io.Discard, io.LimitReader(res.Body, 64<<10))
return nil
}
return s.explain("remove", readError(res))
}
+132
View File
@@ -4,7 +4,9 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"maps"
"net/http"
"net/http/httptest"
"strings"
@@ -115,3 +117,133 @@ func TestRequestArchiveToS3(t *testing.T) {
t.Fatalf("a missing one: %v", err)
}
}
// The archive in the bucket is kept under its size (RequestArchiveMB):
// a bucket grown before, with calls months old, loses its oldest at the
// first upload, and day after day of calls never takes it past the size,
// listed once per tenth of the size uploaded, not once per call. Nothing
// but the archive's own calls is ever removed: the backup, shared usage,
// a file of the user's in the archive's folder, another prefix's archive.
// Before, the bucket grew by every call's whole bodies for good (18 GB in
// a month for an R2 user on X).
func TestRequestArchiveKeptUnderItsSize(t *testing.T) {
newComputer(t).use(t)
f, srv := newFakeS3(t)
if err := Configure(f.config(srv)); err != nil {
t.Fatal(err)
}
was := gateway.ArchiveBucket
gateway.ArchiveBucket = func() (gateway.Putter, bool) { // as main.go sets it
if b, ok := S3Bucket(); ok {
return b, true
}
return nil, false
}
t.Cleanup(func() { gateway.ArchiveBucket = was })
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
io.ReadAll(r.Body)
w.Header().Set("Content-Type", "application/json")
io.WriteString(w, `{"id":"c1","object":"chat.completion","model":"m1","choices":[{"index":0,"message":{"role":"assistant","content":"done"},"finish_reason":"stop"}]}`)
}))
t.Cleanup(up.Close)
if err := provider.Save(provider.Provider{ID: "fake", Name: "Fake", Key: "vendor-key", Models: []string{"m1"}, Chat: up.URL + "/v1"}); err != nil {
t.Fatal(err)
}
settings.Save(settings.Settings{RequestArchive: true, RequestArchiveMB: 1})
const most = 1 << 20
const archive = "team x+y/magpie/archive/"
// what the bucket had before: 3 MiB of calls from 2020, and what
// isn't the archive's, a MiB each
mib := strings.Repeat("o", most)
var old []string
f.mu.Lock()
for i := range 48 {
k := fmt.Sprintf("%s2020-01-%02d/%06d-%016x.json", archive, 1+i/8, 100000+i, i)
f.store(k, []byte(mib[:64<<10]))
old = append(old, k)
}
foreign := []string{
"team x+y/magpie/magpie.magpie-backup",
"team x+y/magpie/usage/a.magpie-usage",
archive + "notes.txt",
archive + "2020-01-01/README.md",
archive + "2020-01-01/UPPER-0000000000000000.json",
"team x+y/other/archive/2020-01-01/000000-0000000000000001.json",
"elsewhere/magpie/archive/2020-01-01/000000-0000000000000002.json",
}
for _, k := range foreign {
f.store(k, []byte(mib))
}
f.mu.Unlock()
s := gateway.New()
// 200 calls of about 20 KB each: 4 MB, four times the size
content := strings.Repeat("y", 20<<10)
const calls = 200
for range calls {
req := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(`{"model":"fake/m1","messages":[{"role":"user","content":"`+content+`"}]}`))
rec := httptest.NewRecorder()
s.Handler().ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("%d %s", rec.Code, rec.Body)
}
}
// the archive's own calls only: what the bucket holds of them
ours := func() (n, bytes int) {
f.mu.Lock()
defer f.mu.Unlock()
for k, b := range f.objects {
if strings.HasPrefix(k, archive) && strings.HasSuffix(k, ".json") && !strings.Contains(k, "UPPER") {
n, bytes = n+1, bytes+len(b)
}
}
return n, bytes
}
oldLeft := func() (n int) {
f.mu.Lock()
defer f.mu.Unlock()
for _, k := range old {
if _, ok := f.objects[k]; ok {
n++
}
}
return n
}
deadline := time.Now().Add(10 * time.Second)
for {
n, b := ours()
if b <= most && oldLeft() == 0 && n > 0 {
break
}
if time.Now().After(deadline) {
left := oldLeft()
f.mu.Lock()
put, lists, deletes := f.put, f.lists, f.deletes
f.mu.Unlock() // the server's handlers wait on it as the test ends
t.Fatalf("after %d calls the archive holds %d calls, %d bytes, over its %d (%d from 2020 left); %d bytes uploaded, %d LISTs, %d DELETEs",
calls, n, b, most, left, put, lists, deletes)
}
time.Sleep(20 * time.Millisecond)
}
n, b := ours()
f.mu.Lock()
put, lists, deletes := f.put, f.lists, f.deletes
objects := maps.Clone(f.objects)
f.mu.Unlock()
t.Logf("%d calls: %d kept, %d bytes; %d bytes uploaded, %d LISTs, %d DELETEs", calls, n, b, put, lists, deletes)
// at least the tenth under the size is kept, not everything removed
if b < most/2 {
t.Errorf("only %d bytes kept of %d", b, most)
}
// a LIST per tenth of the size uploaded, about 100 KB here, and the
// first: never one per call
if lists > 1+put/(most/10)+2 || lists*4 > calls {
t.Errorf("%d LISTs for %d calls of %d bytes", lists, calls, put)
}
for _, k := range foreign {
if string(objects[k]) != mib {
t.Errorf("%s touched", k)
}
}
}
+44
View File
@@ -36,6 +36,8 @@ type fakeS3 struct {
log []string // each request: method, and the condition sent
onWrite func() // runs once, at the next PUT or HEAD (a write's look first), before it is answered
sent int // the bytes of objects read
put int // the bytes of objects written
lists, deletes int // the LISTs and DELETEs answered
// reread, when set, is how the server reads a header back before it
// checks the signature over it
reread func(name, value string) string
@@ -79,6 +81,10 @@ func (f *fakeS3) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
switch r.Method {
case http.MethodGet, http.MethodHead:
if key == "" && r.URL.Query().Get("list-type") == "2" {
f.list(w, r.URL.Query().Get("prefix"))
return
}
b, ok := f.objects[key]
if !ok {
if r.Method == http.MethodHead {
@@ -109,13 +115,51 @@ func (f *fakeS3) ServeHTTP(w http.ResponseWriter, r *http.Request) {
f.fail(w, http.StatusPreconditionFailed, "PreconditionFailed")
return
}
f.put += len(body)
f.store(key, body)
w.Header().Set("ETag", f.etags[key])
case http.MethodDelete:
f.deletes++
delete(f.objects, key)
delete(f.etags, key)
w.WriteHeader(http.StatusNoContent)
default:
f.fail(w, http.StatusNotImplemented, "NotImplemented")
}
}
// list answers a ListObjectsV2 of prefix, in one page.
func (f *fakeS3) list(w http.ResponseWriter, prefix string) {
f.lists++
var keys []string
for k := range f.objects {
if strings.HasPrefix(k, prefix) {
keys = append(keys, k)
}
}
slices.Sort(keys)
var b strings.Builder
b.WriteString(`<?xml version="1.0" encoding="UTF-8"?><ListBucketResult><IsTruncated>false</IsTruncated>`)
for _, k := range keys {
fmt.Fprintf(&b, `<Contents><Key>%s</Key><ETag>%s</ETag><Size>%d</Size></Contents>`, k, f.etags[k], len(f.objects[k]))
}
b.WriteString(`</ListBucketResult>`)
w.Header().Set("Content-Type", "application/xml")
w.Write([]byte(b.String()))
}
// stored is the bytes the bucket holds under prefix.
func (f *fakeS3) stored(prefix string) (n int) {
f.mu.Lock()
defer f.mu.Unlock()
for k, b := range f.objects {
if strings.HasPrefix(k, prefix) {
n += len(b)
}
}
return n
}
func (f *fakeS3) store(key string, b []byte) {
h := md5.Sum(b)
f.objects[key], f.etags[key] = b, `"`+hex.EncodeToString(h[:])+`"`
+3
View File
@@ -311,6 +311,9 @@ func upload(j archiveJob) {
archiveFailed(j.w.name, err)
return
}
if k, ok := j.w.to.(archiveKeeper); ok {
bucketAdded(k, "archive/"+j.w.name+".json", int64(buf.Len())) // kept under its size (archive_bucket.go)
}
archiveMu.Lock()
archiveErr = ""
archiveMu.Unlock()
+239
View File
@@ -0,0 +1,239 @@
package gateway
// The request archive in the bucket is kept to a size, as the one on this
// computer is (archive_local.go): RequestArchiveMB, a GiB unless set. Past
// it the oldest calls are removed, down to a tenth under it. Before this
// the bucket was never pruned, and a month of whole bodies grew one by
// 18 GB (an R2 user on X).
//
// Only objects magpie made are ever removed: under the archive's folder,
// archive/<date>/<id>.json, of ArchiveName's shape. The backup, shared
// usage and anything else in the bucket are never listed or touched.
//
// The bucket is listed once the serving magpie starts (so a bucket grown
// before this is brought under the size whether the archive is on or not),
// and after that only once a tenth of the size more has been uploaded,
// counted as uploads go: one LIST page for a thousand calls, never one
// per call.
import (
"context"
"log"
"sort"
"strings"
"sync"
"time"
"github.com/yetone/magpie/internal/settings"
)
// archiveKeeper is a bucket that can be listed and removed from: the S3
// sync's (davsync.Bucket).
type archiveKeeper interface {
Each(ctx context.Context, prefix string, f func(name string, size int64)) error
Delete(ctx context.Context, name string) error
Where() string
}
// BucketArchiveCap is how large the archive in the bucket grows, in bytes:
// settings' RequestArchiveMB, a GiB unless set.
func BucketArchiveCap() int64 {
mb := settings.Shared().RequestArchiveMB
if mb <= 0 {
mb = 1024
}
return int64(mb) << 20
}
// bucketKept is what the archive in the bucket is known to hold.
var bucketKept struct {
mu sync.Mutex
where string // the bucket counted
total int64 // its bytes, as last listed and uploaded since
known bool
pruning bool
again bool // another pass is wanted once this one ends
}
// bucketCap is the size; a test's own when set.
var bucketCap = BucketArchiveCap
// archiveFirstPrune is how long after the gateway starts the bucket is
// first listed: once start's own work is done.
var archiveFirstPrune = 2 * time.Minute
// KeepBucketArchiveBounded brings the archive in the bucket under its size
// once the serving magpie has started, for a bucket grown before the size
// was kept: on or off, the archive's own objects past the size go.
func KeepBucketArchiveBounded(ctx context.Context) {
t := time.NewTimer(archiveFirstPrune)
defer t.Stop()
select {
case <-ctx.Done():
return
case <-t.C:
}
if ArchiveBucket == nil {
return
}
b, ok := ArchiveBucket()
if !ok || b == nil {
return
}
if k, ok := b.(archiveKeeper); ok {
pruneBucketArchive(ctx, k, "")
}
}
// bucketAdded counts n bytes just uploaded at kept, and starts a pass that
// removes the oldest calls when the count is past the size, or not known.
func bucketAdded(k archiveKeeper, kept string, n int64) {
bucketKept.mu.Lock()
if bucketKept.where != k.Where() {
bucketKept.where, bucketKept.known = k.Where(), false
}
if bucketKept.known {
bucketKept.total += n
if bucketKept.total <= bucketCap() {
bucketKept.mu.Unlock()
return
}
}
bucketKept.mu.Unlock()
// its own goroutine: a bucket of tens of thousands of calls takes a
// while to bring under the size, and uploads go on meanwhile
archivePending.Add(1)
go func() {
defer archivePending.Done()
pruneBucketArchive(context.Background(), k, kept)
}()
}
// pruneBucketArchive lists the archive in k and removes its oldest calls
// past the size, down to a tenth under it; never kept, the call just
// uploaded. One pass at a time: a pass asked for during one runs after it.
func pruneBucketArchive(ctx context.Context, k archiveKeeper, kept string) {
bucketKept.mu.Lock()
if bucketKept.pruning {
bucketKept.again = true
bucketKept.mu.Unlock()
return
}
bucketKept.pruning = true
bucketKept.mu.Unlock()
for {
total, err := pruneBucketOnce(ctx, k, kept)
bucketKept.mu.Lock()
if err != nil {
log.Printf("request archive: keeping %s under %d MiB: %v", k.Where(), bucketCap()>>20, err)
// counted as known all the same, so a bucket that can't be
// listed is tried again only a tenth of the size later, not
// on every upload
}
bucketKept.where, bucketKept.total, bucketKept.known = k.Where(), total, true
if !bucketKept.again || ctx.Err() != nil {
bucketKept.pruning, bucketKept.again = false, false
bucketKept.mu.Unlock()
return
}
bucketKept.again = false
bucketKept.mu.Unlock()
}
}
type bucketCall struct {
name string
size int64
}
// pruneBucketOnce is one pass: the archive's bytes after it.
func pruneBucketOnce(ctx context.Context, k archiveKeeper, kept string) (int64, error) {
var calls []bucketCall
var total int64
err := k.Each(ctx, "archive/", func(name string, size int64) {
if !archiveObject(name) {
return // not one magpie made: never counted, never removed
}
calls = append(calls, bucketCall{name, size})
total += size
})
if err != nil {
return total, err
}
most := bucketCap()
if total <= most {
return total, nil
}
// "archive/<date>/<HHMMSS>-…" sorts by when the call was made
sort.Slice(calls, func(i, j int) bool { return calls[i].name < calls[j].name })
goal := most - most/10
var gone []bucketCall
for _, c := range calls {
if total <= goal {
break
}
if c.name == kept {
continue
}
gone = append(gone, c)
total -= c.size
}
// a few at a time: a bucket grown to tens of GB has tens of thousands
var (
wg sync.WaitGroup
mu sync.Mutex
back int64 // the bytes of calls not removed after all
lastErr error
)
jobs := make(chan bucketCall)
for range 8 {
wg.Add(1)
go func() {
defer wg.Done()
for c := range jobs {
cctx, cancel := context.WithTimeout(ctx, 30*time.Second)
err := k.Delete(cctx, c.name)
cancel()
if err != nil {
mu.Lock()
back += c.size
lastErr = err
mu.Unlock()
}
}
}()
}
var unsent int64
for i, c := range gone {
if ctx.Err() != nil {
for _, r := range gone[i:] {
unsent += r.size
}
break
}
jobs <- c
}
close(jobs)
wg.Wait()
back += unsent
if ctx.Err() != nil {
return total + back, ctx.Err()
}
if len(gone) > 0 && back == 0 {
log.Printf("request archive: removed the %d oldest calls in %s, kept under %d MiB", len(gone), k.Where(), most>>20)
}
return total + back, lastErr
}
// archiveObject says whether name, as the bucket lists it, is a call
// magpie archived: "archive/<date>/<id>.json" as ArchiveName makes it.
func archiveObject(name string) bool {
rest, ok := strings.CutPrefix(name, "archive/")
date, base, ok2 := strings.Cut(rest, "/")
id, ok3 := strings.CutSuffix(base, ".json")
if !ok || !ok2 || !ok3 {
return false
}
n, ok := ArchiveName(date, id)
return ok && n == name
}
+204
View File
@@ -0,0 +1,204 @@
package gateway
import (
"context"
"fmt"
"strings"
"sync"
"testing"
"github.com/yetone/magpie/internal/settings"
)
// keptBucket is a bucket in memory that can be listed and removed from,
// as the S3 sync's is.
type keptBucket struct {
memBucket
where string
lists, deletes int
refuse string // a name Delete fails on
}
func (b *keptBucket) Each(_ context.Context, prefix string, f func(string, int64)) error {
b.mu.Lock()
defer b.mu.Unlock()
b.lists++
for k, v := range b.objs {
if strings.HasPrefix(k, prefix) {
f(k, int64(len(v)))
}
}
return nil
}
func (b *keptBucket) Delete(_ context.Context, name string) error {
b.mu.Lock()
defer b.mu.Unlock()
b.deletes++
if name == b.refuse {
return fmt.Errorf("HTTP 403 AccessDenied")
}
delete(b.objs, name)
return nil
}
func (b *keptBucket) Where() string { return b.where }
// The serving magpie brings a bucket grown before under the archive's size
// once it has started, the archive on or off: the oldest calls go, down to
// a tenth under the size, and nothing but calls of the archive's shape is
// listed as one or removed.
func TestBucketArchiveBroughtUnderItsSizeAtStart(t *testing.T) {
fresh(t)
settings.Save(settings.Settings{}) // the archive off
b := &keptBucket{memBucket: memBucket{objs: map[string][]byte{}}, where: t.Name()}
wasB, wasCap, wasFirst := ArchiveBucket, bucketCap, archiveFirstPrune
ArchiveBucket = func() (Putter, bool) { return b, true }
bucketCap = func() int64 { return 1000 }
archiveFirstPrune = 0
t.Cleanup(func() { ArchiveBucket, bucketCap, archiveFirstPrune = wasB, wasCap, wasFirst })
call := func(day, i int) string {
return fmt.Sprintf("archive/2026-10-%02d/%06d-%016x.json", day, 100000+i, i)
}
body := []byte(strings.Repeat("x", 100))
for day := 1; day <= 3; day++ {
for i := range 10 {
b.objs[call(day, i)] = body // 3000 bytes
}
}
b.refuse = call(1, 3)
foreign := []string{"magpie.magpie-backup", "usage/a.magpie-usage", "archive/notes.txt",
"archive/2026-10-01/README.md", "archive/2026-10-01/ABC.json", "archive/x/2026-10-01/000000-00.json"}
for _, k := range foreign {
b.objs[k] = []byte(strings.Repeat("f", 5000))
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
KeepBucketArchiveBounded(ctx)
// down to 900: the 21 oldest go, but the one the bucket refused
// stays, and the pass ends at 1000, at the size
var kept []string
var total int
for k, v := range b.objs {
if archiveObject(k) {
kept = append(kept, k)
total += len(v)
}
}
if total > 1000 || len(kept) != 10 {
t.Fatalf("kept %d calls, %d bytes: %v", len(kept), total, kept)
}
if _, ok := b.objs[call(1, 3)]; !ok {
t.Error("the call the bucket refused to remove is gone")
}
if _, ok := b.objs[call(3, 0)]; ok {
t.Error("the 21st oldest call kept")
}
for i := 1; i < 10; i++ {
if _, ok := b.objs[call(3, i)]; !ok {
t.Errorf("a newer call removed: %s", call(3, i))
}
}
for _, k := range foreign {
if _, ok := b.objs[k]; !ok {
t.Errorf("%s removed", k)
}
}
if b.lists != 1 {
t.Errorf("%d LISTs", b.lists)
}
// under the size, a start lists once and removes nothing
b.deletes = 0
KeepBucketArchiveBounded(ctx)
if b.deletes != 0 || b.lists != 2 {
t.Errorf("under the size: %d DELETEs, %d LISTs", b.deletes, b.lists)
}
}
// On, each upload is counted: the bucket is listed again only once a
// tenth of the size more is uploaded, and the call just uploaded is never
// the one removed, though it alone be over the size.
func TestBucketArchiveListedPerTenthUploaded(t *testing.T) {
fresh(t)
serveOn(t, "fake", "k", []string{"m1"}, archiveVendor{})
settings.Save(settings.Settings{RequestArchive: true})
b := &keptBucket{memBucket: memBucket{objs: map[string][]byte{}}, where: t.Name()}
wasB, wasCap := ArchiveBucket, bucketCap
ArchiveBucket = func() (Putter, bool) { return b, true }
var most int64 = 1 << 30
var mu sync.Mutex
bucketCap = func() int64 { mu.Lock(); defer mu.Unlock(); return most }
t.Cleanup(func() { ArchiveBucket, bucketCap = wasB, wasCap })
s := New()
archivePost(t, s)
one := 0
for _, v := range b.objs {
one = len(v)
}
if b.lists != 1 {
t.Fatalf("the first upload: %d LISTs, want 1 to count the bucket", b.lists)
}
// a size of ten calls: a tenth is one call, so past the size every
// call or two lists, never more than once a call
mu.Lock()
most = int64(10 * one)
mu.Unlock()
for range 40 {
archivePost(t, s)
}
n := 0
for k := range b.objs {
if archiveObject(k) {
n++
}
}
if n > 10 || n < 8 || b.lists > 41 {
t.Errorf("%d calls kept, %d LISTs", n, b.lists)
}
// well under the size, uploads list nothing
mu.Lock()
most = 1 << 30
mu.Unlock()
archivePost(t, s) // counted, under: no LIST
lists := b.lists
for range 20 {
archivePost(t, s)
}
if b.lists != lists {
t.Errorf("%d LISTs for 20 calls under the size", b.lists-lists)
}
// one call alone over the size is kept
mu.Lock()
most = 1
mu.Unlock()
rec := archivePost(t, s)
id := rec.Header().Get(ArchiveHeader)
found := false
for k := range b.objs {
if strings.HasSuffix(k, "/"+id+".json") {
found = true
}
}
if !found {
t.Error("the call just uploaded was removed")
}
}
func TestArchiveObject(t *testing.T) {
for name, want := range map[string]bool{
"archive/2026-10-01/101010-00ff.json": true,
"archive/2026-10-01/101010-00FF.json": false,
"archive/2026-10-01/101010-00ff.json.gz": false,
"archive/2026-13-01/101010-00ff.json": false,
"archive/2026-10-01/a/b.json": false,
"archive/notes.json": false,
"other/2026-10-01/101010-00ff.json": false,
"archive/2026-10-01/../x.json": false,
} {
if archiveObject(name) != want {
t.Errorf("%s: %v", name, !want)
}
}
}
+3 -3
View File
@@ -217,8 +217,8 @@ func saveDownload(dir, stem, ext string, r io.Reader) (string, error) {
// archiveJSON is the request archive as the Usage page shows it: on or
// off, the bucket it goes to, or, when sync isn't to S3, the folder on this
// computer and the size it is kept under, and why the last upload or save
// failed, if it did.
// computer, the size it is kept under in either, and why the last upload
// or save failed, if it did.
type archiveJSON struct {
On bool `json:"on"`
Bucket string `json:"bucket,omitempty"`
@@ -231,7 +231,7 @@ func archiveState() archiveJSON {
s := settings.Load()
var a archiveJSON
if b, ok := davsync.S3Bucket(); ok {
a.On, a.Bucket = s.RequestArchive, b.Where()
a.On, a.Bucket, a.Cap = s.RequestArchive, b.Where(), gateway.BucketArchiveCap()
} else {
a.On, a.Folder, a.Cap = s.RequestArchiveLocal, tilde(gateway.LocalArchive().Dir), gateway.LocalArchiveCap()
}
+4 -3
View File
@@ -7109,11 +7109,12 @@ function renderArchive() {
}
b.classList.toggle("on", !!a.on);
b.querySelector(".lib-switch").classList.toggle("on", !!a.on);
b.setAttribute("aria-checked", a.on ? "true" : "false");
b.setAttribute("aria-checked", !!a.on);
b.disabled = archiveSaving;
b.querySelector(".led-arch-name").textContent = t("Request archive");
b.title = a.bucket ? t("Keeps each call’s headers and bodies, secrets taken out, in {where}", { where: a.bucket })
: t("Keeps each call’s headers and bodies, secrets taken out, on this computer in {where}, the oldest removed past {size}", { where: a.folder || "", size: fmtBytes(a.cap || 0) });
const o = { where: a.bucket || a.folder, size: fmtBytes(a.cap) };
b.title = a.bucket ? t("Keeps each call’s headers and bodies, secrets taken out, in {where}, up to {size}", o)
: t("Keeps each call’s headers and bodies, secrets taken out, on this computer in {where}, the oldest removed past {size}", o);
let err = box.querySelector(".led-arch-err");
if (a.on && a.error) {
if (!err) { err = el("span", "led-arch-err"); box.prepend(err); }
+4 -4
View File
@@ -3596,7 +3596,7 @@ const I18N = {
"No body captured": "未捕获到内容",
"first 256 KB": "前 256 KB",
"Request archive": "请求存档",
"Keeps each call’s headers and bodies, secrets taken out, in {where}": "每次调用的请求/响应头和正文去除密钥后存到 {where}",
"Keeps each call’s headers and bodies, secrets taken out, in {where}, up to {size}": "每次调用的请求/响应头和正文去除密钥后存到 {where},最多 {size}",
"Keeps each call’s headers and bodies, secrets taken out, on this computer in {where}, the oldest removed past {size}": "每次调用的请求/响应头和正文去除密钥后存到本机的 {where},超过 {size} 时先删除最早的",
"Not saved": "未保存",
"Last save failed: {e}": "上次保存失败:{e}",
@@ -8932,7 +8932,7 @@ const I18N = {
"No body captured": "未捕獲到內容",
"first 256 KB": "前 256 KB",
"Request archive": "請求存檔",
"Keeps each call’s headers and bodies, secrets taken out, in {where}": "每次呼叫的請求/回應頭和正文去除金鑰後存到 {where}",
"Keeps each call’s headers and bodies, secrets taken out, in {where}, up to {size}": "每次呼叫的請求/回應頭和正文去除金鑰後存到 {where},最多 {size}",
"Keeps each call’s headers and bodies, secrets taken out, on this computer in {where}, the oldest removed past {size}": "每次呼叫的請求/回應頭和正文去除金鑰後存到本機的 {where},超過 {size} 時先刪除最早的",
"Not saved": "未儲存",
"Last save failed: {e}": "上次儲存失敗:{e}",
@@ -14269,7 +14269,7 @@ const I18N = {
"No body captured": "本文は記録されていません",
"first 256 KB": "最初の 256 KB",
"Request archive": "リクエストアーカイブ",
"Keeps each call’s headers and bodies, secrets taken out, in {where}": "各呼び出しのヘッダーと本文を、秘密情報を除いて {where} に保存します",
"Keeps each call’s headers and bodies, secrets taken out, in {where}, up to {size}": "各呼び出しのヘッダーと本文を、秘密情報を除いて {where} に最大 {size} まで保存します",
"Keeps each call’s headers and bodies, secrets taken out, on this computer in {where}, the oldest removed past {size}": "各呼び出しのヘッダーと本文を、秘密情報を除いてこのコンピュータの {where} に保存します。{size} を超えると古いものから削除します",
"Not saved": "未保存",
"Last save failed: {e}": "前回の保存に失敗しました:{e}",
@@ -19615,7 +19615,7 @@ const I18N = {
"No body captured": "Kein Body erfasst",
"first 256 KB": "erste 256 KB",
"Request archive": "Anfragearchiv",
"Keeps each call’s headers and bodies, secrets taken out, in {where}": "Speichert Header und Bodys jedes Aufrufs ohne Geheimnisse in {where}",
"Keeps each call’s headers and bodies, secrets taken out, in {where}, up to {size}": "Speichert Header und Bodys jedes Aufrufs ohne Geheimnisse in {where}, bis zu {size}",
"Keeps each call’s headers and bodies, secrets taken out, on this computer in {where}, the oldest removed past {size}": "Speichert Header und Bodys jedes Aufrufs ohne Geheimnisse auf diesem Computer in {where}; über {size} werden die ältesten entfernt",
"Not saved": "Nicht gespeichert",
"Last save failed: {e}": "Letztes Speichern fehlgeschlagen: {e}",
+1
View File
@@ -156,6 +156,7 @@ func TestSettingsSaveKeepsWhatItDoesNotSend(t *testing.T) {
GitHubToken: "ghp_kept",
RequestArchive: true,
RequestArchiveMaxMB: 64,
RequestArchiveMB: 2048,
GatewayConversations: true,
QuotaLeft: true,
UsageOrder: []string{"kimi", "codex"},
+5 -5
View File
@@ -4,7 +4,7 @@
// turned on; with sync not set up with an s3:// bucket it turns on all the
// same and keeps calls on this computer, its tooltip the folder and the size
// they are kept under (CyberCaius on Discord), with one its tooltip says the
// bucket; a failed upload, or a failed save on this computer, is said
// bucket and the size kept there; a failed upload, or a failed save on this computer, is said
// beside it. The Gateway page has no switch
// any more, and its recent calls show their own bodies with nothing of the
// archive under them, even one it kept: reading a call back from the archive
@@ -57,7 +57,7 @@ function serve(lang, seen) {
const body = route.request().postDataJSON();
seen.push(["switch", body]);
await new Promise((r) => setTimeout(r, 80));
gateway.archive = { on: body.on, ...(seen.bucket ? { bucket: where } : here), ...(body.on && seen.failing ? { error: seen.bucket ? "HTTP 403" : "disk full" } : {}) };
gateway.archive = { on: body.on, ...(seen.bucket ? { bucket: where, cap: 1 << 30 } : here), ...(body.on && seen.failing ? { error: seen.bucket ? "HTTP 403" : "disk full" } : {}) };
return json(gateway.archive);
}
if (url.pathname === "/api/archive") {
@@ -82,13 +82,13 @@ const words = {
name: "Request archive", fetch: "Fetch from archive", failed: "Upload failed", failedWhy: "Last upload failed: HTTP 403",
notSaved: "Not saved", notSavedWhy: "Last save failed: disk full",
local: "Keeps each call’s headers and bodies, secrets taken out, on this computer in ~/.config/magpie/request-archive, the oldest removed past 1.1 GB",
bucket: "Keeps each call’s headers and bodies, secrets taken out, in bkt/team on https://s3.example.com",
bucket: "Keeps each call’s headers and bodies, secrets taken out, in bkt/team on https://s3.example.com, up to 1.1 GB",
},
zh: {
name: "请求存档", fetch: "从存档取回", failed: "上传失败", failedWhy: "上次上传失败:HTTP 403",
notSaved: "未保存", notSavedWhy: "上次保存失败:disk full",
local: "每次调用的请求/响应头和正文去除密钥后存到本机的 ~/.config/magpie/request-archive,超过 1.1 GB 时先删除最早的",
bucket: "每次调用的请求/响应头和正文去除密钥后存到 bkt/team on https://s3.example.com",
bucket: "每次调用的请求/响应头和正文去除密钥后存到 bkt/team on https://s3.example.com,最多 1.1 GB",
},
};
@@ -204,7 +204,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
assert.deepEqual(border, [], "no left-border accent");
const missing = await page.evaluate(() => [
"Request archive", "Upload failed", "Last upload failed: {e}", "Not saved", "Last save failed: {e}",
"Keeps each call’s headers and bodies, secrets taken out, in {where}",
"Keeps each call’s headers and bodies, secrets taken out, in {where}, up to {size}",
"Keeps each call’s headers and bodies, secrets taken out, on this computer in {where}, the oldest removed past {size}",
"Not in the archive on this computer: it is saved just after the call, the oldest are removed past the archive's size, or the save failed (magpie's log says why)",
].flatMap((k) => ["zh", "zh-TW", "ja", "de"].filter((l) => !I18N[l][k]).map((l) => l + " " + k)));
+4
View File
@@ -334,6 +334,10 @@ type Settings struct {
// RequestArchiveMaxMB is how much of each body the archive keeps, in
// MiB: 0 for 32, at most 1024 (#447)
RequestArchiveMaxMB int `json:"requestArchiveMaxMB,omitempty"`
// RequestArchiveMB is how large the archive grows in the bucket before
// its oldest calls are removed, in MiB: 0 for 1024. Sync carries it, as
// every computer writes to the one bucket.
RequestArchiveMB int `json:"requestArchiveMB,omitempty"`
// RequestArchiveLocal keeps the request archive on this computer's disk,
// in magpie's folder (gateway/archive_local.go), while sync has no S3
// bucket for it (CyberCaius on Discord). Its own switch, separate from
+1
View File
@@ -316,6 +316,7 @@ func Merge(body []byte, cur settings.Settings, web bool) (settings.Settings, err
in.Proxies = cur.Proxies // set on its own (proxies), the password never sent to the page
in.RequestArchive = cur.RequestArchive // the Gateway page's, set on its own
in.RequestArchiveMaxMB = cur.RequestArchiveMaxMB // in settings.json only
in.RequestArchiveMB = cur.RequestArchiveMB // in settings.json only
in.ClaudeRunsMost = cur.ClaudeRunsMost // magpie claude-code runs, or settings.json (#2956)
in.GatewayConversations = cur.GatewayConversations // Sessions' explicit recording consent
in.RedactRules = cur.RedactRules // the masking rules, set on their own
+1 -1
View File
@@ -228,7 +228,7 @@
<tr><td><code>partner-counts.json</code>(キャッシュフォルダー)</td><td>まだ送っていないパートナーの回数。最大 14 日分</td></tr>
</table></div>
<p><code>install-id</code> と <code>stats-sent</code> は magpie のフォルダーにあります。macOS と Linux では <code>~/.config/magpie</code>、Windows では <code>%USERPROFILE%\.config\magpie</code>、<code>$XDG_CONFIG_HOME</code> が設定されていれば <code>$XDG_CONFIG_HOME/magpie</code>、ポータブル版ではそのデータフォルダーです。<code>partner-counts.json</code> は <code>~/.cache/magpie</code>(<code>$XDG_CACHE_HOME/magpie</code>、ポータブル版ではデータフォルダーの <code>cache</code>)にあります。どれも削除できます。<code>install-id</code> を消すと次の送信で新しいランダムな ID が作られ、新しいユーザーとして数えられます。カウントをオフにすれば、どれも再び書かれません。</p>
<p>リクエストアーカイブ(<span class="ui">使用量</span>ページのリクエスト一覧の上にある<span class="ui">リクエストアーカイブ</span>スイッチ)は<b>既定でオフ</b>です。同期に S3 バケットがないときにオンにすると、ゲートウェイを通る各呼び出しのヘッダーと本文を、S3 アーカイブと同じようにシークレットを伏せて、magpie のフォルダーの <code>request-archive</code> に 1 呼び出し 1 ファイルで保存します。読めるのはあなたのユーザーだけです。上限は 1 GiB(settings.json の <code>requestArchiveLocalMB</code>)で、超えると古い呼び出しから削除します。このスイッチはこのコンピューターだけのもので、同期で別のコンピューターでオンになることはありません。S3 バケットがあるときはバケットに送られ、ここには何も書かれません。フォルダーはいつでも削除できます。</p>
<p>リクエストアーカイブ(<span class="ui">使用量</span>ページのリクエスト一覧の上にある<span class="ui">リクエストアーカイブ</span>スイッチ)は<b>既定でオフ</b>です。同期に S3 バケットがないときにオンにすると、ゲートウェイを通る各呼び出しのヘッダーと本文を、S3 アーカイブと同じようにシークレットを伏せて、magpie のフォルダーの <code>request-archive</code> に 1 呼び出し 1 ファイルで保存します。読めるのはあなたのユーザーだけです。上限は 1 GiB(settings.json の <code>requestArchiveLocalMB</code>)で、超えると古い呼び出しから削除します。このスイッチはこのコンピューターだけのもので、同期で別のコンピューターでオンになることはありません。S3 バケットがあるときはバケットに送られ(そちらも 1 GiB まで、<code>requestArchiveMB</code>。超えると古い呼び出しから削除します)、ここには何も書かれません。フォルダーはいつでも削除できます。</p>
<p>アプリは自分のしたことをログ <code>app.log</code> に書きます。macOS では <code>~/Library/Logs/magpie</code>、Windows では <code>%LOCALAPPDATA%\magpie\logs</code>、Linux では <code>~/.local/state/magpie</code> です(<a href="/docs/ja/start#log">magpie のログはどこにありますか?</a>)。読めるのはあなたのユーザーだけです。magpie がしたことと出会ったエラーを記録し、キー、プロンプト、返答は記録しません。あなたが送らない限り、このコンピューターから出ません。上限は 5 MiB で、古いもの 1 つ(<code>app.old.log</code>)を残します。いつでも削除できます。</p>
<h2 id="site"><a class="anchor" href="#site">usemagpie.ai に見えるもの</a></h2>
+1 -1
View File
@@ -228,7 +228,7 @@
<tr><td><code>partner-counts.json</code> (in the cache folder)</td><td>Partner counts not yet sent, at most 14 days</td></tr>
</table></div>
<p><code>install-id</code> and <code>stats-sent</code> are in magpie’s folder: <code>~/.config/magpie</code> on macOS and Linux, <code>%USERPROFILE%\.config\magpie</code> on Windows, <code>$XDG_CONFIG_HOME/magpie</code> when that is set, and the data folder of a portable magpie. <code>partner-counts.json</code> is in <code>~/.cache/magpie</code> (<code>$XDG_CACHE_HOME/magpie</code>, or <code>cache</code> in a portable magpie’s data folder). You can delete any of them: a deleted <code>install-id</code> is replaced by a new random one at the next send, so you are counted as a new user; with the count off, none of them is written again.</p>
<p>The request archive (the <span class="ui">Request archive</span> switch on the <span class="ui">Usage</span> page, above the list of requests) is <b>off by default</b>. Turned on while sync has no S3 bucket, it keeps each gateway call’s headers and bodies, secrets masked as for the S3 archive, in <code>request-archive</code> in magpie’s folder, one file per call, readable by your user only. It grows to 1 GiB (<code>requestArchiveLocalMB</code> in settings.json) and the oldest calls are removed past that. The switch is this computer’s own: sync never turns it on at another computer. With an S3 bucket the calls go to the bucket instead, and nothing is written here. Delete the folder whenever you like.</p>
<p>The request archive (the <span class="ui">Request archive</span> switch on the <span class="ui">Usage</span> page, above the list of requests) is <b>off by default</b>. Turned on while sync has no S3 bucket, it keeps each gateway call’s headers and bodies, secrets masked as for the S3 archive, in <code>request-archive</code> in magpie’s folder, one file per call, readable by your user only. It grows to 1 GiB (<code>requestArchiveLocalMB</code> in settings.json) and the oldest calls are removed past that. The switch is this computer’s own: sync never turns it on at another computer. With an S3 bucket the calls go to the bucket instead, kept to 1 GiB there too (<code>requestArchiveMB</code>), the oldest removed past it, and nothing is written here. Delete the folder whenever you like.</p>
<p>The app writes a log of what it did, <code>app.log</code>, in <code>~/Library/Logs/magpie</code> on macOS, <code>%LOCALAPPDATA%\magpie\logs</code> on Windows and <code>~/.local/state/magpie</code> on Linux (see <a href="/docs/start#log">Where is magpie’s log?</a>), readable by your user only. It names what magpie did and the errors it met, never keys, prompts or replies, and stays on your computer unless you send it. It is kept to 5 MiB, with one older file, <code>app.old.log</code>. Delete them whenever you like.</p>
<h2 id="site"><a class="anchor" href="#site">What usemagpie.ai sees</a></h2>
+1 -1
View File
@@ -228,7 +228,7 @@
<tr><td><code>partner-counts.json</code>(缓存文件夹)</td><td>还没发送的合作伙伴次数,最多保留 14 天</td></tr>
</table></div>
<p><code>install-id</code> 和 <code>stats-sent</code> 在 magpie 的文件夹里:macOS 和 Linux 上是 <code>~/.config/magpie</code>,Windows 上是 <code>%USERPROFILE%\.config\magpie</code>,设置了 <code>$XDG_CONFIG_HOME</code> 时是 <code>$XDG_CONFIG_HOME/magpie</code>,便携版则在它的数据文件夹里。<code>partner-counts.json</code> 在 <code>~/.cache/magpie</code>(或 <code>$XDG_CACHE_HOME/magpie</code>,便携版数据文件夹里的 <code>cache</code>)。这些文件都可以删:删掉 <code>install-id</code> 后,下次发送会生成新的随机 ID,你会被算作新用户;关掉计数后,它们都不会再写入。</p>
<p>请求存档(<span class="ui">用量</span>页请求列表上方的<span class="ui">请求存档</span>开关)<b>默认关闭</b>。同步没有 S3 存储桶时打开它,每次经过网关的调用的请求头和正文会存到 magpie 文件夹里的 <code>request-archive</code>,一次调用一个文件,只有你的用户能读,密钥按 S3 存档同样的方式遮掉。它最多占 1 GiB(settings.json 里的 <code>requestArchiveLocalMB</code>),超过后先删最早的调用。这个开关只属于这台电脑,同步不会在别的电脑上把它打开。有 S3 存储桶时调用存到桶里,这里不写任何东西。这个文件夹随时可以删。</p>
<p>请求存档(<span class="ui">用量</span>页请求列表上方的<span class="ui">请求存档</span>开关)<b>默认关闭</b>。同步没有 S3 存储桶时打开它,每次经过网关的调用的请求头和正文会存到 magpie 文件夹里的 <code>request-archive</code>,一次调用一个文件,只有你的用户能读,密钥按 S3 存档同样的方式遮掉。它最多占 1 GiB(settings.json 里的 <code>requestArchiveLocalMB</code>),超过后先删最早的调用。这个开关只属于这台电脑,同步不会在别的电脑上把它打开。有 S3 存储桶时调用存到桶里(桶里同样最多 1 GiB,<code>requestArchiveMB</code>,超过时先删除最早的),这里不写任何东西。这个文件夹随时可以删。</p>
<p>应用会把它做了什么写进日志 <code>app.log</code>:macOS 上在 <code>~/Library/Logs/magpie</code>,Windows 上在 <code>%LOCALAPPDATA%\magpie\logs</code>,Linux 上在 <code>~/.local/state/magpie</code>(见 <a href="/docs/zh/start#log">magpie 的日志在哪里?</a>),只有你的用户能读。它记下 magpie 做了什么和遇到的错误,从不记密钥、提示词或回复,除非你发出去,否则只留在你的电脑上。它最多 5 MiB,另留一个更早的 <code>app.old.log</code>。随时可以删。</p>
<h2 id="site"><a class="anchor" href="#site">usemagpie.ai 能看到什么</a></h2>