File size: 12,359 Bytes
bbff072
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
#!/usr/bin/env python3
"""Compare V5, V7 and V8 admission with every final checkpoint included.

Linux/POSIX regular-file prototype measurements only. No native NTFS result,
physical NAND measurement, simulated force delay, or device fault qualification.
"""
from __future__ import annotations
import argparse
import hashlib
import importlib.util
import json
from pathlib import Path
import platform
import random
import statistics
import sys
import tempfile
import time

sys.dont_write_bytecode = True
HERE = Path(__file__).resolve().parent
ROOT = HERE.parent


def load(name, path):
    spec = importlib.util.spec_from_file_location(name, path)
    module = importlib.util.module_from_spec(spec)
    sys.modules[name] = module
    spec.loader.exec_module(module)
    return module


def sha(path):
    return hashlib.sha256(path.read_bytes()).hexdigest()


def percentile(values, q):
    values = sorted(values)
    point = (len(values) - 1) * q
    lower = int(point)
    upper = min(lower + 1, len(values) - 1)
    return values[lower] + (values[upper] - values[lower]) * (point - lower)


def value(label, index):
    return hashlib.shake_256(f'{label}/{index}'.encode()).digest(128)


def workload(namespace, operations, kind):
    if kind == 'bulk_append':
        # A separate atomic workload: one durable transaction contains 128 new
        # keys. Transaction throughput and logical-key throughput differ.
        return [({f'/append/{i:04d}/{j:04d}': value('append', i * 128 + j)
                  for j in range(128)}, f'append-{i:06d}') for i in range(64)]
    names = [f'/file/{i:06d}' for i in range(namespace)]
    candidates = [p for p in names if hashlib.sha256(p.encode()).hexdigest().startswith('0')] if kind == 'hot_prefix' else names
    if not candidates:
        raise ValueError('namespace has no hot-prefix keys')
    rng = random.Random(601131)
    return [({rng.choice(candidates): value(kind, i)}, f'{kind}-{i:06d}') for i in range(operations)]


def allocation(path):
    stat = path.stat()
    return {'apparent_bytes': stat.st_size, 'filesystem_allocated_bytes': getattr(stat, 'st_blocks', 0) * 512}


def run_trial(module, backend, namespace, requests, pool_blocks, kind, trial):
    initial = {f'/file/{i:06d}': value('initial', i) for i in range(namespace)}
    expected = dict(initial)
    epochs = {}
    with tempfile.TemporaryDirectory(prefix='nyarion-admission-benchmark-') as tmp:
        image = Path(tmp) / 'volume.img'
        store = module.PageStore.create(image, initial_files=initial, pool_blocks=pool_blocks)
        before_allocation = allocation(image)
        store.reset_stats()
        latency = []
        started = time.perf_counter_ns()
        for changes, token in requests:
            begin = time.perf_counter_ns()
            epoch = store.transact(changes, token)
            latency.append((time.perf_counter_ns() - begin) / 1e6)
            epochs[token] = epoch
        transaction_end = time.perf_counter_ns()
        store.checkpoint()
        finished = time.perf_counter_ns()
        stats = dict(store.stats)
        if backend == 'v8':
            assert stats.get('full_graph_scans') == 0, 'timed V8 workload must not scan the full graph'
        elapsed = (finished - started) / 1e9
        for changes, _ in requests:
            expected.update(changes)
        assert store.files() == sorted(expected)
        for key, data in expected.items():
            assert store.get(key) == data
        for token, epoch in epochs.items():
            assert store.query(token)['epoch'] == epoch
        assert store.epoch == len(requests)
        after_allocation = allocation(image)
        store.close()
        with module.PageStore(image, writable=False) as reopened:
            assert reopened.epoch == len(requests)
            assert reopened.files() == sorted(expected)
            for key, data in expected.items():
                assert reopened.get(key) == data
            for token, epoch in epochs.items():
                assert reopened.query(token)['epoch'] == epoch
        request_digest = hashlib.sha256(json.dumps(
            [[[key, hashlib.sha256(data).hexdigest()] for key, data in sorted(changes.items())] + [token]
             for changes, token in requests], separators=(',', ':')).encode()).hexdigest()
        logical_updates = sum(len(changes) for changes, _ in requests)
        return {'backend': backend, 'namespace_files': namespace, 'workload': kind,
                'workload_sha256': request_digest,
                'trial': trial, 'transactions': len(requests), 'value_bytes': 128,
                'logical_key_updates': logical_updates,
                'keys_per_transaction': len(requests[0][0]),
                'elapsed_with_final_checkpoint_seconds': elapsed,
                'drained_transactions_per_second': len(requests) / elapsed,
                'drained_logical_key_updates_per_second': logical_updates / elapsed,
                'transaction_calls_seconds': (transaction_end - started) / 1e9,
                'final_checkpoint_ms': (finished - transaction_end) / 1e6,
                'latencies_ms': latency, 'latency_ms_p50': percentile(latency, .5),
                'latency_ms_p95': percentile(latency, .95), 'latency_ms_p99': percentile(latency, .99),
                'latency_ms_max': max(latency), 'engine_stats': stats,
                'allocation_before': before_allocation, 'allocation_after': after_allocation,
                'configured_arena_blocks': pool_blocks, 'configured_arena_bytes': pool_blocks * 4096,
                'all_values_and_exact_token_epochs_verified_before_and_after_reopen': True}


def filesystem_type(path):
    try:
        path = str(Path(path).resolve())
        matches = []
        for line in Path('/proc/mounts').read_text().splitlines():
            fields = line.split()
            mount = fields[1].replace('\\040', ' ')
            if path == mount or path.startswith(mount.rstrip('/') + '/'):
                matches.append((len(mount), fields[2]))
        return max(matches)[1] if matches else 'unknown'
    except (OSError, IndexError):
        return 'unknown'


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--namespaces', nargs='+', type=int, default=[4096, 16384, 65536])
    parser.add_argument('--operations', type=int, default=128)
    parser.add_argument('--trials', type=int, default=3)
    parser.add_argument('--pool-blocks', type=int, default=32768)
    parser.add_argument('--output', type=Path, default=HERE / 'benchmark_final_results.json')
    args = parser.parse_args()
    if min(*args.namespaces, args.operations, args.trials, args.pool_blocks) < 1:
        parser.error('positive sizes required')
    paths = {'v5': HERE / 'baselines/v5.py', 'v7': HERE / 'baselines/v7.py', 'v8': ROOT / 'pagefs.py', 'benchmark': Path(__file__).resolve()}
    hashes = {name: sha(path) for name, path in paths.items()}
    modules = {name: load('v8_benchmark_' + name, paths[name]) for name in ('v5', 'v7', 'v8')}
    rows = []
    configurations = [(n, kind) for n in args.namespaces for kind in ('hot_prefix', 'uniform')]
    configurations.append((0, 'bulk_append'))
    for n, kind in configurations:
        requests = workload(n, args.operations, kind)
        for trial in range(args.trials):
            backends = ('v5', 'v7', 'v8')
            shift = trial % len(backends)
            order = backends[shift:] + backends[:shift]
            for backend in order:
                print(f'{backend}: N={n}, {kind}, trial {trial + 1}', flush=True)
                rows.append(run_trial(modules[backend], backend, n, requests, args.pool_blocks, kind, trial))
    assert hashes == {name: sha(path) for name, path in paths.items()}, 'source changed during measurement'
    summaries = []
    comparisons = []
    for n, kind in configurations:
        grouped = {}
        for backend in ('v5', 'v7', 'v8'):
            group = [row for row in rows if row['backend'] == backend and row['namespace_files'] == n and row['workload'] == kind]
            summary = {'backend': backend, 'namespace_files': n, 'workload': kind, 'trials': len(group),
                       'transactions': group[0]['transactions'],
                       'logical_key_updates': group[0]['logical_key_updates'],
                       'keys_per_transaction': group[0]['keys_per_transaction']}
            for field in ('drained_transactions_per_second', 'drained_logical_key_updates_per_second', 'elapsed_with_final_checkpoint_seconds', 'final_checkpoint_ms', 'latency_ms_p50', 'latency_ms_p95', 'latency_ms_p99', 'latency_ms_max'):
                summary['median_' + field] = statistics.median(row[field] for row in group)
            for field in sorted(set().union(*(row['engine_stats'] for row in group))):
                values = [row['engine_stats'].get(field, 0) for row in group]
                if all(type(v) in (int, float) for v in values):
                    summary['median_' + field] = statistics.median(values)
            grouped[backend] = summary
            summaries.append(summary)
        a, b, c = grouped['v5'], grouped['v7'], grouped['v8']
        comparisons.append({'namespace_files': n, 'workload': kind,
                            'transactions': c['transactions'], 'keys_per_transaction': c['keys_per_transaction'],
                            'logical_key_updates': c['logical_key_updates'],
                            'v7_over_v5_drained_throughput': b['median_drained_transactions_per_second'] / a['median_drained_transactions_per_second'],
                            'v8_over_v7_drained_throughput': c['median_drained_transactions_per_second'] / b['median_drained_transactions_per_second'],
                            'v8_over_v5_drained_throughput': c['median_drained_transactions_per_second'] / a['median_drained_transactions_per_second'],
                            'v5_over_v8_host_write_bytes': a['median_bytes_written'] / c['median_bytes_written'],
                            'v5_over_v7_host_write_bytes': a['median_bytes_written'] / b['median_bytes_written'],
                            'v5_final_checkpoint_ms': a['median_final_checkpoint_ms'],
                            'v7_final_checkpoint_ms': b['median_final_checkpoint_ms'],
                            'v8_final_checkpoint_ms': c['median_final_checkpoint_ms']})
    result = {'benchmark': 'V5/V7/V8 end-to-end admission comparison including final window drain',
              'date': '2026-11-01', 'engine_source_sha256': hashes, 'sources_unchanged_during_measurement': True,
              'environment': {'os': platform.system(), 'python': platform.python_version(),
                              'temporary_filesystem': filesystem_type(tempfile.gettempdir())},
              'method': {'trials': args.trials, 'order': 'three-way rotating backend order; each engine starts one trial per workload',
                         'timing': 'all transaction admission/planning, automatic maintenance, and one explicit final checkpoint; setup/open and validation excluded',
                         'logical_workload': 'single-key: identical seeded key sequence and 128-byte values, hot means SHA-256 first nibble 0; separate bulk-append: empty genesis, 64 atomic transactions with 128 new 128-byte keys each (8192 logical key updates)',
                         'verification': 'every file name/value and exact transaction receipt epoch before and after read-only reopen',
                         'host_writes': 'engine requested bytes, not NAND traffic',
                         'capacity': 'all three use the same configured fixed arena'},
              'limits': ['Different admission guarantees: V5 can acknowledge an arena-undrainable tail; V7 and V8 precheck logical checkpoint capacity.',
                         'POSIX regular-file prototype comparison, not native NTFS.',
                         'All live logical data remain in RAM; no physical power-cut or device qualification.',
                         'No simulated flush latency, cache dropping, or direct I/O.'],
              'trials': rows, 'summaries': summaries, 'comparisons': comparisons}
    args.output.write_text(json.dumps(result, indent=2, sort_keys=True) + '\n')
    print(json.dumps(comparisons, indent=2), flush=True)


if __name__ == '__main__':
    main()