diff --git a/docs/experiments/2026-10-28-s3-1-check_bootstrap.py b/docs/experiments/2026-10-28-s3-1-check_bootstrap.py new file mode 100644 index 00000000..14915198 --- /dev/null +++ b/docs/experiments/2026-10-28-s3-1-check_bootstrap.py @@ -0,0 +1,367 @@ +#!/usr/bin/env python3 +"""Checks for STRA-256 (S3.1): the laptop thresholds schema, its BOOTSTRAP instance, the safety-protocol page. + +Offline tool, Python 3.9, standard library only (production serving never runs this). +Reads files only: no GPU, no nvidia-smi, no powercfg, no setting is ever changed. + + check_bootstrap.py validate the BOOTSTRAP file against the schema + check_bootstrap.py --validate FILE validate FILE against the schema (STRA-292 uses this) + check_bootstrap.py --rules one line per stop / resume rule of SC3, marked field or numeric + check_bootstrap.py --criteria one row per floor of monitor.sh / lap_run.sh, each found by grep + check_bootstrap.py --self-test mutated BOOTSTRAP files must be rejected + check_bootstrap.py --bootstrap-fields the START-UP fields of the BOOTSTRAP file + options: --scripts-dir DIR (default /scripts/laptop), --schema FILE, --bootstrap FILE, --page FILE + +Exit codes: 0 ok, 1 check failed, 2 usage or unreadable input. +""" +import argparse +import copy +import json +import os +import re +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +STEM = "2026-10-28-s3-1-" +DEFAULT_SCHEMA = os.path.join(HERE, STEM + "laptop-thresholds.schema.json") +DEFAULT_BOOTSTRAP = os.path.join(HERE, STEM + "laptop-thresholds.bootstrap.json") +DEFAULT_PAGE = os.path.join(HERE, STEM + "laptop-safety-protocol.md") +DEFAULT_SCRIPTS = os.path.join(os.path.dirname(os.path.dirname(HERE)), "scripts", "laptop") + + +# ---------------------------------------------------------------- minimal JSON Schema interpreter + +def _type_ok(value, name): + if name == "object": + return isinstance(value, dict) + if name == "array": + return isinstance(value, list) + if name == "string": + return isinstance(value, str) + if name == "boolean": + return isinstance(value, bool) + if name == "integer": + return isinstance(value, int) and not isinstance(value, bool) + if name == "number": + return isinstance(value, (int, float)) and not isinstance(value, bool) + if name == "null": + return value is None + raise ValueError("unsupported type in schema: %r" % (name,)) + + +def validate(value, schema, path="$"): + """Return a list of error strings (empty = valid). Supports the keywords the schema file uses.""" + errors = [] + if "const" in schema and not (value == schema["const"] and type(value) == type(schema["const"])): + errors.append("%s: must be %r, got %r" % (path, schema["const"], value)) + if "enum" in schema and value not in schema["enum"]: + errors.append("%s: %r is not one of %r" % (path, value, schema["enum"])) + if "type" in schema and not _type_ok(value, schema["type"]): + errors.append("%s: expected %s, got %s" % (path, schema["type"], type(value).__name__)) + return errors + if isinstance(value, (int, float)) and not isinstance(value, bool): + if "minimum" in schema and value < schema["minimum"]: + errors.append("%s: %r is below the floor %r" % (path, value, schema["minimum"])) + if "maximum" in schema and value > schema["maximum"]: + errors.append("%s: %r is above the ceiling %r" % (path, value, schema["maximum"])) + if "exclusiveMinimum" in schema and value <= schema["exclusiveMinimum"]: + errors.append("%s: %r must be above %r" % (path, value, schema["exclusiveMinimum"])) + if isinstance(value, str) and "minLength" in schema and len(value) < schema["minLength"]: + errors.append("%s: shorter than %d" % (path, schema["minLength"])) + if isinstance(value, list): + if "minItems" in schema and len(value) < schema["minItems"]: + errors.append("%s: fewer than %d items" % (path, schema["minItems"])) + if "items" in schema: + for i, item in enumerate(value): + errors.extend(validate(item, schema["items"], "%s[%d]" % (path, i))) + for needed in schema.get("x-mustContain", []): + if needed not in value: + errors.append("%s: must contain %r" % (path, needed)) + if isinstance(value, dict): + props = schema.get("properties", {}) + for key in schema.get("required", []): + if key not in value: + errors.append("%s: missing required field %r" % (path, key)) + if schema.get("additionalProperties") is False: + for key in value: + if key not in props: + errors.append("%s: unknown field %r" % (path, key)) + for key, sub in props.items(): + if key in value: + errors.extend(validate(value[key], sub, "%s.%s" % (path, key))) + for branch in schema.get("allOf", []): + if "if" in branch: + if not validate(value, branch["if"], path): + errors.extend(validate(value, branch.get("then", {}), path)) + elif "else" in branch: + errors.extend(validate(value, branch["else"], path)) + else: + errors.extend(validate(value, branch, path)) + return errors + + +def load_json(path): + try: + with open(path, "r", encoding="utf-8") as handle: + return json.load(handle) + except (OSError, ValueError) as exc: + print("cannot read %s: %s" % (path, exc), file=sys.stderr) + sys.exit(2) + + +def dig(obj, dotted): + """Value at a dotted path, or raise KeyError.""" + for part in dotted.split("."): + obj = obj[part] + return obj + + +def schema_has(schema, dotted): + node = schema + for part in dotted.split("."): + node = node.get("properties", {}).get(part) + if node is None: + return False + return True + + +# ---------------------------------------------------------------- SC3 stop / resume rules + +# (id, marker, schema field, exact sentence that must appear on the page) +# field = the rule is a schema field (machine-checked by validate()). +# numeric = the rule is an exact numeric sentence on the page (checked by text here). +RULES = [ + ("R01", "numeric", "retry.max_reruns_per_arm_slot", "At most one re-run per arm slot."), + ("R02", "numeric", "retry.consecutive_invalid_pairs_end_block", "Two consecutive invalid pairs end the block."), + ("R03", "field", "cooldown.between_arms_s", "Cool-down 120 s between arms."), + ("R04", "field", "cooldown.after_abort_s", "Cool-down 600 s after any abort."), + ("R05", "field", "halt.on_events", "The first BSOD, unexpected reboot or STALL stops all laptop GPU work."), + ("R06", "field", "resume.requires_orchestrator_recorded_owner_inspection", + "Nothing resumes until the orchestrator records that the owner inspected the machine."), + ("R07", "field", "resume.source", "Resume is from the pair ledger."), + ("R08", "field", "resume.interrupted_pair_invalid", "A pair interrupted by a crash is invalid."), + ("R09", "field", "lock.one_gpu_job_at_a_time", "One laptop GPU job at a time (lock file)."), + ("R10", "field", "preconditions.on_unmet", + "If a precondition is not met the agent stops without changing anything and records 'owner precondition not met'."), + ("R11", "numeric", "under_load.stall_gap_s", "A gap of more than 10 s between two samples is a STALL and aborts the run."), + ("R12", "numeric", "run.cap_minutes", "Under BOOTSTRAP a run is capped at 15 minutes."), +] + + +def cmd_rules(args): + schema = load_json(args.schema) + boot = load_json(args.bootstrap) + try: + with open(args.page, "r", encoding="utf-8") as handle: + page = handle.read() + except OSError as exc: + print("cannot read %s: %s" % (args.page, exc), file=sys.stderr) + return 2 + flat = " ".join(page.split()) + bad = 0 + for rid, marker, field, sentence in RULES: + problems = [] + if marker not in ("field", "numeric"): + problems.append("unmarked") + if " ".join(sentence.split()) not in flat: + problems.append("sentence missing on page") + if not schema_has(schema, field): + problems.append("schema field missing") + else: + try: + dig(boot, field) + except KeyError: + problems.append("bootstrap value missing") + status = "ok" if not problems else "FAIL " + ", ".join(problems) + if problems: + bad += 1 + print("%s %-7s %-60s %s | %s" % (rid, marker, field, status, sentence)) + print("rules: %d, failing: %d" % (len(RULES), bad)) + return 1 if bad else 0 + + +# ---------------------------------------------------------------- floors of the two scripts + +def _gt(path, number): + return lambda b: dig(b, path) <= number + + +def _ge(path, number): + return lambda b: dig(b, path) >= number + + +# (id, criterion, [(script file, regex)], schema field, bootstrap check) +CRITERIA = [ + ("C01", "STALL > 10 s", [("monitor.sh", r"now - prev\)\) -gt 10")], "under_load.stall_gap_s", _gt("under_load.stall_gap_s", 10)), + ("C02", "limit < 100 W", [("monitor.sh", r"l\+0 > 0 && l\+0 < 100")], "under_load.power_limit_floor_w", _ge("under_load.power_limit_floor_w", 100)), + ("C03", "temperature > 90 C", [("monitor.sh", r'"\$\{temp:-0\}" -gt 90')], "under_load.temperature_ceiling_c", _gt("under_load.temperature_ceiling_c", 90)), + ("C04", "P5 with memory clock < 2000 MHz and throttle 0x4/0x20", + [("monitor.sh", r'= P5 \] && \[ "\$\{memc:-0\}" -lt 2000 \].*& 0x24')], "under_load.oem_profile", + lambda b: b["under_load"]["oem_profile"]["pstate"] == "P5" and b["under_load"]["oem_profile"]["memory_clock_mhz_below"] >= 2000 + and 4 in b["under_load"]["oem_profile"]["throttle_reason_bits"] and 32 in b["under_load"]["oem_profile"]["throttle_reason_bits"]), + ("C05", "preflight limit >= 100 W", [("lap_run.sh", r"l\+0 >= 100")], "idle_preflight.limit_min_w", _ge("idle_preflight.limit_min_w", 100)), + ("C06", "SW power cap or SW thermal slowdown active at idle refuses", + [("lap_run.sh", r"grep -E \"SW Power Cap\|SW Thermal Slowdown\""), ("lap_run.sh", r"REFUSED: SW power cap / thermal slowdown active at idle")], + "idle_preflight.sw_power_cap_active_refuses", + lambda b: b["idle_preflight"]["sw_power_cap_active_refuses"] is True and b["idle_preflight"]["sw_thermal_slowdown_active_refuses"] is True), + ("C07", "P5 at idle refuses", [("lap_run.sh", r"REFUSED: performance state P5")], "idle_preflight.p5_refuses", + lambda b: b["idle_preflight"]["p5_refuses"] is True), + ("C08", "COOLDOWN 120 s", [("lap_run.sh", r"COOLDOWN:-120")], "cooldown.between_arms_s", _ge("cooldown.between_arms_s", 120)), + ("C09", "RUN_TIMEOUT 900 s replaced by a caller parameter", [("lap_run.sh", r"RUN_TIMEOUT:-900")], "run.timeout_source", + lambda b: b["run"]["timeout_source"] == "caller_parameter"), + ("C10", "lock mkdir", [("lap_run.sh", r'mkdir "\$HOME/LAPTOP_GPU\.lock"')], "lock.method", + lambda b: b["lock"]["method"] in ("mkdir", "exclusive_create") and b["lock"]["one_gpu_job_at_a_time"] is True), + ("C11", "scripts read power.limit (N/A on this GPU); schema reads enforced.power.limit", + [("monitor.sh", r"power\.limit,temperature\.gpu"), ("lap_run.sh", r"Current Power Limit")], "power_limit_source", + lambda b: b["power_limit_source"] == "enforced.power.limit"), +] + + +def cmd_criteria(args): + boot = load_json(args.bootstrap) + schema = load_json(args.schema) + if not os.path.isdir(args.scripts_dir): + print("scripts directory not found: %s (use --scripts-dir)" % args.scripts_dir, file=sys.stderr) + return 2 + cache = {} + bad = 0 + print("id | criterion | script:line | schema field | bootstrap | result") + for cid, text, greps, field, check in CRITERIA: + where = [] + problems = [] + for fname, regex in greps: + if fname not in cache: + try: + with open(os.path.join(args.scripts_dir, fname), "r", encoding="utf-8") as handle: + cache[fname] = handle.read().splitlines() + except OSError as exc: + print("cannot read %s: %s" % (fname, exc), file=sys.stderr) + return 2 + hits = [i + 1 for i, line in enumerate(cache[fname]) if re.search(regex, line)] + if hits: + where.append("%s:%d" % (fname, hits[0])) + else: + problems.append("not found in %s: %s" % (fname, regex)) + if not schema_has(schema, field): + problems.append("schema field %s missing" % field) + try: + ok = bool(check(boot)) + except (KeyError, TypeError): + ok = False + if not ok: + problems.append("bootstrap does not satisfy the floor") + try: + shown = json.dumps(dig(boot, field)) + except KeyError: + shown = "-" + if problems: + bad += 1 + print("%s | %s | %s | %s | %s | %s" % (cid, text, ", ".join(where) or "-", field, shown, "ok" if not problems else "FAIL " + "; ".join(problems))) + print("criteria: %d, failing: %d" % (len(CRITERIA), bad)) + return 1 if bad else 0 + + +# ---------------------------------------------------------------- the other modes + +def cmd_validate(args, target): + schema = load_json(args.schema) + data = load_json(target) + errors = validate(data, schema) + if errors: + for err in errors: + print("INVALID: " + err) + return 1 + return 0 + + +def cmd_bootstrap(args): + code = cmd_validate(args, args.bootstrap) + if code == 0: + print("bootstrap valid against schema") + return code + + +MUTATIONS = [ + ("floor removed: under_load.power_limit_floor_w", lambda d: d["under_load"].pop("power_limit_floor_w")), + ("floor lowered: power_limit_floor_w = 90", lambda d: d["under_load"].__setitem__("power_limit_floor_w", 90)), + ("ceiling raised: temperature_ceiling_c = 95", lambda d: d["under_load"].__setitem__("temperature_ceiling_c", 95)), + ("stall gap widened: stall_gap_s = 30", lambda d: d["under_load"].__setitem__("stall_gap_s", 30)), + ("dead reading source: power.limit", lambda d: d.__setitem__("power_limit_source", "power.limit")), + ("fail-open run: unreadable.run = IGNORE", lambda d: d["unreadable"].__setitem__("run", "IGNORE")), + ("confirm_samples = 0", lambda d: d["sampling"].__setitem__("confirm_samples", 0)), + ("nvidia-smi timeout 30 s", lambda d: d["sampling"].__setitem__("nvidia_smi_timeout_s", 30)), + ("cool-down after abort 60 s", lambda d: d["cooldown"].__setitem__("after_abort_s", 60)), + ("OEM profile bits lose 0x20", lambda d: d["under_load"]["oem_profile"].__setitem__("throttle_reason_bits", [4, 1])), + ("preflight floor 50 W", lambda d: d["idle_preflight"].__setitem__("limit_min_w", 50)), + ("BOOTSTRAP without run cap", lambda d: d["run"].pop("cap_minutes")), + ("BOOTSTRAP countable", lambda d: d["records"].__setitem__("countable_under_bootstrap", True)), + ("unknown field", lambda d: d.__setitem__("extra", 1)), + ("validity band widened: spread 50 W", lambda d: d["validity_band"].__setitem__("spread_within_arm_w", 50)), + ("agent may change settings", lambda d: d["preconditions"].__setitem__("agent_may_change_settings", True)), +] + + +def cmd_self_test(args): + schema = load_json(args.schema) + boot = load_json(args.bootstrap) + if validate(boot, schema): + print("self-test: the unmutated bootstrap is already invalid", file=sys.stderr) + return 1 + survived = 0 + for name, mutate in MUTATIONS: + mutated = copy.deepcopy(boot) + mutate(mutated) + errors = validate(mutated, schema) + if errors: + print("rejected: %s -> %s" % (name, errors[0])) + else: + survived += 1 + print("NOT REJECTED: %s" % name) + print("self-test: %d mutations, %d survived" % (len(MUTATIONS), survived)) + return 1 if survived else 0 + + +def cmd_bootstrap_fields(args): + boot = load_json(args.bootstrap) + try: + line = "thresholds_source=%s run_cap_minutes=%s confirm_samples=%s nvidia_smi_timeout_s=%s band=%s/%s/%s" % ( + boot["thresholds_source"], boot["run"]["cap_minutes"], boot["sampling"]["confirm_samples"], + boot["sampling"]["nvidia_smi_timeout_s"], boot["validity_band"]["limit_floor_w"], + boot["validity_band"]["arms_mean_limit_within_w"], boot["validity_band"]["spread_within_arm_w"]) + except KeyError as exc: + print("bootstrap lacks field %s" % exc, file=sys.stderr) + return 1 + print(line) + return 0 + + +def main(argv=None): + parser = argparse.ArgumentParser(description="STRA-256 S3.1 checks (offline, stdlib only)") + parser.add_argument("--validate", metavar="FILE") + parser.add_argument("--rules", action="store_true") + parser.add_argument("--criteria", action="store_true") + parser.add_argument("--self-test", dest="self_test", action="store_true") + parser.add_argument("--bootstrap-fields", dest="bootstrap_fields", action="store_true") + parser.add_argument("--schema", default=DEFAULT_SCHEMA) + parser.add_argument("--bootstrap", default=DEFAULT_BOOTSTRAP) + parser.add_argument("--page", default=DEFAULT_PAGE) + parser.add_argument("--scripts-dir", dest="scripts_dir", default=DEFAULT_SCRIPTS) + args = parser.parse_args(argv) + if args.validate: + code = cmd_validate(args, args.validate) + if code == 0: + print("%s valid against schema" % args.validate) + return code + if args.rules: + return cmd_rules(args) + if args.criteria: + return cmd_criteria(args) + if args.self_test: + return cmd_self_test(args) + if args.bootstrap_fields: + return cmd_bootstrap_fields(args) + return cmd_bootstrap(args) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/docs/experiments/2026-10-28-s3-1-laptop-safety-protocol.md b/docs/experiments/2026-10-28-s3-1-laptop-safety-protocol.md new file mode 100644 index 00000000..f7126763 --- /dev/null +++ b/docs/experiments/2026-10-28-s3-1-laptop-safety-protocol.md @@ -0,0 +1,163 @@ +# S3.1 Laptop safety protocol, owner-precondition checklist and thresholds schema (STRA-256) + +Date: 2026-10-28. Leaf STRA-256 of STRA-245. Branch `claude/stra-256`, based on `claude/merge-opt` at `2457d81`. +Machine: any (this page is read, nothing on it is executed on the laptop). This leaf observes nothing and measures nothing. + +Files of this leaf (the only four paths it adds): + +- this page; +- `docs/experiments/2026-10-28-s3-1-laptop-thresholds.schema.json`, the SCHEMA of the thresholds file (the measured values come from S3.7, STRA-292 validates the S3.7 file against this schema); +- `docs/experiments/2026-10-28-s3-1-laptop-thresholds.bootstrap.json`, a START-UP instance of that schema; +- `docs/experiments/2026-10-28-s3-1-check_bootstrap.py`, a stdlib-only (Python 3.9) checker. + +Consumers: STRA-291 (watchdog), STRA-292 (validates the S3.7 thresholds file with `check_bootstrap.py --validate`), STRA-319 (`state.ps1`, the read-only reader), STRA-254. + +Sources read for this page: the scripts `scripts/laptop/monitor.sh` and `scripts/laptop/lap_run.sh` (guard), `scripts/dev/laptop-turbo.ps1` (owner setter), `docs/laptop-vs-vanilla.md` sections 1, 11 and 13, and the standing conventions SC3 and SC10 of STRA-245. + +## 1. Owner preconditions + +The laptop has had two BSODs (0x19C WIN32K_POWER_WATCHDOG_TIMEOUT, 2026-10-16 and 2026-10-23) under the OEM 30 W profile. Every precondition below is performed by the OWNER. No agent step sets any of them. An agent only READS and records. + +If a precondition is not met the agent stops without changing anything and records 'owner precondition not met'. An agent never changes a power, display, lock or sleep setting. + +### 1.1 The setter, cited as owner-run only + +`scripts/dev/laptop-turbo.ps1` is the OWNER-RUN SETTER, started by the owner, never by an agent: `powershell -ExecutionPolicy Bypass -File scripts\dev\laptop-turbo.ps1`. It is NOT a reader. What it does: + +- `powercfg /setactive ` (owner-run, inside laptop-turbo.ps1); +- `powercfg /change standby-timeout-ac 0`, `hibernate-timeout-ac 0` and `monitor-timeout-ac 0` (owner-run, inside laptop-turbo.ps1); +- `powercfg /setacvalueindex SUB_VIDEO VIDEOCONLOCK 0` (owner-run, inside laptop-turbo.ps1); +- it prints only the active scheme and one `nvidia-smi` line (name, `enforced.power.limit`, `power.max_limit`, SM clock, pstate). It does not print the sleep, hibernate or display timeouts and does not read the lock / sign-in requirement. + +Armoury Crate sets the GPU power limit (its performance mode); a script cannot. The script leaves the sign-in requirement to Settings. + +### 1.2 Checklist + +READ is the read-only command an agent runs through STRA-319 (`state.ps1`), or 'owner attestation only' where no read-only command exists. The agent records the output and compares it with EXPECTED VALUE. + +| # | Precondition (owner-run) | READ (agent, read-only) | EXPECTED VALUE | +| --- | --- | --- | --- | +| P1 | OEM Turbo scheme active | `powercfg /getactivescheme` | scheme name `Turbo` (note its GUID for P3, P4) | +| P2 | GPU power mode (Armoury Crate Turbo / Manual) | `nvidia-smi --query-gpu=enforced.power.limit,pstate --format=csv,noheader` | `enforced.power.limit` at or above 100 W (last seen 138.94 W after an owner run of the script; the state since then is unknown) and pstate not P5 at idle. That Turbo is selected in Armoury Crate beyond the limit it produces: owner attestation only | +| P3 | Charger connected | `Get-CimInstance Win32_Battery \| Select-Object BatteryStatus` | `BatteryStatus` 2 (on AC); no Win32_Battery instance: owner attestation only | +| P4 | Sleep and hibernate timeouts off on AC | `powercfg /q SUB_SLEEP` (settings STANDBYIDLE, HIBERNATEIDLE) | Current AC Power Setting Index `0x00000000` for both | +| P5 | Display-off timeouts off on AC | `powercfg /q SUB_VIDEO` (settings VIDEOIDLE, VIDEOCONLOCK) | Current AC Power Setting Index `0x00000000` for both | +| P6 | Lock / sign-in requirement | owner attestation only | Settings > Accounts > Sign-in options > 'require sign-in' = Never | +| P7 | Screen unlocked, session logged in | owner attestation only | unlocked at the start of every laptop GPU job and not locked by the owner during it | +| P8 | Owner has acknowledged the BSOD history and the exposure budget of section 6 | owner attestation only (recorded by the orchestrator) | acknowledgement naming the larger figure of section 6 | + +Notes: + +- The setter's commands appear in this page only in section 1.1, each labelled owner-run; no agent step sets any of them. +- P2 reads `enforced.power.limit`, not `power.limit` (section 4). +- A read that fails, is empty or is N/A is 'precondition not met' (fail closed), not 'assume fine'. +- The laptop state is unknown today (owner, 2026-10-28: 'До ноута я не підходив ще'); no laptop GPU job starts until the owner has run the setter and the orchestrator has recorded the P1-P8 reads. + +## 2. Stop and resume rules (SC3) + +Each rule is marked `field` (a field of the thresholds schema, checked by `check_bootstrap.py`) or `numeric` (an exact numeric sentence, checked by text). `python docs/experiments/2026-10-28-s3-1-check_bootstrap.py --rules` prints one line per rule. + +| id | marker | schema field | rule (exact sentence) | +| --- | --- | --- | --- | +| R01 | numeric | `retry.max_reruns_per_arm_slot` | At most one re-run per arm slot. | +| R02 | numeric | `retry.consecutive_invalid_pairs_end_block` | Two consecutive invalid pairs end the block. | +| R03 | field | `cooldown.between_arms_s` | Cool-down 120 s between arms. | +| R04 | field | `cooldown.after_abort_s` | Cool-down 600 s after any abort. | +| R05 | field | `halt.on_events` | The first BSOD, unexpected reboot or STALL stops all laptop GPU work. | +| R06 | field | `resume.requires_orchestrator_recorded_owner_inspection` | Nothing resumes until the orchestrator records that the owner inspected the machine. | +| R07 | field | `resume.source` | Resume is from the pair ledger. | +| R08 | field | `resume.interrupted_pair_invalid` | A pair interrupted by a crash is invalid. | +| R09 | field | `lock.one_gpu_job_at_a_time` | One laptop GPU job at a time (lock file). | +| R10 | field | `preconditions.on_unmet` | If a precondition is not met the agent stops without changing anything and records 'owner precondition not met'. | +| R11 | numeric | `under_load.stall_gap_s` | A gap of more than 10 s between two samples is a STALL and aborts the run. | +| R12 | numeric | `run.cap_minutes` | Under BOOTSTRAP a run is capped at 15 minutes. | + +R01-R10 are SC3 verbatim in substance; R11 is the monitor.sh stall rule SC3 refers to; R12 is the BOOTSTRAP cap of section 5. The native-Windows watchdog (S3.8, STRA-291) is mandatory for every laptop GPU job; its thresholds come from S3.7. + +## 3. The thresholds file schema + +`docs/experiments/2026-10-28-s3-1-laptop-thresholds.schema.json`. The numeric constraints are FLOORS: a file may be stricter than the scripts, never looser (a floor removed or lowered makes the file invalid; `--self-test` proves it with 16 mutations). + +IDLE-PREFLIGHT conditions are separated from UNDER-LOAD conditions, because P5 means different things in each: at idle P5 refuses the run; under load P5 together with a low memory clock and a throttle reason is the OEM-profile signature that aborts it (monitor.sh does not abort a plain P5 with reason 0x1 'idle' while the model is being loaded into VRAM, a clock ramp seen in T1_short). + +| block | field | floor | taken from | action | +| --- | --- | --- | --- | --- | +| `idle_preflight` | `limit_min_w` | >= 100 W | lap_run.sh `l+0 >= 100` | refuse | +| `idle_preflight` | `sw_power_cap_active_refuses`, `sw_thermal_slowdown_active_refuses` | true | lap_run.sh: SW Power Cap / SW Thermal Slowdown `: Active` at idle | refuse | +| `idle_preflight` | `p5_refuses` | true | lap_run.sh: performance state P5 at idle | refuse | +| `under_load` | `power_limit_floor_w` | limit < 100 W | monitor.sh `l+0 < 100` | kill, abort file | +| `under_load` | `temperature_ceiling_c` | > 90 C | monitor.sh `-gt 90` | kill, abort file | +| `under_load` | `stall_gap_s` | > 10 s | monitor.sh `now - prev ... -gt 10` | kill, STALL, all GPU work stops | +| `under_load.oem_profile` | `pstate`, `memory_clock_mhz_below`, `throttle_reason_bits` | P5, memory clock < 2000 MHz, throttle mask 0x4 (SW power cap) and 0x20 (SW thermal slowdown) = 0x24 | monitor.sh `= P5 ... -lt 2000 ... & 0x24` | kill, abort file | +| `run` | `timeout_source` | `caller_parameter` | lap_run.sh `RUN_TIMEOUT:-900` is replaced: a 900 s default would kill a ~1,300 s arm | timeout set by the caller | +| `cooldown` | `between_arms_s` | >= 120 s | lap_run.sh `COOLDOWN:-120` | wait | +| `cooldown` | `after_abort_s` | >= 600 s | SC3 | wait | +| `lock` | `method`, `path` | `mkdir` (or an exclusive create of the same name on native Windows), `$HOME/LAPTOP_GPU.lock` | lap_run.sh `mkdir "$HOME/LAPTOP_GPU.lock"` | one laptop GPU job at a time | +| `sampling` | `confirm_samples` | >= 1, default 1 | monitor.sh triggers on the first sample; S3.7 may raise it | - | +| `sampling` | `nvidia_smi_timeout_s` | 1..5 | F12: a call that exceeds 5 s counts as a missing sample | fail closed | +| `sampling` | `stall_check_off_sampler_thread` | true | F12: a hung nvidia-smi cannot hide a stall | - | +| `unreadable` | `preflight`, `run` | `REFUSE`, `ABORT` | section 4 | fail closed | +| `validity_band` | `limit_floor_w`, `arms_mean_limit_within_w`, `spread_within_arm_w` | 100 W, <= 10 W, <= 20 W | E2 stable-limit band (BA round 2 D7) | pair validity, section 7 | +| `records` | `must_carry`, `countable_under_bootstrap` | `thresholds_source`, `thresholds_sha256`; false | F12 | section 5 | + +`python docs/experiments/2026-10-28-s3-1-check_bootstrap.py --criteria` prints one row per criterion and greps each number in `scripts/laptop/monitor.sh` or `scripts/laptop/lap_run.sh`, with the line, so a reviewer can diff them. + +## 4. Divergence from the scripts + +`monitor.sh` queries `power.limit` (`--query-gpu=...,power.limit,...`) and `lap_run.sh` preflight parses 'Current Power Limit' of `nvidia-smi -q`. On the laptop GPU `power.limit` is N/A (commit 96484f0: only `enforced.power.limit` works; `laptop-turbo.ps1` reads it for that reason). The consequences on the target machine: + +- `monitor.sh`: the reading is empty, `${lim:-0}` becomes 0, and the test `l > 0 && l < 100` is false, so its 'limit below 100 W' check can NEVER fire. `docs/laptop-vs-vanilla.md` section 13 records a drop from 110-126 W to 51 W (P3) that the guard did not catch. +- `lap_run.sh`: the reading is empty, so the preflight REFUSES every run (`REFUSED: power limit ?`). + +A thresholds file that copied 'exactly the monitor.sh floors' would copy a check that is dead on the target. Therefore: + +- the schema field `power_limit_source` is `enforced.power.limit` (the only allowed value, default); the value 100 W is kept on that source; +- an N/A, empty or non-numeric reading FAILS CLOSED, in preflight (the run is refused) and during the run (the run is aborted): `unreadable.preflight` = `REFUSE`, `unreadable.run` = `ABORT`; +- the two scripts are not edited by this leaf (SC10: they are PORTED by S3.8, not reused silently and not dropped); the port must read `power_limit_source`. + +## 5. The BOOTSTRAP instance (F12) + +`docs/experiments/2026-10-28-s3-1-laptop-thresholds.bootstrap.json` reproduces every criterion of section 3 on the enforced limit. It breaks the deadlock between the watchdog (STRA-291), which needs thresholds, and S3.7, which measures them with the watchdog. It is START-UP ONLY: + +- Under BOOTSTRAP a run is capped at 15 minutes (`run.cap_minutes` = 15). +- Every record carries `thresholds_source` and the sha256 of the thresholds file (`records.must_carry`). +- The validator (STRA-246) rejects a countable pair recorded under BOOTSTRAP (`records.countable_under_bootstrap` is false). +- Basis of the 100 W floor: the recorded good run at 110.0-126.6 W (`docs/laptop-vs-vanilla.md` section 11, `g2-vanilla-noskip`) and the bad event at 51 W (section 13). +- `confirm_samples` is 1 (monitor.sh's immediate trigger); the per-call `nvidia-smi` timeout is 5 s and counts as a missing sample; the stall is checked off the sampler's thread. + +`python docs/experiments/2026-10-28-s3-1-check_bootstrap.py --bootstrap-fields` prints these START-UP fields. + +## 6. Exposure budget + +From the arm times of `docs/laptop-vs-vanilla.md` (ours 1,226 s run A and 1,281 s run A3, mean about 1,253 s; vanilla default 1,341 s; vanilla with the skip off 1,416.6 s, sections 1, 4, 10 and 11) one 3-arm block is 4,010 s, plus three 120 s cool-downs. + +- The 30-pair series: 30 x (4,010 + 3 x 120) s = 36.4 h wall and 33.4 GPU-hours (30 x 4,010 s). With re-runs about 45-49 h wall. +- Diagnostics and sweeps: about 10 GPU-hours. +- PLUS about 21.7 GPU-hours for every alternative that does not exit as SLOWER and for every FIXED end-to-end component (30 pairs x 2 arms x 1,300 s; BA comment dabfd08e). + +The owner's acknowledgement (OR4, precondition P8) must name the larger figure: 33.4 + 10 GPU-hours for the series and diagnostics, plus 21.7 GPU-hours per such alternative or fixed component. + +These are planning figures from the cited arm times, not measurements of this leaf. + +## 7. Validity band of E2 + +The 'stable limit' of E2 is a schema block `validity_band`, applied to the power-limit sample series after a run (validity, not safety; abort is section 3): the limit stays at or above 100 W, the means of the limits of the arms of a pair are within 10 W, and the spread within one arm is at most 20 W (BA round 2 D7). The recorded good run (110.0-126.6 W, spread 16.6 W) is inside the band. `--bootstrap-fields` prints `band=100/10/20`. + +## 8. Checks + +Run from the repository root, Python 3.9, no packages: + +| command | expected | +| --- | --- | +| `python docs/experiments/2026-10-28-s3-1-check_bootstrap.py` | exit 0, `bootstrap valid against schema` | +| `... --validate ` | exit 0 when the file validates (STRA-292) | +| `... --rules` | exit 0, one line per rule of section 2 | +| `... --criteria` | exit 0, one row per criterion of section 3 with the script line | +| `... --self-test` | exit 0, every mutated bootstrap rejected | +| `... --bootstrap-fields` | exit 0, `thresholds_source=BOOTSTRAP run_cap_minutes=15 confirm_samples=1 nvidia_smi_timeout_s=5 band=100/10/20` | + +## 9. Not verified here + +- Nothing was run on the laptop; no `nvidia-smi`, `powercfg` or Win32_Battery read was made. The commands of section 1.2 are the ones the leaf prescribes; their exact output format on the laptop is checked by STRA-319. +- The scripts' behaviour on N/A is derived from reading them and from commit 96484f0, not from a run. +- The arm times of section 6 are those of the cited documents; the 1,300 s per arm and the 21.7 GPU-hours are the planning figures of STRA-245. diff --git a/docs/experiments/2026-10-28-s3-1-laptop-thresholds.bootstrap.json b/docs/experiments/2026-10-28-s3-1-laptop-thresholds.bootstrap.json new file mode 100644 index 00000000..b5309e49 --- /dev/null +++ b/docs/experiments/2026-10-28-s3-1-laptop-thresholds.bootstrap.json @@ -0,0 +1,43 @@ +{ + "schema_version": 1, + "thresholds_source": "BOOTSTRAP", + "power_limit_source": "enforced.power.limit", + "unreadable": {"preflight": "REFUSE", "run": "ABORT"}, + "sampling": { + "interval_s": 1, + "nvidia_smi_timeout_s": 5, + "timeout_counts_as_missing_sample": true, + "stall_check_off_sampler_thread": true, + "confirm_samples": 1 + }, + "idle_preflight": { + "limit_min_w": 100, + "sw_power_cap_active_refuses": true, + "sw_thermal_slowdown_active_refuses": true, + "p5_refuses": true + }, + "under_load": { + "power_limit_floor_w": 100, + "temperature_ceiling_c": 90, + "stall_gap_s": 10, + "oem_profile": {"pstate": "P5", "memory_clock_mhz_below": 2000, "throttle_reason_bits": [4, 32]} + }, + "run": {"timeout_source": "caller_parameter", "cap_minutes": 15}, + "cooldown": {"between_arms_s": 120, "after_abort_s": 600}, + "retry": {"max_reruns_per_arm_slot": 1, "consecutive_invalid_pairs_end_block": 2}, + "halt": {"on_events": ["BSOD", "UNEXPECTED_REBOOT", "STALL"], "scope": "ALL_LAPTOP_GPU_WORK"}, + "resume": { + "requires_orchestrator_recorded_owner_inspection": true, + "source": "pair_ledger", + "interrupted_pair_invalid": true + }, + "lock": {"method": "mkdir", "path": "$HOME/LAPTOP_GPU.lock", "one_gpu_job_at_a_time": true}, + "preconditions": {"on_unmet": "STOP_NO_CHANGE_RECORD_OWNER_PRECONDITION_NOT_MET", "agent_may_change_settings": false}, + "validity_band": {"limit_floor_w": 100, "arms_mean_limit_within_w": 10, "spread_within_arm_w": 20}, + "records": {"must_carry": ["thresholds_source", "thresholds_sha256"], "countable_under_bootstrap": false}, + "basis": { + "limit_floor_w": "recorded good run 110.0-126.6 W (docs/laptop-vs-vanilla.md section 11) against the bad event at 51 W (section 13)", + "floors": "scripts/laptop/monitor.sh and scripts/laptop/lap_run.sh at claude/merge-opt 2457d81", + "start_up_only": "BOOTSTRAP serves STRA-254 and STRA-292 until S3.7 supplies measured values; no countable pair is recorded under it" + } +} diff --git a/docs/experiments/2026-10-28-s3-1-laptop-thresholds.schema.json b/docs/experiments/2026-10-28-s3-1-laptop-thresholds.schema.json new file mode 100644 index 00000000..a373db22 --- /dev/null +++ b/docs/experiments/2026-10-28-s3-1-laptop-thresholds.schema.json @@ -0,0 +1,186 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "leleka/docs/experiments/2026-10-28-s3-1-laptop-thresholds.schema.json", + "title": "Laptop GPU watchdog thresholds (STRA-256 S3.1)", + "description": "Schema of the thresholds file read by the native-Windows watchdog (STRA-291), validated by STRA-292 and filled with measured values by S3.7. Every numeric constraint is a FLOOR taken from scripts/laptop/monitor.sh (runtime) or scripts/laptop/lap_run.sh (preflight): a file may be stricter, never looser. Interpreted by docs/experiments/2026-10-28-s3-1-check_bootstrap.py (stdlib only). Extra keyword x-mustContain: the array must contain every listed value.", + "type": "object", + "additionalProperties": false, + "required": [ + "schema_version", "thresholds_source", "power_limit_source", "unreadable", "sampling", + "idle_preflight", "under_load", "run", "cooldown", "retry", "halt", "resume", "lock", + "preconditions", "validity_band", "records" + ], + "properties": { + "schema_version": {"const": 1}, + "thresholds_source": { + "enum": ["BOOTSTRAP", "S3.7"], + "description": "BOOTSTRAP = the start-up instance of STRA-256 (cap 15 minutes per run, never countable); S3.7 = measured values." + }, + "power_limit_source": { + "enum": ["enforced.power.limit"], + "default": "enforced.power.limit", + "description": "nvidia-smi field the power limit is read from. power.limit is N/A on the laptop GPU (commit 96484f0), so it is not an allowed value; the scripts monitor.sh and lap_run.sh read it and diverge here (page, section 'Divergence from the scripts')." + }, + "unreadable": { + "type": "object", + "additionalProperties": false, + "required": ["preflight", "run"], + "description": "FAIL CLOSED: an N/A, empty or non-numeric reading of power_limit_source (or of any field a rule needs) refuses the run in preflight and aborts it during the run.", + "properties": { + "preflight": {"const": "REFUSE"}, + "run": {"const": "ABORT"} + } + }, + "sampling": { + "type": "object", + "additionalProperties": false, + "required": ["interval_s", "nvidia_smi_timeout_s", "timeout_counts_as_missing_sample", "stall_check_off_sampler_thread", "confirm_samples"], + "properties": { + "interval_s": {"type": "integer", "minimum": 1, "maximum": 1, "description": "monitor.sh samples at 1 Hz (MON_INTERVAL default 1)."}, + "nvidia_smi_timeout_s": {"type": "integer", "minimum": 1, "maximum": 5, "description": "Per-call nvidia-smi timeout; a timeout counts as a missing sample (fail closed)."}, + "timeout_counts_as_missing_sample": {"const": true}, + "stall_check_off_sampler_thread": {"const": true, "description": "The stall gap is checked by a thread other than the sampler, so a hung nvidia-smi cannot hide a stall."}, + "confirm_samples": {"type": "integer", "minimum": 1, "default": 1, "description": "Consecutive samples a runtime condition must hold before the abort. 1 = monitor.sh's immediate trigger (default); S3.7 may raise it."} + } + }, + "idle_preflight": { + "type": "object", + "additionalProperties": false, + "required": ["limit_min_w", "sw_power_cap_active_refuses", "sw_thermal_slowdown_active_refuses", "p5_refuses"], + "description": "Conditions checked at IDLE, before the run (lap_run.sh preflight). A violation REFUSES the run (exit 4 in the script).", + "properties": { + "limit_min_w": {"type": "number", "minimum": 100, "description": "Refuse unless enforced limit >= this (lap_run.sh: l+0 >= 100)."}, + "sw_power_cap_active_refuses": {"const": true}, + "sw_thermal_slowdown_active_refuses": {"const": true}, + "p5_refuses": {"const": true, "description": "At idle a P5 state is a refusal."} + } + }, + "under_load": { + "type": "object", + "additionalProperties": false, + "required": ["power_limit_floor_w", "temperature_ceiling_c", "stall_gap_s", "oem_profile"], + "description": "Conditions checked WHILE the job runs (monitor.sh). A violation kills the job and writes the abort file.", + "properties": { + "power_limit_floor_w": {"type": "number", "minimum": 100, "description": "Abort when enforced limit < this (monitor.sh: l > 0 && l < 100). With N/A the script's test never fires; here an unreadable value aborts (unreadable.run)."}, + "temperature_ceiling_c": {"type": "number", "maximum": 90, "exclusiveMinimum": 0, "description": "Abort when temperature > this (monitor.sh: -gt 90)."}, + "stall_gap_s": {"type": "number", "maximum": 10, "exclusiveMinimum": 0, "description": "Abort and STALL when two consecutive samples are more than this far apart (monitor.sh: -gt 10)."}, + "oem_profile": { + "type": "object", + "additionalProperties": false, + "required": ["pstate", "memory_clock_mhz_below", "throttle_reason_bits"], + "description": "Under load, P5 with a low memory clock and a SW power cap / SW thermal slowdown reason is the OEM profile signature.", + "properties": { + "pstate": {"const": "P5"}, + "memory_clock_mhz_below": {"type": "integer", "minimum": 2000, "description": "monitor.sh: memory clock < 2000 MHz."}, + "throttle_reason_bits": { + "type": "array", + "minItems": 2, + "items": {"type": "integer", "minimum": 1}, + "x-mustContain": [4, 32], + "description": "clocks_throttle_reasons.active bits: 0x4 SW power cap, 0x20 SW thermal slowdown (mask 0x24)." + } + } + } + } + }, + "run": { + "type": "object", + "additionalProperties": false, + "required": ["timeout_source"], + "properties": { + "timeout_source": {"const": "caller_parameter", "description": "lap_run.sh's RUN_TIMEOUT default 900 s would kill a ~1,300 s arm; the ported watchdog takes the timeout from its caller."}, + "cap_minutes": {"type": "integer", "minimum": 1, "maximum": 15, "description": "Hard cap per run. Required for BOOTSTRAP (15)."} + } + }, + "cooldown": { + "type": "object", + "additionalProperties": false, + "required": ["between_arms_s", "after_abort_s"], + "properties": { + "between_arms_s": {"type": "integer", "minimum": 120, "description": "lap_run.sh COOLDOWN default 120; SC3."}, + "after_abort_s": {"type": "integer", "minimum": 600, "description": "SC3: 600 s after any abort."} + } + }, + "retry": { + "type": "object", + "additionalProperties": false, + "required": ["max_reruns_per_arm_slot", "consecutive_invalid_pairs_end_block"], + "properties": { + "max_reruns_per_arm_slot": {"type": "integer", "minimum": 0, "maximum": 1}, + "consecutive_invalid_pairs_end_block": {"type": "integer", "minimum": 1, "maximum": 2} + } + }, + "halt": { + "type": "object", + "additionalProperties": false, + "required": ["on_events", "scope"], + "properties": { + "on_events": {"type": "array", "minItems": 3, "items": {"enum": ["BSOD", "UNEXPECTED_REBOOT", "STALL"]}, "x-mustContain": ["BSOD", "UNEXPECTED_REBOOT", "STALL"]}, + "scope": {"const": "ALL_LAPTOP_GPU_WORK"} + } + }, + "resume": { + "type": "object", + "additionalProperties": false, + "required": ["requires_orchestrator_recorded_owner_inspection", "source", "interrupted_pair_invalid"], + "properties": { + "requires_orchestrator_recorded_owner_inspection": {"const": true}, + "source": {"const": "pair_ledger"}, + "interrupted_pair_invalid": {"const": true} + } + }, + "lock": { + "type": "object", + "additionalProperties": false, + "required": ["method", "path", "one_gpu_job_at_a_time"], + "properties": { + "method": {"enum": ["mkdir", "exclusive_create"], "description": "lap_run.sh: mkdir $HOME/LAPTOP_GPU.lock (atomic directory). The native-Windows port may use an exclusive create of the same name."}, + "path": {"type": "string", "minLength": 1}, + "one_gpu_job_at_a_time": {"const": true} + } + }, + "preconditions": { + "type": "object", + "additionalProperties": false, + "required": ["on_unmet", "agent_may_change_settings"], + "properties": { + "on_unmet": {"const": "STOP_NO_CHANGE_RECORD_OWNER_PRECONDITION_NOT_MET"}, + "agent_may_change_settings": {"const": false} + } + }, + "validity_band": { + "type": "object", + "additionalProperties": false, + "required": ["limit_floor_w", "arms_mean_limit_within_w", "spread_within_arm_w"], + "description": "E2 'stable limit' band (BA round 2 D7), applied to the sample series AFTER the run; it is validity, not safety.", + "properties": { + "limit_floor_w": {"type": "number", "minimum": 100}, + "arms_mean_limit_within_w": {"type": "number", "exclusiveMinimum": 0, "maximum": 10}, + "spread_within_arm_w": {"type": "number", "exclusiveMinimum": 0, "maximum": 20} + } + }, + "records": { + "type": "object", + "additionalProperties": false, + "required": ["must_carry", "countable_under_bootstrap"], + "properties": { + "must_carry": {"type": "array", "items": {"type": "string"}, "x-mustContain": ["thresholds_source", "thresholds_sha256"]}, + "countable_under_bootstrap": {"const": false} + } + }, + "basis": { + "type": "object", + "description": "Free text: where the numbers come from. Not interpreted." + } + }, + "allOf": [ + { + "if": {"properties": {"thresholds_source": {"const": "BOOTSTRAP"}}, "required": ["thresholds_source"]}, + "then": { + "properties": { + "run": {"required": ["cap_minutes"], "properties": {"cap_minutes": {"const": 15}}} + } + } + } + ] +}