Read the object graph, index and HEAD
Why you care
Every git command you'll ever run manipulates one of three things — the working tree, the index, or a ref — and conflating them is why "I committed but nothing changed" and "my fix vanished" happen to developers who've used git daily for years. Interviewers ask "what's the difference between git add and git commit" or "what is HEAD" not to test trivia, but because the answer predicts whether you can read git status output under pressure instead of guessing. This card is the one everything else in the chapter depends on: branching strategy, rebase, conflict recovery and bisect are all just different things you do to this same graph.
Explain like I'm 5
Git's object store is a library that catalogs every unique page by its exact fingerprint, not by title. Two students handing in byte-identical essays get filed as literally one page, referenced twice — the library never keeps a second copy of the same content. HEAD and branch names are sticky notes pointing at a particular filed page (a commit); move the sticky note and you're looking at a different page, but the page itself doesn't change, and it doesn't vanish just because no note points at it anymore — it just gets harder to find.
Core concept
Git's history is a directed graph of four object types, all addressed by the hash of their content:
- A blob stores one file's raw bytes, nothing else — not even a filename.
- A tree stores a snapshot of a directory: names, modes, and the hashes of the blobs/trees inside it.
- A commit stores a tree hash (the whole snapshot), one or more parent commit hashes, and author/message metadata.
- A tag object (from
git tag -a) points at a commit and adds its own message; a lightweight tag is just a ref, no object of its own.
Refs are separate from objects: a branch is a movable pointer (a file holding a commit hash) that advances every time you commit on it. HEAD is almost always a symbolic ref, one level of indirection: it points at a branch, which points at a commit. Moving HEAD by committing normally moves the branch too.
Three things can differ from each other at any moment, and git status exists to tell you which:
- the working tree — files on disk right now;
- the index (a.k.a. the staging area) — what's staged to go into the next commit;
- HEAD — the last commit already made.
git diff compares working tree to index; git diff --cached compares index to HEAD; git status summarizes both at once.
Detached HEAD happens when you check out a specific commit hash (or tag) instead of a branch name: HEAD then points straight at a commit, with no branch in between. It's completely safe to look around in — but any commit you make there has no branch pointing at it, so it's invisible to git log on every existing branch and eligible for eventual garbage collection once you leave.
Decision rule: before you do anything that rewrites history or checks out something unusual, run git status first. If it doesn't say what you expect (extra staged files, "detached HEAD", unmerged paths), stop and figure out why before committing or resetting anything.
Under the hood
Git addresses every object by the SHA-1 hash of its type-tagged, zlib-compressed content (conceptually "blob <size>\0<content>" for a blob), which is why identical content anywhere in history is stored exactly once. New objects start as loose files under .git/objects/<first-two-hex>/<remaining-38-hex>; git gc (and every push/fetch) periodically rolls many loose objects into a single delta-compressed packfile, which is why a fresh clone's .git can be far smaller than the sum of every version of every file ever committed. Refs are plain text files under .git/refs/heads/<name> holding a 40-hex-char hash, and HEAD is usually the one-line file ref: refs/heads/<name> — that line is the symbolic-ref indirection. Freshness note: newer Git versions support SHA-256 object hashing as an opt-in repository format, but SHA-1 remains the default you'll meet almost everywhere in 2026.
Minimal example Content addressing: same bytes, same blob
import subprocess, os
os.makedirs("repo")
os.chdir("repo")
def git(*args):
return subprocess.run(["git", *args], capture_output=True, text=True, check=True).stdout.strip()
git("init", "-q", "-b", "main")
os.makedirs("dir_a")
os.makedirs("dir_b")
with open("dir_a/config.json", "w") as f:
f.write('{"retries": 3}\n')
with open("dir_b/config.json", "w") as f:
f.write('{"retries": 3}\n')
hash_a = git("hash-object", "-w", "dir_a/config.json")
hash_b = git("hash-object", "-w", "dir_b/config.json")
print("same content -> same blob hash:", hash_a == hash_b)
print("hash length:", len(hash_a))
print("object type:", git("cat-file", "-t", hash_a))same content -> same blob hash: True
hash length: 40
object type: blobIn production Working tree, index and HEAD after a staged-only edit, then a detached checkout
import subprocess, os
os.makedirs("repo")
os.chdir("repo")
def git(*args, check=True):
return subprocess.run(["git", *args], capture_output=True, text=True, check=check)
ident = ["-c", "user.name=CI Bot", "-c", "user.email=ci@example.com"]
git("init", "-q", "-b", "main")
with open("etl_config.py", "w") as f:
f.write("BATCH_SIZE = 5000\n")
git("add", "etl_config.py")
git(*ident, "commit", "-q", "-m", "add batch size config")
# edit the working tree, then stage it, but do not commit
with open("etl_config.py", "w") as f:
f.write("BATCH_SIZE = 10000\n")
git("add", "etl_config.py")
status = git("status", "--short").stdout.strip()
staged = git("diff", "--cached", "--stat").stdout.strip()
unstaged = git("diff", "--stat").stdout.strip()
print("status:", status)
print("staged change present:", bool(staged))
print("unstaged change present:", bool(unstaged))
head_ref = git("symbolic-ref", "HEAD").stdout.strip()
print("HEAD points at:", head_ref)
commit_hash = git("rev-parse", "HEAD").stdout.strip()
git(*ident, "checkout", "-q", commit_hash)
detached = git("symbolic-ref", "-q", "HEAD", check=False)
print("detached HEAD (no symbolic ref):", detached.returncode != 0)status: M etl_config.py
staged change present: True
unstaged change present: False
HEAD points at: refs/heads/main
detached HEAD (no symbolic ref): TrueSee it happen Working tree to commit, then HEAD detaches
- Editing etl_config.py only changes the working tree; the index and the last commit still describe the old content.
- `git add` hashes the file into a blob and records it in the index.
- `git commit` writes a tree over the index and a commit over that tree, then the branch ref moves to point at it.
- HEAD is a symbolic ref: it points at the branch, which points at the commit — one extra hop of indirection.
- `git checkout <hash>` instead points HEAD straight at a commit, bypassing the branch entirely: detached HEAD.
- Any commit made here has no branch pointing at it, so it's invisible to `git log` on every existing branch the moment you check out something else.
In your world
The situation
Your ETL repo's Jenkins job stamps every Postgres load with git rev-parse HEAD for audit, and a teammate debugging a discrepancy checks out last month's commit directly: git checkout a1b2c3d.
What actually breaks
They find the bug and fix it right there, without noticing the "You are in 'detached HEAD' state" warning git status already printed. Jenkins builds main, not this commit, so the fix never ships. A week later the commit is unreachable from any branch, and git log on main shows no trace it ever existed.
What you'd do on Monday
Before making any change while not on a named branch, check first, and land on a branch immediately if you're going to keep the work:
git status # look for "HEAD detached at <hash>"
git symbolic-ref -q HEAD || echo "not on a branch"
git checkout -b fix/audit-mismatch a1b2c3d # now the commit has a homeImagine you work at GitLab
The numbers
Illustrative: a monorepo the size of GitLab's own gitlab-org/gitlab is on the order of 1.2M commits; even if each commit touches only ~3 files, that's roughly 1.2M × (1 commit object + ~3-5 tree objects + ~2 blob objects) ≈ 8-10M objects before any packing. Content addressing means a config file that's byte-identical across 50,000 of those commits is stored as exactly one blob, not 50,000 copies.
What the Scenario-A answer does here
The Scenario A habit of running git status/git log on a clone still works, but "just git clone it, same as always" does not scale the same way: cloning a repo this size with no flags pulls every object in every version of every file ever committed — minutes, not seconds, and gigabytes of .git that are almost entirely history nobody asked for today.
What flips at this scale
At this scale the object graph stops being something you fetch in full. Shallow clones (--depth), partial clone (--filter=blob:none) and sparse checkout become the default for CI runners and new laptops, and a dedicated git service (GitLab runs Gitaly in front of its repositories) mediates access instead of every client talking to a bare repo directly.
The trade-off you'd defend
I would default new clones and CI checkouts to --filter=blob:none plus a sparse checkout of only the paths a job actually touches, trading the ability to browse the entire history offline for clone times that don't grow with the repo's entire past.
Illustrative figures for the arithmetic; not GitLab-published numbers.
Gotchas
git added a file but git diff still shows nothing for it
You expect git diff to show a staged change and it shows nothing at all.
git diff compares the working tree to the index; once a change is staged, that particular comparison is clean by definition.
Use git diff --cached (or --staged) to see what's actually about to be committed; use plain git diff for what isn't staged yet.
A detached-HEAD commit "disappears" after checking out a branch
You made a commit, ran git checkout main, and git log on main shows nothing you just did — it feels deleted.
The commit was made while HEAD pointed directly at a commit, not a branch, so no branch ever referenced it.
git reflog still remembers the hash; git branch recovery/<name> <hash> gives it a home again.
"detached HEAD" gets skimmed past
Work continues normally for a while, then someone can't find their commits later.
git status's warning is easy to miss mid-debugging, especially when you weren't planning to commit anything.
Treat "detached HEAD" in git status as a hard stop: branch first (git checkout -b <name>) the moment you intend to keep anything.
Tricky questions
git add copy the file into the commit right away?Yes, git add commits the file.
git add only stages it — it writes a blob and updates the index. Nothing joins history until git commit writes a tree and a commit object over that index.
Yes, HEAD is just a name for the newest commit.
HEAD is a ref — usually a pointer to a branch, which itself points at a commit. Check out a different branch, or a commit directly (detached HEAD), and what HEAD points at changes with no new commit made at all.
Scenario question
You're handed a bug report: "I committed my fix but it's not on GitHub and now I can't find it anywhere, even in git log." The teammate insists they ran git commit. Where do you look, and what likely happened?
Model answer
I'd ask first whether they were on a named branch when they committed, but I wouldn't wait for the answer — git reflog shows every commit HEAD has pointed at recently, detached or not, so I'd run that immediately. My working guess is they were in detached HEAD, probably from an earlier git checkout <hash>, when they committed: the commit exists as a real object, but no branch references it, so git log on any branch won't show it. The fix is git branch recovery/<name> <hash-from-reflog>, then merge or cherry-pick from there. I do this before touching anything else, because further commits or a git gc push reflog entries further from HEAD@{0} and, eventually, past the default ~30-day expiry for entries no branch references.
Interview corner
CommonWhat's the difference between the working tree, the index and HEAD?
git diff compares tree-vs-index, git diff --cached compares index-vs-HEAD, and git status tells me which of those three actually differ.”TrickWhat happens if you commit while in detached HEAD?
Experience checkWhere has understanding refs versus objects actually helped you debug something?
git log on any branch. Knowing that HEAD and branches are just movable pointers, and that the object itself doesn't vanish when a pointer moves off it, is what sent me to git reflog instead of assuming the audit data was fabricated.”CommonHow would you inspect a specific commit without changing your working tree?
git show <hash> for the diff and message, git cat-file -p <hash> if I need the raw object, and git log -p -- <path> for a file's history — none of that touches the working tree or the index.”Memory hook
A branch is a sticky note pointing at a commit; the commit doesn't move or vanish just because you moved the note.
If git status says detached HEAD, branch before you commit.
Self-check
What are the three states
git status/diffcompare?The working tree, the index (staged), and HEAD's commit;
diffanddiff --cachedcompare different pairs of these.Why does
git logshow different commits aftergit checkout <hash>than it did before?Because HEAD now points directly at that commit (detached HEAD) instead of following a branch ref to wherever that branch's tip is.
What makes two files' content hash to the same blob?
Byte-identical content — git addresses objects by content, not by filename or path.
Create a repo, make three commits, check out the first commit's hash directly, and make a fourth commit there. Show with git log on the original branch that it's invisible, then recover its hash with git reflog and paste both outputs.