Phase 13, part 9: running at scale, and the proof

The multi-tenant edition starts. compose.multi.yaml runs several copies
behind Caddy, with the managed Postgres and Garage outside. A test walks
every page and fragment, with ids filled in, and every MCP tool, as one
team, and none shows another team's data or changes it; another has three
copies share six teams' work, each team's turn once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-25 12:46:01 -07:00
co-authored by Claude Opus 5.5
parent b8a64e258a
commit f4c31c9fa3
13 changed files with 453 additions and 14 deletions
+1
View File
@@ -18,3 +18,4 @@ dismissed.json
server.env
server/certs/*
!server/certs/.keep
multi.env
+31 -1
View File
@@ -55,7 +55,7 @@ tools over MCP, approvals, limits and visibility, and the JSON API. Schema
39.
**Phase 13 (multi-tenant) is under way** on branch `phase13`, with a
Postgres schema per team (decided 2026-11-26); parts 1–8 are built.
Postgres schema per team (decided 2026-11-26); parts 1–9 are built.
**Phase 12 (signing in with the Core, OIDC) is set aside for now**
(2026-11-26): before it starts, the user will share the Federated Core's
@@ -2930,6 +2930,36 @@ stand.
schema and role, its agents and their keys, memberships, sessions and
row. People keep their accounts.
**Part 9 built 2026-11-26** on `phase13`. **The multi-tenant edition
starts.**
- `supermarket` with `SUPERMARKET_MODE=multi` opens the teams' schemas,
skips what's only the local edition's (the old app's import, the setup
link, Hermes' socket), and recovers each team's interrupted drafts at
start.
- `compose.multi.yaml`: several copies of the app (`SUPERMARKET_COPIES`,
3 by default) with only scratch space of their own, behind Caddy
(`server/Caddyfile.multi`: every copy found by name, round robin, health
checked); the managed Postgres and Garage outside, in `multi.env`.
Everything a request needs is in Postgres (sessions, OAuth sign-ins under
way, locks), the files in the object storage. Each team's pool is small;
a PgBouncer in front must pool by session (each connection carries its
team's role and search path). The platform page (part 7) shows each
team's size and failures.
- **Done when, checked** (on Postgres, `TestTeamsIsolatedEverywhere`): two
teams, each filled with data marked as its own (profile, Market,
signals, prospects, drafts, suppression, settings, keys). As team A's
owner, every GET route there is, with its ids filled in (1, 2, 3) and
with and without a site and a search (over 300 requests), and as A's
agent with every scope, every MCP tool (over 30, three sets of
arguments): none shows B's data, and A's deletions aimed at B's ids
change nothing of B's. A control checks that B sees its own marker on
the same pages, so the check can tell. `TestThreeCopiesShareTheWork`:
three copies on one database run a round of a job for six teams at once;
each team's turn runs exactly once, the copies share them, and any copy
answers a team's requests.
- Not run yet: the whole multi-tenant edition in Docker with Garage (the
server edition's was, in Phase 10).
1. **Teams everywhere.**
- Every table that holds a company's data gets `team_id`, and its
unique keys include it. The settings table's key becomes
+27
View File
@@ -266,6 +266,33 @@ computer.
Hermes and the CRM bridge use the local edition's socket; on a server, agents
come with their own keys (Phase 11 in PLAN.md).
## The multi-tenant edition
Many teams at one address, each working on one website domain, with its
data in its own Postgres schema and its own database role. People sign up
at `/signup`, belong to as many teams as they like, and switch between them
from the sidebar. A team proves its domain (a DNS record, a file on the
site, or its Search Console property) before Supermarket crawls, reads or
publishes to the site.
`compose.multi.yaml` runs several copies of the app (3 by default) behind
Caddy; the cloud's managed Postgres and the object storage (Garage) are
outside it, named in `multi.env` (the file's top lists what it holds). The
database user needs `CREATEROLE`, to give each team its role. Everything a
request needs is in Postgres and the files are in the object storage, so
any copy answers any request; background work is shared between the copies
team by team.
Connection pooling: each team has a small pool of its own (4 connections,
idle ones closed after a minute). A PgBouncer in front must use session
pooling, since each connection carries its team's role and search path.
The people running the service, listed in `SUPERMARKET_PLATFORM_ADMINS`,
see every team at `/platform` (with two-factor sign-in): their size, people
and what failed lately; they can suspend a team, resend its invitations,
release a domain, and *view as* a team with a reason, for at most an hour,
recorded in the team's own log.
## Development
Requires Go (see `go.mod`).
+22 -3
View File
@@ -241,8 +241,11 @@ func run(log *slog.Logger) error {
if err != nil {
return err
}
multi := cfg.Edition == config.Multi
if !alone {
log.Info("jobs: other copies of Supermarket are running; work they have under way is left to them")
} else if multi {
// Each team's, once the teams are open (below).
} else if n, err := content.RecoverInterrupted(database); err != nil {
return err
} else if n > 0 {
@@ -301,13 +304,17 @@ func run(log *slog.Logger) error {
// The import never stops the app: a bad old file is reported on the
// overview page instead.
status, importErr := legacy.Import(database, sec, filepath.Join(dataDir, "import"))
var status *legacy.Status
var importErr error
if !multi {
status, importErr = legacy.Import(database, sec, filepath.Join(dataDir, "import"))
}
if importErr != nil {
log.Error("importing the old app's data", "err", importErr)
} else if status != nil {
log.Info("imported the old app's data", "summary", strings.Join(status.Summary, "; "))
}
if status == nil && importErr == nil {
if status == nil && importErr == nil && !multi {
status, _ = legacy.LoadStatus(database)
}
@@ -328,6 +335,18 @@ func run(log *slog.Logger) error {
ImportStatus: status,
ImportErr: importErr,
}
// The multi-tenant edition: each team's data in its own schema.
if multi {
teams, err := database.Teams()
if err != nil {
return err
}
defer teams.Close()
srv.Teams, srv.Platform = teams, database
if alone {
srv.RecoverTeams(context.Background())
}
}
// Agents reach /mcp with their keys. On the local edition, mcp-token is
// the key of the built-in Hermes agent.
srv.MCP = mcpserver.Handler(database, version, srv.AgentAuth, srv.AgentTools)
@@ -342,7 +361,7 @@ func run(log *slog.Logger) error {
}
// A new server has no owner yet: a link to create one.
if cfg.Edition != config.Local {
if cfg.Edition == config.Server {
if link, err := setupLink(database, publicURL); err != nil {
return err
} else if link != "" {
+79
View File
@@ -0,0 +1,79 @@
# Supermarket's multi-tenant edition: many teams at one address, each
# working on its own domain, with its data in its own Postgres schema.
# Several copies of the app run behind Caddy; Postgres and the object
# storage are outside (the cloud's managed Postgres, and Garage), named in
# multi.env:
#
# docker compose -f compose.multi.yaml --env-file multi.env up -d --build
#
# multi.env holds:
# SUPERMARKET_DOMAIN the address people open, e.g. app.example.com
# SUPERMARKET_DATABASE_URL postgres://…; its user needs CREATEROLE
# SUPERMARKET_SECRET_KEY supermarket secret-key makes one: keep a copy
# SUPERMARKET_MAIL_URL smtp://… or smtps://…
# SUPERMARKET_STORAGE s3://bucket/prefix
# SUPERMARKET_S3_ENDPOINT https://… (Garage's S3 API)
# SUPERMARKET_S3_ACCESS_KEY, SUPERMARKET_S3_SECRET_KEY
# SUPERMARKET_PLATFORM_ADMINS the platform admins' emails, comma-separated
# SUPERMARKET_COPIES how many copies of the app (default 3)
name: supermarket-multi
services:
supermarket:
build:
context: .
args:
VERSION: ${SUPERMARKET_VERSION:-dev}
image: supermarket:multi
restart: unless-stopped
init: true
user: "10001:10001"
deploy:
replicas: ${SUPERMARKET_COPIES:-3}
environment:
SUPERMARKET_MODE: multi
SUPERMARKET_PUBLIC_URL: https://${SUPERMARKET_DOMAIN:?}
SUPERMARKET_DATABASE_URL: ${SUPERMARKET_DATABASE_URL:?}
SUPERMARKET_SECRET_KEY: ${SUPERMARKET_SECRET_KEY:?}
SUPERMARKET_MAIL_URL: ${SUPERMARKET_MAIL_URL:?}
SUPERMARKET_MAIL_FROM: ${SUPERMARKET_MAIL_FROM:-}
SUPERMARKET_STORAGE: ${SUPERMARKET_STORAGE:?}
SUPERMARKET_S3_ENDPOINT: ${SUPERMARKET_S3_ENDPOINT:?}
SUPERMARKET_S3_REGION: ${SUPERMARKET_S3_REGION:-garage}
SUPERMARKET_S3_ACCESS_KEY: ${SUPERMARKET_S3_ACCESS_KEY:?}
SUPERMARKET_S3_SECRET_KEY: ${SUPERMARKET_S3_SECRET_KEY:?}
SUPERMARKET_PLATFORM_ADMINS: ${SUPERMARKET_PLATFORM_ADMINS:-}
TZ: ${SUPERMARKET_TZ:-UTC}
# Scratch only (sites' clones, previews): everything a request needs is
# in Postgres, and files are in the object storage, so any copy can
# answer any request.
tmpfs:
- /data:uid=10001,gid=10001,mode=0700
- /tmp
read_only: true
cap_drop:
- ALL
security_opt:
- no-new-privileges:true
caddy:
image: caddy:2-alpine
restart: unless-stopped
ports:
- "${SUPERMARKET_HTTP_PORT:-80}:80"
- "${SUPERMARKET_HTTPS_PORT:-443}:443"
- "${SUPERMARKET_HTTPS_PORT:-443}:443/udp"
environment:
SUPERMARKET_DOMAIN: ${SUPERMARKET_DOMAIN:?}
SUPERMARKET_ACME: ${SUPERMARKET_ACME:-}
SUPERMARKET_TLS: ${SUPERMARKET_TLS:-}
volumes:
- ./server/Caddyfile.multi:/etc/caddy/Caddyfile:ro
- ./server/certs:/certs:ro
- caddydata:/data
- caddyconfig:/config
depends_on: [supermarket]
volumes:
caddydata:
caddyconfig:
+3 -9
View File
@@ -324,15 +324,9 @@ func NewKey() (string, error) {
return hex.EncodeToString(b), nil
}
// Ready says whether this version of Supermarket can run the edition. The
// server and multi-tenant editions are planned (PLAN.md, Phases 9–14) and
// come in steps; until they're built, only the settings are checked.
func (c *Config) Ready() error {
if c.Edition != Multi {
return nil
}
return fmt.Errorf("This version of Supermarket runs the local and server editions: the %s edition isn't built yet. Its settings are fine", c.Edition.Name())
}
// Ready says whether this version of Supermarket can run the edition:
// every edition, since Phase 13.
func (c *Config) Ready() error { return nil }
// Item is one line of the settings, to show.
type Item struct {
+1 -1
View File
@@ -121,7 +121,7 @@ func TestMulti(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if err := c.Ready(); err == nil || !strings.Contains(err.Error(), "isn't built yet") {
if err := c.Ready(); err != nil {
t.Fatal(err)
}
s := c.Storage
+2
View File
@@ -112,6 +112,7 @@ type routes struct {
s *Server
mux *http.ServeMux
unmapped []string
patterns []string // every route, for the tests that walk them all
}
// HandleFunc registers a handler: a method expression such as
@@ -147,6 +148,7 @@ func (rt *routes) Handle(pattern string, h http.Handler) {
rt.unmapped = append(rt.unmapped, pattern)
return
}
rt.patterns = append(rt.patterns, pattern)
rt.mux.Handle(pattern, rt.s.allow(area, rt.s.guardDomain(pattern, rt.s.audited(pattern, h))))
}
+13
View File
@@ -12,6 +12,7 @@ import (
"supermarket/internal/appmail"
"supermarket/internal/audit"
"supermarket/internal/content"
"supermarket/internal/storage"
"supermarket/internal/transfer"
"supermarket/internal/users"
@@ -297,3 +298,15 @@ func (s *Server) purgeTeam(ctx context.Context, id int64) error {
}
func teamFilesPrefix(id int64) string { return "teams/" + strconv.FormatInt(id, 10) }
// RecoverTeams marks each team's drafts left "publishing" by a stopped app
// as failed, for review (the multi-tenant edition's start).
func (s *Server) RecoverTeams(ctx context.Context) {
s.eachTeam(ctx, func(_ context.Context, ts *Server) {
if n, err := content.RecoverInterrupted(ts.DB); err != nil {
ts.Log.Error("recovering drafts", "team", ts.team(), "err", err)
} else if n > 0 {
ts.Log.Warn("drafts were being published when Supermarket stopped; marked failed for review", "team", ts.team(), "count", n)
}
})
}
+186
View File
@@ -0,0 +1,186 @@
package web
import (
"context"
"net/http"
"net/url"
"regexp"
"sort"
"strings"
"testing"
"time"
"supermarket/internal/content"
"supermarket/internal/inventory"
"supermarket/internal/profile"
"supermarket/internal/prospects"
"supermarket/internal/signals"
"supermarket/internal/users"
)
// marker is in everything team B has: it must never reach team A.
const marker = "ZEBRAMARK"
// seedTeam fills a team with data carrying a marker, in many tables.
func seedTeam(t *testing.T, ts *Server, mark string) {
t.Helper()
d := ts.DB
must := func(err error) {
t.Helper()
if err != nil {
t.Fatal(err)
}
}
must(profile.Save(d, &profile.Profile{Name: mark + " Inc", Description: mark + " widgets", Keywords: []string{mark}}))
for i := 0; i < 3; i++ {
must(inventory.Save(d, &inventory.Entry{Name: mark + " rival " + string(rune('a'+i)), Relationship: "competitor", Description: mark}))
}
sig := &signals.Signal{Name: mark + " signal", Hypothesis: mark}
must(signals.Save(d, sig))
_, _, err := prospects.AddCompany(d, prospects.Company{Name: mark + " Corp", Domain: strings.ToLower(mark) + ".example", Source: "manual"}, time.Now())
must(err)
_, _, err = prospects.AddContact(d, prospects.Contact{FirstName: mark, LastName: "Lee", Email: "kim@" + strings.ToLower(mark) + ".example", Source: "manual"}, time.Now())
must(err)
_, err = content.CreateDrafts(d, []content.Draft{{Channel: content.ChannelX, Content: mark + " post"}, {Channel: content.ChannelLinkedIn, Content: mark + " update"}})
must(err)
must(prospects.Suppress(d, "domain", strings.ToLower(mark)+"-blocked.example", mark, time.Now()))
must(d.PutJSON("seo:indexnow-key", mark))
must(ts.Secrets.Set(map[string]string{"hunter.api_key": mark}))
}
// sampleValues fill a route's wildcards: ids and names that exist in the
// other team's schema.
var wildcard = regexp.MustCompile(`\{([a-z]+)(\.\.\.)?\}`)
func fillPattern(pattern, v string) string {
return wildcard.ReplaceAllStringFunc(pattern, func(w string) string {
switch {
case strings.Contains(w, "provider"):
return "x"
case strings.Contains(w, "kind"):
return "company"
case strings.Contains(w, "month"):
return "2026-11"
case strings.Contains(w, "token"):
return "nothing"
}
return v
})
}
// TestTeamsIsolatedEverywhere is Phase 13's proof: team A, signed in as its
// owner and through its agent with every scope, reaches every page,
// fragment and tool, and never sees team B's data, nor changes it.
func TestTeamsIsolatedEverywhere(t *testing.T) {
s, h := newMultiEdition(t)
a, _, ac := newTeam(t, s, "Acme", "olu@acme.example")
b, _, bc := newTeam(t, s, "Bolt", "bea@bolt.example")
ta, _ := s.forTeam(a.ID)
tb, _ := s.forTeam(b.ID)
seedTeam(t, ta, "OWNMARK")
seedTeam(t, tb, marker)
// Both prove their domains, so nothing is held back by that.
users.Prove(s.platform(), a.ID, "dns", time.Now())
users.Prove(s.platform(), b.ID, "dns", time.Now())
leaks := func(where, body string) {
t.Helper()
if strings.Contains(body, marker) || strings.Contains(strings.ToLower(body), strings.ToLower(marker)) {
i := strings.Index(strings.ToLower(body), strings.ToLower(marker))
t.Errorf("%s shows team B's data: …%s…", where, body[max(0, i-80):min(len(body), i+80)])
}
}
// The check can see a leak: B's own owner sees the marker.
for _, p := range []string{"/market", "/signals", "/posts", "/prospects", "/settings/profile", "/search?q=" + marker[:5]} {
if body := as(h, bc, http.MethodGet, p, nil).Body.String(); !strings.Contains(body, marker) {
t.Errorf("control: B's own %s lacks the marker", p)
}
}
// Every page and fragment (GET), with its ids filled in.
patterns := append([]string(nil), s.st().patterns...)
sort.Strings(patterns)
n := 0
for _, p := range patterns {
method, path, _ := strings.Cut(p, " ")
if method != http.MethodGet || strings.HasPrefix(path, "/static") || path == "/mcp" {
continue
}
for _, v := range []string{"1", "2", "3"} {
u := strings.TrimSuffix(fillPattern(path, v), "{$}")
for _, q := range []string{"", "?site=0", "?q=" + url.QueryEscape(marker[:5])} {
rec := as(h, ac, http.MethodGet, u+q, nil)
leaks("GET "+u+q, rec.Body.String())
n++
}
}
}
if n < 300 {
t.Errorf("only %d requests", n)
}
// Every MCP tool, as A's agent with every scope.
all := map[string]users.Access{}
for _, g := range agentGrants() {
all[g.ID] = users.Edit
}
_, key := newAgentIn(t, ta, "A's agent", all)
_, tools := mcpTools(h, key)
if len(tools) < 30 {
t.Fatalf("only %d tools", len(tools))
}
for _, tool := range tools {
for _, args := range []map[string]any{{}, {"id": 1, "site": 0, "status": "waiting", "entry": marker + " rival a", "tab": "drafts"},
{"id": 2, "draft_id": 1, "message_id": 1, "contact_id": 1, "change_id": 1}} {
text, _ := mcpCall(t, h, key, tool, args)
leaks("tool "+tool, text)
}
}
// Changes by A, aimed at B's ids, change nothing of B's.
for _, p := range []string{"/market/1/delete", "/market/2/delete", "/signals/1/delete", "/drafts/1/discard", "/drafts/2/discard",
"/prospects/company/1/reject", "/prospects/contact/1/delete"} {
as(h, ac, http.MethodPost, p, url.Values{})
}
if list, _ := inventory.List(tb.DB, ""); len(list) != 3 {
t.Errorf("B's Market: %d", len(list))
}
if list, _ := signals.List(tb.DB); len(list) != 1 {
t.Errorf("B's signals: %d", len(list))
}
if list, _ := content.ListDrafts(tb.DB, 10, content.StatusDraft); len(list) != 2 {
t.Errorf("B's drafts: %d", len(list))
}
if cs, ps, _ := prospects.Review(tb.DB, prospects.StatusNew, 0, 10); len(cs) != 1 || len(ps) != 1 {
t.Errorf("B's prospects: %d %d", len(cs), len(ps))
}
if tb.Secrets.Get("hunter.api_key") != marker {
t.Error("B's key changed")
}
// And the background jobs: one round of each, for both teams, leaves
// B's data B's (and A's job never ran on B's schema: B's drafts are
// where they were).
sent := &fakePosts{}
s.testPublisher = nil
_ = sent
for _, name := range []string{"scheduler", "accounts"} {
s.jobDo(t.Context(), name, func(ctx context.Context, ts *Server) {
if name == "scheduler" {
ts.publishDue(ctx, time.Now())
}
})
}
if list, _ := inventory.List(ta.DB, ""); strings.Contains(entryNames(list), marker) {
t.Error("B's entries in A's schema")
}
}
func entryNames(list []inventory.Entry) string {
var b strings.Builder
for _, e := range list {
b.WriteString(e.Name + " ")
}
return b.String()
}
+2
View File
@@ -94,6 +94,7 @@ type state struct {
runner *jobs.Runner
setupDone atomic.Bool // the team has its owner (server edition)
rotation atomic.Uint64 // which team's turn comes first (eachTeam)
patterns []string // every route's pattern
mu sync.Mutex
copies map[int64]*Server // each team's Server
@@ -574,6 +575,7 @@ func (s *Server) Handler() (http.Handler, error) {
if err := mux.err(); err != nil {
return nil, err
}
s.st().patterns = mux.patterns
return s.guard(s.csrf(s.sessions(mux.mux))), nil
}
+66
View File
@@ -11,6 +11,7 @@ import (
"regexp"
"strconv"
"strings"
"sync"
"testing"
"time"
@@ -551,3 +552,68 @@ func sessionIn(t *testing.T, s *Server, u *users.User, team int64) *http.Cookie
}
return &http.Cookie{Name: sessionCookie, Value: tok}
}
// Three copies of the app, behind a load balancer, share the teams' work:
// each team's turn runs once, and the copies each take some.
func TestThreeCopiesShareTheWork(t *testing.T) {
s, h := newMultiEdition(t)
var ids []int64
for i := 0; i < 6; i++ {
tm, _, _ := newTeam(t, s, "Team"+strconv.Itoa(i), "o"+strconv.Itoa(i)+"@x.example")
ids = append(ids, tm.ID)
}
copies := []*Server{s}
for i := 0; i < 2; i++ {
teams, err := s.platform().Teams()
if err != nil {
t.Fatal(err)
}
t.Cleanup(teams.Close)
c := &Server{DB: s.platform(), Platform: s.platform(), Teams: teams, Secrets: s.Secrets, Config: s.Config, DataDir: t.TempDir(),
PublicURL: s.PublicURL, Version: "test", Log: s.Log}
if _, err := c.Handler(); err != nil {
t.Fatal(err)
}
copies = append(copies, c)
}
var mu sync.Mutex
runs := map[int64]int{} // team → turns
byCopy := map[int]int{} // copy → turns it ran
var wg sync.WaitGroup
for i, c := range copies {
wg.Add(1)
go func() {
defer wg.Done()
c.jobDo(context.Background(), "scheduler", func(ctx context.Context, ts *Server) {
time.Sleep(150 * time.Millisecond) // a turn takes a while
mu.Lock()
runs[ts.team()]++
byCopy[i]++
mu.Unlock()
})
}()
}
wg.Wait()
for _, id := range ids {
if runs[id] != 1 {
t.Errorf("team %d ran %d times", id, runs[id])
}
}
shared := 0
for _, n := range byCopy {
if n > 0 {
shared++
}
}
if shared < 2 {
t.Errorf("one copy did it all: %v", byCopy)
}
// Any copy answers any request: a team's owner, signed in, on another
// copy.
_, _, c0 := newTeamOwnerCookie(t, s, ids[0])
h2, _ := copies[2].Handler()
if rec := as(h2, c0, http.MethodGet, "/settings/profile", nil); rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "Team0") {
t.Errorf("on another copy: %d", rec.Code)
}
_ = h
}
+20
View File
@@ -0,0 +1,20 @@
# Caddy in front of the multi-tenant edition's copies (compose.multi.yaml).
{
{$SUPERMARKET_ACME}
}
{$SUPERMARKET_DOMAIN} {
{$SUPERMARKET_TLS}
encode zstd gzip
header Strict-Transport-Security "max-age=31536000"
# Every copy of the app, found by name, round robin; a copy that stops
# answering is left out until it's healthy.
reverse_proxy {
dynamic a supermarket 8080 {
refresh 10s
}
lb_policy round_robin
health_uri /healthz
health_interval 10s
}
}