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
"""Diagnostic builds of the real collection index. Sync ablations change durability."""
import csv
import json
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
repo = Path(__file__).resolve().parents[2]
zkv = repo.parents[1] / "zzstoatzz.io/zkv"
variants = ("profile", "no-file-sync", "no-parent-sync", "no-sync", "no-maintenance")
def edit(path, old, new):
source = path.read_text()
if source.count(old) != 1:
raise ValueError(f"expected one site in {path}: {old}")
path.write_text(source.replace(old, new))
def instrument(work, library, variant):
shutil.copytree(repo, work, ignore=shutil.ignore_patterns(
".git", ".zig-cache", "zig-out", "zig-pkg"))
(work / "zig-pkg").symlink_to(repo / "zig-pkg", target_is_directory=True)
shutil.copytree(zkv, library, ignore=shutil.ignore_patterns(
".git", ".zig-cache", "zig-out", "zig-pkg"))
edit(work / "build.zig.zon", '.path = "../../zzstoatzz.io/zkv"',
f".path = {json.dumps("../" + library.name)}")
store = library / "src/store/dir.zig"
fields = ("metadata_ns", "write_ns", "file_sync_ns", "close_ns",
"publish_ns", "parent_sync_ns", "cleanup_ns")
declaration = """ profile: Profile = .{},
pub const Profile = struct {
""" + "".join(f" {field}: i96 = 0,\n" for field in fields) + """ };
fn profileNow(self: *DirStore) i96 {
return std.Io.Clock.awake.now(self.io).nanoseconds;
}
"""
edit(store, " const open_handles = 8;", declaration + "\n const open_handles = 8;")
edit(store, " if (std.fs.path.dirname(key)) |parent|",
" const metadata_start = self.profileNow();\n if (std.fs.path.dirname(key)) |parent|")
edit(store, " defer file.close(self.io);", """ self.profile.metadata_ns += self.profileNow() - metadata_start;
defer {
const before_close = self.profileNow();
file.close(self.io);
self.profile.close_ns += self.profileNow() - before_close;
}""")
edit(store, " try file.writeStreamingAll(self.io, bytes);", """ const before_write = self.profileNow();
try file.writeStreamingAll(self.io, bytes);
self.profile.write_ns += self.profileNow() - before_write;""")
sync = "" if variant in ("no-file-sync", "no-sync") else "try file.sync(self.io);"
edit(store, " try file.sync(self.io);", f""" const before_sync = self.profileNow();
{sync}
self.profile.file_sync_ns += self.profileNow() - before_sync;""")
edit(store, " defer self.dir.deleteFile(self.io, name) catch {};", """ defer {
const before_cleanup = self.profileNow();
self.dir.deleteFile(self.io, name) catch {};
self.profile.cleanup_ns += self.profileNow() - before_cleanup;
}
const before_publish = self.profileNow();""")
edit(store, " try self.syncParent(key);\n return etagOf(bytes);", """ self.profile.publish_ns += self.profileNow() - before_publish;
try self.syncParent(key);
return etagOf(bytes);""")
parent_sync = "" if variant in ("no-parent-sync", "no-sync") else "try parent.sync(self.io);"
edit(store, " const parent = try self.dir.openFile", " const before_sync = self.profileNow();\n const parent = try self.dir.openFile")
edit(store, " try parent.sync(self.io);", f""" {parent_sync}
self.profile.parent_sync_ns += self.profileNow() - before_sync;""")
adapter = work / "src/internal/collection_index/index.zig"
edit(adapter, " failed: std.atomic.Value(bool) = .init(false),", """ failed: std.atomic.Value(bool) = .init(false),
profile_commit_ns: i96 = 0,
profile_maintenance_ns: i96 = 0,
profile_commits: u64 = 0,""")
edit(adapter, " self.db.commit() catch", """ const before_commit = std.Io.Clock.awake.now(self.io).nanoseconds;
self.db.commit() catch""")
edit(adapter, " if (self.db.unflushedSegments()", """ self.profile_commits += 1;
self.profile_commit_ns += std.Io.Clock.awake.now(self.io).nanoseconds - before_commit;
const before_maintenance = std.Io.Clock.awake.now(self.io).nanoseconds;
defer self.profile_maintenance_ns += std.Io.Clock.awake.now(self.io).nanoseconds - before_maintenance;
if (self.db.unflushedSegments()""")
if variant == "no-maintenance":
edit(adapter, "if (self.db.unflushedSegments() >= 256 or self.db.memtableBytes() >= 4 << 20)",
"if (false)")
driver = work / "src/index_bench.zig"
source = driver.read_text().replace("fn report(io:", "fn report(ci: *index.CollectionIndex, io:")
source = source.replace("report(io,", "report(&ci, io,")
old = ' std.debug.print("{s},{d},{d}\\n", .{ label, n, elapsed });'
new = """ const p = ci.store.profile;
std.debug.print("phase,{s},{d},{d},{d},{d},{d}""" + ",{d}" * len(fields) + """\\n",
.{ label, n, elapsed, ci.profile_commits, ci.profile_commit_ns, ci.profile_maintenance_ns,
""" + "".join(f" p.{field},\n" for field in fields) + """ });
ci.profile_commits = 0;
ci.profile_commit_ns = 0;
ci.profile_maintenance_ns = 0;
ci.store.profile = .{};"""
if source.count(old) != 1:
raise ValueError("missing driver report site")
source = source.replace(old, new)
source = source.replace(" var start = std.Io.Clock.awake.now(io);",
" ci.store.profile = .{};\n var start = std.Io.Clock.awake.now(io);", 1)
driver.write_text(source)
return fields
writer = csv.writer(sys.stdout)
header = False
with tempfile.TemporaryDirectory(prefix="zlay-profile-") as temp:
root = Path(temp)
for variant in variants:
print(f"building {variant}", file=sys.stderr)
work, library = root / variant, root / (variant + "-zkv")
fields = instrument(work, library, variant)
subprocess.run(["zig", "build", "index-bench", "-Doptimize=ReleaseSafe"],
cwd=work, check=True)
if not header:
writer.writerow(("variant", "pass", "operation", "operations", "elapsed_ns",
"commits", "commit_ns", "maintenance_ns", *fields))
header = True
for repeat in range(3):
db = work / f"data-{repeat}"
run = subprocess.run([work / "zig-out/bin/index-bench", db],
cwd=work, capture_output=True, text=True, check=True)
lines = [line.removeprefix("phase,").split(",") for line in run.stderr.splitlines()
if line.startswith("phase,")]
assert len(lines) == 4
writer.writerows((variant, repeat + 1, *row) for row in lines)
sys.stdout.flush()