diff --git a/.gitattributes b/.gitattributes index 77b101ae..8cd85315 100644 --- a/.gitattributes +++ b/.gitattributes @@ -40,6 +40,12 @@ crates/codegraph-mcp/src/tools_list.json text eol=lf # space. Exempt it from whitespace errors (`git diff --check`). crates/codegraph-ui/viewer/** -whitespace +# --- CLI stdout snapshots: the binary's bytes, compared exactly --- +# `codegraph context`'s Markdown ends with a blank line, as upstream's does, and +# its snapshot keeps that byte. Exempt the snapshots from whitespace errors +# (`git diff --check`). +crates/codegraph-cli/tests/snapshots/*.stdout -whitespace + # --- Binary artifacts: never let git touch these bytes --- # `-text` is explicit (not just `binary`) so the catch-all `* text=auto eol=lf` # can never leave a dangling `eol=lf` applied to a binary SQLite DB: `-text` diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7bb3a5d1..f34553dd 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -140,7 +140,8 @@ jobs: name: Windows Tests needs: workspace-version runs-on: windows-2025 - timeout-minutes: 40 + # The sync-convergence matrix alone takes about 16 minutes on this runner. + timeout-minutes: 60 env: CARGO_PROFILE_TEST_DEBUG: 0 CARGO_PROFILE_TEST_SPLIT_DEBUGINFO: off diff --git a/.oxfmtignore b/.oxfmtignore index 3589e8a7..90b337ae 100644 --- a/.oxfmtignore +++ b/.oxfmtignore @@ -30,6 +30,11 @@ crates/codegraph-bench/fixtures/ crates/codegraph-extract/tests/fixtures/ crates/codegraph-resolve/tests/fixtures/ +# An upstream colbymchenry/codegraph explore fixture, copied byte for byte +# from its `__tests__/fixtures/` (W7-25): the probes assert on the line numbers +# of the definitions inside it, so reflowing it moves what they measure. +crates/codegraph-cli/tests/fixtures/explore_tail_render_ts/ + # Embedded verbatim into the MCP tools/list response and byte-compared against # golden; reformatting breaks the MCP golden test. crates/codegraph-mcp/src/tools_list.json diff --git a/Cargo.lock b/Cargo.lock index ee81d1a9..b382908d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -483,12 +483,15 @@ dependencies = [ "clap", "codegraph-core", "codegraph-extract", + "codegraph-resolve", "criterion", "libc", + "regex", "rusqlite", "serde", "serde_json", "sha2 0.11.1", + "tree-sitter", ] [[package]] @@ -592,6 +595,7 @@ dependencies = [ "serde", "serde_json", "tempfile", + "tree-sitter", "unicode-normalization", ] @@ -627,6 +631,7 @@ dependencies = [ "codegraph-core", "codegraph-extract", "codegraph-store", + "miniz_oxide", "rayon", "regex", "serde", @@ -707,6 +712,7 @@ dependencies = [ "httpdate", "notify", "percent-encoding", + "regex", "rusqlite", "serde", "serde_json", @@ -778,9 +784,9 @@ checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" [[package]] name = "cookie" -version = "0.18.1" +version = "0.18.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ddef33a339a91ea89fb53151bd0a4689cfce27055c291dfa69945475d22c747" +checksum = "d55f2d6c30eeec7d5c6f98bd4395d4abb1895629eab97ee6522d340623615f8a" dependencies = [ "percent-encoding", "time", @@ -1143,7 +1149,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -1220,9 +1226,9 @@ checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" [[package]] name = "form_urlencoded" -version = "1.2.2" +version = "1.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" dependencies = [ "percent-encoding", ] @@ -1820,7 +1826,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "20fd6de4ccfcc187e38bc21cfa543cb5a302cb86a8b114eb7f0bf0dc9f8ac00f" dependencies = [ "io-lifetimes 3.0.1", - "windows-sys 0.52.0", + "windows-sys 0.60.2", ] [[package]] @@ -1984,9 +1990,9 @@ dependencies = [ [[package]] name = "libsqlite3-sys" -version = "0.38.2" +version = "0.39.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1d20bef17f513b9b3004532233187769cd072d790971f4e4da0e346eb6401e8" +checksum = "14a5f01b87b92705d07b433c06f96cbc764637d81a0bffb5734ce17cf0f9a2b3" dependencies = [ "cc", "pkg-config", @@ -2375,16 +2381,16 @@ dependencies = [ [[package]] name = "quinn-udp" -version = "0.5.15" +version = "0.5.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "35a133f956daabe89a61a685c2649f13d82d5aa4bd5d12d1277e1072a21c0694" +checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" dependencies = [ "cfg_aliases", "libc", "once_cell", "socket2", "tracing", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -2580,9 +2586,9 @@ dependencies = [ [[package]] name = "rmcp" -version = "3.5.1" +version = "3.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab5023804cbe0304cbe06197ac16e645a0a0d0ffa2953bf735c15c2fa0213350" +checksum = "391f153431ab68664d946513ea0cb3edbca78eaf99c5a983036cacab6220d85b" dependencies = [ "async-trait", "base64 0.23.0", @@ -2593,13 +2599,16 @@ dependencies = [ "http-body", "http-body-util", "indexmap", + "libc", "pastey", + "percent-encoding", "pin-project-lite", "rand", "rmcp-macros", "schemars", "serde", "serde_json", + "sha2 0.11.1", "sse-stream", "thiserror", "tokio", @@ -2607,14 +2616,16 @@ dependencies = [ "tokio-util", "tower-service", "tracing", + "unicode-general-category", + "unicode-normalization", "uuid", ] [[package]] name = "rmcp-macros" -version = "3.6.0" +version = "3.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f55ef2d84752d676d735604548fcb65811504e23330d85670b0eff5f8735144" +checksum = "3598e3f36f4af2b5219b133baf7d97a2197039225adc3d4acf3dd8805b5a2aef" dependencies = [ "darling", "proc-macro2", @@ -2664,9 +2675,9 @@ dependencies = [ [[package]] name = "rusqlite" -version = "0.40.2" +version = "0.41.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23f2a97da3e3873c73cb2a2e71b35c40ff95e0b1eefa8d72d8499a6928c3b5b3" +checksum = "da9bba6f3506135e120a6586df05be18b48d18896600646a4bec8f993d91a594" dependencies = [ "bitflags", "fallible-iterator", @@ -2702,7 +2713,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -2771,7 +2782,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -3217,7 +3228,7 @@ dependencies = [ "getrandom 0.4.3", "once_cell", "rustix", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -3572,9 +3583,9 @@ dependencies = [ [[package]] name = "tree-sitter" -version = "0.27.0" +version = "0.27.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2038684e0058edba0d17302619f62eabce4a8e11c6ac59506996a8d79848851d" +checksum = "a5129de2ccc97808c4583d48f1fb44576d015cf241e432800572bda11ef30c3b" dependencies = [ "cc", "regex", @@ -3615,9 +3626,9 @@ dependencies = [ [[package]] name = "tree-sitter-cfml" -version = "0.26.42" +version = "0.26.43" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf1c57e5c21ce03a08338c67441b40125227066634297ea0c2c8621372541e95" +checksum = "68ebd7091acf7ec18caf8e99c6b95116bc03b04173244d8ef26c0c185631bb9a" dependencies = [ "cc", "tree-sitter-language", @@ -3655,9 +3666,9 @@ dependencies = [ [[package]] name = "tree-sitter-erlang" -version = "0.20.0" +version = "0.21.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3107efc581d335488dc38d2f51ca8b7a6a98e36f07f95a8e963f031edda6f568" +checksum = "8079a9cfe733c3b6749bb3c683c0e997ee68a2305f7a210800bbbc53e82d3f64" dependencies = [ "cc", "tree-sitter-language", @@ -3745,9 +3756,9 @@ dependencies = [ [[package]] name = "tree-sitter-language" -version = "0.1.8" +version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca0d1bf6fdd806e43ae5198f82f527056d359def39e54e67a0f478ac09dac081" +checksum = "d0af592be68c579aa78a16846bd19422978c3c52e438523d45ff5d1bff1f9d4a" [[package]] name = "tree-sitter-lua" @@ -3801,9 +3812,9 @@ dependencies = [ [[package]] name = "tree-sitter-php" -version = "0.24.2" +version = "0.25.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d8c17c3ab69052c5eeaa7ff5cd972dd1bc25d1b97ee779fec391ad3b5df5592" +checksum = "d9779e392d38af4254f48be0e57b7eed4d50ec7a6e55a7e5e2e74df8f8f032d3" dependencies = [ "cc", "tree-sitter-language", @@ -3861,9 +3872,9 @@ dependencies = [ [[package]] name = "tree-sitter-scala" -version = "0.26.2" +version = "0.26.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24e0ab4505990bfe30051761d40a7bf4033ce5a81c9eda9e20e987a5cdc84826" +checksum = "c554730d29306d9c7cdd26912638d2401378c26961e12d161a071df43f49b81b" dependencies = [ "cc", "tree-sitter-language", @@ -3937,6 +3948,12 @@ version = "1.20.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" +[[package]] +name = "unicode-general-category" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b993bddc193ae5bd0d623b49ec06ac3e9312875fdae725a975c51db1cc1677f" + [[package]] name = "unicode-ident" version = "1.0.24" @@ -4006,9 +4023,9 @@ dependencies = [ [[package]] name = "url" -version = "2.5.8" +version = "2.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" dependencies = [ "form_urlencoded", "idna", @@ -4233,7 +4250,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 0804d9b7..484f768d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -50,7 +50,7 @@ tracing-appender = "0.2" time = { version = "0.3", features = ["macros", "local-offset", "formatting"] } # Database -rusqlite = { version = "0.40", features = ["bundled"] } +rusqlite = { version = "0.41", features = ["bundled"] } # Tree-sitter tree-sitter = "0.27" diff --git a/README.md b/README.md index 2d2abd64..1ec8d55c 100644 --- a/README.md +++ b/README.md @@ -32,8 +32,9 @@ LLM to rediscover structure through repeated text searches. - **Deterministic:** no model calls, embeddings, or vector search; canonical graph output is guarded by byte-stable golden fixtures. -- **Source-aware:** search, callers/callees, impact, file source, and multi-file - exploration use one indexed representation. +- **Source-aware:** search, callers/callees, impact, file source, multi-file + exploration, and task context (`codegraph context`) use one indexed + representation. - **Agent-ready:** an MCP server exposes the same graph and verbatim source used by the CLI. - **Visual (preview):** a local browser viewer reads the same index: a symbol's @@ -42,7 +43,10 @@ LLM to rediscover structure through repeated text searches. - **Local-first:** the index lives under the project; the shared daemon and HTTP transport are local processes. - **Broad language coverage:** grammar-backed languages, embedded/template files, - and framework-aware Godot/Tauri/JS ecosystem relationships share one schema. + and framework-aware relationships (routes, navigation, rendered components and + the dispatch that framework conventions imply) share one schema. A Lua project + that loads its modules through functions of its own can + [name them](docs/cli.md#custom-lua-module-loaders-lua) in its configuration. - **Incremental:** `sync` and the watcher update changed files while preserving the same final canonical result as a clean index. @@ -154,6 +158,7 @@ codegraph index . # full rebuild of the selected project codegraph search "symbol" -p . codegraph explore "area or flow" -p . codegraph node "symbol-or-id" -p . +codegraph context "task" -p . # entry points, symbols and code for a task codegraph files -p . --format tree # Relationships diff --git a/crates/codegraph-bench/Cargo.toml b/crates/codegraph-bench/Cargo.toml index 2c3a2311..cca87923 100644 --- a/crates/codegraph-bench/Cargo.toml +++ b/crates/codegraph-bench/Cargo.toml @@ -26,6 +26,9 @@ rusqlite = { workspace = true } sha2 = { workspace = true } codegraph-core = { path = "../codegraph-core" } codegraph-extract = { path = "../codegraph-extract" } +codegraph-resolve = { path = "../codegraph-resolve" } +regex = "1.10" +tree-sitter = { workspace = true } [target.'cfg(unix)'.dependencies] libc = "0.2" diff --git a/crates/codegraph-bench/fixtures/go/config.go b/crates/codegraph-bench/fixtures/go/config.go new file mode 100644 index 00000000..778b69c5 --- /dev/null +++ b/crates/codegraph-bench/fixtures/go/config.go @@ -0,0 +1,41 @@ +package payroll + +import "errors" + +// Errors a payroll run returns. +var ( + // ErrNoRun is returned when no run is scheduled. + ErrNoRun = errors.New("no run") + ErrTooLate = newRunError("too late") +) + +// Phases of a payroll run. +const ( + PhaseDraft = iota + PhaseFinal +) + +// Schedule runs a hook at the end of a run. +type Schedule struct { + Hook func() error +} + +func newRunError(msg string) error { return errors.New(msg) } + +func closeBooks() error { return nil } + +var nightly = Schedule{Hook: closeBooks} + +var defaultEmitter = &Emitter{Table: "payroll"} + +var runAll = func() error { + _ = RunNightly("all") + return closeBooks() +} + +func phaseOf(final bool) int { + if final { + return PhaseFinal + } + return PhaseDraft +} diff --git a/crates/codegraph-bench/fixtures/servers/artisan b/crates/codegraph-bench/fixtures/servers/artisan new file mode 100644 index 00000000..c8ff8c29 --- /dev/null +++ b/crates/codegraph-bench/fixtures/servers/artisan @@ -0,0 +1,2 @@ +#!/usr/bin/env php +cmd->proc(argc); +} diff --git a/crates/codegraph-bench/fixtures/synthesis/c/src/cmds.h b/crates/codegraph-bench/fixtures/synthesis/c/src/cmds.h new file mode 100644 index 00000000..cbec9bcd --- /dev/null +++ b/crates/codegraph-bench/fixtures/synthesis/c/src/cmds.h @@ -0,0 +1,14 @@ +typedef void cmdProc(int argc); + +struct command { + const char *name; + cmdProc *proc; +}; + +struct client { + int id; + struct command *cmd, *lastcmd; +}; + +#define MAKE_CMD(name, fn) { name, fn } +#define COMMAND_T command diff --git a/crates/codegraph-bench/fixtures/synthesis/c/src/opcodes.c b/crates/codegraph-bench/fixtures/synthesis/c/src/opcodes.c new file mode 100644 index 00000000..a7b9db55 --- /dev/null +++ b/crates/codegraph-bench/fixtures/synthesis/c/src/opcodes.c @@ -0,0 +1,10 @@ +typedef void opcode_t(unsigned char op); + +static void op_nop(unsigned char op) {} +static void op_inc(unsigned char op) {} + +static opcode_t *opcodes[2] = { op_nop, op_inc }; + +void step(unsigned char op) { + opcodes[op](op); +} diff --git a/crates/codegraph-bench/fixtures/synthesis/c/src/optab.c b/crates/codegraph-bench/fixtures/synthesis/c/src/optab.c new file mode 100644 index 00000000..09616f8e --- /dev/null +++ b/crates/codegraph-bench/fixtures/synthesis/c/src/optab.c @@ -0,0 +1,18 @@ +typedef int opRun(void); + +struct op { + const char *name; + opRun *run; +}; + +#define MK(nm, fn) nm, fn +#define CMD_T op + +static int optab_a(void) { return 0; } +static int optab_b(void) { return 0; } + +#include "optab.def" + +int dispatch_op(struct op *o) { + return o->run(); +} diff --git a/crates/codegraph-bench/fixtures/synthesis/c/src/optab.def b/crates/codegraph-bench/fixtures/synthesis/c/src/optab.def new file mode 100644 index 00000000..204e392e --- /dev/null +++ b/crates/codegraph-bench/fixtures/synthesis/c/src/optab.def @@ -0,0 +1,4 @@ +static struct CMD_T optable[] = { + { MK("a", optab_a) }, + { MK("b", optab_b) }, +}; diff --git a/crates/codegraph-bench/fixtures/synthesis/cpp/src/launch.cpp b/crates/codegraph-bench/fixtures/synthesis/cpp/src/launch.cpp new file mode 100644 index 00000000..9b527e07 --- /dev/null +++ b/crates/codegraph-bench/fixtures/synthesis/cpp/src/launch.cpp @@ -0,0 +1,12 @@ +void kernel_a(int n) {} + +template +void kernel_b(T n) {} + +void launch(int n) { + auto kernel = &kernel_a; + if (n > 1) { + kernel = &kernel_b; + } + kernel(n); +} diff --git a/crates/codegraph-bench/fixtures/synthesis/dispatch/app/Http/Registration.php b/crates/codegraph-bench/fixtures/synthesis/dispatch/app/Http/Registration.php new file mode 100644 index 00000000..37ce20ff --- /dev/null +++ b/crates/codegraph-bench/fixtures/synthesis/dispatch/app/Http/Registration.php @@ -0,0 +1,12 @@ + { } + +public class PlaceOrderHandler : IRequestHandler +{ + public Task Handle(PlaceOrder request, CancellationToken ct) => Task.FromResult(1); +} + +public class OrdersController +{ + private readonly ISender _mediator; + + public async Task Place() + { + await _mediator.Send(new PlaceOrder()); + } +} diff --git a/crates/codegraph-bench/fixtures/synthesis/go.mod b/crates/codegraph-bench/fixtures/synthesis/go.mod new file mode 100644 index 00000000..31809419 --- /dev/null +++ b/crates/codegraph-bench/fixtures/synthesis/go.mod @@ -0,0 +1,3 @@ +module example.com/synthesis + +require github.com/gogf/gf/v2 v2.7.0 diff --git a/crates/codegraph-bench/fixtures/synthesis/go/ec2/ec2.go b/crates/codegraph-bench/fixtures/synthesis/go/ec2/ec2.go new file mode 100644 index 00000000..70e36ab1 --- /dev/null +++ b/crates/codegraph-bench/fixtures/synthesis/go/ec2/ec2.go @@ -0,0 +1,30 @@ +package ec2 + +import ( + "context" + + "example.com/synth/refresh" +) + +type Discovery struct { + *refresh.Discovery + region string +} + +func New(region string) *Discovery { + d := &Discovery{region: region} + d.Discovery = refresh.NewDiscovery(refresh.Options{ + Mech: "ec2", + RefreshF: d.refresh, + }) + return d +} + +func (d *Discovery) refresh(ctx context.Context) ([]*refresh.Group, error) { + return nil, nil +} + +func listStatic(ctx context.Context) ([]*refresh.Group, error) { return nil, nil } + +// The static provider's options, wired at package level. +var staticOptions = refresh.Options{Mech: "static", RefreshF: listStatic} diff --git a/crates/codegraph-bench/fixtures/synthesis/go/gin/app.go b/crates/codegraph-bench/fixtures/synthesis/go/gin/app.go new file mode 100644 index 00000000..b2d35574 --- /dev/null +++ b/crates/codegraph-bench/fixtures/synthesis/go/gin/app.go @@ -0,0 +1,11 @@ +package gin + +func Logger(c *Context) {} + +func getUser(c *Context) {} + +func setup(e *Engine) { + e.Use(Logger) + e.GET("/users", getUser) + e.GET("/inline", func(c *Context) {}) +} diff --git a/crates/codegraph-bench/fixtures/synthesis/go/gin/gin.go b/crates/codegraph-bench/fixtures/synthesis/go/gin/gin.go new file mode 100644 index 00000000..39340976 --- /dev/null +++ b/crates/codegraph-bench/fixtures/synthesis/go/gin/gin.go @@ -0,0 +1,28 @@ +package gin + +type HandlerFunc func(*Context) + +type HandlersChain []HandlerFunc + +type Context struct { + handlers HandlersChain + index int +} + +// Next runs the rest of the handler chain. +func (c *Context) Next() { + for c.index < len(c.handlers) { + c.handlers[c.index](c) + c.index++ + } +} + +type Engine struct { + Handlers HandlersChain +} + +func (e *Engine) Use(middleware ...HandlerFunc) { + e.Handlers = append(e.Handlers, middleware...) +} + +func (e *Engine) GET(path string, handlers ...HandlerFunc) {} diff --git a/crates/codegraph-bench/fixtures/synthesis/go/refresh/refresh.go b/crates/codegraph-bench/fixtures/synthesis/go/refresh/refresh.go new file mode 100644 index 00000000..6f111b71 --- /dev/null +++ b/crates/codegraph-bench/fixtures/synthesis/go/refresh/refresh.go @@ -0,0 +1,24 @@ +package refresh + +import "context" + +type Group struct{ Source string } + +// Options are the options for a refreshing discovery. +type Options struct { + Mech string + RefreshF func(ctx context.Context) ([]*Group, error) +} + +// Discovery runs a refresh function on an interval. +type Discovery struct { + refreshf func(ctx context.Context) ([]*Group, error) +} + +func NewDiscovery(opts Options) *Discovery { + return &Discovery{refreshf: opts.RefreshF} +} + +func (d *Discovery) Refresh(ctx context.Context) ([]*Group, error) { + return d.refreshf(ctx) +} diff --git a/crates/codegraph-bench/fixtures/synthesis/go/rpc/greeter_grpc.pb.go b/crates/codegraph-bench/fixtures/synthesis/go/rpc/greeter_grpc.pb.go new file mode 100644 index 00000000..77235adb --- /dev/null +++ b/crates/codegraph-bench/fixtures/synthesis/go/rpc/greeter_grpc.pb.go @@ -0,0 +1,11 @@ +// Code generated by protoc-gen-go-grpc. DO NOT EDIT. + +package rpc + +type UnimplementedGreeterServer struct{} + +func (UnimplementedGreeterServer) SayHello(name string) (string, error) { + return "", nil +} +func (UnimplementedGreeterServer) mustEmbedUnimplementedGreeterServer() {} +func (UnimplementedGreeterServer) testEmbeddedByValue() {} diff --git a/crates/codegraph-bench/fixtures/synthesis/go/rpc/server.go b/crates/codegraph-bench/fixtures/synthesis/go/rpc/server.go new file mode 100644 index 00000000..b280b493 --- /dev/null +++ b/crates/codegraph-bench/fixtures/synthesis/go/rpc/server.go @@ -0,0 +1,9 @@ +package rpc + +type server struct { + UnimplementedGreeterServer +} + +func (s *server) SayHello(name string) (string, error) { + return "hello " + name, nil +} diff --git a/crates/codegraph-bench/fixtures/synthesis/goframe/api/system/dept.go b/crates/codegraph-bench/fixtures/synthesis/goframe/api/system/dept.go new file mode 100644 index 00000000..73c4b69b --- /dev/null +++ b/crates/codegraph-bench/fixtures/synthesis/goframe/api/system/dept.go @@ -0,0 +1,24 @@ +package system + +import "github.com/gogf/gf/v2/frame/g" + +type DeptSearchReq struct { + g.Meta `path:"/dept/list" tags:"Dept" method:"get" summary:"list"` + DeptName string +} +type DeptSearchRes struct { + g.Meta `mime:"application/json"` + List []string +} + +type DeptAddReq struct { + g.Meta `path:"/dept/add" method:"post"` + Name string +} +type DeptAddRes struct{} + +// A declared route whose handler does not exist in this codebase. +type OrphanReq struct { + g.Meta `path:"/orphan" method:"get"` +} +type OrphanRes struct{} diff --git a/crates/codegraph-bench/fixtures/synthesis/goframe/internal/controller/dept.go b/crates/codegraph-bench/fixtures/synthesis/goframe/internal/controller/dept.go new file mode 100644 index 00000000..4def8b32 --- /dev/null +++ b/crates/codegraph-bench/fixtures/synthesis/goframe/internal/controller/dept.go @@ -0,0 +1,24 @@ +package controller + +import ( + "context" + + "example.com/synthesis/goframe/api/system" +) + +type sysDeptController struct{} + +// NB: method name (List) differs from the request type (DeptSearchReq) — the join +// must be by signature, not name. +func (c *sysDeptController) List(ctx context.Context, req *system.DeptSearchReq) (res *system.DeptSearchRes, err error) { + return helper(ctx) +} + +func (c *sysDeptController) Add(ctx context.Context, req *system.DeptAddReq) (res *system.DeptAddRes, err error) { + return +} + +// Returns the response type but takes no request type — must NOT be linked. +func helper(ctx context.Context) (res *system.DeptSearchRes, err error) { + return +} diff --git a/crates/codegraph-bench/fixtures/synthesis/js/src/Posts.tsx b/crates/codegraph-bench/fixtures/synthesis/js/src/Posts.tsx new file mode 100644 index 00000000..d0d2e6cb --- /dev/null +++ b/crates/codegraph-bench/fixtures/synthesis/js/src/Posts.tsx @@ -0,0 +1,7 @@ +import { useGetPostsQuery, useAddPostMutation } from './api'; + +export function Posts() { + const { data } = useGetPostsQuery(); + const [addPost] = useAddPostMutation(); + return data ? addPost : null; +} diff --git a/crates/codegraph-bench/fixtures/synthesis/js/src/api.ts b/crates/codegraph-bench/fixtures/synthesis/js/src/api.ts new file mode 100644 index 00000000..b485c8a0 --- /dev/null +++ b/crates/codegraph-bench/fixtures/synthesis/js/src/api.ts @@ -0,0 +1,20 @@ +import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'; + +async function loadPosts() { + return []; +} + +export const postsApi = createApi({ + reducerPath: 'posts', + baseQuery: fetchBaseQuery({ baseUrl: '/' }), + endpoints: (build) => ({ + getPosts: build.query({ + queryFn: async () => ({ data: await loadPosts() }), + }), + addPost: build.mutation({ + query: (body) => ({ url: 'posts', method: 'POST', body }), + }), + }), +}); + +export const { useGetPostsQuery, useLazyGetPostsQuery, useAddPostMutation } = postsApi; diff --git a/crates/codegraph-bench/fixtures/synthesis/js/src/app.js b/crates/codegraph-bench/fixtures/synthesis/js/src/app.js new file mode 100644 index 00000000..00fb1e9e --- /dev/null +++ b/crates/codegraph-bench/fixtures/synthesis/js/src/app.js @@ -0,0 +1,3 @@ +export function signIn(store, token) { + store.dispatch('user/login', token); +} diff --git a/crates/codegraph-bench/fixtures/synthesis/js/src/cartConsumer.ts b/crates/codegraph-bench/fixtures/synthesis/js/src/cartConsumer.ts new file mode 100644 index 00000000..dc50db89 --- /dev/null +++ b/crates/codegraph-bench/fixtures/synthesis/js/src/cartConsumer.ts @@ -0,0 +1,6 @@ +import { useCartStore } from './store'; + +export function addToCart(item: string) { + const cart = useCartStore(); + cart.add(item); +} diff --git a/crates/codegraph-bench/fixtures/synthesis/js/src/store/auth.js b/crates/codegraph-bench/fixtures/synthesis/js/src/store/auth.js new file mode 100644 index 00000000..feae7043 --- /dev/null +++ b/crates/codegraph-bench/fixtures/synthesis/js/src/store/auth.js @@ -0,0 +1,3 @@ +export function persistToken(token) { + return token; +} diff --git a/crates/codegraph-bench/fixtures/synthesis/js/src/store/modules/user.js b/crates/codegraph-bench/fixtures/synthesis/js/src/store/modules/user.js new file mode 100644 index 00000000..12cd10d0 --- /dev/null +++ b/crates/codegraph-bench/fixtures/synthesis/js/src/store/modules/user.js @@ -0,0 +1,17 @@ +import { persistToken } from '../auth'; + +export default { + namespaced: true, + state: () => ({ token: '' }), + mutations: { + SET_TOKEN(state, token) { + state.token = token; + }, + }, + actions: { + login({ commit }, token) { + persistToken(token); + commit('SET_TOKEN', token); + }, + }, +}; diff --git a/crates/codegraph-bench/fixtures/synthesis/js/src/thunks.ts b/crates/codegraph-bench/fixtures/synthesis/js/src/thunks.ts new file mode 100644 index 00000000..cfda3491 --- /dev/null +++ b/crates/codegraph-bench/fixtures/synthesis/js/src/thunks.ts @@ -0,0 +1,9 @@ +import { createAsyncThunk } from '@reduxjs/toolkit'; + +export const refreshCart = createAsyncThunk('cart/refresh', async (id: string) => { + return { id }; +}); + +export const checkout = createAsyncThunk('cart/checkout', async (id: string, { dispatch }) => { + await dispatch(refreshCart(id)); +}); diff --git a/crates/codegraph-bench/scripts/od9-verdict.py b/crates/codegraph-bench/scripts/od9-verdict.py new file mode 100755 index 00000000..621c059a --- /dev/null +++ b/crates/codegraph-bench/scripts/od9-verdict.py @@ -0,0 +1,297 @@ +#!/usr/bin/env python3 +"""Apply the OD-9 adoption rule to `bench --ab` reports (schema 2). + +usage: + python3 -I od9-verdict.py --target PHASE[,PHASE...] --noise-floor-ms MS + --profile release|fast [--goldens-ok] [--corpora NAME[,NAME...]] + [--threads N[,M...]] [--candidate INDEX] [--json] REPORT.json... + +`--target` names the phases the strategy changes, the phase its cost moves +into included; the target metric of a run is the sum of their milliseconds. +`wall` stands for the run's wall time. `--threads` names the thread cells every +required corpus must have (default `32,4`; `default` is a cell that left +RAYON_NUM_THREADS unset). `--corpora` defaults to every corpus the reports hold. +`--candidate` picks the report's candidate (default 0, the first `--candidate`). +Cells may come from several reports, a cell from one report only. + +A strategy is ADOPTED only when all three rules hold for the candidate: + +(a) every required corpus's canonical graph equals the baseline's on all five + surfaces, and `--goldens-ok` attests that `scripts/regen-goldens.sh --check` + reported every golden identical and the `golden_reextract` test passed, + both on the candidate build; +(b) in every required cell the target improves: with B and C the baseline and + candidate medians over the measured runs (warm-up and void runs left out, + at least five each) and MAD the unscaled median absolute deviation, + (B - C) / B >= 0.05 and B - C > 2 * max(MAD_B, MAD_C); +(c) in every required cell nothing else regresses: no other phase both arms + report, nor the wall time (unless it is the target), nor the peak RSS. + A regression is C / B > 1.02 together with C - B > 2 * max(MAD_B, MAD_C); + a phase whose baseline median is below the noise floor is judged by its + absolute increase alone, C - B > noise floor. + +The verdict needs builds of the release profile (OD-B88); `--profile fast` +prints the same evaluation as attribution only. + +Exit status: 0 ADOPTED, 1 REJECTED_BY_PROFILE, 3 no verdict (a rule could not +be evaluated, or `--profile fast`), 2 a usage or input error. +""" + +import argparse +import json +import sys + +IMPROVEMENT_MIN = 0.05 +REGRESSION_RATIO_MAX = 1.02 +MAD_FACTOR = 2.0 +MIN_MEASURED_RUNS = 5 +WALL = "wall" + + +class InputError(Exception): + """A report that cannot be read as a schema-2 `bench --ab` report.""" + + +def median(values): + """The median, interpolated between the middle two of an even count, as + the bench's `metrics::median` computes it.""" + ordered = sorted(values) + count = len(ordered) + middle = count // 2 + if count % 2: + return ordered[middle] + return ordered[middle - 1] + (ordered[middle] - ordered[middle - 1]) * 0.5 + + +def mad(values): + """The unscaled median absolute deviation.""" + center = median(values) + return median([abs(value - center) for value in values]) + + +def thread_label(cell): + return "default" if cell.get("default_threads") else str(cell["threads"]) + + +def measured(series): + """The runs a statistic counts: neither warm-up nor void.""" + return [run for run in series["runs"] if not run.get("warmup") and not run.get("void")] + + +def metric_values(runs, phases): + """Each run's sum of `phases` (milliseconds), or None when a run lacks one.""" + values = [] + for run in runs: + if phases == [WALL]: + values.append(float(run["wall_ms"])) + continue + reported = run.get("phase_ms") or {} + if any(phase not in reported for phase in phases): + return None + values.append(sum(float(reported[phase]) for phase in phases)) + return values + + +def load_reports(paths, candidate): + """Cells keyed by (corpus, threads label) and graphs by corpus.""" + cells = {} + graphs = {} + for path in paths: + try: + with open(path, encoding="utf-8") as handle: + report = json.load(handle) + except (OSError, ValueError) as error: + raise InputError(f"{path}: {error}") from error + if report.get("kind") != "codegraph-ab" or report.get("schema_version") != 2: + raise InputError(f"{path}: not a schema-2 `bench --ab` report") + if candidate >= len(report.get("candidates", [])): + raise InputError(f"{path}: has no candidate {candidate}") + for corpus in report["corpora"]: + name = corpus["name"] + graphs.setdefault(name, []).append((path, corpus["graphs"][candidate])) + for cell in corpus["cells"]: + key = (name, thread_label(cell)) + if key in cells: + raise InputError( + f"cell {name}/{key[1]} is in both {cells[key][0]} and {path}" + ) + cells[key] = (path, cell["baseline"], cell["candidates"][candidate]["series"]) + return cells, graphs + + +def judge_target(label, base_values, cand_values): + base, cand = median(base_values), median(cand_values) + spread = MAD_FACTOR * max(mad(base_values), mad(cand_values)) + delta = base - cand + relative = delta / base if base > 0 else float("nan") + passed = base > 0 and relative >= IMPROVEMENT_MIN and delta > spread + reason = ( + f"{label}: target {base:.3f} -> {cand:.3f} ms, " + f"improvement {relative * 100:.2f}% (needs >= 5%), " + f"delta {delta:.3f} vs 2*MAD {spread:.3f} (needs >)" + ) + return passed, reason + + +def regression(base_values, cand_values, noise_floor): + """Whether the candidate regressed, and why.""" + base, cand = median(base_values), median(cand_values) + spread = MAD_FACTOR * max(mad(base_values), mad(cand_values)) + increase = cand - base + if base < noise_floor: + return increase > noise_floor, ( + f"{base:.3f} -> {cand:.3f}, increase {increase:.3f} vs noise floor " + f"{noise_floor:.3f} (below the floor: absolute increase only)" + ) + ratio = cand / base if base > 0 else float("inf") + return ratio > REGRESSION_RATIO_MAX and increase > spread, ( + f"{base:.3f} -> {cand:.3f}, ratio {ratio:.4f} (limit 1.02), " + f"increase {increase:.3f} vs 2*MAD {spread:.3f}" + ) + + +def evaluate(args): + targets = [name.strip() for name in args.target.split(",") if name.strip()] + if not targets: + raise InputError("--target names no phase") + if WALL in targets and targets != [WALL]: + raise InputError("`wall` is a target on its own") + threads = [label.strip() for label in args.threads.split(",") if label.strip()] + cells, graphs = load_reports(args.reports, args.candidate) + corpora = ( + [name.strip() for name in args.corpora.split(",") if name.strip()] + if args.corpora + else sorted({name for name, _ in cells}) + ) + failed, missing, passed, notes = [], [], [], [] + + # (a) the graphs. + for name in corpora: + if name not in graphs: + missing.append(f"(a) corpus {name} is in no report") + continue + for path, graph in graphs[name]: + if graph["identical"]: + passed.append(f"(a) {name}: graph identical ({path})") + else: + failed.append( + f"(a) {name}: graph differs in {', '.join(graph['differing_surfaces'])} ({path})" + ) + if args.goldens_ok: + passed.append("(a) goldens and golden_reextract attested (--goldens-ok)") + else: + missing.append("(a) no --goldens-ok: the golden checks are not attested") + + for name in corpora: + for label in threads: + key = (name, label) + if key not in cells: + missing.append(f"cell {name}/{label} is in no report") + continue + path, base_series, cand_series = cells[key] + cell = f"{name}/{label}" + base_runs, cand_runs = measured(base_series), measured(cand_series) + if min(len(base_runs), len(cand_runs)) < MIN_MEASURED_RUNS: + missing.append( + f"cell {cell}: {len(base_runs)} and {len(cand_runs)} measured runs " + f"(needs {MIN_MEASURED_RUNS} each: six runs, the first dropped)" + ) + continue + + # (b) the target. + base_values = metric_values(base_runs, targets) + cand_values = metric_values(cand_runs, targets) + if base_values is None or cand_values is None: + missing.append(f"(b) {cell}: a run does not report {', '.join(targets)}") + else: + ok, reason = judge_target(f"(b) {cell}", base_values, cand_values) + (passed if ok else failed).append(reason) + if targets != [WALL] and median(base_values) < args.noise_floor_ms: + notes.append(f"(b) {cell}: the target is below the noise floor") + + # (c) everything else. + base_phases = set.intersection(*(set(run.get("phase_ms") or {}) for run in base_runs)) + cand_phases = set.intersection(*(set(run.get("phase_ms") or {}) for run in cand_runs)) + for phase in sorted(base_phases ^ cand_phases): + notes.append(f"(c) {cell}: {phase} is reported by one arm only") + others = [phase for phase in sorted(base_phases & cand_phases) if phase not in targets] + if targets != [WALL]: + others.append(WALL) + regressions = [] + for phase in others: + base_other = metric_values(base_runs, [phase]) + cand_other = metric_values(cand_runs, [phase]) + regressed, reason = regression(base_other, cand_other, args.noise_floor_ms) + if regressed: + regressions.append(f"(c) {cell}: {phase} regressed: {reason}") + base_rss = [run.get("peak_rss_kb") for run in base_runs] + cand_rss = [run.get("peak_rss_kb") for run in cand_runs] + if None in base_rss or None in cand_rss: + notes.append(f"(c) {cell}: no peak RSS to compare") + else: + regressed, reason = regression( + [float(kb) for kb in base_rss], [float(kb) for kb in cand_rss], 0.0 + ) + if regressed: + regressions.append(f"(c) {cell}: peak RSS (KiB) regressed: {reason}") + if regressions: + failed.extend(regressions) + else: + passed.append(f"(c) {cell}: none of {len(others)} timings nor the peak RSS regressed") + + if failed: + verdict = "REJECTED_BY_PROFILE" + elif missing: + verdict = "INCOMPLETE" + else: + verdict = "ADOPTED" + return { + "verdict": verdict, + "attribution_only": args.profile != "release", + "target": targets, + "noise_floor_ms": args.noise_floor_ms, + "corpora": corpora, + "threads": threads, + "failed": failed, + "missing": missing, + "passed": passed, + "notes": notes, + } + + +def main(argv): + parser = argparse.ArgumentParser( + description="Apply the OD-9 adoption rule to bench --ab reports (schema 2)." + ) + parser.add_argument("reports", nargs="+", metavar="REPORT.json") + parser.add_argument("--target", required=True) + parser.add_argument("--noise-floor-ms", type=float, required=True) + parser.add_argument("--profile", choices=["release", "fast"], required=True) + parser.add_argument("--goldens-ok", action="store_true") + parser.add_argument("--corpora") + parser.add_argument("--threads", default="32,4") + parser.add_argument("--candidate", type=int, default=0) + parser.add_argument("--json", action="store_true") + args = parser.parse_args(argv) + if args.noise_floor_ms < 0 or args.candidate < 0: + parser.error("--noise-floor-ms and --candidate cannot be negative") + try: + result = evaluate(args) + except (InputError, KeyError, TypeError) as error: + print(f"od9-verdict: {error}", file=sys.stderr) + return 2 + if args.json: + print(json.dumps(result, indent=2, sort_keys=True)) + else: + for heading in ("failed", "missing", "passed", "notes"): + for line in result[heading]: + print(f"{heading}: {line}") + suffix = " (attribution only: --profile fast, OD-B88)" if result["attribution_only"] else "" + print(f"VERDICT: {result['verdict']}{suffix}") + if result["attribution_only"]: + return 3 + return {"ADOPTED": 0, "REJECTED_BY_PROFILE": 1}.get(result["verdict"], 3) + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/crates/codegraph-bench/src/ab.rs b/crates/codegraph-bench/src/ab.rs index f012e2cf..5e316db8 100644 --- a/crates/codegraph-bench/src/ab.rs +++ b/crates/codegraph-bench/src/ab.rs @@ -1,35 +1,59 @@ -//! `bench --ab`: cold-`init` A/B timing of two CodeGraph binaries. +//! `bench --ab`: A/B timing of CodeGraph binaries, a baseline and one or more +//! candidates. //! -//! For every corpus, thread count and run, the harness copies the corpus -//! subtree into a fresh temporary project (without `.git` or an index -//! directory) and runs ` init ` with -//! `RAYON_NUM_THREADS=`, `CODEGRAPH_NO_DAEMON=1` and -//! `CODEGRAPH_NO_WATCH=1`, and with `CODEGRAPH_DIR` removed. The CLI has no -//! thread flag; parsing and resolution run on rayon's global pool, which reads -//! `RAYON_NUM_THREADS`. Each run records its wall time, its peak RSS and the -//! canonical fingerprint of the database it wrote. On Linux the peak RSS is the +//! For every corpus, thread cell and run, the harness times one operation of +//! each binary: +//! +//! - `init` (the default): it copies the corpus subtree into a fresh temporary +//! project (without `.git` or an index directory) and times +//! ` init `; +//! - `sync-edit:` and `sync-edit:1:`: each binary gets its own copy of +//! the corpus, indexed by an untimed `init`; a comment line is appended to +//! the first `N` indexed files that take a line comment (in path order), or +//! to ``, before every ` sync `, of which one untimed +//! warm-up sync comes first and the rest are timed. At the end of the cell +//! every edited file is set to its original text plus one final comment, an +//! untimed sync indexes that, and the synced graph must equal a fresh +//! `init` of the same source, or the harness stops. +//! +//! Every child runs with `RAYON_NUM_THREADS=` (removed for the +//! `default` cell), `CODEGRAPH_NO_DAEMON=1`, `CODEGRAPH_NO_WATCH=1` and +//! `CODEGRAPH_PHASE_TIMINGS=1`, and with `CODEGRAPH_DIR` removed. The CLI has +//! no thread flag; parsing and resolution run on rayon's global pool, which +//! reads `RAYON_NUM_THREADS`. Each timed run records its wall time, its peak +//! RSS, its CPU time (from `wait4`), and the phase-timing lines of its stderr, +//! read before the run's directory is deleted. On Linux the peak RSS is the //! child's own `VmHWM`, polled from `/proc//status` while it runs: //! `wait4`'s `ru_maxrss` also counts the address space the child was forked //! from, the harness's own, which grows as it canonicalizes each database, so //! every run after a large corpus read the harness's size. Other Unix hosts //! report `ru_maxrss`. //! -//! Baseline and candidate runs alternate (even runs baseline first, odd runs -//! candidate first). The first run of every (corpus, binary, threads) cell is a -//! warm-up and is left out of the statistics. +//! The binaries take turns: run `r` of a cell starts with arm `r mod n` of the +//! `n` arms (the baseline, then the candidates in order), so with one +//! candidate even runs time the baseline first and odd runs the candidate +//! first. The first run of every (corpus, binary, threads) cell is a warm-up +//! and is left out of the statistics. With the load guard on +//! ([`crate::load_guard`]), timing starts on a quiet host, and a run the +//! guard finds sharing its CPUs is void, kept in the report and run again. //! //! The harness fails closed and writes no report when a run exits non-zero, is -//! killed or times out; when a run exits 0 without a database, or with one that -//! fails `PRAGMA quick_check` or canonicalization; and when two runs of the -//! same binary on one corpus, at any thread counts, produce different canonical -//! graphs. A baseline/candidate graph difference is not an error: it is -//! reported per corpus, so a candidate that changes the graph can still be -//! timed against its row growth. +//! killed or times out; when an `init` exits 0 without a database, or with one +//! that fails `PRAGMA quick_check` or canonicalization; when two runs of the +//! same binary on one corpus, at any thread counts, produce different +//! canonical graphs; when a sync does not re-index the edited files or does +//! not converge with a fresh `init`; when a binary's phase-timing lines are +//! malformed or name different phases in different runs of a cell; and when a +//! cell cannot collect its runs within the guard's attempts. A baseline and +//! candidate graph difference is not an error: it is reported per corpus, so +//! a candidate that changes the graph can still be timed against its row +//! growth. use std::collections::{BTreeMap, BTreeSet}; use std::ffi::OsStr; use std::fmt; -use std::fs::{self, File}; +use std::fs::{self, File, OpenOptions}; +use std::io::Write; use std::path::{Path, PathBuf}; use std::process::{Child, Command, Stdio}; use std::thread; @@ -42,20 +66,30 @@ use serde::{Deserialize, Serialize}; use crate::corpus::{Corpus, benchmark_path_in, checkout_path_in}; use crate::graph_diff::{ GraphFingerprint, ScratchDir, canonicalize_checked, differing_surfaces, fingerprint, - sha256_file, + load_graph, sha256_file, }; +#[cfg(target_os = "linux")] +use crate::load_guard::ProcProbe; +use crate::load_guard::{LoadGuard, LoadProbe, SessionStart}; #[cfg(unix)] use crate::metrics::read_proc_status_kb; use crate::metrics::{mad, median}; +use crate::oracle::CanonicalRow; use crate::report::{command_stdout, read_cpu_model, read_mem_total_kb, read_os_pretty_name}; /// Environment variable that sets the thread count of each timed run. pub const THREAD_ENV: &str = "RAYON_NUM_THREADS"; +/// Environment variable that makes CodeGraph print its phase timings. +pub const PHASE_TIMINGS_ENV: &str = "CODEGRAPH_PHASE_TIMINGS"; +/// The first field of a phase-timing line (`docs/cli.md`, Index diagnostics). +pub const PHASE_TAG: &str = "codegraph-phase"; /// Default wall-clock cap for one timed run; a run past it is killed and fails. pub const DEFAULT_RUN_TIMEOUT: Duration = Duration::from_secs(30 * 60); /// Regression budget (`docs/benchmark.md`): candidate/baseline cold-`init` /// median wall time. pub const INIT_WALL_RATIO_MAX: f64 = 1.10; +/// Regression budget: candidate/baseline single-file `sync` median wall time. +pub const SYNC_WALL_RATIO_MAX: f64 = 1.15; /// A slower `init` is still within budget when the candidate graph has more /// canonical rows and its rows/s stay at or above this ratio. pub const ROWS_PER_SECOND_RATIO_MIN: f64 = 0.90; @@ -63,21 +97,163 @@ pub const ROWS_PER_SECOND_RATIO_MIN: f64 = 0.90; pub const PEAK_RSS_RATIO_MAX: f64 = 1.15; const REPORT_KIND: &str = "codegraph-ab"; +const REPORT_SCHEMA_VERSION: u32 = 2; const VERSION_TIMEOUT: Duration = Duration::from_secs(30); const POLL_INTERVAL: Duration = Duration::from_millis(1); const STDERR_TAIL_LINES: usize = 40; const DATABASE_FILE: &str = "codegraph.db"; +/// The text of every comment line a sync edit appends, after the comment mark. +const SYNC_EDIT_MARK: &str = "codegraph-bench sync-edit"; + +/// One thread cell: a `RAYON_NUM_THREADS` value, or the variable unset. +#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] +pub enum Threads { + Count(usize), + /// `RAYON_NUM_THREADS` removed: rayon sizes its pool to the CPUs. + Default, +} + +impl Threads { + /// `default`, or a thread count of at least 1. + pub fn parse(text: &str) -> Result { + if text == "default" { + return Ok(Self::Default); + } + let count: usize = text + .parse() + .with_context(|| format!("a thread cell is a count or `default`, not {text:?}"))?; + Ok(Self::Count(count)) + } + + pub fn count(self) -> Option { + match self { + Self::Count(count) => Some(count), + Self::Default => None, + } + } + + /// The thread count the cell's children run with. + pub fn resolved(self) -> usize { + self.count().unwrap_or_else(logical_cpus) + } + + pub fn label(self) -> String { + match self { + Self::Count(count) => count.to_string(), + Self::Default => "default".to_string(), + } + } +} + +impl fmt::Display for Threads { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Count(count) => write!(f, "{THREAD_ENV}={count}"), + Self::Default => write!(f, "{THREAD_ENV} unset"), + } + } +} + +/// The CPUs this process may run on, which a child's rayon pool takes by +/// default. +pub fn logical_cpus() -> usize { + thread::available_parallelism().map_or(1, usize::from) +} + +/// What each timed run does. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum AbOp { + /// A cold `init` of a fresh copy of the corpus. + Init, + /// A `sync` after a comment line is appended to the first `files` indexed + /// files that take a line comment, in path order. + SyncEdit { files: usize }, + /// A `sync` after a comment line is appended to the indexed file `path`. + SyncEditFile { path: String }, +} + +impl AbOp { + /// `init`, `sync-edit:` or `sync-edit:1:`. + pub fn parse(text: &str) -> Result { + if text == "init" { + return Ok(Self::Init); + } + let Some(rest) = text.strip_prefix("sync-edit:") else { + bail!("--op is `init`, `sync-edit:` or `sync-edit:1:`, not {text:?}"); + }; + match rest.split_once(':') { + None => { + let files: usize = rest + .parse() + .with_context(|| format!("sync-edit takes a file count, not {rest:?}"))?; + if files == 0 { + bail!("sync-edit edits at least one file"); + } + Ok(Self::SyncEdit { files }) + } + Some((count, path)) => { + if count != "1" { + bail!("a named file is edited on its own: sync-edit:1:, not {text:?}"); + } + if path.is_empty() + || path.starts_with('/') + || path.contains('\\') + || path + .split('/') + .any(|part| part.is_empty() || part == "." || part == "..") + { + bail!("sync-edit names a project-relative path with `/`, not {path:?}"); + } + Ok(Self::SyncEditFile { + path: path.to_string(), + }) + } + } + } + + pub fn label(&self) -> String { + match self { + Self::Init => "init".to_string(), + Self::SyncEdit { files } => format!("sync-edit:{files}"), + Self::SyncEditFile { path } => format!("sync-edit:1:{path}"), + } + } + + /// The CodeGraph command each timed run runs. + pub fn command(&self) -> &'static str { + match self { + Self::Init => "init", + Self::SyncEdit { .. } | Self::SyncEditFile { .. } => "sync", + } + } + + fn is_sync(&self) -> bool { + !matches!(self, Self::Init) + } + + /// Whether the run is a single-file sync, which the sync budget covers. + fn single_file_sync(&self) -> bool { + matches!( + self, + Self::SyncEdit { files: 1 } | Self::SyncEditFile { .. } + ) + } +} /// What one `bench --ab` invocation compares. #[derive(Clone, Debug)] pub struct AbConfig { pub baseline: PathBuf, - pub candidate: PathBuf, + /// One or more candidates, each compared with the baseline. + pub candidates: Vec, pub corpora: Vec, - pub threads: Vec, + pub threads: Vec, /// Runs per (corpus, binary, threads) cell, including the warm-up. pub runs: usize, pub run_timeout: Duration, + pub op: AbOp, + /// The load guard's limits; `None` times without it. + pub load_guard: Option, /// Workspace whose commit is recorded as the harness commit. pub workspace_root: Option, /// The command line, recorded verbatim in the report. @@ -152,8 +328,14 @@ pub struct AbReport { pub argv: Vec, pub environment: AbEnvironment, pub settings: AbSettings, + /// The load guard's quiet start, when the guard was on. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub session_start: Option, pub baseline: BinaryInfo, + /// The first candidate; every candidate is in `candidates`. pub candidate: BinaryInfo, + #[serde(default)] + pub candidates: Vec, pub corpora: Vec, } @@ -170,23 +352,41 @@ pub struct AbEnvironment { pub rss_collector: String, } +fn init_op() -> String { + "init".to_string() +} + #[derive(Clone, Debug, Deserialize, Serialize)] pub struct AbSettings { pub invocation: String, + #[serde(default = "init_op")] + pub op: String, pub env_set: BTreeMap, pub env_removed: Vec, pub thread_env: String, + /// The thread count of each cell; a `default` cell's is the CPUs'. pub threads: Vec, + /// Each cell as given: a count, or `default`. + #[serde(default)] + pub thread_settings: Vec, pub runs: usize, pub discarded_warmup_runs: usize, pub order: String, pub run_timeout_secs: u64, pub budget: BudgetLimits, + #[serde(default)] + pub load_guard: Option, +} + +fn sync_wall_ratio_max() -> f64 { + SYNC_WALL_RATIO_MAX } #[derive(Clone, Copy, Debug, Deserialize, Serialize)] pub struct BudgetLimits { pub init_wall_ratio_max: f64, + #[serde(default = "sync_wall_ratio_max")] + pub sync_wall_ratio_max: f64, pub rows_per_second_ratio_min: f64, pub peak_rss_ratio_max: f64, } @@ -194,6 +394,7 @@ pub struct BudgetLimits { impl BudgetLimits { pub const PROJECT: Self = Self { init_wall_ratio_max: INIT_WALL_RATIO_MAX, + sync_wall_ratio_max: SYNC_WALL_RATIO_MAX, rows_per_second_ratio_min: ROWS_PER_SECOND_RATIO_MIN, peak_rss_ratio_max: PEAK_RSS_RATIO_MAX, }; @@ -219,10 +420,20 @@ pub struct CorpusAb { pub source: String, pub copied_files: u64, pub skipped_symlinks: u64, + /// The first candidate's graph against the baseline's; every + /// candidate's is in `graphs`. pub graph: GraphComparison, + #[serde(default)] + pub graphs: Vec, + /// The files a sync run edits, in path order. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub edited_files: Vec, pub cells: Vec, } +/// One candidate's graph against the baseline's. For a sync run it is the +/// graph each binary's last sync left, which equals its fresh `init` of the +/// same source. #[derive(Clone, Debug, Deserialize, Serialize)] pub struct GraphComparison { pub identical: bool, @@ -235,29 +446,86 @@ pub struct GraphComparison { #[derive(Clone, Debug, Deserialize, Serialize)] pub struct Cell { pub threads: usize, + /// Whether the cell left `RAYON_NUM_THREADS` unset (`--threads default`). + #[serde(default)] + pub default_threads: bool, pub baseline: ArmSeries, + /// The first candidate's runs, ratios and budget; every candidate's are + /// in `candidates`. pub candidate: ArmSeries, pub ratio: Ratios, pub budget: BudgetVerdict, + #[serde(default)] + pub candidates: Vec, } -/// Every run of one binary in a cell, and the statistics of the measured ones. +/// One candidate in a cell, against the baseline. +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct CandidateCell { + pub series: ArmSeries, + pub ratio: Ratios, + pub budget: BudgetVerdict, + /// Candidate/baseline median of each phase both report. + #[serde(default)] + pub phase_ratio: BTreeMap, +} + +/// Every run of one binary in a cell, and the statistics of the measured ones: +/// neither the warm-up nor a void run. #[derive(Clone, Debug, Deserialize, Serialize)] pub struct ArmSeries { pub runs: Vec, pub wall_ms: Summary, pub peak_rss_kb: Option, pub rows_per_second: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cpu_ms: Option, + /// The foreign CPUs the load guard measured over the measured runs; each + /// run's own value, a void run's included, is in its `load`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub foreign_cpus: Option, + /// Each phase the binary reported, in milliseconds. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub phase_ms: BTreeMap, } #[derive(Clone, Debug, Deserialize, Serialize)] pub struct RunSample { - /// 1-based run number within the cell. + /// 1-based attempt number within the cell; a void run's rerun has the + /// next one. pub run: usize, pub warmup: bool, pub wall_ms: f64, pub peak_rss_kb: Option, - pub canonical_hash: String, + /// The canonical graph an `init` run wrote; a sync run's graph is checked + /// once, at the end of the cell. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub canonical_hash: Option, + /// The child's user and system time, from `wait4`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cpu_ms: Option, + /// The child's phase-timing lines, in milliseconds by phase. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub phase_ms: BTreeMap, + /// What the load guard saw around the run. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub load: Option, + /// Why the load guard voided the run; a void run counts in no statistic. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub void: Option, +} + +/// The load guard's view of one run. +#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)] +pub struct RunLoad { + /// The 1-minute load when the run started. + pub load1: f64, + /// The idle CPUs of the sample before the run. + pub idle_cpus: f64, + /// How long the run waited for the host. + pub waited_ms: f64, + /// The average CPUs other work used during the run. + pub foreign_cpus: f64, } #[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)] @@ -286,14 +554,18 @@ pub struct Ratios { pub rows_per_second: Option, } -/// The regression budget applied to one cell; `None` when not measurable. +/// The regression budget applied to one cell; `None` when not measurable or +/// not the cell's operation. #[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)] pub struct BudgetVerdict { pub init_wall_ok: Option, + #[serde(default)] + pub sync_wall_ok: Option, pub peak_rss_ok: Option, } impl BudgetVerdict { + /// The `init` budget: wall time and peak RSS. pub fn evaluate(ratio: &Ratios, limits: &BudgetLimits) -> Self { let init_wall_ok = ratio.wall_ms.map(|wall| { let rows_grew = ratio.canonical_rows.is_some_and(|rows| rows > 1.0); @@ -302,45 +574,110 @@ impl BudgetVerdict { .is_some_and(|rate| rate >= limits.rows_per_second_ratio_min); wall <= limits.init_wall_ratio_max || (rows_grew && throughput_held) }); - let peak_rss_ok = ratio - .peak_rss_kb - .map(|rss| rss <= limits.peak_rss_ratio_max); Self { init_wall_ok, - peak_rss_ok, + sync_wall_ok: None, + peak_rss_ok: Self::rss_ok(ratio, limits), + } + } + + /// The sync budget: a single-file sync's wall time, and peak RSS. + pub fn evaluate_sync(ratio: &Ratios, limits: &BudgetLimits, single_file: bool) -> Self { + Self { + init_wall_ok: None, + sync_wall_ok: ratio + .wall_ms + .filter(|_| single_file) + .map(|wall| wall <= limits.sync_wall_ratio_max), + peak_rss_ok: Self::rss_ok(ratio, limits), } } + + fn rss_ok(ratio: &Ratios, limits: &BudgetLimits) -> Option { + ratio + .peak_rss_kb + .map(|rss| rss <= limits.peak_rss_ratio_max) + } } -/// Time both binaries on every configured corpus. +/// Time every binary on every configured corpus, with the load guard on the +/// host's `/proc` when the configuration asks for it. pub fn run_ab(config: &AbConfig) -> Result { + if config.load_guard.is_none() { + return run_ab_with_probe(config, None); + } + #[cfg(target_os = "linux")] + { + let mut probe = ProcProbe::new()?; + run_ab_with_probe(config, Some(&mut probe)) + } + #[cfg(not(target_os = "linux"))] + { + bail!("the load guard reads /proc, which this host lacks: pass --no-load-guard") + } +} + +/// [`run_ab`] with the load guard reading `probe`; `None` when the guard is +/// off. +pub fn run_ab_with_probe(config: &AbConfig, probe: Option<&mut dyn LoadProbe>) -> Result { validate(config)?; + let guard = match (&config.load_guard, probe) { + (Some(limits), Some(probe)) => Some((limits, probe)), + (None, _) => None, + (Some(_), None) => bail!("the load guard needs a probe"), + }; let scratch = ScratchDir::new("ab")?; let baseline = BinaryInfo::inspect(&config.baseline, &scratch.path().join("baseline.version")) .context("inspecting the --baseline binary")?; - let candidate = - BinaryInfo::inspect(&config.candidate, &scratch.path().join("candidate.version")) - .context("inspecting the --candidate binary")?; - let binaries = [&baseline, &candidate]; + let candidates = config + .candidates + .iter() + .enumerate() + .map(|(index, path)| { + BinaryInfo::inspect( + path, + &scratch.path().join(format!("candidate{index}.version")), + ) + .with_context(|| format!("inspecting the --candidate binary {}", path.display())) + }) + .collect::>>()?; + let mut session = Session { + config, + binaries: std::iter::once(&baseline).chain(&candidates).collect(), + scratch: scratch.path(), + guard, + }; + let session_start = match &mut session.guard { + Some((limits, probe)) => { + eprintln!( + "==> load guard: waiting for {} quiet checks in a row", + limits.start_checks + ); + let start = limits.wait_for_quiet_start(&mut **probe)?; + eprintln!( + " quiet after {} checks ({:.0} s)", + start.checks.len(), + start.waited_secs + ); + Some(start) + } + None => None, + }; let mut corpora = Vec::with_capacity(config.corpora.len()); for (index, corpus) in config.corpora.iter().enumerate() { eprintln!("==> {} ({})", corpus.name, corpus.source.display()); - corpora.push(measure_corpus( - config, - index, - corpus, - binaries, - scratch.path(), - )?); + corpora.push(session.measure_corpus(index, corpus)?); } Ok(AbReport { - schema_version: 1, + schema_version: REPORT_SCHEMA_VERSION, kind: REPORT_KIND.to_string(), argv: config.argv.clone(), environment: AbEnvironment::detect(config.workspace_root.as_deref()), settings: AbSettings::of(config), + session_start, + candidate: candidates[0].clone(), baseline, - candidate, + candidates, corpora, }) } @@ -352,10 +689,13 @@ fn validate(config: &AbConfig) -> Result<()> { config.runs ); } + if config.candidates.is_empty() { + bail!("--ab needs at least one --candidate"); + } if config.threads.is_empty() { bail!("--ab needs at least one thread count (--threads )"); } - if config.threads.contains(&0) { + if config.threads.contains(&Threads::Count(0)) { bail!("thread counts must be at least 1"); } let distinct: BTreeSet<_> = config.threads.iter().collect(); @@ -372,45 +712,36 @@ fn validate(config: &AbConfig) -> Result<()> { if config.run_timeout.is_zero() { bail!("the run timeout must be positive"); } + if let Some(guard) = &config.load_guard + && (guard.logical_cpus == 0 || guard.max_attempts_factor == 0) + { + bail!("the load guard needs a CPU count and at least one attempt per run"); + } Ok(()) } -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -enum Arm { - Baseline, - Candidate, +/// The arms of run `run` in the order they go: the order rotates by one arm a +/// run, so each of the `arms` arms goes first equally often. With two arms the +/// baseline goes first in even runs and the candidate in odd ones. +fn rotation(run: usize, arms: usize) -> Vec { + (0..arms).map(|offset| (run + offset) % arms).collect() } -impl Arm { - fn index(self) -> usize { - match self { - Self::Baseline => 0, - Self::Candidate => 1, - } - } - - fn name(self) -> &'static str { - match self { - Self::Baseline => "baseline", - Self::Candidate => "candidate", - } - } - - /// Even runs time the baseline first, odd runs the candidate first. - fn order(run: usize) -> [Self; 2] { - if run.is_multiple_of(2) { - [Self::Baseline, Self::Candidate] - } else { - [Self::Candidate, Self::Baseline] - } +/// An arm's name in progress lines and errors: `baseline`, `candidate` when +/// there is one, `candidate ` when there are several. +fn arm_name(arm: usize, candidates: usize) -> String { + match arm { + 0 => "baseline".to_string(), + _ if candidates == 1 => "candidate".to_string(), + index => format!("candidate {index}"), } } /// Names one timed run in progress lines and errors. struct RunLabel<'a> { - arm: Arm, + arm: &'a str, corpus: &'a str, - threads: usize, + threads: Threads, run: usize, runs: usize, } @@ -419,119 +750,515 @@ impl fmt::Display for RunLabel<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, - "{} run {}/{} on {} ({}={})", - self.arm.name(), + "{} run {}/{} on {} ({})", + self.arm, self.run + 1, self.runs, self.corpus, - THREAD_ENV, self.threads ) } } -fn measure_corpus( - config: &AbConfig, - index: usize, - corpus: &AbCorpus, - binaries: [&BinaryInfo; 2], - scratch: &Path, -) -> Result { - let mut graphs: [Option; 2] = [None, None]; - let mut copied = CopyStats::default(); - let mut cells = Vec::with_capacity(config.threads.len()); - for &threads in &config.threads { - let mut series: [Vec; 2] = [Vec::new(), Vec::new()]; - for run in 0..config.runs { - for arm in Arm::order(run) { - let label = RunLabel { - arm, - corpus: &corpus.name, - threads, - run, - runs: config.runs, - }; - let run_dir = scratch.join(format!("c{index}-{}-t{threads}-r{run}", arm.name())); - let outcome = measure_run( - binaries[arm.index()], - corpus, - threads, - &run_dir, - config.run_timeout, - ) - .with_context(|| format!("{label} failed"))?; - fs::remove_dir_all(&run_dir) - .with_context(|| format!("removing {}", run_dir.display()))?; - check_same_graph(&mut graphs[arm.index()], &outcome.graph, &label)?; - copied = outcome.copied; - let wall_ms = outcome.wall.as_secs_f64() * 1000.0; - eprintln!( - " {label}: {wall_ms:.1} ms, peak RSS {}{}", - outcome - .peak_rss_kb - .map_or_else(|| "n/a".to_string(), |kb| format!("{kb} KiB")), - if run == 0 { " (warm-up)" } else { "" } - ); - series[arm.index()].push(RunSample { - run: run + 1, - warmup: run == 0, - wall_ms, - peak_rss_kb: outcome.peak_rss_kb, - canonical_hash: outcome.graph.hash.clone(), +/// One `bench --ab` invocation in progress: the binaries in arm order (the +/// baseline first) and the load guard with its probe. +struct Session<'a, 'p> { + config: &'a AbConfig, + binaries: Vec<&'a BinaryInfo>, + scratch: &'a Path, + guard: Option<(&'a LoadGuard, &'p mut dyn LoadProbe)>, +} + +/// What one timed run measured. +struct TimedRun { + measured: Measured, + phases: BTreeMap, + /// The graph an `init` run wrote. + graph: Option, + copied: CopyStats, + load: Option, + void: Option, +} + +impl Session<'_, '_> { + fn arms(&self) -> usize { + self.binaries.len() + } + + fn arm_name(&self, arm: usize) -> String { + arm_name(arm, self.arms() - 1) + } + + /// The most attempts a cell gives one binary. + fn max_attempts(&self) -> usize { + let factor = self + .guard + .as_ref() + .map_or(1, |(limits, _)| limits.max_attempts_factor); + self.config.runs * factor + } + + fn measure_corpus(&mut self, index: usize, corpus: &AbCorpus) -> Result { + let arms = self.arms(); + let config = self.config; + let mut graphs: Vec> = vec![None; arms]; + let mut copied = CopyStats::default(); + let mut edited_files = Vec::new(); + let mut cells = Vec::with_capacity(config.threads.len()); + for &threads in &config.threads { + let cell_dir = self.scratch.join(format!("c{index}-t{}", threads.label())); + fs::create_dir_all(&cell_dir) + .with_context(|| format!("creating {}", cell_dir.display()))?; + let mut syncs: Vec> = Vec::with_capacity(arms); + for arm in 0..arms { + syncs.push(if config.op.is_sync() { + let (sync, stats) = self + .prepare_sync_arm(arm, corpus, threads, &cell_dir) + .with_context(|| { + format!( + "preparing the {} sync runs on {} ({threads})", + self.arm_name(arm), + corpus.name + ) + })?; + copied = stats; + edited_files = sync.relative_paths(); + Some(sync) + } else { + None }); } + let mut series: Vec> = vec![Vec::new(); arms]; + let mut attempts = vec![0_usize; arms]; + for run in 0..config.runs { + for arm in rotation(run, arms) { + let name = self.arm_name(arm); + let label = RunLabel { + arm: &name, + corpus: &corpus.name, + threads, + run, + runs: config.runs, + }; + loop { + attempts[arm] += 1; + if attempts[arm] > self.max_attempts() { + bail!( + "{label}: the load guard voided too many runs; {} attempts \ + left the cell short of {} valid runs, so no report is written", + self.max_attempts(), + config.runs + ); + } + let attempt = attempts[arm]; + let timed = match &mut syncs[arm] { + Some(sync) => self.timed_sync(arm, sync, threads, run == 0, attempt), + None => { + self.timed_init(arm, corpus, threads, &cell_dir, run == 0, attempt) + } + } + .with_context(|| format!("{label} failed"))?; + if let Some(graph) = &timed.graph { + check_same_graph( + &mut graphs[arm], + graph, + &label.to_string(), + &name, + &corpus.name, + )?; + copied = timed.copied; + } + let sample = RunSample { + run: attempt, + warmup: run == 0, + wall_ms: timed.measured.wall.as_secs_f64() * 1000.0, + peak_rss_kb: timed.measured.peak_rss_kb, + canonical_hash: timed.graph.map(|graph| graph.hash), + cpu_ms: timed.measured.cpu.map(|cpu| cpu.as_secs_f64() * 1000.0), + phase_ms: timed.phases, + load: timed.load, + void: timed.void, + }; + eprintln!( + " {label}: {:.1} ms, peak RSS {}{}{}", + sample.wall_ms, + sample + .peak_rss_kb + .map_or_else(|| "n/a".to_string(), |kb| format!("{kb} KiB")), + if run == 0 { " (warm-up)" } else { "" }, + sample.void.as_ref().map_or_else(String::new, |why| format!( + " (void: {why}; running again)" + )) + ); + let void = sample.void.is_some(); + series[arm].push(sample); + if !void { + break; + } + } + } + } + for (arm, sync) in syncs.into_iter().enumerate() { + let Some(sync) = sync else { continue }; + let name = self.arm_name(arm); + let graph = self + .finish_sync_arm(arm, sync, corpus, threads) + .with_context(|| { + format!( + "finishing the {name} sync runs on {} ({threads})", + corpus.name + ) + })?; + let label = format!("the {name} final sync on {} ({threads})", corpus.name); + check_same_graph(&mut graphs[arm], &graph, &label, &name, &corpus.name)?; + } + fs::remove_dir_all(&cell_dir) + .with_context(|| format!("removing {}", cell_dir.display()))?; + for (arm, runs) in series.iter().enumerate() { + check_phase_names(runs).with_context(|| { + format!( + "the {} runs on {} ({threads})", + self.arm_name(arm), + corpus.name + ) + })?; + } + let rows: Vec> = graphs + .iter() + .map(|graph| graph.as_ref().map(|graph| graph.rows.total)) + .collect(); + cells.push(build_cell(threads, series, &rows, &config.op)?); } - let [baseline_runs, candidate_runs] = series; - let rows = |arm: Arm| graphs[arm.index()].as_ref().map(|graph| graph.rows.total); - let baseline = ArmSeries::new(baseline_runs, rows(Arm::Baseline))?; - let candidate = ArmSeries::new(candidate_runs, rows(Arm::Candidate))?; - let ratio = Ratios::between( - &baseline, - &candidate, - rows(Arm::Baseline), - rows(Arm::Candidate), - ); - cells.push(Cell { + let graphs = graphs + .into_iter() + .collect::>>() + .with_context(|| format!("corpus {} produced no measured runs", corpus.name))?; + let comparisons: Vec = graphs[1..] + .iter() + .enumerate() + .map(|(index, candidate)| { + let differing = differing_surfaces(&graphs[0], candidate); + eprintln!( + " graph: {}", + if differing.is_empty() { + format!("{} identical", self.arm_name(index + 1)) + } else { + format!( + "baseline and {} differ in {}", + self.arm_name(index + 1), + differing.join(", ") + ) + } + ); + GraphComparison { + identical: differing.is_empty(), + differing_surfaces: differing, + baseline: graphs[0].clone(), + candidate: candidate.clone(), + } + }) + .collect(); + Ok(CorpusAb { + name: corpus.name.clone(), + commit: corpus.commit.clone(), + tag: corpus.tag.clone(), + source: corpus.source.display().to_string(), + copied_files: copied.files, + skipped_symlinks: copied.skipped_symlinks, + graph: comparisons[0].clone(), + graphs: comparisons, + edited_files, + cells, + }) + } + + /// Run `spawn` (the timed child alone) inside the load guard: wait for the + /// host, then measure the CPU time others used. A warm-up is never void. + fn guarded( + &mut self, + threads: Threads, + warmup: bool, + spawn: impl FnOnce() -> Result, + ) -> Result<(Measured, Option, Option)> { + let Some((limits, probe)) = &mut self.guard else { + return Ok((spawn()?, None, None)); + }; + let saturating = limits.saturating(threads.count()); + let gate = limits.wait_before_run(&mut **probe, saturating)?; + let window = limits.open_window(&mut **probe)?; + let measured = spawn()?; + let foreign = limits.foreign_cpus( + &mut **probe, + window, + measured.cpu.unwrap_or_default(), + measured.wall, + )?; + let limit = limits.foreign_cpus_limit(saturating); + let void = (!warmup && foreign > limit) + .then(|| format!("{foreign:.2} foreign CPUs, over the {limit} limit")); + let load = RunLoad { + load1: gate.load1, + idle_cpus: gate.idle_cpus, + waited_ms: gate.waited.as_secs_f64() * 1000.0, + foreign_cpus: foreign, + }; + Ok((measured, Some(load), void)) + } + + /// One timed cold `init` of a fresh copy of the corpus. + fn timed_init( + &mut self, + arm: usize, + corpus: &AbCorpus, + threads: Threads, + cell_dir: &Path, + warmup: bool, + attempt: usize, + ) -> Result { + let binary = self.binaries[arm]; + let run_dir = cell_dir.join(format!("arm{arm}-r{attempt}")); + let project = run_dir.join("project"); + fs::create_dir_all(&run_dir).with_context(|| format!("creating {}", run_dir.display()))?; + let copied = copy_corpus(&corpus.source, &project)?; + let stdout = run_dir.join("init.stdout"); + let stderr = run_dir.join("init.stderr"); + let mut command = codegraph_command( + binary, "init", &project, threads, &run_dir, &stdout, &stderr, + )?; + let timeout = self.config.run_timeout; + let (measured, load, void) = self.guarded(threads, warmup, || { + spawn_measured(&mut command, timeout) + .with_context(|| format!("running {} init", binary.path)) + })?; + check_exit(binary, "init", &measured, &stderr, timeout)?; + let phases = read_phases(&stderr, "init")?; + let db = project.join(DEFAULT_CURRENT_DIR).join(DATABASE_FILE); + if !db.is_file() { + bail!( + "`{} init` exited 0 but produced no database at {}", + binary.path, + db.display() + ); + } + let canonical = canonicalize_checked(&db) + .with_context(|| format!("the database {} cannot be canonicalized", db.display()))?; + fs::remove_dir_all(&run_dir).with_context(|| format!("removing {}", run_dir.display()))?; + Ok(TimedRun { + measured, + phases, + graph: Some(fingerprint(&canonical)), + copied, + load, + void, + }) + } + + /// Index the arm's own copy of the corpus, pick the files to edit, and + /// run the untimed warm-up sync. + fn prepare_sync_arm( + &mut self, + arm: usize, + corpus: &AbCorpus, + threads: Threads, + cell_dir: &Path, + ) -> Result<(SyncArm, CopyStats)> { + let binary = self.binaries[arm]; + let dir = cell_dir.join(format!("arm{arm}")); + let project = dir.join("project"); + let copied = copy_corpus(&corpus.source, &project)?; + let timeout = self.config.run_timeout; + run_untimed(binary, "init", &project, threads, &dir, timeout)?; + let db = project.join(DEFAULT_CURRENT_DIR).join(DATABASE_FILE); + if !db.is_file() { + bail!( + "`{} init` exited 0 but produced no database at {}", + binary.path, + db.display() + ); + } + let (_, graph) = load_graph(&db)?; + let edits = select_edits(&graph.files, &self.config.op, &project)?; + let mut sync = SyncArm { + dir, + project, + edits, + }; + sync.append("warm-up")?; + let stdout = run_untimed(binary, "sync", &sync.project, threads, &sync.dir, timeout)?; + check_reindexed(binary, &stdout, sync.edits.len())?; + Ok((sync, copied)) + } + + /// One timed sync after another comment line in every edited file. + fn timed_sync( + &mut self, + arm: usize, + sync: &mut SyncArm, + threads: Threads, + warmup: bool, + attempt: usize, + ) -> Result { + let binary = self.binaries[arm]; + sync.append(&attempt.to_string())?; + let stdout = sync.dir.join(format!("sync-{attempt}.stdout")); + let stderr = sync.dir.join(format!("sync-{attempt}.stderr")); + let mut command = codegraph_command( + binary, + "sync", + &sync.project, threads, - budget: BudgetVerdict::evaluate(&ratio, &BudgetLimits::PROJECT), - baseline, - candidate, - ratio, - }); + &sync.dir, + &stdout, + &stderr, + )?; + let timeout = self.config.run_timeout; + let (measured, load, void) = self.guarded(threads, warmup, || { + spawn_measured(&mut command, timeout) + .with_context(|| format!("running {} sync", binary.path)) + })?; + check_exit(binary, "sync", &measured, &stderr, timeout)?; + let phases = read_phases(&stderr, "sync")?; + let printed = + fs::read_to_string(&stdout).with_context(|| format!("reading {}", stdout.display()))?; + check_reindexed(binary, &printed, sync.edits.len())?; + for path in [&stdout, &stderr] { + fs::remove_file(path).with_context(|| format!("removing {}", path.display()))?; + } + Ok(TimedRun { + measured, + phases, + graph: None, + copied: CopyStats::default(), + load, + void, + }) } - let [Some(baseline), Some(candidate)] = graphs else { - bail!("corpus {} produced no measured runs", corpus.name); - }; - let differing = differing_surfaces(&baseline, &candidate); - eprintln!( - " graph: {}", - if differing.is_empty() { - "identical".to_string() - } else { - format!("baseline and candidate differ in {}", differing.join(", ")) + + /// Set every edited file to its original text plus one final comment, + /// sync that, and check the synced graph against a fresh `init` of the + /// same source: the graph every binary's runs of the cell end with. + fn finish_sync_arm( + &mut self, + arm: usize, + sync: SyncArm, + corpus: &AbCorpus, + threads: Threads, + ) -> Result { + let binary = self.binaries[arm]; + let timeout = self.config.run_timeout; + sync.write_final()?; + let stdout = run_untimed(binary, "sync", &sync.project, threads, &sync.dir, timeout)?; + check_reindexed(binary, &stdout, sync.edits.len())?; + let (_, synced) = load_graph(&sync.project.join(DEFAULT_CURRENT_DIR).join(DATABASE_FILE))?; + let fresh = sync.dir.join("fresh"); + copy_corpus(&sync.project, &fresh)?; + run_untimed(binary, "init", &fresh, threads, &sync.dir, timeout)?; + let fresh_db = fresh.join(DEFAULT_CURRENT_DIR).join(DATABASE_FILE); + let fresh_graph = canonicalize_checked(&fresh_db).with_context(|| { + format!( + "the database {} cannot be canonicalized", + fresh_db.display() + ) + })?; + let (synced, fresh_graph) = (fingerprint(&synced), fingerprint(&fresh_graph)); + if synced.hash != fresh_graph.hash { + bail!( + "`{} sync` on {} does not converge with a fresh init of the edited source \ + (differing surfaces: {}); a sync's timing is only measured on a sync that \ + builds the graph init builds", + binary.path, + corpus.name, + differing_surfaces(&synced, &fresh_graph).join(", ") + ); } - ); - Ok(CorpusAb { - name: corpus.name.clone(), - commit: corpus.commit.clone(), - tag: corpus.tag.clone(), - source: corpus.source.display().to_string(), - copied_files: copied.files, - skipped_symlinks: copied.skipped_symlinks, - graph: GraphComparison { - identical: differing.is_empty(), - differing_surfaces: differing, - baseline, - candidate, - }, - cells, + fs::remove_dir_all(&sync.dir) + .with_context(|| format!("removing {}", sync.dir.display()))?; + Ok(synced) + } +} + +/// The statistics of one cell, its candidates against the baseline. +fn build_cell( + threads: Threads, + series: Vec>, + rows: &[Option], + op: &AbOp, +) -> Result { + let mut arms = series + .into_iter() + .zip(rows) + .map(|(runs, rows)| ArmSeries::new(runs, rows.filter(|_| !op.is_sync()))) + .collect::>>()? + .into_iter(); + let baseline = arms.next().context("a cell has a baseline")?; + let candidates: Vec = arms + .enumerate() + .map(|(index, series)| { + let ratio = Ratios::between(&baseline, &series, rows[0], rows[index + 1]); + let budget = if op.is_sync() { + BudgetVerdict::evaluate_sync(&ratio, &BudgetLimits::PROJECT, op.single_file_sync()) + } else { + BudgetVerdict::evaluate(&ratio, &BudgetLimits::PROJECT) + }; + let phase_ratio = baseline + .phase_ms + .iter() + .filter_map(|(phase, base)| { + let candidate = series.phase_ms.get(phase)?; + Some(( + phase.clone(), + ratio_of(Some(candidate.median), Some(base.median))?, + )) + }) + .collect(); + CandidateCell { + series, + ratio, + budget, + phase_ratio, + } + }) + .collect(); + let first = candidates.first().context("a cell has a candidate")?; + Ok(Cell { + threads: threads.resolved(), + default_threads: threads == Threads::Default, + candidate: first.series.clone(), + ratio: first.ratio, + budget: first.budget, + baseline, + candidates, }) } +/// Every run of one binary in a cell must name the same phases: a set that +/// changes between runs means the runs did not do the same work. +fn check_phase_names(runs: &[RunSample]) -> Result<()> { + let Some(first) = runs.first() else { + return Ok(()); + }; + let names = |run: &RunSample| run.phase_ms.keys().cloned().collect::>(); + let expected = names(first); + for run in &runs[1..] { + let got = names(run); + if got != expected { + bail!( + "run {} and run {} report different phases: {:?}", + first.run, + run.run, + got.symmetric_difference(&expected).collect::>() + ); + } + } + Ok(()) +} + fn check_same_graph( first: &mut Option, graph: &GraphFingerprint, - label: &RunLabel<'_>, + label: &str, + arm: &str, + corpus: &str, ) -> Result<()> { match first { None => { @@ -540,92 +1267,301 @@ fn check_same_graph( } Some(expected) if expected.hash == graph.hash => Ok(()), Some(expected) => bail!( - "non-deterministic graph: {label} produced canonical hash {}, but the first {} run on \ - {} produced {} (differing surfaces: {}); every run of one binary must produce the \ - same canonical graph", + "non-deterministic graph: {label} produced canonical hash {}, but the first {arm} run \ + on {corpus} produced {} (differing surfaces: {}); every run of one binary must \ + produce the same canonical graph", graph.hash, - label.arm.name(), - label.corpus, expected.hash, differing_surfaces(expected, graph).join(", ") ), } } -struct RunOutcome { - wall: Duration, - peak_rss_kb: Option, - graph: GraphFingerprint, - copied: CopyStats, +/// One binary's project for a cell's sync runs. +struct SyncArm { + dir: PathBuf, + project: PathBuf, + edits: Vec, +} + +/// A file the sync runs edit. +struct EditTarget { + relative: String, + full: PathBuf, + original: Vec, + comment: &'static str, +} + +impl SyncArm { + fn relative_paths(&self) -> Vec { + self.edits + .iter() + .map(|edit| edit.relative.clone()) + .collect() + } + + /// Append one comment line, `codegraph-bench sync-edit