0
0
requester and stand-up: retry one-off network failures; failure evidence
docs/plans/0040-findings.md+80−0
| @@ -1894,3 +1894,83 @@ Each: what was seen (with the log), the cause, the fix, its proof. | ||
linked); it lists leaks the change does not close (a reserve whose accept fails before `provision()`: 10 min; an | ||
accept failing in `acceptContract` after its reserve, refreshed by each outbox retry: not bounded). Unproven as the | ||
cause of 0014:concurrent at a4aa6d62; no prod journal shows a phantom. Held out of the cycles in flight. | ||
- 0014:impossible WRITE FAILURE (promote 7, rc183, ee133538; branch `rc-0014i`). SEEN: the RESULT note is exactly 200 | ||
characters: `tests/gate.sh` cut every FAIL note with jq `.[0:200]`, which fell on the `/` before the empty rkey | ||
(`RepoStore.write` with create and no rkey prints `<did>/<collection>/: <cause>`), so the cause was lost; the doc's | ||
error reached the gate unredacted. CAUSE (strong evidence, cause text not recovered): 0014 is exclusive, so from | ||
23:05:26Z to 23:20:56Z only 0014:impossible ran (its 930 s is the failure plus the 900 s freeze). Jetstream replay of | ||
bob's repo (wantedDids, cursor 23:02:30Z) shows one commit in that window: 23:05:58.043Z create `badgeBlueKeys` | ||
(the maxCpus requester publishing its signer key with its fresh session), then nothing until 23:21Z: the compute.vm | ||
createRecord right after it got no commit. Nothing retries that write: `xrpc.Client.do` retries only a DPoP nonce | ||
and one credential renewal, `RepoStore.write` none, and runner.go turned the first error into Failed. Bob's PDS path | ||
(bsky.social entryway, PDS phellinus.us-west.host.bsky.network) answered transient errors to the same account today: | ||
18:54:23Z `InternalServerError (status 500)` and 18:57:01Z `UpstreamFailure (status 502)` (hand runs 0015, 0016; | ||
the release's destroy-event loop retried them). Ruled out: a rate limit (Jetstream from 14:32Z to 23:40Z: 1422 ops, | ||
about 2900 points; the busiest rolling hour 936 points from 17:26Z, the hour before the failure about 700, against | ||
5000/h and 35000/day); OAuth/DPoP (prod.json accounts have no `identity`: each `run request` signs in with the app | ||
password (pdsAccount, its own createSession, no shared session), and the same process's session wrote the badge | ||
key seconds before); a record or validation change (a4aa6d62..ee133538 touches no Go: docs, promote.sh, | ||
tests/host/src/swc.rs). FIX: (a) the contract flow's compute.vm and policy writes go through `putSetupRecord`: a | ||
client TID rkey picked once, putRecord (idempotent, so a write that landed before a lost answer is not duplicated), | ||
retried by `untilSettled` on `netretry.Transient` (5xx, 429, timeouts, network errors; 2 s doubling to 30 s, 2 min, | ||
`requester_contract_waits_transient` / `_settled` / `_gave_up`), the requester's existing transient path; (b) the | ||
host redacts the doc's error with `redact_log` and the gate keeps the whole note (newlines to spaces). The RFP create | ||
(`market.CreateRFP`) still has no retry. PROOF: `go build`, `cargo check -p swc-test-host`, `deploy/check.sh --fast` | ||
on hat-8; the next occurrence prints its cause in the RESULT line, or `requester_contract_transient_settled` in the | ||
request log. | ||
- STAGING STAND-UP put-suite (test-4 at main dbacebf6, 23:15Z to 23:53Z): `gate: staging: 0 of 13 PASS (shard 4/4)`, no | ||
entry ran. The network stood up (four VMs Held at 65 s, mesh 158 s, infra record deployed, `dev up` ready 23:22:06Z), | ||
then `atproto:put-suite` (put-host done 23:22:10.137Z) ran ONE `run requester ssh --exec 'cat > suite.tgz.part && mv'` | ||
over iroh that returned exit 255 `error: connection lost` 36.03 s later (the error text appears twice in the log: the | ||
result line and the FROZEN line; it is one attempt). Earlier green runs' put-suite took 1.4 to 7.1 s | ||
(`~/.tmp/ci-main/*.log`: test-4 d6a2b391 7.1 s, test1 ee133538 6.9 s, the rest under 2 s); the tarball is about 2 MB | ||
(repo files 0.2 MB, module wasm 1.8 MB gzipped, plus the page payload). Nothing else touched the atproto VM in that | ||
window (gateway:probe ended 23:22:09Z; mesh, tls and up were done by 23:21:31Z), so not a concurrent step reconfiguring | ||
the network. 36 s = a stall a few seconds into the stream plus the QUIC idle timeout (about 30 s): the guest's dumbpipe | ||
listener dropping the session (the known `iroh.service` exit, finding at the head of this file; plan 0044 finding 87: | ||
back in about 5 s) or a path blip while the same bidders carried two cycles' staging networks and the prod gate. | ||
Cause in our code: `request.put` (`tests/host/src/swc.rs` `request_put`/`put_exec`) made one attempt, no retry, and | ||
the module's `_ if !ok` ended the run, while the sibling `install` step already retries "connection lost" 3 times at | ||
10 s (`tests/modules/staging/src/lib.rs`, plan 0044 finding 87). Also: the streamed put's `cat > x.part && mv` would move | ||
a truncated stream into place if the remote cat saw EOF on a dropped channel, and a stdin write error returned before | ||
the child was waited for. Same gap in every streamed put: put (meshd without a URL), putbin, tls-root/leaf/key, | ||
put-host (when its URL download fails), put-suite and put-agent (a lost put-agent silently read as "no agent config"). | ||
The ssh exec steps (id, mesh, tls-dir, up, status, accounts) still fail on one lost connection; not changed here. | ||
FIX (test, branch rc-putsuite): `request_put` checks the streamed file's sha256 on the guest before the `mv` (a | ||
partial file is never used) and retries the whole put on "connection lost" up to 3 more times, 10/20/30 s apart (the | ||
install's bound); `put_exec` waits for the child before reporting a stdin write error; the put result carries | ||
`tries` and `sha256`, the multi-VM staging module records `readings.putTries[<step>]` when a put needed more than one. | ||
PROOF: `cargo check -p swc-test-host` and `cargo wasm` (exit 0); the guest command run locally with a truncated | ||
stream exits 1 and leaves no file, with the whole stream exits 0 and the file is identical. Unproven: the retry path itself (needs a lost iroh | ||
session mid-put) and the cause split between the dumbpipe exit and a path blip (the test-4 artifacts' atproto VM | ||
journal would show an `iroh.service` restart at 23:22:1xZ; the knotless CLI on hat-8's PATH has no `run artifacts`). | ||
A hand stand-up was skipped: promote 8 (dbacebf6) was running on kcp main. | ||
- RELIABILITY SWEEP after three reds, each a different one-off network failure at a call that tried once (branch rc-sweep | ||
on nine). SEEN: (1) the requester's setup record write (fixed on nine), (2) the stand-up's streamed put (fixed on nine), | ||
(3) a k8s node never joined (not in this sweep); the reviewers of (1) and (2) named the rest. CAUSE: single-try calls. | ||
FIX: (A) `tests/modules/staging/src/lib.rs` multi layout: every stand-up ssh exec step (id, mesh, tls-dir, up, status, | ||
accounts, kcp, kcpget, authkey, keyscan, gateway, trust, bidder, request, suite) runs again on "connection lost" (never on | ||
a real non-zero exit), up to 3 more times 10/20/30 s apart (the put's bound; `install` keeps its own 3 x 10 s), its | ||
command kept in state until its result (`sshr`), `readings.sshRetries`. Made idempotent first: detached starts go through | ||
`bg_once` (a `<step>.started` marker: dev up, gateway, qr, bidder install, probes and suite start once), mesh starts | ||
meshd only when `pgrep -x socialweb-meshd` finds none, up moves a TLS `.part` only when it is there, the bidder's | ||
reflink mkfs takes `-f` (behind its mountpoint check); trust.sh accounts makes new handles per run (a rerun leaves the | ||
first try's throwaway accounts unused), vouch is putRecord by subject. Not retried: down (teardown), the polls (already | ||
tolerant), the single-VM layout (CI runs multi). (B) `internal/market/requester/runner.go` `putRFP`: the RFP is built and | ||
signed once and put at a setupKeys TID through `putSetupRecord`, so a retry after a landed write gives the same record | ||
and cid (no second RFP, no second set of bids); the bid window reads createdAt, the RFP rkey is opaque everywhere else. | ||
Still single-try on the contract path (for the lead): the accept `market.CreateAcceptAt` (runner.go:878, deterministic | ||
rkey, putRecord, no retry), the contract RBAC record `putRBAC` from `prepareWorkloadGrant` (secrets.go:635) and its | ||
rewrite (secrets.go:482), the webrtc ingress offer createRecord (market.go:668, server rkey); retried already: the | ||
association grant (association.go:307, bounded backoff), outbound ContractEvents (controller backoff, existence check), | ||
the vm.delete destroy loop (runner.go:2070/2081), the badge.blue signer key (identity.go:187, rebind retry). (C) the | ||
watch capture's minute report ran `new URL("getRecord")` (fill()'s source) and died one minute in: fixed on | ||
socialweb-computer-watch main 9fada6f (fast-forward over 0655e91), pinned in `scripts/ci-test.sh`; the staging | ||
network's own relay is not added as a source (the CI VM is off the overlay and does not trust the run's CA: a bigger | ||
change). A failed suite now also brings each bidder VM's and the gateway VM's journals (swc-bidder and stg, run window, | ||
last 1 MiB each, plus the 12 newest `*.log` last 160 KiB each: at most 3.875 MiB, inside one fetch's 4 MiB room; whole | ||
lines, `split -C`; under `timeout 120`; a deadline then keeps the suite's error) into `logs/journals-<vm>/` | ||
(`logs.fetchRuns` input `all`). | ||
PROOF: `go build ./... && go vet ./internal/market/requester/`, `deploy/check.sh --fast` (exit 0), `cargo check -p | ||
swc-test-host`, `cargo wasm`, `bash -n scripts/ci-test.sh`, `node --check capture.mjs`. Unproven without a CI cycle: | ||
every retry path (needs a lost session or a PDS 5xx), the journal fetch on a real failure. | ||
internal/market/requester/runner.go+36−3
| @@ -8,6 +8,7 @@ import ( | ||
"errors" | ||
"fmt" | ||
"log/slog" | ||
mrand "math/rand/v2" | ||
"slices" | ||
"strconv" | ||
"strings" | ||
| @@ -664,7 +665,7 @@ func (r *contractRunner) requestOnce(ctx context.Context) error { | ||
if err != nil { | ||
return fmt.Errorf("encode the compute.vm record: %w", err) | ||
} | ||
payload, err := q.repo.CreateRecord(ctx, q.repoDID, market.ComputeVMNSID, payloadRecord) | ||
payload, err := r.putSetupRecord(ctx, "createComputeVM", market.ComputeVMNSID, payloadRecord) | ||
if err != nil { | ||
return fmt.Errorf("create the compute.vm record: %w", err) | ||
} | ||
| @@ -686,7 +687,7 @@ func (r *contractRunner) requestOnce(ctx context.Context) error { | ||
policyRef = &market.StrongRef{Type: market.StrongRefNSID, URI: state.Policy.URI, CID: state.Policy.CID} | ||
} else { | ||
policyRecord := BuildPolicyRecord(policyName, policyWorkflow, workflowText, q.marketDID, policyArgs, q.nowISO()) | ||
created, err := q.repo.CreateRecord(ctx, q.repoDID, PolicyGhaLiteNSID, policyRecord) | ||
created, err := r.putSetupRecord(ctx, "createPolicy", PolicyGhaLiteNSID, policyRecord) | ||
if err != nil { | ||
return fmt.Errorf("create the policy record: %w", err) | ||
} | ||
| @@ -719,7 +720,7 @@ func (r *contractRunner) requestOnce(ctx context.Context) error { | ||
if err := r.deadlineErr(state); err != nil { | ||
return err | ||
} | ||
rfp, err := market.CreateRFP(ctx, q.repo, q.repoDID, rfpOptions, q.signer) | ||
rfp, err := r.putRFP(ctx, rfpOptions) | ||
if err != nil { | ||
return fmt.Errorf("create the market.rfp record: %w", err) | ||
} | ||
| @@ -1122,6 +1123,38 @@ func isRetryable(err error) bool { | ||
return errors.As(err, &target) | ||
} | ||
| ||
var setupKeys = syntax.NewTIDClock(uint(mrand.IntN(1024))) | ||
| ||
func (r *contractRunner) putSetupRecord(ctx context.Context, site, collection string, record map[string]any) (market.StrongRef, error) { | ||
rkey := setupKeys.Next().String() | ||
var ref market.StrongRef | ||
err := r.untilSettled(ctx, site, func() error { | ||
var err error | ||
ref, err = r.q.repo.PutRecord(ctx, r.q.repoDID, collection, rkey, record) | ||
if netretry.Transient(err) { | ||
return retryable(err) | ||
} | ||
return err | ||
}) | ||
return ref, err | ||
} | ||
| ||
func (r *contractRunner) putRFP(ctx context.Context, opts market.RFPOptions) (market.StrongRef, error) { | ||
rfp, err := market.BuildRFP(opts) | ||
if err != nil { | ||
return market.StrongRef{}, err | ||
} | ||
value, err := market.EncodeRecord(rfp) | ||
if err != nil { | ||
return market.StrongRef{}, err | ||
} | ||
signed, err := market.SignRecord(value, r.q.repoDID, r.q.signer) | ||
if err != nil { | ||
return market.StrongRef{}, err | ||
} | ||
return r.putSetupRecord(ctx, "createRFP", rfp.NSID(), signed) | ||
} | ||
| ||
func (r *contractRunner) untilSettled(ctx context.Context, site string, try func() error) error { | ||
err := try() | ||
if err == nil || !isRetryable(err) || ctx.Err() != nil { | ||
scripts/ci-test.sh+2−1
| @@ -114,7 +114,8 @@ step_staging() { | ||
mkdir -p "$runs" | ||
fi | ||
[ -d "$watch/.git" ] || git clone -q https://knotless.dev/johnandersen777.bsky.social/socialweb-computer-watch "$watch" | ||
git -C "$watch" checkout -q 83541a1bd622a8679d90226fa72cab2af87dcde3 | ||
git -C "$watch" cat-file -e 9fada6f725fe0bc9f6bed8d21106670977bb659a^{commit} 2>/dev/null || git -C "$watch" fetch -q origin | ||
git -C "$watch" checkout -q 9fada6f725fe0bc9f6bed8d21106670977bb659a | ||
sh "$watch/scripts/ci-capture.sh" "$runs/watch.ndjson" 7200 | ||
spec="$(cat "$home/requester.spec")" | ||
echo "requester $spec" | ||
tests/host/src/main.rs+1−1
| @@ -821,7 +821,7 @@ async fn main_() -> Result<bool> { | ||
readings["requester"] = json!({ "spec": target.requester, "version": bin.version }); | ||
let doc = json!({ | ||
"runbook": runbook, "test": "composition", "target": target.name, "startedAt": started, "endedAt": atlibs_host::iso_now(), | ||
"pass": pass, "error": result.get("error"), "phase": result.get("phase"), "cleanupErrors": cleanup, "readings": readings, "dump": dump, "work": dir, | ||
"pass": pass, "error": result.get("error").map(|e| e.as_str().map_or_else(|| e.clone(), |s| json!(swc::redact_log(s).trim_end()))), "phase": result.get("phase"), "cleanupErrors": cleanup, "readings": readings, "dump": dump, "work": dir, | ||
}); | ||
if signed_in { | ||
let out = std::env::var("SWC_READINGS") | ||
tests/host/src/more.rs+6−5
| @@ -568,15 +568,16 @@ impl Swc { | ||
self.bin.run(&args).await.map_err(|e| e.to_string()) | ||
} | ||
| ||
/// logs.fetchRuns {name, contract?, dir, to}: the run dirs under `dir` on a guest that hold a failure.json (the failed | ||
/// compositions of a gate run there) into this run's dump at `logs/<to>/<run>/`: text files redacted and cut as the | ||
/// dump's own logs, a ticks.ndjson.zst whole (the dump's own form) while the room lasts, the rest in `skipped.txt`. | ||
/// The guest is a run requester's contract (`contract`) or an invocation (`name` only). | ||
/// logs.fetchRuns {name, contract?, dir, to, all?}: the run dirs under `dir` on a guest that hold a failure.json (the failed | ||
/// compositions of a gate run there; `all`: every dir under `dir`) into this run's dump at `logs/<to>/<run>/`: text files | ||
/// redacted and cut as the dump's own logs, a ticks.ndjson.zst whole (the dump's own form) while the room lasts, the rest | ||
/// in `skipped.txt`. The guest is a run requester's contract (`contract`) or an invocation (`name` only). | ||
async fn fetch_runs(&self, input: &Value) -> Result<Value, String> { | ||
let (name, dir, to) = (str_of(input, "name")?, str_of(input, "dir")?, str_of(input, "to")?); | ||
let to = std::path::Path::new(to).file_name().ok_or("to: a directory name")?.to_string_lossy().to_string(); | ||
let pick = if input["all"] == true { "[ -d \"$d\" ]" } else { "[ -f \"$d\"failure.json ]" }; | ||
let exec = format!( | ||
"cd '{}' 2>/dev/null || exit 0; echo SWC-LOGS-BEGIN; for d in */; do [ -f \"$d\"failure.json ] && echo \"${{d%/}}\"; done | tar -czf - -T - 2>/dev/null | base64 -w0; echo; echo SWC-LOGS-END", | ||
"cd '{}' 2>/dev/null || exit 0; echo SWC-LOGS-BEGIN; for d in */; do {pick} && echo \"${{d%/}}\"; done | tar -czf - -T - 2>/dev/null | base64 -w0; echo; echo SWC-LOGS-END", | ||
dir.replace('\'', "") | ||
); | ||
let run = async { | ||
tests/host/src/swc.rs+26−8
| @@ -29,6 +29,8 @@ const P: &str = "computer.socialweb.test."; | ||
/// Where the guest requester reads its association ref (the renter writes it), and how long it may take to come. | ||
const R2_REF: &str = "/run/socialweb-r2/association-ref"; | ||
const R2_REF_WAIT: Duration = Duration::from_secs(15 * 60); | ||
const PUT_RETRIES: u32 = 3; | ||
const PUT_RETRY_BACKOFF: Duration = Duration::from_secs(10); | ||
pub const NSIDS: &[&str] = &[ | ||
"computer.socialweb.test.requester.start", | ||
"computer.socialweb.test.request.start", | ||
| @@ -350,9 +352,11 @@ impl Swc { | ||
_ => None, | ||
} | ||
.filter(|u| u.starts_with("https://") && !u.contains(['\'', ' ', '\n'])); | ||
if let Some(url) = url { | ||
let sha: String = { | ||
use sha2::Digest; | ||
let sha: String = sha2::Sha256::digest(&bytes).iter().map(|b| format!("{b:02x}")).collect(); | ||
sha2::Sha256::digest(&bytes).iter().map(|b| format!("{b:02x}")).collect() | ||
}; | ||
if let Some(url) = url { | ||
let exec = format!( | ||
"curl -fsS --retry 3 -o '{remote}.part' '{url}' && echo '{sha} {remote}.part' | sha256sum -c --quiet && mv '{remote}.part' '{remote}'" | ||
); | ||
| @@ -360,11 +364,21 @@ impl Swc { | ||
return Ok(json!({ "remote": remote, "bytes": bytes.len(), "from": url })); | ||
} | ||
} | ||
let exec = format!("{umask}cat > '{remote}.part' && mv '{remote}.part' '{remote}'"); | ||
self.put_exec(name, input, exec, Some(&bytes)) | ||
.await | ||
.map_err(|e| format!("put {remote}: {e}"))?; | ||
Ok(json!({ "remote": remote, "bytes": bytes.len() })) | ||
let exec = format!( | ||
"{umask}cat > '{remote}.part' && echo '{sha} {remote}.part' | sha256sum -c --quiet && mv '{remote}.part' '{remote}'" | ||
); | ||
let mut tries: u32 = 0; | ||
loop { | ||
tries += 1; | ||
match self.put_exec(name, input, exec.clone(), Some(&bytes)).await { | ||
Ok(()) => break, | ||
Err(e) if e.contains("connection lost") && tries <= PUT_RETRIES => { | ||
tokio::time::sleep(PUT_RETRY_BACKOFF * tries).await; | ||
} | ||
Err(e) => return Err(format!("put {remote} (try {tries}): {e}")), | ||
} | ||
} | ||
Ok(json!({ "remote": remote, "bytes": bytes.len(), "sha256": sha, "tries": tries })) | ||
} | ||
| ||
// an exec on the VM of a put: a Held contract of the run requester `name` (an Infra's), else `name` is a run request | ||
| @@ -393,16 +407,20 @@ impl Swc { | ||
.stderr(Stdio::piped()) | ||
.spawn() | ||
.map_err(|e| e.to_string())?; | ||
let mut wrote = Ok(()); | ||
if let Some(bytes) = stdin { | ||
let mut sin = child.stdin.take().unwrap(); | ||
use tokio::io::AsyncWriteExt; | ||
sin.write_all(bytes).await.map_err(|e| e.to_string())?; | ||
wrote = sin.write_all(bytes).await; | ||
drop(sin); | ||
} | ||
let out = child.wait_with_output().await.map_err(|e| e.to_string())?; | ||
if !out.status.success() { | ||
return Err(tail(&String::from_utf8_lossy(&out.stderr))); | ||
} | ||
if let Err(e) = wrote { | ||
return Err(format!("stdin: {e}")); | ||
} | ||
Ok(()) | ||
} | ||
| ||
tests/modules/staging/src/lib.rs+109−27
| @@ -128,6 +128,16 @@ fn bg(step: &str, cmd: String) -> String { | ||
) | ||
} | ||
| ||
/// `bg` started at most once per VM (`<step>.started`): a step run again after a lost ssh session finds the first start. | ||
fn bg_once(step: &str, cmd: String) -> String { | ||
let f = format!("/home/stg/{step}"); | ||
format!("if [ -e {f}.started ]; then echo started; else touch {f}.started; {}; fi", bg(step, cmd)) | ||
} | ||
| ||
/// How many more times a stand-up step runs after its ssh session over iroh was lost ("connection lost"), 10 s, 20 s, 30 s | ||
/// apart: the bound of `install` and of a put (plan 0044 finding 87, plan 0040 Findings). | ||
const SSH_RETRIES: u64 = 3; | ||
| ||
/// The suite's own logs on the VM (the target's, each composition's), tails of each: what a failed suite names its test by. Fetched | ||
/// before the run is torn down and kept in the readings (the run's dump, an artifact), pass or fail. | ||
const SUITE_LOGS: &str = "cd /home/stg/stg 2>/dev/null || exit 0; for f in target-staging.log gate/*.log; do [ -f \"$f\" ] || continue; echo \"=== $f ($(wc -c < \"$f\") bytes)\"; tail -c 6000 \"$f\"; done; for f in qr gateway; do echo \"=== $f.log\"; tail -c 3000 /home/stg/$f.log 2>/dev/null; done; echo '=== suite.log'; tail -c 4000 /home/stg/suite.log 2>/dev/null; exit 0"; | ||
| @@ -526,6 +536,23 @@ fn write_file(path: &str, text: &str) -> Result<String, String> { | ||
| ||
const KCP_SERVE_PORT: u16 = 8099; | ||
| ||
/// Where a VM's evidence of a failed suite is gathered for logs.fetchRuns (`all`): one dir per VM. | ||
const EVIDENCE: &str = "/home/stg/evidence"; | ||
| ||
/// As root on a VM of a failed suite, at most 120 s: the journals of the accounts swc-bidder (the installed bidder's user units) | ||
/// and stg (the run window: `minutes` back), the last 1 MiB each, and the last 160 KiB of the 12 newest `*.log` under | ||
/// /home/stg and the bidder's state (the gateway's dev logs run as processes, not units); each from its first whole line, in | ||
/// pieces that end on a line (the dump keeps a log's last 512 KiB and redacts by line). At most 2 x 1 MiB + 12 x 160 KiB | ||
/// (3.875 MiB), inside one logs.fetchRuns call's room (4 MiB), so nothing is dropped. | ||
fn evidence(vm: &str, minutes: u64) -> String { | ||
format!( | ||
"E={EVIDENCE}/{vm}; rm -rf {EVIDENCE}; install -d $E; timeout 120 sh -c 'E={EVIDENCE}/{vm}; \ | ||
for u in swc-bidder stg; do i=$(id -u $u 2>/dev/null) || continue; journalctl _UID=$i --since -{minutes}min --no-pager -o short-iso 2>&1 | tail -c 1048576 | tail -n +2 | split -C 524288 -a 2 -d - $E/journal-$u.; done; \ | ||
find /home/stg /var/lib/socialweb-computer -name \"*.log\" -size +0 -not -path \"{EVIDENCE}/*\" -printf \"%T@ %p\\n\" 2>/dev/null | sort -rn | head -12 | cut -d\" \" -f2- | \ | ||
while read -r f; do tail -c 163840 \"$f\" | tail -n +2 > \"$E/$(echo \"${{f#/}}\" | tr / _)\"; done'; echo ok" | ||
) | ||
} | ||
| ||
/// On a bidder VM: the suite's ssh key (the atproto VM's stg) may log in as root, as it does on the atproto VM (ROOT_HOST): the installed | ||
/// bidder's units and journal are the system account swc-bidder's (no login shell), which only root reads, restarts and sets properties on. | ||
fn authorize(public: &str) -> String { | ||
| @@ -543,7 +570,7 @@ const BIDDER_SPEC: &str = "/etc/socialweb-computer/bidder.json"; | ||
/// A bidder's state on a reflink filesystem, as prod's hosts have (btrfs): a rental's rootfs is then a clone, not a copy of | ||
/// the 1.44 GiB image. The VM's own disk is ext4 (no reflink), where two rentals at once on one bidder saturated the disk | ||
/// and a guest missed its 2 min network window (plan 0040 Findings, 0014:exhausted). XFS is in the guest kernel. | ||
const BIDDER_REFLINK: &str = "mountpoint -q /var/lib/socialweb-computer || { truncate -s 40G /var/lib/swc-state.xfs && mkfs.xfs -q -m reflink=1 /var/lib/swc-state.xfs && install -d -m 0755 /var/lib/socialweb-computer && mount -o loop /var/lib/swc-state.xfs /var/lib/socialweb-computer; }"; | ||
const BIDDER_REFLINK: &str = "mountpoint -q /var/lib/socialweb-computer || { truncate -s 40G /var/lib/swc-state.xfs && mkfs.xfs -f -q -m reflink=1 /var/lib/swc-state.xfs && install -d -m 0755 /var/lib/socialweb-computer && mount -o loop /var/lib/swc-state.xfs /var/lib/socialweb-computer; }"; | ||
| ||
/// The installed bidder's kcp admin kubeconfig: install.BidderLayout, handles/<sha256(handle)[:10]>/kcp (root reads it). | ||
fn bidder_kubeconfig(handle: &str) -> String { | ||
| @@ -565,7 +592,7 @@ fn bidder_install(handle: &str, dids: &str) -> String { | ||
let spec = json!({ "options": [{ "name": "vouch", "value": dids }] }).to_string(); | ||
format!( | ||
"set -e; {BIDDER_REFLINK}; install -d -m 0755 /etc/socialweb-computer; install -m 0644 /home/stg/stg/net.json {BIDDER_NET}; printf %s '{spec}' > {BIDDER_SPEC}; chmod 0644 {BIDDER_SPEC}; {}", | ||
bg( | ||
bg_once( | ||
"bidder", | ||
format!( | ||
"/home/stg/stg/{BIN} install bidder --handle {handle} --market-network-file {BIDDER_NET} --bidder-spec-file {BIDDER_SPEC} --vmm qemu --compute-kinds vm,deno" | ||
| @@ -632,6 +659,11 @@ fn run_multi(run: Run<Value>) -> Result<Handle, String> { | ||
json!({ "name": format!("{base}-{v}"), "exec": exec }), | ||
), | ||
}; | ||
// a step whose command is safe to run again (idempotent): its command is kept until its result, for a rerun on a lost session | ||
let sshr = |s: &mut S, v: &str, id: &str, exec: String| { | ||
s.st["exec"][id] = json!(exec); | ||
ssh(v, id, exec) | ||
}; | ||
let put_what = |v: &str, step: &str, what: &str, remote: &str| match infra { | ||
true => host( | ||
&format!("{v}:{step}"), | ||
| @@ -716,6 +748,10 @@ fn run_multi(run: Run<Value>) -> Result<Handle, String> { | ||
)) | ||
} | ||
Event::Timer { id } if id == "deadline" => { | ||
if s.st["pending"]["pass"] == false { | ||
let r = s.st["pending"].clone(); | ||
return Ok(down(&mut s, h, r)); | ||
} | ||
let e = format!("not done by the deadline (phase {})", s.phase()); | ||
return Ok(down(&mut s, h, json!({ "pass": false, "error": e }))); | ||
} | ||
| @@ -723,6 +759,15 @@ fn run_multi(run: Run<Value>) -> Result<Handle, String> { | ||
let v = id["reinstall-".len()..].to_string(); | ||
h = h.call(ssh(&v, &format!("{v}:install"), install(s.st["prefix"].as_str().unwrap_or_default()))); | ||
} | ||
Event::Timer { id } if id.starts_with("rerun-") => { | ||
let cid = id["rerun-".len()..].to_string(); | ||
let v = cid.split_once(':').map(|(v, _)| v.to_string()).unwrap_or_default(); | ||
if let Some(exec) = s.st["exec"][cid.as_str()].as_str().map(String::from) { | ||
if !s.is("down") { | ||
h = h.call(ssh(&v, &cid, exec)); | ||
} | ||
} | ||
} | ||
Event::Timer { id } if id.starts_with("poll-") => { | ||
let (v, step) = id[5..].split_once(':').unwrap_or(("atproto", &id[5..])); | ||
let exec = if step == "bidder" { | ||
| @@ -854,6 +899,20 @@ fn run_multi(run: Run<Value>) -> Result<Handle, String> { | ||
if s.is("down") { | ||
return Ok(s.keep(h)); | ||
} | ||
if o["tries"].as_u64().is_some_and(|n| n > 1) { | ||
s.st["readings"]["putTries"][id.as_str()] = o["tries"].clone(); | ||
} | ||
if s.st["exec"][id.as_str()].is_string() { | ||
let n = s.st["sshTries"][id.as_str()].as_u64().unwrap_or(0); | ||
if !ok && text.contains("connection lost") && n < SSH_RETRIES { | ||
s.st["sshTries"][id.as_str()] = json!(n + 1); | ||
s.st["readings"]["sshRetries"][id.as_str()] = json!(n + 1); | ||
return Ok(s.keep(h.timer(&format!("rerun-{id}"), 10_000 * (n + 1)))); | ||
} | ||
if let Some(m) = s.st["exec"].as_object_mut() { | ||
m.remove(id.as_str()); | ||
} | ||
} | ||
match step.as_str() { | ||
"start" if v == "infra" && result.output().is_ok() => { | ||
s.st["key"] = o["sshKey"].clone(); | ||
| @@ -997,7 +1056,7 @@ fn run_multi(run: Run<Value>) -> Result<Handle, String> { | ||
"set -e; chmod 0755 {MESHD}; install -d -m 0700 /var/lib/socialweb/meshd; \ | ||
[ -s {MESH_SECRET} ] || (umask 077; od -An -tx1 -N32 /dev/urandom | tr -d ' \\n' > {MESH_SECRET}); {MESHD} identity --secret-file {MESH_SECRET}" | ||
); | ||
h = h.call(ssh(&v, &format!("{v}:id"), cmd)); | ||
h = h.call(sshr(&mut s, &v, &format!("{v}:id"), cmd)); | ||
} | ||
"id" if ok => { | ||
let endpoint = json_with(&text, "endpoint") | ||
| @@ -1021,11 +1080,11 @@ fn run_multi(run: Run<Value>) -> Result<Handle, String> { | ||
format!("ping -c1 -W2 {} >/dev/null", overlay(0)) | ||
}; | ||
let cmd = format!( | ||
"set -e; {}; (setsid nohup {MESHD} run --secret-file {MESH_SECRET} --roster /home/stg/stg/roster.json > /home/stg/meshd.log 2>&1 < /dev/null &); \ | ||
"set -e; {}; (pgrep -x socialweb-meshd >/dev/null || (setsid nohup {MESHD} run --secret-file {MESH_SECRET} --roster /home/stg/stg/roster.json > /home/stg/meshd.log 2>&1 < /dev/null &)); \ | ||
for i in $(seq 90); do {wait} && break; sleep 2; done; {wait} || {{ tail -c 2000 /home/stg/meshd.log; exit 1; }}; ip -br addr show swmesh0", | ||
write_file("/home/stg/stg/roster.json", &roster)? | ||
); | ||
h = h.call(ssh(n, &format!("{n}:mesh"), cmd)); | ||
h = h.call(sshr(&mut s, n, &format!("{n}:mesh"), cmd)); | ||
} | ||
} | ||
} | ||
| @@ -1035,7 +1094,7 @@ fn run_multi(run: Run<Value>) -> Result<Handle, String> { | ||
s.flag("up"); | ||
let dirs: Vec<&str> = ["", "/dev", "/dev/stg", "/dev/stg/network", "/dev/stg/network/guest-tls"].to_vec(); | ||
let dirs: Vec<String> = dirs.iter().map(|d| format!("/home/stg/stg/s{d}")).collect(); | ||
h = h.call(ssh("atproto", "atproto:tls-dir", format!("set -e; install -d -o stg -g stg -m 0700 {}; echo ok", dirs.join(" ")))); | ||
h = h.call(sshr(&mut s, "atproto", "atproto:tls-dir", format!("set -e; install -d -o stg -g stg -m 0700 {}; echo ok", dirs.join(" ")))); | ||
} | ||
if vms.iter().all(|(n, ..)| s.has(&format!("mesh:{n}"))) { | ||
s.st["readings"]["meshS"] = json!(s.t()); | ||
| @@ -1055,10 +1114,10 @@ fn run_multi(run: Run<Value>) -> Result<Handle, String> { | ||
"tls-key" if ok => { | ||
s.mark("up"); | ||
let cmd = format!( | ||
"set -e; cd {GUEST_TLS}; for f in ca.crt {NET_DOMAIN}.crt {NET_DOMAIN}.key; do mv $f.part $f; done; chmod 0600 {NET_DOMAIN}.key; chown -R stg:stg {GUEST_TLS}; {}", | ||
bg("up", swc(&format!("dev up {INST} --profile market-network --bidders 0 --network-bind {} --network-domain {NET_DOMAIN} --network-atirc-url {ATIRC_URL} --network-qr-origin {QR_ORIGIN} --host-backend proc --ready-timeout 90s --network-timeout 20m", overlay(0)))) | ||
"set -e; cd {GUEST_TLS}; for f in ca.crt {NET_DOMAIN}.crt {NET_DOMAIN}.key; do [ ! -e $f.part ] || mv $f.part $f; done; chmod 0600 {NET_DOMAIN}.key; chown -R stg:stg {GUEST_TLS}; {}", | ||
bg_once("up", swc(&format!("dev up {INST} --profile market-network --bidders 0 --network-bind {} --network-domain {NET_DOMAIN} --network-atirc-url {ATIRC_URL} --network-qr-origin {QR_ORIGIN} --host-backend proc --ready-timeout 90s --network-timeout 20m", overlay(0)))) | ||
); | ||
h = h.call(ssh("atproto", "atproto:up", cmd)); | ||
h = h.call(sshr(&mut s, "atproto", "atproto:up", cmd)); | ||
} | ||
// one ssh session at a time (the single-VM layout's rule): the host, then the suite tarball, then the run | ||
"put-host" if ok => { | ||
| @@ -1086,12 +1145,12 @@ fn run_multi(run: Run<Value>) -> Result<Handle, String> { | ||
"set -e; {}chmod 0755 {d}/swc-test-host; rm -rf {d}/suite; mkdir -p {d}/suite; tar -xzf {d}/suite.tgz -C {d}/suite; chown -R stg:stg {d}/suite; \ | ||
if [ -f {d}/agent-config.toml ]; then chown stg:stg {d}/agent-config.toml; chmod 0600 {d}/agent-config.toml; fi; {}; {}", | ||
format!("{}; ", s.st["netFile"].as_str().unwrap_or("true")), | ||
format!("{}; {}", atirc_up(), bg("qr", qr_up())), | ||
format!("{}; {}", atirc_up(), bg_once("qr", qr_up())), | ||
as_stg(&format!( | ||
"{d}/suite/tests/compositions/staging/trust.sh accounts {run_name}" | ||
)) | ||
); | ||
h = h.call(ssh("atproto", "atproto:accounts", cmd)); | ||
h = h.call(sshr(&mut s, "atproto", "atproto:accounts", cmd)); | ||
} | ||
"trust" if ok => { | ||
s.st["readings"]["trust"] = json!( | ||
| @@ -1109,7 +1168,7 @@ fn run_multi(run: Run<Value>) -> Result<Handle, String> { | ||
one("p1", 1), | ||
one("p2", 2) | ||
); | ||
h = h.call(ssh("atproto", "atproto:request", bg("request", both))); | ||
h = h.call(sshr(&mut s, "atproto", "atproto:request", bg_once("request", both))); | ||
} | ||
"suite" if ok => h = h.timer("poll-atproto:suite", 30_000), | ||
"suite-logs" => { | ||
| @@ -1124,11 +1183,33 @@ fn run_multi(run: Run<Value>) -> Result<Handle, String> { | ||
let r = s.st["pending"].clone(); | ||
return Ok(down(&mut s, h, r)); | ||
} | ||
"runs" => { | ||
s.st["readings"]["gateRuns"] = o; | ||
// a failed suite: then each bidder VM's and the gateway VM's journals and logs (the VMs go with the release) | ||
"runs" | "journals" => { | ||
let order: Vec<String> = (1..=bidders).map(bidder_vm).chain(["gateway".to_string()]).collect(); | ||
let next = if step == "runs" { | ||
s.st["readings"]["gateRuns"] = o; | ||
order.first().cloned() | ||
} else { | ||
s.st["readings"]["journals"][&v] = o; | ||
order.iter().position(|n| *n == v).and_then(|i| order.get(i + 1)).cloned() | ||
}; | ||
if let Some(n) = next { | ||
let minutes = args["deadlineMin"].as_u64().unwrap_or(120) + 30; | ||
return Ok(s.keep(h.call(ssh(&n, &format!("{n}:evidence"), evidence(&n, minutes))))); | ||
} | ||
let r = s.st["pending"].clone(); | ||
return Ok(down(&mut s, h, r)); | ||
} | ||
"evidence" => { | ||
let mut on = match infra { | ||
true => json!({ "name": RQ, "contract": cc(&v) }), | ||
false => json!({ "name": format!("{base}-{v}") }), | ||
}; | ||
on["dir"] = json!(EVIDENCE); | ||
on["to"] = json!(format!("journals-{v}")); | ||
on["all"] = json!(true); | ||
return Ok(s.keep(h.call(host(&format!("{v}:journals"), "logs.fetchRuns", on)))); | ||
} | ||
// each VM's memory after a poll that found the suite still running, one VM at a time (one ssh session at a time), then the next poll; the result is | ||
// only recorded (in the ticks), whatever it says | ||
"mem" => match vms | ||
| @@ -1173,7 +1254,7 @@ fn run_multi(run: Run<Value>) -> Result<Handle, String> { | ||
"" => h = h.timer(&format!("poll-{v}:{step}"), 10_000), | ||
"0" if step == "up" => { | ||
s.st["readings"]["upS"] = json!(s.since("up")); | ||
h = h.call(ssh( | ||
h = h.call(sshr(&mut s, | ||
"atproto", | ||
"atproto:status", | ||
swc(&format!("dev status {INST}")), | ||
| @@ -1186,7 +1267,7 @@ fn run_multi(run: Run<Value>) -> Result<Handle, String> { | ||
.filter(|l| l.starts_with("gateway.sh")) | ||
.collect::<Vec<_>>() | ||
); | ||
h = h.call(ssh( | ||
h = h.call(sshr(&mut s, | ||
"atproto", | ||
"atproto:trust", | ||
as_stg("/home/stg/stg/suite/tests/compositions/staging/trust.sh vouch"), | ||
| @@ -1215,7 +1296,7 @@ fn run_multi(run: Run<Value>) -> Result<Handle, String> { | ||
let cmd = format!( | ||
"{ROOT_HOST}; {}; {}", | ||
s.st["netFile"].as_str().unwrap_or("true"), | ||
bg( | ||
bg_once( | ||
"suite", | ||
as_stg(&format!( | ||
"{}/home/stg/stg/suite/tests/compositions/staging/suite.sh {run_name}", | ||
| @@ -1223,7 +1304,8 @@ fn run_multi(run: Run<Value>) -> Result<Handle, String> { | ||
)), | ||
) | ||
); | ||
return Ok(s.keep(h.call(ssh("atproto", "atproto:suite", cmd)))); | ||
let c = sshr(&mut s, "atproto", "atproto:suite", cmd); | ||
return Ok(s.keep(h.call(c))); | ||
} | ||
return Ok(down(&mut s, h, json!({ "pass": true }))); | ||
} | ||
| @@ -1279,7 +1361,7 @@ fn run_multi(run: Run<Value>) -> Result<Handle, String> { | ||
"kcp" if ok && bidder_index(&v).is_some_and(|i| i < bidders) => { | ||
let i = bidder_index(&v).unwrap_or(0) + 1; | ||
let next = bidder_vm(i); | ||
h = h.call(ssh(&next, &format!("{next}:kcp"), kcp_serve(&handle_of(&next), i))) | ||
h = h.call(sshr(&mut s, &next, &format!("{next}:kcp"), kcp_serve(&handle_of(&next), i))) | ||
} | ||
"kcp" if ok => { | ||
let mut list = vec![]; | ||
| @@ -1307,7 +1389,7 @@ fn run_multi(run: Run<Value>) -> Result<Handle, String> { | ||
let key = as_stg( | ||
"sh -c '[ -f ~/.ssh/id_ed25519 ] || ssh-keygen -q -t ed25519 -N \"\" -f ~/.ssh/id_ed25519; echo PUB $(cat ~/.ssh/id_ed25519.pub)'", | ||
); | ||
h = h.call(ssh( | ||
h = h.call(sshr(&mut s, | ||
"atproto", | ||
"atproto:kcpget", | ||
format!("set -e; {file}; {}; {key}", fetch.join("; ")), | ||
| @@ -1327,14 +1409,14 @@ fn run_multi(run: Run<Value>) -> Result<Handle, String> { | ||
}; | ||
s.st["suiteKey"] = json!(public); | ||
let first = bidder_vm(1); | ||
h = h.call(ssh(&first, &format!("{first}:authkey"), authorize(&public))); | ||
h = h.call(sshr(&mut s, &first, &format!("{first}:authkey"), authorize(&public))); | ||
} | ||
"authkey" if ok && bidder_index(&v).is_some() => { | ||
let public = s.st["suiteKey"].as_str().unwrap_or_default().to_string(); | ||
let next = bidder_vm(bidder_index(&v).unwrap_or(0) + 1); | ||
h = h.call(match bidder_index(&v).is_some_and(|i| i < bidders) { | ||
true => ssh(&next, &format!("{next}:authkey"), authorize(&public)), | ||
false => ssh("gateway", "gateway:authkey", authorize_stg(&public)), | ||
true => sshr(&mut s, &next, &format!("{next}:authkey"), authorize(&public)), | ||
false => sshr(&mut s, "gateway", "gateway:authkey", authorize_stg(&public)), | ||
}); | ||
} | ||
"authkey" if ok => { | ||
| @@ -1345,11 +1427,11 @@ fn run_multi(run: Run<Value>) -> Result<Handle, String> { | ||
hosts.join(" "), | ||
reach.join(" && ") | ||
)); | ||
h = h.call(ssh("atproto", "atproto:keyscan", scan)); | ||
h = h.call(sshr(&mut s, "atproto", "atproto:keyscan", scan)); | ||
} | ||
"keyscan" if ok => { | ||
s.mark("gateway"); | ||
h = h.call(ssh("atproto", "atproto:gateway", bg("gateway", gateway_up(&gateway_addr)))); | ||
h = h.call(sshr(&mut s, "atproto", "atproto:gateway", bg_once("gateway", gateway_up(&gateway_addr)))); | ||
} | ||
"accounts" if ok => { | ||
let dids = text | ||
| @@ -1371,7 +1453,7 @@ fn run_multi(run: Run<Value>) -> Result<Handle, String> { | ||
s.mark("bidders"); | ||
for v in (1..=bidders).map(bidder_vm) { | ||
let cmd = format!("set -e; {file}; {}", bidder_install(&handle_of(&v), &dids)); | ||
h = h.call(ssh(&v, &format!("{v}:bidder"), cmd)); | ||
h = h.call(sshr(&mut s, &v, &format!("{v}:bidder"), cmd)); | ||
} | ||
} | ||
"probe" => s.st["readings"]["gatewayPlcProbe"] = json!(text.trim()), | ||
| @@ -1402,7 +1484,7 @@ fn run_multi(run: Run<Value>) -> Result<Handle, String> { | ||
// the bidders' kcp kubeconfigs, then the host and the suite on the atproto VM, then trust.sh (the accounts and the | ||
// vouches prod has, plan 0047), then the stand-up probes as those accounts with the default policies | ||
let first = bidder_vm(1); | ||
h = h.call(ssh(&first, &format!("{first}:kcp"), kcp_serve(&handle_of(&first), 1))); | ||
h = h.call(sshr(&mut s, &first, &format!("{first}:kcp"), kcp_serve(&handle_of(&first), 1))); | ||
} | ||
} | ||
_ if !ok => { | ||
tests/gate.sh+1−1
| @@ -103,7 +103,7 @@ run_one() { | ||
elif [ $rc = 0 ]; then | ||
res=PASS note=$(jq -r '.dump // ""' <<<"$doc" 2>/dev/null) | ||
else | ||
res=FAIL note=$(jq -r '[.error, (.cleanupErrors // [] | join("; "))] | map(select(. != null and . != "")) | join(" | ") | .[0:200]' <<<"$doc" 2>/dev/null) | ||
res=FAIL note=$(jq -r '[.error, (.cleanupErrors // [] | join("; "))] | map(select(. != null and . != "")) | join(" | ") | gsub("[\n\r\t]"; " ")' <<<"$doc" 2>/dev/null) | ||
[ -n "$note" ] || note="exit $rc: $(tail -1 "$out/$r-$e.log" | cut -c1-200)" | ||
fi | ||
fi | ||