gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Branchgp-gate-ports57af42bbREADME: point to deploy.sh for the port listmregp-gate-ports/plugins/proc/tests/runtime-memory.py

6.9 KB

  1. #!/usr/bin/env python3
  2. """Exercise proc through HTTP delivery and runtime fault unwinding (Linux).
  3. Unlike memory.py's ABI counter, this catches allocations outside the plugin.
  4. Run after native/build.sh. Use --binary for an older compiler as a failing oracle.
  5. Only the explicit --port is used. Every server is stopped in finally.
  6. """
  7. import argparse
  8. import json
  9. import os
  10. import re
  11. from pathlib import Path
  12. import subprocess
  13. import tempfile
  14. import time
  15. import urllib.error
  16. import urllib.request
  17. ROOT = Path(__file__).resolve().parents[3]
  18. SOURCE = """import { NativeHttpServer, Response } from 'hl:http1'
  19. import { run, env } from 'hl:proc'
  20. inherit NativeHttpServer
  21. Number port = toNumber(env('M615_PORT'))
  22. String mode = env('M615_MODE')
  23. String repo = env('M615_REPO')
  24. on request(req) {
  25. if (mode == 'fault') {
  26. r = run('git', ['-C', repo, 'log', '-1'])
  27. return new Response('unexpected')
  28. }
  29. if (mode == 'run') {
  30. r = run(['git', '-C', repo, 'log', '-1'])
  31. return new Response(r.lines.join(' '))
  32. }
  33. return new Response('ok')
  34. }
  35. listen()
  36. """
  37. def main():
  38. ap = argparse.ArgumentParser(description=__doc__)
  39. ap.add_argument('--binary', default=os.environ.get('HL_BIN', str(ROOT / 'native/zig-out/bin/hybriel')))
  40. ap.add_argument('--port', type=int, required=True)
  41. ap.add_argument('--calls', type=int, default=20000)
  42. ap.add_argument('--mode', choices=['control', 'run', 'fault'], default='fault')
  43. ap.add_argument('--allow-growth', action='store_true')
  44. ap.add_argument('--fault-hook', action='store_true', help='allocate in a fault hook and verify exact bodies/logs under frequent GC')
  45. args = ap.parse_args()
  46. assert args.calls >= 20000, 'a short warmup hid this regression'
  47. with tempfile.TemporaryDirectory(prefix='proc-runtime-', dir=os.environ.get('TMPDIR')) as tmp:
  48. tmp = Path(tmp)
  49. source = tmp / 'server.hl'
  50. fixture = SOURCE
  51. if args.fault_hook:
  52. assert args.mode == 'fault'
  53. fixture = fixture.replace('on request(req) {', """on request(req) {
  54. hlOnFault((message) => {
  55. for (let j = 0; j < 64; j = j + 1) {
  56. garbage = ['pressure-' + j, 'x'.repeat(1024)]
  57. }
  58. console.log('hook: ' + message)
  59. })""")
  60. source.write_text(fixture)
  61. env = dict(os.environ, M615_PORT=str(args.port), M615_MODE=args.mode,
  62. M615_REPO=str(ROOT), HL_GC_THRESHOLD='128' if args.fault_hook else '1000', HL_ENV='development')
  63. env.pop('HL_COMPILER', None)
  64. if args.fault_hook:
  65. env['HL_GC_STATS'] = '1'
  66. with (tmp / 'server.log').open('w') as log:
  67. p = subprocess.Popen([args.binary, str(source)], cwd=ROOT, env=env, stdout=log, stderr=log)
  68. requests = 0
  69. located = None
  70. try:
  71. def request():
  72. nonlocal requests, located
  73. try:
  74. with urllib.request.urlopen(f'http://127.0.0.1:{args.port}/', timeout=5) as r:
  75. status, body = r.status, r.read()
  76. except urllib.error.HTTPError as r:
  77. status, body = r.code, r.read()
  78. if args.mode == 'fault':
  79. assert status == 500 and b"unknown option '0'" in body, (status, body)
  80. if args.fault_hook:
  81. message = "hl:proc run: unknown option '0' — the options are cwd, env, binary, stdin and timeout".encode()
  82. if located is None:
  83. match = re.fullmatch(rb'500 Internal Server Error\n\n(' + re.escape(str(source).encode()) + rb':(\d+):(\d+): ' + re.escape(message) + rb')\n', body)
  84. assert match, body
  85. located = match[1]
  86. assert "r = run('git'" in fixture.splitlines()[int(match[2])-1]
  87. assert int(match[3]) == 38, body
  88. assert body == b'500 Internal Server Error\n\n' + located + b'\n', body
  89. elif args.mode == 'run':
  90. assert status == 200 and body.startswith(b'commit '), (status, body)
  91. else:
  92. assert status == 200 and body == b'ok', (status, body)
  93. requests += 1
  94. for _ in range(300):
  95. try:
  96. request()
  97. break
  98. except OSError:
  99. assert p.poll() is None, (tmp / 'server.log').read_text()
  100. time.sleep(.1)
  101. else:
  102. raise AssertionError('server startup timeout')
  103. print(subprocess.check_output(['ss', '-ltnp', f'sport = :{args.port}'], text=True), flush=True)
  104. for _ in range(2000):
  105. request()
  106. samples = []
  107. for i in range(args.calls + 1):
  108. if i:
  109. request()
  110. if i % 2000 == 0:
  111. proc = Path(f'/proc/{p.pid}')
  112. status = (proc / 'status').read_text()
  113. rss = int(status.split('VmRSS:')[1].split()[0])
  114. swap = int(status.split('VmSwap:')[1].split()[0])
  115. samples.append([i, rss, swap, len(list((proc / 'fd').iterdir()))])
  116. if args.fault_hook:
  117. log.flush()
  118. lines = (tmp / 'server.log').read_bytes().splitlines()
  119. errors = [l for l in lines if l.startswith(b'Runtime error: ')]
  120. hooks = [l for l in lines if l.startswith(b'hook: ')]
  121. collections = sum(l.startswith(b'[hl-gc] #') for l in lines)
  122. assert errors == [b'Runtime error: ' + located] * requests
  123. assert hooks == [b'hook: ' + located] * requests
  124. assert collections >= requests, collections
  125. print(json.dumps(dict(exact_bodies=requests, exact_log_lines=len(errors),
  126. exact_hook_lines=len(hooks), collections=collections,
  127. located=located.decode())), flush=True)
  128. print(json.dumps(dict(mode=args.mode, calls=args.calls, warmup=2000,
  129. samples=samples)), flush=True)
  130. if not args.allow_growth:
  131. # Include swapped pages so memory pressure cannot hide leaked pages.
  132. totals = [r[1] + r[2] for r in samples]
  133. assert max(totals) - min(totals) <= 512, samples
  134. assert len({r[3] for r in samples}) == 1, samples
  135. finally:
  136. if p.poll() is None:
  137. assert Path(f'/proc/{p.pid}/cwd').resolve() == ROOT
  138. print(subprocess.check_output(['ss', '-ltnp', f'sport = :{args.port}'], text=True), flush=True)
  139. p.terminate()
  140. p.wait(timeout=10)
  141. if __name__ == '__main__':
  142. main()

Branches

Latest commits

  • 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
  • 6dc08a8eMerge branch 'p51-public-pr-reads' into mainGitoria
  • 7b88cfe0Type publicReaderOfRequest parameters (L10)Gitoria
  • 2a4b3dc1|||PR Anonymous reads of public repos' pulls and statusesmre
  • 21b2c141Merge branch 's25-no-session-on-login-error' into mainGitoria
  • 698458e2|||PR No session for cookieless login errors: READMEmre
  • cce7b785|||PR No session for cookieless login errorsmre
  • 678d6303Merge branch 'v59' into mainGitoria
  • 5803cf4f|||PR vendor: Hybriel set-day59 and GC budget 32 MiBmre
  • 9eff6627Merge branch 'f2-api-bugs' into mainGitoria
  • 26117255|||PR apps API: review comments on files with spaces in their namemre
  • b8796cecMerge branch 'f1-broken-json' into mainGitoria
  • 2f2959c5|||PR apps API: broken JSON body gives 400 invalid_json, not 500mre
  • f7c6ca07Merge branch 'ident-chooser-selector' into mainGitoria
  • 691abb8e|||PR tests: find ident identity choice without the removed .choose classmre
  • 16a3530fMerge branch 'heap-revert' into mainGitoria