carlos / platform Public

console store: people and accounts pages count each relationship on its own page; neutral fixture addresses

The people and accounts lists joined memberships to apps before
COUNT(DISTINCT), so one person in many accounts with many apps made
memberships x apps rows. Each list now materializes its page and
counts memberships and apps separately for it, with CROSS JOIN fixing
page as the outer loop (a plain JOIN walks the whole table, and the plan
witness now refuses it). A concentrated-ownership test checks counts
and time. Fixture addresses move to example.org/.net. The OperatorCounts
budget cites the controller ruling of 2026-10-26.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 347d2028ec3c13a7c6675842fa9be82f06f83197 parent 144057e
2 files changed, +203 −49
  • internal/console/opstore.go +62 −35
  • internal/console/opstore_test.go +141 −14
diff --git a/internal/console/opstore.go b/internal/console/opstore.go
index a3370739a..2ee7b60fa 100644
--- a/internal/console/opstore.go
+++ b/internal/console/opstore.go
@@ -75,46 +75,60 @@ WHERE created_at >= ?1 AND +action IN (?2, ?3)`
opSQLPerDay = `SELECT (created_at - ?1) / 86400, COUNT(*) FROM users
WHERE created_at >= ?1 AND created_at < ?2 GROUP BY 1`
- // The people lists. The page is cut in the inner query over users, in
- // users_by_created order; the outer query looks up only that page's
- // rows: their live memberships (memberships_by_address, then accounts by
- // id) and their live apps (apps_by_creator). The two lookups multiply
- // within one person, which COUNT(DISTINCT) undoes. The first account is
- // the bare column beside the one MIN(): the live membership with the
- // earliest (added_at, account_id).
- opSQLPersonColumns = `SELECT u.address, u.created_at, u.last_seen,
- COUNT(DISTINCT accounts.id),
- MIN(CASE WHEN accounts.id IS NOT NULL THEN printf('%020d %020d', memberships.added_at, memberships.account_id) END),
- accounts.name,
- COUNT(DISTINCT apps.rowid)
-FROM `
- opSQLPersonJoins = ` u
-LEFT JOIN memberships ON memberships.address = u.address
-LEFT JOIN accounts ON accounts.id = memberships.account_id AND accounts.deleted_at = 0
-LEFT JOIN apps ON apps.created_by = u.address AND apps.deleted_at = 0
-GROUP BY u.created_at, u.address
-ORDER BY u.created_at DESC, u.address`
- opSQLNewestPeople = opSQLPersonColumns + `(SELECT address, created_at, last_seen FROM users
-ORDER BY created_at DESC, address LIMIT ?1)` + opSQLPersonJoins
- opSQLPeoplePage = opSQLPersonColumns + `(SELECT address, created_at, last_seen FROM users
+ // The people lists. The page is cut first, in users_by_created order,
+ // and materialized; each relationship is then counted on its own for
+ // the page's people only, so memberships and apps never multiply:
+ // held is their live memberships (memberships_by_address, then accounts
+ // by id), made their live apps (apps_by_creator). The first account is
+ // the bare column beside held's one MIN(): the live membership with the
+ // earliest (added_at, account_id). The page is put back in order in Go
+ // (scanPeople), which keeps a sort of the page out of the SQL. CROSS
+ // JOIN is SQLite's way of fixing the loop order: page outside, so each
+ // lookup is an index search per page row, never a walk of the whole
+ // table in GROUP BY order with page as an automatic index.
+ opSQLPersonPage = `WITH page AS MATERIALIZED (`
+ opSQLPersonLookups = `),
+held AS (SELECT memberships.address AS address, COUNT(*) AS n,
+ MIN(printf('%020d %020d', memberships.added_at, memberships.account_id)) AS k, accounts.name AS first
+ FROM page CROSS JOIN memberships ON memberships.address = page.address
+ CROSS JOIN accounts ON accounts.id = memberships.account_id AND accounts.deleted_at = 0
+ GROUP BY memberships.address),
+made AS (SELECT apps.created_by AS address, COUNT(*) AS n
+ FROM page CROSS JOIN apps ON apps.created_by = page.address AND apps.deleted_at = 0
+ GROUP BY apps.created_by)
+SELECT page.address, page.created_at, page.last_seen, COALESCE(held.n, 0), held.k, held.first, COALESCE(made.n, 0)
+FROM page
+LEFT JOIN held ON held.address = page.address
+LEFT JOIN made ON made.address = page.address`
+ opSQLNewestPeople = opSQLPersonPage + `SELECT address, created_at, last_seen FROM users
+ORDER BY created_at DESC, address LIMIT ?1` + opSQLPersonLookups
+ opSQLPeoplePage = opSQLPersonPage + `SELECT address, created_at, last_seen FROM users
WHERE ?1 = '' OR address LIKE ?2 ESCAPE '\'
-ORDER BY created_at DESC, address LIMIT ?3 OFFSET ?4)` + opSQLPersonJoins
+ORDER BY created_at DESC, address LIMIT ?3 OFFSET ?4` + opSQLPersonLookups
// The accounts list: live accounts, newest first. An account id is
// minted as the highest seen plus one (domains.NextAccountID), so id
- // order is creation order and needs no sort.
+ // order is creation order and needs no sort. As for people, the page is
+ // cut first and each relationship counted on its own: live (apps) and
+ // crew (members), so the two never multiply. AccountsPage puts the page
+ // back in id order in Go.
opSQLAccountsTotal = `SELECT COUNT(*) FROM accounts
WHERE deleted_at = 0 AND (?1 = '' OR name LIKE ?2 ESCAPE '\' OR sqid LIKE ?2 ESCAPE '\')`
- opSQLAccountsPage = `SELECT acc.id, acc.sqid, acc.name, acc.created_at, COALESCE(account_plans.plan, ''),
- COUNT(DISTINCT apps.rowid), COUNT(DISTINCT memberships.address)
-FROM (SELECT id, sqid, name, created_at FROM accounts
+ opSQLAccountsPage = `WITH page AS MATERIALIZED (SELECT id, sqid, name, created_at FROM accounts
WHERE deleted_at = 0 AND (?1 = '' OR name LIKE ?2 ESCAPE '\' OR sqid LIKE ?2 ESCAPE '\')
- ORDER BY id DESC LIMIT ?3 OFFSET ?4) acc
-LEFT JOIN account_plans ON account_plans.account_id = acc.id
-LEFT JOIN apps ON apps.account_id = acc.id AND apps.deleted_at = 0
-LEFT JOIN memberships ON memberships.account_id = acc.id
-GROUP BY acc.id
-ORDER BY acc.id DESC`
+ ORDER BY id DESC LIMIT ?3 OFFSET ?4),
+live AS (SELECT apps.account_id AS id, COUNT(*) AS n
+ FROM page CROSS JOIN apps ON apps.account_id = page.id AND apps.deleted_at = 0
+ GROUP BY apps.account_id),
+crew AS (SELECT memberships.account_id AS id, COUNT(*) AS n
+ FROM page CROSS JOIN memberships ON memberships.account_id = page.id
+ GROUP BY memberships.account_id)
+SELECT page.id, page.sqid, page.name, page.created_at, COALESCE(account_plans.plan, ''),
+ COALESCE(live.n, 0), COALESCE(crew.n, 0)
+FROM page
+LEFT JOIN account_plans ON account_plans.account_id = page.id
+LEFT JOIN live ON live.id = page.id
+LEFT JOIN crew ON crew.id = page.id`
opSQLAccountBySqid = `SELECT id, sqid, name, deleted_at FROM accounts WHERE sqid = ?1`
opSQLTouchLastSeen = `UPDATE users SET last_seen = ?1 WHERE address = ?2 AND last_seen < ?3`
@@ -294,7 +308,16 @@ func scanPeople(rows *sql.Rows) ([]PersonRow, error) {
}
out = append(out, p)
}
- return out, rows.Err()
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ sort.Slice(out, func(i, j int) bool {
+ if !out[i].Joined.Equal(out[j].Joined) {
+ return out[i].Joined.After(out[j].Joined)
+ }
+ return out[i].Address < out[j].Address
+ })
+ return out, nil
}
// NewestPeople is the limit most recently joined people, newest first, ties
@@ -383,7 +406,11 @@ func (s *Store) AccountsPage(q string, offset, limit int) ([]AccountRow, int, er
a.Created = time.Unix(created, 0).UTC()
out = append(out, a)
}
- return out, total, rows.Err()
+ if err := rows.Err(); err != nil {
+ return nil, 0, err
+ }
+ sort.Slice(out, func(i, j int) bool { return out[i].ID > out[j].ID })
+ return out, total, nil
}
// ActivityFilter narrows the activity feed. AccountID 0 is every account;
diff --git a/internal/console/opstore_test.go b/internal/console/opstore_test.go
index 899a1b1f9..a3d8ed537 100644
--- a/internal/console/opstore_test.go
+++ b/internal/console/opstore_test.go
@@ -140,18 +140,18 @@ var opQueryPlans = []opPlanCase{
"SEARCH memberships USING INDEX memberships_by_address (address=?)",
"SEARCH accounts USING INTEGER PRIMARY KEY (rowid=?)",
"SEARCH apps USING INDEX apps_by_creator (created_by=?)"},
- notWant: []string{"SCAN memberships", "SCAN apps", "SCAN accounts"}},
+ notWant: []string{"SCAN memberships", "SCAN apps", "SCAN accounts", "SEARCH page USING AUTOMATIC"}},
{name: "people page", tieSort: true, sql: opSQLPeoplePage, args: []any{"", "%%", 50, 0},
want: []string{"SCAN users USING INDEX users_by_created",
"SEARCH memberships USING INDEX memberships_by_address (address=?)",
"SEARCH accounts USING INTEGER PRIMARY KEY (rowid=?)",
"SEARCH apps USING INDEX apps_by_creator (created_by=?)"},
- notWant: []string{"SCAN memberships", "SCAN apps", "SCAN accounts"}},
+ notWant: []string{"SCAN memberships", "SCAN apps", "SCAN accounts", "SEARCH page USING AUTOMATIC"}},
{name: "people page searched", tieSort: true, sql: opSQLPeoplePage, args: []any{"exam", `%exam%`, 50, 0},
want: []string{"SCAN users",
"SEARCH memberships USING INDEX memberships_by_address (address=?)",
"SEARCH apps USING INDEX apps_by_creator (created_by=?)"},
- notWant: []string{"SCAN memberships", "SCAN apps"}},
+ notWant: []string{"SCAN memberships", "SCAN apps", "SEARCH page USING AUTOMATIC"}},
{name: "accounts total", sql: opSQLAccountsTotal, args: []any{"", "%%"},
want: []string{"SCAN accounts"}},
{name: "accounts page", sql: opSQLAccountsPage, args: []any{"", "%%", 50, 0},
@@ -159,7 +159,7 @@ var opQueryPlans = []opPlanCase{
"SEARCH account_plans USING INTEGER PRIMARY KEY (rowid=?)",
"SEARCH apps USING INDEX sqlite_autoindex_apps_1 (account_id=?)",
"SEARCH memberships USING COVERING INDEX sqlite_autoindex_memberships_1 (account_id=?)"},
- notWant: []string{"SCAN apps", "SCAN memberships", "SCAN account_plans"}},
+ notWant: []string{"SCAN apps", "SCAN memberships", "SCAN account_plans", "SEARCH page USING AUTOMATIC"}},
{name: "account by sqid", sql: opSQLAccountBySqid, args: []any{"abcd"},
want: []string{"SEARCH accounts USING INDEX sqlite_autoindex_accounts_1 (sqid=?)"}},
{name: "touch last seen", sql: opSQLTouchLastSeen, args: []any{int64(2), "ann@example.com", int64(2)},
@@ -202,7 +202,7 @@ var opSQLByName = map[string]string{
"opSQLFeedAll": opSQLFeedAll, "opSQLFeedBefore": opSQLFeedBefore, "opSQLFeedAccount": opSQLFeedAccount,
"opSQLFeedAccountActions": opSQLFeedAccountActions, "opSQLFeedAccountOther": opSQLFeedAccountOther,
"opSQLFeedAction": opSQLFeedAction, "opSQLFeedOther": opSQLFeedOther, "opSQLFeedOtherBefore": opSQLFeedOtherBefore,
- "opSQLPersonColumns": "", "opSQLPersonJoins": "", "opSQLFeedColumns": "",
+ "opSQLPersonPage": "", "opSQLPersonLookups": "", "opSQLFeedColumns": "",
}
// opPlan is the EXPLAIN QUERY PLAN detail lines of one statement.
@@ -312,6 +312,13 @@ WHERE last_seen >= ?1 OR EXISTS (SELECT 1 FROM sessions WHERE sessions.address =
if _, problems, err := opPlanProblems(s.db, exists); err != nil || !opHas(problems, "has CORRELATED") {
t.Errorf("the EXISTS form was not refused: %v %v", problems, err)
}
+ // With a plain JOIN in place of CROSS JOIN, the people lists' lookups
+ // walk all of memberships and apps with the page as an automatic index.
+ plain := opPlanCase{name: "newest people, plain JOIN", sql: strings.ReplaceAll(opSQLNewestPeople, "CROSS JOIN", "JOIN"),
+ args: []any{50}, tieSort: true, notWant: []string{"SCAN memberships", "SCAN apps"}}
+ if _, problems, err := opPlanProblems(s.db, plain); err != nil || !opHas(problems, "has SCAN memberships") {
+ t.Errorf("the plain JOIN form was not refused: %v %v", problems, err)
+ }
// Without sessions_by_time, the active count's sessions half scans.
_, err = s.db.Exec(`DROP INDEX sessions_by_time`)
opMust(t, err)
@@ -424,18 +431,18 @@ func TestNewPeoplePerDayFillsZeroDaysAndIgnoresFuture(t *testing.T) {
func TestNewestPeopleAndPeoplePage(t *testing.T) {
s := openOpStore(t)
- for i, a := range []string{"ann@example.com", "bob@keymail.dev", "cy@keymail.dev", "di@keymail.dev", "ed@keymail.dev"} {
+ for i, a := range []string{"ann@example.com", "bob@example.org", "cy@example.net", "di@example.org", "ed@example.net"} {
opUser(t, s, a, opNow.Add(time.Duration(i-10)*time.Hour))
}
acct := testAccountID()
- opMust(t, s.CreateAccount(acct, "aaaa", "shop", "ed@keymail.dev", opNow.Add(-time.Hour)))
- if _, err := s.CreateAppIn(acct, "shop", "ed@keymail.dev", opNow); err != nil {
+ opMust(t, s.CreateAccount(acct, "aaaa", "shop", "ed@example.net", opNow.Add(-time.Hour)))
+ if _, err := s.CreateAppIn(acct, "shop", "ed@example.net", opNow); err != nil {
t.Fatal(err)
}
- opMust(t, s.TouchLastSeen("ed@keymail.dev", opNow))
+ opMust(t, s.TouchLastSeen("ed@example.net", opNow))
newest, err := s.NewestPeople(2)
opMust(t, err)
- if len(newest) != 2 || newest[0].Address != "ed@keymail.dev" || newest[1].Address != "di@keymail.dev" {
+ if len(newest) != 2 || newest[0].Address != "ed@example.net" || newest[1].Address != "di@example.org" {
t.Fatalf("NewestPeople(2) = %+v", newest)
}
ed := newest[0]
@@ -448,7 +455,7 @@ func TestNewestPeopleAndPeoplePage(t *testing.T) {
}
page, total, err := s.PeoplePage("", 0, 2)
opMust(t, err)
- if total != 5 || len(page) != 2 || page[0].Address != "ed@keymail.dev" {
+ if total != 5 || len(page) != 2 || page[0].Address != "ed@example.net" {
t.Fatalf("PeoplePage = %+v, %d", page, total)
}
page, total, err = s.PeoplePage("", 4, 2)
@@ -456,10 +463,10 @@ func TestNewestPeopleAndPeoplePage(t *testing.T) {
if total != 5 || len(page) != 1 || page[0].Address != "ann@example.com" {
t.Fatalf("PeoplePage offset 4 = %+v, %d", page, total)
}
- page, total, err = s.PeoplePage("exam", 0, 50)
+ page, total, err = s.PeoplePage("n@exam", 0, 50)
opMust(t, err)
if total != 1 || len(page) != 1 || page[0].Address != "ann@example.com" {
- t.Fatalf("PeoplePage(exam) = %+v, %d", page, total)
+ t.Fatalf("PeoplePage(n@exam) = %+v, %d", page, total)
}
}
@@ -754,7 +761,9 @@ func opSeedScale(t *testing.T, s *Store, now time.Time) (account int64) {
// counts deduplicate every address signed in during the window: 60,000
// sessions for the 30-day count, which this SQLite does as a MERGE of two
// sorted halves in about 40 ms on its own (reading the same 60,000 index
-// entries without the dedup takes 2 ms). The other reads keep 20 ms.
+// entries without the dedup takes 2 ms). Allowed by controller ruling
+// 2026-10-26: an operator-only page, still inside the 150 ms screen budget.
+// The other reads keep 20 ms.
const opCountsScaleBudget = 100 * time.Millisecond
// TestOperatorCountsAtScale times every operator read on a production-sized
@@ -858,3 +867,121 @@ func TestFirstAccountIsTheEarliestLiveMembership(t *testing.T) {
t.Fatalf("NewestPeople = %+v, want first account shop, 2 accounts, 2 apps", got)
}
}
+
+// TestPeopleAndAccountsWithConcentratedOwnership: one person in 2,000
+// accounts who created 8,000 apps, and one account holding all those apps
+// and 2,000 members. Each relationship is counted on its own, so neither
+// list multiplies one by the other; under CI each page answers within
+// 20 ms.
+func TestPeopleAndAccountsWithConcentratedOwnership(t *testing.T) {
+ s := openOpStore(t)
+ db, ok := s.db.(*sql.DB)
+ if !ok {
+ t.Fatalf("store handle is %T", s.db)
+ }
+ const big = "owner@example.com"
+ const hub = int64(5000)
+ n := opNow.Unix()
+ tx, err := db.Begin()
+ opMust(t, err)
+ defer tx.Rollback()
+ ins := func(q string, args ...any) {
+ if _, err := tx.Exec(q, args...); err != nil {
+ t.Fatal(err)
+ }
+ }
+ ins(`INSERT INTO users (address, created_at) VALUES (?, ?)`, big, n)
+ for i := 0; i < 2000; i++ {
+ id := hub + int64(i)
+ ins(`INSERT INTO accounts (id, sqid, name, created_at) VALUES (?, ?, ?, ?)`, id, fmt.Sprintf("c%04d", i), fmt.Sprintf("shop %d", i), n)
+ ins(`INSERT INTO memberships (account_id, address, role, added_at) VALUES (?, ?, ?, ?)`, id, big, RoleOwner, n-int64(i))
+ if i > 0 {
+ who := fmt.Sprintf("m%04d@example.org", i)
+ ins(`INSERT INTO users (address, created_at) VALUES (?, ?)`, who, n-int64(i))
+ ins(`INSERT INTO memberships (account_id, address, role, added_at) VALUES (?, ?, ?, ?)`, hub, who, RoleMember, n)
+ }
+ }
+ for i := 0; i < 8000; i++ {
+ if _, err := insertAppRow(tx, newAppRow{AccountID: hub, App: fmt.Sprintf("app%04d", i), CreatedBy: big, CreatedAt: n}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ opMust(t, tx.Commit())
+
+ timed := func(name string, run func() error) {
+ t.Helper()
+ opMust(t, run()) // warm
+ start := time.Now()
+ opMust(t, run())
+ took := time.Since(start)
+ t.Logf("%-12s %8.2f ms", name, float64(took.Microseconds())/1000)
+ if perfEnforce() && took > 20*time.Millisecond {
+ t.Errorf("%s took %v, over 20 ms", name, took)
+ }
+ }
+ var people []PersonRow
+ timed("NewestPeople", func() (err error) { people, err = s.NewestPeople(1); return })
+ if len(people) != 1 || people[0].Address != big || people[0].Accounts != 2000 || people[0].Apps != 8000 ||
+ people[0].FirstAccount != "shop 1999" {
+ t.Fatalf("NewestPeople(1) = %+v", people)
+ }
+ timed("PeoplePage", func() (err error) { people, _, err = s.PeoplePage("owner", 0, 50); return })
+ if len(people) != 1 || people[0].Accounts != 2000 || people[0].Apps != 8000 {
+ t.Fatalf("PeoplePage(owner) = %+v", people)
+ }
+ var accounts []AccountRow
+ timed("AccountsPage", func() (err error) { accounts, _, err = s.AccountsPage("c0000", 0, 50); return })
+ if len(accounts) != 1 || accounts[0].ID != hub || accounts[0].Apps != 8000 || accounts[0].Members != 2000 {
+ t.Fatalf("AccountsPage(c0000) = %+v", accounts)
+ }
+ timed("AccountsPage all", func() (err error) { accounts, _, err = s.AccountsPage("", 1950, 50); return })
+ if len(accounts) != 50 || accounts[49].ID != hub || accounts[49].Apps != 8000 || accounts[49].Members != 2000 ||
+ accounts[0].Members != 1 || accounts[0].Apps != 0 {
+ t.Fatalf("AccountsPage last page = first %+v, last %+v", accounts[0], accounts[len(accounts)-1])
+ }
+}
+
+// TestMigrateOperatorPagesOnAPopulatedStore runs the migration on a store
+// already holding the scale fixture: the column and the eight indexes are
+// taken away, the store is closed, and the next Open puts them back. Both
+// opens are timed and printed (the second is the no-op baseline).
+func TestMigrateOperatorPagesOnAPopulatedStore(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "console.db")
+ s, err := Open(path)
+ opMust(t, err)
+ opSeedScale(t, s, opNow)
+ for _, idx := range []string{"audit_by_time", "audit_by_account", "audit_by_action", "sessions_by_time",
+ "users_by_created", "users_by_last_seen", "memberships_by_address", "apps_by_creator"} {
+ _, err := s.db.Exec(`DROP INDEX ` + idx)
+ opMust(t, err)
+ }
+ _, err = s.db.Exec(`ALTER TABLE users DROP COLUMN last_seen`)
+ opMust(t, err)
+ opMust(t, s.Close())
+
+ start := time.Now()
+ s, err = Open(path)
+ migrated := time.Since(start)
+ opMust(t, err)
+ opMust(t, s.Close())
+ start = time.Now()
+ s, err = Open(path)
+ again := time.Since(start)
+ opMust(t, err)
+ defer s.Close()
+ t.Logf("open with the migration: %v; open again (nothing to do): %v", migrated, again)
+ if perfEnforce() && migrated > 10*time.Second {
+ t.Errorf("the migration took %v on the scale fixture", migrated)
+ }
+ for table, want := range map[string]int{"users": 20000, "sessions": 60000, "audit": 200000, "apps": 8000} {
+ var n int
+ opMust(t, s.db.QueryRow(`SELECT COUNT(*) FROM `+table).Scan(&n))
+ if n != want {
+ t.Errorf("%s has %d rows after the migration, want %d", table, n, want)
+ }
+ }
+ plan, problems, err := opPlanProblems(s.db, opQueryPlans[2])
+ if err != nil || len(problems) > 0 {
+ t.Fatalf("active count after the migration: %v %v\n%s", problems, err, strings.Join(plan, "\n"))
+ }
+}