notes
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
- 996768bf|||PR WIP sequence note creation before provisional-id adoptionAtlas
- c49ce093|||PR WIP remove notes polling and use framework reachabilityAtlas
- c028ac61Merge branch 'notes-pr7-kunibert' into mainAtlas
- 9cc92bdfKeep conflict and history fixes while awaiting queued save supportAtlas
- a5c27cb6Allow real edits back to earlier text and honor configured identAtlas
- 15c46ced|||PR Preserve note edits, conflict bases and visible historyAtlas
- 4c6e0bf6Merge branch 'notes13-day61' into mainAtlas
- eb51864f|||PR Back/Forward via navigate, server drafts, Hybriel day61Atlas
- 3537cf7eMerge branch 'vendor-day59' into mainAtlas
- c13d188b|||PR Vendor Hybriel day59Atlas
- 24c95433Merge branch 'notes17-ghost-note' into mainAtlas
- ae1075b2Preserve rejected drafts during note ID adoptionAtlas
- 383cce23|||PR Prevent saved local edits from restoring deleted notesAtlas
- 99ca1cf6Merge branch 'vendor-day56' into mainAtlas
- 649cef37|||PR Vendor Hybriel day56Atlas
- aadd0abcMerge branch 'hl-standard-2' into mainAtlas
- 52ffac9f|||PR Keyboard and reload checks for the notes gate (HL-STANDARD F21, F5)Atlas
- 617ee8c0Merge branch 'hl-standard' into mainAtlas
- 452458ee|||PR Type the function parameters of notes' own .hl files (HL-STANDARD L10)Atlas
- 23758cd6Re-vendor complete Hybriel plugins and runtime to day44mre