gitoria

tracker

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit63e5ba1a63e5ba1a|||PR BS3: guard boot imports and share resumable sort buffersTracker63e5ba1a/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

  • 63e5ba1a|||PR BS3: guard boot imports and share resumable sort buffersTracker
  • 310613f1Merge branch 'records-dp72' into mainTracker
  • 6f7b61ba|||PR records: deploy-swap fix live, Kunibert findingsTracker
  • c41587d2Merge branch 'bs2' into mainTracker
  • 0dd538a6|||PR BS2: finish the boot index in slices so a booting instance keeps answeringTracker
  • 019d5cedMerge branch 'records-1110' into mainTracker
  • f88ae8b9|||PR records: day56 toggle live, reviewTracker
  • b6b3bb4dMerge branch 'ap56e' into mainTracker
  • 29a26da9|||PR AP56e: guard hidden show helpers during session syncTracker
  • 7c9ec236|||PR AP56e: re-vendor Hybriel set day56 (source 36ae83a8, bin c1f595a2)Tracker
  • 4b54f6f9Merge branch 'records-audit' into mainTracker
  • cab4a3bc|||PR records: branch audit, PR-onlyTracker
  • 641e1c4cMerge branch 'records-dp71' into mainTracker
  • 85a6e9f5|||PR records: DP71 checked in ChromeTracker
  • f5be5f18records: gitoria PR-only planTracker
  • 46a37036records: DP71 liveTracker
  • 3bcb7039Status/log: DP71 in progressTracker
  • 5b3a5693Log: SR1b merged via PR 2, DP71 startedTracker
  • 783957c2Merge branch 'sr1-search' into mainTracker
  • 792b9652README: search results come from the routeTracker