feat(poc-a): gate-a dynamic elf proof of concept (#13)

## Summary

PoC-A proved that dynamically loaded ELF plugins are workable on
ESP32-S3: plugins ship as signed MPB packages, are parsed by a strict
single-type parser shared between host and target, and execute from
PSRAM+IRAM within a measured admission budget. A 1000-cycle load/unload
soak passed 18/18 trend gates with stable heaps, the capacity ladder
settled at 8 coexisting plugin instances with a 3356B per-instance
budget, and the fail-closed corpus executed zero attacker-controlled
bytes across 14 rejection classes. Scheduler semantics (strand FIFO
ordering, completion-cancel CAS, quiesce-as-noop ABI) were validated on
both host (TSan suite) and target. **Gate-A verdict: PASS** — ADR-0002
moves to **Accepted** with the capacity value 8 and global-sum admission
rule as PoC-derived proposals.

## Changes by area

Grouped from `git log main..HEAD --oneline` (18 commits):

- **Vendored loader + patches**: `4bb53f2` vendor elf_loader 1.3.3 +
harness scaffold; `2f67b4f` plugin_iram loader patch with budget
consistency (p1-p5 patch series in `PATCHES.md`).
- **MPB toolchain**: `4793cc2` deterministic MPB manifest builder with
test signing; `408df44` strict single-type MPB parser shared
host/target; `796f9d2` host MPB corpus + policy CI lane.
- **Plugin pipeline + probes**: `21d2842` plugin pipeline and first
PSRAM execution on target; `cab9664` relocation/import allowlist matrix
with probes; `c5d6c6c` C++ feature rejection matrix.
- **Harness commands**: `e0e7159` generation coexistence with measured
admission budget; `2a37556` thousand-cycle lifecycle soak with heap
trend gate; `093a72b` on-target scheduler semantics validation (+
`eea3876` clang-format-18 sweep); `a302151` capacity ladder with signed
budget; `f34dc72` fail-closed corpus with execution sentinel.
- **Host prototypes**: `6198bca` strand FIFO prototype with TSan suite;
`1c3ad59` completion-cancel CAS and cleanup semantics.
- **Evidence + ADR/docs**: `887d0f7` Gate-A manifest and report;
`1c29e8a` ADR-0002 outcome + frozen PoC values.

## QA evidence

- `poc/evidence/poc-a-20260901/manifest.json` — 67-artifact hash index,
every sha256 recomputed at assembly.
- `poc/evidence/poc-a-20260901/GATE-A-REPORT.md` — full nine-item
development-plan §4 mapping; TEST-003 10/10 clauses.
- 14 verbatim per-task transcripts (`task-1` … `task-15-*.log`) + fresh
build artifacts (`build/frame_poc_a.map`, size components).
- Frozen in-repo references: `ALLOWLIST.md`, `REJECT-MATRIX.md`,
`ADMISSION-BUDGET.md`, `soak_samples_1000.csv`, fc corpus (33 committed
`.mpb` containers).
- F1-F4 final-wave verdicts: **APPROVE**.
- Key numbers: soak **18/18** trend gates over 1000 cycles; capacity
**8/8** instances, **3356B** per-instance; fc corpus **14 rejection
classes, zero attacker bytes executed**; **4 upstream loader defects
found and patched** (p1-p5).

## Requirement IDs (GOV-006)

ADR-0002; TEST-002, TEST-003; PLUG-001, PLUG-004, PLUG-008, PLUG-009;
MEM-001, MEM-003, MEM-007, MEM-008; LIFE-001, LIFE-002, LIFE-005,
LIFE-007; SEC-002, SEC-003, SEC-004, SEC-005; GH-003; GOV-004, GOV-005.

## Risks / known limitations

From `GATE-A-REPORT.md` §(f) plus the trade-off table:

1. **Capacity descent path 7-5 unexercised** — rung 8 passed first
attempt; rungs 7/6/5 and retry-once logic never ran on hardware
(untested against real OOM).
2. **No Wi-Fi in the harness (MEM-001 caveat)** — all PSRAM/IRAM budget
numbers are radio-off harness-class; product admission budgets must be
re-measured with the network stack active.
3. **On-target scheduler vectors are a subset of the host suite**
(256-node pool / 2e4 storm posts vs host 31000 / 1e5); consistency
declaration covers only the vectors actually run.
4. **Quiesce is a no-op by ABI semantics** — plugin ABI 1.2 has no
quiesce slot; NULL entry is defined as trivial success; real quiesce
coordination is later-gate work.
5. **MEMPROT=n trade-off** — `CONFIG_ESP_SYSTEM_MEMPROT=n` is required
for the IDF exec heap (`MALLOC_CAP_EXEC`) that `.plugin_iram` needs;
software-only PMP config, no eFuse burned (documented in `PATCHES.md`
p5); production must re-decide security vs plugin IRAM.
6. **Owner sign-off PENDING** — Gate-A PASS is the PoC team's verdict;
formal acceptance of ADR-0002 awaits the owner.

## Not in scope

- Product components (GOV-004) — this PR is PoC evidence only; no
product code paths change.
- **Merge is the owner's call** — do not merge without owner sign-off on
ADR-0002.

---------

Co-authored-by: ania-lain <[email protected]>
This commit is contained in:
Lain
2026-09-07 20:02:18 +08:00
committed by GitHub
co-authored by lain
parent 0018ebbb8f
commit e71842aa8a
163 changed files with 97525 additions and 50 deletions
+291
View File
@@ -0,0 +1,291 @@
#!/usr/bin/env python3
"""T10 capacity ladder: board runner + ladder judge (8 -> 7 -> 6 -> 5).
Drives the poc_a console over /dev/ttyACM0. Each ladder step runs
`poca capacity <N>` (N distinct-name plugins loaded into N live esp_elf_t
instances, check-fn round over all N resident generations, peak heap/stack
snapshot, reverse-order unload). Ladder policy (fail-closed):
- step N=8 first; a step PASSes only on the four [PASS-cap-N-*] markers
plus [PASS-capacity-N] and the device-side distinctness asserts;
- on failure at plugin k the rung records k-1 as provisionally achieved,
the SAME rung is retried once (transient guard), then the ladder
descends to the next rung;
- a PASS at any rung >= 5 ends the ladder (lower rungs stay unexecuted);
- if rung 5 also fails both attempts the gate FAILS (reported, never
masked: exit code 1 with every per-step failure reason printed).
Adversarial re-verification on the PASSING transcript (authority stays with
the on-device asserts; this runner independently re-checks):
n DISTINCT staging sha256 hashes observed (stale-embed guard), n DISTINCT
PSRAM text bases in the respond round, n DISTINCT returned/expected magic
pairs (misleading-success guard: one plugin called n times cannot produce
n distinct magics at n distinct text bases), crash-needle scan.
Serial conventions from T4/T5: "\r" line endings, quiesce-based prompt
detection, RTS pulse after opening the port, per-command + total timeouts.
"""
from __future__ import annotations
import argparse
import re
import sys
import time
import serial
PROMPT = "poca> "
LADDER = [8, 7, 6, 5]
CRASH_NEEDLES = (
"Guru Meditation",
"abort()",
"Backtrace:",
"rst:0x",
"WDT",
"panic",
"LoadProhibited",
"LoadStoreError",
"EXCVADDR",
)
CAP_LOAD_RE = re.compile(
r"\[cap-load\] idx=(\d+) name=(\w+) magic=(0x[0-9a-f]+) text=(0x[0-9a-f]+)"
r" staging=(\d+)B sha256=([0-9a-f]{64}) psram_free=(\d+)"
)
CAP_RESPOND_RE = re.compile(
r"\[cap-respond\] idx=(\d+) name=(\w+) fn=(0x[0-9a-f]+) text=(0x[0-9a-f]+)"
r" returned=(0x[0-9a-f]+) expected=(0x[0-9a-f]+) (MATCH|MISMATCH)"
)
CAPBUD_RE = re.compile(r"^CAPBUD,(.*)$", re.MULTILINE)
FAIL_RE = re.compile(r"\[FAIL-cap-(\d+)-(load|respond|unload)\](.*)")
class Board:
def __init__(self, port: str, baud: int = 115200, timeout: float = 1.0) -> None:
self.serial = serial.Serial(port, baud, timeout=timeout)
self.serial.setRTS(True)
time.sleep(0.1)
self.serial.setRTS(False)
time.sleep(0.1)
self.serial.reset_input_buffer()
def command(self, line: str, deadline_s: float = 300.0) -> str:
self.serial.write((line + "\r").encode())
self.serial.flush()
deadline = time.monotonic() + deadline_s
buf = b""
while time.monotonic() < deadline:
chunk = self.serial.read(4096)
if chunk:
buf += chunk
tail = buf.decode(errors="replace")
if tail.rstrip().endswith(PROMPT.rstrip()):
break
else:
time.sleep(0.1)
text = buf.decode(errors="replace")
print(f"--- poca> {line}")
print(text, end="" if text.endswith("\n") else "\n")
return text
def close(self) -> None:
self.serial.close()
def parse_capbud(text: str) -> dict[str, int]:
match = CAPBUD_RE.search(text)
if not match:
return {}
out: dict[str, int] = {}
for field in match.group(1).split(","):
if "=" in field:
key, value = field.split("=", 1)
out[key.strip()] = int(value.strip())
return out
def judge_step(text: str, count: int) -> tuple[bool, dict]:
"""Re-verify one `poca capacity <count>` transcript on the host."""
verdict: dict = {"fail_stage": None, "fail_step": None, "reasons": [], "capbud": {}}
for needle in CRASH_NEEDLES:
if needle in text:
verdict["reasons"].append(f"crash needle '{needle}'")
fail = FAIL_RE.search(text)
if fail:
verdict["fail_stage"] = fail.group(2)
step_match = re.search(r"step=(\d+)", fail.group(3))
verdict["fail_step"] = int(step_match.group(1)) if step_match else None
verdict["reasons"].append(f"device [FAIL-cap-{fail.group(1)}-{fail.group(2)}] marker")
for marker in (
f"[PASS-cap-{count}-load]",
f"[PASS-cap-{count}-respond]",
f"[PASS-cap-{count}-unload]",
f"[PASS-capacity-{count}]",
):
if marker not in text and not verdict["fail_stage"]:
verdict["reasons"].append(f"missing {marker}")
if "[cap-distinct] text_bases_all_distinct=yes" not in text:
verdict["reasons"].append("cap-distinct line not all-yes")
loads = CAP_LOAD_RE.findall(text)
responds = CAP_RESPOND_RE.findall(text)
verdict["loads"] = loads
verdict["responds"] = responds
verdict["capbud"] = parse_capbud(text)
if len(loads) != count:
verdict["reasons"].append(f"cap-load lines {len(loads)} != {count}")
if len({row[5] for row in loads}) != len(loads):
verdict["reasons"].append("staging sha256 hashes NOT all distinct (stale-embed suspect)")
if len({row[3] for row in loads}) != len(loads):
verdict["reasons"].append("load-phase text bases NOT all distinct")
if len(responds) != count:
verdict["reasons"].append(f"cap-respond lines {len(responds)} != {count}")
if any(row[6] != "MATCH" for row in responds):
verdict["reasons"].append("respond round MISMATCH present")
if len({row[4] for row in responds}) != len(responds):
verdict["reasons"].append("respond magics NOT all distinct (misleading-success suspect)")
if len({row[3] for row in responds}) != len(responds):
verdict["reasons"].append("respond text bases NOT all distinct")
if "[poca-cap] restored=yes" not in text:
verdict["reasons"].append("psram not restored to baseline")
verdict["ok"] = not verdict["reasons"]
return verdict["ok"], verdict
def format_kib(budget: dict[str, int]) -> str:
per = budget.get("per_instance", 0)
return f"{per} B ({per / 1024:.2f} KiB)"
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--port", default="/dev/ttyACM0")
parser.add_argument("--cmd-deadline", type=float, default=300.0)
parser.add_argument("--total-guard", type=float, default=1200.0)
args = parser.parse_args()
started = time.monotonic()
board = Board(args.port)
steps: list[dict] = []
achieved: int | None = None
try:
boot = board.command("", deadline_s=8.0)
if "poca> " not in boot:
boot = board.command("poca status", deadline_s=30.0)
if "poca> " not in boot:
print("FATAL: no console prompt after reboot")
return 2
status_before = board.command("poca status", deadline_s=30.0)
for rung in LADDER:
for attempt in (1, 2):
if time.monotonic() - started > args.total_guard:
print("FATAL: total-session guard expired")
return 2
text = board.command(f"poca capacity {rung}", deadline_s=args.cmd_deadline)
ok, verdict = judge_step(text, rung)
steps.append(
{
"rung": rung,
"attempt": attempt,
"ok": ok,
"fail_stage": verdict["fail_stage"],
"fail_step": verdict["fail_step"],
"reasons": verdict["reasons"],
"capbud": verdict["capbud"],
}
)
if ok:
achieved = rung
break
provisional = (
(verdict["fail_step"] or (rung + 1)) - 1
if verdict["fail_stage"] == "load"
else rung
)
print(
f"--- rung {rung} attempt {attempt} FAILED "
f"(stage={verdict['fail_stage']} step={verdict['fail_step']} "
f"provisional_achieved={provisional})"
)
if achieved is not None:
break
status_after = board.command("poca status", deadline_s=30.0)
finally:
board.close()
print("===== LADDER STEPS =====")
for step in steps:
head = f"rung {step['rung']} attempt {step['attempt']}: {'PASS' if step['ok'] else 'FAIL'}"
if step["fail_stage"]:
head += f" (stage={step['fail_stage']} step={step['fail_step']})"
print(head)
for reason in step["reasons"]:
print(f" reason: {reason}")
print("===== PER-INSTANCE COST TABLE (CAPBUD, measured per executed rung) =====")
print(
"rung psram_base psram_peak consumed per_instance mpb(B) arena(B) "
"iram_delta internal_delta"
)
for step in steps:
budget = step["capbud"]
if not budget:
continue
print(
f"{step['rung']:>4} {budget['psram_base_free']:>11} "
f"{budget['psram_peak_free']:>11} {budget['consumed']:>9} "
f"{budget['per_instance']:>13} {budget['mpb_size']:>6} "
f"{budget['arena_size']:>8} {budget['iram_delta']:>10} "
f"{budget['internal_delta']:>15}"
)
canary_before = re.search(r"entry queries so far: (\d+)", status_before)
canary_after = re.search(r"entry queries so far: (\d+)", status_after)
if canary_before and canary_after:
delta = int(canary_after.group(1)) - int(canary_before.group(1))
queries_expected = sum(
step["rung"]
if step["ok"] or step["fail_stage"] != "load"
else max(step["fail_step"] - 1, 0)
if step["fail_step"]
else 0
for step in steps
)
print(
f"canary: before={canary_before.group(1)} after={canary_after.group(1)} "
f"delta={delta} (expected={queries_expected}) "
f"{'OK' if delta == queries_expected else 'MISMATCH'}"
)
print("===== LADDER VERDICT =====")
if achieved is None:
print("CAPACITY LADDER: GATE FAIL - no rung >= 5 passed (report, not masked)")
return 1
final = next(step for step in reversed(steps) if step["ok"])
budget = final["capbud"]
per_kib = budget["per_instance"] / 1024
pool_pct = budget["consumed"] * 100.0 / (8 * 1024 * 1024)
print(f"achieved={achieved} (attempted rungs: {', '.join(str(s['rung']) for s in steps)})")
print(
f"per-instance cost: {format_kib(budget)} PSRAM "
f"(staging {budget['mpb_size']} B + loader arena {budget['arena_size']} B)"
)
print(f"{achieved}-instance peak: {budget['consumed']} B = {pool_pct:.2f}% of the 8 MiB pool")
print("SIGNED BUDGET LINE:")
print(
f"Capacity: {achieved} ACTIVE verified (8 attempted), per-instance cost "
f"{budget['per_instance']} B ({per_kib:.2f} KiB) PSRAM, {achieved}-instance peak "
f"{budget['consumed']} B = {pool_pct:.2f}% of the 8 MiB pool "
f"(IRAM delta {budget['iram_delta']} B, internal delta {budget['internal_delta']} B, "
f"largest_free_block unchanged), headroom to MEM-007 floor 5: "
f"{achieved}/5, MEM-007 -> ADR-0002 proposal value: {achieved} ACTIVE generations "
f"per distinct plugin name (PSRAM class; re-measure with Wi-Fi at the next gate)"
)
print(f"CAPACITY LADDER: PASS at {achieved}")
return 0
if __name__ == "__main__":
sys.exit(main())