ProjekinAja. Software Engineering Stage 2 · Craft Lesson 2.2
● Stage 2 · Lesson 2.2

Git, Actually: The Object Model

Blobs, trees, commits, and refs — git as a content-addressed DAG with movable pointers, not a save button with extra steps.

⏱ ~18 min read 🧠 Mental model 🛠 TraceLab v1 setup

🎯 By the end you'll understand

How git stores every piece of data as a content-addressed object — blob, tree, commit, or tag — and how branches, HEAD, and remote refs are nothing but text files pointing at SHA-1 hashes. You'll see that every git command is pointer surgery on an immutable directed acyclic graph, and you'll finally understand why detached HEAD, mysterious merge states, and "lost" commits happen and how to recover from all of them. The DAG is visible; nothing git does is scary after this.

KEY INSIGHTGit is a content-addressed database, not a diff engine

Every file you've ever committed is stored by a hash of its content. A branch is a 41-byte file containing one hash. This is the whole system.

Most engineers learn git as a spell-book: git add, git commit, git push, and then an increasingly panicked sequence when things go sideways. That works until a merge conflict tangles, a rebase goes wrong, or — worst of all — you end up in "detached HEAD state" and can't remember what the message was trying to tell you. When you hit those states, the incantations fail. The model saves you.

🔑 The one thing

Git's .git/objects/ directory is a simple key-value store where the key is the SHA-1 hash of the value. Every version of every file you have ever committed is an immutable object in that store. A branch is just a pointer to one commit object — a text file containing 40 hex characters. When you make a new commit, git writes one new object and moves the pointer. When you merge or rebase, it rearranges pointers. Nothing ever mutates. Once you can see the graph, there is no git mystery left.

CORE CONCEPTThe four object types: blob, tree, commit, tag

Open any git repository and look inside .git/objects/. You'll find a flat content-addressed store of exactly four types of object. That's the entire storage layer:

1

Blob — a file's raw content

A blob stores the raw bytes of one file version. No filename, no path — just content. Two files with identical content share one blob. You can inspect any blob with git cat-file -p <hash>. When you stage a file (git add), git immediately writes a blob for it and hands you back its hash.

2

Tree — a directory snapshot

A tree maps filenames (and permissions) to blob hashes and sub-tree hashes. It is a snapshot of one directory at one moment — not a diff. Two identical directories produce the same tree hash. Trees point to blobs and other trees, never backward.

3

Commit — a labeled snapshot in time

A commit points to exactly one root tree (the entire project snapshot), plus zero or more parent commit hashes, plus metadata: author, timestamp, and your message. The parent link is what creates history. A merge commit has two parents. The initial commit has none. Commits are immutable — changing anything changes the hash, producing a different object.

4

Tag (annotated) — a named, signed commit pointer

An annotated tag is an object that points to a commit (or any other object), with a message and optional GPG signature. Lightweight tags are just refs, not objects. For release versioning you always want annotated tags — they're immutable, signable, and part of the object graph.

commit tree: <hash> parent: <hash> tree / tracelab.py → <blob> src/ → <tree> blob raw bytes of tracelab.py tree src/ __init__.py → <blob> core.py → <blob> blob blob commit object tree / blob
A single commit points to a root tree which points (recursively) to blobs for file contents. Nothing mutates — identical content produces the same hash across commits.

The content-addressing is the clever part. Git computes SHA-1("blob " + len + "\0" + content) and uses the first two hex digits as the subdirectory, the remaining 38 as the filename. Because the key is a hash of the value, a corrupted object is immediately detected (hash mismatch), and deduplication is automatic. The same file version in a thousand commits costs one blob.

💡 Try it right now

In any git repo: git cat-file -t HEAD (type: "commit"), git cat-file -p HEAD (the commit's raw contents — tree hash, parent hash, author, message). Then git cat-file -p HEAD^{tree} to see the root tree. You're reading the object store directly, bypassing every porcelain command. This is the real git.

HOW IT WORKSHistory as a directed acyclic graph

Parent pointers make commits form a directed acyclic graph (DAG). Each commit points backward to its parent(s); the graph never has cycles, because a commit's hash encodes its parent's hash — you can't make a commit that is its own ancestor without breaking the hash. This is not a design nicety; it's a cryptographic guarantee of history integrity.

The DAG makes several things obvious that were previously magic:

C1 init C2 add csv C3 fix log C4 add CLI C5 merge main feature main → C5 feature → C5 HEAD → main
Commits C3 and C4 both point back to C2 (diverge). C5 is a merge commit with two parents. Branches (main, feature) and HEAD are movable pointers — text files containing a hash. The commits themselves never change.

One consequence worth internalizing: git never loses your work by default. When you delete a branch, git removes the pointer file; the commits remain in the object store, protected by the reflog for approximately 90 days (gc.reflogExpire default), and unreachable objects survive at least 14 more days after that before git gc prunes them (gc.pruneExpire default). That "lost" commit is almost always still there. git reflog — the local append-only log of where HEAD has been — is your recovery key.

DEFINITIONRefs, branches, HEAD — the movable pointers

The entire refs system is files in .git/refs/ and .git/HEAD. Nothing more. Inspect them directly:

exploring .git refs by hand
# A branch is literally a 41-byte file: 40 hex chars + newline
$ cat .git/refs/heads/main
a3f2c8d9e1b04f7c2e3a8d5b6c9f0e2a1d4b7c8e

# HEAD normally contains a ref name (symbolic ref)
$ cat .git/HEAD
ref: refs/heads/main

# When HEAD points at a hash directly → detached HEAD state
$ git checkout a3f2c8d
$ cat .git/HEAD
a3f2c8d9e1b04f7c2e3a8d5b6c9f0e2a1d4b7c8e

# Remote tracking refs live in refs/remotes/
$ cat .git/refs/remotes/origin/main
9f1a3b5c7e2d4f8a0b6c3e5d7a9f1b3c5e7d9a1b

When you run git commit, exactly three things happen:

1

Write the commit object

git creates a new commit object in .git/objects/ pointing to the staged tree and the current HEAD commit as parent. The hash is deterministic from the content — same tree, same parent, same author, same timestamp → same hash.

2

Advance the branch pointer

git overwrites .git/refs/heads/<current-branch> with the new commit's hash. 41 bytes written to disk. That is the entire branch update.

3

HEAD follows the branch

Because HEAD contains ref: refs/heads/main (a symbolic ref), it implicitly points at wherever main now points. HEAD didn't move; the branch it names moved under it.

📖 Tags vs branches

A branch pointer moves with every new commit. An annotated tag is a frozen pointer — once created, it should never move. Lightweight tags (git tag v1.0) are just a ref file, no object. Annotated tags (git tag -a v1.0 -m "...") are proper objects with a message, tagger, and timestamp — they survive git gc and can be GPG-signed. Use annotated tags for releases.

SEE ITGit object graph builder — live

This widget builds the git object graph in real time as you perform operations. Click the operations in order and watch blobs, trees, and commits appear with their content-derived hashes. The hash display is a short fingerprint (not real SHA-1, but same semantics: changes to content change the hash). Use the "Detached HEAD" mode to see exactly what that state means.

⚙ Interactive · Git object graph builder

Perform operations below; the object graph and refs render live. Each object's hash is derived from its content — change anything and the hash changes.

HEAD
—
Current branch
—
Staged (index)
empty
Last object written
—

Start by staging a file.

Notice what happens to the hash of tracelab.py's blob when you edit the file: an entirely new blob object appears, with a different hash. The old blob still exists — git stores every version. And notice that after merging, both branch refs point at the same commit while HEAD (in normal mode) points to the branch, not the commit directly.

CORE CONCEPTDetached HEAD — the state everyone fears, explained in one paragraph

When HEAD contains a ref name (ref: refs/heads/main), it is attached: new commits advance the branch, and HEAD follows automatically. When HEAD contains a raw hash, it is detached: new commits write objects and update HEAD, but no branch pointer moves. The commits are not "lost" — they exist in the object store. The problem is that nothing points to them except HEAD, and when you git checkout elsewhere, HEAD moves away and those commits become unreachable by any ref. They'll survive in the reflog for ~90 days (default gc.reflogExpire) but won't show up in git log.

The fix is trivial once you understand the model:

recovering from detached HEAD
# you did: git checkout a3f2c8d  (or: git checkout v1.2, or: git rebase left you here)
# you made some commits. now you're here:
$ cat .git/HEAD
d4e9f1a2b3c8d5e0f7a2b6c4d9e0f3a7b8c2d5e1

# Option 1: give those commits a branch right now (before checking out anything else)
$ git checkout -b rescue-branch
# HEAD is now "ref: refs/heads/rescue-branch" — commits are safe forever

# Option 2: you already left and the hash slipped your mind
$ git reflog          # shows every place HEAD has been, most recent first
HEAD@{0}: checkout: moving from d4e9f1a to main
HEAD@{1}: commit: my important work   # ← there it is
$ git checkout -b rescue-branch HEAD@{1}
# nothing is lost
🔑 When does detached HEAD happen?

Four common triggers: git checkout <tag>, git checkout <commit-hash>, some rebase states mid-operation, and git bisect. The message is a warning, not an error. You're free to look around, build, test. Just don't commit new work you care about without creating a branch first.

IN PRACTICEEvery command is pointer surgery on the DAG

Once the object model is visible, every git command becomes transparent. Here's the translation table for the ones that historically confused people:

CommandWhat actually happens in the DAGWhat doesn't happen
git branch featWrite .git/refs/heads/feat containing current HEAD hash. One file write.No objects copied, created, or moved.
git checkout mainRead .git/refs/heads/main, update working tree to match that commit's tree, set HEAD = ref: refs/heads/main.No objects created.
git merge featWalk back both parent chains to find common ancestor; if fast-forwardable, just advance the pointer. Otherwise, 3-way merge the trees, write new objects, write a merge commit with 2 parents.The original commits don't change.
git rebase mainFor each commit on the current branch since divergence, create a new commit object with the same diff but a new parent. Advance the current branch to the last new commit.Old commits aren't deleted — just dereferenced (until GC).
git reset --hard HEAD~1Move the current branch pointer back one commit. Update working tree.The commit you "reset away" still exists in the object store. git reflog can find it.
git stashWrite your working-tree changes as a commit object (no branch pointer); store the hash in .git/refs/stash.Not a separate "stash system" — it's just a dangling commit.

The practical upshot: you can recover from almost anything that happens in git, because objects are immutable and the reflog records every HEAD movement. The only irrecoverable operations are things that truly destroy data: a git gc that collects unreachable objects, or overwriting your working tree before staging (the file was never an object to begin with).

💡 The four tools that save you every time

git reflog — the append-only HEAD history; your recovery net.
git cat-file -p <hash> — read any object directly; diagnose anything.
git log --oneline --graph --all — visualize the full DAG including all branches.
git stash list — you have more stash commits than you remember.

TRACELABTraceLab v1 begins: a real git history

TraceLab v0 was a single script with no history, no packaging, and no way to tell "which version logged these results." Every sin in the debt table from Lesson 1.1 was partly enabled by that. Stage 2's milestone — TraceLab v1 — fixes the structure: a proper package layout, typed interfaces, and a clean git history that a future collaborator (human or AI) can actually read.

The first commit of that history starts here. Here is the target v1 repository layout and the first three commits you should create:

TraceLab v1 initial structuretarget layout
tracelab/
├── .gitignore           # __pycache__, .venv, *.egg-info, runs.csv
├── pyproject.toml       # build system + deps (Lesson 2.5)
├── README.md
└── src/
    └── tracelab/
        ├── __init__.py  # exports the public API
        ├── cli.py       # tracelab init / log / compare commands
        └── core.py      # typed run model + CSV writer (properly)
building a clean first historybash
# Every one of these should be a real commit with a real message.
# The commit message is the story; the diff is the evidence.

$ git init tracelab && cd tracelab
$ git commit --allow-empty -m "chore: initial empty commit"

# Add the layout, then commit cleanly
$ mkdir -p src/tracelab
$ touch src/tracelab/__init__.py src/tracelab/core.py src/tracelab/cli.py
$ touch pyproject.toml README.md .gitignore
$ git add .
$ git commit -m "chore: scaffold src layout per PEP 518"

# Now implement core.py with real types (Lesson 2.4 adds tests)
$ git add src/tracelab/core.py
$ git commit -m "feat: typed Run dataclass + csv_writer"

Why the empty first commit? Git's DAG has a root — a commit with no parents. A deliberately empty root commit lets you rebase the entire branch history later without hitting "root commit" edge cases. It's the kind of thing that costs one second and saves an hour six months from now. That's the Stage 2 theme: the decisions that survive contact with time.

Later in Stage 2, you'll simulate a "disaster" — a bad rebase, a force-push gone wrong — and recover it from the reflog. The point is not that disasters are fun. It's that a model of what git actually does turns a crisis into a three-minute recovery.

💡 Commit messages as design documents

The canonical form is: a 50-char imperative subject (feat: add typed Run dataclass), a blank line, then a body explaining why, not what. The diff tells you what; the message tells future-you why this seemed like the right choice at the time. Write for the engineer who inherits this at 2am after a production incident — that engineer will often be you.

WEAKNESSWhere this bites

⚠ Force-pushing shared history

Rebase rewrites commits — it creates new objects with new hashes. If you've already pushed those commits to a shared branch and someone else has built on them, a git push --force replaces their starting point with your rewritten history. Their commits now dangle with no common ancestor they can reach without surgery. The rule: never rebase (or amend) commits that exist on a shared remote branch. Rebase is for cleaning up local work before sharing it; merge is the safe surgery for shared history. git push --force-with-lease is a weaker safety: it refuses if the remote has new commits you haven't fetched, catching the most common mistake.

⚠ Treating the index (staging area) as a formality

The index is not a waiting room before a commit; it's a separate snapshot of the tree you're building. git diff shows working-tree-vs-index. git diff --staged shows index-vs-HEAD. When you edit a file, stage it, then edit it again and commit — the committed version is the staged one, not your latest edit. Engineers who don't model the index as a distinct layer are the engineers who discover this at the worst possible moment.

⚠ Conflating git with GitHub (or any host)

Git is a local, offline, distributed system. GitHub, GitLab, and Bitbucket are hosting services that add pull requests, code review UIs, and access control on top. git push is not "saving to the cloud" — it's copying local refs to a remote. You can lose commits on a remote the same way you can lose them locally (though the remote's reflog persists server-side). "The repo is on GitHub so it's backed up" is true only if you've pushed. The object model doesn't care where you run it.

KEY INSIGHTHow this connects

  • Data Representation (1.5) — hashing, content-addressing, and why identical bytes produce identical hashes are all applications of what that lesson covers about how computers store information.
  • TraceLab v0 (1.9) — the "no history" debt in the v0 debt table is exactly what this lesson repays: once you know the object model, you know what a meaningful git history actually means and how to build one.
  • 2.3 · Branching, Merging, and Unscrewing Yourself → the next lesson takes everything here and applies it to the workflows that actually break in teams: long-lived branches, conflict resolution, and rebase vs merge as an engineering tradeoff.

The DAG insight extends past git. Merkle trees (content-addressed hash trees) underpin IPFS, Bitcoin's blockchain, and container image layers. The Unix inode-based file system is a similar pointer graph. Once you see "pointer to content hash" as a pattern, you start seeing it everywhere — and you understand why those systems share git's nice properties (tamper-evidence, efficient deduplication, offline-first operation).

GLOSSARYKey terms introduced

Blob
A git object storing the raw bytes of one file version, keyed by SHA-1 of the content. No filename or path — those live in the tree.
Tree
A git object mapping filenames and permissions to blob hashes and sub-tree hashes. A snapshot of one directory.
Commit
A git object pointing to a root tree, zero or more parent commits, and metadata (author, timestamp, message). Immutable — any change produces a new hash.
Content-addressed storage
A storage model where each value is stored at the key derived from hashing its content. Identical content always has the same key; changed content always has a different key.
DAG (directed acyclic graph)
A graph where edges have direction and there are no cycles. Git's commit history is a DAG: each commit points backward to its parents, and no commit can be its own ancestor.
Ref
A named pointer to a git object (usually a commit). Branches, tags, and HEAD are all refs. A branch ref is a text file containing one hash; it moves with every new commit.
Detached HEAD
The state where HEAD contains a raw commit hash instead of a branch ref name. New commits write objects and update HEAD, but no branch pointer advances — the commits become unreachable by any ref when you check out something else.
Reflog
The local, append-only log of every place HEAD has pointed. Your primary recovery tool — finds commits that appear "lost" after resets, rebases, or checkouts.

ACTIVE RECALLCheck your understanding

Answer in your own words first, then reveal.

1You run git commit. Describe precisely what happens in .git/ — which files are written or changed?›

Three things: (1) A new commit object is written to .git/objects/ — its hash is derived from the content (tree pointer, parent hash, author, timestamp, message). (2) The current branch ref (.git/refs/heads/<branch>) is overwritten with the new commit's hash. (3) HEAD, being a symbolic ref to the branch, now implicitly points to the new commit. The index is unchanged; the working tree is unchanged.

2What is "detached HEAD state," and why is it only dangerous if you make commits in it without creating a branch?›

Detached HEAD means HEAD contains a raw commit hash instead of a branch name. New commits write objects and update HEAD's hash, but no branch pointer moves. When you check out a branch later, HEAD moves to that branch's hash, and your detached commits are now only reachable from the reflog — no branch points to them. They're not deleted (the reflog retains them for ~90 days by default), but they won't appear in git log. Fix: create a branch (git checkout -b name) before leaving the detached state.

3You have a 10,000-commit project and two files that happen to have identical content. How many blob objects does git store for those files?›

One blob. Content-addressing means the key is the hash of the content. Identical content → identical hash → same key → same object. Every tree that references either file just stores the same hash. This is automatic, transparent deduplication — no configuration needed.

4What does git rebase main actually do to the commit objects on your feature branch?›

Rebase does not move the existing commit objects. It creates new commit objects — one per commit on the feature branch since divergence — each with the same diff as the original but a new parent (the tip of main). The old commit objects remain in the object store, dereferenced. The feature branch pointer is then updated to point to the last new commit. This is why rebasing published commits causes problems: other people's commits still reference the old (now dereferenced) objects as parents.

Next: branching strategies, merge conflicts, and rebase vs merge — the team-scale tradeoffs →