carlos / platform Public

scripts: G2 fixture review fixes (wake-time replication, host pin)

claude agent, operated by paul@keymail.dev 72a0efae17d73dc9ba888c0868b4ddaf49bd978a parent e313a15
3 files changed, +140 −13
  • scripts/region-ha-g2/FIXTURES.md +21 −7
  • scripts/region-ha-g2/fixture/main.go +39 −5
  • scripts/region-ha-g2/fixture/main_test.go +80 −1

Intent

Human

<task-notification> <task-id>bg1g8xmn5</task-id> <tool-use-id>toolu_018CE7YfiQjymfuMk5tyWRBu</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/dc71bafb-7376-4e4b-a855-4d32f1eed771/tasks/bg1g8xmn5.output</output-file> <status>completed</status> <summary>Background command "Wait for Task 5 fix round" completed (exit code 0)</summary> </task-notification>

Human

<task-notification> <task-id>a05232310b616586c</task-id> <tool-use-id>toolu_01RXNxDNKDTLdCEL2VfyVMAR</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/dc71bafb-7376-4e4b-a855-4d32f1eed771/tasks/a05232310b616586c.output</output-file> <status>completed</status> <summary>Agent "Opus task review of Task 5" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>Fix round 1 (e313a157) passes: spec ✅, task quality Approved. The 33 offline tests pass. - **C1 ADDRESSED.** `--aws-region` now goes only to the runner (`pool-readiness.py:63`, `:346`). `--placement` filters records (`:272`, `:322`), and its validator refuses AWS-region-shaped values (`:310-320`). - **Home "" rule:** it is not literally the console's `haRegion`, but it selects the same records. Every create door turns the home code into "" before storing the record (`homePlacementCode` at `apiinstancemove.go:336`, used for instances and sidecars). So an exact match with `--placement ''`, plus an omitted region counting as "", picks up every home record those doors write. - **I1 ADDRESSED** (`:392`). No matching hosts now gives `no_hosts`, the summary is unknown, and `--strict` returns 1. - **M1 ADDRESSED** (`:238`). The LIST now uses `&lt;host&gt;/000` with one key per page. That prefix covers every Litestream level, `0000/` to `0009/`, and leaves out `files/`, the lock and the old `ltx/`. Claim-generation keys under `g-*/` were never matched and still read as `no_replica`, which is the safe direction. - **M2 ADDRESSED** (`:372-374`), **M4 ADDRESSED** (`:144`, `:259`), **M5 ADDRESSED** (`:210-212`). The report is right that version 1 is enforced at `rootrecord.go:78`, not in DecodeRecord; my citation was off. - **New Critical or Important:** none. - **New Minor M7:** a record that stored the home code literally would be skipped silently on a `--placement ''` run. An optional `--home-code` would close that. It is not blocking, since the doors never store it that way. I appended the re-review to `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-g2-prep/.superpowers/sdd/2026-11-05-region-ha-g2-prep/task-5-review.md`.</result> <usage><subagent_tokens>140461</subagent_tokens><tool_uses>6</tool_uses><duration_ms>56066</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>a02f83ae024fee9f0</task-id> <tool-use-id>toolu_01D19uEhsxRgq7GbKfCj9mHj</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/dc71bafb-7376-4e4b-a855-4d32f1eed771/tasks/a02f83ae024fee9f0.output</output-file> <status>completed</status> <summary>Agent "Opus task review of Task 7" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>**Spec verdict:** ❌ One gap, in the docs only. The fixture code meets the brief. FIXTURES.md, the guide for setting up the drill window, leaves out that a replication class change only takes effect when the instance next wakes. Not checkable from the diff: Tasks 6 and 8 reading the constants, and live behaviour on a box. **Quality verdict:** Needs fixes. It is the one doc step; the rest are minors. The fixture tests pass (`go test ./scripts/region-ha-g2/fixture -count=1`, 6.99 s). What I checked: - **Durable ack:** The ack is only sent after `tx.Commit()` returns. I checked with a throwaway program in `$TMPDIR`, since deleted: the SQLite driver defaults `synchronous` to FULL (2) in WAL mode, so a committed write is on disk before the reply. Writes that are acknowledged and then lost can only be lost to replication lag, which is what the drill measures. - **Activator contract:** It matches. The activator starts the app with `--socket` and `--db`, probes readiness with `GET /` over the socket, and passes stdout through to the journal. - **`/fetch`:** It always dials `G2_HAIRPIN_ADDR`, ignores proxy settings, follows no redirects and verifies TLS. - **CLI steps:** Every command and flag in FIXTURES.md exists as written, and the S3 record path is correct. - **`REPL` column:** The concern in the report is correct. The box-local `carlos instances` labels the column `REPL` (cli.go:660). **Critical:** none. **Important:** - FIXTURES.md:63-71 does not say the class takes effect only at the next wake (cli.go:2088-2092). An instance that is already awake keeps its old sync interval until it sleeps and wakes, while `REPL` already shows the new class. The `batched` and `daily` drills could then quietly measure the default interval. The step should make the class take effect (set it before the first wake, or force a sleep and wake), and should say the route must hibernate. **Minor:** 1. `synchronous` is not set in the code, so FULL comes from the driver default. Pin `synchronous(FULL)`, and say in the doc that a 200 means committed locally, not replicated. 2. `/fetch` takes its Host and SNI from the request. It is not an open proxy, but anyone who reaches the fixture under another hostname can make the box probe any host the NLB serves. Pin the allowed Host or document that the edge only delivers the fixture's own name. 3. `rid` copies `X-Request-Id` verbatim. Spaces in it break the key=value parsing for Tasks 6 and 8. 4. Signed-in `carlos routes` does have a `REPLICATION` column (routes_cli.go:61), so the doc's line about the brief's wording is half right. Say the box-local `REPL` readback is the evidence to keep. 5. The activator's readiness probes will log `host=carlos path=/`. Task 8 should filter them out. 6. TLS alert errors are classed as `connect` rather than `tls`. 7. Endpoints are matched in two separate switches, and `CloseIdleConnections` is redundant. The full review is in `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-g2-prep/.superpowers/sdd/2026-11-05-region-ha-g2-prep/task-7-review.md`.</result> <usage><subagent_tokens>94978</subagent_tokens><tool_uses>19</tool_uses><duration_ms>185912</duration_ms></usage> </task-notification>

Attributed to this commit: 23.0 g CO₂e (2,881,689 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on region-ha-g2-prep, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

diff --git a/scripts/region-ha-g2/FIXTURES.md b/scripts/region-ha-g2/FIXTURES.md
index 2678b5722..721a143bb 100644
--- a/scripts/region-ha-g2/FIXTURES.md
+++ b/scripts/region-ha-g2/FIXTURES.md
@@ -6,7 +6,7 @@ Tasks 6 and 8 parse these formats. The exported constants in `fixture/main.go` d
| Constant | Body or log line, before the final LF. |
| --- | --- |
-| `ResponseFormat` | `g2fixture box=<hostname> hits=<count> max=<max n> rid=<X-Request-Id or ->` |
+| `ResponseFormat` | `g2fixture box=<hostname> hits=<count> max=<max n> rid=<rid>` |
| `RangesFormat` | Comma-separated inclusive ranges, such as `1-120,125-300`. A single number has no hyphen. An empty database gives only LF. |
| `FetchFormat` | `fetch status=<code> ms=<n>` |
| `FetchErrorFormat` | `fetch error=<class>` |
@@ -16,8 +16,13 @@ Tasks 6 and 8 parse these formats. The exported constants in `fixture/main.go` d
| `DatabaseErrorBody` | `database error.` |
| `NotFoundBody` | `not found.` |
| `MethodNotAllowedBody` | `method not allowed.` |
+| `MisdirectedBody` | `misdirected request.` |
-`POST /write?n=<int>` inserts a positive decimal integer of at most 9223372036854775807. A duplicate is ignored. A 200 response follows a successful commit. `GET /` reports the same database count and maximum without writing. An empty database reports `hits=0 max=0`. `box` is the operating system hostname, and `rid` echoes `X-Request-Id`, or `-` when absent. Invalid numbers return 400. Database failures return 500 without `hits=`. `GET /ranges` reports the stored numbers in ascending order. Responses use `Cache-Control: no-store`.
+`POST /write?n=<int>` inserts a positive decimal integer of at most 9223372036854775807. A duplicate is ignored. A 200 write response means the write committed locally and the WAL was fsynced. It does not mean the write was replicated. `GET /` reports the same database count and maximum without writing. An empty database reports `hits=0 max=0`. `box` is the operating system hostname. In both the body and log, `rid` keeps only `[A-Za-z0-9._:-]` from `X-Request-Id`, then truncates to 64 characters. An empty result becomes `-`. Invalid numbers return 400. Database failures return 500 without `hits=`. `GET /ranges` reports the stored numbers in ascending order. Responses use `Cache-Control: no-store`.
+
+Set `G2_FIXTURE_HOSTS` to the fixture's own hostname. This optional comma-separated list matches the request Host exactly, including any port. Spaces around list entries are ignored. When configured, every request with an unlisted Host returns 421. This includes `/fetch`, which refuses before making an outgoing request. When unset, all Hosts are accepted.
+
+The activator's readiness probe logs `host=carlos path=/` on wake. With the host list set to the fixture's hostname, this probe gets 421, which the activator accepts because it is below 500. Evidence consumers must match on the fixture host so readiness probes do not enter the drill evidence.
`GET /fetch` makes an HTTPS GET of `/` on the incoming Host, with that hostname as TLS Server Name Indication (SNI). A Host port is retained in the URL and removed from SNI. The connection goes only to `G2_HAIRPIN_ADDR`, with no proxy or redirect following and a five-second timeout. TLS certificates must validate against the system trust store. The outer response is 200 when an HTTP response arrives, including a redirect; `status` is that response's code and `ms` is elapsed whole milliseconds. An unset address returns 503. A request failure returns 502 with class `timeout`, `tls`, `connect` or `request`. `request` means the URL could not be built; other transport failures use `connect`. No error body contains raw network errors.
@@ -25,7 +30,7 @@ Tasks 6 and 8 parse these formats. The exported constants in `fixture/main.go` d
These commands are for the approved drill window. The build task does not run them. Replace all angle-bracket placeholders. Use the window's console and account, configured so new instances land in `<pool>` in `<region>`. Signed-in `instances enable` cannot set the pool. Confirm that placement before creating fixtures.
-Build the binary from the repository root. The activator supplies `--socket <socket>` and `--db <database>` when it starts the app. The database uses SQLite WAL and a 5000 ms busy timeout.
+Build the binary from the repository root. The activator supplies `--socket <socket>` and `--db <database>` when it starts the app. The database uses SQLite WAL, explicit `synchronous(FULL)` and a 5000 ms busy timeout.
```sh
GOOS=linux GOARCH=arm64 CGO_ENABLED=0 go build -o <binary> ./scripts/region-ha-g2/fixture
@@ -43,6 +48,7 @@ Create a separate app for each label below. Set `<app>` to the chosen app identi
```sh
carlos apps create --app <app> --region <region>
carlos instances enable --app <app> --channel edge
+carlos env set --app <app> G2_FIXTURE_HOSTS=<label>.<domain>
carlos deploy --app <app> --version <v> --channel edge <binary>
carlos instances create --app <app> --host <label>.<domain> --channel edge
carlos instances list --app <app>
@@ -54,18 +60,26 @@ Read back each persisted instance record using the window's operator credentials
aws --profile <profile> --region <aws-region> s3 cp s3://<control-bucket>/apps/<account-id>/<app>/instances/<label>.<domain>.json <record.json>
```
-For the hairpin app, set the selected Network Load Balancer (NLB) address and restart the instance so it receives the environment value. If its egress policy restricts private addresses, the window must already allow this destination.
+For the hairpin app, set the selected Network Load Balancer (NLB) address before its first wake. If its egress policy restricts private addresses, the window must already allow this destination.
```sh
carlos env set --app <app> G2_HAIRPIN_ADDR=<nlb-ip>:443
-carlos restart --app <app>
```
-On every serving box, open the window's approved Systems Manager (SSM) session and run the following commands with `<h>` set to the fixture's full hostname. Set `<class>` from the table. Read the class back in the replication column of `carlos instances` on that box. The current CLI labels it `REPL`; the drill brief calls it `REPLICATION`.
+The route must hibernate and have a database path. The replication class takes effect only at the instance's next wake. Set it on every serving box before the fixture's first wake, and on every replacement before it can serve. Keep requests away from the fixture until this setup is complete.
+
+On each box, open the window's approved Systems Manager (SSM) session and run the following command with `<h>` set to the fixture's full hostname. Set `<class>` from the table.
```sh
carlos route --host <h> --replication <class>
+```
+
+If the fixture is already awake, sleep it through the API after setting the class. Wait until it is asleep, then wake it again with a request to its own hostname. This also loads the configured environment. An awake instance keeps its old replication interval until it sleeps and wakes.
+
+After the wake, run box-local `carlos instances` on every serving box and save the `REPL` column readback as evidence. `REPL` contains the registry setting, so the readback alone does not prove that an already running instance adopted the interval. Keep the sleep and wake evidence with it. Signed-in `carlos routes` has a `REPLICATION` column, but that console view is not per-box proof.
+
+```sh
carlos instances
```
-Repeat this on every replacement before each drill. `carlos route --replication` edits only the box where it runs. Instance records do not carry the class, so setting it on one box does not configure the others. Save each readback with the evidence and stop the drill if any serving box has the wrong class.
+Repeat the setup on every replacement before it can serve and before each drill. `carlos route --replication` edits only the box where it runs. Instance records do not carry the class, so setting it on one box does not configure the others. Stop the drill if any serving box has the wrong class or has not woken since the class was set.
diff --git a/scripts/region-ha-g2/fixture/main.go b/scripts/region-ha-g2/fixture/main.go
index cc025f5a8..14528f906 100644
--- a/scripts/region-ha-g2/fixture/main.go
+++ b/scripts/region-ha-g2/fixture/main.go
@@ -22,6 +22,8 @@ import (
// These formats are shared with the G2 evidence collectors. Bodies end in LF;
// the logger supplies the log line's LF without a timestamp or prefix.
+// ResponseFormat and LogFormat use a rid containing only [A-Za-z0-9._:-],
+// truncated to 64 characters after filtering, with "-" for an empty result.
const (
ResponseFormat = "g2fixture box=%s hits=%d max=%d rid=%s\n"
RangesFormat = "%s\n"
@@ -33,6 +35,7 @@ const (
DatabaseErrorBody = "database error.\n"
NotFoundBody = "not found.\n"
MethodNotAllowedBody = "method not allowed.\n"
+ MisdirectedBody = "misdirected request.\n"
)
type fixture struct {
@@ -47,6 +50,7 @@ func openDB(path string) (*sql.DB, error) {
q := u.Query()
// DSN pragmas apply again if database/sql replaces a connection.
q.Add("_pragma", "journal_mode(WAL)")
+ q.Add("_pragma", "synchronous(FULL)")
q.Add("_pragma", "busy_timeout(5000)")
u.RawQuery = q.Encode()
db, err := sql.Open("sqlite", u.String())
@@ -62,10 +66,7 @@ func openDB(path string) (*sql.DB, error) {
}
func (f *fixture) ServeHTTP(w http.ResponseWriter, r *http.Request) {
- rid := r.Header.Get("X-Request-Id")
- if rid == "" {
- rid = "-"
- }
+ rid := requestID(r.Header.Get("X-Request-Id"))
status, body := f.response(r, rid)
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.Header().Set("Cache-Control", "no-store")
@@ -74,7 +75,39 @@ func (f *fixture) ServeHTTP(w http.ResponseWriter, r *http.Request) {
f.logger.Printf(LogFormat, status, r.Host, r.URL.Path, rid)
}
+func requestID(raw string) string {
+ var id strings.Builder
+ for _, c := range raw {
+ if c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || strings.ContainsRune("._:-", c) {
+ id.WriteByte(byte(c))
+ if id.Len() == 64 {
+ break
+ }
+ }
+ }
+ if id.Len() == 0 {
+ return "-"
+ }
+ return id.String()
+}
+
+func allowedHost(host string) bool {
+ hosts := os.Getenv("G2_FIXTURE_HOSTS")
+ if hosts == "" {
+ return true
+ }
+ for _, allowed := range strings.Split(hosts, ",") {
+ if host != "" && host == strings.TrimSpace(allowed) {
+ return true
+ }
+ }
+ return false
+}
+
func (f *fixture) response(r *http.Request, rid string) (int, string) {
+ if !allowedHost(r.Host) {
+ return http.StatusMisdirectedRequest, MisdirectedBody
+ }
method := "GET"
switch r.URL.Path {
case "/write":
@@ -215,10 +248,11 @@ func fetchError(err error) string {
var netErr net.Error
var certErr *tls.CertificateVerificationError
var recordErr tls.RecordHeaderError
+ var alertErr tls.AlertError
switch {
case errors.As(err, &netErr) && netErr.Timeout():
return "timeout"
- case errors.As(err, &certErr), errors.As(err, &recordErr):
+ case errors.As(err, &certErr), errors.As(err, &recordErr), errors.As(err, &alertErr):
return "tls"
default:
return "connect"
diff --git a/scripts/region-ha-g2/fixture/main_test.go b/scripts/region-ha-g2/fixture/main_test.go
index 5bf22c0ed..4d6f1fb65 100644
--- a/scripts/region-ha-g2/fixture/main_test.go
+++ b/scripts/region-ha-g2/fixture/main_test.go
@@ -18,6 +18,7 @@ import (
func testFixture(t *testing.T) (*fixture, *bytes.Buffer) {
t.Helper()
+ t.Setenv("G2_FIXTURE_HOSTS", "")
db, err := openDB(filepath.Join(t.TempDir(), "fixture.db"))
if err != nil {
t.Fatal(err)
@@ -54,7 +55,7 @@ func TestFixtureWriteReadDuplicate(t *testing.T) {
}
}
var box, at, mode string
- var timeout int
+ var timeout, synchronous int
if err := f.db.QueryRow("SELECT box, at FROM w WHERE n=7").Scan(&box, &at); err != nil {
t.Fatal(err)
}
@@ -67,6 +68,77 @@ func TestFixtureWriteReadDuplicate(t *testing.T) {
if err := f.db.QueryRow("PRAGMA busy_timeout").Scan(&timeout); err != nil || timeout != 5000 {
t.Fatalf("busy timeout=%d: %v", timeout, err)
}
+ if err := f.db.QueryRow("PRAGMA synchronous").Scan(&synchronous); err != nil || synchronous != 2 {
+ t.Fatalf("synchronous=%d: %v", synchronous, err)
+ }
+}
+
+func TestFixtureHostPin(t *testing.T) {
+ f, logs := testFixture(t)
+ var hits atomic.Int32
+ server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ hits.Add(1)
+ w.WriteHeader(204)
+ }))
+ t.Cleanup(server.Close)
+ f.roots = x509.NewCertPool()
+ f.roots.AddCert(server.Certificate())
+ t.Setenv("G2_HAIRPIN_ADDR", server.Listener.Addr().String())
+ t.Setenv("G2_FIXTURE_HOSTS", "fixture.invalid, example.com")
+ for _, tc := range []struct{ method, path string }{
+ {"GET", "/"}, {"POST", "/write?n=1"}, {"GET", "/ranges"}, {"GET", "/fetch"}, {"GET", "/missing"},
+ } {
+ for _, host := range []string{"other.invalid", "fixture.invalid:443", "carlos"} {
+ logs.Reset()
+ r := httptest.NewRequest(tc.method, tc.path, nil)
+ r.Host = host
+ w := httptest.NewRecorder()
+ f.ServeHTTP(w, r)
+ wantLog := fmt.Sprintf("g2fixture status=421 host=%s path=%s rid=-\n", host, r.URL.Path)
+ if w.Code != 421 || w.Body.String() != "misdirected request.\n" || logs.String() != wantLog {
+ t.Errorf("%s %s host=%s: status=%d body=%q log=%q", tc.method, tc.path, host, w.Code, w.Body.String(), logs.String())
+ }
+ }
+ }
+ if hits.Load() != 0 {
+ t.Fatalf("refused fetch reached target %d times", hits.Load())
+ }
+ if w := request(f, "GET", "/", ""); w.Code != 200 || !strings.Contains(w.Body.String(), "hits=0 max=0") {
+ t.Fatalf("allowed read or refused write failed: status=%d body=%q", w.Code, w.Body.String())
+ }
+ w := httptest.NewRecorder()
+ f.ServeHTTP(w, httptest.NewRequest("GET", "https://example.com/fetch", nil))
+ if w.Code != 200 || !strings.HasPrefix(w.Body.String(), "fetch status=204 ms=") || hits.Load() != 1 {
+ t.Fatalf("allowed fetch: status=%d body=%q hits=%d", w.Code, w.Body.String(), hits.Load())
+ }
+ // An explicitly configured list with no names must refuse all hosts.
+ t.Setenv("G2_FIXTURE_HOSTS", " , ")
+ if w := request(f, "GET", "/", ""); w.Code != 421 {
+ t.Fatalf("empty configured list accepted host: %d", w.Code)
+ }
+ t.Setenv("G2_FIXTURE_HOSTS", "")
+ if w := request(f, "GET", "/", ""); w.Code != 200 {
+ t.Fatalf("unset pin refused request: %d", w.Code)
+ }
+}
+
+func TestFixtureRequestID(t *testing.T) {
+ f, logs := testFixture(t)
+ for _, tc := range []struct{ raw, want string }{
+ {"Az09._:-", "Az09._:-"},
+ {"x status=200\r\ng2fixture\t hits=999", "xstatus200g2fixturehits999"},
+ {" \t\r\n=é💥", "-"},
+ {"", "-"},
+ {strings.Repeat("a ", 70), strings.Repeat("a", 64)},
+ } {
+ logs.Reset()
+ w := request(f, "GET", "/", tc.raw)
+ wantBody := "g2fixture box=test-box hits=0 max=0 rid=" + tc.want + "\n"
+ wantLog := "g2fixture status=200 host=fixture.invalid path=/ rid=" + tc.want + "\n"
+ if w.Code != 200 || w.Body.String() != wantBody || logs.String() != wantLog {
+ t.Errorf("rid=%q: status=%d body=%q log=%q", tc.raw, w.Code, w.Body.String(), logs.String())
+ }
+ }
}
func TestFixtureInvalidNumber(t *testing.T) {
@@ -258,6 +330,13 @@ func TestFixtureFetchErrors(t *testing.T) {
if got := fetchError(&tls.CertificateVerificationError{Err: x509.UnknownAuthorityError{}}); got != "tls" {
t.Fatalf("TLS classified as %q", got)
}
+ for _, err := range []error{tls.AlertError(112), tls.RecordHeaderError{}} {
+ for _, wrapped := range []error{err, fmt.Errorf("fetch: %w", err)} {
+ if got := fetchError(wrapped); got != "tls" {
+ t.Errorf("%T classified as %q", wrapped, got)
+ }
+ }
+ }
}
func TestFixtureMethodsAndLogContract(t *testing.T) {