carlos / platform Public

console store: users.last_seen, audit indexes, and the operator pages' reads

migrateOperatorPages adds users.last_seen (constant default, no row
rewrite) and eight CREATE INDEX IF NOT EXISTS indexes. opstore.go holds
the operator reads, every statement a constant; TestOperatorQueryPlans
holds each to its access pattern and shows the check biting, and
TestOperatorCountsAtScale times them on a 20,000-person store.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 43b591bfee8be47df079f637db798246a96a7440 parent de1bace
4 files changed, +1,329 −1
  • .amadan/test-weights.tsv +2 −0
  • internal/console/opstore.go +494 −0
  • internal/console/opstore_test.go +828 −0
  • internal/console/store.go +5 −1
diff --git a/.amadan/test-weights.tsv b/.amadan/test-weights.tsv
index 47bbbb8ad..bf6f5f876 100644
--- a/.amadan/test-weights.tsv
+++ b/.amadan/test-weights.tsv
@@ -79,6 +79,8 @@ github.com/carlosframework/platform/internal/console TestRetiringAnInstancePurge
github.com/carlosframework/platform/internal/console TestDeclaredLostIsLoggedByTheConsole 7.2
github.com/carlosframework/platform/internal/console TestClaimMailPushCountsOutboundEffects 6.4
github.com/carlosframework/platform/internal/console TestPerfSessionS3Requests 2.4
+github.com/carlosframework/platform/internal/console TestOperatorCountsAtScale 3.4
+github.com/carlosframework/platform/internal/console TestGatedStoreOpensWithTheNewSchema 1.9
github.com/carlosframework/platform/internal/console TestEconomicsPassWritesCensusOnce 5.0
github.com/carlosframework/platform/internal/console TestCallbackPostsToSelectedHost 3.8
github.com/carlosframework/platform/internal/console TestClaimDeleteRetryWhileParkingIsNotDone 3.2
diff --git a/internal/console/opstore.go b/internal/console/opstore.go
new file mode 100644
index 000000000..a3370739a
--- /dev/null
+++ b/internal/console/opstore.go
@@ -0,0 +1,494 @@
+package console
+
+import (
+ "database/sql"
+ "encoding/json"
+ "errors"
+ "math"
+ "sort"
+ "strings"
+ "time"
+)
+
+// The operator pages' reads (/fleet, /fleet/people, /fleet/activity), with
+// their column and indexes, kept here so the feature is one file to read.
+//
+// Every statement below is a package-level constant so that
+// TestOperatorQueryPlans can EXPLAIN QUERY PLAN exactly what runs and hold
+// each to its intended access pattern: no correlated subquery anywhere, no
+// sort of a whole result, and the time-window counts on their indexes.
+
+// migrateOperatorPages adds users.last_seen and the indexes the operator
+// reads use. Safe on a live console.db: the ALTER adds a column with a
+// constant default (SQLite rewrites no rows for it), and every index is
+// CREATE INDEX IF NOT EXISTS, built once and skipped after. A console rolled
+// back to an earlier release opens the database unchanged: it never names
+// the column, and SQLite maintains the indexes for it.
+func (s *Store) migrateOperatorPages() error {
+ // When the person was last seen, Unix seconds; 0 = never since the
+ // column landed. Written at most once an hour per person (TouchLastSeen).
+ if _, err := s.db.Exec(`ALTER TABLE users ADD COLUMN last_seen INTEGER NOT NULL DEFAULT 0;`); err != nil &&
+ !strings.Contains(err.Error(), "duplicate column") {
+ return err
+ }
+ for _, stmt := range []string{
+ `CREATE INDEX IF NOT EXISTS audit_by_time ON audit (created_at);`,
+ `CREATE INDEX IF NOT EXISTS audit_by_account ON audit (account_id, id);`,
+ `CREATE INDEX IF NOT EXISTS sessions_by_time ON sessions (created_at, address);`,
+ `CREATE INDEX IF NOT EXISTS users_by_created ON users (created_at);`,
+ `CREATE INDEX IF NOT EXISTS users_by_last_seen ON users (last_seen);`,
+ `CREATE INDEX IF NOT EXISTS memberships_by_address ON memberships (address, added_at);`,
+ `CREATE INDEX IF NOT EXISTS apps_by_creator ON apps (created_by);`,
+ `CREATE INDEX IF NOT EXISTS audit_by_action ON audit (action, id);`,
+ } {
+ if _, err := s.db.Exec(stmt); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// deployActions are the audit actions a deploy writes (server.go and
+// apicli.go's promote and rollback doors).
+var deployActions = []string{"promote", "rollback"}
+
+const opDay = 24 * 60 * 60
+
+const (
+ opSQLPeopleTotal = `SELECT COUNT(*) FROM users`
+ opSQLPeopleMatching = `SELECT COUNT(*) FROM users WHERE address LIKE ?1 ESCAPE '\'`
+ // Active in a window: seen in it, or signed in during it. Set-based: the
+ // two halves are index range reads, and the UNION (a MERGE on this
+ // SQLite, each half sorted by address) holds only the addresses in the
+ // window. INDEXED BY keeps the users half on its range: left to itself
+ // the planner walks every user in address order for the merge.
+ opSQLActive = `SELECT COUNT(*) FROM (SELECT address FROM users INDEXED BY users_by_last_seen WHERE last_seen >= ?1
+UNION SELECT address FROM sessions WHERE created_at >= ?1)`
+ opSQLNewPeople = `SELECT COUNT(*) FROM users WHERE created_at >= ?1 AND created_at < ?2`
+ opSQLNewAccounts = `SELECT COUNT(*) FROM accounts WHERE created_at >= ?1 AND created_at < ?2`
+ opSQLApps = `SELECT COUNT(*), COALESCE(SUM(created_at >= ?1 AND created_at < ?2), 0) FROM apps WHERE deleted_at = 0`
+ // Deploys since a time. The unary + keeps the action test off
+ // audit_by_action, which would walk every deploy ever made: the day's
+ // rows are the small set, read through audit_by_time.
+ opSQLDeploys = `SELECT COUNT(*), COUNT(DISTINCT account_id || '/' || app) FROM audit
+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
+WHERE ?1 = '' OR address LIKE ?2 ESCAPE '\'
+ORDER BY created_at DESC, address LIMIT ?3 OFFSET ?4)` + opSQLPersonJoins
+
+ // 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.
+ 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
+ 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`
+
+ 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`
+
+ // The activity feed, newest first by audit.id, one statement per filter
+ // shape. Each walks an index in id order and stops at the limit, so none
+ // sorts. The account name and sqid come from a LEFT JOIN that keeps
+ // deleted accounts and rows with no account.
+ opSQLFeedColumns = `SELECT audit.id, audit.created_at, audit.address, COALESCE(accounts.name, ''),
+ COALESCE(accounts.sqid, ''), audit.app, audit.action, audit.detail
+FROM audit LEFT JOIN accounts ON accounts.id = audit.account_id
+`
+ opSQLFeedAll = opSQLFeedColumns + `ORDER BY audit.id DESC LIMIT ?1`
+ opSQLFeedBefore = opSQLFeedColumns + `WHERE audit.id < ?1 ORDER BY audit.id DESC LIMIT ?2`
+ // One account: audit_by_account. The action tests (?3, a JSON array)
+ // are made on each row, with + keeping them off audit_by_action.
+ opSQLFeedAccount = opSQLFeedColumns + `WHERE audit.account_id = ?1 AND audit.id < ?2 ORDER BY audit.id DESC LIMIT ?3`
+ opSQLFeedAccountActions = opSQLFeedColumns + `WHERE audit.account_id = ?1 AND audit.id < ?2
+ AND +audit.action IN (SELECT value FROM json_each(?3)) ORDER BY audit.id DESC LIMIT ?4`
+ opSQLFeedAccountOther = opSQLFeedColumns + `WHERE audit.account_id = ?1 AND audit.id < ?2
+ AND +audit.action NOT IN (SELECT value FROM json_each(?3)) ORDER BY audit.id DESC LIMIT ?4`
+ // One action, every account: audit_by_action. ActivityFeed runs it once
+ // per action and merges, so a rare kind never walks the whole table.
+ opSQLFeedAction = opSQLFeedColumns + `WHERE audit.action = ?1 AND audit.id < ?2 ORDER BY audit.id DESC LIMIT ?3`
+ // Everything but some actions (the "other" kind, most rows): the
+ // primary key, with the exclusion made on each row.
+ opSQLFeedOther = opSQLFeedColumns + `WHERE audit.action NOT IN (SELECT value FROM json_each(?1)) ORDER BY audit.id DESC LIMIT ?2`
+ opSQLFeedOtherBefore = opSQLFeedColumns + `WHERE audit.id < ?1
+ AND audit.action NOT IN (SELECT value FROM json_each(?2)) ORDER BY audit.id DESC LIMIT ?3`
+)
+
+// OperatorAccount is an account row as an operator page sees it, deleted
+// or not.
+type OperatorAccount struct {
+ ID int64
+ Sqid, Name string
+ Deleted bool
+}
+
+// OperatorAccountBySqid returns the account row with that sqid whatever its
+// deleted_at, or (nil, nil) when there is no row. It is for operator pages
+// only (the activity feed's account filter, where a deleted account's
+// history is still history) and must never back a member-facing lookup:
+// those use AccountBySqid, which hides a tombstoned account.
+func (s *Store) OperatorAccountBySqid(sqid string) (*OperatorAccount, error) {
+ var a OperatorAccount
+ var deleted int64
+ err := s.db.QueryRow(opSQLAccountBySqid, sqid).Scan(&a.ID, &a.Sqid, &a.Name, &deleted)
+ if errors.Is(err, sql.ErrNoRows) {
+ return nil, nil
+ }
+ if err != nil {
+ return nil, err
+ }
+ a.Deleted = deleted != 0
+ return &a, nil
+}
+
+// TouchLastSeen records that address was seen at now. It never moves
+// last_seen backwards and never creates a users row.
+func (s *Store) TouchLastSeen(address string, now time.Time) error {
+ _, err := s.db.Exec(opSQLTouchLastSeen, now.Unix(), address, now.Unix())
+ return err
+}
+
+// OperatorCounts is the dashboard's headline numbers.
+type OperatorCounts struct {
+ People, Active30, Active7, ActiveToday int
+ NewPeople7, NewPeoplePrev7 int
+ NewAccounts7, NewAccountsPrev7 int
+ Apps, NewApps7 int
+ DeploysToday, DeployApps int
+}
+
+// opMidnight is the UTC midnight that starts now's day.
+func opMidnight(now time.Time) time.Time {
+ y, m, d := now.UTC().Date()
+ return time.Date(y, m, d, 0, 0, 0, 0, time.UTC)
+}
+
+// OperatorCounts counts people, accounts, apps and deploys in the
+// dashboard's windows, all UTC: "this week" is the 7 × 24 h up to now, "last
+// week" the 7 × 24 h before it, "today" since UTC midnight. Active means
+// seen in the window or signed in during it. New accounts count deleted ones
+// too; apps count live rows only.
+func (s *Store) OperatorCounts(now time.Time) (OperatorCounts, error) {
+ var c OperatorCounts
+ if len(deployActions) != 2 {
+ return c, errors.New("console: opSQLDeploys takes two deploy actions")
+ }
+ n := now.Unix()
+ end := n + 1 // up to and including now
+ week, prev := n-7*opDay, n-14*opDay
+ today := opMidnight(now).Unix()
+ for _, q := range []struct {
+ dst []any
+ sql string
+ args []any
+ }{
+ {[]any{&c.People}, opSQLPeopleTotal, nil},
+ {[]any{&c.Active30}, opSQLActive, []any{n - 30*opDay}},
+ {[]any{&c.Active7}, opSQLActive, []any{week}},
+ {[]any{&c.ActiveToday}, opSQLActive, []any{today}},
+ {[]any{&c.NewPeople7}, opSQLNewPeople, []any{week, end}},
+ {[]any{&c.NewPeoplePrev7}, opSQLNewPeople, []any{prev, week}},
+ {[]any{&c.NewAccounts7}, opSQLNewAccounts, []any{week, end}},
+ {[]any{&c.NewAccountsPrev7}, opSQLNewAccounts, []any{prev, week}},
+ {[]any{&c.Apps, &c.NewApps7}, opSQLApps, []any{week, end}},
+ {[]any{&c.DeploysToday, &c.DeployApps}, opSQLDeploys, []any{today, deployActions[0], deployActions[1]}},
+ } {
+ if err := s.db.QueryRow(q.sql, q.args...).Scan(q.dst...); err != nil {
+ return OperatorCounts{}, err
+ }
+ }
+ return c, nil
+}
+
+// DayCount is one UTC day's count.
+type DayCount struct {
+ Day time.Time
+ N int
+}
+
+// NewPeoplePerDay is the number of people who joined on each of the last
+// days UTC days, oldest first and today last, with days nobody joined
+// filled as zero. A row created after now is not counted.
+func (s *Store) NewPeoplePerDay(now time.Time, days int) ([]DayCount, error) {
+ if days <= 0 {
+ return nil, nil
+ }
+ first := opMidnight(now).AddDate(0, 0, -(days - 1))
+ out := make([]DayCount, days)
+ for i := range out {
+ out[i].Day = first.AddDate(0, 0, i)
+ }
+ rows, err := s.db.Query(opSQLPerDay, first.Unix(), now.Unix()+1)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ for rows.Next() {
+ var day int64
+ var n int
+ if err := rows.Scan(&day, &n); err != nil {
+ return nil, err
+ }
+ if day >= 0 && day < int64(days) {
+ out[day].N = n
+ }
+ }
+ return out, rows.Err()
+}
+
+// PersonRow is one person on the operator people lists.
+type PersonRow struct {
+ Address string
+ Joined, LastSeen time.Time // LastSeen zero when never seen
+ Accounts int // live accounts they are a member of
+ FirstAccount string // the earliest live membership's account name; "" for none
+ Apps int // live apps they created
+}
+
+func scanPeople(rows *sql.Rows) ([]PersonRow, error) {
+ defer rows.Close()
+ var out []PersonRow
+ for rows.Next() {
+ var p PersonRow
+ var joined, seen int64
+ var key, first sql.NullString
+ if err := rows.Scan(&p.Address, &joined, &seen, &p.Accounts, &key, &first, &p.Apps); err != nil {
+ return nil, err
+ }
+ p.Joined = time.Unix(joined, 0).UTC()
+ p.LastSeen = timeOrZero(seen)
+ if key.Valid {
+ p.FirstAccount = first.String
+ }
+ out = append(out, p)
+ }
+ return out, rows.Err()
+}
+
+// NewestPeople is the limit most recently joined people, newest first, ties
+// by address.
+func (s *Store) NewestPeople(limit int) ([]PersonRow, error) {
+ if limit <= 0 {
+ return nil, nil
+ }
+ rows, err := s.db.Query(opSQLNewestPeople, limit)
+ if err != nil {
+ return nil, err
+ }
+ return scanPeople(rows)
+}
+
+// opContains is a LIKE pattern matching q literally anywhere: '\' is the
+// escape character, and q's own '\', '%' and '_' are escaped.
+func opContains(q string) string {
+ r := strings.NewReplacer(`\`, `\\`, `%`, `\%`, `_`, `\_`)
+ return "%" + r.Replace(q) + "%"
+}
+
+// PeoplePage is one page of people whose address contains q (literally;
+// "" for everyone), newest first, with the number of people matching.
+func (s *Store) PeoplePage(q string, offset, limit int) ([]PersonRow, int, error) {
+ if offset < 0 {
+ offset = 0
+ }
+ pattern := opContains(q)
+ var total int
+ var err error
+ if q == "" {
+ err = s.db.QueryRow(opSQLPeopleTotal).Scan(&total)
+ } else {
+ err = s.db.QueryRow(opSQLPeopleMatching, pattern).Scan(&total)
+ }
+ if err != nil {
+ return nil, 0, err
+ }
+ if limit <= 0 {
+ return nil, total, nil
+ }
+ rows, err := s.db.Query(opSQLPeoplePage, q, pattern, limit, offset)
+ if err != nil {
+ return nil, 0, err
+ }
+ people, err := scanPeople(rows)
+ return people, total, err
+}
+
+// AccountRow is one live account on the operator accounts list.
+type AccountRow struct {
+ ID int64
+ Sqid, Name, Plan string // Plan "" when the account has no plan row
+ Created time.Time
+ Apps, Members int
+}
+
+// AccountsPage is one page of live accounts whose name or sqid contains q
+// (literally; "" for every account), newest first, with the number of
+// accounts matching.
+func (s *Store) AccountsPage(q string, offset, limit int) ([]AccountRow, int, error) {
+ if offset < 0 {
+ offset = 0
+ }
+ pattern := opContains(q)
+ var total int
+ if err := s.db.QueryRow(opSQLAccountsTotal, q, pattern).Scan(&total); err != nil {
+ return nil, 0, err
+ }
+ if limit <= 0 {
+ return nil, total, nil
+ }
+ rows, err := s.db.Query(opSQLAccountsPage, q, pattern, limit, offset)
+ if err != nil {
+ return nil, 0, err
+ }
+ defer rows.Close()
+ var out []AccountRow
+ for rows.Next() {
+ var a AccountRow
+ var created int64
+ if err := rows.Scan(&a.ID, &a.Sqid, &a.Name, &created, &a.Plan, &a.Apps, &a.Members); err != nil {
+ return nil, 0, err
+ }
+ a.Created = time.Unix(created, 0).UTC()
+ out = append(out, a)
+ }
+ return out, total, rows.Err()
+}
+
+// ActivityFilter narrows the activity feed. AccountID 0 is every account;
+// -1 means the account filter matched nothing, so the feed is empty.
+// Actions keeps only those actions; Exclude drops those (the "other" kind).
+type ActivityFilter struct {
+ AccountID int64
+ Actions, Exclude []string
+}
+
+// FeedRow is one audit row on the activity feed.
+type FeedRow struct {
+ ID int64
+ At time.Time
+ Address, AccountName, AccountSqid, App, Action, Detail string
+}
+
+// ActivityFeed is up to limit audit rows matching f, newest first by id,
+// older than beforeID when beforeID > 0. Rows of deleted accounts carry the
+// account's name; rows with no account carry "".
+func (s *Store) ActivityFeed(f ActivityFilter, beforeID int64, limit int) ([]FeedRow, error) {
+ if limit <= 0 || f.AccountID < 0 {
+ return nil, nil
+ }
+ before := beforeID
+ if before <= 0 {
+ before = math.MaxInt64
+ }
+ actions := opUnique(f.Actions, f.Exclude)
+ if len(f.Actions) > 0 && len(actions) == 0 {
+ return nil, nil // every kind asked for is excluded
+ }
+ if f.AccountID > 0 {
+ switch {
+ case len(actions) > 0:
+ return s.feed(opSQLFeedAccountActions, f.AccountID, before, opJSON(actions), limit)
+ case len(f.Exclude) > 0:
+ return s.feed(opSQLFeedAccountOther, f.AccountID, before, opJSON(f.Exclude), limit)
+ default:
+ return s.feed(opSQLFeedAccount, f.AccountID, before, limit)
+ }
+ }
+ if len(actions) > 0 {
+ var all []FeedRow
+ for _, a := range actions {
+ rows, err := s.feed(opSQLFeedAction, a, before, limit)
+ if err != nil {
+ return nil, err
+ }
+ all = append(all, rows...)
+ }
+ sort.Slice(all, func(i, j int) bool { return all[i].ID > all[j].ID })
+ if len(all) > limit {
+ all = all[:limit]
+ }
+ return all, nil
+ }
+ switch {
+ case len(f.Exclude) > 0 && beforeID > 0:
+ return s.feed(opSQLFeedOtherBefore, before, opJSON(f.Exclude), limit)
+ case len(f.Exclude) > 0:
+ return s.feed(opSQLFeedOther, opJSON(f.Exclude), limit)
+ case beforeID > 0:
+ return s.feed(opSQLFeedBefore, before, limit)
+ default:
+ return s.feed(opSQLFeedAll, limit)
+ }
+}
+
+// opUnique is actions without duplicates and without any in exclude.
+func opUnique(actions, exclude []string) []string {
+ seen := map[string]bool{}
+ for _, e := range exclude {
+ seen[e] = true
+ }
+ var out []string
+ for _, a := range actions {
+ if !seen[a] {
+ seen[a] = true
+ out = append(out, a)
+ }
+ }
+ return out
+}
+
+func opJSON(list []string) string {
+ b, _ := json.Marshal(list) // a []string always marshals
+ return string(b)
+}
+
+func (s *Store) feed(query string, args ...any) ([]FeedRow, error) {
+ rows, err := s.db.Query(query, args...)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ var out []FeedRow
+ for rows.Next() {
+ var r FeedRow
+ var at int64
+ if err := rows.Scan(&r.ID, &at, &r.Address, &r.AccountName, &r.AccountSqid, &r.App, &r.Action, &r.Detail); err != nil {
+ return nil, err
+ }
+ r.At = time.Unix(at, 0).UTC()
+ out = append(out, r)
+ }
+ return out, rows.Err()
+}
diff --git a/internal/console/opstore_test.go b/internal/console/opstore_test.go
new file mode 100644
index 000000000..2885eeb7b
--- /dev/null
+++ b/internal/console/opstore_test.go
@@ -0,0 +1,828 @@
+package console
+
+import (
+ "database/sql"
+ "fmt"
+ "math"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+)
+
+// opNow is the fixed clock every operator store test reads from.
+var opNow = time.Date(2026, 10, 25, 12, 0, 0, 0, time.UTC)
+
+func openOpStore(t *testing.T) *Store {
+ t.Helper()
+ s, err := Open(filepath.Join(t.TempDir(), "console.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { s.Close() })
+ return s
+}
+
+func opMust(t *testing.T, err error) {
+ t.Helper()
+ if err != nil {
+ t.Fatal(err)
+ }
+}
+
+func opUser(t *testing.T, s *Store, address string, at time.Time) {
+ t.Helper()
+ if _, err := s.EnsureUser(address, at); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestMigrateOperatorPagesIsIdempotent(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "console.db")
+ for i := 0; i < 2; i++ {
+ s, err := Open(path)
+ if err != nil {
+ t.Fatalf("open %d: %v", i+1, err)
+ }
+ opMust(t, s.Close())
+ }
+ s, err := Open(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer s.Close()
+ want := map[string]string{
+ "audit_by_time": "audit",
+ "audit_by_account": "audit",
+ "audit_by_action": "audit",
+ "sessions_by_time": "sessions",
+ "users_by_created": "users",
+ "users_by_last_seen": "users",
+ "memberships_by_address": "memberships",
+ "apps_by_creator": "apps",
+ }
+ for index, table := range want {
+ rows, err := s.db.Query(`SELECT name FROM pragma_index_list(?)`, table)
+ if err != nil {
+ t.Fatal(err)
+ }
+ found := false
+ for rows.Next() {
+ var n string
+ opMust(t, rows.Scan(&n))
+ if n == index {
+ found = true
+ }
+ }
+ opMust(t, rows.Close())
+ if !found {
+ t.Errorf("index %s missing on %s", index, table)
+ }
+ }
+ var n int
+ opMust(t, s.db.QueryRow(`SELECT COUNT(*) FROM pragma_table_info('users') WHERE name = 'last_seen'`).Scan(&n))
+ if n != 1 {
+ t.Fatalf("users.last_seen columns = %d, want 1", n)
+ }
+}
+
+// opPlanCase is one row of the query-plan witness: a statement the operator
+// reads run, arguments of the shape they pass, the plan lines that must
+// appear (each a substring of some line) and the ones that must not.
+type opPlanCase struct {
+ name string
+ sql string
+ args []any
+ want []string
+ notWant []string
+ // mergeSorts is how many "USE TEMP B-TREE FOR ORDER BY" lines a MERGE
+ // (UNION) may carry, one per half; 0 everywhere else.
+ mergeSorts int
+}
+
+// opPlanForbidden holds for every operator query: no per-row subquery and
+// no whole-result sort.
+var opPlanForbidden = []string{"CORRELATED", "USE TEMP B-TREE FOR ORDER BY"}
+
+var opQueryPlans = []opPlanCase{
+ {name: "people total", sql: opSQLPeopleTotal,
+ want: []string{"SCAN users USING COVERING INDEX"}},
+ {name: "people matching", sql: opSQLPeopleMatching, args: []any{`%exam%`},
+ want: []string{"SCAN users USING COVERING INDEX"}},
+ // The UNION runs as a MERGE whose two halves are each sorted by
+ // address: those two sorts hold only the addresses in the window (the
+ // spec's allowance for the UNION's own temp B-tree) and are the only
+ // sorts any operator query is allowed.
+ {name: "active", sql: opSQLActive, args: []any{int64(1)}, mergeSorts: 2,
+ want: []string{"MERGE (UNION)", "SEARCH users USING INDEX users_by_last_seen (last_seen>?)",
+ "SEARCH sessions USING COVERING INDEX sessions_by_time (created_at>?)"},
+ notWant: []string{"SCAN users", "SCAN sessions"}},
+ {name: "new people", sql: opSQLNewPeople, args: []any{int64(1), int64(2)},
+ want: []string{"SEARCH users USING COVERING INDEX users_by_created (created_at>? AND created_at<?)"},
+ notWant: []string{"SCAN users"}},
+ {name: "per day", sql: opSQLPerDay, args: []any{int64(1), int64(2)},
+ want: []string{"SEARCH users USING COVERING INDEX users_by_created (created_at>? AND created_at<?)"},
+ notWant: []string{"SCAN users"}},
+ {name: "new accounts", sql: opSQLNewAccounts, args: []any{int64(1), int64(2)},
+ want: []string{"SCAN accounts"}},
+ {name: "apps", sql: opSQLApps, args: []any{int64(1), int64(2)},
+ want: []string{"SCAN apps"}},
+ {name: "deploys", sql: opSQLDeploys, args: []any{int64(1), "promote", "rollback"},
+ want: []string{"SEARCH audit USING INDEX audit_by_time (created_at>?)"},
+ notWant: []string{"SCAN audit", "audit_by_action"}},
+ {name: "newest people", sql: opSQLNewestPeople, args: []any{50},
+ 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"}},
+ {name: "people page", 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"}},
+ {name: "people page searched", 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"}},
+ {name: "accounts total", sql: opSQLAccountsTotal, args: []any{"", "%%"},
+ want: []string{"SCAN accounts"}},
+ {name: "accounts page", sql: opSQLAccountsPage, args: []any{"", "%%", 50, 0},
+ want: []string{"SCAN accounts",
+ "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"}},
+ {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)},
+ want: []string{"SEARCH users USING INDEX sqlite_autoindex_users_1 (address=?)"}},
+ {name: "feed all", sql: opSQLFeedAll, args: []any{50},
+ want: []string{"SCAN audit", "SEARCH accounts USING INTEGER PRIMARY KEY (rowid=?)"},
+ notWant: []string{"audit USING INDEX", "SCAN accounts"}},
+ {name: "feed before", sql: opSQLFeedBefore, args: []any{int64(71), 50},
+ want: []string{"SEARCH audit USING INTEGER PRIMARY KEY (rowid<?)", "SEARCH accounts USING INTEGER PRIMARY KEY (rowid=?)"},
+ notWant: []string{"SCAN audit", "SCAN accounts"}},
+ {name: "feed account", sql: opSQLFeedAccount, args: []any{int64(7), int64(math.MaxInt64), 50},
+ want: []string{"SEARCH audit USING INDEX audit_by_account (account_id=? AND id<?)"},
+ notWant: []string{"SCAN audit", "SCAN accounts"}},
+ {name: "feed account actions", sql: opSQLFeedAccountActions, args: []any{int64(7), int64(math.MaxInt64), `["promote","rollback"]`, 50},
+ want: []string{"SEARCH audit USING INDEX audit_by_account (account_id=? AND id<?)"},
+ notWant: []string{"SCAN audit", "audit_by_action", "SCAN accounts"}},
+ {name: "feed account other", sql: opSQLFeedAccountOther, args: []any{int64(7), int64(math.MaxInt64), `["promote","rollback"]`, 50},
+ want: []string{"SEARCH audit USING INDEX audit_by_account (account_id=? AND id<?)"},
+ notWant: []string{"SCAN audit", "audit_by_action", "SCAN accounts"}},
+ {name: "feed action", sql: opSQLFeedAction, args: []any{"promote", int64(math.MaxInt64), 50},
+ want: []string{"SEARCH audit USING INDEX audit_by_action (action=? AND id<?)"},
+ notWant: []string{"SCAN audit", "SCAN accounts"}},
+ {name: "feed other", sql: opSQLFeedOther, args: []any{`["promote","rollback"]`, 50},
+ want: []string{"SCAN audit"},
+ notWant: []string{"audit USING INDEX", "SCAN accounts"}},
+ {name: "feed other before", sql: opSQLFeedOtherBefore, args: []any{int64(71), `["promote","rollback"]`, 50},
+ want: []string{"SEARCH audit USING INTEGER PRIMARY KEY (rowid<?)"},
+ notWant: []string{"SCAN audit", "SCAN accounts"}},
+}
+
+// opSQLByName names every statement constant in opstore.go; the fragments
+// the statements are built from map to "" and need no row of their own.
+var opSQLByName = map[string]string{
+ "opSQLPeopleTotal": opSQLPeopleTotal, "opSQLPeopleMatching": opSQLPeopleMatching,
+ "opSQLActive": opSQLActive, "opSQLNewPeople": opSQLNewPeople, "opSQLNewAccounts": opSQLNewAccounts,
+ "opSQLApps": opSQLApps, "opSQLDeploys": opSQLDeploys, "opSQLPerDay": opSQLPerDay,
+ "opSQLNewestPeople": opSQLNewestPeople, "opSQLPeoplePage": opSQLPeoplePage,
+ "opSQLAccountsTotal": opSQLAccountsTotal, "opSQLAccountsPage": opSQLAccountsPage,
+ "opSQLAccountBySqid": opSQLAccountBySqid, "opSQLTouchLastSeen": opSQLTouchLastSeen,
+ "opSQLFeedAll": opSQLFeedAll, "opSQLFeedBefore": opSQLFeedBefore, "opSQLFeedAccount": opSQLFeedAccount,
+ "opSQLFeedAccountActions": opSQLFeedAccountActions, "opSQLFeedAccountOther": opSQLFeedAccountOther,
+ "opSQLFeedAction": opSQLFeedAction, "opSQLFeedOther": opSQLFeedOther, "opSQLFeedOtherBefore": opSQLFeedOtherBefore,
+ "opSQLPersonColumns": "", "opSQLPersonJoins": "", "opSQLFeedColumns": "",
+}
+
+// opPlan is the EXPLAIN QUERY PLAN detail lines of one statement.
+func opPlan(db sqlHandle, query string, args ...any) ([]string, error) {
+ rows, err := db.Query("EXPLAIN QUERY PLAN "+query, args...)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ var out []string
+ for rows.Next() {
+ var id, parent, unused int
+ var detail string
+ if err := rows.Scan(&id, &parent, &unused, &detail); err != nil {
+ return nil, err
+ }
+ out = append(out, detail)
+ }
+ return out, rows.Err()
+}
+
+// opPlanProblems checks one witness row against the plan the database
+// would run, returning what is wrong with it.
+func opPlanProblems(db sqlHandle, c opPlanCase) ([]string, []string, error) {
+ plan, err := opPlan(db, c.sql, c.args...)
+ if err != nil {
+ return nil, nil, err
+ }
+ var problems []string
+ has := func(s string) bool {
+ for _, line := range plan {
+ if strings.Contains(line, s) {
+ return true
+ }
+ }
+ return false
+ }
+ for _, w := range c.want {
+ if !has(w) {
+ problems = append(problems, "missing "+w)
+ }
+ }
+ sorts := 0
+ for _, line := range plan {
+ if strings.Contains(line, "USE TEMP B-TREE FOR ORDER BY") {
+ sorts++
+ }
+ }
+ if sorts > 0 && (sorts > c.mergeSorts || !has("MERGE (UNION)")) {
+ problems = append(problems, "has USE TEMP B-TREE FOR ORDER BY")
+ }
+ for _, w := range append(append([]string(nil), opPlanForbidden...), c.notWant...) {
+ if w != "USE TEMP B-TREE FOR ORDER BY" && has(w) {
+ problems = append(problems, "has "+w)
+ }
+ }
+ return plan, problems, nil
+}
+
+// TestOperatorQueryPlans is the witness that every statement the operator
+// reads run takes its intended access pattern, on a store migrated by Open.
+func TestOperatorQueryPlans(t *testing.T) {
+ s := openOpStore(t)
+ for _, c := range opQueryPlans {
+ plan, problems, err := opPlanProblems(s.db, c)
+ if err != nil {
+ t.Errorf("%s: %v", c.name, err)
+ continue
+ }
+ if len(problems) > 0 {
+ t.Errorf("%s: %s\nplan:\n %s", c.name, strings.Join(problems, "; "), strings.Join(plan, "\n "))
+ }
+ }
+ // Every opSQL constant in opstore.go has a row.
+ src, err := os.ReadFile("opstore.go")
+ opMust(t, err)
+ covered := map[string]bool{}
+ for _, c := range opQueryPlans {
+ covered[c.sql] = true
+ }
+ for _, line := range strings.Split(string(src), "\n") {
+ line = strings.TrimSpace(line)
+ if !strings.HasPrefix(line, "opSQL") || !strings.Contains(line, "=") {
+ continue
+ }
+ name := strings.TrimSpace(strings.SplitN(line, "=", 2)[0])
+ stmt, known := opSQLByName[name]
+ if !known {
+ t.Errorf("%s is not in opSQLByName", name)
+ } else if stmt != "" && !covered[stmt] {
+ t.Errorf("%s has no row in opQueryPlans", name)
+ }
+ }
+
+ // The check bites. Rewritten in the earlier per-user EXISTS form, the
+ // active count is refused for its correlated subquery.
+ exists := opPlanCase{name: "active, per-user EXISTS", sql: `SELECT COUNT(*) FROM users
+WHERE last_seen >= ?1 OR EXISTS (SELECT 1 FROM sessions WHERE sessions.address = users.address AND sessions.created_at >= ?1)`,
+ args: []any{int64(1)}}
+ 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)
+ }
+ // Without sessions_by_time, the active count's sessions half scans.
+ _, err = s.db.Exec(`DROP INDEX sessions_by_time`)
+ opMust(t, err)
+ if _, problems, err := opPlanProblems(s.db, opQueryPlans[2]); err != nil || !opHas(problems, "has SCAN sessions") {
+ t.Errorf("dropping sessions_by_time was not caught: %v %v", problems, err)
+ }
+}
+
+func opHas(list []string, s string) bool {
+ for _, l := range list {
+ if l == s {
+ return true
+ }
+ }
+ return false
+}
+
+func TestTouchLastSeenNeverMovesBack(t *testing.T) {
+ s := openOpStore(t)
+ opUser(t, s, "ann@example.com", opNow.Add(-24*time.Hour))
+ opMust(t, s.TouchLastSeen("ann@example.com", opNow))
+ opMust(t, s.TouchLastSeen("ann@example.com", opNow.Add(-time.Hour)))
+ var seen int64
+ opMust(t, s.db.QueryRow(`SELECT last_seen FROM users WHERE address = 'ann@example.com'`).Scan(&seen))
+ if seen != opNow.Unix() {
+ t.Fatalf("last_seen = %d, want %d", seen, opNow.Unix())
+ }
+ opMust(t, s.TouchLastSeen("nobody@example.com", opNow))
+ var n int
+ opMust(t, s.db.QueryRow(`SELECT COUNT(*) FROM users`).Scan(&n))
+ if n != 1 {
+ t.Fatalf("users = %d after touching an unknown address, want 1", n)
+ }
+}
+
+func TestOperatorCountsWindows(t *testing.T) {
+ s := openOpStore(t)
+ people := []struct {
+ addr string
+ ago time.Duration
+ }{
+ {"a@example.com", time.Hour},
+ {"b@example.com", 6 * 24 * time.Hour},
+ {"c@example.com", 8 * 24 * time.Hour},
+ {"d@example.com", 13 * 24 * time.Hour},
+ {"e@example.com", 20 * 24 * time.Hour},
+ }
+ for _, p := range people {
+ opUser(t, s, p.addr, opNow.Add(-p.ago))
+ }
+ acctA, acctB := testAccountID(), testAccountID()
+ opMust(t, s.CreateAccount(acctA, "aaaa", "shop", "a@example.com", opNow.Add(-2*24*time.Hour)))
+ opMust(t, s.CreateAccount(acctB, "bbbb", "notes", "c@example.com", opNow.Add(-10*24*time.Hour)))
+ for _, app := range []string{"shop", "blog", "gone"} {
+ if _, err := s.CreateAppIn(acctA, app, "a@example.com", opNow.Add(-3*24*time.Hour)); err != nil {
+ t.Fatal(err)
+ }
+ }
+ opMust(t, s.TrashAppRow(acctA, "gone", opNow.Add(-time.Hour)))
+ opMust(t, s.RecordEvent(acctA, "shop", "a@example.com", "promote", "promoted v1 to stable", opNow.Add(-2*time.Hour)))
+ opMust(t, s.RecordEvent(acctA, "shop", "a@example.com", "promote", "promoted v2 to stable", opNow.Add(-time.Hour)))
+ opMust(t, s.RecordEvent(acctA, "blog", "a@example.com", "rollback", "rolled back stable to v1", opNow.Add(-time.Hour)))
+ opMust(t, s.RecordEvent(acctA, "blog", "a@example.com", "promote", "promoted v0 to stable", opNow.Add(-24*time.Hour)))
+ opMust(t, s.RecordEvent(acctA, "blog", "a@example.com", "rename", "renamed", opNow.Add(-time.Hour)))
+ opMust(t, s.TouchLastSeen("a@example.com", opNow.Add(-time.Hour)))
+ opMust(t, s.TouchLastSeen("b@example.com", opNow.Add(-5*24*time.Hour)))
+ if _, err := s.CreateSessionMethod("c@example.com", "", MethodKeymail, opNow.Add(-3*24*time.Hour)); err != nil {
+ t.Fatal(err)
+ }
+
+ got, err := s.OperatorCounts(opNow)
+ opMust(t, err)
+ want := OperatorCounts{People: 5, Active30: 3, Active7: 3, ActiveToday: 1,
+ NewPeople7: 2, NewPeoplePrev7: 2, NewAccounts7: 1, NewAccountsPrev7: 1,
+ Apps: 2, NewApps7: 2, DeploysToday: 3, DeployApps: 2}
+ if got != want {
+ t.Fatalf("OperatorCounts =\n %+v\nwant\n %+v", got, want)
+ }
+}
+
+func TestNewPeoplePerDayFillsZeroDaysAndIgnoresFuture(t *testing.T) {
+ s := openOpStore(t)
+ midnight := time.Date(2026, 10, 25, 0, 0, 0, 0, time.UTC)
+ opUser(t, s, "t1@example.com", midnight)
+ opUser(t, s, "t2@example.com", opNow.Add(-time.Hour))
+ opUser(t, s, "t3@example.com", opNow)
+ opUser(t, s, "old@example.com", midnight.Add(-29*24*time.Hour+time.Minute))
+ opUser(t, s, "older@example.com", midnight.Add(-29*24*time.Hour-time.Minute))
+ opUser(t, s, "future@example.com", opNow.Add(time.Hour))
+ days, err := s.NewPeoplePerDay(opNow, 30)
+ opMust(t, err)
+ if len(days) != 30 {
+ t.Fatalf("%d entries, want 30", len(days))
+ }
+ if days[0].N != 1 || days[29].N != 3 {
+ t.Fatalf("first %d, last %d, want 1 and 3", days[0].N, days[29].N)
+ }
+ for i := 1; i < 29; i++ {
+ if days[i].N != 0 {
+ t.Fatalf("day %d = %d, want 0", i, days[i].N)
+ }
+ if !days[i].Day.Equal(midnight.Add(time.Duration(i-29) * 24 * time.Hour)) {
+ t.Fatalf("day %d is %v", i, days[i].Day)
+ }
+ }
+ if !days[29].Day.Equal(midnight) || days[29].Day.Location() != time.UTC {
+ t.Fatalf("last day %v, want %v UTC", days[29].Day, midnight)
+ }
+}
+
+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"} {
+ 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 {
+ t.Fatal(err)
+ }
+ opMust(t, s.TouchLastSeen("ed@keymail.dev", 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" {
+ t.Fatalf("NewestPeople(2) = %+v", newest)
+ }
+ ed := newest[0]
+ if ed.Accounts != 1 || ed.FirstAccount != "shop" || ed.Apps != 1 || !ed.LastSeen.Equal(opNow) ||
+ !ed.Joined.Equal(opNow.Add(-6*time.Hour)) {
+ t.Fatalf("ed = %+v", ed)
+ }
+ if !newest[1].LastSeen.IsZero() {
+ t.Fatalf("di was never seen, LastSeen = %v", newest[1].LastSeen)
+ }
+ page, total, err := s.PeoplePage("", 0, 2)
+ opMust(t, err)
+ if total != 5 || len(page) != 2 || page[0].Address != "ed@keymail.dev" {
+ t.Fatalf("PeoplePage = %+v, %d", page, total)
+ }
+ page, total, err = s.PeoplePage("", 4, 2)
+ opMust(t, err)
+ 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)
+ opMust(t, err)
+ if total != 1 || len(page) != 1 || page[0].Address != "ann@example.com" {
+ t.Fatalf("PeoplePage(exam) = %+v, %d", page, total)
+ }
+}
+
+func TestNewestPeopleBreaksTiesByAddress(t *testing.T) {
+ s := openOpStore(t)
+ for _, a := range []string{"zed@example.com", "amy@example.com", "max@example.com"} {
+ opUser(t, s, a, opNow)
+ }
+ got, err := s.NewestPeople(3)
+ opMust(t, err)
+ if len(got) != 3 || got[0].Address != "amy@example.com" || got[1].Address != "max@example.com" || got[2].Address != "zed@example.com" {
+ t.Fatalf("NewestPeople = %+v", got)
+ }
+}
+
+func TestPeopleAndAccountsSearchIsLiteral(t *testing.T) {
+ s := openOpStore(t)
+ for _, a := range []string{"a%b@example.com", "ab@example.com", "o'brien@example.com"} {
+ opUser(t, s, a, opNow)
+ }
+ long := strings.Repeat("x", 2000)
+ for _, tc := range []struct {
+ q string
+ want int
+ }{{"%", 1}, {"_", 0}, {"o'brien", 1}, {`\`, 0}, {long, 0}} {
+ page, total, err := s.PeoplePage(tc.q, 0, 50)
+ if err != nil {
+ t.Fatalf("PeoplePage(%.20q): %v", tc.q, err)
+ }
+ if total != tc.want || len(page) != tc.want {
+ t.Fatalf("PeoplePage(%.20q) = %d rows, total %d, want %d", tc.q, len(page), total, tc.want)
+ }
+ }
+ page, _, err := s.PeoplePage("%", 0, 50)
+ opMust(t, err)
+ if page[0].Address != "a%b@example.com" {
+ t.Fatalf("%% matched %q", page[0].Address)
+ }
+
+ opMust(t, s.CreateAccount(testAccountID(), "pct1", "50% off", "ab@example.com", opNow))
+ opMust(t, s.CreateAccount(testAccountID(), "plain", "500 off", "ab@example.com", opNow))
+ opMust(t, s.CreateAccount(testAccountID(), "quote", "o'brien's", "ab@example.com", opNow))
+ for _, tc := range []struct {
+ q string
+ want int
+ }{{"%", 1}, {"_", 0}, {"o'brien", 1}, {`\`, 0}, {long, 0}, {"pct", 1}} {
+ page, total, err := s.AccountsPage(tc.q, 0, 50)
+ if err != nil {
+ t.Fatalf("AccountsPage(%.20q): %v", tc.q, err)
+ }
+ if total != tc.want || len(page) != tc.want {
+ t.Fatalf("AccountsPage(%.20q) = %d rows, total %d, want %d", tc.q, len(page), total, tc.want)
+ }
+ }
+ page2, _, err := s.AccountsPage("%", 0, 50)
+ opMust(t, err)
+ if page2[0].Name != "50% off" {
+ t.Fatalf("%% matched %q", page2[0].Name)
+ }
+}
+
+func TestAccountsPageColumns(t *testing.T) {
+ s := openOpStore(t)
+ older, newer, gone := testAccountID(), testAccountID(), testAccountID()
+ opMust(t, s.CreateAccount(older, "aaaa", "shop", "ann@example.com", opNow.Add(-48*time.Hour)))
+ opMust(t, s.CreateAccount(newer, "bbbb", "notes", "ann@example.com", opNow.Add(-time.Hour)))
+ opMust(t, s.CreateAccount(gone, "cccc", "old", "ann@example.com", opNow.Add(-time.Hour)))
+ opMust(t, s.DeleteAccount(gone, opNow))
+ opMust(t, s.AddMember(older, "bob@example.com", RoleMember, opNow))
+ for _, app := range []string{"shop", "blog", "gone"} {
+ if _, err := s.CreateAppIn(older, app, "ann@example.com", opNow); err != nil {
+ t.Fatal(err)
+ }
+ }
+ opMust(t, s.TrashAppRow(older, "gone", opNow))
+ _, err := s.SetAccountPlan(older, "personal", nil, "operator", nil, "", "ann@example.com", opNow)
+ opMust(t, err)
+ page, total, err := s.AccountsPage("", 0, 50)
+ opMust(t, err)
+ if total != 2 || len(page) != 2 {
+ t.Fatalf("AccountsPage = %+v, %d", page, total)
+ }
+ if page[0].Sqid != "bbbb" || page[0].Plan != "" || page[0].Apps != 0 || page[0].Members != 1 {
+ t.Fatalf("newest = %+v", page[0])
+ }
+ if page[1].Sqid != "aaaa" || page[1].Plan != "personal" || page[1].Apps != 2 || page[1].Members != 2 ||
+ !page[1].Created.Equal(opNow.Add(-48*time.Hour)) || page[1].ID != older || page[1].Name != "shop" {
+ t.Fatalf("older = %+v", page[1])
+ }
+ op, err := s.OperatorAccountBySqid("cccc")
+ opMust(t, err)
+ if op == nil || !op.Deleted || op.ID != gone || op.Name != "old" {
+ t.Fatalf("OperatorAccountBySqid(deleted) = %+v", op)
+ }
+ op, err = s.OperatorAccountBySqid("aaaa")
+ opMust(t, err)
+ if op == nil || op.Deleted || op.ID != older {
+ t.Fatalf("OperatorAccountBySqid(live) = %+v", op)
+ }
+ op, err = s.OperatorAccountBySqid("zzzz")
+ if op != nil || err != nil {
+ t.Fatalf("OperatorAccountBySqid(none) = %+v, %v", op, err)
+ }
+}
+
+func TestOperatorReadsSurviveMissingAndDeletedAccounts(t *testing.T) {
+ s := openOpStore(t)
+ opUser(t, s, "loner@example.com", opNow.Add(-2*time.Hour))
+ opUser(t, s, "left@example.com", opNow.Add(-time.Hour))
+ gone := testAccountID()
+ opMust(t, s.CreateAccount(gone, "gone", "closed shop", "left@example.com", opNow.Add(-time.Hour)))
+ opMust(t, s.RecordEvent(gone, "", "left@example.com", "account-created", "created", opNow.Add(-time.Hour)))
+ opMust(t, s.DeleteAccount(gone, opNow))
+ // A membership row left on a deleted account (DeleteAccount removes
+ // them; an older console may not have) still names no first account.
+ _, err := s.db.Exec(`INSERT INTO memberships (account_id, address, role, added_at) VALUES (?, ?, ?, ?)`,
+ gone, "left@example.com", RoleOwner, opNow.Unix())
+ opMust(t, err)
+ opMust(t, s.RecordEvent(0, "", "loner@example.com", "signin", "signed in", opNow))
+
+ people, err := s.NewestPeople(10)
+ opMust(t, err)
+ if len(people) != 2 {
+ t.Fatalf("NewestPeople = %+v", people)
+ }
+ for _, p := range people {
+ if p.Accounts != 0 || p.FirstAccount != "" || p.Apps != 0 {
+ t.Fatalf("%s = %+v, want no accounts", p.Address, p)
+ }
+ }
+ c, err := s.OperatorCounts(opNow)
+ opMust(t, err)
+ if c.People != 2 {
+ t.Fatalf("People = %d, want 2", c.People)
+ }
+ feed, err := s.ActivityFeed(ActivityFilter{}, 0, 10)
+ opMust(t, err)
+ if len(feed) != 2 {
+ t.Fatalf("feed = %+v", feed)
+ }
+ if feed[0].Action != "signin" || feed[0].AccountName != "" || feed[0].AccountSqid != "" {
+ t.Fatalf("account-less row = %+v", feed[0])
+ }
+ if feed[1].AccountName != "closed shop" || feed[1].AccountSqid != "gone" {
+ t.Fatalf("deleted account's row = %+v", feed[1])
+ }
+}
+
+func TestActivityFeedFiltersAndPages(t *testing.T) {
+ s := openOpStore(t)
+ a, b := testAccountID(), testAccountID()
+ opMust(t, s.CreateAccount(a, "aaaa", "shop", "ann@example.com", opNow))
+ opMust(t, s.CreateAccount(b, "bbbb", "notes", "ann@example.com", opNow))
+ actions := []string{"promote", "rename", "rollback"}
+ for i := 1; i <= 120; i++ {
+ acct := a
+ if i%2 == 0 {
+ acct = b
+ }
+ opMust(t, s.RecordEvent(acct, "shop", "ann@example.com", actions[i%3], fmt.Sprintf("row %d", i), opNow.Add(time.Duration(i)*time.Second)))
+ }
+ ids := func(rows []FeedRow) []int64 {
+ var out []int64
+ for _, r := range rows {
+ out = append(out, r.ID)
+ }
+ return out
+ }
+ page, err := s.ActivityFeed(ActivityFilter{}, 0, 50)
+ opMust(t, err)
+ if len(page) != 50 || page[0].ID != 120 || page[49].ID != 71 {
+ t.Fatalf("first page = %v", ids(page))
+ }
+ if page[0].Detail != "row 120" || page[0].AccountSqid != "bbbb" || page[0].AccountName != "notes" ||
+ page[0].App != "shop" || page[0].Address != "ann@example.com" || page[0].Action != "promote" ||
+ !page[0].At.Equal(opNow.Add(120*time.Second)) {
+ t.Fatalf("row 120 = %+v", page[0])
+ }
+ page, err = s.ActivityFeed(ActivityFilter{}, 71, 50)
+ opMust(t, err)
+ if len(page) != 50 || page[0].ID != 70 || page[49].ID != 21 {
+ t.Fatalf("second page = %v", ids(page))
+ }
+ check := func(f ActivityFilter, before int64, limit int, keep func(id int64, acct int64, action string) bool) {
+ t.Helper()
+ got, err := s.ActivityFeed(f, before, limit)
+ opMust(t, err)
+ var want []int64
+ for i := int64(120); i >= 1 && len(want) < limit; i-- {
+ if before > 0 && i >= before {
+ continue
+ }
+ acct := a
+ if i%2 == 0 {
+ acct = b
+ }
+ if keep(i, acct, actions[i%3]) {
+ want = append(want, i)
+ }
+ }
+ if fmt.Sprint(ids(got)) != fmt.Sprint(want) {
+ t.Fatalf("ActivityFeed(%+v, %d, %d) = %v, want %v", f, before, limit, ids(got), want)
+ }
+ }
+ deploys := func(action string) bool { return action == "promote" || action == "rollback" }
+ check(ActivityFilter{AccountID: a}, 0, 50, func(_, acct int64, _ string) bool { return acct == a })
+ check(ActivityFilter{AccountID: a}, 60, 50, func(_, acct int64, _ string) bool { return acct == a })
+ check(ActivityFilter{Actions: deployActions}, 0, 50, func(_, _ int64, act string) bool { return deploys(act) })
+ check(ActivityFilter{Actions: deployActions}, 90, 50, func(_, _ int64, act string) bool { return deploys(act) })
+ check(ActivityFilter{Actions: []string{"rename", "rename"}}, 0, 50, func(_, _ int64, act string) bool { return act == "rename" })
+ check(ActivityFilter{Exclude: deployActions}, 0, 50, func(_, _ int64, act string) bool { return !deploys(act) })
+ check(ActivityFilter{Exclude: deployActions}, 100, 20, func(_, _ int64, act string) bool { return !deploys(act) })
+ check(ActivityFilter{AccountID: b, Actions: deployActions}, 0, 50, func(_, acct int64, act string) bool { return acct == b && deploys(act) })
+ check(ActivityFilter{AccountID: b, Exclude: deployActions}, 0, 50, func(_, acct int64, act string) bool { return acct == b && !deploys(act) })
+ check(ActivityFilter{AccountID: -1}, 0, 50, func(_, _ int64, _ string) bool { return false })
+}
+
+func TestGatedStoreOpensWithTheNewSchema(t *testing.T) {
+ cx := newClaimCase(t)
+ if err := cx.st.TouchLastSeen(claimFxOwner, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// opSeedScale writes the scale fixture in one transaction: 20,000 people,
+// 60,000 sessions over 30 days, 2,000 accounts with their memberships, 8,000
+// apps and 200,000 audit rows, 50 of them of a rare kind.
+func opSeedScale(t *testing.T, s *Store, now time.Time) (account int64) {
+ t.Helper()
+ db, ok := s.db.(*sql.DB)
+ if !ok {
+ t.Fatalf("store handle is %T", s.db)
+ }
+ tx, err := db.Begin()
+ opMust(t, err)
+ defer tx.Rollback()
+ exec := func(stmt *sql.Stmt, args ...any) {
+ if _, err := stmt.Exec(args...); err != nil {
+ t.Fatal(err)
+ }
+ }
+ prep := func(q string) *sql.Stmt {
+ st, err := tx.Prepare(q)
+ opMust(t, err)
+ return st
+ }
+ day := int64(24 * 60 * 60)
+ n := now.Unix()
+ users := prep(`INSERT INTO users (address, created_at, last_seen) VALUES (?, ?, ?)`)
+ for i := 0; i < 20000; i++ {
+ seen := int64(0)
+ if i%3 == 0 {
+ seen = n - int64(i%40)*day
+ }
+ exec(users, fmt.Sprintf("p%05d@example.com", i), n-int64(i)*900, seen)
+ }
+ sessions := prep(`INSERT INTO sessions (token_hash, address, created_at, expires_at) VALUES (?, ?, ?, ?)`)
+ for i := 0; i < 60000; i++ {
+ at := n - int64(i)*43
+ exec(sessions, fmt.Sprintf("h%06d", i), fmt.Sprintf("p%05d@example.com", (i*7)%20000), at, at+30*day)
+ }
+ accounts := prep(`INSERT INTO accounts (id, sqid, name, created_at) VALUES (?, ?, ?, ?)`)
+ members := prep(`INSERT INTO memberships (account_id, address, role, added_at) VALUES (?, ?, ?, ?)`)
+ for i := 0; i < 2000; i++ {
+ id := int64(1000 + i)
+ exec(accounts, id, fmt.Sprintf("s%04d", i), fmt.Sprintf("shop %d", i), n-int64(2000-i)*3600)
+ for j := 0; j < 10; j++ {
+ exec(members, id, fmt.Sprintf("p%05d@example.com", (i*10+j)%20000), RoleMember, n-int64(j))
+ }
+ }
+ for i := 0; i < 8000; i++ {
+ if _, err := insertAppRow(tx, newAppRow{AccountID: int64(1000 + i%2000), App: fmt.Sprintf("app%04d", i),
+ CreatedBy: fmt.Sprintf("p%05d@example.com", (i*3)%20000), CreatedAt: n - int64(i)*600}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ audit := prep(`INSERT INTO audit (account_id, app, address, action, detail, created_at) VALUES (?, ?, ?, ?, ?, ?)`)
+ kinds := []string{"promote", "rollback", "signin", "rename", "domain-add", "invite-sent"}
+ for i := 0; i < 200000; i++ {
+ action := kinds[i%len(kinds)]
+ if i%4000 == 0 {
+ action = "account-deleted"
+ }
+ exec(audit, int64(1000+i%2000), fmt.Sprintf("app%04d", i%8000), fmt.Sprintf("p%05d@example.com", i%20000),
+ action, "detail", n-int64(200000-i)*10)
+ }
+ opMust(t, tx.Commit())
+ return 1000 + 7
+}
+
+// opCountsScaleBudget is OperatorCounts' own budget at scale. Its active
+// 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.
+const opCountsScaleBudget = 100 * time.Millisecond
+
+// TestOperatorCountsAtScale times every operator read on a production-sized
+// store. Each is printed; under CI each must answer within 20 ms, except
+// OperatorCounts (opCountsScaleBudget).
+func TestOperatorCountsAtScale(t *testing.T) {
+ s := openOpStore(t)
+ acct := opSeedScale(t, s, opNow)
+ var rare int
+ opMust(t, s.db.QueryRow(`SELECT COUNT(*) FROM audit WHERE action = 'account-deleted'`).Scan(&rare))
+ if rare != 50 {
+ t.Fatalf("rare kind has %d rows, want 50", rare)
+ }
+ exclude := []string{"promote", "rollback", "signin", "account-deleted", "invite-sent"}
+ reads := []struct {
+ name string
+ run func() (int, error)
+ }{
+ {"OperatorCounts", func() (int, error) {
+ c, err := s.OperatorCounts(opNow)
+ return c.People, err
+ }},
+ {"NewPeoplePerDay", func() (int, error) { d, err := s.NewPeoplePerDay(opNow, 30); return len(d), err }},
+ {"NewestPeople", func() (int, error) { p, err := s.NewestPeople(10); return len(p), err }},
+ {"PeoplePage", func() (int, error) { p, _, err := s.PeoplePage("", 0, 50); return len(p), err }},
+ {"PeoplePage search", func() (int, error) { p, _, err := s.PeoplePage("p19", 0, 50); return len(p), err }},
+ {"AccountsPage", func() (int, error) { p, _, err := s.AccountsPage("", 0, 50); return len(p), err }},
+ {"feed all", func() (int, error) { f, err := s.ActivityFeed(ActivityFilter{}, 0, 50); return len(f), err }},
+ {"feed all, older", func() (int, error) { f, err := s.ActivityFeed(ActivityFilter{}, 100000, 50); return len(f), err }},
+ {"feed account", func() (int, error) {
+ f, err := s.ActivityFeed(ActivityFilter{AccountID: acct}, 0, 50)
+ return len(f), err
+ }},
+ {"feed deploys", func() (int, error) {
+ f, err := s.ActivityFeed(ActivityFilter{Actions: deployActions}, 0, 50)
+ return len(f), err
+ }},
+ {"feed deploys, account", func() (int, error) {
+ f, err := s.ActivityFeed(ActivityFilter{AccountID: acct, Actions: deployActions}, 0, 50)
+ return len(f), err
+ }},
+ {"feed rare kind", func() (int, error) {
+ f, err := s.ActivityFeed(ActivityFilter{Actions: []string{"account-deleted"}}, 0, 50)
+ return len(f), err
+ }},
+ {"feed rare kind, account", func() (int, error) {
+ f, err := s.ActivityFeed(ActivityFilter{AccountID: 1000, Actions: []string{"account-deleted"}}, 0, 50)
+ return len(f), err
+ }},
+ {"feed other", func() (int, error) {
+ f, err := s.ActivityFeed(ActivityFilter{Exclude: exclude}, 0, 50)
+ return len(f), err
+ }},
+ {"feed other, account", func() (int, error) {
+ f, err := s.ActivityFeed(ActivityFilter{AccountID: acct, Exclude: exclude}, 0, 50)
+ return len(f), err
+ }},
+ }
+ for _, r := range reads {
+ // The first call warms the page cache, as a running console's is.
+ if _, err := r.run(); err != nil {
+ t.Fatalf("%s: %v", r.name, err)
+ }
+ start := time.Now()
+ got, err := r.run()
+ took := time.Since(start)
+ if err != nil {
+ t.Fatalf("%s: %v", r.name, err)
+ }
+ if got == 0 {
+ t.Errorf("%s returned nothing", r.name)
+ }
+ t.Logf("%-24s %8.2f ms (%d)", r.name, float64(took.Microseconds())/1000, got)
+ budget := 20 * time.Millisecond
+ if r.name == "OperatorCounts" {
+ budget = opCountsScaleBudget
+ }
+ if perfEnforce() && took > budget {
+ t.Errorf("%s took %v, over %v", r.name, took, budget)
+ }
+ }
+}
diff --git a/internal/console/store.go b/internal/console/store.go
index 229e79aa2..8f289747b 100644
--- a/internal/console/store.go
+++ b/internal/console/store.go
@@ -633,7 +633,11 @@ func (s *Store) migrate() error {
return err
}
// Plans 6a's billing state (billingstore.go), for the same reason.
- return s.migrateBilling()
+ if err := s.migrateBilling(); err != nil {
+ return err
+ }
+ // The operator pages' column and indexes (opstore.go), for the same reason.
+ return s.migrateOperatorPages()
}
// mailCountsBackfillVersion is the user_version this migration stamps. The