311 lines
17 KiB
Python
311 lines
17 KiB
Python
"""固定七轮交错 HTTP/1 服务负载;逐个校验响应并保留吞吐与延迟原样本。"""
|
|
import argparse
|
|
import hashlib
|
|
import http.client
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import socket
|
|
import shutil
|
|
import statistics
|
|
import subprocess
|
|
import time
|
|
import tomllib
|
|
|
|
from scale import execute, fingerprint
|
|
from http_server_reference import source
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('--compiler', type=Path, required=True)
|
|
parser.add_argument('--core-source', type=Path, required=True)
|
|
parser.add_argument('--output', type=Path, required=True)
|
|
parser.add_argument('--size', type=int, default=100000)
|
|
parser.add_argument('--server-cpu', type=int, default=0)
|
|
parser.add_argument('--client-cpu', default='1,2,3', help='comma-separated dedicated client CPUs')
|
|
parser.add_argument('--baseline', type=Path)
|
|
parser.add_argument('--resource-reference', type=Path)
|
|
parser.add_argument('--automatic-api', action='store_true', help='measure generated public JSON API through api::serve')
|
|
parser.add_argument('--old-compiler', type=Path, help='frozen old compiler for the same automatic API workload')
|
|
parser.add_argument('--runtime-baseline', type=Path, help='runtime source directory for a same-generated-code causal comparison')
|
|
args = parser.parse_args()
|
|
if args.size < 1 or str(args.server_cpu) in args.client_cpu.split(','):
|
|
parser.error('positive size and separate server/client CPUs are required')
|
|
if (args.old_compiler or args.runtime_baseline) and not args.automatic_api:
|
|
parser.error('old compiler and runtime baseline require --automatic-api')
|
|
if args.automatic_api and args.resource_reference:
|
|
parser.error('the raw echo resource reference does not implement automatic JSON API')
|
|
core = args.core_source.resolve(strict=True)
|
|
compiler = args.compiler.resolve(strict=True)
|
|
root = args.output.resolve()
|
|
root.mkdir(parents=True, exist_ok=False)
|
|
os.environ['CARGO_BUILD_JOBS'] = '1'
|
|
os.environ['GOMAXPROCS'] = '1'
|
|
os.environ['GOTOOLCHAIN'] = 'local'
|
|
report = dict(compiler_sha256=fingerprint(compiler), size=args.size, concurrency=32,
|
|
server_cpu=args.server_cpu, client_cpu=args.client_cpu,
|
|
semantics='HTTP/1 keep-alive, 32 clients, varying body, every status and byte checked. The same native Go driver on dedicated CPUs. One excluded round then seven interleaved rounds. Every client run has 1024 untimed warmup requests. Rust uses the same locked Hyper/Tokio without Dever runtime; Go uses net/http. Successful echo only: no equivalent child-task faults, saturation, TLS or HTTP/2 performance claim.',
|
|
environment={name: Path('/sys/fs/cgroup', name).read_text().strip() for name in ['cpu.max', 'memory.max']},
|
|
builds=[], samples=[], versions={}, source_hashes={})
|
|
report['automatic_api'] = args.automatic_api
|
|
if args.automatic_api:
|
|
report['semantics'] = ('Public POST JSON {value:Text} -> {code:0,message:ok,data:Text}, 32 keep-alive clients, '
|
|
'all statuses and complete responses checked; one warmup then seven rotated rounds. '
|
|
'Dever uses generated api::serve. Independent Rust/Go use Hyper/Tokio and net/http; '
|
|
'successful JSON path only, no equivalence claim for authentication, cancellation, failure logs or graceful drain. '
|
|
'Go JSON decoding does not reject duplicate keys; that unsupported parity is not measured.')
|
|
def save():
|
|
(root / 'results.json').write_text(json.dumps(report, indent=2) + '\n')
|
|
inputs = [*core.joinpath('rust/src').rglob('*.rs'), *core.joinpath('lib').rglob('*.dv'),
|
|
core/'rust/Cargo.toml', core/'rust/src/runtime/Cargo.toml', core/'rust/Cargo.lock',
|
|
Path(__file__).resolve(), Path(__file__).with_name('http_server_reference.py').resolve(),
|
|
Path(__file__).with_name('http_server_client.go').resolve()]
|
|
for path in inputs:
|
|
relative = str(path.relative_to(core))
|
|
report['source_hashes'][relative] = fingerprint(path)
|
|
saved = root/'inputs'/relative
|
|
saved.parent.mkdir(parents=True, exist_ok=True)
|
|
saved.write_bytes(path.read_bytes())
|
|
locked = {(p['name'], p['version'], p.get('source')) for p in tomllib.loads((core/'rust/Cargo.lock').read_text())['package']}
|
|
client = root/'client'
|
|
report['client_build'] = execute(['go', 'build', '-trimpath', '-o', str(client), str(inputs[-1])], root, 'client-build', 120)
|
|
save()
|
|
if report['client_build']['exit_code']:
|
|
raise RuntimeError(report['client_build'])
|
|
report['client_sha256'] = fingerprint(client)
|
|
programs = {}
|
|
for name, command in [('rust', ['rustc', '+1.95.0', '--version', '--verbose']), ('go', ['go', 'version'])]:
|
|
result = execute(command, root, name+'-version', 30)
|
|
report['versions'][name] = result
|
|
save()
|
|
if result['exit_code']:
|
|
raise RuntimeError(result)
|
|
for language in ['dever', 'rust', 'go'] + (['old'] if args.old_compiler else []):
|
|
case = root/language
|
|
case.mkdir()
|
|
dever = language in ['dever', 'old']
|
|
project = case / 'project' if args.automatic_api and dever else case
|
|
if args.automatic_api and dever:
|
|
domain = project / 'module/benchmark/echo'
|
|
path = domain / ('app/main.dever' if language == 'dever' else 'app.dever')
|
|
else:
|
|
path = case / ('main.' + {'dever': 'dever', 'old': 'dever', 'rust': 'rs', 'go': 'go'}[language])
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
path.write_text(source('dever' if dever else language, args.automatic_api))
|
|
if args.automatic_api and dever:
|
|
api = domain/'api/front/main.dever'
|
|
api.parent.mkdir(parents=True)
|
|
api.write_text('public post echo = app.echo' + chr(10))
|
|
binary = case/'program'
|
|
if dever:
|
|
tool = args.old_compiler.resolve(strict=True) if language == 'old' else compiler
|
|
formatted = execute([str(tool), 'fmt', str(project if args.automatic_api else path)], case, 'fmt', 30)
|
|
if formatted['exit_code']:
|
|
raise RuntimeError(formatted)
|
|
command = [str(tool), 'build', str(project if args.automatic_api else path), '--output', str(binary)]
|
|
elif language == 'rust':
|
|
(case/'Cargo.toml').write_text('''[package]
|
|
name = "http-server-reference"
|
|
version = "0.0.1"
|
|
edition = "2024"
|
|
[[bin]]
|
|
name = "http-server-reference"
|
|
path = "main.rs"
|
|
[dependencies]
|
|
bytes = "=1.12.1"
|
|
tokio = { version = "=1.53.1", features = ["rt", "net", "time", "macros", "sync", "io-util"] }
|
|
futures-util = { version = "=0.3.34", default-features = false, features = ["std"] }
|
|
hyper = { version = "=1.11.1", features = ["http1", "http2", "client", "server"] }
|
|
hyper-util = { version = "=0.1.20", features = ["tokio"] }
|
|
http-body-util = "=0.1.5"
|
|
serde = { version = "=1.0.228", features = ["derive"] }
|
|
serde_json = "=1.0.145"
|
|
[profile.release]
|
|
lto = "fat"
|
|
codegen-units = 1
|
|
overflow-checks = true
|
|
strip = "symbols"
|
|
''')
|
|
(case/'Cargo.lock').write_bytes((core/'rust/Cargo.lock').read_bytes())
|
|
command = ['cargo', '+1.95.0', 'build', '--manifest-path', str(case/'Cargo.toml'), '--offline', '--release', '--target-dir', str(core/'target/next-cargo')]
|
|
binary = core/'target/next-cargo/release/http-server-reference'
|
|
else:
|
|
(case/'go.mod').write_text('module http-server-reference\n\ngo 1.25.0\n')
|
|
command = ['go', '-C', str(case), 'build', '-buildvcs=false', '-p', '1', '-trimpath', '-ldflags=-s -w', '-o', str(binary), '.']
|
|
build = dict(language=language, source_sha256=fingerprint(path), source_lines=len(path.read_text().splitlines()), **execute(command, case, 'build', 900))
|
|
report['builds'].append(build)
|
|
save()
|
|
if build['exit_code']:
|
|
raise RuntimeError(build)
|
|
if language == 'rust':
|
|
shutil.copy2(binary, case/'program')
|
|
binary = case/'program'
|
|
build['binary_sha256'] = fingerprint(binary)
|
|
if language == 'rust':
|
|
packages = tomllib.loads((case/'Cargo.lock').read_text())['package']
|
|
build['dependency_differences'] = [(p['name'], p['version'], p.get('source')) for p in packages if p.get('source') and (p['name'], p['version'], p['source']) not in locked]
|
|
build['lock_sha256'] = fingerprint(case/'Cargo.lock')
|
|
if build['dependency_differences']:
|
|
save()
|
|
raise RuntimeError('reference dependency versions differ')
|
|
programs[language] = binary
|
|
if dever:
|
|
build['compiler_sha256'] = fingerprint(tool)
|
|
build['business_sources'] = {str(p.relative_to(project)): dict(sha256=fingerprint(p), lines=len(p.read_text().splitlines())) for p in project.rglob('*.dever')}
|
|
save()
|
|
if args.runtime_baseline:
|
|
programs['runtime_baseline'] = build_runtime_baseline(core, root, args.runtime_baseline, report, save)
|
|
if args.baseline:
|
|
baseline = args.baseline.resolve(strict=True)
|
|
programs['previous'] = baseline
|
|
(root/'previous').mkdir()
|
|
report['baseline'] = dict(binary=str(baseline), sha256=fingerprint(baseline))
|
|
save()
|
|
if args.resource_reference:
|
|
binary = args.resource_reference.resolve(strict=True)
|
|
project = binary.parents[2]
|
|
paths = [*sorted(project.glob('http_resource_*.rs')), project / 'Cargo.toml', project / 'Cargo.lock']
|
|
report['resource_reference'] = dict(binary=str(binary), sha256=fingerprint(binary),
|
|
sources={str(path): fingerprint(path) for path in paths},
|
|
contract='32 active connections; header/body/handler deadlines; bounded body/headers; handler panic isolation and error logs; tracked connection tasks; owner cancellation and listener graceful drain. Pure echo route only, no child-task/TLS/H2 performance equivalence claimed.')
|
|
programs['resource'] = binary
|
|
(root / 'resource').mkdir()
|
|
save()
|
|
measure(args, core, root, programs, report, save, client)
|
|
|
|
|
|
def measure(args, core, root, programs, report, save, client):
|
|
binaries = {name:dict(path=str(path), sha256=fingerprint(path), bytes=path.stat().st_size) for name,path in programs.items()}
|
|
if report.get('binaries') and report['binaries'] != binaries:
|
|
raise RuntimeError('measured binaries changed; results from different identities cannot be resumed together')
|
|
report['binaries'] = binaries
|
|
save()
|
|
for repeat in range(-1, 7):
|
|
if any(fingerprint(path) != binaries[name]['sha256'] for name,path in programs.items()):
|
|
raise RuntimeError('binary changed during benchmark')
|
|
for relative, sha in report['source_hashes'].items():
|
|
if fingerprint(core/relative) != sha:
|
|
raise RuntimeError('source changed during benchmark: '+relative)
|
|
for path, sha in report.get('resource_reference', {}).get('sources', {}).items():
|
|
if fingerprint(Path(path)) != sha:
|
|
raise RuntimeError('resource reference changed during benchmark: '+path)
|
|
order = list(programs)
|
|
order = order[repeat % len(order):] + order[:repeat % len(order)]
|
|
for language in order:
|
|
if any(row['language'] == language and row['repeat'] == repeat and row.get('count') == args.size for row in report['samples']):
|
|
continue
|
|
case = root/language
|
|
with socket.socket() as reservation:
|
|
reservation.bind(('127.0.0.1', 0))
|
|
port = reservation.getsockname()[1]
|
|
configuration = case/f'setting-{repeat}.json'
|
|
settings = {'http': {'host':'127.0.0.1', 'port':port}, 'sites': {'front': {'path':'front','hosts':['127.0.0.1']}}} if args.automatic_api else {'module': {'main': {'main': {'port': port}}}}
|
|
configuration.write_text(json.dumps(settings))
|
|
dever = language in ['dever', 'previous', 'old', 'runtime_baseline']
|
|
command = [str(programs[language]), '--config', str(configuration), *(['api'] if args.automatic_api else ['main.main.server', '{}'])] if dever else [str(programs[language]), str(port)]
|
|
if language == 'old':
|
|
command = [str(programs[language]), '--config', str(configuration)]
|
|
if language == 'resource':
|
|
command = [str(programs[language]), 'server', str(port)]
|
|
stdout = case/f'server-{repeat}.stdout'
|
|
stderr = case/f'server-{repeat}.stderr'
|
|
with stdout.open('wb') as out, stderr.open('wb') as err:
|
|
process = subprocess.Popen(['taskset', '-c', str(args.server_cpu), *command], stdout=out, stderr=err)
|
|
try:
|
|
deadline = time.monotonic() + 10
|
|
while True:
|
|
if process.poll() is not None:
|
|
raise RuntimeError(f'{language} exited before listening: {stderr.read_text()}')
|
|
try:
|
|
with socket.create_connection(('127.0.0.1', port), timeout=.1):
|
|
break
|
|
except ConnectionRefusedError:
|
|
if time.monotonic() >= deadline:
|
|
raise TimeoutError('server did not listen')
|
|
time.sleep(.01)
|
|
before = cpu_seconds(process.pid)
|
|
if args.automatic_api and repeat == -1:
|
|
report.setdefault('functional', {})[language] = api_contract(port)
|
|
save()
|
|
result = execute(['taskset', '-c', str(args.client_cpu), 'env', '-u', 'GOMAXPROCS', str(client), str(port), str(args.size), 'api' if args.automatic_api else 'echo'], case, f'client-{repeat}', 120)
|
|
row = dict(language=language, repeat=repeat, server_cpu_seconds_including_warmup=cpu_seconds(process.pid)-before,
|
|
server_peak_rss_kib=peak_rss(process.pid), **result)
|
|
report['samples'].append(row)
|
|
save()
|
|
if result['exit_code']:
|
|
raise RuntimeError(result)
|
|
row.update(json.loads(Path(result['stdout']).read_text()))
|
|
if row['count'] != args.size or process.poll() is not None:
|
|
raise RuntimeError('incomplete request workload or server exited')
|
|
save()
|
|
finally:
|
|
process.terminate()
|
|
try:
|
|
process.wait(timeout=10)
|
|
except subprocess.TimeoutExpired:
|
|
process.kill()
|
|
process.wait()
|
|
raise
|
|
report['medians'] = {language: {key: statistics.median(row[key] for row in report['samples'] if row['language'] == language and row['repeat'] >= 0)
|
|
for key in ['seconds', 'requests_per_second', 'p50_ms', 'p95_ms', 'p99_ms', 'server_cpu_seconds_including_warmup', 'server_peak_rss_kib']} for language in programs}
|
|
save()
|
|
print(json.dumps(report['medians'], indent=2))
|
|
|
|
|
|
def build_runtime_baseline(core, root, runtime, report, save):
|
|
runtime = runtime.resolve(strict=True)
|
|
identity = hashlib.sha256(os.fsencode((root/'dever/project').resolve())).hexdigest()
|
|
generated = core/'rust/target/generated'/('dever-program-'+identity)/'x86_64'
|
|
case = root/'runtime_baseline'
|
|
shutil.copytree(generated, case, ignore=shutil.ignore_patterns('build.lock'))
|
|
manifest = case/'Cargo.toml'
|
|
manifest.write_text(manifest.read_text().replace(str(core/'rust/src/runtime'), str(runtime)))
|
|
row = dict(language='runtime_baseline', sources={str(p):fingerprint(p) for p in runtime.rglob('*.rs')},
|
|
**execute(['cargo','+1.95.0','build','--manifest-path',str(manifest),'--locked','--offline','--release',
|
|
'--target-dir',str(core/'target/next-cargo')],case,'build',900))
|
|
report['builds'].append(row)
|
|
save()
|
|
if row['exit_code']:
|
|
raise RuntimeError(row)
|
|
binary = case/'program'
|
|
shutil.copy2(core/'target/next-cargo/release'/('dever-program-'+identity), binary)
|
|
row['binary_sha256'] = fingerprint(binary)
|
|
save()
|
|
return binary
|
|
|
|
|
|
def api_contract(port):
|
|
results = []
|
|
for body, expected in [('{}',400), ('{"value":null}',400), ('{"value":1}',400),
|
|
('{"value":"x","extra":1}',400), ('{"value":"x"} {}',400),
|
|
(json.dumps({'value':'中文 " 雪'}),200)]:
|
|
client = http.client.HTTPConnection('127.0.0.1', port, timeout=5)
|
|
try:
|
|
client.request('POST','/benchmark/echo/front/main/echo',body.encode(),{'content-type':'application/json'})
|
|
reply = client.getresponse()
|
|
data = reply.read().decode()
|
|
results.append(dict(body=body, expected_status=expected, status=reply.status, response=data))
|
|
if reply.status != expected:
|
|
raise AssertionError(results[-1])
|
|
if expected == 200:
|
|
assert json.loads(data) == dict(code=0, message='ok', data=json.loads(body)['value'])
|
|
finally:
|
|
client.close()
|
|
return results
|
|
|
|
|
|
def cpu_seconds(pid):
|
|
# 仅读取本任务子进程的 CPU 计数,不需要 perf 权限。
|
|
fields = Path(f'/proc/{pid}/stat').read_text().rsplit(')', 1)[1].split()
|
|
return (int(fields[11]) + int(fields[12])) / os.sysconf('SC_CLK_TCK')
|
|
|
|
|
|
def peak_rss(pid):
|
|
status = Path(f'/proc/{pid}/status').read_text().splitlines()
|
|
return int(next(line for line in status if line.startswith('VmHWM:')).split()[1])
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|