carlos / platform Public

paths: generation counter, memoised reconcile, one-transaction writes

Brings the path cost benchmarks under the spec §6 budget where Task 1
can (controller ruling on the first report):

- route_paths gets a one-row generation counter bumped by AFTER
  INSERT/UPDATE/DELETE triggers. Fingerprint hashes the generation and
  row count instead of every row (falls back to the rows when the
  triggers are missing). An empty table digests as before.
- writePaths skips reading and writing route_paths when the desired
  set's digest and the table generation match the last pass that left
  the table equal to that set (per registry, in process).
- Registry.ApplyPaths writes a pass's upserts and deletes in one
  BEGIN IMMEDIATE transaction, 500 rows per statement, with a remote
  form, and returns the generation before and after.

At 10 hosts x 10,000 prefixes: Fingerprint 106 -> 5 ms, unchanged pass
360 -> 56 ms, initial derivation 7.2 -> 1.3 s. Reload is unchanged at
about 124 ms (ListPaths is about 86 ms of it); reported, not changed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev f0eeef1fa31fefabfb99eb9fef2c4a486af1bbca parent a18e354
8 files changed, +647 −85
  • .amadan/code-health.tsv +2 −2
  • internal/domains/aliases.go +6 −50
  • internal/domains/paths_cost_test.go +60 −1
  • internal/domains/pathwrite.go +127 −0
  • internal/registry/pathsgen.go +193 −0
  • internal/registry/pathsgen_test.go +241 −0
  • internal/registry/registry.go +13 −26
  • internal/registry/remote_dispatch.go +5 −6
diff --git a/.amadan/code-health.tsv b/.amadan/code-health.tsv
index b5dfee73e..55fb37e44 100644
--- a/.amadan/code-health.tsv
+++ b/.amadan/code-health.tsv
@@ -1853,7 +1853,7 @@ db-no-context internal/registry (*Registry).DemoMoved (*sql.DB).QueryRow 1
db-no-context internal/registry (*Registry).DueInstances (*sql.DB).Query 1
db-no-context internal/registry (*Registry).EarliestTimers (*sql.DB).Query 1
db-no-context internal/registry (*Registry).Fingerprint (*sql.DB).Exec 1
-db-no-context internal/registry (*Registry).Fingerprint (*sql.DB).Query 9
+db-no-context internal/registry (*Registry).Fingerprint (*sql.DB).Query 8
db-no-context internal/registry (*Registry).Fingerprint (*sql.DB).QueryRow 1
db-no-context internal/registry (*Registry).FireTimerNow (*sql.DB).Exec 1
db-no-context internal/registry (*Registry).FireTimerNowRegistration (*sql.DB).Exec 1
@@ -2214,7 +2214,7 @@ func-lines internal/hostbox ColdHandover.Run - 310
func-lines internal/objstore TestDeliveredContractMinio - 325
func-lines internal/provision Reconcile - 811
func-lines internal/provision rootReadArchivedChain - 400
-func-lines internal/registry (*Registry).dispatchRemote - 361
+func-lines internal/registry (*Registry).dispatchRemote - 357
func-lines internal/registry (*Registry).haJournal - 358
func-lines internal/release PassFilter - 399
func-lines internal/release adoptHost - 494
diff --git a/internal/domains/aliases.go b/internal/domains/aliases.go
index d7d50b45d..507293ccc 100644
--- a/internal/domains/aliases.go
+++ b/internal/domains/aliases.go
@@ -503,7 +503,7 @@ func ReconcileAliasesReport(ctx context.Context, s release.Store, reg *registry.
}
desired := map[string]bool{}
desiredWild := map[string]registry.WildcardDomain{}
- desiredPaths := map[string]registry.RoutePath{} // key: host + "\x00" + prefix
+ desiredPaths := newPathSet()
desiredRegional := map[string]registry.RegionalDomain{}
boxRegion := ""
if rep != nil {
@@ -728,10 +728,10 @@ func ReconcileAliasesReport(ctx context.Context, s release.Store, reg *registry.
}
continue
}
- desiredPaths[c.Host+"\x00"+prefix] = registry.RoutePath{
+ desiredPaths.add(registry.RoutePath{
Host: c.Host, Prefix: prefix, Target: target,
Account: c.Account, App: c.App,
- }
+ })
}
if unresolved > 0 {
log.Printf("domains: paths on %s: %d prefix(es) name no local ready route (e.g. %s) — the target is missing, or it is homed on another box; a path target must be homed on the SAME box as %s. Those prefixes serve %s's own route.",
@@ -972,53 +972,9 @@ func ReconcileAliasesReport(ctx context.Context, s release.Store, reg *registry.
return nil
}
-// writePaths brings route_paths to desired (keyed host + "\x00" + prefix).
-// Only a row that differs is written (spec §6): the pass runs every few
-// seconds on every box, and an unchanged republish of a 10,000-prefix map
-// must write nothing. A RoutePath is all its columns, so equality is
-// "already stored exactly so". A row no longer desired is deleted, unless
-// noRemoval (the startup pass) leaves it for the next ordinary pass. It
-// reports whether the result is incomplete: a write failed, or a row was
-// left. The error is the listing's, which aborts the pass.
-func writePaths(reg *registry.Registry, desired map[string]registry.RoutePath, noRemoval bool) (incomplete bool, err error) {
- existing, err := reg.ListPaths()
- if err != nil {
- return false, err
- }
- existingByKey := make(map[string]registry.RoutePath, len(existing))
- for _, p := range existing {
- existingByKey[p.Host+"\x00"+p.Prefix] = p
- }
- for k, p := range desired {
- if cur, ok := existingByKey[k]; ok && cur == p {
- continue
- }
- if upsertPathHook != nil {
- upsertPathHook(p)
- }
- if err := reg.UpsertPath(p); err != nil {
- log.Printf("domains: upsert path %s/%s: %v", p.Host, p.Prefix, err)
- incomplete = true
- }
- }
- for _, p := range existing {
- if _, ok := desired[p.Host+"\x00"+p.Prefix]; !ok {
- if noRemoval {
- incomplete = true // left for the next ordinary pass
- continue
- }
- if err := reg.DeletePath(p.Host, p.Prefix); err != nil {
- log.Printf("domains: remove path %s/%s: %v", p.Host, p.Prefix, err)
- incomplete = true
- }
- }
- }
- return incomplete, nil
-}
-
-// upsertPathHook, when set, is called just before each route_paths upsert
-// the reconcile pass makes. nil in production; the cost tests count writes
-// with it.
+// upsertPathHook, when set, is called for each route_paths row the reconcile
+// pass is about to upsert (writePaths, pathwrite.go). nil in production; the
+// cost tests count writes with it.
var upsertPathHook func(registry.RoutePath)
// deriveRegional adds a regional claim's desired regional_domains rows (#447,
diff --git a/internal/domains/paths_cost_test.go b/internal/domains/paths_cost_test.go
index 30acb389c..2f4d6625e 100644
--- a/internal/domains/paths_cost_test.go
+++ b/internal/domains/paths_cost_test.go
@@ -5,9 +5,12 @@ import (
"encoding/json"
"fmt"
"io"
+ "io/fs"
"log"
+ "os"
"path/filepath"
"testing"
+ "time"
"github.com/carlosframework/platform/internal/registry"
"github.com/carlosframework/platform/internal/release"
@@ -95,6 +98,42 @@ func TestReconcileRepointedPathWritesOnlyThatRow(t *testing.T) {
}
}
+// TestReconcileRestoresAHandEditedPathRow: once a pass has left the table
+// equal to the desired set, later passes skip reading it, but only while its
+// generation stands still. A row deleted or repointed by any other writer
+// moves the generation, and the next pass puts both back.
+func TestReconcileRestoresAHandEditedPathRow(t *testing.T) {
+ ctx := context.Background()
+ s := release.NewDirStore(t.TempDir())
+ reg := aliasRegWith(t)
+ addRoute(t, reg, "ti.to", "tito", "classic")
+ addRoute(t, reg, "go.tito.io", "tito", "go")
+ addRoute(t, reg, "beta.tito.io", "tito", "go")
+ putClaim(t, s, Claim{
+ Host: "ti.to", Account: "tito", App: "classic", Route: "ti.to",
+ CreatedAt: "2026-09-03T00:00:00Z",
+ Paths: map[string]string{"paulca": "go.tito.io", "bigcorp": "go.tito.io", "canary": "go.tito.io"},
+ })
+ for range 2 { // the second pass is the one that skips
+ if err := ReconcileAliases(ctx, s, reg, aliasNow(), nil, nil); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := reg.DeletePath("ti.to", "paulca"); err != nil {
+ t.Fatal(err)
+ }
+ if err := reg.UpsertPath(registry.RoutePath{Host: "ti.to", Prefix: "canary", Target: "beta.tito.io", Account: "tito", App: "classic"}); err != nil {
+ t.Fatal(err)
+ }
+ if err := ReconcileAliases(ctx, s, reg, aliasNow(), nil, nil); err != nil {
+ t.Fatal(err)
+ }
+ got := pathsByPrefix(t, reg, "ti.to")
+ if len(got) != 3 || got["paulca"] != "go.tito.io" || got["canary"] != "go.tito.io" {
+ t.Fatalf("route_paths = %v, want the hand-deleted and hand-repointed rows restored to go.tito.io", got)
+ }
+}
+
// pathCostPrefixes is the per-host prefix count of the cost budget (spec
// §6): every benchmark below runs hosts × this many path rows.
const pathCostPrefixes = 10_000
@@ -157,6 +196,24 @@ func pathCostClaims(tb testing.TB, s release.Store, hosts int) {
}
}
+// pathCostSettle backdates every claim object under root by an hour. The
+// claim cache keeps a claim only once it is older than modSettle, as every
+// claim is in production's steady state; without this each timed pass would
+// re-read and re-parse every claim body.
+func pathCostSettle(tb testing.TB, root string) {
+ tb.Helper()
+ old := time.Now().Add(-time.Hour)
+ err := filepath.WalkDir(root, func(p string, de fs.DirEntry, err error) error {
+ if err != nil || de.IsDir() {
+ return err
+ }
+ return os.Chtimes(p, old, old)
+ })
+ if err != nil {
+ tb.Fatal(err)
+ }
+}
+
func pathCostRegistry(tb testing.TB, hosts int, local bool) *registry.Registry {
tb.Helper()
reg, err := registry.Open(filepath.Join(tb.TempDir(), "registry.db"))
@@ -193,8 +250,10 @@ func BenchmarkReconcilePathSection(b *testing.B) {
b.Cleanup(func() { log.SetOutput(prev) })
for _, hosts := range []int{1, 5, 10} {
b.Run(fmt.Sprintf("hosts=%d", hosts), func(b *testing.B) {
- s := release.NewDirStore(b.TempDir())
+ root := b.TempDir()
+ s := release.NewDirStore(root)
pathCostClaims(b, s, hosts)
+ pathCostSettle(b, root)
b.Run("unchanged", func(b *testing.B) {
reg := pathCostRegistry(b, hosts, pathCostLocal)
diff --git a/internal/domains/pathwrite.go b/internal/domains/pathwrite.go
new file mode 100644
index 000000000..99311661f
--- /dev/null
+++ b/internal/domains/pathwrite.go
@@ -0,0 +1,127 @@
+package domains
+
+import (
+ "crypto/sha256"
+ "encoding/binary"
+ "hash"
+ "log"
+ "sync"
+
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// The reconcile pass's route_paths write (path routes across boxes, spec §6
+// cost budget). A box may hold 10 hosts × 10,000 prefixes, and the pass runs
+// every few seconds on every box, so the steady state must neither rewrite
+// the table nor read it whole.
+
+// pathSet is a pass's desired route_paths rows, keyed host + "\x00" +
+// prefix, and a digest of the rows in the order the pass derived them.
+//
+// The order is the claim listing's, then each claim's sorted prefixes. Equal
+// digests mean the same rows were added in the same order, so the same set.
+// A listing that came back in another order only costs one full diff.
+type pathSet struct {
+ rows map[string]registry.RoutePath
+ h hash.Hash
+ buf []byte
+}
+
+func newPathSet() *pathSet {
+ return &pathSet{rows: map[string]registry.RoutePath{}, h: sha256.New()}
+}
+
+// add makes p desired. Each field is length-prefixed in the digest, so no
+// field's bytes can be read as another's.
+func (s *pathSet) add(p registry.RoutePath) {
+ s.rows[p.Host+"\x00"+p.Prefix] = p
+ s.buf = s.buf[:0]
+ for _, f := range [...]string{p.Host, p.Prefix, p.Target, p.Account, p.App} {
+ s.buf = binary.AppendUvarint(s.buf, uint64(len(f)))
+ s.buf = append(s.buf, f...)
+ }
+ s.h.Write(s.buf)
+}
+
+func (s *pathSet) sum() (d [sha256.Size]byte) {
+ s.h.Sum(d[:0])
+ return d
+}
+
+// pathMemo is what this process knows about one registry's route_paths: at
+// generation gen the table held exactly the set whose digest is digest,
+// because a pass compared or wrote it so.
+type pathMemo struct {
+ digest [sha256.Size]byte
+ gen int64
+}
+
+// pathMemos holds a pathMemo per *registry.Registry. Production holds one
+// registry for the life of the process; the map keeps each key alive, so a
+// pointer is never reused for another registry while its memo is here.
+var pathMemos sync.Map
+
+// writePaths brings route_paths to desired.
+//
+// When the desired digest and the table's generation both equal the memo of
+// the last pass that left the table equal to a set, nothing can differ, and
+// the pass neither reads the table nor writes it. Any mismatch (the claims
+// changed, another writer or a hand edit moved the generation, a restart has
+// no memo, the generation could not be read) falls back to the full diff:
+// only a row that differs from the stored one is written, and a row no longer
+// desired is deleted unless noRemoval (the startup pass) leaves it for the
+// next ordinary pass. The writes go in one transaction (registry.ApplyPaths).
+//
+// It reports whether the result is incomplete: the write failed, or a row
+// was left. The error is the listing's, which aborts the pass.
+func writePaths(reg *registry.Registry, desired *pathSet, noRemoval bool) (incomplete bool, err error) {
+ digest := desired.sum()
+ gen, genErr := reg.PathsGeneration()
+ memo := genErr == nil
+ if m, ok := pathMemos.Load(reg); ok && memo && m.(pathMemo) == (pathMemo{digest, gen}) {
+ return false, nil
+ }
+ existing, err := reg.ListPaths()
+ if err != nil {
+ return false, err
+ }
+ existingByKey := make(map[string]registry.RoutePath, len(existing))
+ for _, p := range existing {
+ existingByKey[p.Host+"\x00"+p.Prefix] = p
+ }
+ var upserts []registry.RoutePath
+ for k, p := range desired.rows {
+ if cur, ok := existingByKey[k]; ok && cur == p {
+ continue
+ }
+ if upsertPathHook != nil {
+ upsertPathHook(p)
+ }
+ upserts = append(upserts, p)
+ }
+ var deletes [][2]string
+ for _, p := range existing {
+ if _, ok := desired.rows[p.Host+"\x00"+p.Prefix]; !ok {
+ if noRemoval {
+ incomplete = true // left for the next ordinary pass
+ continue
+ }
+ deletes = append(deletes, [2]string{p.Host, p.Prefix})
+ }
+ }
+ if len(upserts) > 0 || len(deletes) > 0 {
+ before, after, err := reg.ApplyPaths(upserts, deletes)
+ if err != nil {
+ log.Printf("domains: write %d path row(s) and remove %d: %v", len(upserts), len(deletes), err)
+ return true, nil
+ }
+ // Another writer between this pass's generation read and its
+ // transaction means the table is not exactly what was decided.
+ memo = memo && before == gen
+ gen = after
+ }
+ if memo && !incomplete {
+ pathMemos.Store(reg, pathMemo{digest, gen})
+ }
+ return incomplete, nil
+}
diff --git a/internal/registry/pathsgen.go b/internal/registry/pathsgen.go
new file mode 100644
index 000000000..6eae72682
--- /dev/null
+++ b/internal/registry/pathsgen.go
@@ -0,0 +1,193 @@
+package registry
+
+import (
+ "context"
+ "database/sql"
+ "fmt"
+ "io"
+ "slices"
+ "strings"
+)
+
+// route_paths generation (path routes across boxes, spec §6 cost budget).
+//
+// A box may hold 10 hosts × 10,000 path rows. Hashing every one of them on
+// Fingerprint's two-second poll, and reading every one of them on each
+// reconcile pass, is what the budget rules out. So route_paths carries a
+// one-row generation counter that SQLite triggers bump on every INSERT,
+// UPDATE and DELETE of a row. A trigger lives in the database file, so no
+// writer can forget it: not a new registry method, not an older binary, not
+// a hand edit in the sqlite3 shell.
+//
+// The schema is additive (CREATE ... IF NOT EXISTS, INSERT OR IGNORE), so an
+// existing registry migrates on open. Its counter starts at 0 with whatever
+// rows it already holds, which is fine: the generation only has to MOVE
+// when a row changes, never to equal anything on another box.
+const routePathsGenSchema = `
+CREATE TABLE IF NOT EXISTS route_paths_gen (
+ id INTEGER PRIMARY KEY CHECK (id = 1),
+ gen INTEGER NOT NULL
+);
+INSERT OR IGNORE INTO route_paths_gen (id, gen) VALUES (1, 0);
+CREATE TRIGGER IF NOT EXISTS route_paths_gen_insert AFTER INSERT ON route_paths
+BEGIN UPDATE route_paths_gen SET gen = gen + 1 WHERE id = 1; END;
+CREATE TRIGGER IF NOT EXISTS route_paths_gen_update AFTER UPDATE ON route_paths
+BEGIN UPDATE route_paths_gen SET gen = gen + 1 WHERE id = 1; END;
+CREATE TRIGGER IF NOT EXISTS route_paths_gen_delete AFTER DELETE ON route_paths
+BEGIN UPDATE route_paths_gen SET gen = gen + 1 WHERE id = 1; END;`
+
+const (
+ upsertPathSQL = `
+INSERT INTO route_paths (host, prefix, target, account, app)
+VALUES (?, ?, ?, ?, ?)
+ON CONFLICT(host, prefix) DO UPDATE SET
+ target=excluded.target, account=excluded.account, app=excluded.app`
+ deletePathSQL = `DELETE FROM route_paths WHERE host = ? AND prefix = ?`
+ pathsGenSQL = `SELECT gen FROM route_paths_gen WHERE id = 1`
+ pathsTriggerSQL = `SELECT count(*) FROM sqlite_master WHERE type = 'trigger'
+AND name IN ('route_paths_gen_insert', 'route_paths_gen_update', 'route_paths_gen_delete')`
+)
+
+// PathsGeneration returns route_paths' generation: a counter that moves on
+// every row insert, update and delete, by any writer.
+func (r *Registry) PathsGeneration() (int64, error) {
+ if r.remote != nil {
+ out, err := r.remote.call(context.Background(), remoteRequest{Method: "PathsGeneration"}, nil)
+ return out.Number64, err
+ }
+ var gen int64
+ // No caller context: like every other registry read without one.
+ err := r.sql.QueryRowContext(context.Background(), pathsGenSQL).Scan(&gen)
+ return gen, err
+}
+
+// ApplyPaths writes one reconcile pass's route_paths changes, the upserts
+// then the deletes (each a (host, prefix) pair; a row already gone is a
+// success, as with DeletePath), in one BEGIN IMMEDIATE transaction: a
+// 10,000-row first derivation is one commit, not 10,000. All or nothing: a
+// failure leaves the table as it was.
+//
+// before and after are the generation inside the transaction, before the
+// first write and after the last. A caller that read the generation itself
+// before deciding these writes knows, when its reading equals before, that
+// no other writer moved the table in between, and that after names exactly
+// the table it decided.
+func (r *Registry) ApplyPaths(upserts []RoutePath, deletes [][2]string) (before, after int64, err error) {
+ if r.remote != nil {
+ out, err := r.remote.call(context.Background(), remoteRequest{Method: "ApplyPaths", PathUpserts: upserts, PathDeletes: deletes}, nil)
+ return out.PathGens[0], out.PathGens[1], err
+ }
+ ctx := context.Background() // no caller context: as PathsGeneration
+ tx, err := r.beginClaimTransaction(ctx, false)
+ if err != nil {
+ return 0, 0, err
+ }
+ defer tx.Rollback()
+ if err := tx.QueryRowContext(ctx, pathsGenSQL).Scan(&before); err != nil {
+ return 0, 0, err
+ }
+ // Many rows per statement: each statement costs a prepare and, because
+ // the generation triggers fire inside it, a statement journal of every
+ // page it touches, so one statement per row made a 100,000-row first
+ // derivation take seconds even in one transaction.
+ for chunk := range slices.Chunk(upserts, applyPathsChunk) {
+ args := make([]any, 0, 5*len(chunk))
+ for _, p := range chunk {
+ args = append(args, p.Host, p.Prefix, p.Target, p.Account, p.App)
+ }
+ q := `INSERT INTO route_paths (host, prefix, target, account, app) VALUES ` + groupPlaceholders("(?, ?, ?, ?, ?)", len(chunk)) + `
+ON CONFLICT(host, prefix) DO UPDATE SET
+ target=excluded.target, account=excluded.account, app=excluded.app`
+ if _, err := tx.ExecContext(ctx, q, args...); err != nil {
+ return 0, 0, fmt.Errorf("upsert %d path rows from %s/%s: %w", len(chunk), chunk[0].Host, chunk[0].Prefix, err)
+ }
+ }
+ for chunk := range slices.Chunk(deletes, applyPathsChunk) {
+ args := make([]any, 0, 2*len(chunk))
+ for _, d := range chunk {
+ args = append(args, d[0], d[1])
+ }
+ q := `DELETE FROM route_paths WHERE (host, prefix) IN (VALUES ` + groupPlaceholders("(?, ?)", len(chunk)) + `)`
+ if _, err := tx.ExecContext(ctx, q, args...); err != nil {
+ return 0, 0, fmt.Errorf("remove %d path rows from %s/%s: %w", len(chunk), chunk[0][0], chunk[0][1], err)
+ }
+ }
+ if err := tx.QueryRowContext(ctx, pathsGenSQL).Scan(&after); err != nil {
+ return 0, 0, err
+ }
+ return before, after, tx.Commit()
+}
+
+// dispatchRemotePaths serves route_paths' remote methods for dispatchRemote.
+func (r *Registry) dispatchRemotePaths(q remoteRequest, out *remoteResponse) (err error) {
+ switch q.Method {
+ case "ListPaths":
+ out.Paths, err = r.ListPaths()
+ case "UpsertPath":
+ err = r.UpsertPath(q.P)
+ case "DeletePath":
+ err = r.DeletePath(q.Host, q.Prefix)
+ case "ApplyPaths":
+ out.PathGens[0], out.PathGens[1], err = r.ApplyPaths(q.PathUpserts, q.PathDeletes)
+ case "PathsGeneration":
+ out.Number64, err = r.PathsGeneration()
+ default:
+ err = errRemoteMethod
+ }
+ return err
+}
+
+// applyPathsChunk is how many rows one ApplyPaths statement writes: 2,500
+// bound parameters for an upsert, well under SQLite's limit of 32,766.
+const applyPathsChunk = 500
+
+// groupPlaceholders is n copies of group, comma-separated.
+func groupPlaceholders(group string, n int) string {
+ return strings.TrimSuffix(strings.Repeat(group+", ", n), ", ")
+}
+
+// hashRoutePaths writes Fingerprint's route_paths section to h.
+//
+// With the generation triggers in place it hashes the generation and the row
+// count (a belt), not the rows: every row change moves the generation, so the
+// digest moves with it. A registry with no rows and a generation of 0 adds
+// nothing after the marker, so it digests exactly as an empty table always
+// has (the pinned digests in ratelimit_fingerprint_test.go).
+//
+// Without them (a read-only reader on a registry no read-write open has
+// migrated yet, or a counter row someone deleted) it hashes every row, as
+// before the counter existed: slower, never blind.
+func hashRoutePaths(ctx context.Context, db *sql.DB, h io.Writer) error {
+ fmt.Fprint(h, "\x1droute_paths\x1e")
+ var triggers int
+ if err := db.QueryRowContext(ctx, pathsTriggerSQL).Scan(&triggers); err != nil {
+ return err
+ }
+ if triggers == 3 {
+ var gen sql.NullInt64
+ var n int64
+ if err := db.QueryRowContext(ctx, `SELECT (`+pathsGenSQL+`), (SELECT count(*) FROM route_paths)`).Scan(&gen, &n); err != nil {
+ return err
+ }
+ if gen.Valid {
+ if gen.Int64 != 0 || n != 0 {
+ fmt.Fprintf(h, "gen=%d\x1fcount=%d\x1e", gen.Int64, n)
+ }
+ return nil
+ }
+ }
+ rows, err := db.QueryContext(ctx, `SELECT host, prefix, target, account, app
+FROM route_paths ORDER BY host, prefix`)
+ if err != nil {
+ return err
+ }
+ defer rows.Close()
+ for rows.Next() {
+ var host, prefix, target, account, app string
+ if err := rows.Scan(&host, &prefix, &target, &account, &app); err != nil {
+ return err
+ }
+ fmt.Fprintf(h, "%s\x1f%s\x1f%s\x1f%s\x1f%s\x1e", host, prefix, target, account, app)
+ }
+ return rows.Err()
+}
diff --git a/internal/registry/pathsgen_test.go b/internal/registry/pathsgen_test.go
new file mode 100644
index 000000000..3db67838b
--- /dev/null
+++ b/internal/registry/pathsgen_test.go
@@ -0,0 +1,241 @@
+package registry
+
+import (
+ "context"
+ "fmt"
+ "testing"
+)
+
+func mustFingerprint(t *testing.T, reg *Registry) string {
+ t.Helper()
+ fp, err := reg.Fingerprint()
+ if err != nil {
+ t.Fatal(err)
+ }
+ return fp
+}
+
+func mustExec(t *testing.T, reg *Registry, q string, args ...any) {
+ t.Helper()
+ if _, err := reg.sql.ExecContext(context.Background(), q, args...); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func seedPaths(t *testing.T, reg *Registry) {
+ t.Helper()
+ for _, p := range []RoutePath{
+ {Host: "shop.example.com", Prefix: "a", Target: "one.example.com", Account: "shop", App: "front"},
+ {Host: "shop.example.com", Prefix: "b", Target: "one.example.com", Account: "shop", App: "front"},
+ } {
+ if err := reg.UpsertPath(p); err != nil {
+ t.Fatal(err)
+ }
+ }
+}
+
+// TestFingerprintSeesAPathUpdateByAnyWriter: Fingerprint no longer reads the
+// rows, so it must see an UPDATE that no registry method made, with the row
+// count unchanged. The trigger in the database file is what makes it.
+func TestFingerprintSeesAPathUpdateByAnyWriter(t *testing.T) {
+ reg := openTestRegistry(t)
+ seedPaths(t, reg)
+ for _, col := range []string{"target", "account", "app"} {
+ before := mustFingerprint(t, reg)
+ mustExec(t, reg, `UPDATE route_paths SET `+col+` = 'changed-'||`+col+` WHERE prefix = 'a'`)
+ if after := mustFingerprint(t, reg); after == before {
+ t.Fatalf("fingerprint unchanged across a raw UPDATE of %s", col)
+ }
+ }
+}
+
+// TestFingerprintSeesAPathDeleteByAnyWriter: a raw DELETE moves it, and so
+// does a delete and re-insert that leaves the row count where it was (the
+// count is a belt; the generation is what has to move).
+func TestFingerprintSeesAPathDeleteByAnyWriter(t *testing.T) {
+ reg := openTestRegistry(t)
+ seedPaths(t, reg)
+ before := mustFingerprint(t, reg)
+ mustExec(t, reg, `DELETE FROM route_paths WHERE prefix = 'a'`)
+ mid := mustFingerprint(t, reg)
+ if mid == before {
+ t.Fatal("fingerprint unchanged across a raw DELETE")
+ }
+ mustExec(t, reg, `INSERT INTO route_paths (host, prefix, target, account, app) VALUES ('shop.example.com', 'c', 'two.example.com', 'shop', 'front')`)
+ if after := mustFingerprint(t, reg); after == before || after == mid {
+ t.Fatal("fingerprint repeated an earlier digest after a delete and insert that kept the row count")
+ }
+}
+
+// TestFingerprintEmptyPathsUnchanged: a registry with no path rows and a
+// generation of 0 digests as an empty table always has. The pinned digests
+// in ratelimit_fingerprint_test.go hold the exact bytes; this one holds the
+// rule that a section with nothing in it adds nothing.
+func TestFingerprintEmptyPathsUnchanged(t *testing.T) {
+ reg := openTestRegistry(t)
+ withCounter := mustFingerprint(t, reg)
+ mustExec(t, reg, `DROP TRIGGER route_paths_gen_insert`)
+ if legacy := mustFingerprint(t, reg); legacy != withCounter {
+ t.Fatalf("empty route_paths digests differently with and without the counter: %q vs %q", withCounter, legacy)
+ }
+}
+
+// TestFingerprintWithoutTriggersHashesRows: a registry whose triggers are
+// missing (a read-only reader ahead of the migration) falls back to hashing
+// the rows, so a change is still seen.
+func TestFingerprintWithoutTriggersHashesRows(t *testing.T) {
+ reg := openTestRegistry(t)
+ seedPaths(t, reg)
+ for _, name := range []string{"route_paths_gen_insert", "route_paths_gen_update", "route_paths_gen_delete"} {
+ mustExec(t, reg, `DROP TRIGGER `+name)
+ }
+ before := mustFingerprint(t, reg)
+ mustExec(t, reg, `UPDATE route_paths SET target = 'two.example.com' WHERE prefix = 'a'`)
+ if after := mustFingerprint(t, reg); after == before {
+ t.Fatal("fingerprint unchanged across an UPDATE with the triggers missing")
+ }
+}
+
+// TestPathsGenerationMovesOnEveryWrite: each insert, update and delete moves
+// the generation; reads do not.
+func TestPathsGenerationMovesOnEveryWrite(t *testing.T) {
+ reg := openTestRegistry(t)
+ gen := func() int64 {
+ t.Helper()
+ g, err := reg.PathsGeneration()
+ if err != nil {
+ t.Fatal(err)
+ }
+ return g
+ }
+ g0 := gen()
+ p := RoutePath{Host: "shop.example.com", Prefix: "a", Target: "one.example.com", Account: "shop", App: "front"}
+ if err := reg.UpsertPath(p); err != nil {
+ t.Fatal(err)
+ }
+ g1 := gen()
+ p.Target = "two.example.com"
+ if err := reg.UpsertPath(p); err != nil {
+ t.Fatal(err)
+ }
+ g2 := gen()
+ if _, err := reg.ListPaths(); err != nil {
+ t.Fatal(err)
+ }
+ if gen() != g2 {
+ t.Fatal("a read moved the generation")
+ }
+ if err := reg.DeletePath(p.Host, p.Prefix); err != nil {
+ t.Fatal(err)
+ }
+ g3 := gen()
+ if !(g0 < g1 && g1 < g2 && g2 < g3) {
+ t.Fatalf("generations %d, %d, %d, %d: want strictly increasing across insert, update, delete", g0, g1, g2, g3)
+ }
+}
+
+// TestApplyPathsIsOneTransaction: the writes land together, and before and
+// after are the generation either side of them.
+func TestApplyPathsIsOneTransaction(t *testing.T) {
+ for _, remote := range []bool{false, true} {
+ name := "local"
+ if remote {
+ name = "remote"
+ }
+ t.Run(name, func(t *testing.T) {
+ var reg *Registry
+ if remote {
+ reg, _ = remoteTestRegistry(t)
+ } else {
+ reg = openTestRegistry(t)
+ }
+ seedPaths(t, reg)
+ g0, err := reg.PathsGeneration()
+ if err != nil {
+ t.Fatal(err)
+ }
+ before, after, err := reg.ApplyPaths(
+ []RoutePath{
+ {Host: "shop.example.com", Prefix: "a", Target: "two.example.com", Account: "shop", App: "front"},
+ {Host: "shop.example.com", Prefix: "c", Target: "two.example.com", Account: "shop", App: "front"},
+ },
+ [][2]string{{"shop.example.com", "b"}, {"shop.example.com", "gone"}},
+ )
+ if err != nil {
+ t.Fatal(err)
+ }
+ if before != g0 || after != g0+3 {
+ t.Fatalf("ApplyPaths generations %d -> %d, want %d -> %d (two upserts, one row deleted)", before, after, g0, g0+3)
+ }
+ if g, _ := reg.PathsGeneration(); g != after {
+ t.Fatalf("generation after commit %d, ApplyPaths said %d", g, after)
+ }
+ rows, err := reg.ListPaths()
+ if err != nil {
+ t.Fatal(err)
+ }
+ got := map[string]string{}
+ for _, p := range rows {
+ got[p.Prefix] = p.Target
+ }
+ if len(got) != 2 || got["a"] != "two.example.com" || got["c"] != "two.example.com" {
+ t.Fatalf("route_paths after ApplyPaths = %v, want a and c -> two.example.com, b gone", got)
+ }
+ })
+ }
+}
+
+// TestApplyPathsAllOrNothing: a failing write leaves the table and its
+// generation as they were.
+func TestApplyPathsAllOrNothing(t *testing.T) {
+ reg := openTestRegistry(t)
+ seedPaths(t, reg)
+ g0, _ := reg.PathsGeneration()
+ fp0 := mustFingerprint(t, reg)
+ // A trigger that refuses one row, standing in for any failed write.
+ mustExec(t, reg, `CREATE TRIGGER refuse_bad BEFORE INSERT ON route_paths WHEN NEW.prefix = 'bad'
+BEGIN SELECT RAISE(ABORT, 'refused'); END`)
+ _, _, err := reg.ApplyPaths([]RoutePath{
+ {Host: "shop.example.com", Prefix: "a", Target: "two.example.com", Account: "shop", App: "front"},
+ {Host: "shop.example.com", Prefix: "bad", Target: "two.example.com", Account: "shop", App: "front"},
+ }, [][2]string{{"shop.example.com", "b"}})
+ if err == nil {
+ t.Fatal("ApplyPaths succeeded over a refused row")
+ }
+ if g, _ := reg.PathsGeneration(); g != g0 {
+ t.Fatalf("generation moved from %d to %d on a failed ApplyPaths", g0, g)
+ }
+ if fp := mustFingerprint(t, reg); fp != fp0 {
+ t.Fatal("fingerprint moved on a failed ApplyPaths")
+ }
+}
+
+// TestApplyPathsAcrossChunks: more rows than one statement writes, both
+// ways, land whole, and the generation counts every row.
+func TestApplyPathsAcrossChunks(t *testing.T) {
+ reg := openTestRegistry(t)
+ n := 2*applyPathsChunk + 1
+ var ups []RoutePath
+ var dels [][2]string
+ for i := range n {
+ prefix := fmt.Sprintf("p%05d", i)
+ ups = append(ups, RoutePath{Host: "shop.example.com", Prefix: prefix, Target: "one.example.com", Account: "shop", App: "front"})
+ dels = append(dels, [2]string{"shop.example.com", prefix})
+ }
+ before, after, err := reg.ApplyPaths(ups, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if rows, _ := reg.ListPaths(); len(rows) != n || after-before != int64(n) {
+ t.Fatalf("after upserting %d rows: %d rows, generation moved %d", n, len(rows), after-before)
+ }
+ keep := dels[n-1]
+ before, after, err = reg.ApplyPaths(nil, dels[:n-1])
+ if err != nil {
+ t.Fatal(err)
+ }
+ rows, _ := reg.ListPaths()
+ if len(rows) != 1 || rows[0].Prefix != keep[1] || after-before != int64(n-1) {
+ t.Fatalf("after deleting %d rows: %v, generation moved %d", n-1, rows, after-before)
+ }
+}
diff --git a/internal/registry/registry.go b/internal/registry/registry.go
index 16856e5dd..6efdfd30f 100644
--- a/internal/registry/registry.go
+++ b/internal/registry/registry.go
@@ -894,6 +894,11 @@ CREATE TABLE IF NOT EXISTS route_paths (
);`); err != nil {
return err
}
+ // Its generation counter and triggers (pathsgen.go), with the table.
+ // No caller context: migrate runs inside Open, which takes none.
+ if _, err := r.sql.ExecContext(context.Background(), routePathsGenSchema); err != nil {
+ return err
+ }
if _, err := r.sql.Exec(`CREATE TABLE IF NOT EXISTS timers (
host TEXT NOT NULL,
name TEXT NOT NULL,
@@ -3940,12 +3945,7 @@ func (r *Registry) UpsertPath(p RoutePath) error {
return err
}
- _, err := r.sql.Exec(`
-INSERT INTO route_paths (host, prefix, target, account, app)
-VALUES (?, ?, ?, ?, ?)
-ON CONFLICT(host, prefix) DO UPDATE SET
- target=excluded.target, account=excluded.account, app=excluded.app`,
- p.Host, p.Prefix, p.Target, p.Account, p.App)
+ _, err := r.sql.Exec(upsertPathSQL, p.Host, p.Prefix, p.Target, p.Account, p.App)
return err
}
@@ -3958,7 +3958,7 @@ func (r *Registry) DeletePath(host, prefix string) error {
return err
}
- _, err := r.sql.Exec(`DELETE FROM route_paths WHERE host = ? AND prefix = ?`, host, prefix)
+ _, err := r.sql.Exec(deletePathSQL, host, prefix)
return err
}
@@ -4307,25 +4307,12 @@ FROM fleet_boxes ORDER BY fleet, label`)
// route_paths: which prefix on which hostname reaches which route is a
// routing decision in exactly the sense route_aliases' alias/host is, so
- // it hashes here or a flip never reaches the live map. All five columns
- // hash — unlike route_aliases there is no box-stamped, cadence-driven
- // column on this table to exclude, so there is nothing here that could
- // force a pointless fleet-wide reload.
- fmt.Fprint(h, "\x1droute_paths\x1e")
- prows, err := db.Query(`SELECT host, prefix, target, account, app
-FROM route_paths ORDER BY host, prefix`)
- if err != nil {
- return "", err
- }
- defer prows.Close()
- for prows.Next() {
- var host, prefix, target, account, app string
- if err := prows.Scan(&host, &prefix, &target, &account, &app); err != nil {
- return "", err
- }
- fmt.Fprintf(h, "%s\x1f%s\x1f%s\x1f%s\x1f%s\x1e", host, prefix, target, account, app)
- }
- if err := prows.Err(); err != nil {
+ // it hashes here or a flip never reaches the live map. The section is
+ // hashRoutePaths (pathsgen.go): the table's generation, which every row
+ // insert, update and delete moves, and its row count, not the rows
+ // themselves, so a 100,000-row table costs this poll two small reads
+ // (spec §6).
+ if err := hashRoutePaths(context.Background(), db, h); err != nil {
return "", err
}
diff --git a/internal/registry/remote_dispatch.go b/internal/registry/remote_dispatch.go
index 568e9ceaa..a45cc1559 100644
--- a/internal/registry/remote_dispatch.go
+++ b/internal/registry/remote_dispatch.go
@@ -100,6 +100,8 @@ type remoteRequest struct {
RDs []RegionalDomain
Names map[string]string // SetAccountNamespaces
P RoutePath
+ PathUpserts []RoutePath // ApplyPaths
+ PathDeletes [][2]string // ApplyPaths
Prefix string
Path string
Rows []Timer
@@ -161,6 +163,7 @@ type remoteResponse struct {
Wildcards []WildcardDomain
Regional []RegionalDomain
Paths []RoutePath
+ PathGens [2]int64 // ApplyPaths: the generation before and after
Timers []Timer
Number int
Times map[string]int64
@@ -488,12 +491,8 @@ func (r *Registry) dispatchRemote(ctx context.Context, q remoteRequest, callback
out.StringMap, err = r.ListAccountNamespaces()
case "SetAccountNamespaces":
err = r.SetAccountNamespaces(q.Names)
- case "ListPaths":
- out.Paths, err = r.ListPaths()
- case "UpsertPath":
- err = r.UpsertPath(q.P)
- case "DeletePath":
- err = r.DeletePath(q.Host, q.Prefix)
+ case "ListPaths", "UpsertPath", "DeletePath", "ApplyPaths", "PathsGeneration":
+ err = r.dispatchRemotePaths(q, &out)
case "Fingerprint":
out.Text, err = r.Fingerprint()
case "SnapshotFingerprint":