From 7da38a9e7e870e7112068e873f99530e402aede4 Mon Sep 17 00:00:00 2001 From: Nils Stinnesbeck Date: Thu, 19 Nov 2026 09:46:27 +0100 Subject: [PATCH] sync: a page is stored in one transaction with parallel verification; a sync is cut off by idleness, not a fixed 2 minutes 20,000 listings to a newcomer: 120 s (unfinished) -> 24 s. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01AeFqV96dVeBX94inzcgZKw --- SPECS.md | 5 +- docs/PROTOCOL.md | 9 +++ internal/p2p/idle.go | 58 +++++++++++++++++ internal/p2p/idle_test.go | 51 +++++++++++++++ internal/p2p/recover.go | 10 +-- internal/p2p/sync.go | 45 ++++++++++---- internal/store/putmany_test.go | 93 ++++++++++++++++++++++++++++ internal/store/store.go | 110 +++++++++++++++++++++++++++++---- 8 files changed, 352 insertions(+), 29 deletions(-) create mode 100644 internal/p2p/idle.go create mode 100644 internal/p2p/idle_test.go create mode 100644 internal/store/putmany_test.go diff --git a/SPECS.md b/SPECS.md index 08a46b1..49d600d 100644 --- a/SPECS.md +++ b/SPECS.md @@ -163,7 +163,10 @@ starting a design-heavy item; see "Working with the owner". Not measured: relayed streams (need a node behind a NAT). The run found that a newcomer stored only ~137 listings/s with SQLite's `synchronous=FULL` and its 2-minute sync cut-off left 18% of a 20k region for the next round; the - store now uses `synchronous=NORMAL` (63 s for all 20,140). + store now uses `synchronous=NORMAL`, stores a sync page in one transaction + (`PutMany`, signatures checked in parallel), and a sync is only cut off + after 2 minutes without progress (30 minutes at most). A newcomer taking + 20,000 listings: 120 s and unfinished before, 24 s now. - **What the abuse limits do not cover** (`internal/p2p/guard.go`, `ipgate.go`, `internal/api/ratelimit.go`): attackers with many real addresses, valid but unwanted records under the limits, and bans are per node and not shared diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md index 828e362..f4e6652 100644 --- a/docs/PROTOCOL.md +++ b/docs/PROTOCOL.md @@ -747,6 +747,15 @@ Findings (see "What is left" in SPECS.md for the open ones): (WAL mode: no corruption on a crash, only the last few commits may be lost, and listings come back from peers) the same sync took 63 s for all 20,140. The store now uses `NORMAL`. + + Two more changes make a big catch-up faster and no longer depend on a + fixed deadline. A sync page is stored in one transaction + (`Store.PutMany`), with the signature checks spread over the cores, and + a sync is cut off after 2 minutes *without progress* (any record, request + or stored page counts) or 30 minutes in all, instead of 2 minutes flat. + One newcomer following two regions of a node that holds 20,000 listings + (same machine, same data): old store 120 s, cut off at 15,126 of 20,000; + `synchronous=NORMAL` 38 s for all; plus pages in one transaction 24 s. 2. **Peer limits are crude.** The first run had no peer scoring: the attacker stayed connected to all 10 nodes it dialed after 500 bad messages. Now every node counts, per relaying peer and minute, the messages it gets (over 1200 diff --git a/internal/p2p/idle.go b/internal/p2p/idle.go new file mode 100644 index 0000000..57e1381 --- /dev/null +++ b/internal/p2p/idle.go @@ -0,0 +1,58 @@ +package p2p + +import ( + "context" + "sync" + "time" +) + +// A sync used to be cut off after a fixed two minutes, however well it was +// going: a newcomer catching up from a large region stopped half way and +// waited for the next anti-entropy round. Now it is cut off when it makes no +// progress for syncIdle, and in any case after syncMax. +const ( + syncIdle = 2 * time.Minute + syncMax = 30 * time.Minute +) + +type idleKey struct{} + +// idleTimer ends a context after a period without progress. +type idleTimer struct { + mu sync.Mutex + timer *time.Timer + idle time.Duration + closed bool +} + +func (t *idleTimer) touch() { + t.mu.Lock() + defer t.mu.Unlock() + if !t.closed { + t.timer.Reset(t.idle) + } +} + +// withIdleTimeout returns a context that ends after idle without a call to +// progress(ctx), or after max at the latest. +func withIdleTimeout(parent context.Context, idle, max time.Duration) (context.Context, context.CancelFunc) { + ctx, cancel := context.WithTimeout(parent, max) + t := &idleTimer{idle: idle} + t.timer = time.AfterFunc(idle, cancel) + ctx = context.WithValue(ctx, idleKey{}, t) + return ctx, func() { + t.mu.Lock() + t.closed = true + t.timer.Stop() + t.mu.Unlock() + cancel() + } +} + +// progress tells ctx's idle timer that work is going on; for a context without +// one it does nothing. +func progress(ctx context.Context) { + if t, ok := ctx.Value(idleKey{}).(*idleTimer); ok { + t.touch() + } +} diff --git a/internal/p2p/idle_test.go b/internal/p2p/idle_test.go new file mode 100644 index 0000000..c33c7b7 --- /dev/null +++ b/internal/p2p/idle_test.go @@ -0,0 +1,51 @@ +package p2p + +import ( + "context" + "testing" + "time" +) + +func TestASyncThatKeepsMakingProgressIsNotCutOff(t *testing.T) { + ctx, cancel := withIdleTimeout(context.Background(), 150*time.Millisecond, time.Minute) + defer cancel() + for i := 0; i < 10; i++ { // 500 ms in all, well past the idle limit + time.Sleep(50 * time.Millisecond) + progress(ctx) + if ctx.Err() != nil { + t.Fatalf("cut off after %d steps although it made progress", i) + } + } + select { + case <-ctx.Done(): + case <-time.After(2 * time.Second): + t.Fatal("not cut off after it stopped making progress") + } +} + +func TestASyncWithoutProgressIsCutOff(t *testing.T) { + ctx, cancel := withIdleTimeout(context.Background(), 100*time.Millisecond, time.Minute) + defer cancel() + select { + case <-ctx.Done(): + case <-time.After(2 * time.Second): + t.Fatal("an idle sync was not cut off") + } +} + +func TestASyncIsCutOffAtTheLatestAfterTheMaximum(t *testing.T) { + ctx, cancel := withIdleTimeout(context.Background(), time.Minute, 200*time.Millisecond) + defer cancel() + for end := time.Now().Add(2 * time.Second); time.Now().Before(end); { + progress(ctx) + if ctx.Err() != nil { + return + } + time.Sleep(20 * time.Millisecond) + } + t.Fatal("progress kept a sync alive past the maximum") +} + +func TestProgressOnAPlainContextDoesNothing(t *testing.T) { + progress(context.Background()) // must not panic +} diff --git a/internal/p2p/recover.go b/internal/p2p/recover.go index b93501e..4574bdf 100644 --- a/internal/p2p/recover.go +++ b/internal/p2p/recover.go @@ -45,6 +45,7 @@ func (n *Node) recoverOwn(ctx context.Context, p peer.ID) error { for page := 0; page < maxSyncPages; page++ { var count int var last string + var got []*listing.Listing err := n.request(ctx, p, syncRequest{ Kind: "author", Author: author, Limit: n.cfg.SyncPageSize, AfterID: after, }, func(line []byte) { @@ -57,12 +58,11 @@ func (n *Node) recoverOwn(ctx context.Context, p peer.ID) error { if l.Author != author { return // peer sent something we did not ask for } - if out, err := n.cfg.Store.Put(ctx, &l); err != nil { - n.log.Debug("recover: listing rejected", "peer", p, "err", err) - } else { - n.noteListing(ctx, &l, out, "recover", p) - } + got = append(got, &l) }) + if serr := n.storeSynced(ctx, p, "recover", got); serr != nil { + return serr + } if err != nil { n.recoverAsked.Add(-1) // this peer could not answer; another may return err diff --git a/internal/p2p/sync.go b/internal/p2p/sync.go index 5259caa..dbf7aa3 100644 --- a/internal/p2p/sync.go +++ b/internal/p2p/sync.go @@ -320,7 +320,7 @@ func (n *Node) syncSoon(p peer.ID) { delete(n.syncing, p) n.mu.Unlock() }() - ctx, cancel := context.WithTimeout(n.ctx, syncTimeout) + ctx, cancel := withIdleTimeout(n.ctx, syncIdle, syncMax) defer cancel() if err := n.SyncFrom(ctx, p); err != nil { n.log.Debug("sync", "peer", p, "err", err) @@ -442,17 +442,17 @@ func (n *Node) pullListings(ctx context.Context, p peer.ID, region string) error for i, it := range batch { keys[i] = it.Key() } + var got []*listing.Listing err := n.request(ctx, p, syncRequest{Kind: "fetch", Of: "listings", Region: region, Keys: keys}, func(line []byte) { var l listing.Listing if json.Unmarshal(line, &l) != nil || listing.Region(l.Geohash) != region { return } - if out, err := n.cfg.Store.Put(ctx, &l); err != nil { - n.log.Debug("sync: listing rejected", "peer", p, "err", err) - } else { - n.noteListing(ctx, &l, out, "sync", p) - } + got = append(got, &l) }) + if serr := n.storeSynced(ctx, p, "sync", got); serr != nil { + return serr + } if err != nil { return err } @@ -598,6 +598,7 @@ func (n *Node) syncRegion(ctx context.Context, p peer.ID, region string) error { for page := 0; page < maxSyncPages; page++ { var count int var last *listing.Listing + var got []*listing.Listing err := n.request(ctx, p, syncRequest{ Kind: "listings", Region: region, Limit: n.cfg.SyncPageSize, AfterCreated: cur.CreatedAt, AfterAuthor: cur.Author, AfterID: cur.ID, @@ -611,12 +612,11 @@ func (n *Node) syncRegion(ctx context.Context, p peer.ID, region string) error { if listing.Region(l.Geohash) != region { return // peer sent something we did not ask for } - if out, err := n.cfg.Store.Put(ctx, &l); err != nil { - n.log.Debug("sync: listing rejected", "peer", p, "err", err) - } else { - n.noteListing(ctx, &l, out, "sync", p) - } + got = append(got, &l) }) + if serr := n.storeSynced(ctx, p, "sync", got); serr != nil { + return serr + } if err != nil { return err } @@ -628,6 +628,27 @@ func (n *Node) syncRegion(ctx context.Context, p peer.ID, region string) error { return nil } +// storeSynced stores listings that came from p in one transaction and counts +// them. Refused ones are only logged. +func (n *Node) storeSynced(ctx context.Context, p peer.ID, via string, ls []*listing.Listing) error { + if len(ls) == 0 { + return nil + } + res, err := n.cfg.Store.PutMany(ctx, ls) + if err != nil { + return err + } + progress(ctx) + for i, r := range res { + if r.Err != nil { + n.log.Debug(via+": listing rejected", "peer", p, "err", r.Err) + continue + } + n.noteListing(ctx, ls[i], r.Outcome, via, p) + } + return nil +} + // request opens a sync stream, sends req and calls handle for each line. func (n *Node) request(ctx context.Context, p peer.ID, req syncRequest, handle func([]byte)) error { s, err := n.host.NewStream(ctx, p, SyncProtocol) @@ -648,11 +669,13 @@ func (n *Node) request(ctx context.Context, p peer.ID, req syncRequest, handle f sc := bufio.NewScanner(s) sc.Buffer(make([]byte, 0, 64<<10), listing.MaxSize+4096) for sc.Scan() { + progress(ctx) handle(sc.Bytes()) } if err := sc.Err(); err != nil { _ = s.Reset() return err } + progress(ctx) return nil } diff --git a/internal/store/putmany_test.go b/internal/store/putmany_test.go new file mode 100644 index 0000000..53decb5 --- /dev/null +++ b/internal/store/putmany_test.go @@ -0,0 +1,93 @@ +package store + +import ( + "errors" + "testing" + "time" + + "git.stinnesbeck.com/nils/allmende/internal/listing" +) + +// PutMany gives the same outcomes and the same database as Put one by one, +// refused listings included, and a refused one does not stop the rest. +func TestPutManyDoesWhatPutDoes(t *testing.T) { + e := newQuotaEnv(t, 3) + old := e.listing(t, nil) + e.put(t, old) + + upd := e.listing(t, func(l *listing.Listing) { l.ID, l.Seq, l.Title = old.ID, 2, "Neu" }) + fresh := e.listing(t, nil) + bad := e.listing(t, nil) + bad.Title = "changed after signing" // the signature no longer fits + late := e.listing(t, nil) // the quota is 3: old, fresh, and one more fit + over := e.listing(t, nil) + + res, err := e.s.PutMany(ctx, []*listing.Listing{upd, fresh, bad, late, over, old}) + if err != nil { + t.Fatal(err) + } + want := []struct { + out Outcome + err error + }{ + {Replaced, nil}, {Inserted, nil}, {Ignored, ErrInvalid}, {Inserted, nil}, {Ignored, ErrQuota}, {Ignored, nil}, // old (seq 1) loses to upd + } + for i, w := range want { + if res[i].Outcome != w.out || !errors.Is(res[i].Err, w.err) && (w.err != nil || res[i].Err != nil) { + t.Errorf("listing %d: got (%v, %v), want (%v, %v)", i, res[i].Outcome, res[i].Err, w.out, w.err) + } + } + if n, _ := e.s.Count(ctx); n != 3 { + t.Fatalf("the store holds %d listings, want 3", n) + } + got, err := e.s.Get(ctx, old.Author, old.ID) + if err != nil || got.Title != "Neu" { + t.Fatalf("the update did not win: %v %v", got, err) + } +} + +func TestPutManyOfNothingIsFine(t *testing.T) { + e := newQuotaEnv(t, 3) + if res, err := e.s.PutMany(ctx, nil); err != nil || len(res) != 0 { + t.Fatalf("got %v, %v", res, err) + } +} + +// Logs how long 2000 listings take on a database file, one transaction each +// and in pages of 100 (go test -v -run PutManyIsFaster ./internal/store). +func TestPutManyIsFasterThanPut(t *testing.T) { + e := newQuotaEnv(t, -1) + ls := make([]*listing.Listing, 2000) + for i := range ls { + ls[i] = e.listing(t, nil) + } + took := map[string]time.Duration{} + for _, mode := range []string{"Put", "PutMany"} { + s, err := Open(t.TempDir()+"/"+mode+".db", Options{Difficulty: difficulty, MaxPerAuthor: -1, Clock: func() time.Time { return e.now }}) + if err != nil { + t.Fatal(err) + } + start := time.Now() + if mode == "Put" { + for _, l := range ls { + if _, err := s.Put(ctx, l); err != nil { + t.Fatal(err) + } + } + } else { + for i := 0; i < len(ls); i += 100 { + if _, err := s.PutMany(ctx, ls[i:i+100]); err != nil { + t.Fatal(err) + } + } + } + took[mode] = time.Since(start) + if n, _ := s.Count(ctx); n != len(ls) { + t.Fatalf("%s stored %d of %d", mode, n, len(ls)) + } + s.Close() + } + t.Logf("2000 listings: Put %v (%.0f/s), PutMany %v (%.0f/s)", + took["Put"].Round(time.Millisecond), 2000/took["Put"].Seconds(), + took["PutMany"].Round(time.Millisecond), 2000/took["PutMany"].Seconds()) +} diff --git a/internal/store/store.go b/internal/store/store.go index 8d2cd21..cc538de 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -10,7 +10,9 @@ import ( "encoding/json" "errors" "fmt" + "runtime" "strings" + "sync" "time" _ "modernc.org/sqlite" @@ -268,24 +270,111 @@ func (s *Store) Close() error { return s.db.Close() } // - tombstones are stored like any other version, so a late-arriving older // version cannot resurrect a deleted listing. func (s *Store) Put(ctx context.Context, l *listing.Listing) (Outcome, error) { - if err := l.Check(s.clock(), s.difficulty); err != nil { - return Ignored, fmt.Errorf("%w: %v", ErrInvalid, err) - } - data, err := l.Bytes() + data, hash, err := s.verify(l) if err != nil { return Ignored, err } - hash, err := l.Hash() - if err != nil { - return Ignored, err - } - tx, err := s.db.BeginTx(ctx, nil) if err != nil { return Ignored, err } defer tx.Rollback() + outcome, err := s.putTx(ctx, tx, l, data, hash) + if err != nil { + return Ignored, err + } + if err := tx.Commit(); err != nil { + return Ignored, err + } + return outcome, nil +} +// PutResult is what became of one listing of a PutMany. +type PutResult struct { + Outcome Outcome + Err error // ErrInvalid, ErrRevoked, ErrQuota; the others abort the batch +} + +// PutMany does what Put does for every listing, in one transaction: a sync page +// is stored with one write to disk instead of one per listing. The listings +// are applied in order, so a later one sees the quota use of the earlier ones. +// A listing that is refused (invalid, revoked, over quota) does not stop the +// others; a database error does, and nothing is stored. +func (s *Store) PutMany(ctx context.Context, ls []*listing.Listing) ([]PutResult, error) { + res := make([]PutResult, len(ls)) + type prepared struct { + data []byte + hash string + } + prep := make([]prepared, len(ls)) + // Checking signatures is most of the work and needs no database: spread it + // over the cores. + var wg sync.WaitGroup + next := make(chan int) + for w := 0; w < min(runtime.NumCPU(), max(1, len(ls)/4)); w++ { + wg.Add(1) + go func() { + defer wg.Done() + for i := range next { + data, hash, err := s.verify(ls[i]) + if err != nil { + res[i] = PutResult{Ignored, err} + continue + } + prep[i] = prepared{data, hash} + } + }() + } + for i := range ls { + next <- i + } + close(next) + wg.Wait() + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return nil, err + } + defer tx.Rollback() + for i, l := range ls { + if res[i].Err != nil { + continue + } + out, err := s.putTx(ctx, tx, l, prep[i].data, prep[i].hash) + switch { + case errors.Is(err, ErrRevoked), errors.Is(err, ErrQuota): + res[i] = PutResult{Ignored, err} + case err != nil: + return nil, err + default: + res[i] = PutResult{out, nil} + } + } + if err := tx.Commit(); err != nil { + return nil, err + } + return res, nil +} + +// verify checks l (signature, proof of work, dates) and returns the bytes and +// hash to store. +func (s *Store) verify(l *listing.Listing) ([]byte, string, error) { + if err := l.Check(s.clock(), s.difficulty); err != nil { + return nil, "", fmt.Errorf("%w: %v", ErrInvalid, err) + } + data, err := l.Bytes() + if err != nil { + return nil, "", err + } + hash, err := l.Hash() + if err != nil { + return nil, "", err + } + return data, hash, nil +} + +// putTx applies the conflict rules of Put to a verified listing inside tx. +func (s *Store) putTx(ctx context.Context, tx *sql.Tx, l *listing.Listing, data []byte, hash string) (Outcome, error) { + var err error var revoked int err = tx.QueryRowContext(ctx, ` SELECT COUNT(*) FROM revocations @@ -342,9 +431,6 @@ func (s *Store) Put(ctx context.Context, l *listing.Listing) (Outcome, error) { if err != nil { return Ignored, err } - if err := tx.Commit(); err != nil { - return Ignored, err - } return outcome, nil }