jukebox
All repositories: gitoria
6.9 KB
#!/usr/bin/env python3"""Exercise proc through HTTP delivery and runtime fault unwinding (Linux).Unlike memory.py's ABI counter, this catches allocations outside the plugin.Run after native/build.sh. Use --binary for an older compiler as a failing oracle.Only the explicit --port is used. Every server is stopped in finally."""import argparseimport jsonimport osimport refrom pathlib import Pathimport subprocessimport tempfileimport timeimport urllib.errorimport urllib.requestROOT = Path(__file__).resolve().parents[3]SOURCE = """import { NativeHttpServer, Response } from 'hl:http1'import { run, env } from 'hl:proc'inherit NativeHttpServerNumber port = toNumber(env('M615_PORT'))String mode = env('M615_MODE')String repo = env('M615_REPO')on request(req) {if (mode == 'fault') {r = run('git', ['-C', repo, 'log', '-1'])return new Response('unexpected')}if (mode == 'run') {r = run(['git', '-C', repo, 'log', '-1'])return new Response(r.lines.join(' '))}return new Response('ok')}listen()"""def main():ap = argparse.ArgumentParser(description=__doc__)ap.add_argument('--binary', default=os.environ.get('HL_BIN', str(ROOT / 'native/zig-out/bin/hybriel')))ap.add_argument('--port', type=int, required=True)ap.add_argument('--calls', type=int, default=20000)ap.add_argument('--mode', choices=['control', 'run', 'fault'], default='fault')ap.add_argument('--allow-growth', action='store_true')ap.add_argument('--fault-hook', action='store_true', help='allocate in a fault hook and verify exact bodies/logs under frequent GC')args = ap.parse_args()assert args.calls >= 20000, 'a short warmup hid this regression'with tempfile.TemporaryDirectory(prefix='proc-runtime-', dir=os.environ.get('TMPDIR')) as tmp:tmp = Path(tmp)source = tmp / 'server.hl'fixture = SOURCEif args.fault_hook:assert args.mode == 'fault'fixture = fixture.replace('on request(req) {', """on request(req) {hlOnFault((message) => {for (let j = 0; j < 64; j = j + 1) {garbage = ['pressure-' + j, 'x'.repeat(1024)]}console.log('hook: ' + message)})""")source.write_text(fixture)env = dict(os.environ, M615_PORT=str(args.port), M615_MODE=args.mode,M615_REPO=str(ROOT), HL_GC_THRESHOLD='128' if args.fault_hook else '1000', HL_ENV='development')env.pop('HL_COMPILER', None)if args.fault_hook:env['HL_GC_STATS'] = '1'with (tmp / 'server.log').open('w') as log:p = subprocess.Popen([args.binary, str(source)], cwd=ROOT, env=env, stdout=log, stderr=log)requests = 0located = Nonetry:def request():nonlocal requests, locatedtry:with urllib.request.urlopen(f'http://127.0.0.1:{args.port}/', timeout=5) as r:status, body = r.status, r.read()except urllib.error.HTTPError as r:status, body = r.code, r.read()if args.mode == 'fault':assert status == 500 and b"unknown option '0'" in body, (status, body)if args.fault_hook:message = "hl:proc run: unknown option '0' — the options are cwd, env, binary, stdin and timeout".encode()if located is None:match = re.fullmatch(rb'500 Internal Server Error\n\n(' + re.escape(str(source).encode()) + rb':(\d+):(\d+): ' + re.escape(message) + rb')\n', body)assert match, bodylocated = match[1]assert "r = run('git'" in fixture.splitlines()[int(match[2])-1]assert int(match[3]) == 38, bodyassert body == b'500 Internal Server Error\n\n' + located + b'\n', bodyelif args.mode == 'run':assert status == 200 and body.startswith(b'commit '), (status, body)else:assert status == 200 and body == b'ok', (status, body)requests += 1for _ in range(300):try:request()breakexcept OSError:assert p.poll() is None, (tmp / 'server.log').read_text()time.sleep(.1)else:raise AssertionError('server startup timeout')print(subprocess.check_output(['ss', '-ltnp', f'sport = :{args.port}'], text=True), flush=True)for _ in range(2000):request()samples = []for i in range(args.calls + 1):if i:request()if i % 2000 == 0:proc = Path(f'/proc/{p.pid}')status = (proc / 'status').read_text()rss = int(status.split('VmRSS:')[1].split()[0])swap = int(status.split('VmSwap:')[1].split()[0])samples.append([i, rss, swap, len(list((proc / 'fd').iterdir()))])if args.fault_hook:log.flush()lines = (tmp / 'server.log').read_bytes().splitlines()errors = [l for l in lines if l.startswith(b'Runtime error: ')]hooks = [l for l in lines if l.startswith(b'hook: ')]collections = sum(l.startswith(b'[hl-gc] #') for l in lines)assert errors == [b'Runtime error: ' + located] * requestsassert hooks == [b'hook: ' + located] * requestsassert collections >= requests, collectionsprint(json.dumps(dict(exact_bodies=requests, exact_log_lines=len(errors),exact_hook_lines=len(hooks), collections=collections,located=located.decode())), flush=True)print(json.dumps(dict(mode=args.mode, calls=args.calls, warmup=2000,samples=samples)), flush=True)if not args.allow_growth:# Include swapped pages so memory pressure cannot hide leaked pages.totals = [r[1] + r[2] for r in samples]assert max(totals) - min(totals) <= 512, samplesassert len({r[3] for r in samples}) == 1, samplesfinally:if p.poll() is None:assert Path(f'/proc/{p.pid}/cwd').resolve() == ROOTprint(subprocess.check_output(['ss', '-ltnp', f'sport = :{args.port}'], text=True), flush=True)p.terminate()p.wait(timeout=10)if __name__ == '__main__':main()
Branches
Latest commits
- bc09e1e8|||PR jukebox#20: reset virtual lists through resetKey (partial validation)mre
- 10f8a8c8Merge branch 'code-order' into mainJukebox
- 204fc828Merge branch 'day72' into mainJukebox
- 95f5faae|||PR jukebox#7 Drop needless let declarationsmre
- 33072bb5|||PR Record day72 gates and Chrome proofmre
- 95f2cd73|||PR Use typed parent methods for screen playback and local server facesmre
- 6422a020Sync media-player at 51c3818mre
- b582ba1cVendor complete Hybriel day72 plugin setmre
- 02dccbc9Merge branch 'records-1119' into mainJukebox
- a39e1c23|||PR Records: missions 013-015, reconnect fix livemre
- fc7db075Merge branch 'reconnect-retry' into mainJukebox
- ac6f4c6fL2: plain declaration for a in pickedNextmre
- 2f335086Review round 2: only an explicit queue pick drops pend (not the automatic advance); jb23 records every source changemre
- 3eb6695fReview fixes: action generation, queue pick clears pend, Previous/Next retry the decided request, typed handlersmre
- 7a53c0c2|||PR A tap lost to a dead socket plays after reconnect (mission 015)mre
- 1f0cd77bMerge branch 'records-day41' into mainJukebox
- 67be229f|||PR Records: day41 live (PR #4), mission 012, statusmre
- 0bb027daconductor: caramboleyo is the user, not owner/creatorApollo
- 04f5d9d5Merge branch 'day41' into mainJukebox
- 8ed6da45|||PR README: media-player pin df9e7dfmre