From c5bdd4230bebc58615b4160d5939e94033c5f358 Mon Sep 17 00:00:00 2001 From: Numinous Forge Date: Sat, 5 Sep 2026 20:19:23 +0000 Subject: [PATCH] Forge task 66257843079c685ec7a310c33395c780 Verified tree: d48f7ad10dae36a444610f59abca9c04d1b4862d Policy: 6e7f097750c960348238b82c6517482d1698c8bb0785146572e36cae2ea127b8 --- CHANGELOG.md | 4 + coordinator/api/provider.go | 55 +++-- .../api/provider_reputation_metadata_test.go | 75 ++++++ ...provider_reputation_reconnect_edge_test.go | 135 +++++++++++ .../api/provider_reputation_reconnect_test.go | 137 +++++++++++ coordinator/api/server.go | 9 - coordinator/registry/persistence.go | 60 ++--- coordinator/store/interface_domains.go | 22 ++ coordinator/store/memory.go | 87 +++++++ coordinator/store/postgres.go | 88 +++++++ coordinator/store/provider_se_key_test.go | 229 ++++++++++++++++++ docs/architecture/storage.md | 14 +- 12 files changed, 838 insertions(+), 77 deletions(-) create mode 100644 coordinator/api/provider_reputation_metadata_test.go create mode 100644 coordinator/api/provider_reputation_reconnect_edge_test.go create mode 100644 coordinator/api/provider_reputation_reconnect_test.go create mode 100644 coordinator/store/provider_se_key_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 853c1255a2..6bce30f870 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Changelog +## Unreleased — reconnect reputation keyed to Secure Enclave identity + +- Restore a reconnecting provider's reputation and account linkage from a live store lookup keyed to the attested Secure Enclave public key, excluding the registering session's own row, so a restart, lid-close, or reconnect no longer resets standing to the 0.60 cold-start default. Device metadata comes from the newest row and reputation from the newest row that earned it, with a deterministic `last_seen`/`id` tie-break shared by the memory and PostgreSQL stores. Hardware trust is still re-earned live on every connection. + ## Unreleased — provider console entry - Open the provider workspace directly from the console home page, removing the Consumer/Provider selection page. Keep chat and API access in workspace navigation. diff --git a/coordinator/api/provider.go b/coordinator/api/provider.go index 8ac8befe38..b0d7d5957a 100644 --- a/coordinator/api/provider.go +++ b/coordinator/api/provider.go @@ -3167,35 +3167,42 @@ func (s *Server) verifyProviderAttestation(providerID string, provider *registry "trust_level", registry.TrustSelfSigned, ) - // Restore persisted state: if this provider was previously known (by serial - // number or SE key), restore trust level, reputation, and account linkage. - // Fresh attestation verification still runs (above), but stored reputation - // is preserved so routing quality is maintained across coordinator restarts. - if s.storedProviders != nil { - var storedRec *store.ProviderRecord - if result.SerialNumber != "" { - storedRec = s.storedProviders[result.SerialNumber] - } - if storedRec == nil && result.PublicKey != "" { - storedRec = s.storedProviders["sekey:"+result.PublicKey] - } - if storedRec != nil { + // Restore persisted state: if this provider was previously known, restore + // trust level, reputation, and account linkage. State is keyed to the + // attested Secure Enclave public key ALONE (never the serial number, which is + // shareable across a re-image / key rotation, and never the per-connection + // session id). Fresh attestation verification still runs (above); trust above + // self_signed is re-earned live and is capped away in RestoreProviderState. + // + // The lookup is a LIVE store read against the durable store (Postgres in dev + // and prod), keyed to the SE key. State a machine earns AFTER coordinator + // startup — the 123/123 and 52/52 clean records in the reset report — lands in + // the store on the earning session's row, so only a live read recovers it; a + // one-time startup snapshot never would. The registering session (providerID) + // is excluded so its own just-persisted row cannot shadow the prior history. + if s.store != nil && result.PublicKey != "" { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + storedRec, err := s.store.GetProviderBySEKey(ctx, result.PublicKey, providerID) + cancel() + if err != nil { + s.logger.Warn("failed to look up persisted provider state by SE key", + "provider_id", providerID, "error", err) + } else if storedRec != nil { s.registry.RestoreProviderState(provider, storedRec) s.logger.Info("restored persisted provider state", "provider_id", providerID, + "stored_id", storedRec.ID, "stored_serial", storedRec.SerialNumber, "stored_trust", storedRec.TrustLevel, ) } } - // Stage the durable Apple MDA cert chain from a LIVE store read. storedProviders - // above is a one-time startup snapshot — empty for the coordinator's whole life - // under the in-memory store used in prod — so it cannot surface a chain earned - // during this coordinator's lifetime. The store record survives provider - // disconnect, so a serial lookup recovers a chain a previous connection earned, - // letting attachCachedMDAProof reuse it (re-verified + SE-key-bound) instead of - // forcing a fresh, Apple-rate-limited DevicePropertiesAttestation round-trip. + // Stage the durable Apple MDA cert chain from a LIVE store read. The store + // record survives provider disconnect, so a serial lookup recovers a chain a + // previous connection earned during this coordinator's lifetime, letting + // attachCachedMDAProof reuse it (re-verified + SE-key-bound) instead of forcing + // a fresh, Apple-rate-limited DevicePropertiesAttestation round-trip. s.stageDurableMDAChain(provider, result.SerialNumber) // Deduplicate: if another provider connection exists from the same physical @@ -3438,10 +3445,10 @@ func (s *Server) ApplyLateSecurityInfo( // stageDurableMDAChain recovers a previously-earned Apple MDA cert chain from the // store (by serial) and stages it on the provider as a reuse candidate for this -// reconnect. The store record survives provider disconnect, so this works under -// the in-memory store used in prod — where the startup storedProviders snapshot is -// empty — as well as a durable store. Best-effort: a missing record / chain or a -// read error simply stages nothing, and a fresh attestation is requested. +// reconnect. The store record survives provider disconnect, so a chain earned by +// an earlier connection is recovered by this live read. Best-effort: a missing +// record / chain or a read error simply stages nothing, and a fresh attestation +// is requested. func (s *Server) stageDurableMDAChain(provider *registry.Provider, serial string) { if s.store == nil || serial == "" { return diff --git a/coordinator/api/provider_reputation_metadata_test.go b/coordinator/api/provider_reputation_metadata_test.go new file mode 100644 index 0000000000..12d22f1ce4 --- /dev/null +++ b/coordinator/api/provider_reputation_metadata_test.go @@ -0,0 +1,75 @@ +package api + +import ( + "context" + "io" + "log/slog" + "testing" + "time" + + "github.com/eigeninference/d-inference/coordinator/attestation" + "github.com/eigeninference/d-inference/coordinator/registry" + "github.com/eigeninference/d-inference/coordinator/store" +) + +// TestProviderReconnectRestoresMetadataAndReputationIndependently is the +// regression for the review finding that a reputation-bearing OLD row was +// selected for ALL restored state, discarding a newer session's fresh device +// metadata. Device metadata (account linkage) must come from the newest row; +// reputation must come from the newest row that actually earned it. A reconnect +// therefore keeps its fresh account AND recovers the standing under its SE key. +func TestProviderReconnectRestoresMetadataAndReputationIndependently(t *testing.T) { + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) + st := store.NewMemory(store.Config{}) + publicKey := testPublicKeyB64() + blob := createTestAttestationJSONWithSerial(t, "meta-device", publicKey) + identity, err := attestation.VerifyJSON(blob) + if err != nil || !identity.Valid { + t.Fatalf("invalid test attestation: %v, %+v", err, identity) + } + ctx := context.Background() + + // Older session earned standing under the account it was linked to then. + if err := st.UpsertProvider(ctx, store.ProviderRecord{ + ID: "old-session", SerialNumber: "meta-device", SEPublicKey: identity.PublicKey, + AccountID: "old-account", TrustLevel: "hardware", Attested: true, + LastSeen: time.Now().Add(-2 * time.Hour), + }); err != nil { + t.Fatal(err) + } + if err := st.UpsertReputation(ctx, "old-session", store.ReputationRecord{ + TotalJobs: 60, SuccessfulJobs: 58, FailedJobs: 2, + }); err != nil { + t.Fatal(err) + } + // Newer session re-linked the machine to a fresh account but has not yet + // flushed a reputation row (bare metadata row). + if err := st.UpsertProvider(ctx, store.ProviderRecord{ + ID: "new-session", SerialNumber: "meta-device", SEPublicKey: identity.PublicKey, + AccountID: "new-account", TrustLevel: "hardware", Attested: true, + LastSeen: time.Now().Add(-30 * time.Minute), + }); err != nil { + t.Fatal(err) + } + + reg := registry.New(logger) + srv := NewServer(reg, st, ServerConfig{}, logger) + t.Cleanup(srv.Close) + p := registerReconnectSession(t, reg, srv, "reconnect", publicKey, blob) + + p.Mu().Lock() + defer p.Mu().Unlock() + // Reputation is recovered from the earned (older) row... + if p.Reputation.TotalJobs != 60 || p.Reputation.SuccessfulJobs != 58 || p.Reputation.FailedJobs != 2 { + t.Fatalf("reputation should come from the earned row, got %+v", p.Reputation) + } + // ...while account linkage reflects the NEWEST device metadata, not the old + // reputation-bearing row. + if p.AccountID != "new-account" { + t.Fatalf("account linkage should track newest metadata row, got %q", p.AccountID) + } + // Hardware trust is still re-earned live. + if p.TrustLevel != registry.TrustSelfSigned || p.MDAVerified { + t.Fatalf("reconnect must re-earn hardware trust: trust=%s mda=%v", p.TrustLevel, p.MDAVerified) + } +} diff --git a/coordinator/api/provider_reputation_reconnect_edge_test.go b/coordinator/api/provider_reputation_reconnect_edge_test.go new file mode 100644 index 0000000000..0492437ecd --- /dev/null +++ b/coordinator/api/provider_reputation_reconnect_edge_test.go @@ -0,0 +1,135 @@ +package api + +import ( + "context" + "io" + "log/slog" + "testing" + "time" + + "github.com/eigeninference/d-inference/coordinator/attestation" + "github.com/eigeninference/d-inference/coordinator/protocol" + "github.com/eigeninference/d-inference/coordinator/registry" + "github.com/eigeninference/d-inference/coordinator/store" +) + +// registerReconnectSession drives one registration + attestation verification +// against an already-populated store, mirroring the reconnect hot path without a +// live WebSocket. It returns the freshly registered provider. +func registerReconnectSession(t *testing.T, reg *registry.Registry, srv *Server, sessionID, publicKey string, blob []byte) *registry.Provider { + t.Helper() + msg := &protocol.RegisterMessage{Type: protocol.TypeRegister, PublicKey: publicKey, + Attestation: blob, Version: minProviderVersionForReconnectAttestation} + p := reg.Register(sessionID, nil, msg) + srv.verifyProviderAttestation(sessionID, p, msg) + return p +} + +// TestProviderReconnectWithMissingReputationRow covers a provider whose prior +// record is present and SE-key-matched but has NO persisted reputation row (the +// row was pruned, or the machine never accumulated one). Restoration must not +// invent counters or fail — it recovers account linkage from the matched record +// and leaves reputation at the neutral cold-start default. Trust is still +// re-earned live. +func TestProviderReconnectWithMissingReputationRow(t *testing.T) { + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) + st := store.NewMemory(store.Config{}) + publicKey := testPublicKeyB64() + blob := createTestAttestationJSONWithSerial(t, "missing-rep-device", publicKey) + identity, err := attestation.VerifyJSON(blob) + if err != nil || !identity.Valid { + t.Fatalf("invalid test attestation: %v, %+v", err, identity) + } + ctx := context.Background() + // Prior session known by the attested SE key, with account linkage but no + // reputation row. + if err := st.UpsertProvider(ctx, store.ProviderRecord{ + ID: "prior-session", SerialNumber: "missing-rep-device", + SEPublicKey: identity.PublicKey, AccountID: "owner-account", + TrustLevel: "hardware", Attested: true, LastSeen: time.Now(), + }); err != nil { + t.Fatal(err) + } + + reg := registry.New(logger) + srv := NewServer(reg, st, ServerConfig{}, logger) + t.Cleanup(srv.Close) + p := registerReconnectSession(t, reg, srv, "new-session", publicKey, blob) + + p.Mu().Lock() + defer p.Mu().Unlock() + if p.Reputation.TotalJobs != 0 || p.Reputation.SuccessfulJobs != 0 || p.Reputation.ChallengesPassed != 0 { + t.Fatalf("missing reputation row should leave neutral defaults, got %+v", p.Reputation) + } + if p.AccountID != "owner-account" { + t.Fatalf("account linkage not restored from SE-key match: %q", p.AccountID) + } + if p.TrustLevel != registry.TrustSelfSigned || p.MDAVerified { + t.Fatalf("reconnect must re-earn hardware trust: trust=%s mda=%v", p.TrustLevel, p.MDAVerified) + } +} + +// TestProviderReconnectRepeatedRestoresLatestBySEKey covers a laptop that +// reconnects several times: each reconnect must recover the most recent standing +// bound to the attested SE key, and must ignore the currently registering +// session's own row so a just-persisted empty row cannot shadow the earned +// history. +func TestProviderReconnectRepeatedRestoresLatestBySEKey(t *testing.T) { + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) + st := store.NewMemory(store.Config{}) + publicKey := testPublicKeyB64() + blob := createTestAttestationJSONWithSerial(t, "repeat-device", publicKey) + identity, err := attestation.VerifyJSON(blob) + if err != nil || !identity.Valid { + t.Fatalf("invalid test attestation: %v, %+v", err, identity) + } + ctx := context.Background() + + seed := func(id string, seenAgo time.Duration, jobs int) { + if err := st.UpsertProvider(ctx, store.ProviderRecord{ + ID: id, SerialNumber: "repeat-device", SEPublicKey: identity.PublicKey, + TrustLevel: "hardware", Attested: true, LastSeen: time.Now().Add(-seenAgo), + }); err != nil { + t.Fatal(err) + } + if err := st.UpsertReputation(ctx, id, store.ReputationRecord{ + TotalJobs: jobs, SuccessfulJobs: jobs, + }); err != nil { + t.Fatal(err) + } + } + + // Two prior connections; the newer (session-2) carries the higher standing. + seed("session-1", 2*time.Hour, 10) + seed("session-2", 1*time.Hour, 40) + + reg := registry.New(logger) + srv := NewServer(reg, st, ServerConfig{}, logger) + t.Cleanup(srv.Close) + + // First reconnect: restores the latest-by-last_seen prior standing (40), not + // the stale session-1 (10). + p := registerReconnectSession(t, reg, srv, "reconnect-a", publicKey, blob) + p.Mu().Lock() + got := p.Reputation.TotalJobs + p.Mu().Unlock() + if got != 40 { + t.Fatalf("first reconnect should restore latest standing 40, got %d", got) + } + + // A newer prior session appears (the machine served more), plus a decoy row + // under the very id the next registration will use — carrying an absurd + // counter. The registering session must be excluded from its own lookup, so + // the decoy must never win. + seed("session-3", 30*time.Minute, 75) + seed("reconnect-b", 0, 999) + + // Second reconnect: restores session-3 (75), excluding reconnect-b's own row. + p2 := registerReconnectSession(t, reg, srv, "reconnect-b", publicKey, blob) + p2.Mu().Lock() + got2 := p2.Reputation.TotalJobs + p2.Mu().Unlock() + if got2 != 75 { + t.Fatalf("second reconnect should restore latest prior standing 75 (excluding own row), got %d", got2) + } +} diff --git a/coordinator/api/provider_reputation_reconnect_test.go b/coordinator/api/provider_reputation_reconnect_test.go new file mode 100644 index 0000000000..d444dc2c4d --- /dev/null +++ b/coordinator/api/provider_reputation_reconnect_test.go @@ -0,0 +1,137 @@ +package api + +import ( + "context" + "encoding/json" + "io" + "log/slog" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/eigeninference/d-inference/coordinator/attestation" + "github.com/eigeninference/d-inference/coordinator/protocol" + "github.com/eigeninference/d-inference/coordinator/registry" + "github.com/eigeninference/d-inference/coordinator/store" + "nhooyr.io/websocket" +) + +func TestProviderReconnectRestoresReputationEarnedAfterStartup(t *testing.T) { + for _, serial := range []string{"reconnect-device", ""} { + name := "with_serial" + if serial == "" { + name = "without_serial" + } + t.Run(name, func(t *testing.T) { testProviderReconnectRestoresReputation(t, serial) }) + } +} + +func testProviderReconnectRestoresReputation(t *testing.T, serial string) { + t.Helper() + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) + st := store.NewMemory(store.Config{}) + reg := registry.New(logger) + srv := NewServer(reg, st, ServerConfig{}, logger) + t.Cleanup(srv.Close) + publicKey := testPublicKeyB64() + blob := createTestAttestationJSONWithSerial(t, serial, publicKey) + identity, err := attestation.VerifyJSON(blob) + if err != nil || !identity.Valid { + t.Fatalf("invalid test attestation: %v, %+v", err, identity) + } + + // This session and its successful work did not exist in the startup snapshot. + ctx := context.Background() + if err := st.UpsertProvider(ctx, store.ProviderRecord{ + ID: "previous-session", SerialNumber: "reconnect-device", + SEPublicKey: identity.PublicKey, TrustLevel: "hardware", Attested: true, + LastSeen: time.Now(), + }); err != nil { + t.Fatal(err) + } + want := store.ReputationRecord{TotalJobs: 52, SuccessfulJobs: 50, FailedJobs: 2, + TotalUptimeSeconds: 3600, AvgResponseTimeMs: 120, ChallengesPassed: 12, ChallengesFailed: 1} + if err := st.UpsertReputation(ctx, "previous-session", want); err != nil { + t.Fatal(err) + } + msg := &protocol.RegisterMessage{Type: protocol.TypeRegister, PublicKey: publicKey, + Attestation: blob, Version: minProviderVersionForReconnectAttestation, + Backend: "mlx-swift", Models: []protocol.ModelInfo{{ID: "reconnect-model"}}} + ts := httptest.NewServer(srv.Handler()) + t.Cleanup(ts.Close) + wsCtx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + conn, _, err := websocket.Dial(wsCtx, "ws"+strings.TrimPrefix(ts.URL, "http")+"/ws/provider", nil) + if err != nil { + t.Fatal(err) + } + defer conn.CloseNow() + data, err := json.Marshal(msg) + if err != nil { + t.Fatal(err) + } + if err := conn.Write(wsCtx, websocket.MessageText, data); err != nil { + t.Fatal(err) + } + // desired_models is sent after registration verification and state restoration. + for { + _, data, err := conn.Read(wsCtx) + if err != nil { + t.Fatal(err) + } + var message struct { + Type string `json:"type"` + } + if err := json.Unmarshal(data, &message); err != nil { + t.Fatal(err) + } + if message.Type == "desired_models" { + break + } + } + p := findProviderByModel(reg, "reconnect-model") + if p == nil { + t.Fatal("registered provider missing") + } + p.Mu().Lock() + defer p.Mu().Unlock() + if p.Reputation.TotalJobs != want.TotalJobs || p.Reputation.SuccessfulJobs != want.SuccessfulJobs || + p.Reputation.FailedJobs != want.FailedJobs || p.Reputation.TotalUptime != time.Hour || + p.Reputation.AvgResponseTime != 120*time.Millisecond || p.Reputation.ChallengesPassed != 12 || + p.Reputation.ChallengesFailed != 1 { + t.Fatalf("reconnect lost persisted reputation: got %+v, want %+v", p.Reputation, want) + } + if p.TrustLevel != registry.TrustSelfSigned || p.MDAVerified { + t.Fatalf("reconnect must re-earn hardware trust: trust=%s mda=%v", p.TrustLevel, p.MDAVerified) + } +} + +func TestProviderReconnectDoesNotRestoreAnotherSEKey(t *testing.T) { + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) + st := store.NewMemory(store.Config{}) + publicKey := testPublicKeyB64() + blob := createTestAttestationJSONWithSerial(t, "shared-serial", publicKey) + ctx := context.Background() + if err := st.UpsertProvider(ctx, store.ProviderRecord{ + ID: "other-session", SEPublicKey: "different-signing-key", SerialNumber: "shared-serial", + AccountID: "other-account", TrustLevel: "hardware", LastSeen: time.Now(), + }); err != nil { + t.Fatal(err) + } + if err := st.UpsertReputation(ctx, "other-session", store.ReputationRecord{TotalJobs: 99, SuccessfulJobs: 99}); err != nil { + t.Fatal(err) + } + reg := registry.New(logger) + srv := NewServer(reg, st, ServerConfig{}, logger) + t.Cleanup(srv.Close) + msg := &protocol.RegisterMessage{Type: protocol.TypeRegister, PublicKey: publicKey, + Attestation: blob, Version: minProviderVersionForReconnectAttestation} + p := reg.Register("new-session", nil, msg) + srv.verifyProviderAttestation(p.ID, p, msg) + p.Mu().Lock() + defer p.Mu().Unlock() + if p.Reputation.TotalJobs != 0 || p.AccountID != "" { + t.Fatalf("different SE key inherited state: reputation=%+v account=%q", p.Reputation, p.AccountID) + } +} diff --git a/coordinator/api/server.go b/coordinator/api/server.go index 451285f9e1..407c382e3a 100644 --- a/coordinator/api/server.go +++ b/coordinator/api/server.go @@ -388,12 +388,6 @@ type Server struct { // Set from CORS_ORIGIN env var. Empty defaults to the production console domain. corsOrigin string - // storedProviders is a lookup table of persisted provider records, indexed - // by serial number and SE public key. When a provider reconnects after a - // coordinator restart, this table is checked to restore trust/reputation. - // Populated once at startup from the store. - storedProviders map[string]*store.ProviderRecord - // geoResolver resolves provider and consumer request locations from IP // addresses or trusted reverse-proxy headers. Nil when GeoIP is not configured. geoResolver providerGeoResolver @@ -880,9 +874,6 @@ func NewServer(reg *registry.Registry, st store.Store, cfg ServerConfig, logger s.registerDefaultGauges() s.routes() - // Load stored provider records into a lookup table for matching - // reconnecting providers to their persisted state. - s.storedProviders = reg.LoadStoredProviders() // Apply server configuration from ServerConfig. // TODO(auth): storing admin emails in the server struct is an antipattern. // Move admin verification to an external auth service (Privy or IDP) so that diff --git a/coordinator/registry/persistence.go b/coordinator/registry/persistence.go index 06b076f6ec..aa6f5e41b9 100644 --- a/coordinator/registry/persistence.go +++ b/coordinator/registry/persistence.go @@ -1,10 +1,11 @@ package registry // Provider state persistence: the bridge between the in-memory registry and the -// durable store. Loads stored provider records + reputation at startup, restores -// them onto reconnecting live providers (never resurrecting hardware trust or -// the MDA proof — that is re-earned live), and writes provider + reputation -// state back (unconditionally for critical changes, throttled for heartbeats). +// durable store. On reconnect it restores stored provider records + reputation +// onto live providers via a LIVE store read keyed by the freshly verified +// Secure Enclave public key (never resurrecting hardware trust or the MDA proof — +// that is re-earned live), and writes provider + reputation state back +// (unconditionally for critical changes, throttled for heartbeats). import ( "context" @@ -20,43 +21,10 @@ func (r *Registry) SetStore(st store.Store) { r.store = st } -// LoadStoredProviders loads provider records and reputation from the store -// on startup. This pre-populates a lookup table so that reconnecting providers -// can have their trust level and reputation restored. Providers are NOT added -// to the active registry (they need to reconnect via WebSocket first). -func (r *Registry) LoadStoredProviders() map[string]*store.ProviderRecord { - if r.store == nil { - return nil - } - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) - defer cancel() - - records, err := r.store.ListProviderRecords(ctx) - if err != nil { - r.logger.Warn("failed to load stored providers", "error", err) - return nil - } - - lookup := make(map[string]*store.ProviderRecord, len(records)) - for i := range records { - rec := records[i] - // Index by serial number for matching reconnecting providers - if rec.SerialNumber != "" { - lookup[rec.SerialNumber] = &rec - } - // Also index by SE public key - if rec.SEPublicKey != "" { - lookup["sekey:"+rec.SEPublicKey] = &rec - } - } - - r.logger.Info("loaded stored provider records", "count", len(records)) - return lookup -} - // RestoreProviderState restores trust level and reputation from a stored record -// onto a live provider. Called after a provider reconnects and is matched to -// its stored state by serial number or SE key. +// onto a live provider. Called after a provider reconnects and is matched to its +// stored state by the freshly verified Secure Enclave public key (rec is the +// newest metadata row for that key; reputation is re-fetched by SE key below). func (r *Registry) RestoreProviderState(p *Provider, rec *store.ProviderRecord) { if rec == nil { return @@ -141,12 +109,18 @@ func (r *Registry) RestoreProviderState(p *Provider, rec *store.ProviderRecord) p.Stats = providerRecordStats(rec.LifetimeStats, rec.LifetimeRequestsServed, rec.LifetimeTokensGenerated) p.lastSessionStats = providerRecordStats(rec.LastSessionStats, rec.LastSessionRequestsServed, rec.LastSessionTokensGenerated) - // Restore reputation from store + // Restore reputation keyed to the attested SE key, not to rec.ID. rec is the + // freshest DEVICE METADATA row, which on a reconnect may be a bare row that has + // not flushed its reputation yet; the standing lives on an earlier session's + // row under the same SE key. GetReputationBySEKey finds the newest row that + // actually carries reputation and excludes this registering session (p.ID) so + // its own just-persisted empty row cannot shadow the earned history. A missing + // reputation row leaves the neutral cold-start default untouched. if r.store != nil { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() - repRec, err := r.store.GetReputation(ctx, rec.ID) - if err == nil { + repRec, err := r.store.GetReputationBySEKey(ctx, rec.SEPublicKey, p.ID) + if err == nil && repRec != nil { p.Reputation.TotalJobs = repRec.TotalJobs p.Reputation.SuccessfulJobs = repRec.SuccessfulJobs p.Reputation.FailedJobs = repRec.FailedJobs diff --git a/coordinator/store/interface_domains.go b/coordinator/store/interface_domains.go index c8b4b65ad7..44299d8a34 100644 --- a/coordinator/store/interface_domains.go +++ b/coordinator/store/interface_domains.go @@ -651,6 +651,28 @@ type ProviderStore interface { // GetProviderBySerial returns a provider record by serial number. GetProviderBySerial(ctx context.Context, serial string) (*ProviderRecord, error) + // GetProviderBySEKey returns the most-recently-seen provider record whose + // Secure Enclave public key matches sePublicKey, excluding the record whose id + // equals excludeID (the currently registering session). "Most recent" is + // ordered by LastSeen descending, ties broken deterministically by id + // descending so Memory and Postgres agree. Identity is the attested Secure + // Enclave key ALONE — never the serial number (shareable across a re-image / + // key rotation) nor the per-connection session id. This selects the freshest + // DEVICE METADATA (account linkage, failed challenges, lifetime/session + // counters, cached MDA chain); reputation is looked up separately via + // GetReputationBySEKey so a newer session that has not yet flushed a reputation + // row does not discard fresh device state. Returns (nil, nil) if none match. + GetProviderBySEKey(ctx context.Context, sePublicKey, excludeID string) (*ProviderRecord, error) + + // GetReputationBySEKey returns the reputation of the most-recently-seen + // provider record that both matches sePublicKey and carries a persisted + // reputation row, excluding excludeID. Ordering and identity rules match + // GetProviderBySEKey (LastSeen desc, id desc tie-break; SE key only). This lets + // a reconnect recover standing earned by an earlier session under the same + // attested key even when the newest record has no reputation row yet. Returns + // (nil, nil) if none match. + GetReputationBySEKey(ctx context.Context, sePublicKey, excludeID string) (*ReputationRecord, error) + // GetMDAChainBySerial returns the newest NON-EMPTY Apple MDA cert chain stored // for a serial, or (nil, nil) if none. A reconnecting provider gets a new row // (keyed by a fresh provider id) that may be persisted with an empty chain diff --git a/coordinator/store/memory.go b/coordinator/store/memory.go index 48f1e45bbe..2f19302ff8 100644 --- a/coordinator/store/memory.go +++ b/coordinator/store/memory.go @@ -3075,6 +3075,93 @@ func (s *MemoryStore) GetProviderBySerial(_ context.Context, serial string) (*Pr return &cp, nil } +func (s *MemoryStore) GetProviderBySEKey(_ context.Context, sePublicKey, excludeID string) (*ProviderRecord, error) { + if sePublicKey == "" { + return nil, nil + } + s.mu.RLock() + defer s.mu.RUnlock() + + best := s.latestProviderBySEKeyLocked(sePublicKey, excludeID, nil) + if best == nil { + return nil, nil + } + return cloneProviderRecord(best), nil +} + +func (s *MemoryStore) GetReputationBySEKey(_ context.Context, sePublicKey, excludeID string) (*ReputationRecord, error) { + if sePublicKey == "" { + return nil, nil + } + s.mu.RLock() + defer s.mu.RUnlock() + + best := s.latestProviderBySEKeyLocked(sePublicKey, excludeID, func(p *ProviderRecord) bool { + _, ok := s.reputationRecords[p.ID] + return ok + }) + if best == nil { + return nil, nil + } + rep := *s.reputationRecords[best.ID] + return &rep, nil +} + +// latestProviderBySEKeyLocked returns the provider record bound to sePublicKey +// (excluding excludeID) that satisfies keep, choosing the newest LastSeen and +// breaking ties on id descending so the result is deterministic and matches the +// Postgres ORDER BY. Identity is the SE public key alone — serial-indexed +// lookups are deliberately not used, because a serial can be shared across a +// re-image or key rotation. Caller holds s.mu. A nil keep accepts every match. +func (s *MemoryStore) latestProviderBySEKeyLocked(sePublicKey, excludeID string, keep func(*ProviderRecord) bool) *ProviderRecord { + var best *ProviderRecord + for _, p := range s.providerRecords { + if p.SEPublicKey != sePublicKey || p.ID == excludeID { + continue + } + if keep != nil && !keep(p) { + continue + } + if best == nil || moreRecentProviderRecord(p, best) { + best = p + } + } + return best +} + +// moreRecentProviderRecord reports whether a should sort ahead of b: newer +// LastSeen first, ties broken by lexicographically greater id. The tie-break is +// shared with the Postgres `ORDER BY ... p.last_seen DESC, p.id DESC` so both +// backends pick the same record when timestamps are equal. +func moreRecentProviderRecord(a, b *ProviderRecord) bool { + if a.LastSeen.Equal(b.LastSeen) { + return a.ID > b.ID + } + return a.LastSeen.After(b.LastSeen) +} + +// cloneProviderRecord returns a deep copy whose mutable fields — the +// json.RawMessage byte slices and the pointer fields — do not alias the stored +// record. GetProviderBySEKey hands this to callers that may mutate the returned +// value (RestoreProviderState stages MDACertChain), so aliasing the stored slice +// would let a caller corrupt store state. Scoped to this new API; other getters +// keep their existing ownership. +func cloneProviderRecord(p *ProviderRecord) *ProviderRecord { + cp := *p + cp.Hardware = bytes.Clone(p.Hardware) + cp.Models = bytes.Clone(p.Models) + cp.AttestationResult = bytes.Clone(p.AttestationResult) + cp.MDACertChain = bytes.Clone(p.MDACertChain) + cp.LifetimeStats = bytes.Clone(p.LifetimeStats) + cp.LastSessionStats = bytes.Clone(p.LastSessionStats) + cp.LastChallengeVerified = cloneTimePtr(p.LastChallengeVerified) + if p.Location != nil { + loc := *p.Location + cp.Location = &loc + } + return &cp +} + func (s *MemoryStore) GetMDAChainBySerial(_ context.Context, serial string) (json.RawMessage, error) { if serial == "" { return nil, nil diff --git a/coordinator/store/postgres.go b/coordinator/store/postgres.go index be667f241c..6224db6de5 100644 --- a/coordinator/store/postgres.go +++ b/coordinator/store/postgres.go @@ -4412,6 +4412,94 @@ func (s *PostgresStore) GetProviderBySerial(ctx context.Context, serial string) return &p, nil } +func (s *PostgresStore) GetProviderBySEKey(ctx context.Context, sePublicKey, excludeID string) (*ProviderRecord, error) { + if sePublicKey == "" { + return nil, nil + } + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + + var p ProviderRecord + var locationRaw []byte + // Newest DEVICE METADATA bound to this SE key, excluding the registering + // session. Identity is the attested SE public key alone — never the serial + // (shareable across a re-image / key rotation) or the per-connection id. + // Ordered by last_seen desc, ties broken by id desc — the same tie-break the + // memory store applies (moreRecentProviderRecord) so both backends agree. + // Reputation is fetched separately (GetReputationBySEKey) so a fresh session + // that has not yet flushed a reputation row still contributes its newer + // account linkage / MDA chain here. + err := s.pool.QueryRow(ctx, + `SELECT p.id, p.hardware, p.models, p.backend, p.location, p.trust_level, p.attested, + p.attestation_result, p.se_public_key, p.serial_number, + p.mda_verified, p.mda_cert_chain, + p.version, p.runtime_verified, p.python_hash, p.runtime_hash, + p.last_challenge_verified, p.failed_challenges, p.account_id, + p.lifetime_requests_served, p.lifetime_tokens_generated, + p.last_session_requests_served, p.last_session_tokens_generated, + p.lifetime_stats, p.last_session_stats, + p.registered_at, p.last_seen, p.public_key + FROM providers p + WHERE p.se_public_key = $1 AND p.se_public_key != '' AND p.id != $2 + ORDER BY p.last_seen DESC, p.id DESC LIMIT 1`, sePublicKey, excludeID, + ).Scan( + &p.ID, &p.Hardware, &p.Models, &p.Backend, + &locationRaw, + &p.TrustLevel, &p.Attested, + &p.AttestationResult, &p.SEPublicKey, &p.SerialNumber, + &p.MDAVerified, &p.MDACertChain, + &p.Version, &p.RuntimeVerified, &p.PythonHash, &p.RuntimeHash, + &p.LastChallengeVerified, &p.FailedChallenges, &p.AccountID, + &p.LifetimeRequestsServed, &p.LifetimeTokensGenerated, + &p.LastSessionRequestsServed, &p.LastSessionTokensGenerated, + &p.LifetimeStats, &p.LastSessionStats, + &p.RegisteredAt, &p.LastSeen, &p.PublicKey, + ) + if err != nil { + if errors.Is(err, pgx.ErrNoRows) { + return nil, nil + } + return nil, fmt.Errorf("store: get provider by se key: %w", err) + } + p.Location = unmarshalProviderLocation(locationRaw) + return &p, nil +} + +func (s *PostgresStore) GetReputationBySEKey(ctx context.Context, sePublicKey, excludeID string) (*ReputationRecord, error) { + if sePublicKey == "" { + return nil, nil + } + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + + var rep ReputationRecord + // Reputation of the newest record that both matches this SE key and actually + // carries a reputation row. The inner join drops metadata-only rows, and the + // last_seen desc, id desc ordering matches GetProviderBySEKey and the memory + // store, so a reconnect recovers the standing an earlier session earned under + // the same attested key even when the newest record has no reputation row yet. + err := s.pool.QueryRow(ctx, + `SELECT r.total_jobs, r.successful_jobs, r.failed_jobs, + r.total_uptime_seconds, r.avg_response_time_ms, + r.challenges_passed, r.challenges_failed + FROM provider_reputation r + JOIN providers p ON p.id = r.provider_id + WHERE p.se_public_key = $1 AND p.se_public_key != '' AND p.id != $2 + ORDER BY p.last_seen DESC, p.id DESC LIMIT 1`, sePublicKey, excludeID, + ).Scan( + &rep.TotalJobs, &rep.SuccessfulJobs, &rep.FailedJobs, + &rep.TotalUptimeSeconds, &rep.AvgResponseTimeMs, + &rep.ChallengesPassed, &rep.ChallengesFailed, + ) + if err != nil { + if errors.Is(err, pgx.ErrNoRows) { + return nil, nil + } + return nil, fmt.Errorf("store: get reputation by se key: %w", err) + } + return &rep, nil +} + func (s *PostgresStore) GetMDAChainBySerial(ctx context.Context, serial string) (json.RawMessage, error) { if serial == "" { return nil, nil diff --git a/coordinator/store/provider_se_key_test.go b/coordinator/store/provider_se_key_test.go new file mode 100644 index 0000000000..1de0d2e5f5 --- /dev/null +++ b/coordinator/store/provider_se_key_test.go @@ -0,0 +1,229 @@ +package store + +import ( + "context" + "encoding/json" + "testing" + "time" +) + +// TestProviderBySEKeyContract pins the reconnect-lookup contract on BOTH the +// memory store and a real isolated PostgreSQL (via DATABASE_URL, using +// storeBackends). GetProviderBySEKey returns the freshest DEVICE METADATA row +// for a Secure Enclave key; GetReputationBySEKey returns the standing from the +// newest reputation-bearing row for that key. Both exclude the registering +// session and never inherit across a different SE key. +func TestProviderBySEKeyContract(t *testing.T) { + for name, st := range storeBackends(t) { + st := st + t.Run(name, func(t *testing.T) { + ctx := context.Background() + now := time.Now().UTC().Truncate(time.Millisecond) + + seedProvider := func(id, seKey, account string, seen time.Time) { + if err := st.UpsertProvider(ctx, ProviderRecord{ + ID: id, SEPublicKey: seKey, AccountID: account, Hardware: json.RawMessage(`{}`), Models: json.RawMessage(`[]`), + TrustLevel: "hardware", Attested: true, LastSeen: seen, + }); err != nil { + t.Fatalf("UpsertProvider %s: %v", id, err) + } + } + seedRep := func(id string, jobs int) { + if err := st.UpsertReputation(ctx, id, ReputationRecord{ + TotalJobs: jobs, SuccessfulJobs: jobs, + }); err != nil { + t.Fatalf("UpsertReputation %s: %v", id, err) + } + } + + const seKey = "se-key-alpha" + + // Newer session carries fresh device metadata but NO reputation row; + // an older session carries the earned standing. + seedProvider("old-earned", seKey, "old-account", now.Add(-2*time.Hour)) + seedRep("old-earned", 40) + seedProvider("new-bare", seKey, "new-account", now.Add(-1*time.Hour)) + + // A different SE key must never be inherited. + seedProvider("stranger", "se-key-beta", "beta-account", now) + seedRep("stranger", 999) + + // Metadata: newest row wins regardless of reputation presence. + rec, err := st.GetProviderBySEKey(ctx, seKey, "registering") + if err != nil { + t.Fatalf("GetProviderBySEKey: %v", err) + } + if rec == nil || rec.ID != "new-bare" || rec.AccountID != "new-account" { + t.Fatalf("metadata lookup should pick newest row (new-bare/new-account), got %+v", rec) + } + + // Reputation: earned standing from the older row survives even though + // the newest row has none. + rep, err := st.GetReputationBySEKey(ctx, seKey, "registering") + if err != nil { + t.Fatalf("GetReputationBySEKey: %v", err) + } + if rep == nil || rep.TotalJobs != 40 { + t.Fatalf("reputation lookup should recover 40 from old-earned, got %+v", rep) + } + + // Different SE key is isolated. + betaRep, err := st.GetReputationBySEKey(ctx, "se-key-beta", "registering") + if err != nil { + t.Fatalf("GetReputationBySEKey beta: %v", err) + } + if betaRep == nil || betaRep.TotalJobs != 999 { + t.Fatalf("beta key must see its own 999, got %+v", betaRep) + } + if betaMeta, _ := st.GetProviderBySEKey(ctx, "se-key-beta", "registering"); betaMeta == nil || betaMeta.AccountID != "beta-account" { + t.Fatalf("beta key metadata isolation failed: %+v", betaMeta) + } + + // Empty SE key never matches. + if r, err := st.GetProviderBySEKey(ctx, "", "registering"); err != nil || r != nil { + t.Fatalf("empty SE key must return (nil,nil), got (%+v,%v)", r, err) + } + if r, err := st.GetReputationBySEKey(ctx, "", "registering"); err != nil || r != nil { + t.Fatalf("empty SE key reputation must return (nil,nil), got (%+v,%v)", r, err) + } + // Unknown SE key never matches. + if r, err := st.GetProviderBySEKey(ctx, "se-key-missing", "registering"); err != nil || r != nil { + t.Fatalf("unknown SE key must return (nil,nil), got (%+v,%v)", r, err) + } + if r, err := st.GetReputationBySEKey(ctx, "se-key-missing", "registering"); err != nil || r != nil { + t.Fatalf("unknown SE key reputation must return (nil,nil), got (%+v,%v)", r, err) + } + }) + } +} + +// TestProviderBySEKeyExcludesRegisteringSession covers the core reset bug: the +// registering session persists its own bare/empty row before restoration runs, +// and that row must be excluded from both lookups so it cannot shadow prior +// standing under the same SE key. +func TestProviderBySEKeyExcludesRegisteringSession(t *testing.T) { + for name, st := range storeBackends(t) { + st := st + t.Run(name, func(t *testing.T) { + ctx := context.Background() + now := time.Now().UTC() + const seKey = "se-key-exclude" + + // Prior session earned standing. + if err := st.UpsertProvider(ctx, ProviderRecord{ + ID: "prior", SEPublicKey: seKey, Hardware: json.RawMessage(`{}`), Models: json.RawMessage(`[]`), TrustLevel: "hardware", + Attested: true, LastSeen: now.Add(-time.Hour), + }); err != nil { + t.Fatal(err) + } + if err := st.UpsertReputation(ctx, "prior", ReputationRecord{TotalJobs: 75, SuccessfulJobs: 75}); err != nil { + t.Fatal(err) + } + // The registering session's own row is the newest and carries an absurd + // decoy counter; excluding it must make prior win. + if err := st.UpsertProvider(ctx, ProviderRecord{ + ID: "registering", SEPublicKey: seKey, Hardware: json.RawMessage(`{}`), Models: json.RawMessage(`[]`), TrustLevel: "hardware", + Attested: true, LastSeen: now, + }); err != nil { + t.Fatal(err) + } + if err := st.UpsertReputation(ctx, "registering", ReputationRecord{TotalJobs: 999, SuccessfulJobs: 999}); err != nil { + t.Fatal(err) + } + + rec, err := st.GetProviderBySEKey(ctx, seKey, "registering") + if err != nil { + t.Fatalf("GetProviderBySEKey: %v", err) + } + if rec == nil || rec.ID != "prior" { + t.Fatalf("registering session must be excluded, got %+v", rec) + } + rep, err := st.GetReputationBySEKey(ctx, seKey, "registering") + if err != nil { + t.Fatalf("GetReputationBySEKey: %v", err) + } + if rep == nil || rep.TotalJobs != 75 { + t.Fatalf("registering decoy reputation must be excluded, got %+v", rep) + } + + // With no other row, excluding the only (registering) row yields none. + if r, _ := st.GetProviderBySEKey(ctx, "se-key-solo", "solo"); r != nil { + t.Fatalf("no match expected for solo key") + } + }) + } +} + +// TestProviderBySEKeyEqualTimestampsDeterministic pins the shared tie-break: +// with equal LastSeen the greater id wins, identically on memory and Postgres, +// so 1,000 repeated queries never flip between candidates. +func TestProviderBySEKeyEqualTimestampsDeterministic(t *testing.T) { + for name, st := range storeBackends(t) { + st := st + t.Run(name, func(t *testing.T) { + ctx := context.Background() + ts := time.Now().UTC().Truncate(time.Millisecond) + const seKey = "se-key-tie" + + for _, id := range []string{"aaa", "bbb", "ccc"} { + if err := st.UpsertProvider(ctx, ProviderRecord{ + ID: id, SEPublicKey: seKey, AccountID: "acct-" + id, Hardware: json.RawMessage(`{}`), Models: json.RawMessage(`[]`), + TrustLevel: "hardware", Attested: true, LastSeen: ts, + }); err != nil { + t.Fatal(err) + } + if err := st.UpsertReputation(ctx, id, ReputationRecord{TotalJobs: 1}); err != nil { + t.Fatal(err) + } + } + + for i := 0; i < 1000; i++ { + rec, err := st.GetProviderBySEKey(ctx, seKey, "registering") + if err != nil { + t.Fatalf("GetProviderBySEKey: %v", err) + } + if rec == nil || rec.ID != "ccc" { + t.Fatalf("iteration %d: equal-timestamp tie-break must pick greatest id 'ccc', got %+v", i, rec) + } + } + }) + } +} + +// TestGetProviderBySEKeyReturnsDeepCopy proves the memory getter does not alias +// stored mutable fields: mutating the returned Hardware / Location must not +// corrupt the stored record. Scoped to the new API. +func TestGetProviderBySEKeyReturnsDeepCopy(t *testing.T) { + st := NewMemory(Config{}) + ctx := context.Background() + const seKey = "se-key-copy" + hardware := json.RawMessage(`{"model":"Mac17,6"}`) + if err := st.UpsertProvider(ctx, ProviderRecord{ + ID: "sess", SEPublicKey: seKey, Hardware: hardware, Models: json.RawMessage(`[]`), + Location: &ProviderLocation{City: "Original"}, + TrustLevel: "hardware", Attested: true, LastSeen: time.Now(), + }); err != nil { + t.Fatal(err) + } + + rec, err := st.GetProviderBySEKey(ctx, seKey, "registering") + if err != nil || rec == nil { + t.Fatalf("GetProviderBySEKey: rec=%v err=%v", rec, err) + } + // Mutate every returned mutable field. + for i := range rec.Hardware { + rec.Hardware[i] = 'X' + } + rec.Location.City = "Mutated" + + again, err := st.GetProviderBySEKey(ctx, seKey, "registering") + if err != nil || again == nil { + t.Fatalf("GetProviderBySEKey re-read: rec=%v err=%v", again, err) + } + if string(again.Hardware) != `{"model":"Mac17,6"}` { + t.Fatalf("stored Hardware was aliased and mutated: %s", again.Hardware) + } + if again.Location == nil || again.Location.City != "Original" { + t.Fatalf("stored Location was aliased and mutated: %+v", again.Location) + } +} diff --git a/docs/architecture/storage.md b/docs/architecture/storage.md index 6ccb486aec..dd2dd99b50 100644 --- a/docs/architecture/storage.md +++ b/docs/architecture/storage.md @@ -1,6 +1,6 @@ # Storage -> Last updated: 2026-09-05 · commit `4d9811f7c` +> Last updated: 2026-09-05 · commit `bbf6f83d4` What the coordinator persists, through which interface, in which backend, and how the schema reaches a fresh database; then what a provider keeps on its own @@ -191,6 +191,17 @@ KV blocks under a per-model key, not tokens. 7. **Provider secrets never leave the Keychain in the clear.** The KV KEK is wrapped by a Secure Enclave key and the SSD cache is unreadable without it (`provider-swift/Sources/ProviderCore/KVCache/WrappedKEKStorage.swift`). +8. **Reconnect standing is keyed to the attested Secure Enclave key, not the + session.** A reconnecting provider gets a fresh row (new `providers.id`); its + prior reputation and account linkage are recovered by a live lookup on the + verified SE public key, excluding the registering session's own row. + `GetProviderBySEKey` returns the newest device-metadata row (by `last_seen` + desc, `id` desc tie-break) and `GetReputationBySEKey` returns the standing + from the newest row that carries a `provider_reputation` row, so a bare new + session neither discards fresh metadata nor loses earned reputation + (`coordinator/store/interface_domains.go`, + `coordinator/registry/persistence.go` `RestoreProviderState`). Hardware trust + is never restored — it is re-earned live on every connection. ## Failure modes @@ -214,6 +225,7 @@ KV blocks under a per-model key, not tokens. | Postgres pool, schema, one-shot migrations | `coordinator/store/postgres.go`, `coordinator/store/postgres_usage_totals_migration.go`, `coordinator/store/postgres_withdrawable_migration.go`, `coordinator/store/postgres_log_report_privacy.go` | | Domain files | `coordinator/store/postgres_model_registry.go`, `coordinator/store/postgres_base_rewards.go`, `coordinator/store/postgres_profiles.go`, `coordinator/store/route_telemetry.go`, `coordinator/store/usage_time_series.go`, `coordinator/store/apikey.go` | | Memory backend | `coordinator/store/memory.go`, `coordinator/store/memory_base_rewards.go` | +| Reconnect state restore (SE-key lookup) | `GetProviderBySEKey`/`GetReputationBySEKey` in `coordinator/store/memory.go`, `coordinator/store/postgres.go`; `coordinator/registry/persistence.go` (`RestoreProviderState`) | | Manual SQL | `coordinator/store/migrations/` | | Persistent-disk state outside Postgres (MicroMDM, journals) | `coordinator/deploy/start.sh`, `coordinator/api/trust_reuse_journal.go`, [`../operations/state-export.md`](../operations/state-export.md) | | Provider files and Keychain | `provider-swift/Sources/ProviderCore/Config/ProviderConfig.swift`, `provider-swift/Sources/ProviderCore/Service/`, `provider-swift/Sources/ProviderCore/KVCacheSSD/`, `provider-swift/Sources/ProviderCore/KVCache/WrappedKEKStorage.swift` |