Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 33.7 KiBRenderedRawPermalink
1# Design
2
3Braid is a version control system for repositories where many agents create
4and land changes at the same time. This document explains the architecture and
5the reasons behind it. The byte-level format is in
6[`spec/format-v1.md`](spec/format-v1.md).
7
8## Goals
9
10- **Cost follows the change, not the repository.** Creating, rebasing and
11 landing a change costs time proportional to the files it touches.
12- **Many writers, no repository-wide lock.** Agents create changes in parallel;
13 the only serial step is moving a branch, and it is short.
14- **Correct without a daemon.** Any number of `braid` processes, of any version
15 that understands the format, can share one store. A daemon may speed things
16 up but is never needed for correctness.
17- **Immutable, content-addressed data.** Any cache can serve any object, and
18 nothing is ever rewritten in place.
19- **Git at the edges.** Existing repositories come in with their full history,
20 and GitHub or Gitea keep working as mirrors.
21- **Built for agents.** Every command has a JSON form, a change can be
22 created through the API without a working copy, and `braid agents init`
23 tells a project's agents, in its `AGENTS.md`, how to work through braid.
24
25## Non-goals
26
27- Being a drop-in replacement for the `git` command line.
28- Offline-first distributed workflows with many equal peers. Braid works
29 offline on one machine, and a server is the authority when several machines
30 share a repository.
31- Preventing semantic conflicts: two changes can merge cleanly and still break
32 the build together. Braid records what landed so CI can find out.
33
34## Data model
35
36- **Blob:** file content. **Tree:** a directory (flat, or split into
37 content-defined nodes when large). **Changeset:** parents, the root tree, and
38 the files that changed relative to the first parent.
39- Ids are BLAKE3 hashes in key-derivation mode, one context per kind.
40- A changeset stores both the per-file change list and the root tree id, and
41 the store checks that they agree before accepting it. The change list makes
42 history, blame and rebase cheap; the root tree id makes the changeset commit
43 to the whole repository state.
44- Large directories are split with a rule that depends only on entry names, so
45 an edit rewrites a few small nodes instead of the whole directory, and equal
46 contents always have equal ids.
47- A changeset may carry extra fields, ordered key and value pairs that are
48 part of its hash. Braid writes two: `agent`, the label of the agent that
49 made the changeset, and `rebased-from`, the changeset a rebased one comes
50 from. A rebase keeps the original's other fields, so `agent` names the
51 agent that made the change wherever it lands. The git bridge writes extra
52 fields as commit headers.
53- Ids are shown as their first 12 hex digits, and any unique prefix of six
54 digits or more names an object; the lookup reads the fan-out bucket of
55 each index that the prefix falls in, and a prefix that several objects
56 share is an error that lists them.
57
58## Store
59
60A store is a directory of files that several processes share. Its correctness
61rests only on guarantees every local file system gives: exclusive create,
62appends protected by checksums, advisory locks that the kernel releases when a
63process dies, atomic rename, and ordered syncs.
64
65- **Segments.** Objects are appended to segment files. A writer leases an open
66 segment with a non-blocking lock, or creates a new one. Segments are never
67 truncated: after a crash, the next writer appends after the last valid record.
68- **Journals and indexes.** Each open segment has a journal of fixed-size,
69 checksummed entries, so readers find new objects without scanning payloads. A
70 segment is sealed with a sorted index once it is full or its journal lists
71 8,192 records, and a writer merges the indexes of sealed segments once 8 of
72 them pile up, so that a lookup goes through few. A process keeps a map of
73 ids only for the open segments, and reads an index as lookups need it, one
74 fan-out bucket at a time, each entry checked by its own checksum: opening a
75 store reads no index entry, whatever the store holds. Nothing is
76 memory-mapped.
77- **Deltas.** Writers say which object a new one is probably close to: the
78 engine names the directory node a rebuilt one replaces and, for a merged
79 file, the branch's version; a workspace commit names the file's previous
80 blob; the git import names the first parent's blob or tree at the same
81 path, and its raw commit; a new git map names the one it grew from. A blob
82 under 4 MiB, a tree or a derived object is then stored as a zstd frame
83 against that object when this takes at most a quarter of the bytes.
84 Deltas are one level deep: a base is always stored whole, so a read
85 applies at most one delta, never a chain. The price is size: each delta
86 holds every change since its base, until a version is stored whole again.
87- **Large files.** Blobs of 4 MiB or more are cut into content-defined chunks
88 (FastCDC), each a blob of its own, so versions of a large file, such as a
89 model's weights, share every chunk an edit did not touch, with no side
90 system like LFS. A blob's id is still the hash of its whole content. Large
91 blobs are written and read as streams, a chunk at a time.
92- **Garbage collection** is not there yet: nothing is ever removed from a
93 store. When it comes, it must keep every base a delta needs and every chunk
94 a chunk list names. `braid stats` shows how a store's objects are stored,
95 and `braid fsck` checks deltas and chunked blobs with everything else.
96- **Op log.** Branch heads and the history of operations live in an
97 append-only log behind a short lock. Every record names the agent that wrote
98 it, so `braid op log` shows who did what and `braid undo` can step back. A
99 record's description is written inside the transaction, once the outcome
100 is known: a landing says how it went, which changeset landed as which, and
101 how many paths it merged.
102- **Publish order.** Objects and their journal entries, flushed in one batch,
103 then the op log record that refers to them, flushed in a second. The op log
104 never points at an object that is not durable, and an index never reaches
105 the disk before the segment it points into.
106- **Durability modes.** `ordered` (local default) may lose the last operations
107 on power loss but is never inconsistent; where the system has a write
108 barrier (`F_BARRIERFSYNC` on Apple systems), it keeps the order of writes
109 with one instead of waiting for the drive to write out its whole cache.
110 `full` (server default) syncs fully before acknowledging. Either way,
111 inside its lock a transaction flushes the two batches above, however many
112 files it wrote to.
113- **Derived data** (generation numbers, ancestry skip pointers, changed-path
114 filters, blame, git mappings) is stored as records keyed by their inputs, and
115 can always be recomputed.
116
117### Derived data
118
119Everything that is not in a changeset is derived data: computed from
120changesets, stored, and always recomputable. A derived value is what a named
121function, at some version, gives for some inputs, and its key is
122`BLAKE3-derive-key("elffuss-braid 2026 derived v1", function ‖ version ‖ input
123ids ‖ argument)`. The encodings are in section 8 of the format spec.
124
125- **Records.** A value is stored as an ordinary derived object whose payload
126 is its key followed by its encoding, which each function versions on its
127 own: a new encoding is a new version, so new keys. The object's id depends
128 on the value, so the store keeps a *derived index* next to its segments,
129 `derived/index`: an append-only file of fixed-size entries, a key and a
130 record id, each with a checksum.
131- **A cache, checked on use.** The index is never trusted: a record is used
132 only when its payload starts with the key and its value decodes, and a
133 value whose record is missing, damaged or unindexed is computed again.
134 Losing the index, or part of it, costs only time.
135- **Many processes, no database.** Values are deterministic functions of their
136 inputs, so two processes that compute the same value store the same bytes
137 under the same id; storing an object twice does nothing, and two entries
138 for a key name the same record. Writers append to the index under an
139 exclusive lock, at a multiple of the entry size, so a crash leaves at worst
140 an entry that fails its checksum, and readers take no lock. Records are
141 made durable before an entry names them.
142- **Lazy.** A value is computed the first time a command needs it, with the
143 values it depends on, and recorded when the command finishes. `braid
144 derive` computes them ahead of time, after a large import for example.
145- The git map is a derived record too, but a single one, found through the
146 ref `braid/git-map` rather than the index.
147
148## Landing on a branch
149
150`land` takes a changeset `C` built on base `B` and moves a branch to include it.
151Bases are always ids, never branch names, so nothing is resolved late.
152
1531. If the request for `(branch, C)` already landed, return that result. A lost
154 acknowledgement is retried safely.
1552. `B` must be on the branch's first-parent chain.
1563. If `B` is the head, fast-forward.
1574. Otherwise rebase `C` onto the head, path by path: unchanged since `B` takes
158 `C`'s value; changed on both sides goes through a three-way merge. The cost
159 follows the size of `C`.
1605. Write the new objects, append the landing record, sync, then publish the new
161 head.
162
163Locally this step runs under the op log lock; on a server, one task per branch
164runs it in order, grouping several landings into one sync.
165
166Conflicts are reported as data, not as markers in a file: the path, the kind,
167what the base, the head (ours) and the change (theirs) have there, and the
168hunks, with line numbers counted from 0 and the end excluded. The command line
169names the sides from the caller's point of view: `base`, `branch` and
170`workspace`. Braid is stricter than git about structural conflicts: a file
171against a directory, two names that differ only in case or Unicode
172normalisation, a directory removed under a new file, and the same file renamed
173two ways.
174
175A revert is a landing like any other. The revert `R` of a changeset `C` has
176`C` as its only parent, the change list from `C`'s tree back to its first
177parent's, and a `reverts` extra field naming `C`. Landed on a head that moved
178past `C`, it is rebased path by path with `C` as the base, the head as ours
179and `C`'s parent as theirs: later work on other lines stays, and later work
180on the same lines is a conflict. `braid verify` lands the reverts it makes
181the same way, with the agent `braid-verify`. Its limits are read from the
182branch, so that a fresh clone keeps them: it refuses to revert a changeset
183that has a `reverts` field and that agent, and counts the reverts of the
184last hour by each one's own committer time, among the last 10,000
185changesets of the branch. Dates are not in order along a branch, since a
186fast-forward keeps the date a changeset was made with and a git commit can
187carry any date, so an old one stops nothing: only the depth bounds the
188walk. Anyone can write that field and that label: the label is only
189ever a reason to refuse. The field also tells bisecting where a culprit
190was reverted later in the range, but verify only acts on that by testing
191the changeset that carries it, and bisects on after it only if the tests
192pass there: a false field can make verify run one more test, or end with
193`no_culprit` instead of reverting the culprit, but it never blames a
194changeset that passes, or one whose parent fails. A local record in
195`.braid/verify/` is a second source for both limits. Its green ref,
196`braid/green/<branch>`, lives in braid's own namespace: it is local to the
197repository and never exported or sent to a hub.
198
199**Invariants.** A branch only moves forward. A branch never contains a
200conflict. No value is overwritten except by a change whose base already
201contained it. An acknowledged landing is durable. Readers only see durable
202heads.
203
204## History
205
206Three derived functions answer history queries without walking all of
207history every time. The engine's `History` reads them through the derived
208index, computes what is missing, and remembers what it read.
209
210- **Commit graph data** (`graph`, per changeset): the parents, the
211 generation (1 without parents, otherwise 1 more than the largest of the
212 parents'), the height along first parents, and a skip pointer to the
213 first-parent ancestor at the height that Bitcoin's block index picks for
214 its skip pointers. Following skip pointers reaches any first-parent
215 ancestor in a number of steps that grows with the logarithm of the
216 distance. With them, `is_ancestor` and `first_parent_chain_contains` find a
217 first-parent ancestor in logarithmic time, and every other walk stops
218 below the generation it looks for, since an ancestor always has a smaller
219 generation. `merge_bases` walks down from both sides in order of
220 generation, marking what each side reaches; a changeset reached from both
221 is a merge base unless it is below one already found, and the walk stops
222 when everything left to visit is. The answers are those of the walking
223 functions, which landing, merging, workspaces and git sync still use,
224 since they are given only objects; property tests compare the two on
225 random histories with octopus and criss-cross merges.
226- **Changed-path filters** (`changed-paths`, per changeset): the first parent
227 and a Bloom filter, with git's parameters (10 bits per entry, 7 hashes), of
228 the paths the change list names and their parent directories. `braid log
229 [rev] -- <path>...` lists, newest first, the changesets on the first-parent
230 chain whose change list touches a path or anything below it, as `git log
231 --first-parent -- <path>` does, without following renames. It reads one
232 small record per changeset walked, and a change list only where the filter
233 lets the changeset through: the ones that touched the path, and about one
234 in a hundred of the others.
235- **Blame** (`blame`, per changeset and path, where the changeset sets the
236 file): the changeset that last changed each line, as runs. It is computed
237 from the blame of the previous version of the file on the first-parent
238 chain and a line diff between the two versions, imara-diff's Myers
239 algorithm with its indentation heuristic, which is what git's blame uses by
240 default; a merge on the first-parent chain owns the lines it brought in.
241 Blaming a file computes the records of the versions that lack one, back to
242 the newest that has one, so blaming it again, at the same revision or a
243 later one, costs one diff per new version. `braid blame <rev> <path>`
244 prints the short id, the agent or the author, the date, the line number
245 and the line; `--json` gives the same per line.
246
247Blame differs from git's on purpose in two ways, and the differential tests
248check that it differs in no other:
249
250- **Renames are not followed.** Git follows a file across whole-file renames,
251 and has no switch to turn that off. Braid's history of a path starts where
252 the path last appeared: a line that git traces back across a rename is the
253 changeset's that created the path.
254- **The two diffs can differ.** Git's blame and braid's both use Myers'
255 algorithm with an indentation heuristic, but not the same implementation.
256 When a change has several shortest line diffs, they may keep different
257 copies of lines that repeat, such as closing braces and blank lines. And
258 neither always finds a shortest diff: both give up on it where the search
259 would cost too much, and imara-diff's preprocessing can miss it too, so on
260 a few changes one inserts and deletes more lines than the other. Blame
261 then gives those lines to different changesets. On this repository's own
262 history, fewer than one line in a thousand differs this way. Where the
263 blames differ, the tests walk the versions of the file: replaying git's
264 own diffs must give git's blame line for line, braid's blame at every
265 version must be braid's own diff applied to its blame at the version
266 before, and braid's diff must never insert fewer lines than the shortest
267 diff (`git diff --minimal`).
268
269## Workspaces
270
271- One workspace per agent, all sharing one store. No staging area: tracked
272 files are snapshotted as they are.
273- A workspace is any directory holding a `.braid` *file*, local and never
274 tracked, that names the repository and the workspace. It goes in
275 `.braid/work/<name>` of the repository unless `workspace add` is given a
276 directory, and it tracks a branch the repository has: a branch that does
277 not exist would give an empty checkout whose first landing starts a new
278 history under that name, so it is refused unless the repository has no
279 branch yet or `--new-branch` asks for it.
280- Every workspace also holds a `.git` *file* whose `gitdir:` line points
281 nowhere. A workspace inside a git checkout, as `.braid/work/` is, would
282 otherwise let git run in it find that checkout's repository, and `git
283 stash` or `git reset --hard` there would act on the shared checkout's
284 files. With the file, git stops with "not a git repository" instead. The
285 walk skips `.git`, as it skips `.braid`, so neither is ever committed.
286 `braid cat-object <base>:<path>` gives what git would have for a review
287 or an undo: the file as the workspace's base has it.
288- The workspace's state lives in the repository, under
289 `.braid/ws/<name>/`: `state` (the base changeset, the branch it lands on,
290 its directory, the file system's name rules, a rebase in progress),
291 `stat` (the stat cache) and `lock`. Every command that changes a
292 workspace holds its lock, so two processes never change one workspace at
293 once; different workspaces never wait for each other, except for the
294 short transaction in which a landing moves a branch.
295- New files that look like secrets (`.env*`, `*.pem`, `id_*`) or are larger than
296 1 MiB need an explicit `braid track`. Until then `braid commit` refuses,
297 naming them, and `--force` leaves them out.
298- Status uses a stat cache (modification time, size, inode, type, blob id),
299 with the usual guard: a file whose modification time is not strictly older
300 than the start of the scan that cached it, read from the workspace's own
301 file system clock, is hashed again. Files the cache cannot vouch for are
302 hashed in parallel. `.gitignore` and `.braidignore` are honoured; tracked
303 files count whatever they say. A daemon can add a file system watcher.
304- Checkouts never follow symlinks while walking or writing: every step opens
305 one name from its parent's directory handle, refusing symlinks. They write
306 through a temporary file and a rename, with modes 0644 or 0755 only, remove
307 before they create when a path changes type, write symlink targets as data,
308 and make gitlinks empty directories. Each workspace finds out once, with a
309 scratch file, whether its file system ignores letter case or Unicode
310 normalisation; names that would collide there, or that the platform cannot
311 hold, are refused before anything is written. Untracked files in the way
312 stop a checkout too. Nothing from repository content is ever run.
313- `braid commit` records the working copy as a changeset on the base. It
314 refuses while something blocks it, listing every reason at once: conflict
315 markers left in a file, a conflict that is not about content and not marked
316 resolved, a new file waiting for `braid track`. Before any of them it needs
317 someone to sign as, from `--author`, `BRAID_AUTHOR` or `.braid/config`, as
318 `land` and `update` do. `braid status` lists the same reasons as
319 `blocking`, with `ready_to_commit`, and a missing or invalid author first,
320 read the same way; it also counts how far the branch's head is ahead of
321 the workspace along first parents, stopping after 5000 changesets, and
322 lists the changesets that have not landed, including those of a rebase in
323 progress.
324- `braid land` puts the workspace's changesets on its branch in one op log
325 transaction: the engine fast-forwards or rebases them onto the head, and the
326 branch moves with a compare-and-swap. The working copy then follows, writing
327 only the difference. On conflicts the branch does not move, the conflicts
328 come back as data, and the command exits with status 2. `land` and `update`
329 report the same fields: where each changeset went, from its id to the one
330 that holds it now, the paths merged, the paths of the working copy written
331 or removed, and on conflicts the command to run next.
332- `braid update` brings a workspace onto its branch's head, rebasing its own
333 changesets without moving the branch. On conflicts, the working copy gets
334 the head's tree with the change's clean paths and git-style markers for
335 content conflicts; a rebase is then in progress, `braid resolve` settles the
336 other conflicts, and the next `braid commit` records the resolution on the
337 head, refusing while markers remain. The resolution keeps the rebased
338 changeset's author, extra fields and message, unless `-m` gives another.
339- A changeset can also be made without any working copy: `braid change
340 create` takes the base, the new contents and the deletions, and can require
341 what the base holds at each path first, so that an agent never overwrites
342 an edit it did not see.
343- Signatures record the time with the offset of the local time zone, which
344 [jiff](https://github.com/BurntSushi/jiff) reads from `TZ` or the system's
345 setting without calling into the C library; when it cannot be determined,
346 the offset is zero.
347
348### Instructions for agents
349
350Coding agents learn a project's rules from its `AGENTS.md`, or, for Claude
351Code and Gemini CLI, from a `CLAUDE.md` or a `GEMINI.md` that can include
352it. `braid agents init` writes there what an agent needs to work through
353braid, so that a project set up once tells every later session, whatever
354harness runs it. The guide that sets a project up is part 1 of the
355repository's `AGENTS.md`, which the site also serves as `agents.md`. It
356installs braid from the tag of the version it describes, since the site
357serves it apart from the code.
358
359- **A section of the file, not the file.** The rules sit between a line
360 `<!-- braid:start -->` and a line `<!-- braid:end -->`, appended to the
361 file the first time and rewritten in place after that. Text outside them
362 is never touched, a second run changes nothing, and markers that do not
363 pair up are refused before anything is written. Marker lines inside
364 fenced code blocks are examples, not markers, and a file that ends inside
365 an open block, where the section would read as code, is refused; a byte
366 order mark before the first line stays where it is. A `CLAUDE.md` or a
367 `GEMINI.md` that does not include `AGENTS.md` outside code gets the line
368 `@AGENTS.md`, and nothing else.
369- **Files written whole, or not at all.** Every check comes before any
370 write, and the same checks run with `--dry-run`: a name that is not a
371 regular file, a symbolic link out of the project, where other projects
372 may read the file, a read-only file, and a file with hard links other
373 than the project's guides are refused. Each file is written to a
374 temporary file next to it, all of them before the first is renamed into
375 place, so a failure while writing leaves every file as it was; one with
376 hard links, `CLAUDE.md` and `AGENTS.md` as one file, say, is written in
377 place, so that its names stay one file. A symbolic link stays one: the
378 file it points to is the one written, and the JSON names it.
379- **Only where braid is set up.** The section is committed, so every clone
380 of the project has it, including clones where braid is not set up: CI,
381 other machines, other people's agents. Its first rule says that a
382 checkout without a `.braid` directory does not use braid, and that braid
383 is set up there only when the user asks.
384- **Workspaces under `.braid/work/`.** Each session creates its workspace
385 at `.braid/work/<name>`, where `workspace add` puts it by default: inside
386 the project, where a harness that only lets an agent write in the
387 project can reach it; inside `.braid/`, which the setup has git ignore,
388 so that the shared checkout's git never sees the workspaces; and gone
389 with `.braid/` when braid is taken out. The setup's exclude line is
390 `.braid`, which also covers the `.braid` file of a workspace made
391 anywhere else in the checkout, since that file names the repository by
392 its absolute path. Git does not run in a workspace (see
393 [Workspaces](#workspaces)), and the section says why, and what to use
394 instead.
395- **The branch.** The section names the branch agents land on: the one
396 `--branch` gives, which the repository must have; else the one the
397 section already names, if the repository has it, so that a later run
398 keeps it; else, inside a workspace, the one it tracks; else `main`,
399 `master` or the repository's only branch. A branch the section names but
400 the repository does not have was named before the project's history came
401 in, or has been removed since: it is chosen again, and the command says
402 so. With several branches and none of those, or with no repository or
403 branch yet, the command asks for `--branch` rather than guess. The name
404 goes into shell commands and is read back from the section, so it takes
405 only characters that need no quoting.
406- **Every command names its agent.** A harness may run each command in a
407 new shell, which keeps neither variables nor the current directory, so
408 the section passes `--agent` on every command that records an operation
409 or a changeset, sync and undo included, and `--workspace` lets them run
410 from the project root. The hints braid prints, and `next` in its JSON,
411 repeat the `--repo`, `--agent` and `--workspace` typed on the command
412 line, so that a session that follows them stays the same session.
413- **What landed, and where.** A landing moves braid's branch only: the
414 shared checkout and the git remote get it from `braid git sync` and
415 `git pull --ff-only`. The section has a session that finishes say so to
416 the user, and offer to run them, rather than leave the user looking at
417 files that did not change; where the project has no git remote, it says
418 so, and offers to make a bare one next to the project first. When the
419 sync stops on conflicts, the section says that the merge is made with
420 git, in the user's checkout, and points to the guide's steps, as the
421 text `git sync` prints does.
422- **Nobody signs by guesswork.** The guide's setup writes `.braid/config`
423 from git's `user.name` and `user.email`, and stops before it imports
424 anything while either is missing, rather than let every commit and
425 landing fail later with "no author". Its own commit runs git with
426 `user.useConfigOnly`, so that git refuses rather than sign with a name
427 and an address made up from the machine's user and host, which the
428 first sync would publish. Its check for a finished setup asks braid's
429 copy of the branch for the section, so that a setup that stopped half
430 way is run again rather than taken for done.
431
432## Git bridge
433
434- Built on [gitoxide](https://github.com/GitoxideLabs/gitoxide). Braid contains
435 no code from git itself, which is GPLv2.
436- Import keeps the raw bytes of commits, tags and non-canonical trees, and
437 verifies each commit by exporting it again and comparing ids.
438- Export is deterministic. What it generates for changesets made in braid
439 (their commits, trees and blobs) enters the git map, so importing those
440 commits back, from wherever they went, gives the same changesets.
441- Braid's refs keep to their own namespaces: `braid/` for its bookkeeping
442 (the git map is `braid/git-map`), `tags/`, `git/` for other git refs, and
443 `remote/<label>/<branch>` for where the branches of git remotes were last
444 seen. A git branch named like one of them is imported under its full name,
445 below `git/`.
446- Sync fetches and imports first, then pushes with a lease, as a fast-forward:
447 the remote's history is never rewritten. The push itself runs the `git`
448 binary as a subprocess, since gitoxide does not push yet.
449
450### Sync
451
452`braid git sync <remote> [--branch main] [--remote-branch <name>]` keeps a
453braid branch and a branch of a git remote (GitHub, Gitea, a path) in step,
454so that the git host stays the public face of a repository while agents land
455in braid.
456
457- **Mirror.** Each remote has a bare mirror at `.braid/git/<label>.git`. The
458 label is the last name of the remote's path without `.git`, with every
459 character other than ASCII letters, digits, `.`, `_` and `-` turned into
460 `-`, then a `-` and the first 12 hex digits of the BLAKE3 hash of the
461 address without user name, password, trailing `/` or `.git`. So
462 `https://example.org/team/project.git` is `project-` and a hash, and no
463 credential ever reaches a file or ref name. In the mirror,
464 `refs/remotes/origin/<branch>` is the remote branch as fetched and
465 `refs/heads/<branch>` the braid branch as exported. `.braid/git/<label>.lock`
466 makes syncs with one remote take turns.
467- **Fetch and import.** The remote branch is fetched with an explicit refspec
468 and no tags, then imported. The braid ref `remote/<label>/<branch>` records
469 it.
470- **Reconcile.** With B the braid branch and G the remote branch: if they are
471 equal, there is nothing to do; without B, the braid branch is created at G;
472 if B is an ancestor of G, braid fast-forwards; if G is an ancestor of B, or
473 there is no G, B is pushed. Otherwise braid merges them with the engine's
474 `merge`, which follows landing's rules and conflicts: a clean merge moves
475 the braid branch to the merge, which is then pushed; conflicts move nothing
476 and exit with status 2. The braid branch moves only with a compare and swap,
477 in one operation with the git map and the remote's ref.
478- **Push.** `git push --atomic --porcelain
479 --force-with-lease=refs/heads/<branch>:<fetched> <remote>
480 <commit>:refs/heads/<branch>`, where `<fetched>` is what the same sync
481 fetched. What is pushed descends from it, so the remote only fast-forwards.
482 If someone else pushed in between, the lease fails and braid records
483 nothing more (after a merge, its branch is already at the merge); the next
484 sync merges the new commits.
485- **Crashes.** Each sync first records in the git map the commits of the
486 braid branch's changesets, which exports make deterministically. After a
487 crash between a push and its record, the commits that come back from the
488 remote are recognised as the changesets they came from, and nothing is
489 imported twice.
490- **Git commands** run with the user's environment, so credentials and SSH
491 settings work, minus the variables that would point git at another
492 repository, and with hooks, automatic garbage collection and the `ext::`
493 transport turned off.
494- **Identity.** A merge made by sync is committed by the `--agent` label, with
495 the `email` that `.braid/config` sets (`email = ...`), or else
496 `<agent>@example.org`. Git's own configuration is never read for identity.
497- **Dry run.** `--dry-run` fetches into a temporary repository that borrows
498 the mirror's objects, keeps braid objects in memory, and writes nothing.
499
500## Server and caches
501
502- HTTP, with immutable objects served by id so that a daemon, a regional cache,
503 nginx or a CDN can all answer the same request.
504- The daemon, the cache tier and the server implement the same API, so a client
505 does not know which one answers.
506- Writes go to the authority: one ordered landing task per branch.
507- Background work (derived data, compaction, git export) runs under an I/O
508 budget, so a small server's disk is never saturated.
509
510## Testing
511
512- **Deterministic simulation** (`crates/sim`). Simulated agents commit and
513 land at once through a lander that does what the CLI does inside its op log
514 transaction, with injected faults: lost acknowledgements, duplicate and
515 late resubmissions, and lander crashes before the compare-and-swap. It runs
516 on memory and on the real store. Every seed reproduces its run, and the
517 landing invariants are checked after every step against an independent
518 reference model.
519- **Crash tests.** Failpoints and repeated `kill -9` of real processes sharing
520 one store, and a power-loss model that drops whatever was not flushed before
521 each flush batch.
522- **Properties.** Encodings round-trip canonically; incremental tree updates
523 equal building from scratch; disjoint landings commute; a changeset's change
524 list equals the diff of its trees; three-way merges keep each side's changes
525 and are symmetric; ancestry with derived data answers what the walks answer
526 on random histories; changed-path filters never miss a path they hold;
527 derived records do not depend on the order they are computed in.
528- **Fuzzing.** Five targets: tree and changeset decoding, name rules, the git
529 map record, and git commit, tag and tree parsing. Anything that decodes must
530 encode back to the same bytes. CI runs each for a minute.
531- **Differential tests with git as the oracle** on fixtures, random histories
532 and this repository's own: path history (`git log --first-parent --
533 <path>`), merge bases (`git merge-base --all`) and blame (`git blame
534 --first-parent`, with the two differences above checked as such).
535- **Round trips** through import and export, bit for bit, of fixture
536 repositories full of unusual git objects and of this repository's history,
537 in CI; several public repositories were also round-tripped by hand.
538
539## Performance targets
540
541Stated as complexity and as ratios against git on the same machine. Braid's
542published benchmarks will only ever be ratios with the script that reproduces
543them.
544
545- Opening a store: proportional to its number of segments, of up to 8,192
546 objects each, not to its number of objects. A lookup reads one fan-out
547 bucket of each index it goes through, the first time it needs it.
548- Commit and land: proportional to the changed paths times the tree depth.
549- `log -- path`: proportional to the changes that touched the path, plus one
550 filter check per changeset walked.
551- Ancestry and merge base: logarithmic for first-parent ancestors, using skip
552 pointers; otherwise proportional to the changesets above the generation
553 looked for. Derived data is computed once, the first time.
554- Blame: one line diff per version of the file not blamed before.
555- A lazy sparse clone: proportional to the objects under the requested paths.
556- Store size: at most twice a garbage-collected git repository of the same
557 history.