Dever v0.0.2

This commit is contained in:
Codex committed 2026-11-27 06:03:56 +00:00
commit e6e175ebcf
816 files changed
+120349

No files matched your search

+709
View File
@@ -0,0 +1,709 @@
"""顺序 loop 的独立 Rust/Go 运行对照;先完成全部构建,再交错测量真实程序。"""
import argparse
import json
import os
from pathlib import Path
import statistics
import tomllib
from scale import execute, fingerprint
from legacy_reference import SHAPES as LEGACY_SHAPES, source as legacy_source
from token_reference import source as token_source
from file_reference import source as file_source
from file_stream_reference import source as file_stream_source
from bytes_reference import source as bytes_source
from standard_reference import source as standard_source
from uuid_reference import source as uuid_source
from calendar_reference import source as calendar_source
from settings_reference import source as settings_source, config as settings_config, expected as settings_expected
from port_reference import source as port_source, config as port_config, project as port_project
from async_reference import source as async_source
from parallel_reference import source as parallel_source
from concurrent_reference import source as concurrent_source
from stdout_reference import source as stdout_source
from arguments_reference import source as arguments_source
from net_reference import source as net_source
from tls_reference import source as tls_source
from http_reference import source as http_source, server as http_server
from http_pool_reference import source as http_pool_source
from http_stream_reference import source as http_stream_source
from crypto_reference import source as crypto_source, config as crypto_config, expected as crypto_expected
def group_source(language):
if language == 'dever':
return '''loop grouped(n: Int) (out: Map<Int, List<Int>>)
| each value in range(0, n) | result |
| out | group value % 64 |
loop total(values: List<Int>) (out: Int)
| each value in values | result |
| out | sum value |
loop checksum(values: List<MapEntry<Int, List<Int>>>) (out: Int)
| each entry in values | result |
| out | sum total(entry.value) + entry.key |
measure(n: Int) (out: Int) { out = checksum(entries(grouped(n))) }
cmd bench = app.measure
'''
if language == 'rust':
return '''use indexmap::IndexMap;
fn main() {
let n: i64 = std::env::args().nth(1).unwrap().parse().unwrap();
let mut groups: IndexMap<i64, Vec<i64>, ahash::RandomState> = IndexMap::with_capacity_and_hasher(0, ahash::RandomState::new());
for value in 0..n { groups.entry(value % 64).or_default().push(value); }
let entries: Vec<_> = groups.into_iter().collect();
let mut checksum = 0i64;
for (key, values) in entries {
let mut total = 0i64;
for value in values { total = total.checked_add(value).expect("sum overflow"); }
checksum = checksum.checked_add(total.checked_add(key).expect("key overflow")).expect("checksum overflow");
}
println!("{checksum}");
}
'''
return '''package main
import ("fmt"; "os"; "strconv")
func add(a, b int64) int64 {
result := a + b
if (b > 0 && result < a) || (b < 0 && result > a) { panic("integer overflow") }
return result
}
type entry struct { key int64; values []int64 }
func main() {
n, err := strconv.ParseInt(os.Args[1], 10, 64)
if err != nil { panic(err) }
positions := make(map[int64]int)
groups := make([]entry, 0)
for value := int64(0); value < n; value++ {
key := value % 64
position, exists := positions[key]
if !exists {
position = len(groups)
positions[key] = position
groups = append(groups, entry{key: key})
}
groups[position].values = append(groups[position].values, value)
}
checksum := int64(0)
for _, group := range groups {
total := int64(0)
for _, value := range group.values { total = add(total, value) }
checksum = add(checksum, add(total, group.key))
}
fmt.Println(checksum)
}
'''
def index_source(language):
if language == 'dever':
return '''loop indexed(n: Int) (out: Map<Int, Int>)
| each value in range(0, n) | result |
| out | index value |
loop checksum(values: List<MapEntry<Int, Int>>) (out: Int)
| each entry in values | result |
| out | sum entry.value + entry.key |
measure(n: Int) (out: Int) { out = checksum(entries(indexed(n))) }
cmd bench = app.measure
'''
if language == 'rust':
return '''use indexmap::{IndexMap, map::Entry};
#[derive(Debug)]
enum Error { DuplicateKey }
fn measure(n: i64) -> Result<i64, Error> {
let mut indexed: IndexMap<i64, i64, ahash::RandomState> = IndexMap::with_capacity_and_hasher(0, ahash::RandomState::new());
for value in 0..n {
match indexed.entry(value) {
Entry::Vacant(entry) => { entry.insert(value); }
Entry::Occupied(_) => return Err(Error::DuplicateKey),
}
}
let entries: Vec<_> = indexed.into_iter().collect();
let mut checksum = 0i64;
for (key, value) in entries {
checksum = checksum.checked_add(value.checked_add(key).expect("value overflow")).expect("checksum overflow");
}
Ok(checksum)
}
fn main() {
let n: i64 = std::env::args().nth(1).unwrap().parse().unwrap();
println!("{}", measure(n).unwrap());
}
'''
return '''package main
import ("errors"; "fmt"; "os"; "strconv")
func add(a, b int64) int64 {
result := a + b
if (b > 0 && result < a) || (b < 0 && result > a) { panic("integer overflow") }
return result
}
type entry struct { key int64; value int64 }
func measure(n int64) (int64, error) {
positions := make(map[int64]int)
entries := make([]entry, 0)
for value := int64(0); value < n; value++ {
if _, exists := positions[value]; exists { return 0, errors.New("DuplicateKey") }
positions[value] = len(entries)
entries = append(entries, entry{key: value, value: value})
}
checksum := int64(0)
for _, entry := range entries { checksum = add(checksum, add(entry.value, entry.key)) }
return checksum, nil
}
func main() {
n, err := strconv.ParseInt(os.Args[1], 10, 64)
if err != nil { panic(err) }
checksum, err := measure(n)
if err != nil { panic(err) }
fmt.Println(checksum)
}
'''
def source(language, shape):
if shape == 'http':
return http_source(language)
if shape == 'http_stream':
return http_stream_source(language)
if shape == 'http_pool':
return http_pool_source(language)
if shape == 'net':
return net_source(language)
if shape == 'tls':
return tls_source(language)
if shape == 'arguments':
return arguments_source(language)
if shape == 'stdout':
return stdout_source(language)
if shape == 'concurrent':
return concurrent_source(language)
if shape == 'file_stream':
return file_stream_source(language)
if shape in ('file', 'file_stream'):
return file_source(language)
if shape == 'token':
return token_source(language)
if shape == 'parallel':
return parallel_source(language)
if shape == 'calendar':
return calendar_source(language)
if shape == 'async':
return async_source(language)
if shape == 'port':
return port_source(language)
if shape == 'settings':
return settings_source(language)
if shape == 'crypto':
return crypto_source(language)
if shape == 'uuid':
return uuid_source(language)
if shape == 'standard':
return standard_source(language)
if shape == 'bytes':
return bytes_source(language)
if shape == 'fields':
return field_source(language)
if shape == 'walk':
return walk_source(language)
if shape in ('fold', 'foldUntil'):
return fold_source(language, shape == 'foldUntil')
if shape == 'index':
return index_source(language)
if shape == 'group':
return group_source(language)
filtered = shape == 'filtered'
if language == 'dever':
body = (
'loop totals(n: Int) (total: Int, count: Int)\n'
'| each value in range(0, n) | value % 2 | result |\n'
'| total | 0 | sum value |\n| count | - | count |\n'
'measure(n: Int) (out: Int) { result = totals(n)\nout = result.total + result.count }\n'
if filtered else
'loop measure(n: Int) (out: Int)\n| each value in range(0, n) | result |\n| out | sum value |\n'
)
return body + 'cmd bench = app.measure\n'
if language == 'rust':
accumulation = 'if value % 2 == 0 { total = total.checked_add(value).expect("sum overflow"); }\ncount = count.checked_add(1).expect("count overflow");' if filtered else 'total = total.checked_add(value).expect("sum overflow");'
result = 'total.checked_add(count).expect("result overflow")' if filtered else 'total'
return '''use std::env;
fn measure(n: i64) -> i64 {
let mut total = 0i64;
''' + (' let mut count = 0i64;\n' if filtered else '') + f''' for value in 0..n {{
{accumulation}
}}
{result}
}}
fn main() {{
let n = env::args().nth(1).unwrap().parse::<i64>().unwrap();
println!("{{}}", measure(n));
}}
'''
accumulation = 'if value % 2 == 0 { total = add(total, value) }; count = add(count, 1)' if filtered else 'total = add(total, value)'
return '''package main
import ("fmt"; "os"; "strconv")
func add(a, b int64) int64 {
result := a + b
if (b > 0 && result < a) || (b < 0 && result > a) { panic("integer overflow") }
return result
}
func measure(n int64) int64 {
total := int64(0)
''' + (' count := int64(0)\n' if filtered else '') + f''' for value := int64(0); value < n; value++ {{
{accumulation}
}}
return {"add(total, count)" if filtered else "total"}
}}
func main() {{
n, err := strconv.ParseInt(os.Args[1], 10, 64)
if err != nil {{ panic(err) }}
fmt.Println(measure(n))
}}
'''
def fold_source(language, until):
if language == 'dever':
update = ('update(value: Int, previous: Int, limit: Int) (acc: Int, stop: Bool) { acc = previous + value\nstop = value >= limit }\n' if until else
'update(value: Int, previous: Int) (out: Int) { out = previous + value }\n')
aggregation = 'foldUntil(acc = 0, update(value, acc, n // 2))' if until else 'fold(acc = 0, update(value, acc))'
return update + 'loop measure(n: Int) (out: Int)\n| each value in range(0, n) | result |\n| out | ' + aggregation + ' |\ncmd bench = app.measure\n'
if language == 'rust':
update = ('fn update(value: i64, previous: i64, limit: i64) -> (i64, bool) { (previous.checked_add(value).expect("sum overflow"), value >= limit) }' if until else
'fn update(value: i64, previous: i64) -> i64 { previous.checked_add(value).expect("sum overflow") }')
step = 'let (next, stop) = update(value, acc, n / 2); acc = next; if stop { break; }' if until else 'acc = update(value, acc);'
return update + f'''
fn measure(n: i64) -> i64 {{
let mut acc = 0;
for value in 0..n {{ {step} }}
acc
}}
fn main() {{
let n: i64 = std::env::args().nth(1).unwrap().parse().unwrap();
println!("{{}}", measure(n));
}}
'''
update = ('func update(value, previous, limit int64) (int64, bool) { return add(previous, value), value >= limit }' if until else
'func update(value, previous int64) int64 { return add(previous, value) }')
step = 'next, stop := update(value, acc, n / 2); acc = next; if stop { break }' if until else 'acc = update(value, acc)'
return '''package main
import ("fmt"; "os"; "strconv")
func add(a, b int64) int64 {
result := a + b
if (b > 0 && result < a) || (b < 0 && result > a) { panic("integer overflow") }
return result
}
''' + update + f'''
func measure(n int64) int64 {{
acc := int64(0)
for value := int64(0); value < n; value++ {{ {step} }}
return acc
}}
func main() {{
n, err := strconv.ParseInt(os.Args[1], 10, 64)
if err != nil {{ panic(err) }}
fmt.Println(measure(n))
}}
'''
def walk_source(language):
if language == 'dever':
return '''rule next(state: Int) (out: Walk<Int, Int>)
| state | out |
| > 0 | Next(state - 1, state - 1) |
| <= 0 | Done |
loop measure(n: Int) (out: Int)
| each value in walk(n, next) | result |
| out | sum value |
cmd bench = app.measure
'''
if language == 'rust':
return '''enum Step { Next(i64, i64), Done }
fn next(state: i64) -> Step {
if state > 0 { Step::Next(state.checked_sub(1).expect("state overflow"), state.checked_sub(1).expect("state overflow")) } else { Step::Done }
}
fn measure(mut state: i64) -> i64 {
let mut total = 0i64;
loop {
let item = match next(state) { Step::Next(item, next_state) => { state = next_state; item }, Step::Done => break };
total = total.checked_add(item).expect("sum overflow");
}
total
}
fn main() {
let n: i64 = std::env::args().nth(1).unwrap().parse().unwrap();
println!("{}", measure(n));
}
'''
return '''package main
import ("fmt"; "os"; "strconv")
type step struct { item, state int64; done bool }
func next(state int64) step {
if state > 0 { return step{item: state - 1, state: state - 1} }
return step{done: true}
}
func measure(state int64) int64 {
total := int64(0)
for {
result := next(state)
if result.done { break }
state = result.state
sum := total + result.item
if (result.item > 0 && sum < total) || (result.item < 0 && sum > total) { panic("sum overflow") }
total = sum
}
return total
}
func main() {
n, err := strconv.ParseInt(os.Args[1], 10, 64)
if err != nil { panic(err) }
fmt.Println(measure(n))
}
'''
def field_source(language):
if language == 'dever':
return '''type Pair { left: List<Int>, right: List<Int> }
swap(previous: Pair) (out: Pair) { out = Pair { left = previous.right, right = previous.left } }
loop values(n: Int, offset: Int) (out: List<Int>)
| each value in range(0, n) | result |
| out | list value + offset |
loop swapped(seed: Pair) (out: Pair)
| each value in range(0, 1001) | result |
| out | fold(acc = seed, swap(acc)) |
loop total(values: List<Int>) (out: Int)
| each value in values | result |
| out | sum value |
measure(n: Int) (out: Int) {
pair = swapped(Pair { left = values(n, 0), right = values(n, 1) })
out = total(pair.left) + 2 * total(pair.right)
}
cmd bench = app.measure
'''
if language == 'rust':
return '''struct Pair { left: Vec<i64>, right: Vec<i64> }
fn swap(previous: Pair) -> Pair { Pair { left: previous.right, right: previous.left } }
fn total(values: &[i64]) -> i64 {
values.iter().fold(0i64, |sum, value| sum.checked_add(*value).expect("sum overflow"))
}
fn main() {
let n: i64 = std::env::args().nth(1).unwrap().parse().unwrap();
let mut left = Vec::with_capacity(n as usize);
let mut right = Vec::with_capacity(n as usize);
for value in 0..n { left.push(value); }
for value in 0..n { right.push(value.checked_add(1).expect("value overflow")); }
let mut pair = Pair { left, right };
for _ in 0..1001 { pair = swap(pair); }
let checksum = total(&pair.left).checked_add(total(&pair.right).checked_mul(2).expect("multiply overflow")).expect("checksum overflow");
println!("{checksum}");
}
'''
return '''package main
import ("fmt"; "os"; "strconv")
type pair struct { left, right []int64 }
func swap(previous pair) pair { return pair{left: previous.right, right: previous.left} }
func add(a, b int64) int64 {
result := a + b
if (b > 0 && result < a) || (b < 0 && result > a) { panic("integer overflow") }
return result
}
func total(values []int64) int64 {
sum := int64(0)
for _, value := range values { sum = add(sum, value) }
return sum
}
func main() {
n, err := strconv.ParseInt(os.Args[1], 10, 64)
if err != nil { panic(err) }
left, right := make([]int64, 0, n), make([]int64, 0, n)
for value := int64(0); value < n; value++ { left = append(left, value) }
for value := int64(0); value < n; value++ { right = append(right, add(value, 1)) }
state := pair{left: left, right: right}
for i := 0; i < 1001; i++ { state = swap(state) }
subtotal := total(state.right)
fmt.Println(add(total(state.left), add(subtotal, subtotal)))
}
'''
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--compiler', type=Path, required=True)
parser.add_argument('--old-compiler', type=Path, help='frozen R0 compiler for the supported standard-library workloads')
parser.add_argument('--output', type=Path, required=True)
parser.add_argument('--size', type=int, default=300_000_000)
parser.add_argument('--shape', nargs='+', choices=['sum', 'filtered', 'group', 'index', 'fold', 'foldUntil', 'walk', 'fields', 'bytes', 'standard', 'uuid', 'calendar', 'settings', 'port', 'crypto', 'token', 'file', 'file_stream', 'async', 'parallel', 'concurrent', 'stdout', 'arguments', 'net', 'tls', 'http', 'http_pool', 'http_stream'], default=['sum', 'filtered'])
parser.add_argument('--core-source', type=Path)
parser.add_argument('--runtime-reference', action='store_true')
args = parser.parse_args()
if args.old_compiler and not set(args.shape) <= LEGACY_SHAPES:
parser.error('old-compiler currently supports standard, uuid and calendar')
if not 1 <= args.size <= 1_000_000_000:
parser.error('size must be between 1 and 1000000000')
if args.runtime_reference and (args.shape not in (['concurrent'], ['arguments'], ['net']) or not args.core_source):
parser.error('runtime-reference requires --shape concurrent|arguments|net and --core-source')
languages = ['dever', 'rust', 'go'] + (['old'] if args.old_compiler else []) + (['runtime'] if args.runtime_reference else [])
compiler = args.compiler.resolve(strict=True)
root = args.output.resolve()
root.mkdir(parents=True, exist_ok=False)
(root / 'legacy_reference.py').write_bytes(Path(__file__).with_name('legacy_reference.py').read_bytes())
for name in ['loop.py', 'scale.py', 'bytes_reference.py', 'standard_reference.py', 'uuid_reference.py', 'calendar_reference.py', 'settings_reference.py', 'port_reference.py', 'crypto_reference.py', 'token_reference.py', 'file_reference.py', 'file_stream_reference.py', 'async_reference.py', 'parallel_reference.py', 'concurrent_reference.py', 'stdout_reference.py', 'arguments_reference.py', 'net_reference.py', 'tls_reference.py', 'http_reference.py', 'http_pool_reference.py', 'http_stream_reference.py']:
(root / name).write_bytes(Path(__file__).with_name(name).read_bytes())
os.environ['CARGO_BUILD_JOBS'] = '1'
os.environ['GOMAXPROCS'] = '1'
os.environ['GOTOOLCHAIN'] = 'local'
cgroup = Path('/sys/fs/cgroup')
report = dict(compiler=str(compiler), compiler_sha256=fingerprint(compiler),
cpu_affinity=sorted(os.sched_getaffinity(0)),
driver_sha256=fingerprint(root / 'loop.py'), rounds=7, size=args.size,
semantics='signed 64-bit checked sum; lazy half-open range; filtered rows keep declaration order; group uses 64 buckets in first-key order and checksums every value; index keeps key order, checks duplicates and checksums every key/value; fold uses a named state update; foldUntil adopts the updated state before stopping at value >= n/2; walk uses a named Next/Done stepper counting down from n-1 to 0; fields swaps two n-element lists 1001 times and computes a weighted sum; bytes creates n integers modulo 256, validates and converts to Bytes, shares slice [1,n), then checksums every byte; standard decorates each integer with Unicode whitespace and snow, trims, splits into scalars, rejoins, replaces snow, parses and checksums every integer; uuid creates a varying canonical identifier, strictly parses, formats, reads its last Unicode scalar and sums that decimal digit; calendar adds successive millisecond offsets, formats canonical UTC, parses and checks the exact difference; settings loads a valid typed configuration once, borrows its corpus and sums every value whose decimal residue modulo 1000 appears in the corpus; crypto uses a public benchmark key from configuration and hashes each varying decimal message with HMAC-SHA256 then SHA256 and sums every digest byte; async executes ordered direct async calls with one 1ms timer per million inputs and checksums every value; Go uses its native sleep and has a different timer resolution',
scope='whole-process time; Dever additionally decodes one small JSON argument and encodes its response; Rust/Go parse one decimal argument',
memory_scope='wait4 peak_rss may include the Python fork before exec; these samples do not establish application-only RSS',
environment=dict(cpu_max=(cgroup/'cpu.max').read_text().strip(),
memory_max=(cgroup/'memory.max').read_text().strip()),
versions={}, builds=[], samples=[])
if args.old_compiler:
old = args.old_compiler.resolve(strict=True)
report['old_compiler'] = dict(path=str(old), sha256=fingerprint(old))
report['old_semantics'] = 'Frozen language uses sum(each(..., range(...))); current language uses loop tables. Same operations, inputs, checked checksum and locked reference dependencies. Old and new language implementations retain their own allocation strategies; no full standard-library contract parity claim.'
if 'port' in args.shape:
report['port_semantics'] = 'Two concrete implementations, contains and prefix, selected once from the same startup configuration; contains selected in this workload. Each call dispatches over the selected implementation, borrows its text corpus and searches the decimal residue. Rust uses a concrete enum and directly owned private settings, the same locked Serde versions, and no Dever runtime. Go uses a checked startup selector. All results are checked against the settings checksum; invalid configuration, effects, task sharing and error obligations are covered by functional tests, not this timing.'
if 'parallel' in args.shape:
report['parallel_semantics'] = 'Each input concurrently calls item(value) and item(value+1), waits for both, checks signed 64-bit addition and sums all pairs. Each item sleeps 1ms when divisible by one million. Rust uses the same Tokio biased try_join and direct futures; Go uses two goroutines and a WaitGroup with GOMAXPROCS=1. This measures successful completion, not cancellation/error equivalence; timer resolution and scheduling differ.'
if 'token' in args.shape:
report['token_semantics'] = 'Generate a new 32-byte key from the real OS secure random source for each varying decimal input, compute two HMAC-SHA256 digests, compare all digest bytes and checksum the validated inputs. Rust uses the same getrandom/RustCrypto/Bytes/Zeroizing without Dever runtime. Go uses crypto/rand, hmac and clear; this does not prove equivalent zeroization or RNG failure behavior.'
report['cpu_affinity'] = sorted(os.sched_getaffinity(0))
if any(shape in ('file', 'file_stream') for shape in args.shape):
fixture = root / 'input.bin'
pattern = bytes(range(64)) * 1024
with fixture.open('xb') as output:
full, tail = divmod(args.size, 1024)
for _ in range(full):
output.write(pattern)
output.write(bytes(range(64)) * tail)
report['file_fixture'] = dict(path=str(fixture), sha256=fingerprint(fixture), bytes=fixture.stat().st_size)
report['file_semantics'] = 'Shared file cursor, n synchronous 64-byte reads, checked sum of every returned byte, explicit EOF probe and close. File prepared before builds/timing; warm page cache. Independent Rust uses std File/Mutex/Arc and Bytes, no Dever runtime; Go uses os.File and Mutex. This measures successful reads, not durable writes, cold storage or cancellation.'
if 'file_stream' in args.shape:
report['file_stream_semantics'] = 'Lazily read the same shared file through a shared synchronous stream at 64 bytes per chunk, sum every byte and count every chunk, close the stream and verify a second traversal is empty while retaining the file alias for explicit close. Independent Rust uses std Arc/Mutex and Bytes without Dever runtime. Go uses os.File and Mutex. Error and short-circuit behavior tested separately.'
if 'arguments' in args.shape:
report['arguments_semantics'] = 'All peers receive identical argv[1..]: command name and JSON input. Each iteration obtains a fresh argument list, checks UTF-8 and sums every Unicode character with checked Int arithmetic. Rust uses std args_os without Dever runtime; Go copies its slice and shares immutable string contents. Allocation contracts are language-specific.'
report['arguments_scope'] = 'Whole-process time; all peers decode the same JSON object. Dever wraps the final checksum in its response envelope. The optional runtime peer only diagnoses generated-layer cost and is not an independent Rust reference.'
if 'net' in args.shape:
report['net_semantics'] = 'One persistent loopback TCP pair, TCP_NODELAY on both ends; each iteration writes value modulo 251 as one byte, reads and verifies it, then increments a checked count. Rust uses Tokio directly without Dever runtime; no alias-close, cancellation or read/write-lock equivalence is claimed by this success-path timing. Go uses its standard TCP stack with GOMAXPROCS=1. Tests separately cover close, cancellation, streams and deadlines.'
if 'stdout' in args.shape:
report['stdout_semantics'] = 'Write decimal values 0..n as separate lines, then the checked count; validate every line outside the timed process. Rust uses std stdout lock and writeln without Dever runtime. Files retain real output; this is successful writing, not equivalent error handling or durable storage.'
if 'concurrent' in args.shape:
report['concurrent_semantics'] = 'n ordered results, capacity 64 including pending delivery, one real 1ms timer per 4096 inputs, validate each delivered value against its position. Rust uses futures-util buffered without Dever runtime; Go uses 64 workers with a bounded ordered window. This success workload does not establish equivalent failure observation/cancellation contracts.'
source_hashes = {}
if 'tls' in args.shape:
report['tls_semantics'] = 'Repeatedly parse the same CA PEM and construct a shared TLS client configuration with the default session cache; count only successful configurations. Rust directly uses the same locked rustls/ring without Dever runtime. Go uses crypto/x509 and crypto/tls. This is configuration cost, not handshake throughput or equivalent certificate-policy behavior; real handshake rejection is tested separately.'
if args.core_source:
core = args.core_source.resolve(strict=True)
inputs = [core / 'rust/Cargo.lock']
inputs += sorted(path for path in (core / 'rust/src/runtime').rglob('*') if path.is_file() and path.suffix in {'.rs', '.toml'})
inputs += sorted((core / 'lib').rglob('*.dv'))
source_hashes = {str(path.relative_to(core)): fingerprint(path) for path in inputs}
locked_packages = {
(p['name'], p['version'], p.get('source'))
for p in tomllib.loads((core/'rust/Cargo.lock').read_text())['package']
}
for path in inputs:
saved = root / 'inputs' / path.relative_to(core)
saved.parent.mkdir(parents=True, exist_ok=True)
saved.write_bytes(path.read_bytes())
report.update(core_source=str(core), source_hashes=source_hashes)
def save():
(root/'results.json').write_text(json.dumps(report, indent=2) + '\n')
for language, command in [('rust', ['rustc', '+1.95.0', '--version', '--verbose']), ('go', ['go', 'version'])]:
result = execute(command, root, language + '-version', 30)
if result['exit_code']: raise SystemExit(result['stderr'])
report['versions'][language] = Path(result['stdout']).read_text()
programs = {}
if any(shape in args.shape for shape in ['http', 'http_pool', 'http_stream']):
port = http_server(root)
if 'http' in args.shape:
report['http_semantics'] = 'Each iteration opens a new loopback HTTP/1 connection to the same Node echo fixture, sends the varying decimal input, checks status, bounds the response body and verifies every returned byte. CPU affinity includes the fixture. Rust uses the same locked Hyper/Tokio without Dever runtime; Go uses net/http with keep-alive disabled. No pool, TLS, HTTP/2, load/concurrency or full protocol-error equivalence is claimed by this successful sequential workload.'
if 'http_pool' in args.shape:
report['http_pool_semantics'] = 'Same varying body, status/header/body bounds and every returned byte checked; one shared HTTP/1 client per process, 10000ms idle timeout, no retries. Independent Rust uses locked Hyper legacy Client directly; Go uses net/http keep-alive. Sequential successful calls only; TLS/H2, concurrency, cancellation, fault tracking and DNS lifecycle are covered by separate functional tests, not equivalent performance claims.'
if 'http_stream' in args.shape:
report['http_stream_semantics'] = 'Same HTTP/1 pool and varying body as http_pool; download incrementally, compare every chunk at its exact offset and verify final length without collecting the response. Rust uses Hyper frames directly, Go uses Body.Read. Successful small-response cost only, not full timeout/TLS/cancellation or bounded-memory large-stream equivalence.'
report['http_server_sha256'] = fingerprint(root/'http-server.cjs')
for shape in args.shape:
for language in languages:
case = root/f'{shape}-{language}'
case.mkdir()
path = case/('main.' + dict(dever='dever', old='dever', rust='rs', go='go', runtime='rs')[language])
if language == 'old':
domain = case / 'module/main/main'
domain.mkdir(parents=True)
path = domain / 'app.dever'
(domain / 'api.dever').write_text('cmd bench = app.measure\n')
text = legacy_source(shape).removesuffix('cmd bench = app.measure\n') if language == 'old' else source(language, shape)
path.write_text(text)
binary = case/'program'
if language in ('dever', 'old'):
tool = old if language == 'old' else compiler
application = case if language == 'old' else port_project(case, path.read_text()) if shape == 'port' else path
formatted = execute([str(tool), 'fmt', str(application)], case, 'format', 30)
if formatted['exit_code']: raise SystemExit(formatted['stderr'])
command = [str(tool), 'build', str(application), '--output', str(binary)]
elif language in ('rust', 'runtime') and shape in ('group', 'index', 'bytes', 'uuid', 'calendar', 'settings', 'port', 'crypto', 'token', 'file', 'file_stream', 'async', 'parallel', 'concurrent', 'arguments', 'net', 'tls', 'http', 'http_pool', 'http_stream'):
dependencies = 'bytes = "=1.12.1"' if shape == 'bytes' else 'indexmap = "=2.14.0"\nahash = "=0.8.12"'
if shape in ('async', 'parallel', 'concurrent'):
dependencies = 'tokio = { version = "=1.53.1", features = ["rt", "time", "macros", "sync"] }'
if shape == 'concurrent':
dependencies += '\nfutures-util = "=0.3.34"'
if shape == 'arguments':
dependencies = 'serde_json = "=1.0.145"'
if shape == 'net':
dependencies = 'tokio = { version = "=1.53.1", features = ["rt", "net", "io-util", "time"] }\nbytes = "=1.12.1"'
if language == 'runtime':
features = ', features = ["net"]' if shape == 'net' else ''
dependencies += '\ndever-runtime = { path = ' + json.dumps(str(core / 'rust/src/runtime')) + features + ' }'
if shape == 'uuid':
dependencies = 'uuid = "=1.28.0"'
if shape == 'calendar':
dependencies = 'chrono = { version = "=0.4.45", default-features = false, features = ["std"] }'
if shape in ('settings', 'port'):
dependencies = 'serde = { version = "=1.0.228", features = ["derive"] }\nserde_json = "=1.0.145"'
if shape == 'tls':
dependencies = 'rustls = { version = "=0.23.44", default-features = false, features = ["std", "ring", "tls12"] }\nserde = { version = "=1.0.228", features = ["derive"] }\nserde_json = "=1.0.145"'
if shape in ('http', 'http_pool', 'http_stream'):
dependencies = '\n'.join(['hyper = { version = "=1.11.1", features = ["http1", "http2", "client", "server"] }', 'hyper-util = { version = "=0.1.20", features = ["tokio"] }', 'http-body-util = "=0.1.5"', 'tokio = { version = "=1.53.1", features = ["rt", "net", "io-util", "time", "macros"] }', 'bytes = "=1.12.1"', 'serde = { version = "=1.0.228", features = ["derive"] }', 'serde_json = "=1.0.145"'])
if shape in ('http_pool', 'http_stream'):
dependencies = dependencies.replace('features = ["tokio"]', 'features = ["tokio", "client-legacy", "http1", "http2"]')
if shape in ('file', 'file_stream'):
dependencies = chr(10).join(['bytes = "=1.12.1"', 'serde = { version = "=1.0.228", features = ["derive"] }', 'serde_json = "=1.0.145"'])
if shape == 'token':
dependencies = chr(10).join(['getrandom = "=0.2.17"', 'sha2 = "=0.10.9"', 'hmac = "=0.12.1"', 'bytes = "=1.12.1"', 'zeroize = "=1.9.0"', 'subtle = "=2.6.1"'])
if shape == 'crypto':
dependencies = 'serde = { version = "=1.0.228", features = ["derive"] }\nserde_json = "=1.0.145"\nsha2 = "=0.10.9"\nhmac = "=0.12.1"\nbytes = "=1.12.1"\nzeroize = "=1.9.0"'
(case/'Cargo.toml').write_text('''[package]
name = "collection-reference"
version = "0.0.1"
edition = "2024"
[[bin]]
name = "collection-reference"
path = "main.rs"
[dependencies]
''' + dependencies + '''
[profile.release]
lto = "fat"
codegen-units = 1
overflow-checks = true
strip = "symbols"
''')
if args.core_source:
# 参考端沿用核心锁中的传递依赖,避免离线缓存选出不同版本。
(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(case/'target')]
binary = case/'target/release/collection-reference'
elif language == 'rust':
command = ['rustc', '+1.95.0', '--edition=2024', '-C', 'opt-level=3', '-C', 'lto=fat', '-C', 'codegen-units=1', '-C', 'overflow-checks=true', '-C', 'strip=symbols', str(path), '-o', str(binary)]
else:
(case/'go.mod').write_text(f'module loop-reference/{root.name}/{shape}\n\ngo 1.25.0\n')
command = ['go', '-C', str(case), 'build', '-buildvcs=false', '-p', '1', '-trimpath', '-o', str(binary), '.']
result = dict(language=language, shape=shape, source_sha256=fingerprint(path),
source_lines=len(path.read_text().splitlines()), **execute(command, case, 'build', 900))
if (shape == 'port' and language == 'dever') or language == 'old':
result['project_sources'] = {str(p.relative_to(case)): fingerprint(p) for p in sorted((case/'module').rglob('*.dever'))}
result['source_lines'] = sum(len(p.read_text().splitlines()) for p in (case/'module').rglob('*.dever'))
report['builds'].append(result)
if result['exit_code']:
save()
raise SystemExit(result['stderr'])
result['binary_sha256'] = fingerprint(binary)
if language in ('rust', 'runtime') and (case/'Cargo.lock').exists():
result['lock_sha256'] = fingerprint(case/'Cargo.lock')
if args.core_source:
packages = tomllib.loads((case/'Cargo.lock').read_text())['package']
different = [(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_packages]
result['dependency_differences'] = different
if different:
save()
raise SystemExit(f'reference dependencies differ from core lock: {different}')
if shape in ('settings', 'port', 'crypto', 'file', 'file_stream', 'tls', 'http', 'http_pool', 'http_stream'):
config = case / 'setting.json'
value = port_config() if shape == 'port' else settings_config() if shape == 'settings' else crypto_config()
if shape in ('http', 'http_pool', 'http_stream'):
value = {'module': {'main': {'main': {'port': port}}}}
if shape == 'tls':
ca_pem = (Path(__file__).parent.parent/'fixtures/tls/root.pem').read_text()
value = {'module': {'main': {'main': {'ca_pem': ca_pem}}}}
if shape in ('file', 'file_stream'):
value = {'module': {'main': {'main': {'input': str(root / 'input.bin')}}}}
config.write_text(json.dumps(value, ensure_ascii=False))
result['config_sha256'] = fingerprint(config)
programs[shape, language] = binary
save()
# 预热也核验并留原始结果,不混入固定七轮统计。输入由进程参数传入。
for repeat in range(-1, 7):
if source_hashes:
assert source_hashes == {str(path.relative_to(core)): fingerprint(path) for path in inputs}, 'runtime/library inputs changed during measurement'
for shape in args.shape:
for offset in range(len(languages)):
language = languages[(repeat + 1 + offset) % len(languages)]
binary = programs[shape, language]
n = args.size
count = (n + 1) // 2
expected = n * (n - 1) // 2 if shape != 'filtered' else count * (count - 1) + n
if shape == 'group':
expected += min(n, 64) * (min(n, 64) - 1) // 2
elif shape == 'index':
expected *= 2
elif shape == 'foldUntil':
consumed = min(n, n // 2 + 1)
expected = consumed * (consumed - 1) // 2
elif shape == 'fields':
expected = 3 * expected + n
elif shape == 'calendar':
expected = n
elif shape == 'parallel':
expected = n * n
elif shape in ('concurrent', 'stdout', 'net', 'tls', 'http', 'http_pool', 'http_stream'):
expected = n
elif shape == 'arguments':
expected = n * (len('main.main.bench') + len(json.dumps(dict(n=n))))
elif shape in ('settings', 'port'):
expected = settings_expected(n)
elif shape in ('file', 'file_stream'):
expected = n * sum(range(64))
elif shape == 'crypto':
expected = crypto_expected(n)
elif shape == 'uuid':
expected = (n // 10) * 45 + (n % 10) * ((n % 10) - 1) // 2
elif shape == 'bytes':
expected = (n // 256) * 32640 + (n % 256) * ((n % 256) - 1) // 2
command = [str(binary), 'main.main.bench', json.dumps(dict(n=n))] if language in ('dever', 'old') or shape == 'arguments' else [str(binary), str(n)]
if shape in ('settings', 'port', 'crypto', 'file', 'file_stream', 'tls', 'http', 'http_pool', 'http_stream'):
config = root / f'{shape}-{language}' / 'setting.json'
if language == 'dever':
command[1:1] = ['--config', str(config)]
else:
command.append(str(config))
result = dict(language=language, shape=shape, repeat=repeat, expected=expected,
**execute(command, binary.parent, f'run-{repeat}', 60))
output = Path(result['stdout']).read_text()
if shape == 'stdout':
rows = output.splitlines()
result['correct'] = (result['exit_code'] == 0 and len(rows) == n + 1
and all(row == str(index) for index, row in enumerate(rows[:-1]))
and (json.loads(rows[-1])['data'] if language == 'dever' else int(rows[-1])) == expected)
else:
result['correct'] = result['exit_code'] == 0 and (json.loads(output)['data'] if language in ('dever', 'old') else int(output)) == expected
report['samples'].append(result)
save()
print(json.dumps(result), flush=True)
if not result['correct']: raise SystemExit('incorrect result: ' + result['stderr'])
report['medians'] = {shape: {language: statistics.median(
sample['seconds'] for sample in report['samples']
if sample['shape'] == shape and sample['language'] == language and sample['repeat'] >= 0
) for language in languages} for shape in args.shape}
save()
print(json.dumps(report['medians']), flush=True)
if __name__ == '__main__':
main()