"""真实创建并领取叶子任务;独立 Rust 直接使用 Tokio,不依赖 Dever 运行库。""" import argparse import json import os from pathlib import Path import shutil import statistics from scale import execute, fingerprint import task_combinations import channel_reference import stream_reference def source(language, shape='wait'): if shape == 'stream': return stream_reference.source(language) if shape == 'channel': return channel_reference.source(language) if shape in {'timeout', 'race', 'group', 'parallel', 'blocking', 'blocking_run'}: return task_combinations.source(language, shape) if language == 'dever': return """identity(value: Int) (out: Int) { out = value } flow receive(value: Int) (out: Int) | step | kind | do | | task | calc | run(identity(value)) | | out | calc | wait(task) | loop total(n: Int) (out: Int) | each value in range(0, n) | result | | out | sum receive(value) | cmd total = total """ if shape != 'wait': return cleanup_source(language, shape) if language == 'runtime': return '''fn main() { let n: i64 = std::env::args().nth(1).unwrap().parse().unwrap(); let result = dever_runtime::task::run(true, 4096, async |scope| { let mut sum = 0i64; for value in 0..n { let task = scope.spawn_leaf(async move { value }).unwrap(); sum = sum.checked_add(task.wait().await.unwrap()).expect("sum overflow"); } Ok::<_, ()>(sum) }).unwrap().unwrap(); println!("{result}"); } ''' if language == 'rust': return '''use std::sync::Arc; use tokio::{sync::Semaphore, runtime::Builder}; use tokio_util::task::{TaskTracker, AbortOnDropHandle}; fn main() { let n: i64 = std::env::args().nth(1).unwrap().parse().unwrap(); let runtime = Builder::new_current_thread().enable_time().build().unwrap(); let result = runtime.block_on(async { let capacity = Arc::new(Semaphore::new(4096)); let tracker = TaskTracker::new(); let mut sum = 0i64; for value in 0..n { let permit = capacity.clone().try_acquire_owned().unwrap(); let tracking = tracker.token(); let task = AbortOnDropHandle::new(tokio::spawn(async move { drop(permit); (value, tracking) })); let (value, _tracking) = task.await.unwrap(); sum = sum.checked_add(value).expect("sum overflow"); } tracker.close(); tracker.wait().await; sum }); println!("{result}"); } ''' return '''package main import ("fmt"; "os"; "strconv") func main() { n, err := strconv.ParseInt(os.Args[1], 10, 64); if err != nil { panic(err) } sum := int64(0) for value := int64(0); value < n; value++ { completed := make(chan int64, 1) go func(input int64) { completed <- input }(value) next := sum + <-completed if next < sum { panic("sum overflow") }; sum = next } fmt.Println(sum) } ''' def cleanup_source(language, shape): prefix = '''use std::{future::pending, sync::{Arc, atomic::{AtomicI64, Ordering}}}; struct Released(Arc, i64); impl Drop for Released { fn drop(&mut self) { self.0.fetch_add(self.1, Ordering::SeqCst); } } fn main() { let n: i64 = std::env::args().nth(1).unwrap().parse().unwrap(); let released = Arc::new(AtomicI64::new(0)); ''' if language == 'runtime': begin = ''' dever_runtime::task::run(true, 64, async |scope| { for value in 0..n { let held = Released(released.clone(), value); let task = scope.spawn_leaf(async move { let _held = held; pending::().await }).unwrap(); ''' action = ' assert_eq!(task.stop().await, Ok(None));' if shape == 'stop' else ' drop(task);\n tokio::task::yield_now().await;' end = ''' } Ok::<_, ()>(()) }).unwrap().unwrap(); ''' else: begin = ''' use tokio::{sync::Semaphore, runtime::Builder}; use tokio_util::task::{TaskTracker, AbortOnDropHandle}; let runtime = Builder::new_current_thread().enable_time().build().unwrap(); runtime.block_on(async { let capacity = Arc::new(Semaphore::new(64)); let tracker = TaskTracker::new(); for value in 0..n { let held = Released(released.clone(), value); let permit = capacity.clone().try_acquire_owned().unwrap(); let tracking = tracker.token(); let task = AbortOnDropHandle::new(tokio::spawn(async move { let _held = held; let value = pending::().await; drop(permit); (value, tracking) })); ''' action = ' task.abort();\n assert!(task.await.unwrap_err().is_cancelled());' if shape == 'stop' else ' drop(task);\n tokio::task::yield_now().await;' end = ''' } tracker.close(); tracker.wait().await; }); ''' return prefix + begin + action + end + ' println!("{}", released.load(Ordering::SeqCst));\n}\n' def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--output', type=Path, required=True) parser.add_argument('--core-source', type=Path, required=True) parser.add_argument('--size', type=int, default=1000000) parser.add_argument('--shape', choices=['wait', 'stop', 'drop', 'timeout', 'race', 'group', 'parallel', 'blocking', 'blocking_run', 'channel', 'stream'], default='wait') parser.add_argument('--previous-source', type=Path) parser.add_argument('--dever-binary', type=Path, help='Include real compiled Dever task operations against independent references') args = parser.parse_args() if not 1 <= args.size <= 1000000000: parser.error('size must be within 1..1000000000') if args.dever_binary and args.shape in {'stop', 'drop'}: parser.error('Dever comparisons support wait/timeout/race/group/parallel') compiler = args.dever_binary.resolve(strict=True) if args.dever_binary else None core = args.core_source.resolve(strict=True) root = args.output.resolve() root.mkdir(parents=True, exist_ok=False) os.environ.update(CARGO_BUILD_JOBS='1', GOMAXPROCS='1', GOTOOLCHAIN='local') for name in ['task.py', 'scale.py', 'task_combinations.py', 'channel_reference.py', 'stream_reference.py']: (root / name).write_bytes(Path(__file__).with_name(name).read_bytes()) inputs = [core / 'rust/Cargo.lock'] + sorted(path for path in (core / 'rust/src/runtime').rglob('*') if path.suffix in {'.rs', '.toml'}) if compiler: inputs += sorted((core / 'rust/src/compiler').rglob('*.rs')) inputs += sorted((core / 'lib').rglob('*.dv')) hashes = {str(path.relative_to(core)): fingerprint(path) for path in inputs} 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()) previous = args.previous_source.resolve(strict=True) if args.previous_source else None previous_hashes = {str(path.relative_to(previous)): fingerprint(path) for path in sorted((previous / 'rust/src/runtime').rglob('*')) if path.suffix in {'.rs', '.toml'}} if previous else {} report = dict(size=args.size, shape=args.shape, rounds=7, cpu_affinity=sorted(os.sched_getaffinity(0)), inputs=hashes, previous_source=str(previous) if previous else None, previous_inputs=previous_hashes, versions={}, builds=[], samples=[], semantics='Spawn one leaf task, await its result, checked i64 checksum; one task at a time. Runtime and independent Rust use the same Tokio current-thread runtime, task tracking and capacity permits. Rust uses AbortOnDropHandle. Go uses native goroutines/channels with GOMAXPROCS=1. This measures successful spawn/join, not equivalence of failure journals, descendant cleanup or language frontend performance.', scope='Whole-process time. wait4 RSS may include Python fork memory; not application-only RSS. Cargo dependencies share a within-run build cache; build times are not cold-build comparisons.', environment={name: (Path('/sys/fs/cgroup')/name).read_text().strip() for name in ['cpu.max', 'memory.max']}) if args.shape != 'wait': report['semantics'] = 'Cancel a pending leaf before its first poll using stop/await or drop/yield. A destructor accumulates every owned input and is checked after root cleanup. Independent Rust uses the same Tokio, capacity and task tracker, but has no unclaimed-fault journal. Go is omitted because goroutine cancellation is not equivalent.' if args.shape in {'timeout', 'race', 'group'}: report['semantics'] = 'Successful task composition: timeout with a 60s deadline and immediate result; race of two equal results with biased parameter order and loser cancellation/join; group of two zero-output members at limit=1, checked nonnegative input and full drain. Checksums are checked i64 sums. Independent Rust uses Tokio, AbortOnDropHandle, Semaphore, TaskTracker and FuturesUnordered; no Dever runtime. Fault journals and descendant faults are tested separately, not compared by these successful-path timings. Go omitted because cancellation contracts differ.' if args.shape == 'parallel': report['semantics'] = 'Two concurrent CPU calls per group, each summing 4096 checked i64 additions modulo 97. Eight worker slots, Tokio spawn_blocking, owned values, task tracking and cancellation handles; independent Rust does not use Dever runtime. Successful-path timings do not compare fault journals; queued cancellation and running-work cleanup are tested separately. Go omitted because cancellation contracts differ.' blocking = args.shape in {'blocking', 'blocking_run'} if blocking: report['semantics'] = 'Real Argon2id v19 verification at default m=19456,t=2,p=1 with the same public benchmark password and PHC input. Owned password/hash per call, eight worker slots, direct blocking or spawned blocking task then wait; checked checksum of successful verifications. Independent Rust uses Argon2 and Tokio directly, not Dever runtime. Success timing does not establish fault-journal equivalence; cancellation and late errors are tested separately.' if compiler: report['compiler'] = dict(binary=str(compiler), sha256=fingerprint(compiler)) report['semantics'] += ' Dever uses real task flow steps, sequential loop sum and the generated CMD input/output boundary.' if args.shape == 'channel': report['semantics'] = 'One producer task sends n integers to a shared bounded channel at capacity 64; one consumer verifies every receive and accumulates a checked i64 checksum. Explicit close, full drain and producer join. Independent Rust uses async-channel 2.5.0 and Tokio directly, with task capacity and tracking, no Dever runtime. Success timing does not establish fault-journal equivalence; cancellation, aliases and close are tested separately.' if args.shape == 'stream': report['semantics'] = 'Construct n integers, move the Vec into one shared boxed async stream, consume once with checked i64 checksum, close it and verify a second traversal is empty. Independent Rust directly uses futures-util and Tokio mutex/semaphore, with close notification and a consumption guard; it does not depend on Dever runtime. Successful drain timings do not compare runtime-fault diagnostics or the closed-then-cancelled-pull drop path, which are separately tested.' 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) assert result['exit_code'] == 0, result report['versions'][language] = Path(result['stdout']).read_text() programs = {} arguments = {} languages = ['runtime', 'rust'] + (['go'] if args.shape == 'wait' else []) + (['previous'] if previous else []) + (['dever'] if compiler else []) for language in languages: case = root / language case.mkdir() path = case / ('main.go' if language == 'go' else 'app.dever' if language == 'dever' else 'main.rs') path.write_text(source('runtime' if language == 'previous' else language, args.shape)) arguments[language] = [str(args.size)] if language == 'dever': formatted = dict(language='dever-format', **execute([str(compiler), 'fmt', str(path)], case, 'format', 30)) report['builds'].append(formatted) save() assert formatted['exit_code'] == 0, formatted binary = case / 'program' command = [str(compiler), 'build', str(path), '--profile', 'release', '--output', str(binary)] arguments[language] = ['main.main.total', json.dumps(dict(n=args.size))] elif language == 'go': (case / 'go.mod').write_text(f'module tasks/{root.name}\n\ngo 1.25.0\n') binary = case / 'program' command = ['go', '-C', str(case), 'build', '-buildvcs=false', '-p', '1', '-trimpath', '-o', str(binary), '.'] else: dependency = 'tokio = { version = "=1.53.1", features = ["rt", "sync", "time", "macros"] }' dependency += '\nfutures-util = { version = "=0.3.34", default-features = false, features = ["std"] }' if language in ['runtime', 'previous']: dependency += f'\ndever-runtime = {{ path = {json.dumps(str((previous if language == "previous" else core) / "rust/src/runtime"))} }}' else: dependency += '\ntokio-util = { version = "=0.7.19", features = ["rt"] }' if blocking: dependency += '\nargon2 = { version = "=0.5.3", features = ["zeroize"] }\nzeroize = "=1.9.0"' if args.shape == 'channel': dependency += '\nasync-channel = "=2.5.0"' (case / 'Cargo.toml').write_text('[package]\nname = "task-reference"\nversion = "0.0.1"\nedition = "2024"\n[[bin]]\nname = "task-reference"\npath = "main.rs"\n[dependencies]\n' + dependency + '\n[profile.release]\nlto = "fat"\ncodegen-units = 1\noverflow-checks = true\nstrip = "symbols"\n') command = ['cargo', '+1.95.0', 'build', '--manifest-path', str(case / 'Cargo.toml'), '--offline', '--release', '--target-dir', str(root / 'cargo-build')] binary = case / 'program' result = dict(language=language, source_sha256=fingerprint(path), **execute(command, case, 'build', 900)) report['builds'].append(result) save() assert result['exit_code'] == 0, result if language not in ['go', 'dever']: shutil.copy2(root / 'cargo-build/release/task-reference', binary) result['binary'] = str(binary) result['binary_sha256'] = fingerprint(binary) programs[language] = binary languages = list(programs) if blocking: fixture = execute([str(programs['rust']), '--fixture'], root, 'fixture', 60) report['fixture'] = fixture save() assert fixture['exit_code'] == 0, fixture encoded = Path(fixture['stdout']).read_text().strip() password = 'public-benchmark-password' for language in languages: if language == 'dever': arguments[language] = ['main.main.total', json.dumps(dict(n=args.size, password=password, hash=encoded))] else: arguments[language] += [password, encoded] # 模 97 的完整周期与尾段独立计算校验和,不复制被测循环。 def residue_sum(end): periods, rest = divmod(end, 97) return periods * 96 * 97 // 2 + rest * (rest - 1) // 2 expected = args.size * (args.size - 1) // 2 if args.shape == 'parallel': period = [residue_sum(value + 4096) - residue_sum(value) + residue_sum(value + 4097) - residue_sum(value + 1) for value in range(97)] periods, rest = divmod(args.size, 97) expected = periods * sum(period) + sum(period[:rest]) report['expected'] = expected for repeat in range(-1, 7): assert hashes == {str(path.relative_to(core)): fingerprint(path) for path in inputs}, 'runtime changed during measurement' assert all(fingerprint(previous / name) == digest for name, digest in previous_hashes.items()), 'previous runtime changed during measurement' for offset in range(len(languages)): language = languages[(repeat + 1 + offset) % len(languages)] binary = programs[language] result = dict(language=language, repeat=repeat, **execute([str(binary)] + arguments[language], binary.parent, f'run-{repeat}', 60)) output = Path(result['stdout']).read_text() value = json.loads(output)['data'] if language == 'dever' and result['exit_code'] == 0 else output result['correct'] = result['exit_code'] == 0 and int(value) == expected report['samples'].append(result) save() assert result['correct'], result report['medians'] = {language: statistics.median(row['seconds'] for row in report['samples'] if row['language'] == language and row['repeat'] >= 0) for language in languages} save() print(json.dumps(report['medians'])) if __name__ == '__main__': main()