carlos / platform Public

scripts: G2 probe fails loudly on missing samples; fixture runbook fixes

claude agent, operated by paul@keymail.dev c2b0345d2a5690eb3b314d5367c6c25e367d8f01 parent 28d8715
5 files changed, +221 −49
  • scripts/region-ha-g2/FIXTURES.md +34 −1
  • scripts/region-ha-g2/g2-probe.py +77 −37
  • scripts/region-ha-g3/chrony-fixed-box.sh +1 −1
  • scripts/region_ha_g2_probe_test.py +107 −10
  • scripts/region_ha_g3_chrony_test.py +2 −0

Intent

Human

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

Human

<task-notification> <task-id>af3ba57b512b6d0a2</task-id> <tool-use-id>toolu_01Q9kqb8ZuSF7HdnFdQ6uqkS</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/dc71bafb-7376-4e4b-a855-4d32f1eed771/tasks/af3ba57b512b6d0a2.output</output-file> <status>completed</status> <summary>Agent "Opus task review of Task 6" 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 passes: spec compliant, task quality Approved, with five minors left. I appended the re-review to `task-6-review.md`. The 27 offline tests pass at HEAD (fa5407e3). - **Earlier findings:** all ADDRESSED. - Critical: requests now go out every second, at most 6 in flight per stream (`g2-probe.py:375-428`). Every row carries a slot number. The cap or a late scheduler writes an explicit skipped row (`:409-417`). The summary lists expected, recorded, skipped and missing slots, and counts the non-200 run in seconds (`:241-267`). - Lock absence: reads now use `s3api get-object` only and recognise `NoSuchKey`/404 (`:112-135`). - Write numbers: they start from the run's epoch, and compare keeps only this run's range (`:383`, `:465-466`, `:552`). - All seven minors are fixed: `:336`, `:488`, `:450-461`, `:168`, `:32`, `:324`, `:20`. - **Log line:** nothing depends on it. The probe parses only the response body, and the test reads only `ResponseFormat` and `RangesFormat`, which are still at `fixture/main.go:31-32`. - **Thread safety:** each JSONL line is written, flushed and counted under one mutex. Locks are always taken budget then mutex, never the reverse, so there is no deadlock. - **Clock jumps:** scheduling and slots use only the monotonic clock. A wall-clock step shows up as `t` disagreeing with `slot_utc`, so it is visible. - **New Critical/Important:** none. - **New minors:** - No single "evidence incomplete" line, and the exit stays 0 when slots are skipped or missing (`:255-267`). - The in-flight cap of 6 leaves thin margin; 7 or 8 would be safer (`:376`). - The lock reader still skips slow reads silently (`:437`). - Compare trusts a non-empty saved `.acks` after checking only its host names (`:543-551`). - A truncated last JSONL line makes compare refuse the whole file (`:520`).</result> <usage><subagent_tokens>121654</subagent_tokens><tool_uses>5</tool_uses><duration_ms>95896</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>a24b5ad82182d1b4a</task-id> <tool-use-id>toolu_01W2ugAHQFGmKdiBU3QHug8H</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/dc71bafb-7376-4e4b-a855-4d32f1eed771/tasks/a24b5ad82182d1b4a.output</output-file> <status>completed</status> <summary>Agent "Opus task review of Task 8" 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 (commit fa5407e3) clears both Important findings and minors 1-8. There is no new Critical or Important problem. **Spec:** ✅ compliant (the window rehearsal is still to do). **Quality:** Approved. I didn't re-run the tests. - **I1 addressed:** the delivery line now runs the script through `/bin/bash /run/g2-firstserve.sh`. It is changed in the script header (sh:3), FIXTURES.md and the plan, and a test pins it. - **I2 addressed:** the trigger now matches only at the start of a line, with the fixture's dots escaped. The fixture's logged path can no longer contain spaces, `=` or newlines, so a crafted request cannot add a field or a line. - The only lines that can still trigger are a real 200 for the fixture host, or a tenant app printing the exact line at the start of its output. FIXTURES.md records that risk, and the limits are unchanged (one shot, window only, one dev box). - **Minors 1-8 all addressed:** post-STOP identity warning, `match_read_utc`/`stop_utc` stamp, removal only under `/run`, `carlos` and ports refused, setenv note in the docs, anchored-prefix tests, host-form rehearsal note. The command check now allows six exact lines and has 15 negative cases. It catches `/bin/kill`, but not indirection like `eval`, which is fine as a tripwire. - **Tasks 6 and 7:** Task 6 is unaffected because `LogFormat` and every response body are unchanged; only the logged path value differs. Task 7's existing tests log path `/`, which the cleaning leaves as it was, and request routing still uses the raw path. - **New minor 1:** the stamp format changed, so the card's T4 and drill 3 text should say t0 is `stop_utc`. - **New minor 2:** a literal `%0A` can show up as text in the log after double-encoding. It is cosmetic only. The re-review is appended to `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-g2-prep/.superpowers/sdd/2026-11-05-region-ha-g2-prep/task-8-review.md`.</result> <usage><subagent_tokens>117252</subagent_tokens><tool_uses>3</tool_uses><duration_ms>56934</duration_ms></usage> </task-notification>

Human

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

Human

<task-notification> <task-id>b2ymnzjnk</task-id> <tool-use-id>toolu_016C1kixD9FLLnsKYJ6g4dKh</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/dc71bafb-7376-4e4b-a855-4d32f1eed771/tasks/b2ymnzjnk.output</output-file> <status>completed</status> <summary>Background command "Push merged tip and wait for CI" completed (exit code 0)</summary> </task-notification>

Human

<task-notification> <task-id>a1e11543a933d5199</task-id> <tool-use-id>toolu_019Wk5Gde9wCA2YJneHW7KA2</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/dc71bafb-7376-4e4b-a855-4d32f1eed771/tasks/a1e11543a933d5199.output</output-file> <status>completed</status> <summary>Agent "Whole-branch review G2 prep tools" 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>**Verdict: READY AFTER FIXES** **Critical:** none. **Important:** - **I1, must fix before merge.** The drill probe can lose samples and still exit 0, with nothing on one line that says so. `scripts/region-ha-g2/g2-probe.py:362-364` skips missed lock reads without writing any row. The summary at `:228-267` never counts lock reads, and `:496-499` returns 0 even when time slots were skipped or missing. The addendum says any missing sample is FAIL, so the operator cannot apply that rule reliably. - **I2, must fix before merge.** `scripts/region-ha-g2/FIXTURES.md:71` tells the operator to check `region: &lt;region&gt;`. Card G1.1 expects region `""`, and home-region records leave the field out entirely (`internal/provision/provision.go:60`). Following the doc literally stalls the "check before sending numbered writes" step. - **I3, fix before the G2 window, not a merge blocker.** Nothing in `scripts/region-ha-g2/FIXTURES.md` or `fixture/main.go` lets the operator register the card's once-timers (G1.2) or read their delivery for drill 1. A recipe would use `PUT /schedule/{name}` on the instance's control socket with the `CARLOS_ADMIN_TOKEN` bearer (`internal/schedule/control.go:104`). A path like `/write?n=&lt;reserved n&gt;` would show each delivery in the fixture's log line and in `/ranges`. **Must-fix minors:** - The deferred Task 6 minor "no single evidence-incomplete line, exit 0" (part of I1). - The deferred Task 6 minor "lock reader skips slow reads silently" (part of I1). - The skipped copy row at `scripts/region-ha-g3/chrony-fixed-box.sh:11`. Apply the approved text verbatim: "Command failed at line %s: %s. Check the command error and the current state below.\n". Every other deferred minor and cannot-verify item is OK to defer. The full review is at `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-g2-prep/.superpowers/sdd/2026-11-05-region-ha-g2-prep/final-review.md`.</result> <usage><subagent_tokens>166824</subagent_tokens><tool_uses>61</tool_uses><duration_ms>575710</duration_ms></usage> </task-notification>

Attributed to this commit: 22.7 g CO₂e (2,958,078 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 1528007da..ef44feccf 100644
--- a/scripts/region-ha-g2/FIXTURES.md
+++ b/scripts/region-ha-g2/FIXTURES.md
@@ -68,7 +68,7 @@ carlos instances create --app <app> --host <label>.<domain> --channel edge
carlos instances list --app <app>
```
-Read back each saved instance record using the window's operator credentials. Save it with the drill evidence. Check `ha: true`, `pool: <pool>` and `region: <region>` before sending numbered writes. The formatted `instances list` output does not prove these fields.
+Read back each saved instance record using the window's operator credentials. Save it with the drill evidence. Check `ha: true` and `pool: <pool>` before sending numbered writes. For a home-region fixture in dev ie, `region` must be `""` or absent, as required by card G1.1 and `internal/provision/provision.go:60`. If it is anything else, stop. The formatted `instances list` output does not prove these fields.
```sh
aws --profile <profile> --region <aws-region> s3 cp s3://<control-bucket>/apps/<account-id>/<app>/instances/<label>.<domain>.json <record.json>
@@ -97,3 +97,36 @@ carlos instances
```
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.
+
+## Once-timers for drill 1
+
+In the approved window, use a root shell on the serving box while the fixture is awake. Register one timer for about t0 plus 25 minutes and another for t0 plus 48 hours. Use a different `<timer-name>` and `<reserved-n>` for each timer. Names must match `[a-z0-9][a-z0-9-]{0,31}`. Set `<at-utc>` to the intended UTC time in RFC3339 form. The request body has exactly `at` and `path` (`internal/schedule/control.go:104`). Delivery always uses POST, so there is no method field (`internal/schedule/runner.go:743`). Query parameters are allowed in the path (`internal/schedule/declaration.go:40`).
+
+Reserve 9000000001 through 9000000999 for these timers. Allocate a fresh number for each registration and record the fixture, timer name, number and due time in the window evidence. The probe's default run-unique range starts at the run's epoch seconds times 1000000 plus one. At the drill date it is above this reservation and cannot collide. If you override `--write-base`, keep the entire run range outside the reservation and distinct from every other run.
+
+Use the serving instance's `CARLOS_CONTROL_SOCKET` value for `<control-socket>`. The control socket is the app socket path with `.control` appended (`internal/activator/backend_exec.go:2395`). For the flat layout it is `/run/carlos/<host>.sock.control` (`internal/provision/provision.go:3180`). For the nested layout it is `/run/carlos/instances/<instance-id>/app.sock.control` (`internal/provision/provision.go:3243`). The instance identifier is defined in `internal/provision/provision.go:3221`. If a generation uses a different app socket, use that generation's control socket.
+
+Read `CARLOS_ADMIN_TOKEN` from the instance's own `<host>.env` file, without sourcing it as shell code. Its path is `<data-dir>/<host>.env` for the flat layout or `<data-dir>/instances/<instance-id>/<host>.env` for the nested layout (`internal/activator/paths.go:40`). The control handler reads that token on each request (`internal/activator/backend_exec.go:2408`). Supply it as `<instance-admin-token>` below. Keep the token out of saved evidence.
+
+```sh
+curl --fail-with-body --silent --show-error --noproxy '*' \
+ --unix-socket '<control-socket>' \
+ --request PUT \
+ --header 'Authorization: Bearer <instance-admin-token>' \
+ --header 'Content-Type: application/json' \
+ --data '{"at":"<at-utc>","path":"/write?n=<reserved-n>"}' \
+ 'http://<host>/schedule/<timer-name>'
+```
+
+Save the returned timer record. Read it back through the same socket with `GET /schedule` and the same bearer (`internal/schedule/control.go:225`). Stop if either request fails or the name, path or due time differs. Register the second timer with its own name, reserved number and time. Do not register a finished timer again.
+
+After each due time, read the fixture through the entry selected for the drill:
+
+```sh
+curl --fail-with-body --silent --show-error --noproxy '*' \
+ --resolve '<host>:443:<entry-ip>' 'https://<host>/ranges'
+```
+
+The returned ranges must contain the reserved number exactly once, either as a single number or inside one inclusive range. Each successful delivery also produces `g2fixture status=200 host=<host> path=/write rid=-` in the fixture log. The fixture logs only the path, so the query number is absent from that line (`scripts/region-ha-g2/fixture/main.go:78`). Match it to the schedule event containing the timer name and `/write?n=<reserved-n>` (`internal/schedule/runner.go:684`). Save that event, the fixture line and the ranges. The 48 hour timer also needs the adopter's marker evidence required by the card.
+
+The fixture ignores duplicate numbers (`scripts/region-ha-g2/fixture/main.go:172`). One occurrence in `/ranges` proves a stored write, but cannot prove there was only one delivery attempt. Check the schedule events for duplicate attempts before recording the card's once-only result.
diff --git a/scripts/region-ha-g2/g2-probe.py b/scripts/region-ha-g2/g2-probe.py
index ac24f8952..652eaf237 100755
--- a/scripts/region-ha-g2/g2-probe.py
+++ b/scripts/region-ha-g2/g2-probe.py
@@ -226,35 +226,56 @@ class Budget:
class Summary:
- def __init__(self, fixtures, expected=0):
+ def __init__(self, fixtures, expected=0, lock_expected=0):
self.rows = {}
self.expected = expected
+ self.lock_expected = lock_expected
+ if lock_expected:
+ for fixture in fixtures:
+ self.stream(fixture, None, 'lock')
def stream(self, fixture, entry, kind):
return self.rows.setdefault((fixture, entry, kind), {})
def add(self, row):
- kind = row.get('stream') if row['kind'] == 'skipped' else row['kind']
- if kind in ('get', 'write'):
+ kind = row.get('stream') if row['kind'] in ('skipped', 'lock_skipped') else row['kind']
+ if kind in ('get', 'write', 'lock'):
self.stream(row['fixture'], row['entry'], kind)[row['slot']] = row
- def metrics(self, rows):
- expected = set(range(self.expected))
- recorded = {slot for slot, row in rows.items() if row['kind'] != 'skipped'}
+ def metrics(self, rows, kind='get'):
+ count = self.lock_expected if kind == 'lock' else self.expected
+ expected = set(range(count))
+ recorded = {slot for slot, row in rows.items() if row['kind'] not in ('skipped', 'lock_skipped')}
skipped = set(rows) - recorded
missing = expected - set(rows)
longest = run = 0
# Completion order is irrelevant. Missing and skipped seconds cannot prove recovery.
- for slot in range(self.expected):
+ for slot in range(count):
row = rows.get(slot, {})
run = 0 if row.get('status') == 200 else run + 1
longest = max(longest, run)
- return dict(expected=self.expected, recorded=len(recorded), skipped=sorted(skipped),
+ return dict(expected=count, recorded=len(recorded), skipped=sorted(skipped),
missing=sorted(missing), longest=longest)
+ def completeness(self):
+ counts = {stream: dict(skipped=0, missing=0, worker_failed=0) for stream in ('http', 'lock')}
+ for (_, _, kind), rows in self.rows.items():
+ metrics = self.metrics(rows, kind)
+ stream = counts['lock' if kind == 'lock' else 'http']
+ for field in ('skipped', 'missing'):
+ stream[field] += len(metrics[field])
+ stream['worker_failed'] += sum(row.get('err') == 'worker_failed' for row in rows.values())
+ return counts
+
def print(self, out):
- for (fixture, entry, kind), rows in sorted(self.rows.items()):
- metrics = self.metrics(rows)
+ for (fixture, entry, kind), rows in sorted(self.rows.items(), key=lambda item: (
+ item[0][0], item[0][1] or '', item[0][2])):
+ metrics = self.metrics(rows, kind)
+ if kind == 'lock':
+ print(f'Lock reads for {fixture}: expected {metrics["expected"]}, '
+ f'recorded {metrics["recorded"]}, skipped {len(metrics["skipped"])}, '
+ f'missing {len(metrics["missing"])}.', file=out)
+ continue
records = [row for row in rows.values() if row['kind'] != 'skipped']
status = Counter(str(row['status']) if row['status'] is not None else 'none' for row in records)
boxes = Counter(row['box'] or 'unknown' for row in records)
@@ -334,7 +355,8 @@ class Probe:
self.aws = AWSRunner(args.profile, args.region, runner=runner)
self.budget = Budget(args.max_lock_gets, self.out,
lambda: self.note('lock_cap', TEXT['cap']))
- self.summary = Summary(args.fixture, math.ceil(args.duration))
+ self.summary = Summary(args.fixture, math.ceil(args.duration),
+ math.ceil(args.duration / args.lock_every))
for fixture in args.fixture:
for entry in args.entries:
self.summary.stream(fixture, entry, 'get')
@@ -349,22 +371,8 @@ class Probe:
self.evidence.flush()
self.summary.add(row)
- def periodic(self, interval, action):
- tick = 0.0
- while tick < self.args.duration and not self.stop.is_set():
- delay = self.start + tick - self.clock.monotonic()
- if delay > 0:
- self.clock.sleep(delay)
- if self.stop.is_set() or self.clock.monotonic() >= self.end:
- return
- if action() is False:
- return
- # Skip missed slots after a slow request; never send a catch-up burst.
- elapsed = self.clock.monotonic() - self.start
- tick = max(tick + interval, math.ceil(elapsed / interval) * interval)
-
- def stamp(self, row, slot):
- row.update(slot=slot, slot_utc=(self.started_at + timedelta(seconds=slot)).isoformat().replace('+00:00', 'Z'))
+ def stamp(self, row, slot, interval=1):
+ row.update(slot=slot, slot_utc=(self.started_at + timedelta(seconds=slot * interval)).isoformat().replace('+00:00', 'Z'))
return row
def note(self, reason, message, **fields):
@@ -428,13 +436,34 @@ class Probe:
thread.join()
def lock_loop(self, fixture):
- def request():
- if not self.budget.take():
- return False
- slot = max(0, int(self.clock.monotonic() - self.start))
- self.record(self.stamp(lock_record(fixture, self.args.bucket, self.args.prefix,
- aws=self.aws, clock=self.clock), slot))
- self.periodic(self.args.lock_every, request)
+ interval = self.args.lock_every
+ next_read = 0
+ for slot in range(self.summary.lock_expected):
+ if self.stop.is_set():
+ break
+ due = self.start + slot * interval
+ reason = None
+ if slot < next_read:
+ reason = 'slow_previous_read'
+ else:
+ delay = due - self.clock.monotonic()
+ if delay > 0:
+ self.clock.sleep(delay)
+ if self.stop.is_set():
+ break
+ if self.clock.monotonic() >= min(due + interval, self.end):
+ reason = 'scheduler_delay'
+ elif not self.budget.take():
+ reason = 'budget_cap'
+ if reason:
+ row = base_record('lock_skipped', fixture, None, self.clock)
+ row.update(stream='lock', reason=reason)
+ else:
+ row = lock_record(fixture, self.args.bucket, self.args.prefix,
+ aws=self.aws, clock=self.clock)
+ # Account for each elapsed slot without sending a catch-up burst.
+ next_read = math.ceil((self.clock.monotonic() - self.start) / interval)
+ self.record(self.stamp(row, slot, interval))
def worker(self, action, *args):
try:
@@ -492,10 +521,21 @@ class Probe:
self.summary.print(self.out)
if interrupted:
print(TEXT['interrupted'], file=self.out)
+ counts = self.summary.completeness()
+ incomplete = bool(self.failures) or any(value for stream in counts.values() for value in stream.values())
+ message = 'Evidence complete.'
+ if incomplete:
+ message = ('Evidence incomplete: ' + '; '.join(
+ f'{name.upper() if name == "http" else name} skipped {stream["skipped"]}, '
+ f'missing {stream["missing"]}, failed {stream["worker_failed"]}'
+ for name, stream in counts.items()) + f'; worker failures {len(self.failures)}.')
+ self.note('evidence_incomplete' if incomplete else 'evidence_complete', message,
+ counts=counts, worker_failures=len(self.failures))
+ print(message, file=self.out, flush=True)
+ if incomplete:
+ return 3
+ if interrupted:
return 130
- if self.failures:
- print(TEXT['worker'], file=self.out)
- return 2
return 0
diff --git a/scripts/region-ha-g3/chrony-fixed-box.sh b/scripts/region-ha-g3/chrony-fixed-box.sh
index aa67ace94..fada47c78 100755
--- a/scripts/region-ha-g3/chrony-fixed-box.sh
+++ b/scripts/region-ha-g3/chrony-fixed-box.sh
@@ -8,7 +8,7 @@ readonly PREFLIGHT_FAILURE='Run this script as root on a fixed box with /etc/car
readonly CONFIG_FAILURE='Chrony configuration checks failed. Check the paths, fixed box settings and installed chrony package.'
readonly CLOCK_FAILURE='Chrony did not find an Amazon Time Sync source within 20 seconds. Check chrony sources and network access.'
readonly SERVICE_FAILURE='Chrony service checks failed. Enable chrony and confirm that systemd-timesyncd is inactive.'
-readonly COMMAND_FAILURE='A command failed at line %s: %s. Check the command error and current state below.\n'
+readonly COMMAND_FAILURE='Command failed at line %s: %s. Check the command error and the current state below.\n'
readonly ROLLBACK='To restore the previous time service, run NEEDRESTART_MODE=l DEBIAN_FRONTEND=noninteractive apt-get -y -q -o DPkg::Lock::Timeout=120 install systemd-timesyncd. This removes chrony.'
readonly CONF='/etc/chrony/conf.d/carlos-fixed.conf'
diff --git a/scripts/region_ha_g2_probe_test.py b/scripts/region_ha_g2_probe_test.py
index d9502471f..2d44daf18 100644
--- a/scripts/region_ha_g2_probe_test.py
+++ b/scripts/region_ha_g2_probe_test.py
@@ -62,6 +62,21 @@ class FakeRunner:
return subprocess.CompletedProcess(command, 0, '{"ContentLength": 123}', '')
+class InlineRequests(threading.Thread):
+ # Lock tests advance simulated seconds without waiting for HTTP workers.
+ # Keep the stream threads real, but finish each fake HTTP request inline.
+ def start(self):
+ self.inline = self._target.__name__ == 'request'
+ if self.inline:
+ self.run()
+ else:
+ super().start()
+
+ def join(self, timeout=None):
+ if not self.inline:
+ super().join(timeout)
+
+
class ProbeTests(unittest.TestCase):
def setUp(self):
self.fake = FakeRunner()
@@ -315,27 +330,109 @@ class ProbeTests(unittest.TestCase):
self.assertEqual(row['err'], 'curl_error')
def test_cap_stops_only_locks_once(self):
- config = probe.parse_args(self.args + ['--duration', '7', '--max-lock-gets', '2'])
+ config = probe.parse_args(self.args + ['--duration', '16', '--max-lock-gets', '4'])
job = probe.Probe(config, runner=self.fake, clock=self.clock, out=self.stdout)
- job.budget.used = 1
- self.assertEqual(job.run(), 0)
+ job.budget.used = 3
+ with patch.object(probe.threading, 'Thread', InlineRequests):
+ self.assertEqual(job.run(), 3)
rows = [json.loads(line) for line in self.out.read_text().splitlines()]
self.assertEqual(sum(r['kind'] == 'lock' for r in rows), 1)
- self.assertEqual(sum(r['kind'] == 'get' for r in rows), 7)
- self.assertEqual(sum(r['kind'] == 'write' for r in rows), 7)
+ self.assertEqual(sum(r['kind'] == 'get' for r in rows), 16)
+ self.assertEqual(sum(r['kind'] == 'write' for r in rows), 16)
+ skipped = [r for r in rows if r['kind'] == 'lock_skipped']
+ self.assertEqual([r['slot'] for r in skipped], [1, 2, 3])
+ self.assertTrue(all(r['reason'] == 'budget_cap' for r in skipped))
+ self.assertIn('Lock reads for example.com: expected 4, recorded 1, skipped 3, missing 0.', self.stdout.getvalue())
+ self.assert_verdict(rows, 'Evidence incomplete: HTTP skipped 0, missing 0, failed 0; '
+ 'lock skipped 3, missing 0, failed 0; worker failures 0.')
self.assertEqual(self.stdout.getvalue().count('Lock reads stopped at the limit.'), 1)
notes = [r for r in rows if r.get('reason') == 'lock_cap']
self.assertEqual(len(notes), 1)
self.assertEqual(notes[0]['message'], 'Lock reads stopped at the limit.')
+ def assert_verdict(self, rows, message):
+ self.assertEqual(self.stdout.getvalue().splitlines()[-1], message)
+ self.assertEqual(sum(line.startswith('Evidence ') for line in self.stdout.getvalue().splitlines()), 1)
+ self.assertEqual(rows[-1]['message'], message)
+ self.assertEqual(sum(r.get('reason') in ('evidence_complete', 'evidence_incomplete') for r in rows), 1)
+
+ def test_skipped_http_slots_fail_run(self):
+ class DelayedClock(FakeClock):
+ def sleep(self, seconds):
+ super().sleep(seconds + 2 if seconds == 1 else seconds)
+
+ self.assertEqual(probe.main(self.args, runner=self.fake, clock=DelayedClock(), out=self.stdout), 3)
+ rows = [json.loads(line) for line in self.out.read_text().splitlines()]
+ for kind in ('get', 'write'):
+ skipped = [r for r in rows if r['kind'] == 'skipped' and r['stream'] == kind]
+ self.assertEqual([r['slot'] for r in skipped], [1, 2])
+ self.assertTrue(all(r['reason'] == 'scheduler_delay' for r in skipped))
+ self.assert_verdict(rows, 'Evidence incomplete: HTTP skipped 4, missing 0, failed 0; '
+ 'lock skipped 0, missing 0, failed 0; worker failures 0.')
+
+ def test_slow_lock_read_records_every_skipped_slot(self):
+ for duration in (11, 16):
+ with self.subTest(duration=duration):
+ self.out.unlink(missing_ok=True)
+ Path(str(self.out) + '.acks').unlink(missing_ok=True)
+ self.stdout = io.StringIO()
+ reads = []
+
+ def slow(command, **kwargs):
+ if command[0] == 'aws':
+ reads.append(self.clock.monotonic())
+ if len(reads) == 1:
+ self.clock.sleep(11)
+ return self.fake(command, **kwargs)
+
+ with patch.object(probe.threading, 'Thread', InlineRequests):
+ self.assertEqual(probe.main(self.args + ['--duration', str(duration)], runner=slow,
+ clock=self.clock, out=self.stdout), 3)
+ rows = [json.loads(line) for line in self.out.read_text().splitlines()]
+ locks = [r for r in rows if r['kind'] in ('lock', 'lock_skipped')]
+ self.assertEqual([r['slot'] for r in locks], list(range(3 if duration == 11 else 4)))
+ skipped = [r for r in locks if r['kind'] == 'lock_skipped']
+ self.assertEqual([r['slot'] for r in skipped], [1, 2])
+ self.assertTrue(all(r['reason'] == 'slow_previous_read' for r in skipped))
+ self.assertEqual([(datetime.fromisoformat(r['slot_utc']) - NOW).total_seconds()
+ for r in locks], [5 * r['slot'] for r in locks])
+ self.assertEqual(reads, [0] if duration == 11 else [0, 15])
+ self.assert_verdict(rows, 'Evidence incomplete: HTTP skipped 0, missing 0, failed 0; '
+ 'lock skipped 2, missing 0, failed 0; worker failures 0.')
+
+ def test_missing_slot_fails_run(self):
+ original = probe.Probe.record
+ for kind in ('get', 'lock'):
+ with self.subTest(kind=kind):
+ self.out.unlink(missing_ok=True)
+ Path(str(self.out) + '.acks').unlink(missing_ok=True)
+ self.stdout = io.StringIO()
+
+ def drop(job, row):
+ if row['kind'] == kind and row['slot'] == 0:
+ return
+ original(job, row)
+
+ with patch.object(probe.Probe, 'record', drop):
+ self.assertEqual(probe.main(self.args, runner=self.fake, clock=self.clock,
+ out=self.stdout), 3)
+ rows = [json.loads(line) for line in self.out.read_text().splitlines()]
+ counts = rows[-1]['counts']
+ self.assertEqual(counts['http']['missing'], int(kind == 'get'))
+ self.assertEqual(counts['lock']['missing'], int(kind == 'lock'))
+ self.assert_verdict(rows, rows[-1]['message'])
+
def test_http_and_lock_cadence(self):
- self.assertEqual(probe.main(self.args + ['--duration', '11'],
- runner=self.fake, clock=self.clock, out=self.stdout), 0)
+ with patch.object(probe.threading, 'Thread', InlineRequests):
+ self.assertEqual(probe.main(self.args + ['--duration', '11'],
+ runner=self.fake, clock=self.clock, out=self.stdout), 0)
rows = [json.loads(line) for line in self.out.read_text().splitlines()]
for kind, ticks in [('get', list(range(11))), ('write', list(range(11))), ('lock', [0, 5, 10])]:
times = [(datetime.fromisoformat(row['slot_utc'].replace('Z', '+00:00')) - NOW).total_seconds()
for row in rows if row['kind'] == kind]
self.assertEqual(sorted(times), ticks, kind)
+ self.assertIn('Lock reads for example.com: expected 3, recorded 3, skipped 0, missing 0.', self.stdout.getvalue())
+ self.assert_verdict(rows, 'Evidence complete.')
def test_exclusive_evidence_files(self):
for path in (self.out, Path(str(self.out) + '.acks')):
@@ -353,7 +450,7 @@ class ProbeTests(unittest.TestCase):
args = self.args + ['--entry', 'backhaul=192.0.2.20', '--fixture', 'second.example.com']
self.assertEqual(probe.main(args, runner=self.fake, clock=self.clock, out=self.stdout), 0)
rows = [json.loads(line) for line in self.out.read_text().splitlines()]
- self.assertEqual(len(rows), 21)
+ self.assertEqual(len(rows), 22)
self.assertEqual(len({r['rid'] for r in rows if r['kind'] in ('get', 'write')}), 18)
self.assertEqual(json.loads(Path(str(self.out) + '.acks').read_text()),
{'example.com': [1, 2, 3], 'second.example.com': [1, 2, 3]})
@@ -417,7 +514,7 @@ class ProbeTests(unittest.TestCase):
raise RuntimeError('Synthetic failure.')
return self.fake(command, **kwargs)
- self.assertEqual(probe.main(self.args, runner=broken, clock=self.clock, out=self.stdout), 2)
+ self.assertEqual(probe.main(self.args, runner=broken, clock=self.clock, out=self.stdout), 3)
rows = [json.loads(line) for line in self.out.read_text().splitlines()]
notes = [row for row in rows if row.get('reason') == 'worker_failed']
self.assertEqual(len(notes), 1)
@@ -489,7 +586,7 @@ class ProbeTests(unittest.TestCase):
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
rows = [json.loads(line) for line in self.out.read_text().splitlines()]
self.assertEqual({row['kind'] for row in rows}, {'get', 'write', 'lock', 'note'})
- self.assertEqual(len(rows), 4)
+ self.assertEqual(len(rows), 5)
self.assertTrue(all(row['err'] is None for row in rows))
self.assertEqual(json.loads(Path(str(self.out) + '.acks').read_text()), {'example.com': [1]})
diff --git a/scripts/region_ha_g3_chrony_test.py b/scripts/region_ha_g3_chrony_test.py
index 2631a34ea..a944e9aa2 100644
--- a/scripts/region_ha_g3_chrony_test.py
+++ b/scripts/region_ha_g3_chrony_test.py
@@ -233,6 +233,8 @@ class ChronyFixedBoxTests(unittest.TestCase):
self.assertNotIn(WITNESS, calls)
self.assertNotIn('Chrony checks passed.', result.stdout)
self.assertIn(failure, result.stderr)
+ self.assertRegex(result.stderr, r'Command failed at line [0-9]+: [^\n]+\. '
+ r'Check the command error and the current state below\.\n')
self.assertIn(ROLLBACK, result.stderr)
self.assertIn('Current package states.', result.stderr)
self.assertIn('chrony ', result.stderr)