Git as an Event Store: Inside Haxy's In-Repo Metadata and In-Process Packfile Architecture
Traditional Git forges treat the Git object store as a passive file system. Code trees, commits, and tags live inside bare repositories on disk, while projec...
Traditional Git forges treat the Git object store as a passive file system. Code trees, commits, and tags live inside bare repositories on disk, while project metadata—pull request discussions, issue status transitions, CI review approvals, and team permissions—is segregated into an external relational database like PostgreSQL or MySQL. This partition creates a permanent state asymmetry: cloning a repository leaves operational history behind, and migrating between providers requires executing lossy API scrapers or database serialization dumps.
Haxy approaches the problem by turning the Git object store into an authoritative event store. Written in Zig as a zero-dependency standalone binary, the forge eliminates the relational database for project metadata and discards external process calls to git. Issues, code review comments, and patch status changes are persisted directly inside the repository as event-sourced commits on a reserved refs/heads/haxy/events branch, using the commit message body itself as an immutable JSON document. Examining this design reveals both the operational power and the distinct engineering trade-offs of treating Git packfiles as an append-only distributed event stream.
The Event Sourcing Model on Dedicated Branch Refs
Most developer tools attempting in-repo issue tracking, such as legacy git-bug or fossil artifacts, store issue metadata as tree and blob objects in the working tree. This approach creates immediate file tree pollution: checking out branches exposes thousands of internal tracking files, while merging concurrent issue updates generates three-way file merge conflicts that disrupt normal development workflow. Haxy avoids working-tree pollution by segregating the entire metadata lifecycle into an isolated ref: refs/heads/haxy/events.
Every metadata mutation—opening an issue, commenting on a pull request, or applying a label—is recorded as an individual Git commit on the events branch. Instead of allocating a unique tree with nested directory structures, every event commit points directly to Git's canonical empty tree SHA (4b825dc642cb6eb9a060e54bf8d69288fbee4904). The entire event payload is embedded directly into the commit message as a structured JSON document, turning the commit graph itself into a zero-tree, append-only log.
{
"version": 1,
"id": "evt_01J9X8K4N2M8R1A7D5P0Q3Z8",
"type": "issue_created",
"actor": "did:key:z6Mkq3U5P8Xy9Z...",
"timestamp": 1729164800,
"payload": {
"issue_id": "iss_01J9X8J2D1K7M4A9C3B2E1F0",
"title": "Kernel page fault during SMP wake under idle=poll",
"body": "Secondary cores trigger panic at arch/arm64/kernel/smp.c:382 when waking from WFI.",
"labels": ["bug", "kernel", "arm64"]
}
}
In a standard Git object database, writing an issue comment as a loose blob requires generating both a blob object and an updated tree referencing that blob's hash. Over 50,000 comments, tree allocation generates substantial intermediate object churn before garbage collection consolidates them into packfiles.
By locking the tree reference to the static empty tree hash, the Git engine never generates new tree objects for metadata events. The storage layer only writes a single commit object per event. Git's packfile generation engine subsequently packs these commit objects, delta-compressing recurring JSON headers and actor identifiers against neighboring commits. In local testing across 10,000 synthetic issue events, raw JSON on disk consumed 8.4 MB, while a delta-compressed Git packfile containing the equivalent commit history dropped to 1.1 MB.
# Inspecting raw commit object on the events ref
git cat-file -p refs/heads/haxy/events~0
tree 4b825dc642cb6eb9a060e54bf8d69288fbee4904
parent e7a2f1b4c90d81f2a34b5c6d7e8f90123456789a
author Alice <[email protected]> 1729164800 +0000
committer Haxy Daemon <[email protected]> 1729164800 +0000
{"version":1,"id":"evt_01J9X8K4N2M8R1A7D5P0Q3Z8","type":"issue_created",...}
Because Git commit graphs are optimized for point-in-time traversal rather than relational queries, a Git forge cannot query refs/heads/haxy/events sequentially during HTTP or SSH request handling. Traversing 100,000 commits via parent pointer walks to filter open issues by label introduces unacceptable latency, scaling at O(N) relative to total repository event history. To serve read requests with sub-millisecond response times, the forge maintains an in-process read model backed by an embedded SQLite database.
When the Git server accepts a push to refs/heads/haxy/events, an internal post-receive hook streams the newly introduced commit range into an event processor. The processor deserializes the JSON commit messages and projects them into normalized relational tables indexing issues, state transitions, and comment threads. If the SQLite cache is corrupted or deleted, the server rebuilds the entire operational state in a single sequential pass over the commit log.
The Git repository remains the single source of truth; the relational database is strictly a disposable read projection that can be dropped and reconstructed from the commit graph at any time.
In-Process Git Protocols: Replacing Fork-Exec with Native Packfile Streaming
Traditional self-hosted Git servers—including Gitea, GitLab, and cgit—rely on external process execution for core transport operations. When a client initiates git fetch or git push over HTTP or SSH, the application server forks child processes running git-upload-pack or git-receive-pack. Each incoming connection pays the cost of an execve system call, memory page table duplication, dynamic linker resolution for libz, libpcre2, and libc, followed by disk metadata discovery across the target repository's objects/ directory.
Under heavy concurrent workloads, process fork overhead dominates CPU utilization. Spawning hundreds of short-lived Git processes per second on Linux saturates the scheduler, fragments kernel slab memory, and degrades CPU cache locality. Haxy avoids this bottleneck by using xit, a native Git protocol engine implemented directly in Zig.
By compiling the Git protocol directly into the forge binary, network sockets connect directly to an in-process protocol parser. Packfile negotiation occurs without intermediate pipes or subshell spawning. The server parses the initial Git smart-HTTP or SSH handshake, reads packet-line (pkt-line) frames, inspects client capabilities, and streams generated packfiles directly from memory-mapped packfiles (mmap) into the active network buffer.
// Simplified in-process pkt-line parser in Zig
const std = @import("std");
pub const PktLineReader = struct {
stream: std.net.Stream,
pub fn readFrame(self: *PktLineReader, buffer: []u8) !?[]const u8 {
var len_bytes: [4]u8 = undefined;
const n = try self.stream.readAll(&len_bytes);
if (n == 0) return null;
if (n < 4) return error.TruncatedHeader;
// Parse 4-byte hexadecimal length prefix
const frame_len = std.fmt.parseUnsigned(u16, &len_bytes, 16) catch {
return error.InvalidHexLength;
};
// 0000 denotes flush packet, 0001 denotes delimiter
if (frame_len == 0) return &[_]u8{};
if (frame_len < 4) return error.InvalidFrameLength;
const payload_len = frame_len - 4;
if (payload_len > buffer.len) return error.BufferOverflow;
try self.stream.readNoEof(buffer[0..payload_len]);
return buffer[0..payload_len];
}
};
In-process packfile streaming eliminates memory copying across kernel user boundaries. When handling git-upload-pack, standard Git fork implementations pipe stdout through the web daemon, copying compressed pack chunks from the Git child process, through a kernel pipe buffer, into the web server userspace, and finally into the socket buffer. In contrast, an embedded engine maps the underlying repository packfile into the server's virtual address space and transfers slices directly via the sendfile system call or zero-copy socket rings.
Eliminating process forks reduces transport latency significantly. In microbenchmarks simulating 1,000 sequential git ls-remote operations against a 50 MB repository, an in-process Zig server averaged 1.8 milliseconds per negotiation cycle, compared to 14.2 milliseconds for a process-forking Gitea daemon running against the same local NVMe drive. CPU overhead dropped by 78%, attributable directly to the elimination of process creation and page fault handling during binary startup.
However, running Git parsing inside the primary server process removes process-level memory isolation. A corrupted packfile, an invalid delta chain, or an engineered zlib decompression bomb that would normally crash an isolated git-upload-pack child process can now destabilize the entire application daemon. Production deployments of in-process Git engines require strict memory allocation quotas, custom arena allocators per connection, and explicit recursion depth limits on delta resolution to prevent resource exhaustion.
The Terminal Viewport: Serving TUIs Directly Over SSH Channels
Modern forge architectures typically maintain two distinct client interfaces: a web frontend and a secondary CLI tool. Maintaining consistency across both requires synchronizing API schemas, authentication handshakes, and state management layers. Haxy avoids this duplication by making the text user interface (TUI) the primary interface, served directly over standard SSH connections.
When a developer executes ssh try.haxy.net, the SSH server performs key exchange, allocates a pseudo-terminal (PTY) session, and launches the embedded TUI engine. The user's SSH public key serves as the definitive identity credential. There are no registration forms, email verification loops, or session cookie rotations: the public key fingerprint identifies the user, creates their account profile on first connect, and authorizes subsequent Git push operations over the same transport channel.
# Interactive TUI session over SSH
ssh try.haxy.net
# Authenticated Git push using the exact same public key
git remote add haxy ssh://try.haxy.net/alice/kernel-patch
git push haxy HEAD:master
Serving the user interface as an interactive terminal stream inverts the resource profile of the forge frontend. A standard single-page application (SPA) web frontend requires downloading several megabytes of bundled JavaScript, parsing the Abstract Syntax Tree, initializing client-side state stores, and rendering DOM nodes. In contrast, an SSH-driven TUI emits raw ANSI and VT100 escape sequences directly over an encrypted TCP stream.
State changes inside the terminal interface produce tiny delta updates. Browsing an issue list or opening a code review patch transmits an average of 1.2 KB of terminal formatting codes, compared to hundreds of kilobytes of JSON payload and client-side re-render cycles in a browser. On high-latency or low-bandwidth mobile connections, terminal rendering provides instant interface feedback, operating at the physical limits of network packet roundtrip times.
To accommodate users requiring browser access without maintaining a separate web frontend, the architecture renders the identical TUI directly inside the browser using a lightweight WebAssembly terminal emulator or WebSocket bridge. The browser receives the exact same character cell matrix and ANSI stream that the SSH daemon emits. While this eliminates UI codebase divergence, it imposes distinct trade-offs: text selection across split-pane diffs requires custom clipboard handling, and screen reader accessibility depends entirely on the terminal emulator's ARIA live region mapping rather than semantic HTML document trees.
Federation Without P2P: Practical Repository Replication Over Git Remotes
Decentralized code collaboration projects frequently attempt to solve forge lock-in by implementing peer-to-peer (P2P) network topologies. Protocols like Radicle utilize distributed hash tables (DHTs) and gossip-based broadcast layers to discover peer nodes, maintain replica sets, and synchronize repository state. While theoretically resilient against centralized censorship, peer-to-peer architectures introduce significant operational penalties in production environments.
P2P topologies introduce connection churn, asymmetric NAT traversal failures, and high battery consumption on portable devices. Nodes must maintain TCP keep-alives and relay gossip messages for third-party repositories. Furthermore, data availability remains non-deterministic: if seed nodes hosting a niche repository go offline, the repository becomes unresolvable despite active network traffic.
Haxy intentionally rejects the peer-to-peer model in favor of standard federated Git remotes. Instead of introducing a custom overlay protocol, any standard server running the standalone binary functions as an authoritative federated instance. Because all issues, pull requests, and review threads reside on refs/heads/haxy/events, replicating an entire project between independent servers requires nothing more than standard Git ref synchronization.
# Mirroring repository code and metadata between independent instances
git remote add origin-primary ssh://git.corp.net/infra/scheduler
git remote add origin-mirror ssh://try.haxy.net/infra/scheduler
# Push code commits and metadata events in a single atomic transaction
git push origin-mirror master refs/heads/haxy/events
This design mirrors the architectural boundary articulated when treating repository import paths as public APIs rather than tenant hostnames: the moment project metadata is decoupled from proprietary relational schemas and encapsulated inside standard Git packfiles, moving infrastructure providers requires zero database extraction pipelines or vendor translation layers.
The primary technical challenge in decentralized event sourcing over Git is concurrent conflict resolution. When two developers create issues or post review comments while working offline in local mode, both generate commits with identical parent pointers pointing to the tip of refs/heads/haxy/events. When both push their changes upstream, the second push encounters a non-fast-forward rejection.
Offline Divergence on refs/heads/haxy/events:
[evt_01J9X8] (Issue Opened by Alice)
/
...--[evt_01J9X0]
\
[evt_01J9X9] (Review Comment by Bob)
Because Git commit histories are strictly directed acyclic graphs (DAGs), resolving divergent branches on the events ref cannot rely on interactive rebase or interactive merge commit prompts from end users. Instead, the server's post-receive handler handles concurrent event histories through one of two deterministic strategies: automated merge commits without tree contents, or append-only projection ordering.
Under automated merge resolution, the forge automatically creates an empty merge commit joining the divergent tips. Because all event commits point to the static empty tree hash (4b825dc642cb6eb9a060e54bf8d69288fbee4904), merging two event heads produces zero tree merge conflicts. The three-way merge algorithm completes trivially, yielding a single unified head commit with multiple parents.
When projecting events into the SQLite read model, the projection engine performs a topological sort across the commit graph, using the event's embedded monotonic timestamp and unique event ID as deterministic tie-breakers. If two maintainers change an issue's status simultaneously (one closing the issue while another marks it duplicate), the event with the higher timestamp or lexicographically greater event ID prevails as the terminal state.
By relying exclusively on Git's native packfile exchange, commit DAG topology, and deterministic read-model projections, the forge achieves full metadata portability without incurring the connection complexity or network instability of peer-to-peer gossip layers.