gitoria
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
- f1-broken-json
- f2-api-bugs
- gp-gate-ports
- heap-revert
- hl25-records
- ident-chooser-selector
- mainmain branch
- p51-public-pr-reads
- records-1112
- s25-no-session-on-login-error
- v59
- w52-person-approval
- w52b-approval-followup
- w52c-header-phone
- w53-pulls-speed-pr
- w54-repo-rename-pr
- w55-rename-org
- w56-owner-members
- w62-pr-close
- w63-force-push
- w64-org-slash
Latest commits
- 0bab9e46|||PR header: ident status wraps on phones instead of clippingmre
- e7af3eceMerge branch 'w52b-approval-followup' into mainGitoria
- c01e66c6|||PR approvals follow-up: live Merge after status writes, helpers (#52)mre
- 841da497Merge branch 'w53-pulls-speed-pr' into mainGitoria
- 80307ae2|||PR pulls page cache: live PR numbers, complete scans onlymre
- 69141f65|||PR pulls page: cache the git part per repo by branch tipsmre
- 155861f6Merge branch 'w52-person-approval' into mainGitoria
- b5435de8|||PR person approvals: second Kunibert round (#52)mre
- 3a8b2fb8|||PR person approvals: Kunibert review fixes (#52)mre
- 2a89d8d0|||PR person approvals: Approve button for people; merge needs the required checks or a listed person's approval (#52)mre
- 83f0c953Report person approval verificationmre
- 3ae94b86Record browser failures and verify owned tab cleanupmre
- 54eec687Gate person approvals and merge alternativesmre
- 12b08829Add person approvals for pull request headsmre
- 55c84779Merge branch 'gp-gate-ports' into mainGitoria
- 57af42bbREADME: point to deploy.sh for the port listmre
- d63375d2README: gate commands with explicit portsmre
- feeaa701|||PR gates: explicit ports only, deploy.sh passes themmre
- 6cc1f943Merge branch 'records-1112' into mainGitoria
- 9448c438|||PR records: LOG, missions and reports since 11-09mre