test(perf): observe owned counters at payload completion

Add opt-in, owned payload-completion cgroup witnesses without changing default receipts, terminal-counter semantics, resource limits, or REA public APIs. Preserve unknown and nonzero outcomes; verify ownership, observer capacity, cleanup, and actual SDK/model workflows.

Validation: eleven Python semantic tests, supported full-project typecheck and lint, controlled Linux failure/cancellation/capacity probes, real managed/WASM/Android SDK and Codex runs, and all 39 exact-head CI checks. Curated evidence retains mixed timings and whole-scope uncertainty.

Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
This commit is contained in:
Ysopwnable
2026-10-13 09:44:41 +08:00
committed by GitHub
co-authored by factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
parent 4773c152bc
commit ca2d15b3ee
6 changed files with 384 additions and 4 deletions
@@ -1,14 +1,18 @@
"""Run one owned experiment in a bounded, transient Linux systemd scope."""
import argparse
import hashlib
import json
import os
from pathlib import Path
import subprocess
import sys
import tempfile
import time
import uuid
from resource_payload import read_observation
def available_bytes():
for line in Path('/proc/meminfo').read_text().splitlines():
@@ -64,10 +68,14 @@ def stop_owned_scope(unit, process, group):
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--task-ceiling', type=int, default=192)
parser.add_argument('--observe-payload-exit', action='store_true',
help='Observe payload-exit counters before the cgroup observer exits')
parser.add_argument('command', nargs=argparse.REMAINDER)
options = parser.parse_args()
if options.task_ceiling <= 0:
parser.error('--task-ceiling must be positive')
if options.observe_payload_exit and options.task_ceiling < 2:
parser.error('--observe-payload-exit requires capacity for the observer and payload (at least 2 tasks)')
args = options.command
if args and args[0] == '--':
args = args[1:]
@@ -78,22 +86,41 @@ def main():
raise SystemExit('Refusing experiment: less than 8 GiB available')
unit = 'rea-efficiency-' + uuid.uuid4().hex + '.scope'
cpu = max(os.sched_getaffinity(0))
receipt_root = tempfile.TemporaryDirectory(prefix='rea-payload-counters-') if options.observe_payload_exit else None
receipt_path = Path(receipt_root.name) / 'observation.json' if receipt_root else None
release_path = Path(receipt_root.name) / 'release' if receipt_root else None
payload = args if receipt_root is None else [
sys.executable, str(Path(__file__).with_name('resource_payload.py')),
str(receipt_path), str(release_path), unit, *args,
]
command = [
'systemd-run', '--user', '--scope', '--unit=' + unit,
'-p', 'MemoryMax=4G', '-p', 'MemoryHigh=3G', '-p', 'MemorySwapMax=0',
'-p', 'CPUQuota=100%', '-p', 'TasksMax=' + str(options.task_ceiling),
'taskset', '-c', str(cpu), *args,
'taskset', '-c', str(cpu), *payload,
]
process = subprocess.Popen(command)
observer_sources = {
name: hashlib.sha256(Path(__file__).with_name(name).read_bytes()).hexdigest()
for name in ['resource-run.py', 'resource_payload.py']
} if options.observe_payload_exit else None
try:
process = subprocess.Popen(command)
except BaseException:
if receipt_root is not None:
receipt_root.cleanup()
raise
peak = 0
peak_tasks = 0
events = {}
cpu_stats = {}
abort = None
final_events = None
payload_observation = None
payload_group = None
code = None
group = None
started = time.monotonic()
try:
group = None
while process.poll() is None:
if group is None:
reply = subprocess.run(
@@ -104,6 +131,18 @@ def main():
path = reply.stdout.strip()
if path:
group = Path('/sys/fs/cgroup') / path.lstrip('/')
if receipt_path is not None and payload_observation is None and group is not None:
candidate = read_observation(receipt_path, unit)
if candidate is not None:
payload_observation = candidate
if candidate['control_group'] == str(group.relative_to('/sys/fs/cgroup')):
try:
actors = [int(x) for x in (group / 'cgroup.procs').read_text().splitlines()]
if candidate['observer_pid'] in actors:
payload_group = group
except (OSError, ValueError):
pass
release_path.touch(exist_ok=False)
current = group / 'memory.current' if group else None
if current and current.exists():
try:
@@ -132,6 +171,8 @@ def main():
# Read while the owned group still exists, before wait/cleanup can remove it.
final_events = final_resource_events(group)
code = process.wait()
if receipt_path is not None and payload_observation is None:
payload_observation = read_observation(receipt_path, unit)
except BaseException:
stop_owned_scope(unit, process, group)
raise
@@ -150,7 +191,22 @@ def main():
'resource_events_final': final_events,
'resource_counters_verified': final_events is not None,
'cpu_stat_last_observed': cpu_stats,
**({
'payload_resource_observation': payload_observation,
'payload_resource_observation_verified': (
payload_observation is not None
and payload_observation['payload_cleanup_verified']
and payload_group is not None and abort is None
and code is not None
and (payload_observation['payload_exit_code'] if payload_observation['payload_exit_code'] >= 0
else 128 - payload_observation['payload_exit_code']) == code
),
'payload_observation_scope': 'Counters at payload exit while observer remains alive; not final whole-scope counters.',
'payload_observer_sources_sha256': observer_sources,
} if options.observe_payload_exit else {}),
}), file=sys.stderr)
if receipt_root is not None:
receipt_root.cleanup()
raise SystemExit(125 if abort else code)