docs: retire #335's simulation; PDF comments
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
17 files changed,
+14
−6,249
docs/superpowers/specs/2026-10-21-fleet-internal-engines-design.md+4 −0internal/release/system.go+3 −2internal/sim/engines/calls_test.go+0 −850internal/sim/engines/classify_test.go+0 −592internal/sim/engines/dedicated_test.go+0 −508internal/sim/engines/edge_test.go+0 −315internal/sim/engines/expected-outcomes.txt+0 −12internal/sim/engines/invariants_test.go+0 −359internal/sim/engines/launch_test.go+0 −489internal/sim/engines/mutate.sh+0 −196internal/sim/engines/rules_test.go+0 −95internal/sim/engines/sim_test.go+0 −348internal/sim/engines/witness_test.go+0 −2,105internal/sim/engines/world_test.go+0 −370internal/sim/regionha/mutate.sh+3 −4internal/sim/regionha/witness_test.go+1 −2internal/svcrole/svcrole.go+3 −2
diff --git a/docs/superpowers/specs/2026-10-21-fleet-internal-engines-design.md b/docs/superpowers/specs/2026-10-21-fleet-internal-engines-design.md| index 86ae8f17c..284be7473 100644 |
| --- a/docs/superpowers/specs/2026-10-21-fleet-internal-engines-design.md |
| +++ b/docs/superpowers/specs/2026-10-21-fleet-internal-engines-design.md |
| @@ -1,5 +1,9 @@ |
| # Fleet-internal engines: a doc engine nobody on the internet can call |
| +**Superseded:** On 2026-11-02 by [2026-11-02-pdf-service-design.md](2026-11-02-pdf-service-design.md). |
| +The platform runs the engine, so the internal-route, grant and socket |
| +machinery has nothing left to protect. This spec and its findings stay as history. |
| + |
| **Date:** 2026-10-21 |
| **Revision:** 14. Approved by Paul, 2026-10-21. |
| **Discussion:** amadan carlos/platform #335. Related: #328 (per-app egress allow). |
diff --git a/internal/release/system.go b/internal/release/system.go| index 8491a3a2a..b3f913e3c 100644 |
| --- a/internal/release/system.go |
| +++ b/internal/release/system.go |
| @@ -7,8 +7,9 @@ |
| // |
| // A typed record per feature rather than one generic settings map, for the |
| // same reason: a map would be features.json by another name, uninterpreted and |
| -// impossible to schema-pin meaningfully. system/pdf.json later is a new type |
| -// and a new door, not a new magic string. |
| +// impossible to schema-pin meaningfully. PDF rendering is a Service door |
| +// (POST /api/cli/apps/{account}/{app}/pdf/...), configured by CARLOS_PDF_ADDR, |
| +// with no system record. |
| package release |
| import ( |
diff --git a/internal/sim/engines/calls_test.go b/internal/sim/engines/calls_test.go| deleted file mode 100644 |
| index c38bdbb59..000000000 |
| --- a/internal/sim/engines/calls_test.go |
| +++ /dev/null |
| @@ -1,850 +0,0 @@ |
| -package engines |
| - |
| -import ( |
| - "fmt" |
| - "strings" |
| -) |
| - |
| -// Calls, identity, grants and arming (spec §5.2 the signed record; §5.3 the |
| -// grant mirror; §5.4 the call path; §6.1 identity; §6.2 armed boxes; §6.4 |
| -// freshness). |
| -// |
| -// The console publishes the grant set as one signed record with a strictly |
| -// increasing revision, its signing time and a 72-hour expiry, and re-signs it |
| -// every two minutes and on every change; every edge mirrors it, keeps a |
| -// durable revision floor, and treats a stale, expired or never-read table as |
| -// empty. Stale is either no good read for ten minutes or a record signed more |
| -// than ten minutes ago (ruling R5). A nested instance calls an engine through its engine socket, which |
| -// is open only on an armed box; a host-app process calls through the door. |
| -// The calling box proves the caller (the peer's cgroup, or a door key from a |
| -// uid other than carlos), checks its own table and hops to the engine's home |
| -// box with the caller signed into the hop's MAC. The engine box checks its |
| -// own table again and dispatches to the engine hostname's own route only. |
| -// |
| -// The model leaves out the per-app cap, the transport limits and the deploy |
| -// watch ticket (Plan 2 tests those directly). |
| - |
| -// Time: one tick is 10 s. |
| -const ( |
| - pollTicks = 3 // the mirror polls every 30 s |
| - staleTicks = 60 // no good read, or a record signed, ten minutes ago: stale (R5) |
| - resignTicks = 12 // the console re-signs every two minutes while it is up (R5) |
| - lifetimeTicks = 25920 // a record expires 72 hours after it is signed |
| -) |
| - |
| -// now is the model's clock: one tick per step, plus any fast-forward. |
| -func (w *world) now() int { return w.step + w.skew } |
| - |
| -// advance is time passing with no step: n ticks in which nothing polls (an |
| -// outage, a console down for days). |
| -func (w *world) advance(n int) { |
| - w.skew += n |
| - w.logf("%d ticks pass (now %d)", n, w.now()) |
| -} |
| - |
| -// ---------- the console's record (spec §5.2) ---------- |
| - |
| -// record is one signed control/engines.json: its revision, its signed_at and |
| -// expiry (in ticks), and its grants by account/app/engine. |
| -type record struct { |
| - Rev, SignedAt, Expires int |
| - Grants map[string]bool |
| -} |
| - |
| -// mirror is an edge's grant mirror (§5.3): the record it holds, its revision |
| -// floor and the tick of its last good read, and what it has persisted to its |
| -// data directory (the record and the floor, written before either is used). |
| -type mirror struct { |
| - Rec *record |
| - Floor, ReadAt int |
| - Persisted *record |
| - PersistedFloor int |
| -} |
| - |
| -// engConsole is the console's side: its database (Grants, the authority), |
| -// every record it has signed, the newest revision, and the object in the |
| -// bucket. RevokedAt and RevokedRev are the oracle's: the tick and revision of |
| -// the publish that stopped granting a key. BucketDown: the edges cannot read |
| -// the bucket. Down: the console is down, so it neither re-signs nor takes a |
| -// grant or revoke. |
| -// |
| -// Pinned is a bucket writer's replay: an older signed record it keeps in the |
| -// bucket, overwriting each record the console publishes, until tick |
| -// PinnedUntil. |
| -type engConsole struct { |
| - Rev int |
| - Records map[int]*record |
| - Grants map[string]bool |
| - RevokedAt map[string]int |
| - RevokedRev map[string]int |
| - Bucket *record |
| - BucketDown bool |
| - Down bool |
| - Pinned *record |
| - PinnedUntil int |
| -} |
| - |
| -// The engines the operator has named (carlos engines add): name to its |
| -// hostname. eng's hostname is the engine group's minted row; site's is box |
| -// 0's static row, whose path map sends /convert to eng's route (R4-2: the |
| -// console cannot check a hostname, and path targets may cross apps). |
| -const site = "site" |
| - |
| -var engineHosts = map[string]string{eng: engHost, site: engSite} |
| - |
| -// callerOf is the caller account/app calling engine. |
| -func callerOf(app, engine string) caller { |
| - acct, a, _ := strings.Cut(app, "/") |
| - return caller{Account: acct, App: a, Engine: engine} |
| -} |
| - |
| -func (c caller) app() string { return c.Account + "/" + c.App } |
| -func (c caller) key() string { return c.app() + "/" + c.Engine } |
| - |
| -// initEngines is the starting world: the console's first record grants shop |
| -// the engine eng, and every edge has read it. |
| -func (w *world) initEngines() { |
| - w.console = engConsole{Records: map[int]*record{}, Grants: map[string]bool{"acct/shop/eng": true}, RevokedAt: map[string]int{}, RevokedRev: map[string]int{}} |
| - w.publish(1) |
| - for _, b := range w.boxes { |
| - w.mirrorTick(b) |
| - } |
| -} |
| - |
| -// publish is the console signing its grant set as revision rev, signed now |
| -// and expiring 72 hours out, and writing it to the bucket (where a pinned |
| -// replay overwrites it at once). A revision is strictly increasing; a re-sign |
| -// with the same grants is a new revision. |
| -func (w *world) publish(rev int) { |
| - c := &w.console |
| - if rev <= c.Rev { |
| - panic(fmt.Sprintf("publish: revision %d after %d", rev, c.Rev)) |
| - } |
| - rec := &record{Rev: rev, SignedAt: w.now(), Expires: w.now() + lifetimeTicks, Grants: map[string]bool{}} |
| - for k, v := range c.Grants { |
| - if v { |
| - rec.Grants[k] = true |
| - } |
| - } |
| - if prev := c.Records[c.Rev]; prev != nil { |
| - for _, k := range sortedKeys(prev.Grants) { |
| - if !rec.Grants[k] { |
| - c.RevokedAt[k], c.RevokedRev[k] = w.now(), rev |
| - } |
| - } |
| - } |
| - for k := range rec.Grants { |
| - delete(c.RevokedAt, k) |
| - delete(c.RevokedRev, k) |
| - } |
| - c.Records[rev], c.Rev, c.Bucket = rec, rev, rec |
| - w.logf("console: publishes revision %d, signed at %d, expiring at %d, grants %v", rev, rec.SignedAt, rec.Expires, sortedKeys(rec.Grants)) |
| - if c.Pinned != nil { |
| - c.Bucket = c.Pinned |
| - w.logf("bucket writer: overwrites it with revision %d", c.Pinned.Rev) |
| - } |
| -} |
| - |
| -// consoleGrant and consoleRevoke are carlos engines grant/revoke: the |
| -// database changes and the console publishes the next revision. A console |
| -// that is down takes neither (false). |
| -func (w *world) consoleGrant(key string) bool { |
| - if w.console.Down { |
| - w.logf("console: down; carlos engines grant %s fails", key) |
| - return false |
| - } |
| - w.console.Grants[key] = true |
| - w.publish(w.console.Rev + 1) |
| - return true |
| -} |
| - |
| -func (w *world) consoleRevoke(key string) bool { |
| - if w.console.Down { |
| - w.logf("console: down; carlos engines revoke %s fails", key) |
| - return false |
| - } |
| - delete(w.console.Grants, key) |
| - w.publish(w.console.Rev + 1) |
| - return true |
| -} |
| - |
| -// replay is a bucket writer restoring an older signed record (validly signed, |
| -// and unexpired unless 72 hours have passed) and keeping it in the bucket |
| -// over everything the console publishes, until it stops (unpin). |
| -func (w *world) replay(rev int) { w.replayUntil(rev, 1<<62) } |
| - |
| -// replayUntil is replay for a writer who stops at tick until. |
| -func (w *world) replayUntil(rev, until int) { |
| - rec := w.console.Records[rev] |
| - if rec == nil { |
| - panic(fmt.Sprintf("replay: no revision %d", rev)) |
| - } |
| - w.console.Bucket, w.console.Pinned, w.console.PinnedUntil = rec, rec, until |
| - w.logf("bucket writer: replays revision %d (signed at %d; newest %d) into the bucket, until tick %d", rev, rec.SignedAt, w.console.Rev, until) |
| -} |
| - |
| -// unpin is the bucket writer stopping: the newest record is in the bucket |
| -// again. |
| -func (w *world) unpin() { |
| - c := &w.console |
| - c.Pinned, c.Bucket = nil, c.Records[c.Rev] |
| - w.logf("bucket writer: stops; the bucket holds revision %d again", c.Rev) |
| -} |
| - |
| -func (w *world) setBucketDown(down bool) { |
| - w.console.BucketDown = down |
| - w.logf("the bucket is unreachable = %v", down) |
| -} |
| - |
| -// ---------- the grant mirror (spec §5.3) ---------- |
| - |
| -// mirrorTick is one poll of b's mirror. It verifies the record's expiry and |
| -// its signed_at (a record signed more than ten minutes ago is stale, like an |
| -// expired one, grant-freshness-bound) and refuses a revision below its floor |
| -// (an equal revision is the same signed bytes: the model's records are |
| -// immutable per revision). A good read replaces the record, raises the floor, |
| -// and persists both before either is used (floor-persisted). |
| -func (w *world) mirrorTick(b *box) { |
| - m := &b.Mirror |
| - c := &w.console |
| - if c.BucketDown || c.Bucket == nil { |
| - return |
| - } |
| - rec, now := c.Bucket, w.now() |
| - if now >= rec.Expires { |
| - if m.Rec != rec { |
| - w.logf("box%d: mirror refuses revision %d: expired at %d", b.ID, rec.Rev, rec.Expires) |
| - } |
| - return |
| - } |
| - if now-rec.SignedAt >= staleTicks && on("grant-freshness-bound") { |
| - if m.Rec != rec { |
| - w.logf("box%d: mirror refuses revision %d: signed at %d, ten minutes ago or more", b.ID, rec.Rev, rec.SignedAt) |
| - } |
| - return |
| - } |
| - if rec.Rev < m.Floor { |
| - w.logf("box%d: mirror refuses revision %d: below the floor %d", b.ID, rec.Rev, m.Floor) |
| - return |
| - } |
| - if rec.Rev > m.Floor || m.Rec == nil { |
| - w.logf("box%d: mirror reads revision %d (floor %d -> %d)", b.ID, rec.Rev, m.Floor, rec.Rev) |
| - } |
| - m.Rec, m.ReadAt = rec, now |
| - if rec.Rev > m.Floor { |
| - m.Floor = rec.Rev |
| - } |
| - if rec.Rev > b.ReadRev { |
| - b.ReadRev = rec.Rev |
| - } |
| - if on("floor-persisted") { |
| - m.Persisted, m.PersistedFloor = m.Rec, m.Floor |
| - } |
| -} |
| - |
| -// restartEdge is b's edge restarting: it loads the persisted record and |
| -// floor before any engine socket opens. The time of the last good read is |
| -// persisted with the record, so a restart is not a good read. |
| -func (w *world) restartEdge(b *box) { |
| - m := &b.Mirror |
| - m.Rec, m.Floor = m.Persisted, m.PersistedFloor |
| - rev := 0 |
| - if m.Rec != nil { |
| - rev = m.Rec.Rev |
| - } |
| - w.logf("box%d: edge restarts: mirror loads revision %d, floor %d", b.ID, rev, m.Floor) |
| -} |
| - |
| -// rebuild is a new or rebuilt box: its edge's data directory is gone, so it |
| -// has no floor and no record until its first read, and may admit any validly |
| -// signed record a bucket writer replays, until ten minutes after its signing |
| -// (§5.3). The oracle forgets what the box had read (ReadRev). |
| -func (w *world) rebuild(b *box) { |
| - b.Mirror = mirror{} |
| - b.ReadRev = 0 |
| - w.logf("box%d: rebuilt: the edge has no persisted floor", b.ID) |
| -} |
| - |
| -// tableGrants is b's grant table on key. Never read: empty. No good read for |
| -// ten minutes, or expired: empty (stale-clears-grants). A record signed more |
| -// than ten minutes ago: empty (grant-freshness-bound, R5). |
| -func (w *world) tableGrants(b *box, key string) bool { |
| - m := b.Mirror |
| - if m.Rec == nil { |
| - return false |
| - } |
| - if on("stale-clears-grants") && (w.now()-m.ReadAt >= staleTicks || w.now() >= m.Rec.Expires) { |
| - return false |
| - } |
| - if on("grant-freshness-bound") && w.now()-m.Rec.SignedAt >= staleTicks { |
| - return false |
| - } |
| - return m.Rec.Grants[key] |
| -} |
| - |
| -// ---------- the call path (spec §5.4) ---------- |
| - |
| -// call is one engine call as its sender makes it. host is the instance |
| -// whose engine socket the process connects to, or whose door key it |
| -// presents; engine is the Host: header; forged an X-Carlos-Hop-Caller header |
| -// the sender wrote, or nil. |
| -type call struct { |
| - from *box |
| - p *proc |
| - viaDoor bool |
| - uid string |
| - host string |
| - engine string |
| - path string |
| - forged *caller |
| -} |
| - |
| -// engineCall is process p on box from calling engine (its Host:) at path, |
| -// through the engine socket of instance host, or through the door with |
| -// host's door key under uid. It reports whether the call reached an engine |
| -// process. |
| -func (w *world) engineCall(from *box, p *proc, viaDoor bool, uid string, host, engine, path string) bool { |
| - return w.placeCall(call{from: from, p: p, viaDoor: viaDoor, uid: uid, host: host, engine: engine, path: path}) |
| -} |
| - |
| -// unitBacked: the route runs as a unit-backed DynamicUser service. The |
| -// model's engine route is (§8: arm succeeds with nested callers and a |
| -// unit-backed engine); every other instance route is nested. Unit-backed |
| -// routes are not callers (ruling R2): they have no engine socket. |
| -func unitBacked(g string) bool { return g == eng } |
| - |
| -// socketOpen: instance g on b has an engine socket: the box is armed and |
| -// its listener manager has the sockets open, and g is a nested instance. |
| -func (w *world) socketOpen(b *box, g string) bool { |
| - if !b.Armed || !b.Sockets || unitBacked(g) { |
| - return false |
| - } |
| - for _, x := range w.groups(b) { |
| - if x == g { |
| - return true |
| - } |
| - } |
| - return false |
| -} |
| - |
| -// realApp is the account/app whose code process p runs: planted code's app, |
| -// else its group's route's, else (a tenant with no row in the model: a flat, |
| -// foreign or worker tenant) acct/<group). nil is a public client: no app. |
| -func (w *world) realApp(b *box, p *proc) string { |
| - switch { |
| - case p == nil: |
| - return "" |
| - case p.Code != "": |
| - return p.Code |
| - } |
| - if r := b.Rows[p.Group]; r != nil && r.App != "" { |
| - return r.App |
| - } |
| - return "acct/" + p.Group |
| -} |
| - |
| -func (w *world) placeCall(c call) bool { |
| - b := c.from |
| - how := "socket of " + c.host |
| - if c.viaDoor { |
| - how = "door (uid " + c.uid + ", key of " + c.host + ")" |
| - } |
| - who := "a public client" |
| - if c.p != nil { |
| - who = fmt.Sprintf("process %d (%s)", c.p.ID, c.p.Slice) |
| - } |
| - w.logf("box%d: %s calls Host: %s%s through the %s", b.ID, who, c.engine, c.path, how) |
| - if strings.Contains(c.engine, ".") { |
| - w.logf("box%d: Host: %s is no engine name (it has a dot): not an engine call", b.ID, c.engine) |
| - return false |
| - } |
| - r := b.Rows[c.host] |
| - if r == nil || r.Kind != "instance" || r.Platform { |
| - w.logf("box%d: no instance route %s", b.ID, c.host) |
| - return false |
| - } |
| - // who is calling |
| - if !c.viaDoor { |
| - if !w.socketOpen(b, c.host) { |
| - w.logf("box%d: %s has no engine socket (armed %v)", b.ID, c.host, b.Armed) |
| - return false |
| - } |
| - if on("cgroup-identity") && c.p.Slice != "inst:"+c.host { |
| - w.logf("box%d: engine socket of %s: peer cgroup %s is not the instance's slice; closed unread", b.ID, c.host, c.p.Slice) |
| - return false |
| - } |
| - } else if on("door-uid") && c.uid == "carlos" { |
| - w.logf("box%d: door: an engine call from uid carlos: 404 engine not granted", b.ID) |
| - return false |
| - } |
| - mark := callerOf(r.App, c.engine) |
| - // the listener strips every X-Carlos-* header the sender wrote |
| - if c.forged != nil && on("hop-caller-signed") { |
| - w.logf("box%d: X-Carlos-Hop-Caller %s from the sender deleted", b.ID, c.forged.key()) |
| - c.forged = nil |
| - } |
| - if !w.tableGrants(b, mark.key()) { |
| - w.logf("box%d: %s not in the grant table: 404 engine not granted", b.ID, mark.key()) |
| - return false |
| - } |
| - hostname := engineHosts[c.engine] |
| - home := w.homeOf(hostname) |
| - if home == nil { |
| - w.logf("box%d: %s homed nowhere: 502 engine unreachable", b.ID, hostname) |
| - return false |
| - } |
| - seen := mark |
| - if home != b { |
| - w.logf("box%d: hop to box%d, caller %s signed into the MAC", b.ID, home.ID, mark.key()) |
| - if c.forged != nil { |
| - w.logf("box%d: the hop also carries the sender's X-Carlos-Hop-Caller %s; the engine box takes it", home.ID, c.forged.key()) |
| - seen = *c.forged |
| - } |
| - } |
| - return w.engineAdmit(home, b, seen, hostname, c.path, c.host, w.realApp(b, c.p), c.p) |
| -} |
| - |
| -// clientHop is a public client sending b's edge a request for hostname that |
| -// carries X-Carlos-Hop-Caller with no hop MAC. Only a verified hop's caller |
| -// is a caller (hop-caller-signed): the header is deleted and the request is |
| -// a public request like any other. |
| -func (w *world) clientHop(b *box, hostname, path string, forged caller) bool { |
| - w.logf("box%d: a public client sends %s%s with X-Carlos-Hop-Caller %s", b.ID, hostname, path, forged.key()) |
| - if on("hop-caller-signed") { |
| - w.logf("box%d: unverified X-Carlos-Hop-Caller deleted; a public request", b.ID) |
| - if r := w.admitPublic(b, hostname, path); r != nil { |
| - w.deliver(r) |
| - } |
| - return false |
| - } |
| - return w.engineAdmit(b, b, forged, hostname, path, "", "", nil) |
| -} |
| - |
| -// homeOf is the box whose registry has hostname (the edge's home map). |
| -func (w *world) homeOf(hostname string) *box { |
| - for _, b := range w.boxes { |
| - if b.Rows[hostname] != nil { |
| - return b |
| - } |
| - } |
| - return nil |
| -} |
| - |
| -// exactRoute is the row an engine call to hostname resolves to on b: the |
| -// hostname's own row, through an alias (the same route), never a path map |
| -// (exact-route-engine). ok is false for an unknown host. |
| -func (w *world) exactRoute(b *box, hostname string) (row, bool) { |
| - final, ok := b.EdgeRows[hostname] |
| - if ok && final.Alias != "" { |
| - final, ok = b.EdgeRows[final.Alias] |
| - } |
| - return final, ok |
| -} |
| - |
| -// engineAdmit is the engine box (home) deciding an engine-marked request for |
| -// hostname: the route must be internal, the engine box's own table must name |
| -// the hostname for the mark's engine and grant it to the mark's app |
| -// (engine-box-recheck), and the route must be the hostname's own |
| -// (exact-route-engine). Then the activator's dispatch, which may wake the |
| -// engine. via is the instance whose engine socket or door key the call came |
| -// through ("" for a client's hop); real is the calling process's real app; |
| -// p the process. |
| -func (w *world) engineAdmit(home, from *box, mark caller, hostname, path, via, real string, p *proc) bool { |
| - final, ok := w.exactRoute(home, hostname) |
| - if !ok { |
| - w.logf("box%d: engine call to %s: unknown host", home.ID, hostname) |
| - return false |
| - } |
| - if !on("exact-route-engine") { |
| - if to, ok := final.PathTo[path]; ok { |
| - if t, ok := home.EdgeRows[to]; ok { |
| - w.logf("box%d: engine call to %s%s follows the path map to %s", home.ID, hostname, path, to) |
| - final = t |
| - } |
| - } |
| - } |
| - if home.Serving[final.Host] != markInternal { |
| - w.logf("box%d: engine call to %s: %s is not internal (%v): the internal refusal", home.ID, hostname, final.Host, home.Serving[final.Host]) |
| - return false |
| - } |
| - if on("engine-box-recheck") { |
| - if engineHosts[mark.Engine] != hostname || !w.tableGrants(home, mark.key()) { |
| - w.logf("box%d: engine box: %s not granted for %s: the internal refusal", home.ID, mark.key(), hostname) |
| - return false |
| - } |
| - } |
| - g := truthGroup(home, final.Host) |
| - q := w.newest(home, g) |
| - if q == nil { |
| - w.wake(home, g, "recovery", nil) |
| - q = w.newest(home, g) |
| - } |
| - if q == nil { |
| - w.logf("box%d: engine call: %s has no process; the wake failed", home.ID, g) |
| - return false |
| - } |
| - w.logf("box%d: engine call reaches process %d (%s v%d); the access log records caller %s", home.ID, q.ID, q.Group, q.Ver, mark.app()) |
| - w.events["engine-call-reached"]++ |
| - w.checkCall(home, from, mark, via, real, p, q) |
| - return true |
| -} |
| - |
| -// ---------- armed boxes (spec §6.2) ---------- |
| - |
| -// unisolatedKinds are the launch paths that run tenant code outside an |
| -// instance slice: a flat instance, a foreign one, and an app's worker. |
| -var unisolatedKinds = []string{"flat", "foreign", "worker"} |
| - |
| -// arm is `carlos engines arm`: refused unless every exec-backed instance |
| -// route is nested (unit-backed routes are judged by backing and admitted), |
| -// no route spawns workers, and every carlos-exec@ cgroup is empty |
| -// (arm-checks-box). Then the box records the armed state and the edge opens |
| -// the engine sockets. |
| -func (w *world) arm(b *box) bool { |
| - if b.Armed { |
| - return true |
| - } |
| - if on("arm-checks-box") { |
| - var why []string |
| - for _, k := range sortedKeys(b.Unisolated) { |
| - why = append(why, "a "+k+" route") |
| - } |
| - for _, p := range b.Procs { |
| - if p.Unisolated { |
| - why = append(why, fmt.Sprintf("process %d in %s", p.ID, p.Slice)) |
| - } |
| - } |
| - if len(why) > 0 { |
| - w.logf("box%d: carlos engines arm: refused: %s", b.ID, strings.Join(why, ", ")) |
| - return false |
| - } |
| - } |
| - b.Armed = true |
| - b.Sockets = true |
| - w.logf("box%d: armed; engine sockets open (arming vouches for the present, not the past)", b.ID) |
| - return true |
| -} |
| - |
| -// disarm is `carlos engines disarm`: it closes every engine socket first, |
| -// then clears the state; launches follow. |
| -func (w *world) disarm(b *box) { |
| - if !b.Armed { |
| - return |
| - } |
| - b.Sockets = false |
| - b.Armed = false |
| - w.logf("box%d: disarmed: engine sockets closed, then the state cleared", b.ID) |
| -} |
| - |
| -// launchUnisolated starts tenant code outside an instance slice: kind flat |
| -// or foreign (an instance of that layout, through the exec-child path) or |
| -// worker (an app's worker in carlos-exec@). While armed it is refused before |
| -// any process starts (armed-refuses-unisolated). The model's unisolated |
| -// tenants are one route per kind, acct/<kind>. |
| -func (w *world) launchUnisolated(b *box, kind string) bool { |
| - if b.Armed && on("armed-refuses-unisolated") { |
| - w.logf("box%d: %s launch refused: the box is armed (carlos engines disarm to run it)", b.ID, kind) |
| - return false |
| - } |
| - b.Unisolated[kind] = true |
| - w.nextID++ |
| - p := &proc{ID: w.nextID, Group: kind, Slice: "exec:" + kind, Unisolated: true} |
| - b.Procs = append(b.Procs, p) |
| - w.logf("box%d: %s tenant started as process %d in %s", b.ID, kind, p.ID, p.Slice) |
| - return true |
| -} |
| - |
| -// moveToNested is the operator moving the kind route off the box's |
| -// unisolated layouts (or its workers into instance slices): its processes |
| -// stop and the route no longer blocks arming. |
| -func (w *world) moveToNested(b *box, kind string) { |
| - w.stopGroup(b, kind) |
| - delete(b.Unisolated, kind) |
| - w.logf("box%d: the %s route moved to nested; its processes stopped", b.ID, kind) |
| -} |
| - |
| -// tamper is unisolated process by writing nested group g's instance |
| -// directory (an environment file and an LD_PRELOAD): g's next start runs by's |
| -// code inside g's slice. Only an unisolated process can, which an armed box |
| -// never runs; the walk generates it only under flatEraTamper. |
| -func (w *world) tamper(b *box, by *proc, g string) { |
| - b.Tampered[g] = w.realApp(b, by) |
| - w.logf("box%d: process %d (%s) plants code in %s's instance directory", b.ID, by.ID, by.Slice, g) |
| -} |
| - |
| -// applyTamper is a nested start picking up planted code (launch calls it). |
| -func (w *world) applyTamper(b *box, p *proc) { |
| - if app := b.Tampered[p.Group]; app != "" { |
| - p.Code = app |
| - w.logf("box%d: process %d of %s runs code %s planted", b.ID, p.ID, p.Group, app) |
| - } |
| -} |
| - |
| -// ---------- the random walk ---------- |
| - |
| -// walkApps are the apps the console may grant: the model's routes' apps and |
| -// the unisolated tenants'. |
| -var walkApps = []string{"acct/eng", "acct/flat", "acct/shop", "acct/tcp"} |
| - |
| -func (w *world) pickEngine() string { return []string{eng, site}[w.rng.Intn(2)] } |
| -func (w *world) pickPath() string { return []string{"/", engSitePath}[w.rng.Intn(2)] } |
| -func (w *world) pickKey() string { |
| - return walkApps[w.rng.Intn(len(walkApps))] + "/" + w.pickEngine() |
| -} |
| - |
| -// maybeForged is, one call in four, an X-Carlos-Hop-Caller the sender wrote. |
| -func (w *world) maybeForged() *caller { |
| - if w.rng.Intn(4) != 0 { |
| - return nil |
| - } |
| - c := callerOf(walkApps[w.rng.Intn(len(walkApps))], w.pickEngine()) |
| - return &c |
| -} |
| - |
| -// pickReplay is the revision a bucket writer replays: one that grants a key |
| -// the console has since revoked, if any (the damaging choice: half the time |
| -// the newest such, signed most recently, else any), else any older one. |
| -func (w *world) pickReplay() int { |
| - newest := w.console.Records[w.console.Rev] |
| - var damaging []int |
| - for r := 1; r < w.console.Rev; r++ { |
| - for k := range w.console.Records[r].Grants { |
| - if !newest.Grants[k] { |
| - damaging = append(damaging, r) |
| - break |
| - } |
| - } |
| - } |
| - if len(damaging) > 0 { |
| - if w.rng.Intn(2) == 0 { |
| - return damaging[len(damaging)-1] |
| - } |
| - return damaging[w.rng.Intn(len(damaging))] |
| - } |
| - return 1 + w.rng.Intn(w.console.Rev-1) |
| -} |
| - |
| -// walkReplay is the walk's bucket writer: it replays an older record and |
| -// keeps it in place for up to twenty minutes. |
| -func (w *world) walkReplay() bool { |
| - if w.console.Rev < 2 { |
| - return false |
| - } |
| - w.replayUntil(w.pickReplay(), w.now()+1+w.rng.Intn(2*staleTicks)) |
| - return true |
| -} |
| - |
| -// callers are the nested instance groups on b with an engine socket open. |
| -func (w *world) callers(b *box) []string { |
| - var out []string |
| - for _, g := range w.groups(b) { |
| - if w.socketOpen(b, g) { |
| - out = append(out, g) |
| - } |
| - } |
| - return out |
| -} |
| - |
| -func init() { |
| - stepHooks = append(stepHooks, |
| - // a bucket writer whose time is up stops; the console, while up, |
| - // re-signs every two minutes (R5) |
| - func(w *world) { |
| - c := &w.console |
| - if c.Pinned != nil && w.now() >= c.PinnedUntil { |
| - w.unpin() |
| - } |
| - if !c.Down && w.now()-c.Records[c.Rev].SignedAt >= resignTicks { |
| - w.publish(c.Rev + 1) |
| - } |
| - }, |
| - // the mirror polls every 30 s, whatever the walk does |
| - func(w *world) { |
| - if w.now()%pollTicks == 0 { |
| - for _, b := range w.boxes { |
| - w.mirrorTick(b) |
| - } |
| - } |
| - }) |
| - actions = append(actions, |
| - action{name: "engine-call", weight: 4, run: func(w *world) bool { |
| - b := w.pickBox() |
| - gs := w.callers(b) |
| - if len(gs) == 0 || len(b.Procs) == 0 { |
| - return false |
| - } |
| - host := gs[w.rng.Intn(len(gs))] |
| - // usually the instance's own process; one call in three, any |
| - // process on the box connects to the socket (mode 0666) |
| - p := w.newest(b, host) |
| - if p == nil || w.rng.Intn(3) == 0 { |
| - p = b.Procs[w.rng.Intn(len(b.Procs))] |
| - } |
| - c := call{from: b, p: p, uid: "carlos", host: host, engine: w.pickEngine(), path: w.pickPath()} |
| - c.forged = w.maybeForged() |
| - w.placeCall(c) |
| - return true |
| - }}, |
| - action{name: "door-call", weight: 1, run: func(w *world) bool { |
| - b := w.pickBox() |
| - gs := w.groups(b) |
| - if len(gs) == 0 { |
| - return false |
| - } |
| - host := gs[w.rng.Intn(len(gs))] |
| - c := call{from: b, viaDoor: true, host: host, engine: w.pickEngine(), path: w.pickPath()} |
| - if len(b.Procs) > 0 && w.rng.Intn(2) == 0 { |
| - // any process running as carlos presents host's door key |
| - // (every flat tenant can read every other's config) |
| - c.p, c.uid = b.Procs[w.rng.Intn(len(b.Procs))], "carlos" |
| - } else { |
| - // an enrolled host-app user: its own app's key, its own uid |
| - c.p, c.uid = &proc{Group: host, Slice: "user:u-" + host}, "u-"+host |
| - } |
| - c.forged = w.maybeForged() |
| - w.placeCall(c) |
| - return true |
| - }}, |
| - action{name: "client-hop", weight: 1, run: func(w *world) bool { |
| - hosts := []string{engHost, engSite} |
| - c := callerOf(walkApps[w.rng.Intn(len(walkApps))], w.pickEngine()) |
| - w.clientHop(w.pickBox(), hosts[w.rng.Intn(2)], w.pickPath(), c) |
| - return true |
| - }}, |
| - action{name: "console-grant", weight: 1, run: func(w *world) bool { return w.consoleGrant(w.pickKey()) }}, |
| - action{name: "console-revoke", weight: 1, run: func(w *world) bool { |
| - keys := sortedKeys(w.console.Grants) |
| - return len(keys) > 0 && w.consoleRevoke(keys[w.rng.Intn(len(keys))]) |
| - }}, |
| - action{name: "console-resign", weight: 1, run: func(w *world) bool { |
| - if w.console.Down { |
| - return false |
| - } |
| - w.publish(w.console.Rev + 1) |
| - return true |
| - }}, |
| - action{name: "console-down", weight: 1, run: func(w *world) bool { |
| - w.console.Down = !w.console.Down && !w.calm() |
| - w.logf("console: down = %v", w.console.Down) |
| - return true |
| - }}, |
| - action{name: "bucket-down", weight: 1, run: func(w *world) bool { |
| - w.setBucketDown(!w.console.BucketDown && !w.calm()) |
| - return true |
| - }}, |
| - action{name: "fast-forward", weight: 1, run: func(w *world) bool { |
| - if w.calm() { |
| - return false |
| - } |
| - if w.rng.Intn(8) == 0 { |
| - w.console.Down = true |
| - w.logf("console: down = true") |
| - w.advance(lifetimeTicks + staleTicks) // the console is down for three days |
| - return true |
| - } |
| - w.advance(staleTicks) // ten minutes with no poll |
| - return true |
| - }}, |
| - // any older signed record, at any time: the freshness bound, not the |
| - // walk, limits what a replay can do (R5) |
| - action{name: "replay", weight: 1, run: func(w *world) bool { |
| - return w.walkReplay() |
| - }}, |
| - action{name: "restart-edge", weight: 2, run: func(w *world) bool { |
| - switch w.rng.Intn(3) { |
| - case 0: // a release roll restarts every edge |
| - for _, b := range w.boxes { |
| - w.restartEdge(b) |
| - } |
| - case 1: |
| - w.restartEdge(w.pickBox()) |
| - default: |
| - // a rebuilt box, the engine's home included; a bucket writer |
| - // may replay at once |
| - w.rebuild(w.pickBox()) |
| - if w.rng.Intn(2) == 0 { |
| - w.walkReplay() |
| - } |
| - } |
| - return true |
| - }}, |
| - action{name: "arm", weight: 2, run: func(w *world) bool { |
| - b := w.pickBox() |
| - if b.Armed { |
| - return false |
| - } |
| - w.arm(b) |
| - return true |
| - }}, |
| - action{name: "disarm", weight: 1, run: func(w *world) bool { |
| - b := w.pickBox() |
| - if !b.Armed { |
| - return false |
| - } |
| - w.disarm(b) |
| - return true |
| - }}, |
| - action{name: "launch-unisolated", weight: 1, run: func(w *world) bool { |
| - b := w.pickBox() |
| - kind := unisolatedKinds[w.rng.Intn(len(unisolatedKinds))] |
| - if !w.launchUnisolated(b, kind) || !w.flatEraTamper || b.Armed { |
| - return true |
| - } |
| - var gs []string |
| - for _, g := range w.groups(b) { |
| - if !unitBacked(g) { |
| - gs = append(gs, g) |
| - } |
| - } |
| - if len(gs) > 0 { |
| - w.tamper(b, w.newest(b, kind), gs[w.rng.Intn(len(gs))]) |
| - } |
| - return true |
| - }}, |
| - action{name: "unisolated-exit", weight: 1, run: func(w *world) bool { |
| - b := w.pickBox() |
| - var ps []*proc |
| - for _, p := range b.Procs { |
| - if p.Unisolated { |
| - ps = append(ps, p) |
| - } |
| - } |
| - if len(ps) == 0 { |
| - return false |
| - } |
| - p := ps[w.rng.Intn(len(ps))] |
| - for i, x := range b.Procs { |
| - if x == p { |
| - b.Procs = append(b.Procs[:i], b.Procs[i+1:]...) |
| - break |
| - } |
| - } |
| - w.logf("box%d: process %d (%s) exited", b.ID, p.ID, p.Slice) |
| - return true |
| - }}, |
| - action{name: "move-to-nested", weight: 1, run: func(w *world) bool { |
| - b := w.pickBox() |
| - ks := sortedKeys(b.Unisolated) |
| - if len(ks) == 0 { |
| - return false |
| - } |
| - w.moveToNested(b, ks[w.rng.Intn(len(ks))]) |
| - return true |
| - }}, |
| - ) |
| -} |
| - |
| -// mirrorsState is a one-line summary of the console and every mirror, for a |
| -// failing witness. |
| -func (w *world) mirrorsState() string { |
| - out := []string{fmt.Sprintf("console{rev %d bucket %d bucketDown %v down %v pinned %v now %d}", w.console.Rev, w.console.Bucket.Rev, w.console.BucketDown, w.console.Down, w.console.Pinned != nil, w.now())} |
| - for _, b := range w.boxes { |
| - m := b.Mirror |
| - rev := 0 |
| - if m.Rec != nil { |
| - rev = m.Rec.Rev |
| - } |
| - out = append(out, fmt.Sprintf("box%d{rec %d floor %d readAt %d persisted %d readRev %d armed %v sockets %v}", b.ID, rev, m.Floor, m.ReadAt, m.PersistedFloor, b.ReadRev, b.Armed, b.Sockets)) |
| - } |
| - return strings.Join(out, " ") |
| -} |
diff --git a/internal/sim/engines/classify_test.go b/internal/sim/engines/classify_test.go| deleted file mode 100644 |
| index 84f6a9c53..000000000 |
| --- a/internal/sim/engines/classify_test.go |
| +++ /dev/null |
| @@ -1,592 +0,0 @@ |
| -package engines |
| - |
| -import ( |
| - "fmt" |
| - "sort" |
| - "strings" |
| -) |
| - |
| -// Classification, minted groups and the operator clear (spec §5.1 "The |
| -// column", "Platform-minted rows", "Becoming public is never automatic", |
| -// "Classification before serving"; §6.3). |
| - |
| -// ---------- minted groups ---------- |
| - |
| -// followsOwner: the row is a platform-minted row that takes its execution |
| -// owner's mark and barrier. Only minted instance rows do: a minted static or |
| -// service row is 0 by construction (static-minted-public). |
| -func followsOwner(r *row) bool { |
| - if !r.Platform || !on("minted-follow-owner") { |
| - return false |
| - } |
| - return r.Kind == "instance" || (r.Kind == "static" && !on("static-minted-public")) |
| -} |
| - |
| -// resolveOwner is the edge's (and the agent's) owner for a minted row, under |
| -// the rules in force. |
| -func (b *box) resolveOwner(r *row) (string, bool) { |
| - return b.resolveOwnerWith(r, on("owner-nonempty-unique")) |
| -} |
| - |
| -// resolveOwnerWith: the recorded owner, if its row exists; else the |
| -// non-platform instance row with the same account and app and the same |
| -// backend. strict is the spec's fallback: empty values never match, and a |
| -// match that is not unique counts as no match. Without it, empty values |
| -// match and the first match wins. |
| -func (b *box) resolveOwnerWith(r *row, strict bool) (string, bool) { |
| - if r.Owner != "" { |
| - if o := b.Rows[r.Owner]; o != nil && !o.Platform { |
| - return r.Owner, true |
| - } |
| - return "", false |
| - } |
| - var found []string |
| - for _, h := range hostsOf(b) { |
| - c := b.Rows[h] |
| - if c.Platform || c.Kind != "instance" || c.App != r.App { |
| - continue |
| - } |
| - cs, ca, rs, ra := socketOf(c), addrOf(c), socketOf(r), addrOf(r) |
| - if strict && ((cs != "" && cs == rs) || (ca != "" && ca == ra)) || |
| - !strict && (cs == rs || ca == ra) { |
| - found = append(found, h) |
| - } |
| - } |
| - if len(found) == 1 || (!strict && len(found) > 0) { |
| - return found[0], true |
| - } |
| - return "", false |
| -} |
| - |
| -// socketOf and addrOf split a backend into the registry's Socket and Addr. |
| -func socketOf(r *row) string { |
| - if strings.HasPrefix(r.Backend, "/") { |
| - return r.Backend |
| - } |
| - return "" |
| -} |
| - |
| -func addrOf(r *row) string { |
| - if r.Backend != "" && !strings.HasPrefix(r.Backend, "/") { |
| - return r.Backend |
| - } |
| - return "" |
| -} |
| - |
| -func hostsOf(b *box) []string { |
| - hosts := make([]string, 0, len(b.Rows)) |
| - for h := range b.Rows { |
| - hosts = append(hosts, h) |
| - } |
| - sort.Strings(hosts) |
| - return hosts |
| -} |
| - |
| -// truthGroup is the group a row really serves: a minted row's source, else |
| -// its own host. The oracle reads it; the protocol never does. |
| -func truthGroup(b *box, host string) string { |
| - if r := b.Rows[host]; r != nil && r.Platform && r.Source != "" { |
| - return r.Source |
| - } |
| - return host |
| -} |
| - |
| -// mint is the domains reconciler minting a platform row from src: it copies |
| -// the source's kind, backend and app (no version), and, being a row of the |
| -// same group, the group's mark. recordOwner is whether it writes |
| -// routes.owner (rows minted before the column was added have none until the |
| -// reconciler's next pass). |
| -func (w *world) mint(b *box, src, host string, recordOwner bool) { |
| - s := b.Rows[src] |
| - m := w.groupMark(b, w.group(b, src)) |
| - r := &row{Host: host, Kind: s.Kind, App: s.App, Backend: s.Backend, Platform: true, Source: src, PathTo: map[string]string{}} |
| - if recordOwner { |
| - r.Owner = src |
| - } |
| - b.Rows[host] = r |
| - b.Mark[host] = m |
| - b.Wrote++ |
| - w.logf("box%d: registry change %d: minted %s %s from %s (owner %q, mark %v)", b.ID, b.Wrote, r.Kind, host, src, r.Owner, m) |
| -} |
| - |
| -// reconcileOwners is the reconciler's backfill pass: it records the owner of |
| -// every minted instance row that has none. The row takes its owner group's |
| -// mark (one group, one mark). It reports whether it recorded any. |
| -func (w *world) reconcileOwners(b *box) bool { |
| - did := false |
| - for _, h := range hostsOf(b) { |
| - r := b.Rows[h] |
| - if !r.Platform || r.Kind != "instance" || r.Owner != "" || b.Rows[r.Source] == nil { |
| - continue |
| - } |
| - m := w.groupMark(b, w.group(b, r.Source)) |
| - r.Owner = r.Source |
| - b.Mark[h] = m |
| - b.Wrote++ |
| - did = true |
| - w.logf("box%d: registry change %d: owner of %s recorded as %s (mark %v)", b.ID, b.Wrote, h, r.Owner, m) |
| - } |
| - return did |
| -} |
| - |
| -// provision creates instance route host (a new route: NULL, unclassified), |
| -// then its first adoption classifies it before it is served: a declaring |
| -// build through the gate, a readable plain one as 0 (spec §5.1, "A route the |
| -// agent creates later ... is classified by its first adoption"). |
| -func (w *world) provision(b *box, host, app, backend string, ver int) bool { |
| - b.Rows[host] = &row{Host: host, Kind: "instance", App: app, Backend: backend, PathTo: map[string]string{}} |
| - b.Wrote++ |
| - w.logf("box%d: registry change %d: provisioned %s (%s, %s), NULL until its first adoption", b.ID, b.Wrote, host, app, backend) |
| - ok := w.adopt(b, host, ver, nil) |
| - if w.groupMark(b, host) == markNull { |
| - if m := w.classify(b, host); m != markNull { |
| - w.writeMark(b, host, m) |
| - } |
| - } |
| - return ok |
| -} |
| - |
| -// addStaticApp creates static app name with its minted platform row and a |
| -// static canary on its own channel (domains/reconcile.go:368). |
| -func (w *world) addStaticApp(b *box, name string) (minted, canary string) { |
| - b.Rows[name] = &row{Host: name, Kind: "static", App: "acct/" + name, PathTo: map[string]string{}} |
| - b.Mark[name] = markPublic // 0 by construction |
| - b.Wrote++ |
| - w.logf("box%d: registry change %d: static app %s", b.ID, b.Wrote, name) |
| - minted, canary = name+".acct.apps.example", "canary-"+name+".acct.apps.example" |
| - w.mint(b, name, minted, true) |
| - w.mint(b, name, canary, true) |
| - return minted, canary |
| -} |
| - |
| -// ---------- grants ---------- |
| - |
| -// groupHasGrant: a row of group g holds the doc-engine grant. With |
| -// grant-marks-group, any row of the group; without it, only the owner's own |
| -// row (a grant on a minted row is ignored, R6-1). |
| -func (w *world) groupHasGrant(b *box, g string) bool { |
| - if !on("grant-marks-group") { |
| - r := b.Rows[g] |
| - return r != nil && r.Grant |
| - } |
| - for _, h := range w.groupHosts(b, g) { |
| - if b.Rows[h].Grant { |
| - return true |
| - } |
| - } |
| - return false |
| -} |
| - |
| -// grantLoaded is the oracle's grant: a row whose true group is g holds the |
| -// grant and the edge has loaded the change that recorded it. It returns that |
| -// row, or "". |
| -func (w *world) grantLoaded(b *box, g string) string { |
| - for _, h := range hostsOf(b) { |
| - r := b.Rows[h] |
| - if r.Grant && truthGroup(b, h) == g && b.Fenced >= r.GrantAt { |
| - return h |
| - } |
| - } |
| - return "" |
| -} |
| - |
| -// grant is `carlos route --host <host> --grant doc-engine`: it records the |
| -// grant, writes 1 on the group if the group now holds it, and returns once |
| -// the edge has loaded the change (or says it timed out). On a minted row |
| -// whose owner cannot be resolved it is refused: the CLI cannot find the |
| -// group to mark, and the row itself stays NULL and refused. |
| -func (w *world) grant(b *box, host string) bool { |
| - r := b.Rows[host] |
| - if r == nil || r.Kind != "instance" || r.Grant { |
| - return false |
| - } |
| - if followsOwner(r) { |
| - if _, ok := b.resolveOwner(r); !ok { |
| - w.logf("box%d: --grant doc-engine on %s: refused: the row's owner is not recorded and cannot be found uniquely; the row stays NULL and refused", b.ID, host) |
| - return false |
| - } |
| - } |
| - b.Wrote++ |
| - r.Grant, r.GrantAt = true, b.Wrote |
| - g := w.group(b, host) |
| - w.logf("box%d: registry change %d: --grant doc-engine on %s (group %s)", b.ID, b.Wrote, host, g) |
| - if w.groupHasGrant(b, g) && w.groupMark(b, g) != markInternal { |
| - w.writeMark(b, g, markInternal) |
| - } |
| - want := b.Wrote |
| - for i := 0; i < fenceWaitTicks && b.Fenced < want; i++ { |
| - w.reload(b) |
| - } |
| - if b.Fenced < want { |
| - w.logf("box%d: --grant on %s: the edge has not loaded it; timed out", b.ID, host) |
| - return false |
| - } |
| - return true |
| -} |
| - |
| -// revoke is --revoke doc-engine on any row of a group: the grant goes and |
| -// the group's mark stays (becoming public is never automatic; only --public |
| -// writes 0). Like --grant it runs the barrier for the group: it returns once |
| -// the edge has loaded the change, so the group's mark is fenced, or says it |
| -// timed out. Refused on a minted row whose owner cannot be resolved. |
| -func (w *world) revoke(b *box, host string) bool { |
| - r := b.Rows[host] |
| - if r == nil || !r.Grant { |
| - return false |
| - } |
| - if followsOwner(r) { |
| - if _, ok := b.resolveOwner(r); !ok { |
| - w.logf("box%d: --revoke doc-engine on %s: refused: the row's owner cannot be resolved", b.ID, host) |
| - return false |
| - } |
| - } |
| - g := w.group(b, host) |
| - b.Wrote++ |
| - r.Grant = false |
| - want := b.Wrote |
| - w.logf("box%d: registry change %d: --revoke doc-engine on %s (group %s); the mark stays %v", b.ID, b.Wrote, host, g, w.groupMark(b, g)) |
| - for i := 0; i < fenceWaitTicks && b.Fenced < want; i++ { |
| - w.reload(b) |
| - } |
| - if b.Fenced < want { |
| - w.logf("box%d: --revoke on %s: the edge has not loaded it; timed out", b.ID, host) |
| - return false |
| - } |
| - return true |
| -} |
| - |
| -// ---------- classification before serving ---------- |
| - |
| -// classify is the upgrade's classification of group g: 1 if a row of the |
| -// group holds the grant, the live manifest declares, or the manifest of any |
| -// other version of the app staged on the box declares, whichever instance of |
| -// the app staged it (classify-staged); 0 if the live manifest is readable and |
| -// none of those holds; else NULL. |
| -func (w *world) classify(b *box, g string) mark { |
| - if w.groupHasGrant(b, g) { |
| - return markInternal |
| - } |
| - live, liveOK := w.builds[b.Live[g]] |
| - liveOK = liveOK && b.Live[g] != 0 && live.ManifestOK |
| - if liveOK && live.Declares { |
| - return markInternal |
| - } |
| - if on("classify-staged") { |
| - for _, v := range w.stagedForApp(b, g) { |
| - if bd := w.builds[v]; bd.ManifestOK && bd.Declares { |
| - return markInternal |
| - } |
| - } |
| - } |
| - if liveOK { |
| - return markPublic |
| - } |
| - return markNull |
| -} |
| - |
| -// classifiedGroups is every group with a row the classification covers: an |
| -// instance row, or a row that follows an owner. |
| -func (w *world) classifiedGroups(b *box) []string { |
| - seen := map[string]bool{} |
| - var out []string |
| - for _, h := range hostsOf(b) { |
| - r := b.Rows[h] |
| - if r.Kind != "instance" && !followsOwner(r) { |
| - continue |
| - } |
| - if g := w.group(b, h); !seen[g] { |
| - seen[g] = true |
| - out = append(out, g) |
| - } |
| - } |
| - return out |
| -} |
| - |
| -// upgrade is the agent's first start on the build that adds routes.internal. |
| -// The column arrives NULL on every instance route; before any edge listener |
| -// opens, the agent classifies every NULL group. The edge then starts on the |
| -// classified map: in-flight requests did not survive the restart, and the |
| -// fence covers everything written. Running processes are untouched. |
| -func (w *world) upgrade(b *box) { |
| - if w.unwrittenManifestAcrossUpgrade { |
| - if why, procs := w.upgradeResidual(b); why != "" { |
| - for _, p := range procs { |
| - p.Residual = "unwrittenManifestAcrossUpgrade" |
| - } |
| - w.logf("box%d: upgrade: the stated residual (%s); its processes' breaches are counted as residual", b.ID, why) |
| - } |
| - } |
| - gs := w.classifiedGroups(b) |
| - w.logf("box%d: upgrade: routes.internal arrives NULL on %v", b.ID, gs) |
| - for _, g := range gs { |
| - w.writeMark(b, g, markNull) |
| - } |
| - for _, g := range gs { |
| - if m := w.classify(b, g); m != markNull { |
| - w.writeMark(b, g, m) |
| - } else { |
| - w.logf("box%d: upgrade: %s stays NULL (live manifest unreadable): refused publicly, named every pass", b.ID, g) |
| - } |
| - } |
| - b.loadEdge() |
| - b.Epoch++ |
| - if len(b.Admitted) > 0 { |
| - w.logf("box%d: upgrade: %d in-flight requests ended with the restart", b.ID, len(b.Admitted)) |
| - } |
| - b.Admitted = nil |
| - b.Fenced = b.Wrote |
| - // the restart loaded every group's mark and drained the whole box: a |
| - // fence for every closed group, NULL included |
| - for _, g := range gs { |
| - if w.closed(b, g) && !w.recorded(b, g) { |
| - b.SetAt[g] = b.Wrote |
| - } |
| - } |
| - w.logf("box%d: upgrade: listeners open on the classified map, epoch %d, fenced %d", b.ID, b.Epoch, b.Fenced) |
| -} |
| - |
| -// residualAtUpgrade names the spec's stated residual if an upgrade of b now |
| -// would produce it: a running declaring build whose manifest cannot be read, |
| -// in a group the (correct) classification would mark 0 because the live |
| -// manifest reads and does not declare. The default world does not generate |
| -// it; Task 5's flag (unwrittenManifestAcrossUpgrade) does. |
| -func (w *world) residualAtUpgrade(b *box) string { |
| - why, _ := w.upgradeResidual(b) |
| - return why |
| -} |
| - |
| -// upgradeResidual is residualAtUpgrade with the processes it names: every |
| -// running unreadable declaring process of each group it applies to. |
| -func (w *world) upgradeResidual(b *box) (string, []*proc) { |
| - first := "" |
| - var procs []*proc |
| - for _, g := range w.groups(b) { |
| - var unreadable *proc |
| - var group []*proc |
| - for _, p := range b.Procs { |
| - if bd := w.builds[p.Ver]; p.Group == g && bd.Declares && !bd.ManifestOK { |
| - unreadable = p |
| - group = append(group, p) |
| - } |
| - } |
| - if unreadable == nil { |
| - continue |
| - } |
| - granted := false |
| - for _, h := range hostsOf(b) { |
| - granted = granted || (b.Rows[h].Grant && truthGroup(b, h) == g) |
| - } |
| - live, ok := w.builds[b.Live[g]] |
| - if granted || b.Live[g] == 0 || !ok || !live.ManifestOK || live.Declares { |
| - continue |
| - } |
| - staged := false |
| - for _, v := range w.stagedForApp(b, g) { |
| - if bd := w.builds[v]; bd.ManifestOK && bd.Declares { |
| - staged = true |
| - } |
| - } |
| - if !staged { |
| - if first == "" { |
| - first = fmt.Sprintf("%s runs v%d (declares, manifest unreadable) while live v%d reads as plain", g, unreadable.Ver, b.Live[g]) |
| - } |
| - procs = append(procs, group...) |
| - } |
| - } |
| - return first, procs |
| -} |
| - |
| -// ---------- the operator clear ---------- |
| - |
| -// operatorPublic is `carlos route --host <host> --public` on group g (spec |
| -// §5.1, "Becoming public is never automatic"). Holding the group's lock for |
| -// its whole run (adoption's repoint honours it, public-holds-lock; so does |
| -// every launch through the gate, clear-launch-lock): |
| -// 1. refuse unless the live manifest is readable and does not declare |
| -// (public-checks-live), and no row of the group holds the grant; |
| -// 2. stop the whole group (public-stops-group); |
| -// 3. refuse unless every cgroup of the group is empty (public-confirms-empty); |
| -// 4. write 0 and release the lock. |
| -// |
| -// Step 3 is what catches a stop that did not complete (w.clearStopMisses). |
| -// |
| -// w.clearHook, if set, runs after step 1 ("locked"), after step 2 |
| -// ("stopped") and after step 3 ("confirmed"). |
| -func (w *world) operatorPublic(b *box, g string) bool { |
| - w.logf("box%d: --public %s: taking the group's lock", b.ID, g) |
| - b.Locked[g] = true |
| - defer delete(b.Locked, g) |
| - if on("public-checks-live") { |
| - live, ok := w.builds[b.Live[g]] |
| - if b.Live[g] == 0 || !ok || !live.ManifestOK || live.Declares { |
| - w.logf("box%d: --public %s: refused: the live release v%d is unreadable or declares doc_engine", b.ID, g, b.Live[g]) |
| - return false |
| - } |
| - } |
| - if w.groupHasGrant(b, g) { |
| - w.logf("box%d: --public %s: refused: a row of the group holds the doc-engine grant", b.ID, g) |
| - return false |
| - } |
| - w.hook(b, g, "locked") |
| - if on("public-stops-group") { |
| - w.clearStop(b, g) |
| - } |
| - w.hook(b, g, "stopped") |
| - if on("public-confirms-empty") && w.running(b, g) { |
| - w.logf("box%d: --public %s: refused: a cgroup of the group is not empty", b.ID, g) |
| - return false |
| - } |
| - w.hook(b, g, "confirmed") |
| - w.writeMark(b, g, markPublic) |
| - w.logf("box%d: --public %s: 0 written; the lock is released", b.ID, g) |
| - return true |
| -} |
| - |
| -// clearStop is step 2: stop every process of group g, except, when |
| -// w.clearStopMisses is set, the first one, whose stop did not complete. |
| -func (w *world) clearStop(b *box, g string) { |
| - var left *proc |
| - if w.clearStopMisses { |
| - for _, p := range b.Procs { |
| - if p.Group == g { |
| - left = p |
| - break |
| - } |
| - } |
| - } |
| - w.stopGroup(b, g) |
| - if left != nil { |
| - b.Procs = append(b.Procs, left) |
| - w.logf("box%d: --public %s: the stop did not complete: process %d (v%d) still runs", b.ID, g, left.ID, left.Ver) |
| - return |
| - } |
| - w.logf("box%d: --public %s: the group is stopped", b.ID, g) |
| -} |
| - |
| -func (w *world) hook(b *box, g, stage string) { |
| - if w.clearHook != nil { |
| - w.clearHook(b, g, stage) |
| - } |
| -} |
| - |
| -// ---------- the random walk ---------- |
| - |
| -// pickInstanceRow is any instance row of b, minted included, or "". |
| -func (w *world) pickInstanceRow(b *box) string { |
| - var hs []string |
| - for _, h := range hostsOf(b) { |
| - if b.Rows[h].Kind == "instance" { |
| - hs = append(hs, h) |
| - } |
| - } |
| - if len(hs) == 0 { |
| - return "" |
| - } |
| - return hs[w.rng.Intn(len(hs))] |
| -} |
| - |
| -// maxRows bounds a box's table in the walk. |
| -const maxRows = 24 |
| - |
| -func init() { |
| - actions = append(actions, |
| - action{name: "upgrade", weight: 1, run: func(w *world) bool { |
| - b := w.pickBox() |
| - if why := w.residualAtUpgrade(b); why != "" && !w.unwrittenManifestAcrossUpgrade { |
| - w.logf("box%d: upgrade not generated: the stated residual (%s)", b.ID, why) |
| - return false |
| - } |
| - w.upgrade(b) |
| - return true |
| - }}, |
| - action{name: "grant", weight: 1, run: func(w *world) bool { |
| - b := w.pickBox() |
| - h := w.pickInstanceRow(b) |
| - if h == "" || b.Rows[h].Grant { |
| - return false |
| - } |
| - w.grant(b, h) |
| - return true |
| - }}, |
| - action{name: "revoke", weight: 1, run: func(w *world) bool { |
| - b := w.pickBox() |
| - h := w.pickInstanceRow(b) |
| - if h == "" || !b.Rows[h].Grant { |
| - return false |
| - } |
| - w.revoke(b, h) |
| - return true |
| - }}, |
| - action{name: "operator-public", weight: 2, run: func(w *world) bool { |
| - b := w.pickBox() |
| - g := w.pickGroup(b) |
| - if g == "" { |
| - return false |
| - } |
| - switch w.rng.Intn(5) { |
| - case 1: // an adoption tries to run during the clear |
| - w.clearHook = func(hb *box, hg, stage string) { |
| - if stage == "locked" { |
| - w.adopt(hb, hg, w.pickVer(), nil) |
| - } |
| - } |
| - case 2: // an awake repoint tries to run during the clear |
| - w.clearHook = func(hb *box, hg, stage string) { |
| - if stage == "locked" { |
| - w.repointAwake(hb, hg, w.pickVer()) |
| - } |
| - } |
| - case 3: // a swap's incoming generation races the stop |
| - w.clearHook = func(hb *box, hg, stage string) { |
| - if stage == "stopped" { |
| - w.launch(hb, hg, w.pickVer(), "swap") |
| - } |
| - } |
| - case 4: // a launch races the write of 0, after the empty check |
| - w.clearHook = func(hb *box, hg, stage string) { |
| - if stage == "confirmed" { |
| - w.launch(hb, hg, w.pickVer(), []string{"cmd", "recovery", "seed"}[w.rng.Intn(3)]) |
| - } |
| - } |
| - } |
| - w.clearStopMisses = w.rng.Intn(4) == 0 |
| - w.operatorPublic(b, g) |
| - w.clearHook, w.clearStopMisses = nil, false |
| - return true |
| - }}, |
| - action{name: "adopt-awake", weight: 2, run: func(w *world) bool { |
| - b := w.pickBox() |
| - g := w.pickGroup(b) |
| - if g == "" { |
| - return false |
| - } |
| - w.repointAwake(b, g, w.pickVer()) |
| - return true |
| - }}, |
| - action{name: "add-tcp-instance", weight: 1, run: func(w *world) bool { |
| - b := w.pickBox() |
| - if len(b.Rows) >= maxRows { |
| - return false |
| - } |
| - w.nextID++ |
| - host := fmt.Sprintf("t%d", w.nextID) |
| - app := []string{"acct/shop", "acct/tcp"}[w.rng.Intn(2)] |
| - addr := fmt.Sprintf("10.0.%d.1:%d", b.ID, 9100+w.nextID) // unique: no ambiguous owner in the walk |
| - w.provision(b, host, app, addr, w.pickVer()) |
| - w.mint(b, host, host+".acct.apps.example", w.rng.Intn(2) == 0) |
| - return true |
| - }}, |
| - action{name: "add-static-app", weight: 1, run: func(w *world) bool { |
| - b := w.pickBox() |
| - if len(b.Rows) >= maxRows { |
| - return false |
| - } |
| - w.nextID++ |
| - w.addStaticApp(b, fmt.Sprintf("s%d", w.nextID)) |
| - return true |
| - }}, |
| - action{name: "reconcile-owners", weight: 1, run: func(w *world) bool { |
| - return w.reconcileOwners(w.pickBox()) |
| - }}, |
| - ) |
| -} |
diff --git a/internal/sim/engines/dedicated_test.go b/internal/sim/engines/dedicated_test.go| deleted file mode 100644 |
| index 620dc809e..000000000 |
| --- a/internal/sim/engines/dedicated_test.go |
| +++ /dev/null |
| @@ -1,508 +0,0 @@ |
| -package engines |
| - |
| -import ( |
| - "fmt" |
| - "sort" |
| - "strings" |
| -) |
| - |
| -// The dedicated engine box and ingress (spec §5.9 "The engine box is |
| -// dedicated"; §5.1 "The edge is the only ingress"). |
| -// |
| -// I1 keeps a declaring build from starting before the edge refuses the |
| -// public, but the edge is not the only way to a process on its box. These |
| -// rules close the others: |
| -// |
| -// - ports-excluded: a release declaring doc_engine and ports is refused at |
| -// ship, and the box renders no ListenStream for an internal group. The |
| -// capability pass removes an existing one whenever the group's mark |
| -// closes (writeMark calls dropListeners), so it is gone before any fence |
| -// of that write completes. |
| -// - dedicated-launch-check: a declaring launch is refused on a box with a |
| -// proxying row outside its group (the gate, before it writes or waits). |
| -// - dedicated-edge-refusal: while an internal group is homed on the box, |
| -// the edge gives every proxying row outside that group the internal |
| -// refusal. |
| -// - ingress-precondition: the operator's firewall admits connections from |
| -// every source, public or private (the deployment's other boxes too), |
| -// only on the edge's ports and the ports the operator granted. It is a |
| -// world flag, not a box mechanism: the platform cannot see it. |
| -// |
| -// A proxying row is an instance or service row with a backend: the edge |
| -// proxies it to a process. Static rows (and the status host, the tunnel and |
| -// steering handlers, which the model does not have) are answered by the edge |
| -// itself. Alias rows and path maps resolve to their final row, and the edge |
| -// checks that one. |
| - |
| -// ---------- addresses ---------- |
| - |
| -// A TCP backend is on a box by its subnet, 10.0.<box>.<n>:<port>; a socket |
| -// path or 127.0.0.1 is reachable on its own box only. |
| - |
| -// boxAddr is box b's address. |
| -func boxAddr(b *box) string { return fmt.Sprintf("10.0.%d.1", b.ID) } |
| - |
| -// addrBox is the box an address backend is on, and its port; nil for a |
| -// socket path, loopback, or an address on no box. |
| -func (w *world) addrBox(backend string) (*box, string) { |
| - i := strings.LastIndex(backend, ":") |
| - if strings.HasPrefix(backend, "/") || i < 0 { |
| - return nil, "" |
| - } |
| - for _, b := range w.boxes { |
| - if strings.HasPrefix(backend[:i], fmt.Sprintf("10.0.%d.", b.ID)) { |
| - return b, backend[i+1:] |
| - } |
| - } |
| - return nil, "" |
| -} |
| - |
| -// ownPort is the port process p binds on its own, if it does (OwnPort). |
| -func ownPort(p *proc) string { return fmt.Sprint(20000 + p.ID) } |
| - |
| -// bindOwnPort is process p binding a port of its own on every interface: |
| -// the unit template allows it and the capability validator leaves high |
| -// ports to the app (spec §5.9, codex R12-1). |
| -func (w *world) bindOwnPort(b *box, p *proc) { |
| - p.OwnPort = true |
| - w.logf("box%d: process %d (%s v%d) binds port %s on every interface", b.ID, p.ID, p.Group, p.Ver, ownPort(p)) |
| -} |
| - |
| -// newest is group g's newest process on b, or nil. |
| -func (w *world) newest(b *box, g string) *proc { |
| - var p *proc |
| - for _, x := range b.Procs { |
| - if x.Group == g { |
| - p = x |
| - } |
| - } |
| - return p |
| -} |
| - |
| -// ---------- service rows ---------- |
| - |
| -// proxying: the edge proxies the row to a process. |
| -func proxying(r *row) bool { |
| - return (r.Kind == "instance" || r.Kind == "service") && r.Backend != "" |
| -} |
| - |
| -// addServiceRow is `carlos add` of a service row on box b whose upstream is |
| -// backend: a socket path or address on b, or, from box 1, box 0's address. |
| -// A service row is 0 by construction. |
| -func (w *world) addServiceRow(b *box, host, backend string) { |
| - b.Rows[host] = &row{Host: host, Kind: "service", Backend: backend, PathTo: map[string]string{}} |
| - b.Mark[host] = markPublic |
| - b.Wrote++ |
| - w.logf("box%d: registry change %d: service row %s -> %s", b.ID, b.Wrote, host, backend) |
| -} |
| - |
| -// deleteRow removes a service row. A request admitted through it keeps the |
| -// proxy it holds (the fence's business, fence-box-wide). |
| -func (w *world) deleteRow(b *box, host string) { |
| - delete(b.Rows, host) |
| - delete(b.Mark, host) |
| - b.Wrote++ |
| - w.logf("box%d: registry change %d: row %s deleted", b.ID, b.Wrote, host) |
| -} |
| - |
| -// removeGroup is the operator removing instance route g from b, as the |
| -// dedicated-box refusal's log line tells them to: its processes stop, its |
| -// rows and the rows minted from it go, and so do its listeners. The app's |
| -// staged versions stay on the box (/opt/carlos/versions is per app): any |
| -// recorded under g pass to another instance of the app. |
| -func (w *world) removeGroup(b *box, g string) { |
| - others := []string{} |
| - for _, h := range w.appGroups(b, g) { |
| - if h != g { |
| - others = append(others, h) |
| - } |
| - } |
| - if len(others) > 0 { |
| - for _, v := range b.Staged[g] { |
| - b.Staged[others[0]] = append(b.Staged[others[0]], v) |
| - } |
| - } |
| - w.stopGroup(b, g) |
| - for _, h := range hostsOf(b) { |
| - if r := b.Rows[h]; h == g || (r.Platform && r.Source == g) { |
| - delete(b.Rows, h) |
| - delete(b.Mark, h) |
| - } |
| - } |
| - for port, lg := range b.Listen { |
| - if lg == g { |
| - delete(b.Listen, port) |
| - } |
| - } |
| - delete(b.Live, g) |
| - delete(b.Good, g) |
| - delete(b.Staged, g) |
| - delete(b.SetAt, g) |
| - delete(b.PortGrant, g) |
| - b.Wrote++ |
| - w.logf("box%d: registry change %d: route %s removed with its minted rows", b.ID, b.Wrote, g) |
| -} |
| - |
| -// ---------- the dedicated box ---------- |
| - |
| -// dedicatedLaunchCheck is the launch gate's check before it writes or waits |
| -// for anything: a declaring launch in group g is refused while any proxying |
| -// row of the box's registry belongs to another group, and each such row is |
| -// named with the move or remove command. |
| -func (w *world) dedicatedLaunchCheck(b *box, g string, ver int, path string) bool { |
| - if !on("dedicated-launch-check") { |
| - return true |
| - } |
| - var outside []string |
| - for _, h := range hostsOf(b) { |
| - if r := b.Rows[h]; proxying(r) && w.group(b, h) != g { |
| - outside = append(outside, h) |
| - } |
| - } |
| - for _, h := range outside { |
| - w.logf("box%d: gate(%s) %s v%d: %s row %s proxies outside the group on the box that would home an engine; move or remove it", b.ID, path, g, ver, b.Rows[h].Kind, h) |
| - } |
| - if len(outside) > 0 { |
| - w.logf("box%d: gate(%s) %s v%d: refused: the box is not dedicated", b.ID, path, g, ver) |
| - return false |
| - } |
| - return true |
| -} |
| - |
| -// edgeHomed is every internal group homed on b, as the edge's map has it: a |
| -// group whose own route the edge serves 1 or NULL. The edge refuses NULL like |
| -// 1 (classify-null-refused), and so does this rule, release or not: a gate |
| -// writing 1 over a NULL group finds it fenced already and bumps no epoch, so |
| -// a request admitted through a row beside a NULL route would outlive a |
| -// declaring launch there (TestNullRouteHomesTheBox). The cost: a NULL route |
| -// on a shared box (an upgrade that cannot read its live manifest, a |
| -// provisioned route whose declaring first adoption the launch check refused) |
| -// takes every proxying neighbour out of service until it is classified. |
| -func (w *world) edgeHomed(b *box) map[string]bool { |
| - homed := map[string]bool{} |
| - for h, r := range b.EdgeRows { |
| - if r.Kind != "instance" || r.Platform { |
| - continue |
| - } |
| - if m := b.Serving[h]; m == markInternal || (m == markNull && on("classify-null-refused")) { |
| - homed[h] = true |
| - } |
| - } |
| - return homed |
| -} |
| - |
| -// dedicatedRefusal is the edge's refusal of final, the row a public request |
| -// resolved to: on a box that homes an internal group, a proxying row of any |
| -// other group gets the internal refusal. It returns why, or "" when the row |
| -// is served. |
| -func (w *world) dedicatedRefusal(b *box, final row) string { |
| - if !on("dedicated-edge-refusal") || !proxying(&final) { |
| - return "" |
| - } |
| - homed := w.edgeHomed(b) |
| - if len(homed) == 0 || homed[edgeGroup(b, final.Host)] { |
| - return "" |
| - } |
| - return fmt.Sprintf("%s row %s proxies outside %v, the internal group homed on the box; move or remove it", final.Kind, final.Host, sortedKeys(homed)) |
| -} |
| - |
| -func sortedKeys(m map[string]bool) []string { |
| - out := make([]string, 0, len(m)) |
| - for k := range m { |
| - out = append(out, k) |
| - } |
| - sort.Strings(out) |
| - return out |
| -} |
| - |
| -// ---------- ports ---------- |
| - |
| -// ship is `carlos ship` of build ver's release for group g, its capability |
| -// block declaring ports or not, then its adoption on b. A ports release |
| -// records the operator's grant (a port) and the capability pass runs. |
| -func (w *world) ship(b *box, g string, ver int, ports bool) bool { |
| - if ports && w.builds[ver].Declares && on("ports-excluded") { |
| - w.logf("ship %s v%d: refused: the release declares doc_engine and ports together", g, ver) |
| - return false |
| - } |
| - if !w.adopt(b, g, ver, nil) { |
| - return false |
| - } |
| - if ports && b.PortGrant[g] == "" { |
| - w.nextID++ |
| - b.PortGrant[g] = fmt.Sprint(40000 + w.nextID) |
| - w.logf("box%d: %s holds a ports grant: port %s", b.ID, g, b.PortGrant[g]) |
| - } |
| - w.capsPass(b) |
| - return true |
| -} |
| - |
| -// capsPass is the agent's capability pass: it renders each granted port's |
| -// ListenStream, except for a route of an internal group, whose listener it |
| -// removes. It fails closed: the route's own mark or any row of its group |
| -// being 1 or NULL is enough. |
| -func (w *world) capsPass(b *box) { |
| - gs := make([]string, 0, len(b.PortGrant)) |
| - for g := range b.PortGrant { |
| - gs = append(gs, g) |
| - } |
| - sort.Strings(gs) |
| - for _, g := range gs { |
| - if on("ports-excluded") && (b.Mark[g] != markPublic || w.closed(b, g)) { |
| - w.dropListeners(b, g) |
| - continue |
| - } |
| - if port := b.PortGrant[g]; b.Listen[port] != g { |
| - b.Listen[port] = g |
| - w.logf("box%d: capability pass renders ListenStream=%s for %s", b.ID, port, g) |
| - } |
| - } |
| -} |
| - |
| -// dropListeners removes group g's ListenStream sockets, stopping their |
| -// socket units, and logs the grant it is ignoring. writeMark calls it on |
| -// every write of 1 or NULL. |
| -func (w *world) dropListeners(b *box, g string) { |
| - if !on("ports-excluded") { |
| - return |
| - } |
| - ports := make([]string, 0, len(b.Listen)) |
| - for port, lg := range b.Listen { |
| - if lg == g { |
| - ports = append(ports, port) |
| - } |
| - } |
| - sort.Strings(ports) |
| - for _, port := range ports { |
| - delete(b.Listen, port) |
| - w.logf("box%d: %s is internal: ListenStream=%s removed, its ports grant ignored (revoke it with carlos caps)", b.ID, g, port) |
| - } |
| -} |
| - |
| -// ---------- ingress ---------- |
| - |
| -// directConnect is a connection to port on box b that does not go through |
| -// b's edge: from the internet, or from another box (a service row there |
| -// aimed at b's address). A ports listener takes it whatever the firewall |
| -// flag (the operator granted that port, so the firewall admits it); a stopped |
| -// unit is socket-activated from its live link. Otherwise it reaches a process |
| -// only if the ingress precondition is violated: one bound to the port on its |
| -// own, or a TCP route's backend. |
| -func (w *world) directConnect(b *box, port string, public bool) *proc { |
| - return w.connect(b, port, public, true) |
| -} |
| - |
| -// connect is directConnect, or with firewalled false the box's own traffic |
| -// (a local row's proxy to an address on its own box), which no firewall sees. |
| -func (w *world) connect(b *box, port string, public, firewalled bool) *proc { |
| - src := "private" |
| - if public { |
| - src = "public" |
| - } |
| - if g, ok := b.Listen[port]; ok { |
| - w.logf("box%d: %s connection to port %s: the ports listener of %s", b.ID, src, port, g) |
| - w.socketActivate(b, g) |
| - return w.reach(b, w.newest(b, g), public, "the ports listener on "+port) |
| - } |
| - if firewalled && on("ingress-precondition") { |
| - w.logf("box%d: %s connection to port %s: refused by the firewall (the edge's ports only)", b.ID, src, port) |
| - return nil |
| - } |
| - return w.reach(b, w.portProc(b, port), public, "port "+port) |
| -} |
| - |
| -// portProc is the process listening on port on b: one bound to it on its |
| -// own, else the newest process of the TCP route whose backend it is. |
| -func (w *world) portProc(b *box, port string) *proc { |
| - for i := len(b.Procs) - 1; i >= 0; i-- { |
| - if p := b.Procs[i]; p.OwnPort && ownPort(p) == port { |
| - return p |
| - } |
| - } |
| - for _, h := range hostsOf(b) { |
| - r := b.Rows[h] |
| - if r.Kind != "instance" || r.Platform { |
| - continue |
| - } |
| - if tb, pt := w.addrBox(r.Backend); tb == b && pt == port { |
| - return w.newest(b, w.group(b, h)) |
| - } |
| - } |
| - return nil |
| -} |
| - |
| -// reach records a connection past the edge reaching process p. INV-P, as in |
| -// deliver: a public connection never reaches a declaring build, nor a group |
| -// holding a loaded doc-engine grant. |
| -func (w *world) reach(b *box, p *proc, public bool, how string) *proc { |
| - if p == nil { |
| - w.logf("box%d: %s: nothing listens", b.ID, how) |
| - return nil |
| - } |
| - w.logf("box%d: %s reached process %d (%s v%d) past the edge", b.ID, how, p.ID, p.Group, p.Ver) |
| - w.events["delivered"]++ |
| - // a ports listener exists only because the group is public: a path the |
| - // upgrade's 0 opens; any other way past the edge is the ingress rule's |
| - listener := strings.HasPrefix(how, "the ports listener") |
| - if public && w.builds[p.Ver].Declares { |
| - w.failProc(b, p, "INV-P", listener, "box%d: a public connection through %s reached process %d of %s running v%d, which declares doc_engine, past the edge", b.ID, how, p.ID, p.Group, p.Ver) |
| - } else if g := w.grantLoaded(b, p.Group); public && g != "" { |
| - w.failProc(b, p, "INV-P", listener, "box%d: a public connection through %s reached process %d of %s running v%d, whose group holds the doc-engine grant (on %s), past the edge", b.ID, how, p.ID, p.Group, p.Ver, g) |
| - } |
| - return p |
| -} |
| - |
| -// deliverDirect is the proxy of request r on b whose backend is an address |
| -// no instance row of b carries: on another box, a direct connection there |
| -// (the firewall decides); on b itself, the process bound to that port. False |
| -// when the backend is no such address. |
| -func (w *world) deliverDirect(b *box, r *req) bool { |
| - tb, port := w.addrBox(r.Backend) |
| - if tb == nil { |
| - return false |
| - } |
| - w.logf("box%d: request %d proxies to %s, box%d's address", b.ID, r.ID, r.Backend, tb.ID) |
| - if p := w.connect(tb, port, r.Public, tb != b); p != nil { |
| - r.Reached = p.ID |
| - } |
| - return true |
| -} |
| - |
| -// ---------- INV-AV ---------- |
| - |
| -// A proxying row outside the internal group homed on its box is refused by |
| -// the dedicated-box rule on purpose (spec §5.9): INV-AV does not count it. |
| -// The row's true group decides, not the edge's resolution. |
| -func init() { |
| - avExemptions = append(avExemptions, func(w *world, b *box, host string) string { |
| - r := b.Rows[host] |
| - if r == nil || !proxying(r) { |
| - return "" |
| - } |
| - homed := w.edgeHomed(b) |
| - if len(homed) == 0 || homed[truthGroup(b, host)] { |
| - return "" |
| - } |
| - return fmt.Sprintf("a proxying row outside %v, the internal group homed on the box: refused by design (§5.9)", sortedKeys(homed)) |
| - }) |
| -} |
| - |
| -// ---------- the random walk ---------- |
| - |
| -// addressablePorts is every port on b a direct connection can name: TCP |
| -// routes' backends, ports processes bound on their own, ports listeners. |
| -func (w *world) addressablePorts(b *box) []string { |
| - set := map[string]bool{} |
| - for _, h := range hostsOf(b) { |
| - if r := b.Rows[h]; r.Kind == "instance" && !r.Platform { |
| - if tb, port := w.addrBox(r.Backend); tb == b { |
| - set[port] = true |
| - } |
| - } |
| - } |
| - for _, p := range b.Procs { |
| - if p.OwnPort { |
| - set[ownPort(p)] = true |
| - } |
| - } |
| - for port := range b.Listen { |
| - set[port] = true |
| - } |
| - return sortedKeys(set) |
| -} |
| - |
| -// localBackends is every upstream a local service row on b can name: its |
| -// instance routes' backends and the ports on b's own address. |
| -func (w *world) localBackends(b *box) []string { |
| - set := map[string]bool{"127.0.0.1:1": true} // nothing listens |
| - for _, h := range hostsOf(b) { |
| - if r := b.Rows[h]; r.Kind == "instance" && !r.Platform && r.Backend != "" { |
| - set[r.Backend] = true |
| - } |
| - } |
| - for _, port := range w.addressablePorts(b) { |
| - set[boxAddr(b)+":"+port] = true |
| - } |
| - return sortedKeys(set) |
| -} |
| - |
| -func init() { |
| - actions = append(actions, |
| - action{name: "add-service-row", weight: 2, run: func(w *world) bool { |
| - b := w.pickBox() |
| - if len(b.Rows) >= maxRows { |
| - return false |
| - } |
| - w.nextID++ |
| - host := fmt.Sprintf("svc%d.example", w.nextID) |
| - if b.ID == 1 && w.rng.Intn(2) == 0 { |
| - // aimed at box 0's address (codex R13-1) |
| - ports := append(w.addressablePorts(w.boxes[0]), "1") |
| - w.addServiceRow(b, host, boxAddr(w.boxes[0])+":"+ports[w.rng.Intn(len(ports))]) |
| - return true |
| - } |
| - bs := w.localBackends(b) |
| - w.addServiceRow(b, host, bs[w.rng.Intn(len(bs))]) |
| - return true |
| - }}, |
| - action{name: "delete-service-row", weight: 2, run: func(w *world) bool { |
| - type at struct { |
| - b *box |
| - host string |
| - } |
| - var rows []at |
| - for _, b := range w.boxes { |
| - for _, h := range hostsOf(b) { |
| - if b.Rows[h].Kind == "service" { |
| - rows = append(rows, at{b, h}) |
| - } |
| - } |
| - } |
| - if len(rows) == 0 { |
| - return false |
| - } |
| - x := rows[w.rng.Intn(len(rows))] |
| - w.deleteRow(x.b, x.host) |
| - return true |
| - }}, |
| - action{name: "own-port", weight: 1, run: func(w *world) bool { |
| - b := w.pickBox() |
| - if len(b.Procs) == 0 { |
| - return false |
| - } |
| - w.bindOwnPort(b, b.Procs[w.rng.Intn(len(b.Procs))]) |
| - return true |
| - }}, |
| - action{name: "direct-connect", weight: 2, run: func(w *world) bool { |
| - b := w.pickBox() |
| - ports := append(w.addressablePorts(b), "1") |
| - w.directConnect(b, ports[w.rng.Intn(len(ports))], true) |
| - return true |
| - }}, |
| - action{name: "ship-ports", weight: 1, run: func(w *world) bool { |
| - b := w.pickBox() |
| - g := w.pickGroup(b) |
| - if g == "" { |
| - return false |
| - } |
| - w.ship(b, g, w.pickVer(), true) |
| - return true |
| - }}, |
| - action{name: "caps-pass", weight: 1, run: func(w *world) bool { w.capsPass(w.pickBox()); return true }}, |
| - action{name: "remove-route", weight: 1, run: func(w *world) bool { |
| - // an instance route the walk added (the starting eng and shop stay) |
| - b := w.pickBox() |
| - var gs []string |
| - for _, g := range w.groups(b) { |
| - if g != eng && g != "shop" { |
| - gs = append(gs, g) |
| - } |
| - } |
| - if len(gs) == 0 { |
| - return false |
| - } |
| - w.removeGroup(b, gs[w.rng.Intn(len(gs))]) |
| - return true |
| - }}, |
| - ) |
| -} |
diff --git a/internal/sim/engines/edge_test.go b/internal/sim/engines/edge_test.go| deleted file mode 100644 |
| index f6506eee8..000000000 |
| --- a/internal/sim/engines/edge_test.go |
| +++ /dev/null |
| @@ -1,315 +0,0 @@ |
| -package engines |
| - |
| -import "sort" |
| - |
| -// The edge side of the internal mark (spec §5.1 "Setting the mark: the |
| -// serving barrier", "What the edge does with it"; §5.9 box-wide fence; §6.3). |
| -// |
| -// The registry holds the mark (the intent); the edge serves the map its last |
| -// successful reload swapped in, and publishes the registry change it has |
| -// fenced. A launch trusts only the fence. |
| - |
| -// loadEdge swaps the registry into the edge's map: rows by value (a later |
| -// registry edit does not leak into the served map) and their marks. |
| -// |
| -// The edge resolves owners at load (spec §5.1, "Platform-minted rows"): a |
| -// row that follows an owner carries the resolved owner in its copy's Owner; |
| -// one whose owner cannot be found, or is found ambiguously, is served NULL |
| -// (refused) until the reconciler records its owner. Any other row's copy has |
| -// no Owner, so edgeGroup is its own host. |
| -func (b *box) loadEdge() { |
| - b.EdgeRows = make(map[string]row, len(b.Rows)) |
| - b.Serving = make(map[string]mark, len(b.Rows)) |
| - for h, r := range b.Rows { |
| - c := *r |
| - c.PathTo = make(map[string]string, len(r.PathTo)) |
| - for p, to := range r.PathTo { |
| - c.PathTo[p] = to |
| - } |
| - b.Serving[h] = b.Mark[h] |
| - c.Owner = "" |
| - if followsOwner(r) { |
| - if o, ok := b.resolveOwner(r); ok { |
| - c.Owner = o |
| - } else { |
| - b.Serving[h] = markNull |
| - } |
| - } |
| - b.EdgeRows[h] = c |
| - } |
| -} |
| - |
| -// groupHosts is every registry row of group g, sorted. |
| -func (w *world) groupHosts(b *box, g string) []string { |
| - var out []string |
| - for h := range b.Rows { |
| - if w.group(b, h) == g { |
| - out = append(out, h) |
| - } |
| - } |
| - sort.Strings(out) |
| - return out |
| -} |
| - |
| -// groupMark is the registry's mark of group g: internal only if every row of |
| -// the group is, NULL if any row is NULL or the group has no row, else public. |
| -func (w *world) groupMark(b *box, g string) mark { |
| - hosts := w.groupHosts(b, g) |
| - if len(hosts) == 0 { |
| - return markNull |
| - } |
| - all := markInternal |
| - for _, h := range hosts { |
| - switch b.Mark[h] { |
| - case markNull: |
| - return markNull |
| - case markPublic: |
| - all = markPublic |
| - } |
| - } |
| - return all |
| -} |
| - |
| -// writeMark writes mark m on every registry row of group g: one registry |
| -// change, so Wrote counts it. A change that closes a group the edge has not |
| -// fenced closed (an open group, or a new row's NULL the edge has never |
| -// loaded) is the one a fence must reach: it records the group's fence |
| -// generation (SetAt). 1 written over a NULL whose generation is recorded |
| -// moves nothing: the edge already refuses it. |
| -func (w *world) writeMark(b *box, g string, m mark) { |
| - wasClosed := w.closed(b, g) && (w.recorded(b, g) || !on("new-group-fenced")) |
| - b.Wrote++ |
| - for _, h := range w.groupHosts(b, g) { |
| - b.Mark[h] = m |
| - } |
| - if !wasClosed && m != markPublic { |
| - b.SetAt[g] = b.Wrote |
| - } |
| - w.logf("box%d: registry change %d: %s marked %v", b.ID, b.Wrote, g, m) |
| - if m != markPublic { |
| - w.dropListeners(b, g) // before any fence of this write (ports-excluded) |
| - } |
| -} |
| - |
| -// recorded: group g has a fence generation, the registry change at which it |
| -// last closed (SetAt has the key). A group whose rows are new, or were |
| -// created NULL and never written, has none. |
| -func (w *world) recorded(b *box, g string) bool { |
| - _, ok := b.SetAt[g] |
| - return ok |
| -} |
| - |
| -// fenced is the gate's reading of I1's "fenced": the group is closed, it has |
| -// a fence generation, and the edge's fenced counter has reached it (no later |
| -// change has cleared it). |
| -// |
| -// NULL counts as closed here only once the edge has loaded that NULL: the |
| -// group has a recorded generation, set by the change that closed it, and the |
| -// reload that reached it bumped the epoch and drained every older public |
| -// request on the box (the upgrade's restart is such a fence). A newly created |
| -// or unseen row is NULL in the registry but has no generation, so a first |
| -// declaring launch writes 1 and waits for the fence like any other |
| -// (new-group-fenced; final review, finding 1). |
| -func (w *world) fenced(b *box, g string) bool { |
| - return (w.recorded(b, g) || !on("new-group-fenced")) && w.closed(b, g) && b.Fenced >= b.SetAt[g] |
| -} |
| - |
| -// fencedTruth is the oracle's fenced: fenced with every rule in place. I1 |
| -// reads it, so a mutation that weakens the gate's reading cannot weaken the |
| -// invariant too. |
| -func (w *world) fencedTruth(b *box, g string) bool { |
| - return w.recorded(b, g) && w.closed(b, g) && b.Fenced >= b.SetAt[g] |
| -} |
| - |
| -// closed: group g has a row and none of its registry rows is 0. |
| -func (w *world) closed(b *box, g string) bool { |
| - hosts := w.groupHosts(b, g) |
| - if len(hosts) == 0 { |
| - return false |
| - } |
| - for _, h := range hosts { |
| - if b.Mark[h] == markPublic { |
| - return false |
| - } |
| - } |
| - return true |
| -} |
| - |
| -// reload is the edge's registry poll. A failed reload swaps nothing and |
| -// advances nothing. A successful one swaps the map; if any row went from not |
| -// internal to internal it bumps the box's admission epoch and cancels every |
| -// public request admitted under an older one (including those waiting in the |
| -// activator's queue); then the fenced counter reaches the registry. |
| -func (w *world) reload(b *box) bool { |
| - if b.ReloadFails { |
| - if !on("fence-needs-reload") { |
| - b.Fenced = b.Wrote |
| - w.logf("box%d: reload failed; fenced %d anyway", b.ID, b.Fenced) |
| - return false |
| - } |
| - w.logf("box%d: reload failed; nothing swapped, fenced stays %d", b.ID, b.Fenced) |
| - return false |
| - } |
| - old := b.Serving |
| - b.loadEdge() |
| - changed := map[string]bool{} |
| - for h, m := range b.Serving { |
| - if (m == markInternal && old[h] != markInternal) || (m == markNull && old[h] == markPublic) { |
| - changed[h] = true |
| - } |
| - } |
| - if len(changed) > 0 { |
| - b.Epoch++ |
| - if on("fence-drains-admitted") { |
| - kept := b.Admitted[:0] |
| - for _, r := range b.Admitted { |
| - // box-wide: every older public request on any row, deleted |
| - // rows included (spec §5.9); without it, only the rows the |
| - // change marked |
| - if r.Public && r.Epoch < b.Epoch && (on("fence-box-wide") || changed[r.Row]) { |
| - w.logf("box%d: fence cancels request %d (row %s, epoch %d)", b.ID, r.ID, r.Row, r.Epoch) |
| - continue |
| - } |
| - kept = append(kept, r) |
| - } |
| - b.Admitted = kept |
| - } |
| - } |
| - b.Fenced = b.Wrote |
| - w.logf("box%d: reload: map swapped, epoch %d, fenced %d", b.ID, b.Epoch, b.Fenced) |
| - return true |
| -} |
| - |
| -// admitPublic is the edge's internal check for a request with no caller: it |
| -// resolves the alias, the path map and the minted row to the final row, and |
| -// refuses when that row is internal or NULL (spec §5.1: the check runs on the |
| -// final resolved upstream's route). A static row answers without a proxy, so |
| -// nothing is admitted. Otherwise the request is admitted under the box's |
| -// epoch, holding the final row's backend. |
| -func (w *world) admitPublic(b *box, host, path string) *req { |
| - r, _ := w.admit(b, host, path) |
| - return r |
| -} |
| - |
| -// The outcomes of admit. |
| -const ( |
| - admitted = "admitted" // proxied: the request holds a backend |
| - answered = "answered" // a static row: the edge answers it itself |
| - refused = "refused" // the internal refusal |
| - unknown = "unknown" // no such host, alias target or path target |
| -) |
| - |
| -// admit is admitPublic with its outcome, for INV-AV. The edge treats NULL |
| -// like 1 (classify-null-refused). |
| -func (w *world) admit(b *box, host, path string) (*req, string) { |
| - asked, ok := b.EdgeRows[host] |
| - if !ok { |
| - w.logf("box%d: public %s%s: unknown host", b.ID, host, path) |
| - return nil, unknown |
| - } |
| - final := asked |
| - if asked.Alias != "" { |
| - if final, ok = b.EdgeRows[asked.Alias]; !ok { |
| - w.logf("box%d: public %s%s: alias target %s unknown", b.ID, host, path, asked.Alias) |
| - return nil, unknown |
| - } |
| - } |
| - if to, ok := final.PathTo[path]; ok { |
| - if final, ok = b.EdgeRows[to]; !ok { |
| - w.logf("box%d: public %s%s: path target %s unknown", b.ID, host, path, to) |
| - return nil, unknown |
| - } |
| - } |
| - checked := final |
| - if !on("mark-on-final-upstream") { |
| - checked = asked |
| - } |
| - m := b.Serving[checked.Host] |
| - if m == markNull && !on("classify-null-refused") { |
| - w.logf("box%d: public %s%s: %s is NULL, served like 0", b.ID, host, path, checked.Host) |
| - m = markPublic |
| - } |
| - if m != markPublic { |
| - w.logf("box%d: public %s%s: internal refusal (%s is %v)", b.ID, host, path, checked.Host, m) |
| - return nil, refused |
| - } |
| - if final.Backend == "" { |
| - w.logf("box%d: public %s%s: answered by the edge (%s)", b.ID, host, path, final.Host) |
| - return nil, answered |
| - } |
| - if why := w.dedicatedRefusal(b, final); why != "" { |
| - w.logf("box%d: public %s%s: internal refusal: %s", b.ID, host, path, why) |
| - return nil, refused |
| - } |
| - w.nextID++ |
| - r := &req{ID: w.nextID, Epoch: b.Epoch, Row: checked.Host, Backend: final.Backend, Public: true, Box: b.ID} |
| - b.Admitted = append(b.Admitted, r) |
| - w.logf("box%d: public %s%s admitted as request %d (row %s, backend %s, epoch %d)", b.ID, host, path, r.ID, r.Row, r.Backend, r.Epoch) |
| - return r, admitted |
| -} |
| - |
| -// backendGroup is the group whose process listens on backend: the group of |
| -// the instance row that carries it, whatever row the request came in by. A |
| -// minted row copies its source's backend; the process is the source's, so |
| -// the source's own row decides (the truth, whatever the edge resolved). |
| -func (w *world) backendGroup(b *box, backend string) string { |
| - hosts := make([]string, 0, len(b.Rows)) |
| - for h := range b.Rows { |
| - hosts = append(hosts, h) |
| - } |
| - sort.Strings(hosts) |
| - for _, h := range hosts { |
| - if r := b.Rows[h]; r.Kind == "instance" && !r.Platform && r.Backend == backend { |
| - return w.group(b, h) |
| - } |
| - } |
| - return "" |
| -} |
| - |
| -// deliver resumes an admitted request: unless the fence cancelled it, its |
| -// proxy reaches the newest process of the group listening on its backend. |
| -// INV-P: a public request never reaches a process whose build declares |
| -// doc_engine, nor one of a group that holds the doc-engine grant once the |
| -// edge has loaded the grant (the grant sets 1 whatever the manifest says, |
| -// spec §5.1 "The column"; a grant whose barrier timed out protects nothing |
| -// until the edge loads it, and the load drains every request admitted before). |
| -func (w *world) deliver(r *req) { |
| - b := w.boxes[r.Box] |
| - idx := -1 |
| - for i, x := range b.Admitted { |
| - if x == r { |
| - idx = i |
| - } |
| - } |
| - if idx < 0 { |
| - w.logf("box%d: request %d was cancelled; nothing delivered", b.ID, r.ID) |
| - return |
| - } |
| - b.Admitted = append(b.Admitted[:idx], b.Admitted[idx+1:]...) |
| - r.Held = false |
| - g := w.backendGroup(b, r.Backend) |
| - if g == "" && w.deliverDirect(b, r) { |
| - return |
| - } |
| - var p *proc |
| - for _, x := range b.Procs { |
| - if x.Group == g && g != "" { |
| - p = x |
| - } |
| - } |
| - if p == nil { |
| - w.logf("box%d: request %d: no process on %s; wake failure answer", b.ID, r.ID, r.Backend) |
| - return |
| - } |
| - r.Reached = p.ID |
| - w.events["delivered"]++ |
| - w.logf("box%d: request %d delivered to process %d (%s v%d)", b.ID, r.ID, p.ID, p.Group, p.Ver) |
| - if r.Public && w.builds[p.Ver].Declares { |
| - w.failProc(b, p, "INV-P", true, "box%d: public request %d (row %s) delivered to process %d of %s running v%d, which declares doc_engine", b.ID, r.ID, r.Row, p.ID, p.Group, p.Ver) |
| - } else if r.Public && w.grantLoaded(b, g) != "" { |
| - w.failProc(b, p, "INV-P", true, "box%d: public request %d (row %s) delivered to process %d of %s running v%d, whose group holds the doc-engine grant (on %s)", b.ID, r.ID, r.Row, p.ID, p.Group, p.Ver, w.grantLoaded(b, g)) |
| - } |
| - if p.Ver == b.Live[g] { |
| - b.Good[g] = p.Ver // the live build answered: it is the good version now |
| - } |
| -} |
diff --git a/internal/sim/engines/expected-outcomes.txt b/internal/sim/engines/expected-outcomes.txt| deleted file mode 100644 |
| index 03c910d34..000000000 |
| --- a/internal/sim/engines/expected-outcomes.txt |
| +++ /dev/null |
| @@ -1,12 +0,0 @@ |
| -# rule outcome reason. Read by mutate.sh: a rule listed `missed` is not |
| -# expected to be caught alone, by the random sweep or by its witness |
| -# (witness_test.go), and is reported EXPECTED-MISS; the sweep fails if it |
| -# is caught (the expectation is stale). Each reason names the combination |
| -# that catches the rule; its witness's `needs` is that combination, and |
| -# TestWitnesses proves the witness holds under every proper subset of it. |
| -# A rule listed `rare N` is reached by the random sweep only at N seeds or |
| -# more; below N its miss is expected. No rule is listed rare. |
| -gate-adopt missed caught with set-before-repoint (witness): adoption's set-before is the same gate reached earlier, so with it in place the restart's gate always finds the group already fenced |
| -public-stops-group missed caught with public-confirms-empty (witness): without the stop, --public step 3 finds the declaring generation still serving and refuses, so the clear never writes 0 under it |
| -dedicated-launch-check missed caught with dedicated-edge-refusal (witness): without the launch check a declaring adoption beside a proxying row goes ahead, but the edge's refusal then refuses that row once the group is internal, so no public request reaches the engine |
| -stale-clears-grants missed caught with grant-freshness-bound (witness): a table's record was signed no later than its last good read, and expires long after it goes stale by its signing, so the signed_at bound (R5) empties a stale or expired table first; with both gone the stale table serves a revoked grant |
diff --git a/internal/sim/engines/invariants_test.go b/internal/sim/engines/invariants_test.go| deleted file mode 100644 |
| index d0dbe5fc1..000000000 |
| --- a/internal/sim/engines/invariants_test.go |
| +++ /dev/null |
| @@ -1,359 +0,0 @@ |
| -package engines |
| - |
| -import ( |
| - "fmt" |
| - "sort" |
| - "strings" |
| -) |
| - |
| -// fail records a violation of invariant inv, once per invariant id: the |
| -// first message is the one the sweep reports and the later ones are the same |
| -// fault again. The stored text begins "<inv>: ", which invariantOf reads back. |
| -func (w *world) fail(inv, format string, args ...any) { |
| - for _, v := range w.violations { |
| - if invariantOf(v) == inv { |
| - return |
| - } |
| - } |
| - w.violations = append(w.violations, inv+": "+fmt.Sprintf(format, args...)) |
| -} |
| - |
| -// invariantOf is the invariant id a violation string was recorded under. |
| -func invariantOf(violation string) string { |
| - if i := strings.Index(violation, ": "); i >= 0 { |
| - return violation[:i] |
| - } |
| - return violation |
| -} |
| - |
| -// The invariants of Task 2 (spec §5.1, §6.3): |
| -// |
| -// - INV-P (event, recorded in deliver): a public request is never delivered |
| -// to a process whose build declares doc_engine. |
| -// - INV-I1: no process of a declaring build runs unless its group is fenced |
| -// as internal. Checked when each process starts, on every launch path |
| -// (systemd and socket starts included), and again at every step boundary |
| -// for every running process, since a later change can unfence a group |
| -// under a process already running. It is two conditions: |
| -// 1. the fence itself, as the spec states I1: the edge's fenced counter |
| -// has reached the registry change that set the group's mark to 1, and |
| -// nothing later cleared it (fencedTruth). A group open, NULL but never |
| -// loaded (a new row), unloaded or written but not yet fenced fails here. |
| -// 2. the fact the fence stands for: no row of the group is served 0 by |
| -// the edge's map. This catches a counter advanced without a swap, which |
| -// condition 1 cannot see because it reads that counter. |
| - |
| -// i1Broken reports why process p breaks I1, or "" when it does not. |
| -func (w *world) i1Broken(b *box, p *proc) string { |
| - if !w.builds[p.Ver].Declares { |
| - return "" |
| - } |
| - if !w.fencedTruth(b, p.Group) { |
| - at := "never" |
| - if w.recorded(b, p.Group) { |
| - at = fmt.Sprint(b.SetAt[p.Group]) |
| - } |
| - return fmt.Sprintf("the group is not fenced (registry %v, fenced %d, set at %s)", w.groupMark(b, p.Group), b.Fenced, at) |
| - } |
| - hosts := make([]string, 0, len(b.EdgeRows)) |
| - for h := range b.EdgeRows { |
| - hosts = append(hosts, h) |
| - } |
| - sort.Strings(hosts) |
| - for _, h := range hosts { |
| - if edgeGroup(b, h) == p.Group && b.Serving[h] == markPublic { |
| - return fmt.Sprintf("the edge serves %s public", h) |
| - } |
| - } |
| - return "" |
| -} |
| - |
| -// checkStart is I1 at the moment process p starts. |
| -func (w *world) checkStart(b *box, p *proc) { |
| - if why := w.i1Broken(b, p); why != "" { |
| - w.failProc(b, p, "INV-I1", true, "box%d: process %d of %s started v%d, which declares doc_engine: %s", b.ID, p.ID, p.Group, p.Ver, why) |
| - } |
| -} |
| - |
| -// check runs the state invariants over every running process. doStep calls |
| -// it after every action; a witness calls it at each of its step boundaries. |
| -// Task 5 adds INV-ARM (checkArm); its event invariants INV-ID and INV-G are |
| -// recorded when an engine call reaches a process (checkCall). |
| -func (w *world) check() { |
| - w.endResidualWindows() |
| - for _, b := range w.boxes { |
| - for _, p := range b.Procs { |
| - if why := w.i1Broken(b, p); why != "" { |
| - w.failProc(b, p, "INV-I1", true, "box%d: process %d of %s runs v%d, which declares doc_engine: %s", b.ID, p.ID, p.Group, p.Ver, why) |
| - } |
| - } |
| - } |
| - w.checkArm() |
| -} |
| - |
| -// edgeGroup is group over the edge's loaded rows. |
| -func edgeGroup(b *box, host string) string { |
| - if r, ok := b.EdgeRows[host]; ok && r.Kind == "instance" && r.Owner != "" { |
| - return r.Owner |
| - } |
| - return host |
| -} |
| - |
| -// INV-AV (liveness, Task 3): at the end of the calm phase, every row of a |
| -// group whose mark is 0 answers a public request. It is what catches the |
| -// rules that only protect availability (static-minted-public, |
| -// owner-nonempty-unique), which no safety invariant can see. Checked in |
| -// final() only, after every edge has polled with its faults cleared. |
| -// |
| -// The truth, not the model's resolution, decides which rows must answer: |
| -// - a static or service row is 0 by construction (spec §5.1, "The column"), |
| -// minted or not; |
| -// - an instance row answers when its group's mark is 0: the registry mark |
| -// of its own row, or for a minted row, of the row it was minted from |
| -// (Source); |
| -// - alias rows are skipped: they answer as their target does. |
| -// |
| -// Not counted, as the spec's fail-closed choices or another rule's stated |
| -// refusal: a minted row whose owner the correct fallback cannot find |
| -// uniquely (refused and logged until the reconciler records its owner), and |
| -// any row an avExemption names. |
| -func (w *world) checkAV() { |
| - for _, b := range w.boxes { |
| - hosts := make([]string, 0, len(b.Rows)) |
| - for h := range b.Rows { |
| - hosts = append(hosts, h) |
| - } |
| - sort.Strings(hosts) |
| - for _, h := range hosts { |
| - r := b.Rows[h] |
| - switch r.Kind { |
| - case "alias": |
| - continue |
| - case "instance": |
| - owner := h |
| - if r.Platform { |
| - if _, ok := b.resolveOwnerWith(r, true); !ok { |
| - w.logf("box%d: final: minted row %s has no unique owner; refused by design, not counted", b.ID, h) |
| - continue |
| - } |
| - owner = r.Source |
| - } |
| - if b.Mark[owner] != markPublic { |
| - continue |
| - } |
| - } |
| - if why := w.avExempt(b, h); why != "" { |
| - w.logf("box%d: final: %s exempt from INV-AV: %s", b.ID, h, why) |
| - continue |
| - } |
| - req, outcome := w.admit(b, h, "/") |
| - switch outcome { |
| - case admitted: |
| - w.deliver(req) |
| - case answered: |
| - default: |
| - w.fail("INV-AV", "box%d: row %s (%s) of a public group is %s a public request at the end of the calm phase (registry %v, edge %v)", b.ID, h, r.Kind, outcome, b.Mark[h], b.Serving[h]) |
| - } |
| - } |
| - } |
| -} |
| - |
| -// avExemptions are later tasks' stated refusals of a public row (each |
| -// returns why, or ""), which INV-AV must not count. |
| -var avExemptions []func(w *world, b *box, host string) string |
| - |
| -func (w *world) avExempt(b *box, host string) string { |
| - for _, f := range avExemptions { |
| - if why := f(w, b, host); why != "" { |
| - return why |
| - } |
| - } |
| - return "" |
| -} |
| - |
| -// ---------- Task 5: INV-ID, INV-G, INV-ARM (calls_test.go) ---------- |
| - |
| -// checkCall is INV-ID and INV-G for an engine call that reached process q on |
| -// home, sent by process p (nil: a public client) on box from through the |
| -// engine socket or door key of instance via. |
| -// |
| -// - INV-ID: the caller the engine box records is the app whose code made |
| -// the call. The flat-era residual covers only a call whose recorded |
| -// caller is the compromised instance itself (compromisedItself). |
| -// - INV-G: the call reaches the engine's exact route, and grantBreach finds |
| -// no breach of the grant's freshness. |
| -func (w *world) checkCall(home, from *box, mark caller, via, real string, p, q *proc) { |
| - if mark.app() != real { |
| - msg := fmt.Sprintf("box%d: the engine box records caller %s for a call made by %q (process %v)", home.ID, mark.app(), real, procID(p)) |
| - if w.flatEraTamper && w.compromisedItself(from, mark, via, p) { |
| - w.residual("flatEraTamper", "%s: code planted before the box was armed", msg) |
| - } else { |
| - w.fail("INV-ID", "%s", msg) |
| - } |
| - } |
| - exact, _ := w.exactRoute(home, engineHosts[mark.Engine]) |
| - if want := truthGroup(home, exact.Host); q.Group != want { |
| - w.fail("INV-G", "box%d: an engine call for %s reached process %d of %s, not the engine's exact route %s", home.ID, mark.key(), q.ID, q.Group, want) |
| - } |
| - if why := w.grantBreach(home, from, mark.key()); why != "" { |
| - w.fail("INV-G", "box%d: an engine call for %s reached process %d of %s; %s", home.ID, mark.key(), q.ID, q.Group, why) |
| - } |
| -} |
| - |
| -// compromisedItself: the flat-era residual's own case, from facts no rule |
| -// changes. Process p is the instance via's own process, in via's own slice, |
| -// running the code planted in via's directory, and the caller recorded is |
| -// via's own app. Planted code that borrows another instance's socket or |
| -// forges a hop caller is a violation like any other. |
| -func (w *world) compromisedItself(from *box, mark caller, via string, p *proc) bool { |
| - if p == nil || p.Code == "" || p.Unisolated || via == "" { |
| - return false |
| - } |
| - r := from.Rows[via] |
| - return r != nil && p.Group == via && p.Slice == "inst:"+via && from.Tampered[via] == p.Code && mark.app() == r.App |
| -} |
| - |
| -// grantBreach is INV-G's grant clauses for key on a call admitted by the |
| -// tables of from and home, each from facts no rule changes (spec §5.3, §6.4, |
| -// ruling R5). It returns the first breach, or "". |
| -// |
| -// 1. Expiry: a key the newest record grants is granted by no table once that |
| -// record has expired (every older record expired first), at once. |
| -// 2. Revoke age: a key the newest record does not grant is granted by no |
| -// table more than ten minutes plus one poll after the revoke, whatever |
| -// was replayed (every record that grants it was signed before the |
| -// revoke, and is stale ten minutes after its signing). A key no record |
| -// ever granted is never granted. |
| -// 3. The admitting tables: neither box admits on a table that was never |
| -// read, holds an expired record, has had no good read for ten minutes, or |
| -// holds a record signed ten minutes ago or more, whatever the key's |
| -// revoke (from always checks its table; home is the engine box, whose |
| -// table must be empty too). |
| -// 4. A revoke a box has read stays in force there (§6.4: the floor refuses |
| -// every older record). |
| -func (w *world) grantBreach(home, from *box, key string) string { |
| - c := &w.console |
| - now := w.now() |
| - newest := c.Records[c.Rev] |
| - if newest.Grants[key] && now >= newest.Expires { |
| - return fmt.Sprintf("the newest record (revision %d), which grants it, expired at %d, now %d", newest.Rev, newest.Expires, now) |
| - } |
| - if !newest.Grants[key] { |
| - since, ok := c.RevokedAt[key] |
| - if !ok { |
| - return fmt.Sprintf("no record has granted it (newest revision %d)", newest.Rev) |
| - } |
| - if now-since > staleTicks+pollTicks { |
| - return fmt.Sprintf("the newest record (revision %d) has not granted it since tick %d, now %d", newest.Rev, since, now) |
| - } |
| - } |
| - boxes := []*box{from} |
| - if home != from { |
| - boxes = append(boxes, home) |
| - } |
| - for _, b := range boxes { |
| - if why := w.tableStale(b); why != "" { |
| - return fmt.Sprintf("box%d admitted it on a table that %s", b.ID, why) |
| - } |
| - } |
| - if rr, ok := c.RevokedRev[key]; ok && !newest.Grants[key] { |
| - for _, b := range boxes { |
| - if b.ReadRev >= rr { |
| - return fmt.Sprintf("box%d had read revision %d, which revoked it (read %d)", b.ID, rr, b.ReadRev) |
| - } |
| - } |
| - } |
| - return "" |
| -} |
| - |
| -// tableStale says why b's table must be empty, or "". |
| -func (w *world) tableStale(b *box) string { |
| - m, now := b.Mirror, w.now() |
| - switch { |
| - case m.Rec == nil: |
| - return "was never read" |
| - case now >= m.Rec.Expires: |
| - return fmt.Sprintf("holds revision %d, expired at %d, now %d", m.Rec.Rev, m.Rec.Expires, now) |
| - case now-m.ReadAt >= staleTicks: |
| - return fmt.Sprintf("has had no good read for %d ticks", now-m.ReadAt) |
| - case now-m.Rec.SignedAt >= staleTicks: |
| - return fmt.Sprintf("holds revision %d, signed at %d, %d ticks ago", m.Rec.Rev, m.Rec.SignedAt, now-m.Rec.SignedAt) |
| - } |
| - return "" |
| -} |
| - |
| -func procID(p *proc) any { |
| - if p == nil { |
| - return "none" |
| - } |
| - return p.ID |
| -} |
| - |
| -// INV-ARM (state): no unisolated tenant process exists on a box while an |
| -// engine socket is open there. check() runs it. |
| -func (w *world) checkArm() { |
| - for _, b := range w.boxes { |
| - if !b.Sockets { |
| - continue |
| - } |
| - for _, p := range b.Procs { |
| - if p.Unisolated { |
| - w.fail("INV-ARM", "box%d: engine sockets are open (armed %v) while process %d runs unisolated in %s", b.ID, b.Armed, p.ID, p.Slice) |
| - } |
| - } |
| - } |
| -} |
| - |
| -// residual records the stated residual name once: "residual:<name>: ...". |
| -func (w *world) residual(name, format string, args ...any) { |
| - for _, r := range w.residuals { |
| - if strings.HasPrefix(r, "residual:"+name+":") { |
| - return |
| - } |
| - } |
| - w.residuals = append(w.residuals, "residual:"+name+": "+fmt.Sprintf(format, args...)) |
| - w.logf("residual:%s recorded", name) |
| -} |
| - |
| -// failProc is fail for a breach process p on b causes. It records the stated |
| -// residual p belongs to instead only when the breach is the residual's own: |
| -// viaClassification says the breach came by a path the upgrade's 0 opened |
| -// (I1 itself, the edge serving the group, a ports listener rendered for a |
| -// public group), and the residual's window still holds (residualHolds). Any |
| -// other breach of a tagged process is a violation. |
| -func (w *world) failProc(b *box, p *proc, inv string, viaClassification bool, format string, args ...any) { |
| - if viaClassification && w.residualHolds(b, p) { |
| - w.residual(p.Residual, inv+": "+format, args...) |
| - return |
| - } |
| - w.fail(inv, format, args...) |
| -} |
| - |
| -// residualHolds: p is tagged with the unwritten-manifest residual and its |
| -// group is still open, as the upgrade classified it. The window ends for good |
| -// the first time the group is closed again (a grant, a gate's 1): the tag is |
| -// cleared, so a later 0 (another rule's failure) is never misfiled as the |
| -// upgrade's. |
| -func (w *world) residualHolds(b *box, p *proc) bool { |
| - if p == nil || p.Residual == "" { |
| - return false |
| - } |
| - if w.closed(b, p.Group) { |
| - w.logf("box%d: %s is closed again: process %d's residual window (%s) ends", b.ID, p.Group, p.ID, p.Residual) |
| - p.Residual = "" |
| - return false |
| - } |
| - return true |
| -} |
| - |
| -// endResidualWindows runs residualHolds on every tagged process, so a window |
| -// ends when its group closes even if nothing breaches meanwhile. |
| -func (w *world) endResidualWindows() { |
| - for _, b := range w.boxes { |
| - for _, p := range b.Procs { |
| - if p.Residual != "" { |
| - w.residualHolds(b, p) |
| - } |
| - } |
| - } |
| -} |
diff --git a/internal/sim/engines/launch_test.go b/internal/sim/engines/launch_test.go| deleted file mode 100644 |
| index b0fe537dd..000000000 |
| --- a/internal/sim/engines/launch_test.go |
| +++ /dev/null |
| @@ -1,489 +0,0 @@ |
| -package engines |
| - |
| -import ( |
| - "fmt" |
| - "sort" |
| -) |
| - |
| -// The launch gate (spec §5.1 "The invariant", "Setting the mark", "Starts |
| -// systemd makes on its own"). |
| -// |
| -// I1: a process of a build whose manifest declares doc_engine starts only |
| -// after the edge has fenced its group as internal. Every activator launch |
| -// path ends in the gate; systemd's own starts (Restart=always, socket |
| -// activation) execute the live link and pass no gate, so they are safe only |
| -// because adoption gates before it repoints and nothing else moves the link. |
| - |
| -// fenceWaitTicks is the gate's bound: 30 s of the edge's reloads, one per |
| -// tick. |
| -const fenceWaitTicks = 3 |
| - |
| -// gateRule names the rule that gates a launch path; systemd and socket |
| -// starts are not activator launches and have none. |
| -var gateRule = map[string]string{ |
| - "adopt": "gate-adopt", |
| - "swap": "gate-swap", |
| - "fallback": "gate-fallback", |
| - "recovery": "gate-recovery", |
| - "seed": "gate-seed", |
| - "cmd": "gate-cmd", |
| - "systemd": "", |
| - "socket": "", |
| -} |
| - |
| -// gateSeesDeclaring is what the gate reads from the build's manifest: its |
| -// declaration, or, when the manifest cannot be read, declaring. |
| -func (w *world) gateSeesDeclaring(ver int) bool { |
| - bd := w.builds[ver] |
| - if !bd.ManifestOK { |
| - return on("unreadable-declares") |
| - } |
| - return bd.Declares |
| -} |
| - |
| -// gate is the launch gate for a build about to start in group g: a build it |
| -// sees as declaring writes 1 if 1 is not already written, then always waits |
| -// for the edge's fence to cover the group's mark, within the bound. False is |
| -// a refused launch (the wake fails). |
| -func (w *world) gate(b *box, g string, ver int, path string) bool { |
| - if !w.gateSeesDeclaring(ver) { |
| - return true |
| - } |
| - if !w.dedicatedLaunchCheck(b, g, ver, path) { |
| - return false |
| - } |
| - wrote := false |
| - if w.groupMark(b, g) != markInternal { |
| - w.writeMark(b, g, markInternal) |
| - wrote = true |
| - } |
| - if !wrote && !on("gate-waits-when-written") { |
| - w.logf("box%d: gate(%s) %s v%d: 1 already written; not waiting", b.ID, path, g, ver) |
| - return true |
| - } |
| - for i := 0; i < fenceWaitTicks && !w.fenced(b, g); i++ { |
| - w.reload(b) |
| - } |
| - if !w.fenced(b, g) { |
| - w.logf("box%d: gate(%s) %s v%d: no fence within the bound; refused", b.ID, path, g, ver) |
| - return false |
| - } |
| - return true |
| -} |
| - |
| -// launch starts build ver in group g by path, through the gate where the |
| -// path has one. It returns false when the gate refuses. |
| -func (w *world) launch(b *box, g string, ver int, path string) bool { |
| - rule, known := gateRule[path] |
| - if !known { |
| - panic(fmt.Sprintf("launch: unknown path %q", path)) |
| - } |
| - // the gate holds the group's lock from its check through process |
| - // creation; --public holds the same lock for its whole run, so a launch |
| - // that finds it held waits (here: is refused this pass) |
| - if rule != "" && b.Locked[g] && on("clear-launch-lock") { |
| - w.logf("box%d: %s %s v%d: --public holds the group's lock; not this pass", b.ID, path, g, ver) |
| - return false |
| - } |
| - if rule != "" && on(rule) && !w.gate(b, g, ver, path) { |
| - return false |
| - } |
| - // a group keeps at most three processes: the oldest has exited |
| - n := 0 |
| - for _, p := range b.Procs { |
| - if p.Group == g { |
| - n++ |
| - } |
| - } |
| - if n >= 3 { |
| - for i, p := range b.Procs { |
| - if p.Group == g { |
| - b.Procs = append(b.Procs[:i], b.Procs[i+1:]...) |
| - w.logf("box%d: process %d of %s exited", b.ID, p.ID, g) |
| - break |
| - } |
| - } |
| - } |
| - w.stage(b, g, ver) // a build runs from /opt/carlos/versions: it is staged |
| - w.nextID++ |
| - p := &proc{ID: w.nextID, Group: g, Ver: ver, Slice: "inst:" + g} |
| - b.Procs = append(b.Procs, p) |
| - w.logf("box%d: %s started %s v%d as process %d", b.ID, path, g, ver, p.ID) |
| - w.applyTamper(b, p) |
| - w.checkStart(b, p) |
| - return true |
| -} |
| - |
| -// stopGroup stops every process of group g. |
| -func (w *world) stopGroup(b *box, g string) { |
| - kept := b.Procs[:0] |
| - for _, p := range b.Procs { |
| - if p.Group != g { |
| - kept = append(kept, p) |
| - } |
| - } |
| - b.Procs = kept |
| -} |
| - |
| -func (w *world) running(b *box, g string) bool { |
| - for _, p := range b.Procs { |
| - if p.Group == g { |
| - return true |
| - } |
| - } |
| - return false |
| -} |
| - |
| -// adopt makes ver the live release of group g: set-before (the gate, reached |
| -// before the repoint; on a timeout the link does not move and the mark stays |
| -// 1), then the repoint, then the restart, itself a gated launch. between runs |
| -// after the repoint and before the restart: whatever systemd does there. |
| -func (w *world) adopt(b *box, g string, ver int, between func()) bool { |
| - w.logf("box%d: adopt %s v%d (live v%d)", b.ID, g, ver, b.Live[g]) |
| - if !w.repoint(b, g, ver) { |
| - return false |
| - } |
| - if between != nil { |
| - between() |
| - } |
| - w.stopGroup(b, g) |
| - return w.launch(b, g, ver, "adopt") |
| -} |
| - |
| -// repointAwake is adoption that repoints the live link and does not restart: |
| -// an awake hibernating route (release/adopt.go:1174), or a generation |
| -// rollout that only schedules the swap. What ran keeps running. |
| -func (w *world) repointAwake(b *box, g string, ver int) bool { |
| - w.logf("box%d: adopt %s v%d without a restart (live v%d)", b.ID, g, ver, b.Live[g]) |
| - if !w.repoint(b, g, ver) { |
| - return false |
| - } |
| - w.logf("box%d: %s keeps its running processes until their next start", b.ID, g) |
| - return true |
| -} |
| - |
| -// repoint is adoption up to the repoint: the group's lock (public-holds-lock), |
| -// set-before (the gate, reached before the repoint; on a timeout the link |
| -// does not move and the mark stays 1), then the repoint. |
| -func (w *world) repoint(b *box, g string, ver int) bool { |
| - if b.Locked[g] && on("public-holds-lock") { |
| - w.logf("box%d: adopt %s v%d: --public holds the group's lock; not this pass", b.ID, g, ver) |
| - return false |
| - } |
| - if on("set-before-repoint") && !w.gate(b, g, ver, "adopt") { |
| - w.logf("box%d: adopt %s v%d: not repointed this pass", b.ID, g, ver) |
| - return false |
| - } |
| - b.Live[g] = ver |
| - w.stage(b, g, ver) |
| - if b.Good[g] == 0 { |
| - b.Good[g] = ver |
| - } |
| - w.logf("box%d: live link of %s -> v%d", b.ID, g, ver) |
| - return true |
| -} |
| - |
| -// stage records that build ver of group g is staged on the box. A version is |
| -// staged once per app (/opt/carlos/versions holds the app's versions): if |
| -// another instance of the app already staged it, it stays recorded there |
| -// only, and this group runs it from that copy. |
| -func (w *world) stage(b *box, g string, ver int) { |
| - for _, v := range w.stagedForApp(b, g) { |
| - if v == ver { |
| - return |
| - } |
| - } |
| - b.Staged[g] = append(b.Staged[g], ver) |
| -} |
| - |
| -// appGroups is group g and every other instance group on the box whose own |
| -// row has the same non-empty account/app, sorted. |
| -func (w *world) appGroups(b *box, g string) []string { |
| - own := b.Rows[g] |
| - if own == nil || own.App == "" { |
| - return []string{g} |
| - } |
| - out := []string{} |
| - seen := false |
| - for _, h := range w.groups(b) { |
| - if r := b.Rows[h]; r != nil && r.App == own.App { |
| - out = append(out, h) |
| - seen = seen || h == g |
| - } |
| - } |
| - if !seen { |
| - out = append(out, g) |
| - sort.Strings(out) |
| - } |
| - return out |
| -} |
| - |
| -// stagedForApp is every version of g's app staged on the box, whichever |
| -// instance of the app staged it. |
| -func (w *world) stagedForApp(b *box, g string) []int { |
| - var out []int |
| - for _, h := range w.appGroups(b, g) { |
| - out = append(out, b.Staged[h]...) |
| - } |
| - return out |
| -} |
| - |
| -// wake is the activator waking group g by its wake plan: "recovery" starts |
| -// the recovery build, "fallback" first fails to start the live build and |
| -// falls back; both choose GoodVersion. The triggering request, if any, is |
| -// delivered afterwards (or finds the fence cancelled it). It reports whether |
| -// there was a build to launch. |
| -func (w *world) wake(b *box, g string, mode string, trigger *req) bool { |
| - ver := b.Good[g] |
| - if mode == "fallback" { |
| - w.logf("box%d: wake %s: live v%d fails to start; falling back to good v%d", b.ID, g, b.Live[g], ver) |
| - } else { |
| - w.logf("box%d: wake %s: recovery build good v%d", b.ID, g, ver) |
| - } |
| - if ver != 0 { |
| - w.launch(b, g, ver, mode) |
| - } |
| - if trigger != nil { |
| - w.deliver(trigger) |
| - } |
| - return ver != 0 |
| -} |
| - |
| -// moveLive is anything other than adoption moving group g's live link (a |
| -// rollout tool, a hand repair). Only adoption, through the gate, and |
| -// --public may move a live link. |
| -func (w *world) moveLive(b *box, g string, ver int, who string) bool { |
| - if on("live-link-only-adoption") { |
| - w.logf("box%d: %s may not move the live link of %s; refused", b.ID, who, g) |
| - return false |
| - } |
| - b.Live[g] = ver |
| - w.logf("box%d: %s moved the live link of %s -> v%d", b.ID, who, g, ver) |
| - return true |
| -} |
| - |
| -// systemdRestart is Restart=always: the unit's main process exits and |
| -// systemd starts /opt/carlos/live/<host> again, with no activator. False |
| -// when the route has no live release. |
| -func (w *world) systemdRestart(b *box, g string) bool { |
| - if b.Live[g] == 0 { |
| - return false |
| - } |
| - w.stopGroup(b, g) |
| - w.launch(b, g, b.Live[g], "systemd") |
| - return true |
| -} |
| - |
| -// socketActivate is carlos-app@.socket starting a stopped unit from the live |
| -// link, with no activator. False when there is nothing to start. |
| -func (w *world) socketActivate(b *box, g string) bool { |
| - if b.Live[g] == 0 || w.running(b, g) { |
| - return false |
| - } |
| - w.launch(b, g, b.Live[g], "socket") |
| - return true |
| -} |
| - |
| -// ---------- the random walk ---------- |
| - |
| -func (w *world) pickBox() *box { return w.boxes[w.rng.Intn(len(w.boxes))] } |
| - |
| -// groups is every instance group of b's registry, sorted: the groups of the |
| -// instance rows that are not platform-minted (adoption skips minted rows, |
| -// release/adopt.go:1210; their processes are their source's). |
| -func (w *world) groups(b *box) []string { |
| - seen := map[string]bool{} |
| - var out []string |
| - for h, r := range b.Rows { |
| - if r.Kind != "instance" || r.Platform { |
| - continue |
| - } |
| - if g := w.group(b, h); !seen[g] { |
| - seen[g] = true |
| - out = append(out, g) |
| - } |
| - } |
| - sort.Strings(out) |
| - return out |
| -} |
| - |
| -func (w *world) pickGroup(b *box) string { |
| - gs := w.groups(b) |
| - if len(gs) == 0 { |
| - return "" |
| - } |
| - return gs[w.rng.Intn(len(gs))] |
| -} |
| - |
| -func (w *world) pickVer() int { return 1 + w.rng.Intn(nBuilds) } |
| - |
| -// randomPublic sends one public request to a host of b's edge map, by its |
| -// own name, an alias or a path map. |
| -func (w *world) randomPublic(b *box) *req { |
| - hosts := make([]string, 0, len(b.EdgeRows)) |
| - for h := range b.EdgeRows { |
| - hosts = append(hosts, h) |
| - } |
| - if len(hosts) == 0 { |
| - return nil |
| - } |
| - sort.Strings(hosts) |
| - h := hosts[w.rng.Intn(len(hosts))] |
| - paths := []string{"/"} |
| - for p := range b.EdgeRows[h].PathTo { |
| - paths = append(paths, p) |
| - } |
| - sort.Strings(paths[1:]) |
| - return w.admitPublic(b, h, paths[w.rng.Intn(len(paths))]) |
| -} |
| - |
| -// heldFor is the oldest held request on b whose proxy reaches group g. |
| -func (w *world) heldFor(b *box, g string) *req { |
| - for _, r := range b.Admitted { |
| - if r.Held && w.backendGroup(b, r.Backend) == g { |
| - return r |
| - } |
| - } |
| - return nil |
| -} |
| - |
| -func init() { |
| - actions = append(actions, |
| - action{name: "adopt", weight: 3, run: func(w *world) bool { |
| - b := w.pickBox() |
| - g := w.pickGroup(b) |
| - if g == "" { |
| - return false |
| - } |
| - ver := w.pickVer() |
| - var between func() |
| - switch w.rng.Intn(3) { |
| - case 1: |
| - between = func() { w.systemdRestart(b, g) } |
| - case 2: |
| - between = func() { |
| - if r := w.randomPublic(b); r != nil { |
| - w.socketActivate(b, w.backendGroup(b, r.Backend)) |
| - w.deliver(r) |
| - } |
| - } |
| - } |
| - w.adopt(b, g, ver, between) |
| - return true |
| - }}, |
| - action{name: "reload", weight: 4, run: func(w *world) bool { w.reload(w.pickBox()); return true }}, |
| - action{name: "reload-fails", weight: 1, run: func(w *world) bool { |
| - b := w.pickBox() |
| - b.ReloadFails = !b.ReloadFails && !w.calm() |
| - w.logf("box%d: reload fails = %v", b.ID, b.ReloadFails) |
| - return true |
| - }}, |
| - // 9, not 6 (Task 6): fence-box-wide's sweep catch needs a request held |
| - // through a service row that is deleted before a declaring adoption's |
| - // fence; at 6 the 3000-seed sweep caught it 7 times, at 9 12 times |
| - action{name: "public-request", weight: 9, run: func(w *world) bool { |
| - b := w.pickBox() |
| - r := w.randomPublic(b) |
| - if r == nil { |
| - return false |
| - } |
| - if len(b.Admitted) <= 8 && w.rng.Intn(2) == 0 { |
| - r.Held = true |
| - w.logf("box%d: request %d held in the activator's queue", b.ID, r.ID) |
| - return true |
| - } |
| - w.deliver(r) |
| - return true |
| - }}, |
| - action{name: "resume", weight: 3, run: func(w *world) bool { |
| - var held []*req |
| - for _, b := range w.boxes { |
| - for _, r := range b.Admitted { |
| - if r.Held { |
| - held = append(held, r) |
| - } |
| - } |
| - } |
| - if len(held) == 0 { |
| - return false |
| - } |
| - sort.Slice(held, func(i, j int) bool { return held[i].ID < held[j].ID }) |
| - w.deliver(held[w.rng.Intn(len(held))]) |
| - return true |
| - }}, |
| - action{name: "wake", weight: 3, run: func(w *world) bool { |
| - b := w.pickBox() |
| - g := w.pickGroup(b) |
| - if g == "" { |
| - return false |
| - } |
| - mode := "recovery" |
| - if w.rng.Intn(2) == 0 { |
| - mode = "fallback" |
| - } |
| - w.stopGroup(b, g) // the group had gone to sleep |
| - return w.wake(b, g, mode, w.heldFor(b, g)) |
| - }}, |
| - action{name: "swap", weight: 2, run: func(w *world) bool { |
| - b := w.pickBox() |
| - g := w.pickGroup(b) |
| - if g == "" { |
| - return false |
| - } |
| - if w.launch(b, g, w.pickVer(), "swap") { |
| - // the incoming generation serves; the outgoing ones stop |
| - newest := b.Procs[len(b.Procs)-1] |
| - kept := b.Procs[:0] |
| - for _, p := range b.Procs { |
| - if p.Group != g || p == newest { |
| - kept = append(kept, p) |
| - } |
| - } |
| - b.Procs = kept |
| - } |
| - return true |
| - }}, |
| - action{name: "seed", weight: 1, run: func(w *world) bool { |
| - b := w.pickBox() |
| - g := w.pickGroup(b) |
| - if g == "" { |
| - return false |
| - } |
| - w.stopGroup(b, g) |
| - w.launch(b, g, w.pickVer(), "seed") |
| - return true |
| - }}, |
| - action{name: "cmd", weight: 1, run: func(w *world) bool { |
| - b := w.pickBox() |
| - g := w.pickGroup(b) |
| - if g == "" { |
| - return false |
| - } |
| - w.launch(b, g, w.pickVer(), "cmd") |
| - return true |
| - }}, |
| - action{name: "systemd-restart", weight: 2, run: func(w *world) bool { |
| - b := w.pickBox() |
| - return w.systemdRestart(b, w.pickGroup(b)) |
| - }}, |
| - action{name: "socket-activation", weight: 2, run: func(w *world) bool { |
| - b := w.pickBox() |
| - g := w.pickGroup(b) |
| - w.stopGroup(b, g) // the unit exited idle; a connection arrives |
| - ok := w.socketActivate(b, g) |
| - if r := w.heldFor(b, g); r != nil { |
| - w.deliver(r) |
| - } |
| - return ok |
| - }}, |
| - action{name: "repoint-live", weight: 1, run: func(w *world) bool { |
| - b := w.pickBox() |
| - g := w.pickGroup(b) |
| - if g == "" { |
| - return false |
| - } |
| - w.moveLive(b, g, w.pickVer(), "a rollout tool") |
| - return true |
| - }}, |
| - ) |
| -} |
diff --git a/internal/sim/engines/mutate.sh b/internal/sim/engines/mutate.sh| deleted file mode 100755 |
| index c16aae224..000000000 |
| --- a/internal/sim/engines/mutate.sh |
| +++ /dev/null |
| @@ -1,196 +0,0 @@ |
| -#!/bin/bash |
| -# Mutation checks for the engines model (fleet-internal engines spec §8; |
| -# #335 plan 1). Adapted from internal/sim/hostlife/mutate.sh: the same |
| -# build-once, run-per-rule shape and the same verdicts. |
| -# |
| -# Build the test binary once (this is the only step that writes the Go |
| -# build cache), then run the sweep. The sweep never copies or edits the |
| -# source: each rule runs the same binary with ENGINESIM_MUTATE set. |
| -# |
| -# go test -c -o "$TMPDIR/enginesim/engines.test" ./internal/sim/engines/ |
| -# nice -n 19 internal/sim/engines/mutate.sh 3000 # every rule |
| -# nice -n 19 internal/sim/engines/mutate.sh 3000 @all # the same |
| -# nice -n 19 internal/sim/engines/mutate.sh 3000 rule-a rule-b # named rules |
| -# nice -n 19 internal/sim/engines/mutate.sh 3000 rule-a,rule-b # a combination, dropped together |
| -# ENGINESIM_LIST=1 internal/sim/engines/mutate.sh 0 # print the rules a run would check, and run nothing |
| -# |
| -# Each rule gets two runs under its mutation: the random sweep (TestEngines |
| -# over the seeds) and the rule's deterministic witness scenarios |
| -# (TestWitnesses, witness_test.go). The verdict line reports both, |
| -# separately: |
| -# |
| -# CAUGHT rule: sweep N of S (first seed n); witness violated|held|none |
| -# |
| -# Classification: |
| -# |
| -# CAUGHT the sweep completed and reported at least one seed that |
| -# violated an invariant, with the seed number parsed from its |
| -# output (so it can be replayed with ENGINESIM_SEED), OR a |
| -# witness of the rule violated an invariant under the mutation; |
| -# MISSED the sweep completed with every seed passing, and every |
| -# witness held (or the rule has none); |
| -# ERROR anything else: an unknown rule, a stale binary, a panic, a |
| -# timeout, output the harness cannot parse, or a witness run |
| -# that failed (a witness that must violate under this mutation |
| -# and held: the witness is broken). An error is never a |
| -# detection. |
| -# |
| -# Expected outcomes live in expected-outcomes.txt beside this script: a |
| -# rule listed there as `missed` (caught only in a stated combination: its |
| -# witness holds alone) is reported as EXPECTED-MISS. A rule listed as |
| -# `rare <N>` is caught by the random sweep only at N seeds or more: below |
| -# N a miss is EXPECTED-MISS and a catch is CAUGHT; at N or more a miss is |
| -# MISSED. The sweep exits nonzero on any ERROR, on any unexpected MISSED, |
| -# and on any rule listed as `missed` that is CAUGHT (STALE). |
| -# |
| -# The machine is shared: run the sweep once per revision, serially, under |
| -# nice -n 19. ENGINESIM_PAR (default 1) runs that many rules at once. |
| -# |
| -# Scratch (the binary, every run's log, the verdicts) lives under |
| -# ${ENGINESIM_SCRATCH:-$TMPDIR/enginesim}; remove that one directory, by |
| -# its exact path, once, after the whole sweep. |
| -set -u |
| -SEEDS=${1:?seeds} |
| -shift |
| -ROOT=$(git -C "$(dirname "$0")" rev-parse --show-toplevel) |
| -PKG="$ROOT/internal/sim/engines" |
| -SCRATCH=${ENGINESIM_SCRATCH:-${TMPDIR:?}/enginesim} |
| -BIN=${ENGINESIM_BIN:-$SCRATCH/engines.test} |
| -RULES="$*" |
| -if [ -z "$RULES" ] || [ "$RULES" = "@all" ]; then |
| - RULES=$(sed -n '/^var allRules/,/^}/p' "$PKG/rules_test.go" | grep -o '^\s*"[a-z0-9-]*"' | tr -d ' "\t') |
| -fi |
| -if [ -n "${ENGINESIM_LIST:-}" ]; then |
| - printf '%s\n' $RULES |
| - exit 0 |
| -fi |
| -mkdir -p "$SCRATCH/logs" "$SCRATCH/verdicts" || { echo "cannot create $SCRATCH" >&2; exit 2; } |
| -EXPECT="$PKG/expected-outcomes.txt" |
| -if [ ! -x "$BIN" ]; then |
| - echo "no test binary at $BIN; build it with: go test -c -o $BIN ./internal/sim/engines/" >&2 |
| - exit 2 |
| -fi |
| -if [ -n "$(find "$PKG" -name '*.go' -newer "$BIN")" ]; then |
| - echo "the test binary $BIN is older than the source; rebuild it" >&2 |
| - exit 2 |
| -fi |
| -# the rules that have witnesses (the witnesses table in witness_test.go): a |
| -# run of one of them with no witness output is an ERROR, never "none" |
| -WRULES=$(sed -n '/^var witnesses/,/^}/p' "$PKG/witness_test.go" | grep -o '^\s*{"[a-z0-9-]*",' | tr -d ' \t{",' | sort -u) |
| -# the verdicts of this run only: remove the files inside, by exact name |
| -for f in "$SCRATCH"/verdicts/*; do |
| - [ -e "$f" ] && { rm -f -- "$f" || exit 2; } |
| -done |
| - |
| -# the unmutated sweep first, at the same seed count: if the model violates |
| -# with every rule in place, no catch below means anything (ENGINESIM_MUTATE |
| -# set empty here, so a value in the caller's environment cannot leak in) |
| -blog="$SCRATCH/logs/unmutated.log" |
| -ENGINESIM_MUTATE= ENGINESIM_SEEDS=$SEEDS "$BIN" -test.run '^TestEngines$' -test.count=1 -test.v -test.timeout 180m >"$blog" 2>&1 |
| -brc=$? |
| -if [ $brc -ne 0 ] || [ "$(grep -c "^ sim_test.go:[0-9]*: $SEEDS seeds, 0 failed, 0 residuals; mutated=\"\"" "$blog")" -ne 1 ]; then |
| - echo "BASELINE unmutated: FAILED (rc=$brc); see $blog" >&2 |
| - exit 1 |
| -fi |
| -echo "BASELINE unmutated: sweep 0 of $SEEDS" |
| - |
| -one() { |
| - r=$1 |
| - tag=$(echo "$r" | tr ',' '+') |
| - log="$SCRATCH/logs/$tag.log" |
| - verdict="$SCRATCH/verdicts/$tag" |
| - for x in $(echo "$r" | tr ',' ' '); do |
| - if ! sed -n '/^var allRules/,/^}/p' "$PKG/rules_test.go" | grep -q "^\s*\"$x\","; then |
| - echo "ERROR $r: no rule named $x" | tee "$verdict" |
| - return |
| - fi |
| - done |
| - # the random sweep |
| - ENGINESIM_MUTATE=$r ENGINESIM_SEEDS=$SEEDS "$BIN" -test.run '^TestEngines$' -test.count=1 -test.v -test.timeout 180m >"$log" 2>&1 |
| - rc=$? |
| - expect=$(awk -v r="$r" '$1==r {print $2}' "$EXPECT" 2>/dev/null) |
| - depth=$(awk -v r="$r" '$1==r {print $3}' "$EXPECT" 2>/dev/null) |
| - nviol=$(grep -o "[0-9]* of $SEEDS seeds violated an invariant" "$log" | head -1 | awk '{print $1}') |
| - seed=$(grep -o "first seed [0-9]*" "$log" | head -1 | awk '{print $3}') |
| - clean=$(grep -c "^ sim_test.go:[0-9]*: $SEEDS seeds, 0 failed.*mutated=\"$r\"" "$log") |
| - sweep="" |
| - if [ $rc -ne 0 ] && [ -n "$nviol" ] && [ -n "$seed" ] && ! grep -q "^panic:\|test timed out" "$log"; then |
| - sweep="sweep $nviol of $SEEDS (first seed $seed)" |
| - elif [ $rc -eq 0 ] && [ "$clean" -eq 1 ]; then |
| - sweep="sweep 0 of $SEEDS" |
| - fi |
| - # the witnesses: the rule's own hand-scheduled scenarios, run under the |
| - # same mutation; "violated" if any of them violates an invariant, "held" |
| - # if they all hold, "none" if the rule has no witness. A witness that |
| - # must violate under this mutation and holds fails the test, which is an |
| - # ERROR here: the witness is broken, not the rule |
| - wlog="$SCRATCH/logs/$tag.witness.log" |
| - ENGINESIM_MUTATE=$r "$BIN" -test.run '^TestWitnesses$' -test.count=1 -test.v -test.timeout 10m >"$wlog" 2>&1 |
| - wrc=$? |
| - wit=none |
| - if grep -q "^ witness_test.go:[0-9]*: witness .*: violated" "$wlog"; then |
| - wit=violated |
| - elif grep -q "^ witness_test.go:[0-9]*: witness .*: held" "$wlog"; then |
| - wit=held |
| - fi |
| - if [ $wrc -ne 0 ] || grep -q "^panic:\|test timed out" "$wlog"; then |
| - echo "ERROR $r: witness run rc=$wrc; see $wlog" | tee "$verdict" |
| - return |
| - fi |
| - if [ "$wit" = none ]; then |
| - for x in $(echo "$r" | tr ',' ' '); do |
| - if echo "$WRULES" | grep -qx "$x"; then |
| - echo "ERROR $r: $x has witnesses but the run produced no witness output; see $wlog" | tee "$verdict" |
| - return |
| - fi |
| - done |
| - fi |
| - if [ -z "$sweep" ]; then |
| - echo "ERROR $r: rc=$rc, no parsable sweep verdict; see $log" | tee "$verdict" |
| - return |
| - fi |
| - caught=0 |
| - if [ "$sweep" != "sweep 0 of $SEEDS" ] || [ "$wit" = violated ]; then |
| - caught=1 |
| - fi |
| - if [ $caught -eq 1 ]; then |
| - if [ "$expect" = "missed" ]; then |
| - echo "STALE $r: $sweep; witness $wit; but expected-outcomes.txt says missed" | tee "$verdict" |
| - else |
| - echo "CAUGHT $r: $sweep; witness $wit" | tee "$verdict" |
| - fi |
| - elif [ "$expect" = "missed" ]; then |
| - echo "EXPECTED-MISS $r: $sweep; witness $wit" | tee "$verdict" |
| - elif [ "$expect" = "rare" ] && [ -n "$depth" ] && [ "$SEEDS" -lt "$depth" ]; then |
| - echo "EXPECTED-MISS $r: $sweep; witness $wit (rare: caught at $depth seeds)" | tee "$verdict" |
| - else |
| - echo "MISSED $r: $sweep; witness $wit" | tee "$verdict" |
| - fi |
| -} |
| -export -f one |
| -export SEEDS PKG SCRATCH BIN WRULES EXPECT |
| -printf '%s\n' $RULES | xargs -P "${ENGINESIM_PAR:-1}" -I{} bash -c 'one "$@"' _ {} |
| -xrc=$? |
| -if [ $xrc -ne 0 ]; then |
| - echo "sweep: orchestration failed (xargs rc=$xrc)" >&2 |
| - exit 2 |
| -fi |
| -# exactly one well-formed verdict per requested mutation |
| -want=$(printf '%s\n' $RULES | wc -l) |
| -have=$(find "$SCRATCH/verdicts" -type f | wc -l) |
| -if [ "$have" -ne "$want" ]; then |
| - echo "sweep: $want mutation(s) requested, $have verdict(s) written" >&2 |
| - exit 2 |
| -fi |
| -for r in $RULES; do |
| - v="$SCRATCH/verdicts/$(echo "$r" | tr ',' '+')" |
| - if ! grep -qE '^(CAUGHT|MISSED|EXPECTED-MISS|STALE|ERROR) ' "$v" 2>/dev/null; then |
| - echo "sweep: no well-formed verdict for $r" >&2 |
| - exit 2 |
| - fi |
| -done |
| -bad=$(cat "$SCRATCH"/verdicts/* | grep -c "^ERROR\|^MISSED\|^STALE") |
| -if [ "$bad" -gt 0 ]; then |
| - echo "sweep: $bad rule(s) ERROR, MISSED or STALE" >&2 |
| - exit 1 |
| -fi |
diff --git a/internal/sim/engines/rules_test.go b/internal/sim/engines/rules_test.go| deleted file mode 100644 |
| index d988036f5..000000000 |
| --- a/internal/sim/engines/rules_test.go |
| +++ /dev/null |
| @@ -1,95 +0,0 @@ |
| -package engines |
| - |
| -import ( |
| - "os" |
| - "strings" |
| -) |
| - |
| -// Every protocol rule the model enforces has a name here. The mutation |
| -// harness runs one prebuilt test binary with ENGINESIM_MUTATE set to one |
| -// rule name (or a comma-separated combination), and requires at least one |
| -// seed to fail. A rule whose mutation no seed catches is either redundant or |
| -// untested, and the run says which. |
| -// |
| -// Never edit `mutated` in place; the harness sets ENGINESIM_MUTATE. |
| -var mutated = "" |
| - |
| -// ENGINESIM_MUTATE sets `mutated` for one run of a prebuilt test binary, so |
| -// the mutation harness never edits or copies the source (mutate.sh). |
| -func init() { |
| - if v := os.Getenv("ENGINESIM_MUTATE"); v != "" { |
| - mutated = v |
| - } |
| -} |
| - |
| -// on reports whether a rule is enforced: false only when the mutation set |
| -// names it. |
| -func on(rule string) bool { |
| - for _, m := range strings.Split(mutated, ",") { |
| - if m == rule { |
| - return false |
| - } |
| - } |
| - return true |
| -} |
| - |
| -// allRules is the mutation list. Each task appends its rules, in spec order, |
| -// with a comment naming the spec section each answers. |
| -var allRules = []string{ |
| - // Task 2: the fence and the launch gate, I1 (spec §5.1 "The invariant", |
| - // "Setting the mark: the serving barrier", "What the edge does with it", |
| - // "Starts systemd makes on its own"; §5.9 the box-wide fence; §6.3) |
| - "set-before-repoint", // adoption gates before it repoints the live link (R2-1) |
| - "fence-needs-reload", // a failed reload advances nothing (R10-1) |
| - "fence-drains-admitted", // the fence cancels public requests admitted before the swap (R3-1) |
| - "fence-box-wide", // ... on every row of the box, deleted rows included (§5.9, R13-2) |
| - "gate-adopt", // the gate on adoption's restart |
| - "gate-swap", // ... on a swap's incoming generation (R7-1) |
| - "gate-fallback", // ... on a wake plan's fallback build (R9-1) |
| - "gate-recovery", // ... on a wake plan's recovery build (R9-1) |
| - "gate-seed", // ... on a seed |
| - "gate-cmd", // ... on a carlos run command |
| - "gate-waits-when-written", // the gate waits for the fence when 1 is already written (R10-1) |
| - "unreadable-declares", // an unreadable manifest is treated as declaring |
| - "live-link-only-adoption", // nothing but adoption (and --public) moves a live link (R11) |
| - "mark-on-final-upstream", // the edge checks the final resolved upstream's row (R1-2) |
| - |
| - // Task 3: classification, minted groups, the operator clear (spec §5.1 |
| - // "The column", "Platform-minted rows", "Becoming public is never |
| - // automatic", "Classification before serving"; §6.3) |
| - "classify-null-refused", // the edge refuses NULL like 1 (R2-2) |
| - "classify-staged", // the upgrade classifies 1 if any staged version declares (R8-1) |
| - "minted-follow-owner", // a minted instance row is in its owner's group: one mark, one barrier (R5-1) |
| - "grant-marks-group", // a grant on any row of the group marks the group (R6-1) |
| - "static-minted-public", // a minted static row is 0 by construction, never classified (R6-2) |
| - "owner-nonempty-unique", // the owner fallback matches only non-empty backends, and only uniquely (R7-2) |
| - "public-checks-live", // --public step 1: the live manifest is readable and does not declare |
| - "public-stops-group", // --public step 2: stop the whole group (R7-1, R8-2) |
| - "public-holds-lock", // --public holds the group's lock: adoption cannot move the live link under it |
| - "public-confirms-empty", // --public step 3: refuse unless every cgroup of the group is empty |
| - |
| - // Task 4: the dedicated engine box and ingress (spec §5.9; §5.1 "The |
| - // edge is the only ingress") |
| - "ports-excluded", // doc_engine with ports refused at ship; no listener for an internal group (R11-1) |
| - "dedicated-launch-check", // a declaring launch is refused on a box with a proxying row outside its group (R12-2) |
| - "dedicated-edge-refusal", // the edge refuses every proxying row outside the internal group homed on its box (R12-2) |
| - "ingress-precondition", // the operator's firewall admits only the edge's ports, from every source (R12-1, R13-1) |
| - |
| - // Task 5: calls, identity, grants and arming (spec §5.2 the signed |
| - // record; §5.3 the grant mirror; §5.4 the call path; §6.1, §6.2, §6.4) |
| - "cgroup-identity", // the engine socket admits only a process in its own instance's slice (R1-1) |
| - "door-uid", // the door makes an engine call only for a uid other than carlos (R2-3) |
| - "hop-caller-signed", // the engine box takes the caller only from a MAC-verified hop; the header is stripped elsewhere |
| - "engine-box-recheck", // the engine box checks its own grant table, whatever the calling box admitted (G4) |
| - "exact-route-engine", // an engine call reaches only the engine hostname's own route, never through a path map (R4-2) |
| - "floor-persisted", // the mirror's revision floor and record survive a restart (R1-4) |
| - "stale-clears-grants", // a stale, expired or never-read table grants nothing (§5.3, §6.4) |
| - "armed-refuses-unisolated", // an armed box refuses flat, foreign and worker launches before they start (R3-2, R4-1) |
| - "arm-checks-box", // arming refuses a box with an unisolated route or a non-empty carlos-exec@ cgroup (R5-2) |
| - |
| - // Final review (spec §5.1 "The invariant", "Becoming public is never |
| - // automatic"; §5.2, §5.3 the freshness bound, ruling R5) |
| - "new-group-fenced", // a new or unseen row's NULL is never fenced: a first declaring launch writes 1 and waits for the fence |
| - "clear-launch-lock", // the launch gate takes the group's lock, which --public holds for its whole run |
| - "grant-freshness-bound", // a record signed ten minutes ago or more is stale: the mirror refuses it and the table is empty |
| -} |
diff --git a/internal/sim/engines/sim_test.go b/internal/sim/engines/sim_test.go| deleted file mode 100644 |
| index fc66252fb..000000000 |
| --- a/internal/sim/engines/sim_test.go |
| +++ /dev/null |
| @@ -1,348 +0,0 @@ |
| -package engines |
| - |
| -import ( |
| - "fmt" |
| - "os" |
| - "os/exec" |
| - "reflect" |
| - "sort" |
| - "strconv" |
| - "strings" |
| - "testing" |
| -) |
| - |
| -// seedsFromEnv is the sweep size: ENGINESIM_SEEDS, else def. |
| -func seedsFromEnv(def int) int { |
| - if s := os.Getenv("ENGINESIM_SEEDS"); s != "" { |
| - if n, err := strconv.Atoi(s); err == nil && n > 0 { |
| - return n |
| - } |
| - } |
| - return def |
| -} |
| - |
| -// TestEngines is the sweep. ENGINESIM_SEEDS sets the seed count (the gate's |
| -// default is 200); ENGINESIM_SEED=n runs one seed and prints its trace. |
| -func TestEngines(t *testing.T) { |
| - if s := os.Getenv("ENGINESIM_SEED"); s != "" { |
| - seed, err := strconv.ParseInt(s, 10, 64) |
| - if err != nil { |
| - t.Fatalf("ENGINESIM_SEED=%q: %v", s, err) |
| - } |
| - w := runSeed(seed, true) |
| - for _, line := range w.trace { |
| - t.Log(line) |
| - } |
| - for _, v := range w.violations { |
| - t.Errorf("seed %d: %s", seed, v) |
| - } |
| - return |
| - } |
| - n := seedsFromEnv(200) |
| - failed := 0 |
| - count := map[string]int{} |
| - firstSeed := map[string]int64{} |
| - stats, done, events := map[string]int{}, map[string]int{}, map[string]int{} |
| - residuals := 0 |
| - for seed := int64(1); seed <= int64(n); seed++ { |
| - w := runSeed(seed, false) |
| - for k, v := range w.stats { |
| - stats[k] += v |
| - } |
| - for k, v := range w.done { |
| - done[k] += v |
| - } |
| - for k, v := range w.events { |
| - events[k] += v |
| - } |
| - residuals += len(w.residuals) |
| - if len(w.violations) == 0 { |
| - continue |
| - } |
| - failed++ |
| - for _, v := range w.violations { |
| - id := invariantOf(v) |
| - count[id]++ |
| - if _, ok := firstSeed[id]; !ok { |
| - firstSeed[id] = seed |
| - t.Logf("seed %d: %s", seed, v) |
| - } |
| - } |
| - } |
| - t.Logf("%d seeds, %d failed, %d residuals; mutated=%q", n, failed, residuals, mutated) |
| - t.Logf("actions chosen: %v", stats) |
| - t.Logf("actions completed: %v", done) |
| - t.Logf("events: %v", events) |
| - ids := make([]string, 0, len(count)) |
| - for id := range count { |
| - ids = append(ids, id) |
| - } |
| - sort.Strings(ids) |
| - for _, id := range ids { |
| - t.Logf(" %4d x %s (first seed %d)", count[id], id, firstSeed[id]) |
| - } |
| - if failed > 0 { |
| - t.Fatalf("%d of %d seeds violated an invariant", failed, n) |
| - } |
| - // the default world sets no residual flag, so it never generates one of |
| - // the spec's stated residuals (TestResidualsAreCountedNotFailed) |
| - if residuals > 0 { |
| - t.Fatalf("the default world recorded %d residuals; only a test's flag may generate one", residuals) |
| - } |
| -} |
| - |
| -// TestSeedDeterministic: one seed gives one trace, or no reported seed can |
| -// be replayed. |
| -func TestSeedDeterministic(t *testing.T) { |
| - for _, verbose := range []bool{false, true} { |
| - a, b := runSeed(7, verbose), runSeed(7, verbose) |
| - if len(a.trace) == 0 { |
| - t.Fatalf("verbose=%v: the trace is empty, so equality proves nothing", verbose) |
| - } |
| - if !reflect.DeepEqual(a.trace, b.trace) { |
| - t.Fatalf("verbose=%v: two runs of seed 7 differ", verbose) |
| - } |
| - if !reflect.DeepEqual(a.stats, b.stats) || !reflect.DeepEqual(a.done, b.done) || !reflect.DeepEqual(a.events, b.events) || !reflect.DeepEqual(a.violations, b.violations) { |
| - t.Fatalf("verbose=%v: two runs of seed 7 differ in stats or violations", verbose) |
| - } |
| - } |
| - if reflect.DeepEqual(newWorld(7, false).builds, newWorld(8, false).builds) && |
| - reflect.DeepEqual(newWorld(7, false).builds, newWorld(9, false).builds) && |
| - reflect.DeepEqual(newWorld(7, false).builds, newWorld(10, false).builds) { |
| - t.Fatal("builds do not vary with the seed") |
| - } |
| -} |
| - |
| -// TestMain handles ENGINESIM_LIST=1 before any test runs: it prints the rules |
| -// a run would check, one per line, to stdout and exits 0 without running a |
| -// test (the mutation harness reads this list). |
| -func TestMain(m *testing.M) { |
| - if os.Getenv("ENGINESIM_LIST") == "1" { |
| - for _, r := range allRules { |
| - fmt.Println(r) |
| - } |
| - os.Exit(0) |
| - } |
| - os.Exit(m.Run()) |
| -} |
| - |
| -// TestListPrintsRulesAndRunsNothing runs this test binary as a subprocess |
| -// with ENGINESIM_LIST=1 and requires that its output is exactly the rule |
| -// list and that no test ran. A control run without the variable shows the |
| -// "=== RUN" marker is what a test run prints. |
| -func TestListPrintsRulesAndRunsNothing(t *testing.T) { |
| - run := func(list bool) string { |
| - cmd := exec.Command(os.Args[0], "-test.v", "-test.run=TestOnMutation") |
| - cmd.Env = os.Environ() |
| - for i := 0; i < len(cmd.Env); i++ { |
| - if strings.HasPrefix(cmd.Env[i], "ENGINESIM_LIST=") { |
| - cmd.Env = append(cmd.Env[:i], cmd.Env[i+1:]...) |
| - i-- |
| - } |
| - } |
| - if list { |
| - cmd.Env = append(cmd.Env, "ENGINESIM_LIST=1") |
| - } |
| - out, err := cmd.Output() |
| - if err != nil { |
| - t.Fatalf("list=%v: %v", list, err) |
| - } |
| - return string(out) |
| - } |
| - if control := run(false); !strings.Contains(control, "=== RUN") { |
| - t.Fatalf("control run printed no test markers: %q", control) |
| - } |
| - want := "" |
| - for _, r := range allRules { |
| - want += r + "\n" |
| - } |
| - if got := run(true); got != want { |
| - t.Fatalf("ENGINESIM_LIST=1 output = %q, want exactly the rule list %q", got, want) |
| - } |
| -} |
| - |
| -// TestNewWorldShape pins the starting world the brief describes. |
| -func TestNewWorldShape(t *testing.T) { |
| - w := newWorld(1, false) |
| - if len(w.boxes) != 2 || w.boxes[0].ID != 0 || w.boxes[1].ID != 1 { |
| - t.Fatalf("want boxes 0 and 1, got %d", len(w.boxes)) |
| - } |
| - const eng = "eng.acct.apps.example" |
| - r := w.boxes[0].Rows[eng] |
| - if r == nil || !r.Platform || r.Kind != "instance" || r.Owner != "eng" || r.Backend == "" { |
| - t.Fatalf("box 0 lacks the minted platform row %s: %+v", eng, r) |
| - } |
| - if got := w.group(w.boxes[0], eng); got != "eng" { |
| - t.Fatalf("group of the minted row = %q, want eng", got) |
| - } |
| - if m := w.boxes[0].Mark[eng]; m != markInternal { |
| - t.Fatalf("the engine row's mark = %v, want markInternal", m) |
| - } |
| - s := w.boxes[1].Rows["shop"] |
| - if s == nil || s.Platform || s.Owner != "" || s.Backend == "" { |
| - t.Fatalf("box 1 lacks the public app row shop: %+v", s) |
| - } |
| - if got := w.group(w.boxes[1], "shop"); got != "shop" { |
| - t.Fatalf("group of an unminted row = %q, want its host", got) |
| - } |
| - if m := w.boxes[1].Mark["shop"]; m != markPublic { |
| - t.Fatalf("shop's mark = %v, want markPublic", m) |
| - } |
| - for v := 1; v <= 4; v++ { |
| - if b, ok := w.builds[v]; !ok || b.Ver != v { |
| - t.Fatalf("build %d missing or mislabelled: %+v", v, b) |
| - } |
| - } |
| - if len(w.builds) != 4 { |
| - t.Fatalf("want builds 1 to 4, got %d", len(w.builds)) |
| - } |
| - for _, b := range w.boxes { |
| - if b.Rows == nil || b.Mark == nil || b.Live == nil || b.Good == nil || b.Staged == nil { |
| - t.Fatalf("box %d has a nil map", b.ID) |
| - } |
| - } |
| - // a service row and a static row group by their own host |
| - b := w.boxes[1] |
| - b.Rows["svc"] = &row{Host: "svc", Kind: "service", Owner: "x"} |
| - if got := w.group(b, "svc"); got != "svc" { |
| - t.Fatalf("group of a service row = %q, want svc", got) |
| - } |
| -} |
| - |
| -// TestStepLoop: with no actions a step does nothing but advance w.step; with |
| -// actions registered each run is counted under the action's name (in done |
| -// only when it reports a completed transition), the walk is weighted, and |
| -// 400 chaos plus 200 calm steps run. |
| -func TestStepLoop(t *testing.T) { |
| - saved := actions |
| - defer func() { actions = saved }() |
| - |
| - actions = nil |
| - w := runSeed(3, false) |
| - if w.step != chaosSteps+calmSteps { |
| - t.Fatalf("w.step = %d, want %d", w.step, chaosSteps+calmSteps) |
| - } |
| - if len(w.stats) != 0 || len(w.violations) != 0 { |
| - t.Fatalf("no actions: stats %v violations %v", w.stats, w.violations) |
| - } |
| - |
| - calls := map[string]int{} |
| - var chaosCalls, calmCalls int |
| - phase := func(w *world) { |
| - if w.calm() { |
| - calmCalls++ |
| - } else { |
| - chaosCalls++ |
| - } |
| - } |
| - actions = []action{ |
| - {name: "alpha", weight: 3, run: func(w *world) bool { |
| - calls["alpha"]++ |
| - phase(w) |
| - return true |
| - }}, |
| - {name: "beta", weight: 1, run: func(w *world) bool { |
| - calls["beta"]++ |
| - phase(w) |
| - return false // chosen, but found nothing to do |
| - }}, |
| - {name: "never", weight: 0, run: func(w *world) bool { t.Error("a zero-weight action ran"); return true }}, |
| - } |
| - w = runSeed(3, false) |
| - if w.stats["alpha"] != calls["alpha"] || w.stats["beta"] != calls["beta"] { |
| - t.Fatalf("stats %v do not match calls %v", w.stats, calls) |
| - } |
| - if w.done["alpha"] != calls["alpha"] || w.done["beta"] != 0 { |
| - t.Fatalf("done %v: want alpha's every run and none of beta's (calls %v)", w.done, calls) |
| - } |
| - if calls["alpha"]+calls["beta"] != chaosSteps+calmSteps { |
| - t.Fatalf("each step should run one action: %v", calls) |
| - } |
| - if calls["alpha"] < 2*calls["beta"] { |
| - t.Fatalf("weights ignored: %v", calls) |
| - } |
| - if chaosCalls != chaosSteps || calmCalls != calmSteps || chaosSteps != 400 || calmSteps != 200 { |
| - t.Fatalf("phase split: chaos %d calm %d, want 400 and 200", chaosCalls, calmCalls) |
| - } |
| - if _, ok := w.stats["never"]; ok { |
| - t.Fatal("a zero-weight action was counted") |
| - } |
| -} |
| - |
| -// TestFailOncePerInvariant: fail records the first violation of each |
| -// invariant id and ignores the repeats. |
| -func TestFailOncePerInvariant(t *testing.T) { |
| - w := newWorld(1, false) |
| - w.fail("INV-X", "first %d", 1) |
| - w.fail("INV-X", "second %d", 2) |
| - w.fail("INV-Y", "other") |
| - if len(w.violations) != 2 { |
| - t.Fatalf("violations = %v, want two", w.violations) |
| - } |
| - if !strings.HasPrefix(w.violations[0], "INV-X: first 1") || !strings.HasPrefix(w.violations[1], "INV-Y: other") { |
| - t.Fatalf("violations = %v", w.violations) |
| - } |
| - if invariantOf(w.violations[0]) != "INV-X" { |
| - t.Fatalf("invariantOf = %q", invariantOf(w.violations[0])) |
| - } |
| -} |
| - |
| -// TestOnMutation: on is false only for a rule named in the mutation set. |
| -func TestOnMutation(t *testing.T) { |
| - saved := mutated |
| - defer func() { mutated = saved }() |
| - mutated = "" |
| - if !on("any-rule") { |
| - t.Fatal("no mutation: every rule is on") |
| - } |
| - mutated = "a-rule,b-rule" |
| - if on("a-rule") || on("b-rule") || !on("c-rule") { |
| - t.Fatal("only the named rules are off") |
| - } |
| -} |
| - |
| -// TestEveryActionFires: over 200 seeds of the unmutated walk every registered |
| -// action completes its transition at least once (chosen is not enough: an |
| -// action that always finds nothing to do exercises nothing), and public |
| -// requests and engine calls really reach processes. A rule that guards an |
| -// action no seed fires is untested however green the sweep looks (Review |
| -// Focus 2; final review, minor 3). |
| -func TestEveryActionFires(t *testing.T) { |
| - saved := mutated |
| - mutated = "" |
| - defer func() { mutated = saved }() |
| - if len(actions) == 0 { |
| - t.Fatal("no actions registered") |
| - } |
| - names := map[string]bool{} |
| - for _, a := range actions { |
| - if names[a.name] { |
| - t.Errorf("action %q registered twice", a.name) |
| - } |
| - names[a.name] = true |
| - if a.weight <= 0 { |
| - t.Errorf("action %q has weight %d: the walk never picks it", a.name, a.weight) |
| - } |
| - } |
| - done, events := map[string]int{}, map[string]int{} |
| - for seed := int64(1); seed <= 200; seed++ { |
| - w := runSeed(seed, false) |
| - for k, v := range w.done { |
| - done[k] += v |
| - } |
| - for k, v := range w.events { |
| - events[k] += v |
| - } |
| - } |
| - for _, a := range actions { |
| - if done[a.name] == 0 { |
| - t.Errorf("action %q never completed a transition over 200 seeds", a.name) |
| - } |
| - } |
| - for _, e := range []string{"delivered", "engine-call-reached"} { |
| - if events[e] == 0 { |
| - t.Errorf("no %s over 200 seeds", e) |
| - } |
| - } |
| - t.Logf("completed: %v; events: %v", done, events) |
| -} |
diff --git a/internal/sim/engines/witness_test.go b/internal/sim/engines/witness_test.go| deleted file mode 100644 |
| index cbc759729..000000000 |
| --- a/internal/sim/engines/witness_test.go |
| +++ /dev/null |
| @@ -1,2105 +0,0 @@ |
| -package engines |
| - |
| -import ( |
| - "fmt" |
| - "os" |
| - "sort" |
| - "strings" |
| - "testing" |
| -) |
| - |
| -// Witness scenarios, in hostlife's shape (internal/sim/hostlife/witness_test.go). |
| -// |
| -// The random sweep reaches some interleavings rarely. A witness is one |
| -// fixed, hand-scheduled scenario for one rule: it forces exactly the |
| -// interleaving the rule exists for, as a sequence of protocol steps, and |
| -// draws nothing from the world's RNG. It must hold (no invariant violated) |
| -// with the rules in place, and violate its named invariant when the rule's |
| -// mutation is applied, alone or in the stated combination. |
| -// |
| -// A witness calls w.check() at each step boundary, as doStep does in the |
| -// sweep; event invariants (INV-P at delivery) are recorded inside the step. |
| - |
| -type witness struct { |
| - rule string // the rule it is for |
| - needs string // the mutation set under which it must violate: the rule alone, or a combination the rule belongs to |
| - want string // the failure the scenario names: a substring of the first violation; "+X" parts must also be recorded |
| - note string // what it shows |
| - run func(t *testing.T, w *world) |
| -} |
| - |
| -var witnesses = []witness{ |
| - {"set-before-repoint", "set-before-repoint", "INV-I1+INV-P", |
| - "R2-1: adoption of a declaring build over a public route; between the repoint and the restart's gate a public request socket-activates the live unit under 0 (INV-I1 at the start) and is served by the declaring build (INV-P)", wSetBeforeRepoint}, |
| - {"set-before-repoint", "set-before-repoint", "INV-I1", |
| - "R2-1: between the repoint and the restart's gate, Restart=always starts the live unit, a declaring build, under 0; the restart then fences and replaces it, so only the check at the start sees it", wSetBeforeRepointSystemd}, |
| - {"fence-needs-reload", "fence-needs-reload", "INV-I1", |
| - "R10-1: the edge's reload keeps failing; a failed reload that advances the fenced counter lets adoption repoint and start the declaring build under the public map", wFenceNeedsReload}, |
| - {"fence-drains-admitted", "fence-drains-admitted", "INV-P", |
| - "R3-1: a request admitted at 0 waits in the activator's queue across the adoption; a fence that does not drain it lets it resume into the declaring build", wFenceDrainsAdmitted}, |
| - {"fence-box-wide", "fence-box-wide", "INV-P", |
| - "R13-2: a request admitted through a service row aimed at the engine's backend; the row is deleted, the request held across a declaring adoption; a fence scoped to the group's rows leaves it, and it resumes into the engine", wFenceBoxWide}, |
| - {"gate-adopt", "gate-adopt,set-before-repoint", "INV-I1", |
| - "redundant alone: adoption's set-before is the same gate reached earlier, so with it in place the restart's gate finds the group fenced; with both gone adoption starts the declaring build under 0", wGateAdopt}, |
| - {"gate-swap", "gate-swap", "INV-I1", |
| - "R7-1: a generation swap's incoming generation is a declaring build; ungated, it starts under 0", wGateSwap}, |
| - {"gate-fallback", "gate-fallback", "INV-I1+INV-P", |
| - "R9-1: after --public the first wake fails and the wake plan falls back to a declaring GoodVersion; ungated, it starts under 0 (INV-I1) and the triggering public request is served by it (INV-P)", wGateFallback}, |
| - {"gate-recovery", "gate-recovery", "INV-I1", |
| - "R9-1: wake recovery picks a declaring GoodVersion; ungated, it starts under 0", wGateRecovery}, |
| - {"gate-seed", "gate-seed", "INV-I1", |
| - "a seed of a declaring build; ungated, it starts under 0", wGateSeed}, |
| - {"gate-cmd", "gate-cmd", "INV-I1", |
| - "a carlos run command of a declaring build; ungated, it starts under 0", wGateCmd}, |
| - {"gate-waits-when-written", "gate-waits-when-written", "INV-I1", |
| - "R10-1: adoption times out with 1 written and the reload failing; a gate that waits only when it wrote the mark lets wake recovery start a declaring GoodVersion under the public map", wGateWaitsWhenWritten}, |
| - {"unreadable-declares", "unreadable-declares", "INV-I1", |
| - "a declaring build whose manifest cannot be read, launched under 0; read as non-declaring, it starts under 0", wUnreadableDeclares}, |
| - {"live-link-only-adoption", "live-link-only-adoption", "INV-I1", |
| - "R11: something other than adoption moves the live link to a declaring build; systemd's Restart=always starts it, ungated, under 0", wLiveLinkOnly}, |
| - {"mark-on-final-upstream", "mark-on-final-upstream", "INV-P", |
| - "R1-2: a public request through an alias whose final upstream is the engine; checked on the alias row, it reaches the engine", wMarkOnFinalUpstreamAlias}, |
| - {"mark-on-final-upstream", "mark-on-final-upstream", "INV-P", |
| - "R1-2: a public request through a static row's path map whose final upstream is the engine; checked on the static row, it reaches the engine", wMarkOnFinalUpstreamPath}, |
| - |
| - // Task 3: classification, minted groups, the operator clear |
| - {"classify-null-refused", "classify-null-refused", "INV-P", |
| - "R2-2: the engine runs a declaring build whose live manifest cannot be read; the upgrade leaves it NULL; an edge that serves NULL like 0 admits a public request into the engine", wClassifyNullRefused}, |
| - {"classify-staged", "classify-staged", "INV-I1+INV-P", |
| - "R8-1: an awake engine is repointed to a plain build without a restart, so the declaring build still runs; an upgrade that reads only the live manifest classifies the group 0, under the running engine (INV-I1) and a public request reaches it (INV-P)", wClassifyStaged}, |
| - {"classify-staged", "classify-staged,dedicated-launch-check", "INV-I1", |
| - "R8-1, app scope: two instances of one app; the declaring build is staged once, by the other instance; this one runs it from that copy, is repointed to a plain build without a restart and upgraded; read per group, or without the staged clause, it classifies 0 under the running engine. Since Task 4 the launch check refuses the second instance's declaring adoption (another group's row on the box), so it needs that check gone too, and the edge's dedicated refusal keeps the public out (INV-I1 only)", wClassifyStagedApp}, |
| - {"minted-follow-owner", "minted-follow-owner,dedicated-launch-check,dedicated-edge-refusal", "INV-P", |
| - "R5-1: an app minted a platform row while public; adoption of a declaring build marks and fences the app; a minted row that is its own group stays 0 and a public request by the minted host reaches the engine", wMintedFollowOwner}, |
| - {"minted-follow-owner", "minted-follow-owner", "INV-P", |
| - "R5-1, by the grant: --grant doc-engine on the minted row of a public app; a minted row that is its own group takes the mark alone, and a public request by the app's own host reaches the granted app", wMintedFollowOwnerGrant}, |
| - {"grant-marks-group", "grant-marks-group", "INV-P", |
| - "R6-1: --grant doc-engine on the minted row of a plain release; a grant that marks only when it is on the owner's own row leaves the group 0, and a public request by the minted host reaches the granted app", wGrantMarksGroup}, |
| - {"static-minted-public", "static-minted-public", "INV-AV", |
| - "R6-2: a static app with a minted row and a canary; an upgrade that classifies minted static rows like instance rows leaves them NULL, and they never answer (liveness)", wStaticMintedPublic}, |
| - {"owner-nonempty-unique", "owner-nonempty-unique,dedicated-edge-refusal", "INV-P", |
| - "R7-2: an engine instance's minted row was minted before owners were recorded; a fallback that matches empty sockets puts it in the group of a later plain instance of the app, so --public on that instance writes 0 on the engine's minted row. Since Task 4 its availability effect is gone (a misgrouped row on a box that homes a closed group is refused by design either way) and its safety effect needs the edge's dedicated refusal gone too: a public request by the minted host reaches the engine", wOwnerNonEmptyUnique}, |
| - {"public-checks-live", "public-checks-live", "INV-I1+INV-P", |
| - "--public on a group whose live release declares; without step 1 the clear writes 0, and systemd's socket activation starts the declaring live build ungated (INV-I1) for a public request (INV-P)", wPublicChecksLive}, |
| - {"public-stops-group", "public-stops-group,public-confirms-empty", "INV-I1+INV-P", |
| - "R7-1/R8-2: redundant alone: without the stop, step 3 finds the declaring generation still serving and refuses; with both gone, a clear after a rollout that repointed the live link to a plain build and only scheduled the swap writes 0 under the still-serving declaring generation", wPublicStopsGroup}, |
| - {"public-confirms-empty", "public-confirms-empty", "INV-I1+INV-P", |
| - "the clear's stop does not complete and leaves the declaring generation running; without step 3 the clear writes 0 under it (INV-I1) and a public request reaches it (INV-P)", wPublicConfirmsEmpty}, |
| - {"public-holds-lock", "public-holds-lock", "INV-I1+INV-P", |
| - "--public checks a plain live release; without the adoption lock, adoption repoints to a declaring build before the stop; the clear writes 0 over a declaring live link, and socket activation starts it ungated", wPublicHoldsLock}, |
| - |
| - // Task 4: the dedicated engine box and ingress |
| - {"ports-excluded", "ports-excluded", "INV-P", |
| - "R11-1: the engine route holds a port grant from a plain release, so the box renders its listener; adoption of a declaring build marks the group; a box that keeps the listener lets a public connection to the port, which the firewall admits as granted, reach the engine past the edge, with no capability pass in between", wPortsExcluded}, |
| - {"ports-excluded", "ports-excluded", "INV-P", |
| - "R11-1, by the grant: the public engine route on a plain build holds a port grant and its listener; --grant doc-engine marks the group; a box that keeps the listener lets a public connection reach the granted group past the edge, with no capability pass in between", wPortsExcludedGrant}, |
| - {"dedicated-launch-check", "dedicated-launch-check,dedicated-edge-refusal", "INV-P", |
| - "R12-2: redundant alone: a service row aimed at the engine's backend exists before a declaring adoption; the launch check refuses the adoption; without it the edge's refusal still refuses the row once the group is internal; with both gone a public request through the row reaches the engine", wDedicatedLaunchCheck}, |
| - {"dedicated-edge-refusal", "dedicated-edge-refusal", "INV-P", |
| - "R12-2: a service row aimed at the engine's backend is added after the engine runs internal, where no launch check sees it; an edge that serves it lets a public request reach the engine", wDedicatedEdgeRefusal}, |
| - {"ingress-precondition", "ingress-precondition", "INV-P", |
| - "R13-1: a service row on the calling box aimed at the engine box's address; a firewall that admits it lets a public request through the calling box's edge reach the engine directly", wIngressPrivate}, |
| - {"ingress-precondition", "ingress-precondition", "INV-P", |
| - "R12-1: the engine binds a port of its own on every interface; a firewall that admits it lets a public connection reach the engine", wOwnPort}, |
| - |
| - // Task 5: calls, identity, grants and arming |
| - {"cgroup-identity", "cgroup-identity", "INV-ID", |
| - "R1-1: on an armed box a sibling instance's process connects to the granted instance's engine socket (mode 0666); a socket whose path is the identity records the granted app as the caller", wCgroupIdentity}, |
| - {"door-uid", "door-uid", "INV-ID", |
| - "R2-3: a flat tenant running as carlos reads a granted app's door key and calls an engine through the door; a door that takes the key from uid carlos records the granted app as the caller", wDoorUID}, |
| - {"hop-caller-signed", "hop-caller-signed", "INV-ID", |
| - "a public client sends the engine box a request carrying X-Carlos-Hop-Caller naming a granted app; an engine box that takes the caller from the header rather than a verified hop records that app as the caller", wHopCallerSigned}, |
| - {"engine-box-recheck", "engine-box-recheck", "INV-G", |
| - "G4: a revoke is read everywhere; the calling box is rebuilt (no floor) and a bucket writer at once replays the record the revoke superseded, still inside its ten minutes; the calling box admits on it; an engine box that trusts the calling box's admission serves the revoked app although it has read the revoke", wEngineBoxRecheck}, |
| - {"exact-route-engine", "exact-route-engine", "INV-G", |
| - "R4-2: an app holds engine A's grant only; A's hostname is a static row whose path map points at engine B's route; an engine call resolved through the path map reaches B", wExactRouteEngine}, |
| - {"floor-persisted", "floor-persisted", "INV-G", |
| - "R1-4: a grant is revoked and read everywhere; a bucket writer at once replays the older record, still inside its ten minutes, which the floor refuses; both edges restart; a floor not persisted admits the replay, and the revoke both boxes had read is no longer in force", wFloorPersisted}, |
| - {"stale-clears-grants", "stale-clears-grants,grant-freshness-bound", "INV-G", |
| - "§6.4: redundant alone: a table's record was signed no later than its last good read, so the signed_at bound empties a stale table first. The bucket is unreachable when a revoke is published; ten minutes pass with no good read; with both checks gone the stale table still grants and serves the revoked app", wStaleClearsGrants}, |
| - {"armed-refuses-unisolated", "armed-refuses-unisolated", "INV-ARM", |
| - "R3-2/R4-1: on an armed box with engine sockets open, a foreign instance starts and a worker spawns; a box that does not refuse them runs unisolated tenant code beside open sockets", wArmedRefusesUnisolated}, |
| - {"armed-refuses-unisolated", "armed-refuses-unisolated", "INV-ARM", |
| - "R4-1: on an armed box, an app's worker spawns into carlos-exec@ (worker alone)", wArmedRefusesWorker}, |
| - {"armed-refuses-unisolated", "armed-refuses-unisolated", "INV-ARM", |
| - "R3-2: on an armed box, a flat instance starts (flat alone)", wArmedRefusesFlat}, |
| - {"arm-checks-box", "arm-checks-box", "INV-ARM", |
| - "R5-2: an app's worker runs in carlos-exec@ on an unarmed box; arming that does not check the box opens engine sockets beside it", wArmChecksBox}, |
| - |
| - // Final review |
| - {"new-group-fenced", "new-group-fenced", "INV-I1+INV-P", |
| - "a public request is admitted through a service row aimed at address X and held; the row is deleted; a declaring instance is provisioned at X; a new row's NULL taken as fenced lets its first launch skip the reload, so the held request is never drained and reaches the engine", wNewGroupFenced}, |
| - {"grant-freshness-bound", "grant-freshness-bound", "INV-G", |
| - "R5: the console re-signs (revision 2) and both edges read it; it revokes shop (revision 3) and a bucket writer puts revision 2 back before any edge reads 3; the floor admits it (equal revision); a mirror with no signed_at bound keeps the revoked grant until revision 2 expires, so a call ten minutes and one poll later reaches the engine", wGrantFreshnessBound}, |
| - {"clear-launch-lock", "clear-launch-lock", "INV-I1+INV-P", |
| - "--public on an internal group whose live release is plain; after its empty check and before its write of 0, a carlos run command of a declaring build passes the gate (the group is still fenced as internal); a launch that ignores the group's lock starts it, and --public writes 0 under it", wClearLaunchLock}, |
| -} |
| - |
| -// TestWitnesses is the deterministic half of the mutation evidence. |
| -// |
| -// With no mutation (the gate) it proves every witness's claim in full: the |
| -// scenario holds with every rule in place, holds under every proper subset of |
| -// its stated mutation set (so a rule a combination names is shown necessary, |
| -// not assumed), and under the whole set violates the failure the scenario |
| -// names, not merely some invariant. |
| -// |
| -// Under ENGINESIM_MUTATE=m (the harness) it runs the witnesses of the rules |
| -// in m; a witness whose set is within m must violate with its named failure. |
| -// ENGINESIM_WITNESS=rule runs one rule's witnesses with their trace. |
| -func TestWitnesses(t *testing.T) { |
| - only := os.Getenv("ENGINESIM_WITNESS") |
| - if mutated == "" { |
| - ran := 0 |
| - for _, x := range witnesses { |
| - if only != "" && x.rule != only { |
| - continue |
| - } |
| - ran++ |
| - check(t, x, "", false, only != "") |
| - for _, s := range properSubsets(x.needs) { |
| - check(t, x, s, false, only != "") |
| - } |
| - check(t, x, x.needs, true, only != "") |
| - } |
| - if only != "" && ran == 0 { |
| - t.Fatalf("no witness for rule %q", only) |
| - } |
| - return |
| - } |
| - set := mutationSet(mutated) |
| - for _, x := range witnesses { |
| - if only != "" && x.rule != only { |
| - continue |
| - } |
| - if !set[x.rule] { |
| - continue |
| - } |
| - needs := true |
| - for _, m := range strings.Split(x.needs, ",") { |
| - if !set[m] { |
| - needs = false |
| - } |
| - } |
| - if needs { |
| - check(t, x, mutated, true, only != "") |
| - continue |
| - } |
| - // the mutation set is not the witness's: report, enforce nothing |
| - report(t, x, mutated, only != "") |
| - } |
| -} |
| - |
| -// TestWitnessRulesKnown: every witness names a rule in allRules, and so does |
| -// every member of its mutation set. |
| -func TestWitnessRulesKnown(t *testing.T) { |
| - known := map[string]bool{} |
| - for _, r := range allRules { |
| - known[r] = true |
| - } |
| - for _, x := range witnesses { |
| - if !known[x.rule] { |
| - t.Errorf("witness for unknown rule %q", x.rule) |
| - } |
| - for _, m := range strings.Split(x.needs, ",") { |
| - if !known[m] { |
| - t.Errorf("witness %s needs unknown rule %q", x.rule, m) |
| - } |
| - } |
| - } |
| -} |
| - |
| -func report(t *testing.T, x witness, m string, trace bool) { |
| - saved := mutated |
| - mutated = m |
| - defer func() { mutated = saved }() |
| - w := newWitness() |
| - x.run(t, w) |
| - tag := "held" |
| - if len(w.violations) > 0 { |
| - tag = "violated: " + w.violations[0] |
| - } |
| - t.Logf("witness %s under %q (needs %q): %s", x.rule, m, x.needs, tag) |
| - if trace { |
| - dump(t, w) |
| - } |
| -} |
| - |
| -// check runs one witness under mutation m, reports it, and fails the test if |
| -// the outcome is not the stated one: held when no violation is expected, the |
| -// named failure when one is. |
| -func check(t *testing.T, x witness, m string, expectViolation bool, trace bool) { |
| - saved := mutated |
| - mutated = m |
| - defer func() { mutated = saved }() |
| - w := newWitness() |
| - x.run(t, w) |
| - violated := len(w.violations) > 0 |
| - tag := "held" |
| - if violated { |
| - tag = "violated: " + w.violations[0] |
| - } |
| - t.Logf("witness %s under %q (needs %q): %s", x.rule, m, x.needs, tag) |
| - switch { |
| - case expectViolation && !violated: |
| - t.Errorf("witness %s held under %q, which it must violate", x.rule, m) |
| - dump(t, w) |
| - case expectViolation && !wantMet(w.violations, x.want): |
| - t.Errorf("witness %s under %q violated, but not its named failure %q", x.rule, m, x.want) |
| - dump(t, w) |
| - case !expectViolation && violated: |
| - t.Errorf("witness %s violated under %q, where it must hold", x.rule, m) |
| - dump(t, w) |
| - } |
| - if trace { |
| - dump(t, w) |
| - } |
| -} |
| - |
| -// wantMet: the first violation names want's first part, and every further |
| -// "+" part is named by some recorded violation. |
| -func wantMet(vs []string, want string) bool { |
| - parts := strings.Split(want, "+") |
| - if len(vs) == 0 || !namedFailure(vs[0], parts[0]) { |
| - return false |
| - } |
| - for _, f := range parts[1:] { |
| - found := false |
| - for _, v := range vs { |
| - found = found || namedFailure(v, f) |
| - } |
| - if !found { |
| - return false |
| - } |
| - } |
| - return true |
| -} |
| - |
| -// namedFailure: the violation names the witness's failure. want is one |
| -// failure or several separated by "|"; a failure that ends in a digit must not |
| -// run on into another (INV-I1 is not INV-I10). |
| -func namedFailure(v, want string) bool { |
| - for _, f := range strings.Split(want, "|") { |
| - for i := 0; ; { |
| - j := strings.Index(v[i:], f) |
| - if j < 0 { |
| - break |
| - } |
| - end := i + j + len(f) |
| - last := f[len(f)-1] |
| - if !(last >= '0' && last <= '9') || end == len(v) || v[end] < '0' || v[end] > '9' { |
| - return true |
| - } |
| - i = i + j + 1 |
| - } |
| - } |
| - return false |
| -} |
| - |
| -func mutationSet(m string) map[string]bool { |
| - set := map[string]bool{} |
| - for _, x := range strings.Split(m, ",") { |
| - if x != "" { |
| - set[x] = true |
| - } |
| - } |
| - return set |
| -} |
| - |
| -// properSubsets: every non-empty proper subset of a comma-separated set. |
| -func properSubsets(needs string) []string { |
| - xs := strings.Split(needs, ",") |
| - var out []string |
| - for mask := 1; mask < (1<<len(xs))-1; mask++ { |
| - var sub []string |
| - for i, x := range xs { |
| - if mask&(1<<i) != 0 { |
| - sub = append(sub, x) |
| - } |
| - } |
| - out = append(out, strings.Join(sub, ",")) |
| - } |
| - return out |
| -} |
| - |
| -func dump(t *testing.T, w *world) { |
| - for _, line := range w.trace { |
| - t.Log(line) |
| - } |
| - t.Logf("state: %s", w.boxesState()) |
| -} |
| - |
| -// boxesState is a one-line summary of every box, for a failing witness. |
| -func (w *world) boxesState() string { |
| - var out []string |
| - for _, b := range w.boxes { |
| - hosts := make([]string, 0, len(b.Rows)) |
| - for h := range b.Rows { |
| - hosts = append(hosts, h) |
| - } |
| - sort.Strings(hosts) |
| - var marks []string |
| - for _, h := range hosts { |
| - marks = append(marks, fmt.Sprintf("%s=%v/%v", h, b.Mark[h], b.Serving[h])) |
| - } |
| - var procs []string |
| - for _, p := range b.Procs { |
| - procs = append(procs, fmt.Sprintf("%d:%s@v%d", p.ID, p.Group, p.Ver)) |
| - } |
| - var adm []string |
| - for _, r := range b.Admitted { |
| - adm = append(adm, fmt.Sprintf("%d:%s@e%d", r.ID, r.Row, r.Epoch)) |
| - } |
| - out = append(out, fmt.Sprintf("box%d{marks(reg/edge) %v wrote=%d fenced=%d epoch=%d reloadFails=%v live=%v good=%v procs=%v admitted=%v}", |
| - b.ID, marks, b.Wrote, b.Fenced, b.Epoch, b.ReloadFails, b.Live, b.Good, procs, adm)) |
| - } |
| - return strings.Join(out, " ") |
| -} |
| - |
| -// ---------- the fixture ---------- |
| - |
| -// The witness builds: one of each kind, fixed, so no scenario depends on a |
| -// seed's draw. |
| -const ( |
| - vPlain = 1 // reads, does not declare |
| - vEngine = 2 // reads, declares doc_engine |
| - vUnreadable = 3 // declares, but its manifest cannot be read |
| - vBlind = 4 // does not declare, manifest unreadable |
| -) |
| - |
| -func newWitness() *world { |
| - w := newWorld(0, true) |
| - w.builds = map[int]build{ |
| - vPlain: {Ver: vPlain, Declares: false, ManifestOK: true}, |
| - vEngine: {Ver: vEngine, Declares: true, ManifestOK: true}, |
| - vUnreadable: {Ver: vUnreadable, Declares: true, ManifestOK: false}, |
| - vBlind: {Ver: vBlind, Declares: false, ManifestOK: false}, |
| - } |
| - w.logf("witness world: builds %s", w.buildsString()) |
| - return w |
| -} |
| - |
| -// clearPublic is the operator's --public on group g (operatorPublic), then |
| -// the edge's next poll, as one witness step. False when the clear refused. |
| -func (w *world) clearPublic(b *box, g string) bool { |
| - ok := w.operatorPublic(b, g) |
| - w.reload(b) |
| - w.check() |
| - return ok |
| -} |
| - |
| -// publicEngine sets the engine group on box 0 to a public route serving the |
| -// plain build: live and good are vPlain, the mark is 0 and fenced, and one |
| -// process runs. |
| -func (w *world) publicEngine(t *testing.T) *box { |
| - b := w.boxes[0] |
| - b.Live[eng], b.Good[eng] = vPlain, vPlain |
| - if !w.clearPublic(b, eng) { |
| - t.Fatalf("witness: --public refused on a plain live release: %s", w.boxesState()) |
| - } |
| - if !w.launch(b, eng, vPlain, "seed") { |
| - t.Fatalf("witness: the plain build did not start under 0: %s", w.boxesState()) |
| - } |
| - w.check() |
| - if len(w.violations) > 0 { |
| - t.Fatalf("witness: the fixture violates: %v", w.violations) |
| - } |
| - return b |
| -} |
| - |
| -// ---------- the witnesses ---------- |
| - |
| -// wSetBeforeRepoint (R2-1): adoption repoints the live link to a declaring |
| -// build; before its restart a public request arrives, socket activation |
| -// starts the live unit (no activator, no gate) and serves it. With the mark |
| -// set and fenced before the repoint, the request is refused. |
| -func wSetBeforeRepoint(t *testing.T, w *world) { |
| - b := w.publicEngine(t) |
| - w.stopGroup(b, eng) |
| - w.adopt(b, eng, vEngine, func() { |
| - if r := w.admitPublic(b, engHost, "/"); r != nil { |
| - w.socketActivate(b, eng) |
| - w.deliver(r) |
| - } |
| - }) |
| - w.check() |
| -} |
| - |
| -// wSetBeforeRepointSystemd (R2-1): adoption repoints the live link to a |
| -// declaring build; before its restart, Restart=always starts the live unit |
| -// (no activator, no gate). No request is involved. |
| -func wSetBeforeRepointSystemd(t *testing.T, w *world) { |
| - b := w.publicEngine(t) |
| - w.adopt(b, eng, vEngine, func() { w.systemdRestart(b, eng) }) |
| - w.check() |
| -} |
| - |
| -// wFenceDrainsAdmitted (R3-1): a request admitted at 0 waits in the |
| -// activator's queue while adoption marks, fences, repoints and restarts; it |
| -// then resumes. |
| -func wFenceDrainsAdmitted(t *testing.T, w *world) { |
| - b := w.publicEngine(t) |
| - r := w.admitPublic(b, engHost, "/") |
| - if r == nil { |
| - t.Fatalf("witness: a public request to a public route was refused") |
| - } |
| - r.Held = true |
| - w.adopt(b, eng, vEngine, nil) |
| - w.check() |
| - w.deliver(r) |
| - w.check() |
| -} |
| - |
| -// r10Sequence (R10-1): the edge's reload fails; adoption of a declaring |
| -// build writes 1 and times out without repointing; then wake recovery picks |
| -// the declaring GoodVersion. |
| -func r10Sequence(t *testing.T, w *world) { |
| - b := w.publicEngine(t) |
| - b.Good[eng] = vEngine |
| - b.ReloadFails = true |
| - w.logf("witness: the edge's reload starts failing") |
| - w.adopt(b, eng, vEngine, nil) |
| - w.check() |
| - w.stopGroup(b, eng) |
| - w.wake(b, eng, "recovery", nil) |
| - w.check() |
| -} |
| - |
| -func wFenceNeedsReload(t *testing.T, w *world) { r10Sequence(t, w) } |
| -func wGateWaitsWhenWritten(t *testing.T, w *world) { r10Sequence(t, w) } |
| - |
| -// wFenceBoxWide (R13-2): a service row aimed at the engine's backend admits a |
| -// public request; the row is deleted and the request held; adoption of a |
| -// declaring build fences the group; the request resumes on the proxy it |
| -// already holds. |
| -func wFenceBoxWide(t *testing.T, w *world) { |
| - b := w.publicEngine(t) |
| - const svc = "svc.example" |
| - b.Rows[svc] = &row{Host: svc, Kind: "service", Backend: b.Rows[engHost].Backend, PathTo: map[string]string{}} |
| - b.Mark[svc] = markPublic |
| - w.reload(b) |
| - w.check() |
| - r := w.admitPublic(b, svc, "/") |
| - if r == nil { |
| - t.Fatalf("witness: the service row refused a public request: %s", w.boxesState()) |
| - } |
| - r.Held = true |
| - delete(b.Rows, svc) |
| - delete(b.Mark, svc) |
| - w.logf("witness: row %s deleted; request %d still holds its proxy", svc, r.ID) |
| - w.adopt(b, eng, vEngine, nil) |
| - w.check() |
| - w.deliver(r) |
| - w.check() |
| -} |
| - |
| -// wGateAdopt: adoption of a declaring build with no other start. |
| -func wGateAdopt(t *testing.T, w *world) { |
| - b := w.publicEngine(t) |
| - w.adopt(b, eng, vEngine, nil) |
| - w.check() |
| -} |
| - |
| -// wGateSwap (R7-1), wGateSeed, wGateCmd, wGateRecovery: a declaring build |
| -// started by that path under 0. |
| -func gatePath(path string) func(*testing.T, *world) { |
| - return func(t *testing.T, w *world) { |
| - b := w.publicEngine(t) |
| - if path == "recovery" { |
| - b.Good[eng] = vEngine |
| - w.stopGroup(b, eng) |
| - w.wake(b, eng, "recovery", nil) |
| - } else { |
| - w.launch(b, eng, vEngine, path) |
| - } |
| - w.check() |
| - } |
| -} |
| - |
| -func wGateSwap(t *testing.T, w *world) { gatePath("swap")(t, w) } |
| -func wGateSeed(t *testing.T, w *world) { gatePath("seed")(t, w) } |
| -func wGateCmd(t *testing.T, w *world) { gatePath("cmd")(t, w) } |
| -func wGateRecovery(t *testing.T, w *world) { gatePath("recovery")(t, w) } |
| - |
| -// oraclePublic makes box 0's engine group public on a plain live release. |
| -func oraclePublic(w *world, b *box) { |
| - b.Live[eng] = vPlain |
| - w.clearPublic(b, eng) |
| -} |
| - |
| -// wGateFallback (R9-1): the group ran a declaring build, was adopted to a |
| -// plain one (the mark stays 1) and cleared with --public; a public request |
| -// wakes it, the first wake fails and the plan falls back to the declaring |
| -// GoodVersion. |
| -func wGateFallback(t *testing.T, w *world) { |
| - b := w.boxes[0] |
| - b.Live[eng], b.Good[eng] = vEngine, vEngine |
| - if !w.launch(b, eng, vEngine, "seed") { |
| - t.Fatalf("witness: the engine did not start under its fenced mark: %s", w.boxesState()) |
| - } |
| - w.check() |
| - w.adopt(b, eng, vPlain, nil) |
| - w.check() |
| - b.Good[eng] = vEngine // the plain build has not proved itself yet |
| - if !w.clearPublic(b, eng) { |
| - t.Fatalf("witness: --public refused on a plain live release: %s", w.boxesState()) |
| - } |
| - r := w.admitPublic(b, engHost, "/") |
| - if r == nil { |
| - t.Fatalf("witness: a public request after --public was refused: %s", w.boxesState()) |
| - } |
| - r.Held = true |
| - w.wake(b, eng, "fallback", r) |
| - w.check() |
| -} |
| - |
| -// wUnreadableDeclares: a build that declares but whose manifest cannot be |
| -// read, seeded under 0. |
| -func wUnreadableDeclares(t *testing.T, w *world) { |
| - b := w.publicEngine(t) |
| - w.launch(b, eng, vUnreadable, "seed") |
| - w.check() |
| -} |
| - |
| -// wLiveLinkOnly (R11): something other than adoption moves the live link to |
| -// a declaring build, then systemd restarts the unit from the live link. |
| -func wLiveLinkOnly(t *testing.T, w *world) { |
| - b := w.publicEngine(t) |
| - w.moveLive(b, eng, vEngine, "a rollout tool") |
| - w.check() |
| - w.systemdRestart(b, eng) |
| - w.check() |
| -} |
| - |
| -// markOnFinalUpstream (R1-2): the engine runs fenced as internal; one public |
| -// request arrives by host and path, a row that resolves to the engine's row. |
| -func markOnFinalUpstream(t *testing.T, w *world, host, path string) { |
| - b := w.boxes[0] |
| - b.Live[eng], b.Good[eng] = vEngine, vEngine |
| - if !w.launch(b, eng, vEngine, "seed") { |
| - t.Fatalf("witness: the engine did not start under its fenced mark: %s", w.boxesState()) |
| - } |
| - w.check() |
| - if r := w.admitPublic(b, host, path); r != nil { |
| - w.deliver(r) |
| - } |
| - w.check() |
| -} |
| - |
| -func wMarkOnFinalUpstreamAlias(t *testing.T, w *world) { markOnFinalUpstream(t, w, engAlias, "/") } |
| -func wMarkOnFinalUpstreamPath(t *testing.T, w *world) { |
| - markOnFinalUpstream(t, w, engSite, engSitePath) |
| -} |
| - |
| -// ---------- Task 3: classification, minted groups, the operator clear ---------- |
| - |
| -// requestBy sends one public request by host and delivers it if admitted. |
| -func (w *world) requestBy(b *box, host string) { |
| - if r := w.admitPublic(b, host, "/"); r != nil { |
| - w.deliver(r) |
| - } |
| -} |
| - |
| -// wClassifyNullRefused (R2-2): the engine's live release declares but its |
| -// manifest cannot be read; the upgrade can classify it neither way, so it |
| -// stays NULL; a public request arrives. |
| -func wClassifyNullRefused(t *testing.T, w *world) { |
| - b := w.boxes[0] |
| - if !w.adopt(b, eng, vUnreadable, nil) { |
| - t.Fatalf("witness: adoption of the engine refused: %s", w.boxesState()) |
| - } |
| - w.check() |
| - w.upgrade(b) |
| - w.check() |
| - if m := w.groupMark(b, eng); m != markNull { |
| - t.Fatalf("witness: the upgrade classified an unreadable live release %v, want NULL", m) |
| - } |
| - w.requestBy(b, engHost) |
| - w.check() |
| -} |
| - |
| -// wClassifyStaged (R8-1): the engine runs a declaring build; adoption of a |
| -// plain build repoints the awake route without a restart, so the declaring |
| -// build keeps running; then the agent upgrades and a public request arrives. |
| -func wClassifyStaged(t *testing.T, w *world) { |
| - b := w.boxes[0] |
| - if !w.adopt(b, eng, vEngine, nil) { |
| - t.Fatalf("witness: adoption of the engine refused: %s", w.boxesState()) |
| - } |
| - w.check() |
| - if !w.repointAwake(b, eng, vPlain) { |
| - t.Fatalf("witness: the awake repoint was refused: %s", w.boxesState()) |
| - } |
| - w.check() |
| - w.upgrade(b) |
| - w.check() |
| - w.requestBy(b, engHost) |
| - w.check() |
| -} |
| - |
| -// wClassifyStagedApp (R8-1, app scope): tcp-a stages the declaring build |
| -// first; tcp-b, another instance of the app, adopts the same build (staged |
| -// for the app already, so recorded under tcp-a only), is repointed to a |
| -// plain build without a restart, and the agent upgrades. |
| -// |
| -// Since Task 4 the launch check refuses tcp-b's declaring adoption beside |
| -// tcp-a (a proxying row of another group): the model has no era before the |
| -// upgrade in which launches pass no gate, so this scenario needs the launch |
| -// check gone too. The edge's dedicated refusal then still refuses tcp-b's |
| -// public request (tcp-a is homed internal), so it violates INV-I1 only. |
| -func wClassifyStagedApp(t *testing.T, w *world) { |
| - b := w.engineFreeBox(t) |
| - if !w.provision(b, tcpA, tcpApp, "10.0.0.7:9101", vEngine) || !w.provision(b, tcpB, tcpApp, "10.0.0.7:9102", vPlain) { |
| - t.Fatalf("witness: provisioning refused: %s", w.boxesState()) |
| - } |
| - if !w.adopt(b, tcpB, vEngine, nil) { |
| - if on("dedicated-launch-check") { |
| - w.logf("witness: the launch check refuses %s's declaring adoption beside %s; on a dedicated box the scenario cannot arise", tcpB, tcpA) |
| - return |
| - } |
| - t.Fatalf("witness: adoption of the declaring build refused: %s", w.boxesState()) |
| - } |
| - w.check() |
| - for _, v := range b.Staged[tcpB] { |
| - if v == vEngine { |
| - t.Fatalf("witness: the declaring build is recorded under %s too; the scenario needs it staged for the other instance only", tcpB) |
| - } |
| - } |
| - if !w.repointAwake(b, tcpB, vPlain) { |
| - t.Fatalf("witness: the awake repoint was refused: %s", w.boxesState()) |
| - } |
| - w.check() |
| - w.upgrade(b) |
| - w.check() |
| - w.requestBy(b, tcpB) |
| - w.check() |
| -} |
| - |
| -const ( |
| - tcpApp = "acct/tcp" |
| - tcpA = "tcp-a" |
| - tcpB = "tcp-b" |
| - tcpC = "tcp-c" |
| - tcpD = "tcp-d" |
| - mintedB = "tcp-b.acct.apps.example" |
| - mintedC = "tcp-c.acct.apps.example" |
| -) |
| - |
| -// tcpPublic provisions a TCP-backed instance tcp-b of a plain build and mints |
| -// its platform row with the owner recorded; both answer publicly. |
| -func (w *world) tcpPublic(t *testing.T, b *box) { |
| - if !w.provision(b, tcpB, tcpApp, "10.0.0.7:9102", vPlain) { |
| - t.Fatalf("witness: provisioning %s refused: %s", tcpB, w.boxesState()) |
| - } |
| - w.mint(b, tcpB, mintedB, true) |
| - w.reload(b) |
| - w.check() |
| - if r := w.admitPublic(b, mintedB, "/"); r == nil { |
| - t.Fatalf("witness: the minted row of a public app refused a public request: %s", w.boxesState()) |
| - } else { |
| - w.deliver(r) |
| - } |
| - w.check() |
| - if len(w.violations) > 0 { |
| - t.Fatalf("witness: the fixture violates: %v", w.violations) |
| - } |
| -} |
| - |
| -// wMintedFollowOwner (R5-1): a public app with a minted row adopts a |
| -// declaring build; a public request arrives by the minted host. |
| -// |
| -// Since Task 4 a minted row that is its own group is a proxying row of |
| -// another group: the launch check refuses the adoption beside it, and the |
| -// edge's dedicated refusal refuses it once the app is internal. The witness |
| -// needs both gone with minted-follow-owner. |
| -func wMintedFollowOwner(t *testing.T, w *world) { |
| - b := w.engineFreeBox(t) |
| - w.tcpPublic(t, b) |
| - if !w.adopt(b, tcpB, vEngine, nil) { |
| - if on("minted-follow-owner") || !on("dedicated-launch-check") { |
| - t.Fatalf("witness: adoption of the declaring build refused: %s", w.boxesState()) |
| - } |
| - w.logf("witness: the minted row, its own group, is another group's row beside %s; the launch check refuses the adoption", tcpB) |
| - return |
| - } |
| - w.check() |
| - w.requestBy(b, mintedB) |
| - w.check() |
| -} |
| - |
| -// wMintedFollowOwnerGrant (R5-1, by the grant): a public app of a plain |
| -// build with a minted row; the operator grants doc-engine on the minted row; |
| -// a public request arrives by the app's own host. |
| -func wMintedFollowOwnerGrant(t *testing.T, w *world) { |
| - b := w.engineFreeBox(t) |
| - w.tcpPublic(t, b) |
| - w.grant(b, mintedB) |
| - w.check() |
| - w.requestBy(b, tcpB) |
| - w.check() |
| -} |
| - |
| -// wGrantMarksGroup (R6-1): a public app of a plain build with a minted row; |
| -// the operator grants doc-engine on the minted row; a public request arrives |
| -// by the minted host. |
| -func wGrantMarksGroup(t *testing.T, w *world) { |
| - b := w.engineFreeBox(t) |
| - w.tcpPublic(t, b) |
| - w.grant(b, mintedB) |
| - w.check() |
| - w.requestBy(b, mintedB) |
| - w.check() |
| -} |
| - |
| -// wStaticMintedPublic (R6-2): a static app with its minted row and a canary |
| -// on its own channel; the agent upgrades; at the end every public row must |
| -// answer. |
| -func wStaticMintedPublic(t *testing.T, w *world) { |
| - b := w.boxes[0] |
| - w.addStaticApp(b, "site") |
| - w.reload(b) |
| - w.check() |
| - w.upgrade(b) |
| - w.check() |
| - w.final() |
| -} |
| - |
| -// wOwnerNonEmptyUnique (R7-2): app acct/tcp's TCP instance tcp-b runs a |
| -// declaring build, internal; its platform row was minted before owners were |
| -// recorded, so the edge finds its owner by backend. tcp-a, a later plain |
| -// instance of the app, is cleared with --public. A public request arrives by |
| -// tcp-b's minted host. |
| -// |
| -// Task 3's version ended in INV-AV: tcp-b's public minted row, misgrouped |
| -// into a closed group, never answered. Since Task 4 a closed group homes its |
| -// box, so every row outside it, the misgrouped row included (its true group |
| -// is tcp-b), is refused by design and INV-AV does not count it. The safety |
| -// effect remains, behind the edge's dedicated refusal. |
| -func wOwnerNonEmptyUnique(t *testing.T, w *world) { |
| - b := w.engineFreeBox(t) |
| - if !w.provision(b, tcpB, tcpApp, "10.0.0.7:9102", vEngine) { |
| - t.Fatalf("witness: provisioning %s refused: %s", tcpB, w.boxesState()) |
| - } |
| - w.mint(b, tcpB, mintedB, false) |
| - w.reload(b) |
| - w.check() |
| - if !w.provision(b, tcpA, tcpApp, "10.0.0.7:9101", vPlain) { |
| - t.Fatalf("witness: provisioning %s refused: %s", tcpA, w.boxesState()) |
| - } |
| - w.check() |
| - if !w.clearPublic(b, tcpA) { |
| - t.Fatalf("witness: --public refused on %s's plain live release: %s", tcpA, w.boxesState()) |
| - } |
| - w.requestBy(b, mintedB) |
| - w.check() |
| -} |
| - |
| -// wPublicChecksLive: the engine's live release declares; the operator runs |
| -// --public; a public request arrives and socket activation starts the unit. |
| -func wPublicChecksLive(t *testing.T, w *world) { |
| - b := w.boxes[0] |
| - if !w.adopt(b, eng, vEngine, nil) { |
| - t.Fatalf("witness: adoption of the engine refused: %s", w.boxesState()) |
| - } |
| - w.check() |
| - w.clearPublic(b, eng) |
| - r := w.admitPublic(b, engHost, "/") |
| - w.socketActivate(b, eng) |
| - if r != nil { |
| - w.deliver(r) |
| - } |
| - w.check() |
| -} |
| - |
| -// wPublicStopsGroup (R7-1, R8-2): the engine runs a declaring generation; a |
| -// generation rollout of a plain build repoints the live link and only |
| -// schedules the swap; the operator runs --public; a public request arrives. |
| -func wPublicStopsGroup(t *testing.T, w *world) { |
| - b := w.boxes[0] |
| - if !w.adopt(b, eng, vEngine, nil) { |
| - t.Fatalf("witness: adoption of the engine refused: %s", w.boxesState()) |
| - } |
| - w.check() |
| - if !w.repointAwake(b, eng, vPlain) { |
| - t.Fatalf("witness: the rollout's repoint was refused: %s", w.boxesState()) |
| - } |
| - w.check() |
| - w.clearPublic(b, eng) |
| - w.requestBy(b, engHost) |
| - w.check() |
| -} |
| - |
| -// wPublicConfirmsEmpty: the engine runs a declaring generation; a rollout of |
| -// a plain build repoints the live link and only schedules the swap; the |
| -// operator runs --public and its stop leaves that generation running; a |
| -// public request arrives. |
| -func wPublicConfirmsEmpty(t *testing.T, w *world) { |
| - b := w.boxes[0] |
| - if !w.adopt(b, eng, vEngine, nil) { |
| - t.Fatalf("witness: adoption of the engine refused: %s", w.boxesState()) |
| - } |
| - w.check() |
| - if !w.repointAwake(b, eng, vPlain) { |
| - t.Fatalf("witness: the rollout's repoint was refused: %s", w.boxesState()) |
| - } |
| - w.check() |
| - w.clearStopMisses = true |
| - w.clearPublic(b, eng) |
| - w.clearStopMisses = false |
| - w.requestBy(b, engHost) |
| - w.check() |
| -} |
| - |
| -// TestGrantRefusedOnUnresolvedMintedRow: --grant doc-engine on a minted row |
| -// whose owner is not recorded and cannot be found uniquely (here two |
| -// instances of its app share its address) is refused; the row stays NULL at |
| -// the edge and refused, and no group is marked. |
| -func TestGrantRefusedOnUnresolvedMintedRow(t *testing.T) { |
| - w := newWitness() |
| - b := w.engineFreeBox(t) |
| - for _, h := range []string{tcpC, tcpD} { |
| - if !w.provision(b, h, tcpApp, "10.0.0.7:9103", vPlain) { |
| - t.Fatalf("provisioning %s refused: %s", h, w.boxesState()) |
| - } |
| - } |
| - w.mint(b, tcpC, mintedC, false) |
| - // and one whose recorded owner has no row |
| - b.Rows["gone"] = &row{Host: "gone", Kind: "instance", App: tcpApp, Backend: "10.0.0.7:9104", PathTo: map[string]string{}} |
| - w.mint(b, "gone", "gone.acct.apps.example", true) |
| - delete(b.Rows, "gone") |
| - w.reload(b) |
| - wrote := b.Wrote |
| - for _, h := range []string{mintedC, "gone.acct.apps.example"} { |
| - if w.grant(b, h) { |
| - t.Errorf("--grant on %s, whose owner cannot be resolved, succeeded", h) |
| - } |
| - if b.Rows[h].Grant { |
| - t.Errorf("--grant on %s recorded the grant", h) |
| - } |
| - if b.Serving[h] != markNull { |
| - t.Errorf("the edge serves %s %v, want NULL", h, b.Serving[h]) |
| - } |
| - if r := w.admitPublic(b, h, "/"); r != nil { |
| - t.Errorf("a public request to %s was admitted", h) |
| - } |
| - } |
| - if b.Wrote != wrote { |
| - t.Errorf("a refused grant changed the registry (%d to %d)", wrote, b.Wrote) |
| - } |
| - for _, g := range []string{tcpC, tcpD} { |
| - if m := w.groupMark(b, g); m != markPublic { |
| - t.Errorf("group %s is %v after a refused grant, want public", g, m) |
| - } |
| - } |
| - if len(w.violations) > 0 { |
| - t.Errorf("violations: %v", w.violations) |
| - } |
| - if t.Failed() { |
| - dump(t, w) |
| - } |
| -} |
| - |
| -// TestRevokeRunsTheBarrier: --grant on a minted row times out while the |
| -// edge's reload fails (1 written, not fenced); a public request is admitted |
| -// and held; --revoke through the minted row also times out and the mark stays |
| -// 1; adoption of a declaring build is refused for want of the fence. Once |
| -// the reload recovers, the fence drains the held request, the declaring |
| -// build starts, and nothing public reaches it. With the reload working, |
| -// --revoke returns once the edge has loaded it, and the mark is still 1. |
| -func TestRevokeRunsTheBarrier(t *testing.T) { |
| - w := newWitness() |
| - b := w.engineFreeBox(t) |
| - w.tcpPublic(t, b) |
| - b.ReloadFails = true |
| - if w.grant(b, mintedB) { |
| - t.Fatal("--grant returned loaded while the edge's reload fails") |
| - } |
| - if m := w.groupMark(b, tcpB); m != markInternal { |
| - t.Fatalf("after the timed-out grant the group is %v, want internal", m) |
| - } |
| - held := w.admitPublic(b, tcpB, "/") |
| - if held == nil { |
| - t.Fatalf("the edge (still serving 0) refused a public request: %s", w.boxesState()) |
| - } |
| - held.Held = true |
| - if w.revoke(b, mintedB) { |
| - t.Fatal("--revoke returned loaded while the edge's reload fails") |
| - } |
| - if b.Rows[mintedB].Grant { |
| - t.Fatal("--revoke left the grant recorded") |
| - } |
| - if m := w.groupMark(b, tcpB); m != markInternal { |
| - t.Fatalf("--revoke changed the mark to %v; only --public writes 0", m) |
| - } |
| - if w.adopt(b, tcpB, vEngine, nil) { |
| - t.Fatalf("adoption of a declaring build passed the gate without a fence: %s", w.boxesState()) |
| - } |
| - w.check() |
| - b.ReloadFails = false |
| - if !w.adopt(b, tcpB, vEngine, nil) { |
| - t.Fatalf("adoption refused after the reload recovered: %s", w.boxesState()) |
| - } |
| - w.check() |
| - w.deliver(held) |
| - if held.Reached != 0 { |
| - t.Fatalf("the request admitted before the fence reached process %d", held.Reached) |
| - } |
| - for _, h := range []string{tcpB, mintedB} { |
| - if r := w.admitPublic(b, h, "/"); r != nil { |
| - t.Fatalf("a public request to %s was admitted after the fence", h) |
| - } |
| - } |
| - // with the reload working, revoke waits for the edge and returns loaded |
| - w.grant(b, tcpB) |
| - if !w.revoke(b, tcpB) || b.Fenced < b.Wrote { |
| - t.Fatalf("--revoke with a working reload did not return loaded: %s", w.boxesState()) |
| - } |
| - if m := w.groupMark(b, tcpB); m != markInternal || !w.fenced(b, tcpB) { |
| - t.Fatalf("after --revoke the group is %v (fenced %v), want internal and fenced", m, w.fenced(b, tcpB)) |
| - } |
| - if len(w.violations) > 0 { |
| - t.Fatalf("violations: %v", w.violations) |
| - } |
| - if t.Failed() { |
| - dump(t, w) |
| - } |
| -} |
| - |
| -// wPublicHoldsLock: the engine was adopted to a plain build (the mark stays |
| -// 1); the operator runs --public; after its checks pass and before it stops |
| -// the group, adoption of a declaring build runs; then a public request |
| -// arrives and socket activation starts the unit. |
| -func wPublicHoldsLock(t *testing.T, w *world) { |
| - b := w.boxes[0] |
| - if !w.adopt(b, eng, vEngine, nil) || !w.adopt(b, eng, vPlain, nil) { |
| - t.Fatalf("witness: adoption refused: %s", w.boxesState()) |
| - } |
| - w.check() |
| - w.clearHook = func(hb *box, g, stage string) { |
| - if stage == "locked" { |
| - w.adopt(hb, g, vEngine, nil) |
| - } |
| - } |
| - w.clearPublic(b, eng) |
| - w.clearHook = nil |
| - r := w.admitPublic(b, engHost, "/") |
| - w.socketActivate(b, eng) |
| - if r != nil { |
| - w.deliver(r) |
| - } |
| - w.check() |
| -} |
| - |
| -// TestI1Oracle pins INV-I1 on hand-built states of box 0's engine group with |
| -// a declaring process running: the fence condition alone catches a group that |
| -// is NULL, unloaded by the edge, or written and swapped but unacknowledged; |
| -// the served-map condition alone catches a counter advanced without a swap. |
| -// A NULL group counts as closed once the edge has fenced the change that made |
| -// it NULL: the edge refuses NULL like 1 (spec §5.1 "The column"), and the |
| -// upgrade leaves a group NULL under a running declaring build whose live |
| -// manifest cannot be read (Task 3). A new row's NULL, which no change closed |
| -// and no reload has drained, never counts (final review, finding 1). |
| -func TestI1Oracle(t *testing.T) { |
| - cases := []struct { |
| - name string |
| - setup func(w *world, b *box) |
| - want string // "" holds; else a substring of the reason |
| - }{ |
| - {"fenced as internal", func(w *world, b *box) {}, ""}, |
| - {"NULL written over 0, not yet fenced", func(w *world, b *box) { |
| - oraclePublic(w, b) |
| - w.writeMark(b, eng, markNull) |
| - }, "not fenced"}, |
| - {"NULL written over 0 and fenced (the edge treats NULL like 1)", func(w *world, b *box) { |
| - oraclePublic(w, b) |
| - w.writeMark(b, eng, markNull) |
| - w.reload(b) |
| - }, ""}, |
| - {"a new row, NULL, with no fence generation", func(w *world, b *box) { |
| - for _, h := range []string{eng, engHost} { |
| - delete(b.Rows, h) |
| - delete(b.Mark, h) |
| - } |
| - delete(b.SetAt, eng) |
| - b.Rows[eng] = &row{Host: eng, Kind: "instance", App: "acct/eng", Backend: "/run/carlos/eng.sock", PathTo: map[string]string{}} |
| - b.Wrote++ |
| - w.reload(b) |
| - }, "not fenced"}, |
| - {"NULL on one row, 0 served on the other", func(w *world, b *box) { |
| - oraclePublic(w, b) |
| - b.Mark[engHost] = markNull |
| - b.Serving[engHost] = markNull |
| - }, "not fenced"}, |
| - {"written 1, absent from the edge's map", func(w *world, b *box) { |
| - oraclePublic(w, b) |
| - w.writeMark(b, eng, markInternal) |
| - delete(b.EdgeRows, engHost) |
| - delete(b.Serving, engHost) |
| - }, "not fenced"}, |
| - {"written 1 and swapped in, fence not acknowledged", func(w *world, b *box) { |
| - oraclePublic(w, b) |
| - w.writeMark(b, eng, markInternal) |
| - b.Serving[engHost] = markInternal |
| - }, "not fenced"}, |
| - {"counter advanced without a swap", func(w *world, b *box) { |
| - oraclePublic(w, b) |
| - w.writeMark(b, eng, markInternal) |
| - b.Fenced = b.Wrote |
| - }, "serves " + eng + " public"}, |
| - } |
| - for _, c := range cases { |
| - w := newWitness() |
| - b := w.boxes[0] |
| - c.setup(w, b) |
| - p := &proc{ID: 99, Group: eng, Ver: vEngine, Slice: "inst:" + eng} |
| - b.Procs = append(b.Procs, p) |
| - why := w.i1Broken(b, p) |
| - w.check() |
| - switch { |
| - case c.want == "" && (why != "" || len(w.violations) > 0): |
| - t.Errorf("%s: want held, got %q %v", c.name, why, w.violations) |
| - case c.want != "" && !strings.Contains(why, c.want): |
| - t.Errorf("%s: reason %q, want it to name %q", c.name, why, c.want) |
| - case c.want != "" && (len(w.violations) != 1 || invariantOf(w.violations[0]) != "INV-I1"): |
| - t.Errorf("%s: check recorded %v, want one INV-I1", c.name, w.violations) |
| - } |
| - // a plain build in the same state breaks nothing |
| - p.Ver = vPlain |
| - if why := w.i1Broken(b, p); why != "" { |
| - t.Errorf("%s: a non-declaring process breaks I1: %q", c.name, why) |
| - } |
| - } |
| -} |
| - |
| -// ---------- Task 4: the dedicated engine box and ingress ---------- |
| - |
| -const ( |
| - svcHost = "svc.example" // a service row of the witnesses |
| - tcpE = "tcp-e" // a TCP-backed engine on box 0 |
| - tcpEAddr = "10.0.0.7:9200" |
| -) |
| - |
| -// engineFreeBox is box 0 with the engine's rows removed, the edge reloaded: |
| -// a box that homes no internal group, for scenarios that need instances of |
| -// their own (the dedicated-box rule refuses every other proxying row on a box |
| -// that homes the engine, and refuses a declaring launch beside one). |
| -func (w *world) engineFreeBox(t *testing.T) *box { |
| - b := w.boxes[0] |
| - for _, h := range []string{eng, engHost, engAlias, engSite} { |
| - delete(b.Rows, h) |
| - delete(b.Mark, h) |
| - } |
| - delete(b.SetAt, eng) |
| - b.Wrote++ |
| - w.logf("witness: box0's engine rows removed (registry change %d)", b.Wrote) |
| - w.reload(b) |
| - w.check() |
| - if len(w.violations) > 0 { |
| - t.Fatalf("witness: the fixture violates: %v", w.violations) |
| - } |
| - return b |
| -} |
| - |
| -// runningEngine starts the engine group on box 0 on the declaring build, |
| -// fenced as internal (its starting mark), and returns its process. |
| -func (w *world) runningEngine(t *testing.T) (*box, *proc) { |
| - b := w.boxes[0] |
| - b.Live[eng], b.Good[eng] = vEngine, vEngine |
| - if !w.launch(b, eng, vEngine, "seed") { |
| - t.Fatalf("witness: the engine did not start under its fenced mark: %s", w.boxesState()) |
| - } |
| - w.check() |
| - if len(w.violations) > 0 { |
| - t.Fatalf("witness: the fixture violates: %v", w.violations) |
| - } |
| - return b, b.Procs[len(b.Procs)-1] |
| -} |
| - |
| -// portsEngine is the public engine route shipping a plain release declaring |
| -// ports: the box renders its listener, and a public connection to the port |
| -// reaches the plain build. It returns the port. |
| -func (w *world) portsEngine(t *testing.T) (*box, string) { |
| - b := w.publicEngine(t) |
| - if !w.ship(b, eng, vPlain, true) { |
| - t.Fatalf("witness: a plain release declaring ports was refused: %s", w.boxesState()) |
| - } |
| - port := b.PortGrant[eng] |
| - if port == "" || b.Listen[port] != eng { |
| - t.Fatalf("witness: no listener rendered for the granted port: %s", w.boxesState()) |
| - } |
| - if p := w.directConnect(b, port, true); p == nil { |
| - t.Fatalf("witness: the granted port of a public route reached nothing: %s", w.boxesState()) |
| - } |
| - w.check() |
| - return b, port |
| -} |
| - |
| -// listenerGone fails the witness if the write that closed the group left |
| -// port's listener in place, while ports-excluded holds: the write removes it |
| -// itself, before any fence and with no capability pass (final review, minor |
| -// 2). |
| -func (w *world) listenerGone(t *testing.T, b *box, port, after string) { |
| - if on("ports-excluded") && b.Listen[port] != "" { |
| - t.Fatalf("witness: the listener on %s is still there right after %s: %s", port, after, w.boxesState()) |
| - } |
| -} |
| - |
| -// wPortsExcluded (R11-1): the public engine route ships a plain release |
| -// declaring ports, and the box renders its listener; then adoption of a |
| -// declaring build; at once, with no capability pass, a public connection |
| -// arrives on the granted port. |
| -func wPortsExcluded(t *testing.T, w *world) { |
| - b, port := w.portsEngine(t) |
| - if !w.adopt(b, eng, vEngine, nil) { |
| - t.Fatalf("witness: adoption of the engine refused: %s", w.boxesState()) |
| - } |
| - w.listenerGone(t, b, port, "the adoption") |
| - w.check() |
| - w.directConnect(b, port, true) |
| - w.check() |
| -} |
| - |
| -// wPortsExcludedGrant (R11-1, by the grant): the public engine route serves a |
| -// plain build on its ports listener; the operator grants doc-engine on it; at |
| -// once, with no capability pass, a public connection arrives on the port. |
| -func wPortsExcludedGrant(t *testing.T, w *world) { |
| - b, port := w.portsEngine(t) |
| - w.grant(b, engHost) |
| - w.listenerGone(t, b, port, "the grant") |
| - w.check() |
| - w.directConnect(b, port, true) |
| - w.check() |
| -} |
| - |
| -// TestPortsListenerGoneOnNull (final review, minor 2): the upgrade leaves a |
| -// route with no live release NULL; the write of NULL removes its ports |
| -// listener at once, before the capability pass runs, and a public connection |
| -// to the port is refused by the firewall. |
| -func TestPortsListenerGoneOnNull(t *testing.T) { |
| - w := newWitness() |
| - b := w.boxes[1] |
| - b.PortGrant["shop"] = "40001" |
| - w.capsPass(b) |
| - if b.Listen["40001"] != "shop" { |
| - t.Fatalf("fixture: no listener for shop's grant: %s", w.boxesState()) |
| - } |
| - w.upgrade(b) |
| - if m := w.groupMark(b, "shop"); m != markNull { |
| - t.Fatalf("fixture: shop is %v after the upgrade, want NULL", m) |
| - } |
| - if b.Listen["40001"] != "" { |
| - t.Errorf("the listener is still there right after the upgrade's NULL: %s", w.boxesState()) |
| - } |
| - if p := w.directConnect(b, "40001", true); p != nil { |
| - t.Errorf("a public connection to the NULL route's port reached process %d", p.ID) |
| - } |
| - w.check() |
| - if len(w.violations) > 0 { |
| - t.Errorf("violations: %v", w.violations) |
| - } |
| - if t.Failed() { |
| - dump(t, w) |
| - } |
| -} |
| - |
| -// wDedicatedLaunchCheck (R12-2): the public engine route has a service row |
| -// beside it aimed at its backend; adoption of a declaring build; a public |
| -// request arrives through the service row. |
| -func wDedicatedLaunchCheck(t *testing.T, w *world) { |
| - b := w.publicEngine(t) |
| - w.addServiceRow(b, svcHost, b.Rows[eng].Backend) |
| - w.reload(b) |
| - w.check() |
| - ok := w.adopt(b, eng, vEngine, nil) |
| - if ok && on("dedicated-launch-check") { |
| - t.Fatalf("witness: a declaring adoption passed the launch check beside a service row: %s", w.boxesState()) |
| - } |
| - w.check() |
| - w.requestBy(b, svcHost) |
| - w.check() |
| -} |
| - |
| -// wDedicatedEdgeRefusal (R12-2): the engine runs internal; a service row |
| -// aimed at its backend is added afterwards; the edge polls; a public request |
| -// arrives through the service row. |
| -func wDedicatedEdgeRefusal(t *testing.T, w *world) { |
| - b, _ := w.runningEngine(t) |
| - w.addServiceRow(b, svcHost, b.Rows[eng].Backend) |
| - w.reload(b) |
| - w.check() |
| - w.requestBy(b, svcHost) |
| - w.check() |
| -} |
| - |
| -// wIngressPrivate (R13-1): a TCP-backed engine runs internal on box 0; a |
| -// service row on box 1 is aimed at box 0's address and the engine's port; a |
| -// public request arrives at box 1's edge through it. |
| -func wIngressPrivate(t *testing.T, w *world) { |
| - b0, b1 := w.engineFreeBox(t), w.boxes[1] |
| - if !w.provision(b0, tcpE, tcpApp, tcpEAddr, vEngine) { |
| - t.Fatalf("witness: provisioning the TCP engine refused: %s", w.boxesState()) |
| - } |
| - w.check() |
| - w.addServiceRow(b1, svcHost, tcpEAddr) |
| - w.reload(b1) |
| - w.check() |
| - r := w.admitPublic(b1, svcHost, "/") |
| - if r == nil { |
| - t.Fatalf("witness: box1's edge refused its own service row: %s", w.boxesState()) |
| - } |
| - w.deliver(r) |
| - w.check() |
| -} |
| - |
| -// wOwnPort (R12-1): the engine runs internal and binds a port of its own on |
| -// every interface; a public connection arrives on that port. |
| -func wOwnPort(t *testing.T, w *world) { |
| - b, p := w.runningEngine(t) |
| - w.bindOwnPort(b, p) |
| - w.directConnect(b, ownPort(p), true) |
| - w.check() |
| -} |
| - |
| -// TestNullRouteHomesTheBox: a NULL route homes its box like a route marked |
| -// 1, whether or not it has a release. Here box 1's shop has no release, so |
| -// the upgrade leaves it NULL; a service row aimed at its backend must get the |
| -// internal refusal. Were it served, a request admitted through it and held, |
| -// with the row then deleted, would outlive a declaring `carlos run` in the |
| -// NULL group: the gate writes 1 over NULL, a group already fenced, so no |
| -// reload bumps the epoch, and the launch check finds no row to refuse. |
| -func TestNullRouteHomesTheBox(t *testing.T) { |
| - w := newWitness() |
| - b := w.boxes[1] |
| - w.upgrade(b) |
| - if m := w.groupMark(b, "shop"); m != markNull || b.Live["shop"] != 0 { |
| - t.Fatalf("fixture: shop is %v with live v%d, want NULL with no release", m, b.Live["shop"]) |
| - } |
| - w.addServiceRow(b, svcHost, b.Rows["shop"].Backend) |
| - w.reload(b) |
| - r := w.admitPublic(b, svcHost, "/") |
| - if r != nil { |
| - r.Held = true |
| - w.deleteRow(b, svcHost) |
| - w.launch(b, "shop", vEngine, "cmd") |
| - w.deliver(r) |
| - } |
| - w.check() |
| - if r != nil { |
| - t.Errorf("a service row beside a NULL route was served (request %d)", r.ID) |
| - } |
| - if len(w.violations) > 0 { |
| - t.Errorf("violations: %v", w.violations) |
| - } |
| - if t.Failed() { |
| - dump(t, w) |
| - } |
| -} |
| - |
| -// TestShipRefusesDocEngineWithPorts (spec §8): `carlos ship` refuses a |
| -// release declaring doc_engine and ports together, and nothing is adopted or |
| -// granted; a plain release declaring ports ships, and its port listens. |
| -func TestShipRefusesDocEngineWithPorts(t *testing.T) { |
| - w := newWitness() |
| - b := w.publicEngine(t) |
| - wrote := b.Wrote |
| - if w.ship(b, eng, vEngine, true) { |
| - t.Fatal("a release declaring doc_engine and ports shipped") |
| - } |
| - if b.Live[eng] != vPlain || b.PortGrant[eng] != "" || len(b.Listen) != 0 || b.Wrote != wrote { |
| - t.Fatalf("a refused ship changed the box: %s", w.boxesState()) |
| - } |
| - if !w.ship(b, eng, vPlain, true) || b.Listen[b.PortGrant[eng]] != eng { |
| - t.Fatalf("a plain release declaring ports did not ship with its listener: %s", w.boxesState()) |
| - } |
| - if len(w.violations) > 0 { |
| - t.Fatalf("violations: %v", w.violations) |
| - } |
| -} |
| - |
| -// TestEngineBoxKeepsStaticRows (spec §8): on a box homing an internal group, |
| -// a service row aimed at the engine and another app's instance get the |
| -// internal refusal, a declaring launch beside them is refused, and the |
| -// static row keeps answering. |
| -func TestEngineBoxKeepsStaticRows(t *testing.T) { |
| - w := newWitness() |
| - b, _ := w.runningEngine(t) |
| - w.addServiceRow(b, svcHost, b.Rows[eng].Backend) |
| - b.Rows["other"] = &row{Host: "other", Kind: "instance", App: "acct/other", Backend: "10.0.0.7:9300", PathTo: map[string]string{}} |
| - b.Mark["other"] = markPublic |
| - w.reload(b) |
| - for _, h := range []string{svcHost, "other"} { |
| - if _, outcome := w.admit(b, h, "/"); outcome != refused { |
| - t.Errorf("%s on the engine's box: %s, want the internal refusal", h, outcome) |
| - } |
| - } |
| - if _, outcome := w.admit(b, engSite, "/"); outcome != answered { |
| - t.Errorf("the static row %s on the engine's box: %s, want answered", engSite, outcome) |
| - } |
| - if w.launch(b, eng, vEngine, "seed") { |
| - t.Errorf("a declaring launch beside other proxying rows was not refused") |
| - } |
| - w.check() |
| - if len(w.violations) > 0 { |
| - t.Errorf("violations: %v", w.violations) |
| - } |
| - if t.Failed() { |
| - dump(t, w) |
| - } |
| -} |
| - |
| -// wNewGroupFenced (final review, finding 1): on a box that homes nothing, a |
| -// service row aimed at address X admits a public request, which is held; the |
| -// row is deleted; a declaring instance is provisioned at X. Its row is new |
| -// and NULL, but the edge has never loaded it: its first launch must write 1 |
| -// and wait for a fence, whose epoch bump drains the held request. |
| -func wNewGroupFenced(t *testing.T, w *world) { |
| - b := w.engineFreeBox(t) |
| - w.addServiceRow(b, svcHost, tcpEAddr) |
| - w.reload(b) |
| - w.check() |
| - r := w.admitPublic(b, svcHost, "/") |
| - if r == nil { |
| - t.Fatalf("witness: the service row refused a public request: %s", w.boxesState()) |
| - } |
| - r.Held = true |
| - w.deleteRow(b, svcHost) |
| - if !w.provision(b, tcpE, tcpApp, tcpEAddr, vEngine) { |
| - t.Fatalf("witness: provisioning the declaring instance refused: %s", w.boxesState()) |
| - } |
| - w.check() |
| - w.deliver(r) |
| - w.check() |
| -} |
| - |
| -// wClearLaunchLock (final review, finding 2): the engine was adopted to a |
| -// plain build (the mark stays 1); the operator runs --public; after its empty |
| -// check, a carlos run command of the declaring build tries to start; then a |
| -// public request arrives. |
| -func wClearLaunchLock(t *testing.T, w *world) { |
| - b := w.boxes[0] |
| - if !w.adopt(b, eng, vEngine, nil) || !w.adopt(b, eng, vPlain, nil) { |
| - t.Fatalf("witness: adoption refused: %s", w.boxesState()) |
| - } |
| - w.check() |
| - w.clearHook = func(hb *box, g, stage string) { |
| - if stage == "confirmed" { |
| - w.launch(hb, g, vEngine, "cmd") |
| - } |
| - } |
| - w.clearPublic(b, eng) |
| - w.clearHook = nil |
| - w.requestBy(b, engHost) |
| - w.check() |
| -} |
| - |
| -// wGrantFreshnessBound (final review, finding 3; ruling R5): thirty ticks in, |
| -// the console re-signs (revision 2, granting shop) and both edges read it; |
| -// the console revokes shop (revision 3) and a bucket writer puts revision 2 |
| -// back before any edge reads 3. Each edge reads revision 2 again (equal to |
| -// its floor: the same signed bytes). Shop calls at once (within the bound), |
| -// then again ten minutes and one poll after the revoke. |
| -func wGrantFreshnessBound(t *testing.T, w *world) { |
| - w.runningEngine(t) |
| - shop := w.armedShop(t) |
| - w.advance(30) |
| - w.publish(w.console.Rev + 1) // the periodic re-sign: revision 2, signed at 30 |
| - w.pollAll() |
| - w.consoleRevoke(shopEng) // revision 3, at 30 |
| - w.replay(2) |
| - w.pollAll() |
| - w.check() |
| - w.engineCall(w.boxes[1], shop, false, "carlos", "shop", eng, "/") |
| - w.check() |
| - w.advance(staleTicks + pollTicks + 1) |
| - w.pollAll() |
| - w.engineCall(w.boxes[1], shop, false, "carlos", "shop", eng, "/") |
| - w.check() |
| -} |
| - |
| -// TestReplayBoundedBySignedAt (ruling R5): wGrantFreshnessBound's replay, with |
| -// every rule in place, keeps the revoked grant on both edges until the |
| -// replayed record's signed_at plus ten minutes, and not one tick longer. |
| -func TestReplayBoundedBySignedAt(t *testing.T) { |
| - w := newWitness() |
| - w.runningEngine(t) |
| - shop := w.armedShop(t) |
| - w.advance(30) |
| - w.publish(w.console.Rev + 1) |
| - signed := w.now() |
| - w.pollAll() |
| - w.consoleRevoke(shopEng) |
| - w.replay(2) |
| - w.advance(staleTicks - 1) // 59 ticks after revision 2 was signed |
| - w.pollAll() |
| - if !w.engineCall(w.boxes[1], shop, false, "carlos", "shop", eng, "/") { |
| - t.Errorf("at signed_at+%d the replayed record should still grant (the bound is not tighter than R5): %s", w.now()-signed, w.mirrorsState()) |
| - } |
| - w.advance(1) |
| - w.pollAll() |
| - if w.engineCall(w.boxes[1], shop, false, "carlos", "shop", eng, "/") { |
| - t.Errorf("at signed_at+%d the replayed record still grants: %s", w.now()-signed, w.mirrorsState()) |
| - } |
| - w.check() |
| - if len(w.violations) > 0 || len(w.residuals) > 0 { |
| - t.Errorf("violations %v residuals %v", w.violations, w.residuals) |
| - } |
| - if t.Failed() { |
| - dump(t, w) |
| - } |
| -} |
| - |
| -// ---------- Task 5: calls, identity, grants and arming ---------- |
| - |
| -// shopEng is the grant every Task 5 world starts with: shop may call eng. |
| -const shopEng = "acct/shop/eng" |
| - |
| -// armedShop starts shop on box 1 on the plain build and arms box 1, so |
| -// shop's engine socket is open. It returns shop's process. |
| -func (w *world) armedShop(t *testing.T) *proc { |
| - b := w.boxes[1] |
| - b.Live["shop"], b.Good["shop"] = vPlain, vPlain |
| - if !w.launch(b, "shop", vPlain, "seed") { |
| - t.Fatalf("witness: shop did not start: %s", w.boxesState()) |
| - } |
| - if !w.arm(b) { |
| - t.Fatalf("witness: arming box 1 with only nested shop refused: %s", w.boxesState()) |
| - } |
| - w.check() |
| - if len(w.violations) > 0 { |
| - t.Fatalf("witness: the fixture violates: %v", w.violations) |
| - } |
| - return w.newest(b, "shop") |
| -} |
| - |
| -// pollAll is one mirror poll on every box. |
| -func (w *world) pollAll() { |
| - for _, b := range w.boxes { |
| - w.mirrorTick(b) |
| - } |
| -} |
| - |
| -// wCgroupIdentity (R1-1): box 1 runs shop and a sibling instance, other, |
| -// and is armed; other's process connects to shop's engine socket. |
| -func wCgroupIdentity(t *testing.T, w *world) { |
| - w.runningEngine(t) |
| - b := w.boxes[1] |
| - if !w.provision(b, "other", "acct/other", "127.0.0.1:9002", vPlain) { |
| - t.Fatalf("witness: provisioning other refused: %s", w.boxesState()) |
| - } |
| - w.armedShop(t) |
| - op := w.newest(b, "other") |
| - if op == nil { |
| - t.Fatalf("witness: other is not running: %s", w.boxesState()) |
| - } |
| - w.engineCall(b, op, false, "carlos", "shop", eng, "/") |
| - w.check() |
| -} |
| - |
| -// wDoorUID (R2-3): a flat tenant on unarmed box 1, running as carlos, |
| -// presents shop's door key with Host: eng. |
| -func wDoorUID(t *testing.T, w *world) { |
| - w.runningEngine(t) |
| - b := w.boxes[1] |
| - if !w.launchUnisolated(b, "flat") { |
| - t.Fatalf("witness: a flat start on an unarmed box refused: %s", w.boxesState()) |
| - } |
| - w.check() |
| - w.engineCall(b, w.newest(b, "flat"), true, "carlos", "shop", eng, "/") |
| - w.check() |
| -} |
| - |
| -// wHopCallerSigned: a public client sends box 0 a request for the engine's |
| -// hostname carrying X-Carlos-Hop-Caller: acct/shop/eng and no hop MAC. |
| -func wHopCallerSigned(t *testing.T, w *world) { |
| - b, _ := w.runningEngine(t) |
| - w.clientHop(b, engHost, "/", callerOf("acct/shop", eng)) |
| - w.check() |
| -} |
| - |
| -// wEngineBoxRecheck (G4): shop's grant is revoked and read everywhere; box |
| -// 1's data directory is lost (a rebuilt box: no floor), and a bucket writer |
| -// at once replays revision 1, signed moments ago; box 1 accepts it, box 0's |
| -// floor refuses it; shop calls eng. |
| -func wEngineBoxRecheck(t *testing.T, w *world) { |
| - w.runningEngine(t) |
| - shop := w.armedShop(t) |
| - b1 := w.boxes[1] |
| - w.consoleRevoke(shopEng) |
| - w.pollAll() |
| - w.rebuild(b1) |
| - w.replay(1) |
| - w.pollAll() |
| - w.check() |
| - if !w.tableGrants(b1, shopEng) { |
| - t.Fatalf("witness: the rebuilt calling box does not hold the replayed grant: %s", w.mirrorsState()) |
| - } |
| - w.engineCall(b1, shop, false, "carlos", "shop", eng, "/") |
| - w.check() |
| -} |
| - |
| -// wExactRouteEngine (R4-2): shop holds engine site's grant and not eng's; |
| -// site's hostname is box 0's static row, whose path map sends /convert to |
| -// eng's route; shop calls site at /convert. |
| -func wExactRouteEngine(t *testing.T, w *world) { |
| - w.runningEngine(t) |
| - shop := w.armedShop(t) |
| - w.consoleGrant("acct/shop/" + site) |
| - w.consoleRevoke(shopEng) |
| - w.pollAll() |
| - w.check() |
| - w.engineCall(w.boxes[1], shop, false, "carlos", "shop", site, engSitePath) |
| - w.check() |
| -} |
| - |
| -// wFloorPersisted (R1-4): shop's grant is revoked and read everywhere; a |
| -// bucket writer at once replays revision 1 (signed moments ago), which both |
| -// floors refuse; both edges restart; each polls; shop calls eng. |
| -func wFloorPersisted(t *testing.T, w *world) { |
| - w.runningEngine(t) |
| - shop := w.armedShop(t) |
| - w.consoleRevoke(shopEng) |
| - w.pollAll() |
| - w.replay(1) |
| - w.pollAll() |
| - for _, b := range w.boxes { |
| - w.restartEdge(b) |
| - } |
| - w.pollAll() |
| - w.check() |
| - w.engineCall(w.boxes[1], shop, false, "carlos", "shop", eng, "/") |
| - w.check() |
| -} |
| - |
| -// wStaleClearsGrants (§6.4): the bucket is unreachable; shop's grant is |
| -// revoked; ten minutes pass with no good read; shop calls eng. |
| -func wStaleClearsGrants(t *testing.T, w *world) { |
| - w.runningEngine(t) |
| - shop := w.armedShop(t) |
| - w.setBucketDown(true) |
| - w.consoleRevoke(shopEng) |
| - w.advance(staleTicks) |
| - w.pollAll() |
| - w.check() |
| - w.engineCall(w.boxes[1], shop, false, "carlos", "shop", eng, "/") |
| - w.check() |
| -} |
| - |
| -// armedRefuses: box 1 is armed with shop's socket open; each kind of |
| -// unisolated launch is tried in turn. |
| -func armedRefuses(kinds ...string) func(*testing.T, *world) { |
| - return func(t *testing.T, w *world) { |
| - w.armedShop(t) |
| - b := w.boxes[1] |
| - for _, k := range kinds { |
| - ok := w.launchUnisolated(b, k) |
| - if ok && on("armed-refuses-unisolated") { |
| - t.Fatalf("witness: an armed box admitted a %s launch: %s", k, w.boxesState()) |
| - } |
| - w.check() |
| - } |
| - } |
| -} |
| - |
| -func wArmedRefusesUnisolated(t *testing.T, w *world) { armedRefuses("foreign", "worker")(t, w) } |
| -func wArmedRefusesWorker(t *testing.T, w *world) { armedRefuses("worker")(t, w) } |
| -func wArmedRefusesFlat(t *testing.T, w *world) { armedRefuses("flat")(t, w) } |
| - |
| -// wArmChecksBox (R5-2): an app's worker runs in carlos-exec@ on unarmed box |
| -// 1 beside nested shop; the operator arms box 1. |
| -func wArmChecksBox(t *testing.T, w *world) { |
| - b := w.boxes[1] |
| - b.Live["shop"], b.Good["shop"] = vPlain, vPlain |
| - w.launch(b, "shop", vPlain, "seed") |
| - if !w.launchUnisolated(b, "worker") { |
| - t.Fatalf("witness: a worker spawn on an unarmed box refused: %s", w.boxesState()) |
| - } |
| - w.check() |
| - ok := w.arm(b) |
| - if ok && on("arm-checks-box") { |
| - t.Fatalf("witness: arming a box with a running worker succeeded: %s", w.boxesState()) |
| - } |
| - w.check() |
| -} |
| - |
| -// TestResidualsAreCountedNotFailed: each of the spec's two stated residuals, |
| -// as a fixed scenario. With its flag off the scenario is a |
| -// violation (the sequence really breaks the invariant the residual |
| -// concedes); with the flag on the world records residual:<name> and no |
| -// violation. The default world never sets a flag (TestEngines asserts the |
| -// sweep records no residual). |
| -func TestResidualsAreCountedNotFailed(t *testing.T) { |
| - cases := []struct { |
| - name string |
| - set func(w *world) |
| - run func(t *testing.T, w *world) |
| - }{ |
| - {"unwrittenManifestAcrossUpgrade", func(w *world) { w.unwrittenManifestAcrossUpgrade = true }, residualUnwrittenManifest}, |
| - {"flatEraTamper", func(w *world) { w.flatEraTamper = true }, residualFlatEraTamper}, |
| - } |
| - for _, c := range cases { |
| - t.Run(c.name, func(t *testing.T) { |
| - off := newWitness() |
| - c.run(t, off) |
| - if len(off.violations) == 0 || len(off.residuals) > 0 { |
| - t.Errorf("flag off: want a violation and no residual, got violations %v residuals %v", off.violations, off.residuals) |
| - dump(t, off) |
| - } |
| - on := newWitness() |
| - c.set(on) |
| - c.run(t, on) |
| - if len(on.violations) > 0 || len(on.residuals) == 0 { |
| - t.Errorf("flag on: want residuals and no violation, got violations %v residuals %v", on.violations, on.residuals) |
| - dump(t, on) |
| - } |
| - for _, r := range on.residuals { |
| - if !strings.HasPrefix(r, "residual:"+c.name) { |
| - t.Errorf("flag on: residual %q is not residual:%s", r, c.name) |
| - } |
| - } |
| - }) |
| - } |
| -} |
| - |
| -// residualUnwrittenManifest (§5.1 "Classification before serving"): the |
| -// engine runs a declaring build whose staged manifest was never written; |
| -// an awake repoint moves its live link to a plain build without a restart; |
| -// the box takes the upgrade, which classifies the group 0 under the |
| -// running engine; a public request arrives. |
| -func residualUnwrittenManifest(t *testing.T, w *world) { |
| - b := w.boxes[0] |
| - b.Live[eng], b.Good[eng] = vUnreadable, vUnreadable |
| - if !w.launch(b, eng, vUnreadable, "seed") { |
| - t.Fatalf("scenario: the engine did not start: %s", w.boxesState()) |
| - } |
| - if !w.repointAwake(b, eng, vPlain) { |
| - t.Fatalf("scenario: the awake repoint refused: %s", w.boxesState()) |
| - } |
| - w.check() |
| - if w.residualAtUpgrade(b) == "" { |
| - t.Fatalf("scenario: the upgrade residual is not set up: %s", w.boxesState()) |
| - } |
| - w.upgrade(b) |
| - w.check() |
| - w.requestBy(b, engHost) |
| - w.check() |
| -} |
| - |
| -// residualFlatEraTamper (§6.2): a flat tenant on unarmed box 1 plants code |
| -// in shop's instance directory; the operator moves the flat route off and |
| -// arms the box (arming vouches for the present, not the past); shop's next |
| -// start runs the planted code in shop's slice, which calls eng. |
| -func residualFlatEraTamper(t *testing.T, w *world) { |
| - w.runningEngine(t) |
| - b := w.boxes[1] |
| - b.Live["shop"], b.Good["shop"] = vPlain, vPlain |
| - if !w.launchUnisolated(b, "flat") { |
| - t.Fatalf("scenario: a flat start on an unarmed box refused: %s", w.boxesState()) |
| - } |
| - w.tamper(b, w.newest(b, "flat"), "shop") |
| - w.moveToNested(b, "flat") |
| - if !w.arm(b) { |
| - t.Fatalf("scenario: arming refused after the flat route moved: %s", w.boxesState()) |
| - } |
| - if !w.launch(b, "shop", vPlain, "seed") { |
| - t.Fatalf("scenario: shop did not start: %s", w.boxesState()) |
| - } |
| - w.check() |
| - w.engineCall(b, w.newest(b, "shop"), false, "carlos", "shop", eng, "/") |
| - w.check() |
| -} |
| - |
| -// TestGrantedCallsReach is the positive control for the Task 5 witnesses, |
| -// which hold by refusing: with every rule on, a granted caller reaches the |
| -// engine through the socket (across a hop) and through the door from an |
| -// enrolled host-app uid (spec §8), and a revoke is in force once read. |
| -func TestGrantedCallsReach(t *testing.T) { |
| - w := newWitness() |
| - w.runningEngine(t) |
| - shop := w.armedShop(t) |
| - b1 := w.boxes[1] |
| - if !w.engineCall(b1, shop, false, "carlos", "shop", eng, "/") { |
| - t.Errorf("shop's own process through shop's socket did not reach eng") |
| - } |
| - user := &proc{Group: "shop", Slice: "user:u-shop"} |
| - if !w.engineCall(b1, user, true, "u-shop", "shop", eng, "/") { |
| - t.Errorf("the door from shop's enrolled uid with shop's key did not reach eng") |
| - } |
| - if w.engineCall(b1, user, true, "carlos", "shop", eng, "/") { |
| - t.Errorf("the same key from uid carlos reached eng") |
| - } |
| - w.consoleRevoke(shopEng) |
| - w.pollAll() |
| - if w.engineCall(b1, shop, false, "carlos", "shop", eng, "/") { |
| - t.Errorf("a revoke read by both boxes did not stop the call") |
| - } |
| - w.check() |
| - if len(w.violations) > 0 { |
| - t.Errorf("violations: %v", w.violations) |
| - } |
| - if t.Failed() { |
| - dump(t, w) |
| - } |
| -} |
| - |
| -// TestArmRefusesAndAdmits (spec §8): arming refuses a box with a flat |
| -// route, a foreign route, a route with workers, or a non-empty carlos-exec@ |
| -// cgroup; it succeeds on the engine's box (a unit-backed engine) and on a box |
| -// of nested callers; on an armed box every unisolated launch is refused |
| -// before a process starts; disarm closes the engine sockets, and then |
| -// launches resume. |
| -func TestArmRefusesAndAdmits(t *testing.T) { |
| - for _, kind := range unisolatedKinds { |
| - w := newWitness() |
| - b := w.boxes[1] |
| - w.launchUnisolated(b, kind) |
| - if w.arm(b) { |
| - t.Errorf("%s: arming succeeded with the %s tenant running", kind, kind) |
| - } |
| - w.stopGroup(b, kind) // the cgroup is empty; the route remains |
| - if w.arm(b) { |
| - t.Errorf("%s: arming succeeded with a %s route on the box", kind, kind) |
| - } |
| - w.moveToNested(b, kind) |
| - if !w.arm(b) { |
| - t.Errorf("%s: arming refused once the route moved to nested", kind) |
| - } |
| - } |
| - w := newWitness() |
| - w.runningEngine(t) |
| - if !w.arm(w.boxes[0]) { |
| - t.Errorf("arming the engine's box (unit-backed engine) refused") |
| - } |
| - w.armedShop(t) |
| - b := w.boxes[1] |
| - n := len(b.Procs) |
| - for _, kind := range unisolatedKinds { |
| - if w.launchUnisolated(b, kind) { |
| - t.Errorf("an armed box admitted a %s launch", kind) |
| - } |
| - } |
| - if len(b.Procs) != n { |
| - t.Errorf("a refused launch started a process: %d -> %d", n, len(b.Procs)) |
| - } |
| - w.disarm(b) |
| - if b.Sockets || b.Armed { |
| - t.Errorf("disarm left sockets %v armed %v", b.Sockets, b.Armed) |
| - } |
| - if !w.launchUnisolated(b, "worker") { |
| - t.Errorf("a worker spawn after disarm refused") |
| - } |
| - w.check() |
| - if len(w.violations) > 0 { |
| - t.Errorf("violations: %v", w.violations) |
| - } |
| - if t.Failed() { |
| - dump(t, w) |
| - } |
| -} |
| - |
| -// withMutation runs f with the mutation set m, restoring the previous set. |
| -func withMutation(m string, f func()) { |
| - saved := mutated |
| - mutated = m |
| - defer func() { mutated = saved }() |
| - f() |
| -} |
| - |
| -// TestExpiryKeepsRevokeAge: the grant oracle keeps expiry, staleness and |
| -// revoke age apart (final review, finding 4). With the table's own checks off |
| -// (stale-clears-grants and grant-freshness-bound), the edges keep serving a |
| -// cached grant, and the oracle alone decides: |
| -// - a key revoked long before the newest record expires is a violation by |
| -// its revoke's age, whatever the expiry; |
| -// - a key the newest record grants is a violation the moment that record |
| -// expires: an expired record admits nothing, with no grace; |
| -// - a key nobody revoked is a violation once the admitting box has had no |
| -// good read for ten minutes, whatever the revoke's age (there is none), |
| -// and not a tick earlier. |
| -func TestExpiryKeepsRevokeAge(t *testing.T) { |
| - withMutation("stale-clears-grants,grant-freshness-bound", func() { |
| - w := newWitness() |
| - w.runningEngine(t) |
| - shop := w.armedShop(t) |
| - w.setBucketDown(true) |
| - w.consoleRevoke(shopEng) // tick 0; revision 2, never read |
| - w.advance(lifetimeTicks) // revision 2 expires now |
| - w.engineCall(w.boxes[1], shop, false, "carlos", "shop", eng, "/") |
| - if len(w.violations) != 1 || invariantOf(w.violations[0]) != "INV-G" || !strings.Contains(w.violations[0], "since tick 0") { |
| - t.Errorf("a key revoked at tick 0, called across the record's expiry: want INV-G since tick 0, got %v", w.violations) |
| - dump(t, w) |
| - } |
| - |
| - w = newWitness() |
| - w.runningEngine(t) |
| - shop = w.armedShop(t) |
| - w.setBucketDown(true) |
| - w.advance(lifetimeTicks) // revision 1, which grants shop, expires now |
| - w.engineCall(w.boxes[1], shop, false, "carlos", "shop", eng, "/") |
| - if len(w.violations) != 1 || invariantOf(w.violations[0]) != "INV-G" || !strings.Contains(w.violations[0], "expired at 25920") { |
| - t.Errorf("a granted key at its record's expiry: want INV-G at once, naming the expiry, got %v", w.violations) |
| - dump(t, w) |
| - } |
| - |
| - w = newWitness() |
| - w.runningEngine(t) |
| - shop = w.armedShop(t) |
| - w.setBucketDown(true) |
| - w.advance(staleTicks - 1) // no good read for 59 ticks; shop still granted |
| - w.engineCall(w.boxes[1], shop, false, "carlos", "shop", eng, "/") |
| - if len(w.violations) != 0 { |
| - t.Errorf("a granted key 59 ticks after the last good read is within the bound: got %v", w.violations) |
| - dump(t, w) |
| - } |
| - w.advance(1) |
| - w.engineCall(w.boxes[1], shop, false, "carlos", "shop", eng, "/") |
| - if len(w.violations) != 1 || invariantOf(w.violations[0]) != "INV-G" || !strings.Contains(w.violations[0], "no good read") { |
| - t.Errorf("a granted key ten minutes after the last good read: want INV-G for the stale read, got %v", w.violations) |
| - dump(t, w) |
| - } |
| - }) |
| -} |
| - |
| -// upgradeResidualFixture is residualUnwrittenManifest up to the upgrade, |
| -// with the flag on: the residual is recorded and nothing violates. It |
| -// returns the engine's box and the tagged process. |
| -func upgradeResidualFixture(t *testing.T) (*world, *box, *proc) { |
| - w := newWitness() |
| - w.unwrittenManifestAcrossUpgrade = true |
| - b := w.boxes[0] |
| - b.Live[eng], b.Good[eng] = vUnreadable, vUnreadable |
| - w.launch(b, eng, vUnreadable, "seed") |
| - p := w.newest(b, eng) |
| - w.repointAwake(b, eng, vPlain) |
| - w.upgrade(b) |
| - w.check() |
| - if len(w.residuals) == 0 || len(w.violations) > 0 || p.Residual == "" { |
| - t.Fatalf("fixture: want the upgrade residual recorded on process %d, got residuals %v violations %v", p.ID, w.residuals, w.violations) |
| - } |
| - return w, b, p |
| -} |
| - |
| -// TestResidualCoversOnlyItsOwnBreaches: a process tagged with the |
| -// unwritten-manifest residual is not a licence. While its group is still |
| -// open, a breach by a path the upgrade's 0 did not open (a public connection |
| -// to a port the engine bound itself, through a broken firewall) is a |
| -// violation. Once the group is closed again the window has ended: a later 0 |
| -// written by a broken --public, under that same process, is a violation. |
| -func TestResidualCoversOnlyItsOwnBreaches(t *testing.T) { |
| - t.Run("another path", func(t *testing.T) { |
| - w, b, p := upgradeResidualFixture(t) |
| - withMutation("ingress-precondition", func() { |
| - w.bindOwnPort(b, p) |
| - w.directConnect(b, ownPort(p), true) |
| - }) |
| - w.check() |
| - if len(w.violations) != 1 || invariantOf(w.violations[0]) != "INV-P" { |
| - t.Errorf("want INV-P through the broken firewall, got violations %v residuals %v", w.violations, w.residuals) |
| - dump(t, w) |
| - } |
| - }) |
| - t.Run("after the window", func(t *testing.T) { |
| - w, b, p := upgradeResidualFixture(t) |
| - w.writeMark(b, eng, markInternal) // a gate's 1: the group is closed again |
| - w.reload(b) |
| - w.check() |
| - if p.Residual != "" || len(w.violations) > 0 { |
| - t.Fatalf("closing the group: want the window ended and no violation, got tag %q violations %v", p.Residual, w.violations) |
| - } |
| - withMutation("public-confirms-empty", func() { |
| - w.clearStopMisses = true |
| - w.operatorPublic(b, eng) // the stop misses process p; step 3 is gone |
| - w.reload(b) |
| - w.check() |
| - }) |
| - if len(w.violations) == 0 || invariantOf(w.violations[0]) != "INV-I1" { |
| - t.Errorf("a broken --public under the formerly tagged process: want INV-I1, got violations %v residuals %v", w.violations, w.residuals) |
| - dump(t, w) |
| - } |
| - }) |
| -} |
| - |
| -// flatEraFixture is residualFlatEraTamper's setup with the flag on, the |
| -// tamper planted in group target's instance directory instead of shop's: a |
| -// flat tenant on unarmed box 1 plants it, its route moves off, the box is |
| -// armed, and shop and other (a sibling instance) start. It returns box 1. |
| -func flatEraFixture(t *testing.T, target string) (*world, *box) { |
| - w := newWitness() |
| - w.flatEraTamper = true |
| - w.runningEngine(t) |
| - b := w.boxes[1] |
| - if !w.provision(b, "other", "acct/other", "127.0.0.1:9002", vPlain) { |
| - t.Fatalf("fixture: provisioning other refused: %s", w.boxesState()) |
| - } |
| - b.Live["shop"], b.Good["shop"] = vPlain, vPlain |
| - if !w.launchUnisolated(b, "flat") { |
| - t.Fatalf("fixture: a flat start on an unarmed box refused: %s", w.boxesState()) |
| - } |
| - w.tamper(b, w.newest(b, "flat"), target) |
| - w.moveToNested(b, "flat") |
| - if !w.arm(b) { |
| - t.Fatalf("fixture: arming refused after the flat route moved: %s", w.boxesState()) |
| - } |
| - for _, g := range []string{"shop", "other"} { |
| - w.stopGroup(b, g) |
| - if !w.launch(b, g, vPlain, "seed") { |
| - t.Fatalf("fixture: %s did not start: %s", g, w.boxesState()) |
| - } |
| - } |
| - w.check() |
| - if len(w.violations) > 0 { |
| - t.Fatalf("fixture: violations %v", w.violations) |
| - } |
| - return w, b |
| -} |
| - |
| -// TestFlatEraTamperKeepsUnrelatedViolations: the flat-era residual covers a |
| -// call whose recorded caller is the compromised instance itself, made by its |
| -// own process in its own slice (final review, finding 5). Combined with an |
| -// unrelated mutation, the unrelated breach stays a violation: |
| -// - cgroup-identity off: planted code in other borrows shop's engine |
| -// socket; the engine box records shop, which is not the compromised |
| -// instance; |
| -// - hop-caller-signed off: planted code in shop sends its own socket's call |
| -// with an X-Carlos-Hop-Caller naming another granted app, which the |
| -// engine box takes. |
| -// |
| -// And the positive control: planted code in shop calling through shop's own |
| -// socket is the residual, not a violation. |
| -func TestFlatEraTamperKeepsUnrelatedViolations(t *testing.T) { |
| - t.Run("own socket: the residual", func(t *testing.T) { |
| - w, b := flatEraFixture(t, "shop") |
| - w.engineCall(b, w.newest(b, "shop"), false, "carlos", "shop", eng, "/") |
| - w.check() |
| - if len(w.violations) > 0 || len(w.residuals) != 1 || !strings.HasPrefix(w.residuals[0], "residual:flatEraTamper:") { |
| - t.Errorf("want residual:flatEraTamper and no violation, got violations %v residuals %v", w.violations, w.residuals) |
| - dump(t, w) |
| - } |
| - }) |
| - t.Run("cgroup-identity off: a borrowed socket", func(t *testing.T) { |
| - w, b := flatEraFixture(t, "other") |
| - withMutation("cgroup-identity", func() { |
| - w.engineCall(b, w.newest(b, "other"), false, "carlos", "shop", eng, "/") |
| - }) |
| - w.check() |
| - if len(w.violations) != 1 || invariantOf(w.violations[0]) != "INV-ID" || len(w.residuals) > 0 { |
| - t.Errorf("want INV-ID and no residual, got violations %v residuals %v", w.violations, w.residuals) |
| - dump(t, w) |
| - } |
| - }) |
| - t.Run("hop-caller-signed off: a forged hop caller", func(t *testing.T) { |
| - w, b := flatEraFixture(t, "shop") |
| - w.consoleGrant("acct/tcp/" + eng) |
| - w.pollAll() |
| - forged := callerOf("acct/tcp", eng) |
| - withMutation("hop-caller-signed", func() { |
| - w.placeCall(call{from: b, p: w.newest(b, "shop"), uid: "carlos", host: "shop", engine: eng, path: "/", forged: &forged}) |
| - }) |
| - w.check() |
| - if len(w.violations) != 1 || invariantOf(w.violations[0]) != "INV-ID" || len(w.residuals) > 0 { |
| - t.Errorf("want INV-ID and no residual, got violations %v residuals %v", w.violations, w.residuals) |
| - dump(t, w) |
| - } |
| - }) |
| -} |
| - |
| -// TestWitnessesHoldUnmutated: every witness holds with every rule in place. |
| -// A witness that violates unmutated is a model bug, and a witness that |
| -// passes under its mutation for the wrong reason starts here (Review Focus 1). |
| -func TestWitnessesHoldUnmutated(t *testing.T) { |
| - saved := mutated |
| - mutated = "" |
| - defer func() { mutated = saved }() |
| - if len(witnesses) == 0 { |
| - t.Fatal("no witnesses") |
| - } |
| - for _, x := range witnesses { |
| - w := newWitness() |
| - x.run(t, w) |
| - if len(w.violations) > 0 { |
| - t.Errorf("witness %s (needs %q) violates with no mutation: %v", x.rule, x.needs, w.violations) |
| - dump(t, w) |
| - } |
| - } |
| -} |
| - |
| -// expectedOutcome is one line of expected-outcomes.txt: `rule missed reason` |
| -// or `rule rare N reason` (hostlife's format, read by mutate.sh). |
| -type expectedOutcome struct { |
| - rule, outcome string |
| - depth int |
| - reason string |
| -} |
| - |
| -func readExpectedOutcomes(t *testing.T) []expectedOutcome { |
| - t.Helper() |
| - data, err := os.ReadFile("expected-outcomes.txt") |
| - if err != nil { |
| - t.Fatalf("mutate.sh reads expected-outcomes.txt beside it: %v", err) |
| - } |
| - var out []expectedOutcome |
| - for i, line := range strings.Split(string(data), "\n") { |
| - if strings.HasPrefix(line, "#") || strings.TrimSpace(line) == "" { |
| - continue |
| - } |
| - f := strings.Fields(line) |
| - e := expectedOutcome{rule: f[0]} |
| - if len(f) > 1 { |
| - e.outcome = f[1] |
| - } |
| - rest := f[min(2, len(f)):] |
| - if e.outcome == "rare" { |
| - if len(f) < 3 { |
| - t.Errorf("expected-outcomes.txt:%d: rare needs a seed count: %q", i+1, line) |
| - continue |
| - } |
| - if _, err := fmt.Sscanf(f[2], "%d", &e.depth); err != nil || e.depth <= 0 { |
| - t.Errorf("expected-outcomes.txt:%d: rare needs a positive seed count: %q", i+1, line) |
| - } |
| - rest = f[3:] |
| - } |
| - e.reason = strings.Join(rest, " ") |
| - out = append(out, e) |
| - } |
| - return out |
| -} |
| - |
| -// TestEveryRuleHasWitness: each rule in allRules has a witness or a line in |
| -// expected-outcomes.txt that says why it has none or why it is not caught |
| -// alone; every line there is well formed and names a known rule; and a rule |
| -// listed `missed` has no witness that its mutation alone must violate (the |
| -// harness would report it STALE). |
| -func TestEveryRuleHasWitness(t *testing.T) { |
| - known := map[string]bool{} |
| - for _, r := range allRules { |
| - known[r] = true |
| - } |
| - expected := map[string]expectedOutcome{} |
| - for _, e := range readExpectedOutcomes(t) { |
| - if !known[e.rule] { |
| - t.Errorf("expected-outcomes.txt names unknown rule %q", e.rule) |
| - } |
| - if _, dup := expected[e.rule]; dup { |
| - t.Errorf("expected-outcomes.txt lists %q twice", e.rule) |
| - } |
| - if e.outcome != "missed" && e.outcome != "rare" { |
| - t.Errorf("expected-outcomes.txt: %s: outcome %q, want missed or rare N", e.rule, e.outcome) |
| - } |
| - if e.reason == "" { |
| - t.Errorf("expected-outcomes.txt: %s gives no reason", e.rule) |
| - } |
| - expected[e.rule] = e |
| - } |
| - witnessed := map[string]bool{} |
| - for _, x := range witnesses { |
| - witnessed[x.rule] = true |
| - if e, ok := expected[x.rule]; ok && e.outcome == "missed" && x.needs == x.rule { |
| - t.Errorf("%s is listed missed, but a witness must violate under its mutation alone", x.rule) |
| - } |
| - } |
| - for _, r := range allRules { |
| - if !witnessed[r] { |
| - if _, ok := expected[r]; !ok { |
| - t.Errorf("rule %q has neither a witness nor an expected-outcomes.txt line", r) |
| - } |
| - } |
| - } |
| -} |
diff --git a/internal/sim/engines/world_test.go b/internal/sim/engines/world_test.go| deleted file mode 100644 |
| index 69497a060..000000000 |
| --- a/internal/sim/engines/world_test.go |
| +++ /dev/null |
| @@ -1,370 +0,0 @@ |
| -package engines |
| - |
| -import ( |
| - "fmt" |
| - "math/rand" |
| - "sort" |
| -) |
| - |
| -// The model of the fleet-internal engines (spec |
| -// docs/superpowers/specs/2026-10-21-fleet-internal-engines-design.md). One |
| -// tick is 10 s: a step is a tick. Everything is decided from one seeded |
| -// source; nothing reads the clock, starts a goroutine or lets a map's |
| -// iteration order choose. |
| - |
| -const ( |
| - chaosSteps = 400 // faults and every action are eligible |
| - calmSteps = 200 // the same walk, then the final oracle |
| - nBuilds = 4 |
| -) |
| - |
| -// The starting world's names. |
| -const ( |
| - eng = "eng" // the engine group (its owner's host; engine names have no dot) |
| - engHost = "eng.acct.apps.example" |
| - engAlias = "docs.example" // alias row on box 0, to engHost |
| - engSite = "www.example" // static row on box 0, path map to engHost |
| - engSitePath = "/convert" |
| - shopAlias = "shop-alias.example" // alias row on box 1, to shop |
| - shopSite = "shop-www.example" // static row on box 1, path map to shop |
| - shopSitePath = "/app" |
| -) |
| - |
| -// build is a platform build: whether it declares the internal-engine |
| -// protocol, and whether the manifest it writes is in place. |
| -type build struct { |
| - Ver int |
| - Declares, ManifestOK bool |
| -} |
| - |
| -// proc is a running process. Slice is the cgroup the peer check reads: |
| -// inst:<group>, exec:<host> or unit:<host>. |
| -// |
| -// Code is the account/app whose code the process runs when that is not its |
| -// group's: code a flat-era tamper planted in the group's instance directory |
| -// (Task 5). Residual names the stated residual the process belongs to, if |
| -// any; a breach it causes is recorded as that residual, not a violation. |
| -type proc struct { |
| - ID int |
| - Group string |
| - Ver int |
| - Slice string |
| - Unisolated, OwnPort bool |
| - Code, Residual string |
| -} |
| - |
| -// row is a host row of a box's table. Kind is instance, service, static or |
| -// alias; Backend is a socket path or an address, "" for static and alias. |
| -// An alias row names its target host in Alias and copies its upstream |
| -// (edge.go:929); PathTo maps a path to the host that serves it (edge.go:1364). |
| -// |
| -// A platform-minted row (Platform) names in Source the host it was minted |
| -// from: the truth the oracle reads. Owner is what the registry has recorded |
| -// (routes.owner), "" for a row minted before owners were recorded; the edge |
| -// then finds the owner by App and backend (spec §5.1, "Platform-minted |
| -// rows"). App is the row's account/app. GrantAt is the registry change that |
| -// recorded the doc-engine grant. |
| -type row struct { |
| - Host, Kind, Owner, Backend string |
| - Platform, Grant bool |
| - PathTo map[string]string |
| - Alias string |
| - App, Source string |
| - GrantAt int |
| -} |
| - |
| -// mark is a row's exposure mark. |
| -type mark int |
| - |
| -const ( |
| - markNull mark = iota |
| - markPublic |
| - markInternal |
| -) |
| - |
| -func (m mark) String() string { |
| - switch m { |
| - case markPublic: |
| - return "public" |
| - case markInternal: |
| - return "internal" |
| - } |
| - return "null" |
| -} |
| - |
| -// caller names who a request is on behalf of. |
| -type caller struct{ Account, App, Engine string } |
| - |
| -// req is a request the box admitted. Row is the row whose mark admitted it; |
| -// Backend the proxy it holds from then on; Reached the process it was |
| -// delivered to (0 for none). |
| -type req struct { |
| - ID, Epoch int |
| - Row, Backend string |
| - Public bool |
| - Caller *caller |
| - Held bool |
| - Box, Reached int |
| -} |
| - |
| -// box is one host of the fleet: box 0 is the engine's home, box 1 a calling |
| -// box. |
| -// |
| -// Rows and Mark are the registry (the intent). EdgeRows and Serving are the |
| -// edge's in-memory map, swapped in only by a successful reload. Wrote counts |
| -// registry mark changes, Fenced is the change the edge has fenced, SetAt the |
| -// change that last closed a group (its fence generation; a group with no key |
| -// has never been fenced closed, spec §5.1, "Setting the mark"). |
| -type box struct { |
| - ID int |
| - Rows map[string]*row |
| - Mark map[string]mark |
| - Wrote, Fenced, Epoch int |
| - ReloadFails, Armed bool |
| - Locked map[string]bool // the group's lock, held by --public for its whole run |
| - Live, Good map[string]int |
| - Staged map[string][]int |
| - Procs []*proc |
| - Admitted []*req |
| - |
| - EdgeRows map[string]row |
| - Serving map[string]mark |
| - SetAt map[string]int |
| - |
| - // PortGrant is the operator's ports grant by group (the port); Listen the |
| - // ListenStream sockets the capability pass has rendered, port to group |
| - // (spec §5.1, "The edge is the only ingress"). |
| - PortGrant, Listen map[string]string |
| - |
| - // Task 5 (calls_test.go). Mirror is the edge's grant mirror (spec §5.3). |
| - // Armed is `carlos engines arm`; Sockets is whether the edge's listener |
| - // manager has the engine sockets open (§5.4, §6.2). Unisolated is every |
| - // route on the box whose tenant code runs outside an instance slice, by |
| - // kind (flat, foreign, worker). Tampered is a nested group's instance |
| - // directory written by an unisolated tenant: the planter's app. |
| - // |
| - // ReadRev is the oracle's, not the protocol's: the highest revision the |
| - // box's mirror has read since it was last rebuilt (a restart keeps it), so |
| - // INV-G can hold a revoke the box has read in force (§6.4). |
| - Mirror mirror |
| - Sockets bool |
| - Unisolated map[string]bool |
| - Tampered map[string]string |
| - ReadRev int |
| -} |
| - |
| -type world struct { |
| - seed int64 |
| - rng *rand.Rand |
| - boxes []*box |
| - builds map[int]build |
| - step int |
| - trace []string |
| - violations []string |
| - residuals []string |
| - stats map[string]int // actions selected, by name |
| - done map[string]int // actions whose transition completed, by name |
| - events map[string]int // deliveries: public requests and engine calls that reached a process |
| - nextID int // process and request ids |
| - |
| - // clearHook, when set, runs inside operatorPublic at each stage |
| - // ("locked": step 1 passed; "stopped": step 2 done; "confirmed": step 3 |
| - // passed, before the write of 0), so a scenario or the walk can |
| - // interleave there. |
| - clearHook func(b *box, g, stage string) |
| - // clearStopMisses, when set, makes operatorPublic's stop leave one |
| - // process of the group behind (a unit or generation whose stop the |
| - // activator or control service failed to complete). |
| - clearStopMisses bool |
| - |
| - // Task 5 (calls_test.go): the console's engines record and the bucket |
| - // that carries it; skew is time that passed without a step (a |
| - // fast-forward), so now() is step+skew. |
| - console engConsole |
| - skew int |
| - |
| - // The spec's two stated residuals. Off by default and set only by tests: |
| - // with one on, the walk may generate its sequence, and the breach it |
| - // causes is recorded in residuals as residual:<name>, never in |
| - // violations. (A fresh box's replay was a third until ruling R5 bounded |
| - // it by the freshness bound; INV-G now covers it.) |
| - unwrittenManifestAcrossUpgrade, flatEraTamper bool |
| - |
| - verbose bool |
| -} |
| - |
| -// action is one thing the random walk can do. Tasks 2 to 5 append theirs |
| -// from their own files' init; the walk picks among them by weight. |
| -// |
| -// run reports whether the transition completed: false when the action found |
| -// nothing to act on (no group, no held request, a full table) and returned |
| -// without calling into the model. A refusal by the protocol is a completed |
| -// transition. The walk counts selections (stats) and completions (done) |
| -// apart, so coverage can be checked on what really ran. |
| -type action struct { |
| - name string |
| - weight int |
| - run func(*world) bool |
| -} |
| - |
| -var actions []action |
| - |
| -// stepHooks run at the start of every step, before its action: what happens |
| -// on a timer whatever the walk chooses (Task 5: the mirror's poll). |
| -var stepHooks []func(*world) |
| - |
| -func newWorld(seed int64, verbose bool) *world { |
| - w := &world{ |
| - seed: seed, |
| - rng: rand.New(rand.NewSource(seed)), |
| - builds: map[int]build{}, |
| - stats: map[string]int{}, |
| - done: map[string]int{}, |
| - events: map[string]int{}, |
| - verbose: verbose, |
| - } |
| - newBox := func(id int) *box { |
| - return &box{ID: id, Rows: map[string]*row{}, Mark: map[string]mark{}, Live: map[string]int{}, Good: map[string]int{}, Staged: map[string][]int{}, |
| - EdgeRows: map[string]row{}, Serving: map[string]mark{}, SetAt: map[string]int{}, |
| - PortGrant: map[string]string{}, Listen: map[string]string{}, Locked: map[string]bool{}, |
| - Unisolated: map[string]bool{}, Tampered: map[string]string{}} |
| - } |
| - home, calling := newBox(0), newBox(1) |
| - w.boxes = []*box{home, calling} |
| - |
| - // one engine group, eng: its own route and its minted platform row |
| - home.Rows[eng] = &row{Host: eng, Kind: "instance", App: "acct/eng", Backend: "/run/carlos/eng.sock", PathTo: map[string]string{}} |
| - home.Rows[engHost] = &row{Host: engHost, Kind: "instance", App: "acct/eng", Owner: eng, Source: eng, Backend: "/run/carlos/eng.sock", Platform: true, PathTo: map[string]string{}} |
| - home.Mark[eng], home.Mark[engHost] = markInternal, markInternal |
| - home.SetAt[eng] = 0 // closed from the start, and loaded below |
| - // one public app group, shop, on the calling box |
| - calling.Rows["shop"] = &row{Host: "shop", Kind: "instance", App: "acct/shop", Backend: "127.0.0.1:9001", PathTo: map[string]string{}} |
| - calling.Mark["shop"] = markPublic |
| - // on each box an alias row and a static row with a path map, both |
| - // resolving to the box's group: rows of kinds that serve no release, 0 |
| - // by construction (spec §5.1, "What the edge does with it") |
| - for _, x := range []struct { |
| - b *box |
| - alias, site, path, to string |
| - }{{home, engAlias, engSite, engSitePath, engHost}, {calling, shopAlias, shopSite, shopSitePath, "shop"}} { |
| - x.b.Rows[x.alias] = &row{Host: x.alias, Kind: "alias", Alias: x.to, PathTo: map[string]string{}} |
| - x.b.Rows[x.site] = &row{Host: x.site, Kind: "static", PathTo: map[string]string{x.path: x.to}} |
| - x.b.Mark[x.alias], x.b.Mark[x.site] = markPublic, markPublic |
| - } |
| - // the edges start with the registry loaded |
| - for _, b := range w.boxes { |
| - b.loadEdge() |
| - } |
| - w.initEngines() // the console's first record, read by every edge |
| - |
| - for v := 1; v <= nBuilds; v++ { |
| - w.builds[v] = build{Ver: v, Declares: w.rng.Intn(2) == 0, ManifestOK: w.rng.Intn(2) == 0} |
| - } |
| - w.logf("world seed %d: builds %s", seed, w.buildsString()) |
| - return w |
| -} |
| - |
| -func (w *world) buildsString() string { |
| - var out []string |
| - for v := 1; v <= nBuilds; v++ { |
| - b := w.builds[v] |
| - out = append(out, fmt.Sprintf("%d{declares=%v manifest=%v}", v, b.Declares, b.ManifestOK)) |
| - } |
| - return fmt.Sprint(out) |
| -} |
| - |
| -// logf appends a trace line. The trace is always kept: it is what the |
| -// determinism test compares, and what ENGINESIM_SEED prints. |
| -func (w *world) logf(format string, args ...any) { |
| - w.trace = append(w.trace, fmt.Sprintf("[%d] ", w.step)+fmt.Sprintf(format, args...)) |
| -} |
| - |
| -// calm is true once the chaos steps are over. doStep counts the step before |
| -// it runs the action, so steps 1 to chaosSteps are chaos and the rest calm. |
| -func (w *world) calm() bool { return w.step > chaosSteps } |
| - |
| -// group is a row's group key: its owner for a minted instance row whose |
| -// owner the registry can find, else its own host (spec §5.1, |
| -// "Platform-minted rows"; resolveOwner). |
| -func (w *world) group(b *box, host string) string { |
| - if r := b.Rows[host]; r != nil && followsOwner(r) { |
| - if o, ok := b.resolveOwner(r); ok { |
| - return o |
| - } |
| - } |
| - return host |
| -} |
| - |
| -// pick chooses one registered action by weight. The registry is sorted by |
| -// name first, so the order files' init functions ran in never matters. |
| -func (w *world) pick() *action { |
| - sorted := make([]action, 0, len(actions)) |
| - total := 0 |
| - for _, a := range actions { |
| - if a.weight > 0 { |
| - sorted = append(sorted, a) |
| - total += a.weight |
| - } |
| - } |
| - if total == 0 { |
| - return nil |
| - } |
| - sort.SliceStable(sorted, func(i, j int) bool { return sorted[i].name < sorted[j].name }) |
| - n := w.rng.Intn(total) |
| - for i := range sorted { |
| - if n < sorted[i].weight { |
| - return &sorted[i] |
| - } |
| - n -= sorted[i].weight |
| - } |
| - return nil |
| -} |
| - |
| -// doStep advances one tick: it counts the step, runs one chosen action and |
| -// counts it under its name, in stats when chosen and in done when its |
| -// transition completed. |
| -func (w *world) doStep() { |
| - w.step++ |
| - for _, h := range stepHooks { |
| - h(w) |
| - } |
| - a := w.pick() |
| - if a == nil { |
| - if w.verbose { |
| - w.logf("idle") |
| - } |
| - return |
| - } |
| - w.stats[a.name]++ |
| - w.logf("action %s", a.name) // always traced: the determinism test compares the action sequence |
| - if a.run(w) { |
| - w.done[a.name]++ |
| - } |
| - w.check() |
| -} |
| - |
| -// final is the end-of-run oracle: what must hold once the calm steps are |
| -// over. Later tasks add their end-state checks here. |
| -// |
| -// The faults are over: every edge's reload works again, and each edge polls |
| -// once, so every row has had its chance to answer. Then INV-AV. |
| -func (w *world) final() { |
| - for _, b := range w.boxes { |
| - if b.ReloadFails { |
| - b.ReloadFails = false |
| - w.logf("box%d: final: the reload fault has cleared", b.ID) |
| - } |
| - w.reload(b) |
| - } |
| - w.checkAV() |
| - w.logf("final: %d steps, %d violations, %d residuals", w.step, len(w.violations), len(w.residuals)) |
| -} |
| - |
| -func runSeed(seed int64, verbose bool) *world { |
| - w := newWorld(seed, verbose) |
| - for i := 0; i < chaosSteps+calmSteps; i++ { |
| - w.doStep() |
| - } |
| - w.final() |
| - return w |
| -} |
diff --git a/internal/sim/regionha/mutate.sh b/internal/sim/regionha/mutate.sh| index e7001fd3e..43e74e309 100755 |
| --- a/internal/sim/regionha/mutate.sh |
| +++ b/internal/sim/regionha/mutate.sh |
| @@ -1,8 +1,7 @@ |
| #!/bin/bash |
| -# Mutation checks for the region HA model (plan Task 14), in the engines |
| -# model's shape (internal/sim/engines/mutate.sh): build the test binary |
| -# once, then run it once per rule with RHASIM_MUTATE set. The sweep never |
| -# copies or edits the source. |
| +# Mutation checks for the region HA model (plan Task 14): build the test |
| +# binary once, then run it once per rule with RHASIM_MUTATE set. The sweep |
| +# never copies or edits the source. |
| # |
| # The first argument is the test binary (pre-flight ruling S14); its |
| # directory holds the scratch. Build it, run the sweep, remove the one |
diff --git a/internal/sim/regionha/witness_test.go b/internal/sim/regionha/witness_test.go| index b5550c104..cf8937be0 100644 |
| --- a/internal/sim/regionha/witness_test.go |
| +++ b/internal/sim/regionha/witness_test.go |
| @@ -18,8 +18,7 @@ import ( |
| "github.com/carlosframework/platform/internal/hafresh" |
| ) |
| -// Witness scenarios, in the engines model's shape |
| -// (internal/sim/engines/witness_test.go). |
| +// Witness scenarios for the region HA model. |
| // |
| // The random sweep reaches some interleavings rarely. A witness is one |
| // fixed, hand-scheduled scenario for one rule: it forces exactly the |
diff --git a/internal/svcrole/svcrole.go b/internal/svcrole/svcrole.go| index de316d06b..b4af58747 100644 |
| --- a/internal/svcrole/svcrole.go |
| +++ b/internal/svcrole/svcrole.go |
| @@ -46,8 +46,9 @@ const ( |
| Operate Role = "operate" |
| // Service is an app calling a platform SERVICE at runtime — work the |
| // platform performs for the app, on the app's own data, that costs the |
| - // deployment resources. Scanning an object is the first; PDF rendering is |
| - // the next. |
| + // deployment resources. Scanning an object and PDF rendering use Service |
| + // doors. PDF rendering uses POST /api/cli/apps/{account}/{app}/pdf/... |
| + // and is configured by CARLOS_PDF_ADDR, with no system record. |
| // |
| // It is deliberately NOT Instance. That role is defined by observation of |
| // its call sites rather than by its name, and a token minted to read logs |