SYSTEMS ARCHITECTURE • CONTENT-ADDRESSABLE DAG • SRE LAB

How Git Works Under the Hood

An interactive systems engineering guide, visual state machine simulator, and intuitive mental models demystifying Git's Directed Acyclic Graph (DAG), storage engine, 3-way merges, and disaster recovery.

MODULE 01 • INTERACTIVE STATE MACHINE

The 4 Git Architecture Zones

Git does not work directly between your code editor and GitHub. It coordinates transitions between four distinct, decoupled rooms. Click the buttons below to simulate file movements and observe internal state changes in real time.

Live File State Machine branch: main • HEAD -> 7a9f1c
1. Working Tree 2 files
Filesystem • Raw uncommitted edits
2. Staging Area 0 files
.git/index • Prepared snapshot
3. Local Repo 1 commit
.git/objects/ • Immutable commit DAG
4. Remote Repo origin/main
GitHub / GitLab • Upstream sync
DISPATCH COMMAND:
TERMINAL & INTERNAL ENGINE TELEMETRY ● ENGINE IDLE
$ git status
On branch main
Changes not staged for commit: modified: server.go
Untracked files: auth.go
⚙️ [Under The Hood] Working Directory holds unstaged file descriptors. Staging Index (.git/index) has not hashed these new contents yet.
💡 Intuitive Mental Model
The 4 Rooms of Git

Think of Git as a photography studio with four separate rooms. Code walks through them one door at a time:

  • Room 1: Your Messy Desk (Working Directory): Where you type code, break things, and experiment. Git watches through a window, but doesn't touch your desk.
  • Room 2: The Photo Stage (Staging Area / Index): When you run git add, you invite specific files onto the stage to strike a pose. Any file you didn't add stays on your desk.
  • Room 3: The Fireproof Safe (Local Repository): When you run git commit, the camera shutter snaps a permanent photo, stamps the date, and locks it inside your safe in .git/. Even if your laptop battery dies, this snapshot is permanent.
  • Room 4: The Cloud Warehouse (GitHub / Remote): When you run git push, you photocopy all the photos in your safe and mail them to GitHub for your team to see.
MODULE 02 • INTERACTIVE RESOLUTION ENGINE

Live Merge Conflict Resolution Lab

A merge conflict is not an error—it is Git safely pausing when two branches diverge and edit the same line since their Lowest Common Ancestor (Base).

🍔 Everyday Analogy
The Restaurant Menu Analogy: Why Conflicts Happen

Imagine you and your teammate both download a restaurant menu file where Burger Price = $10.
• You decide: "Burgers should be $12", edit line 3, and commit.
• Your teammate decides: "Burgers should be $15", edits line 3, and commits.
When you type git merge, Git looks at the original $10 base and compares both changes. Git is smart, but Git is not psychic. Git says: "You both changed line 3 from $10 to different prices! I refuse to guess who is right because I might crash your restaurant. You human, look at this and choose!"

config/service.yaml Merging 'feature/metrics' into 'main'
PHASE 1: CONFLICT MARKERS DETECTED
1 | service_name: "telemetry-collector"
2 | replicas: 3
<<<<<<< HEAD (main - current branch)
3 | listen_port: 8080
4 | log_level: "info"
======= (Separator: Base Common Ancestor was listen_port: 8000)
5 | listen_port: 9090
6 | log_level: "debug"
>>>>>>> feature/metrics (incoming branch)
7 | health_check_path: "/healthz"
8 | timeout_seconds: 30
RESOLUTION STRATEGY:
PIPELINE ACTIONS:
💡 Systems Insight: Why Resolved Conflicts Never Re-Occur

Once you stage and commit the resolution above, Git generates a Merge Commit with two parents. This new merge commit permanently becomes the Lowest Common Ancestor (Base) for any future merges between these two branches. Because the base now contains your resolved code, the diff between the base and either branch tip is zero—preventing Git from ever prompting on that line again!

MODULE 03 • STORAGE ARCHITECTURE

The Content-Addressable Object Database & DAG

Under the hood, Git is not a file tree—it is a key-value database (like a giant warehouse with numbered lockers). The key is a 40-character SHA-1 hash, and the value is compressed data. Everything in .git/objects/ is one of four primitive types:

🌳 Demystifying DAG
What is a DAG? (Directed Acyclic Graph)

• Directed: Arrows point in one direction only. (Children point backward to their parent commits).
• Acyclic (NO LOOPS): You can never loop in a circle. You can't be your own grandfather.
• Graph: Dots (commits) connected by lines.
Why is it unbreakable? Each commit's fingerprint includes its parent's fingerprint. If someone tampers with an old commit from 3 months ago, every single commit after it breaks instantly, alerting Git to tampering!

OBJECT 01 • DATA

Blob (Binary Large Object)

Stores pure file contents compressed via zlib. A blob does not know its own filename, folder, or permissions! It is just nameless raw content.

$ git cat-file -t 3f1a77 blob $ git cat-file -p 3f1a77 package main ...
OBJECT 02 • DIRECTORY

Tree Object (A Folder)

Represents a directory node. It is a checklist that maps filenames and file permissions (e.g. 100644 for normal files, 040000 for subdirectories) to Blob hashes.

$ git cat-file -p d83a21 100644 blob 3f1a77 server.go 040000 tree b5c942 config
OBJECT 03 • SNAPSHOT

Commit Object

The snapshot envelope. Contains a pointer to the root Tree object, author/committer identities, ISO timestamps, commit message, and a pointer to the parent commit(s).

tree d83a21... parent 4b2e8d... author Santosh Parsa <...> committer Santosh Parsa <...>
OBJECT 04 • REFERENCES

Branches & HEAD (41 Bytes)

A branch is not a copy of your files. It is a 5-cent yellow sticky note in .git/refs/heads/ containing a 40-character commit hash! HEAD is just a red sticker saying "You Are Here".

$ cat .git/refs/heads/main 7a9f1c42e88a91b... $ cat .git/HEAD ref: refs/heads/main
MODULE 04 • SYSTEMS DEEP DIVES

10 Core Git Engineering Topics & Systems Scenarios

Deep technical breakdowns paired with plain-English mental models covering Git topology, merge theory, disaster recovery, and DevSecOps integrity controls. Click each topic to expand.

TOPIC 01 • DATA STRUCTURES
Snapshots vs Deltas: The Content-Addressable DAG Model
▼
💡 Mental Model

The Photo Album vs 500 Transparent Tracing Papers: Older systems (SVN/CVS) store revisions as diff deltas (transparent tracing papers layered on top of each other). To see version 500, SVN has to stack 500 tracing papers, making it slower and slower over time. Git stores full Polaroid snapshots. Checking out any past commit is a constant-time \(O(1)\) lookup.

Automatic File Deduplication

If a file is unchanged between commits, the new tree simply references the pre-existing Blob's SHA-1 hash. Even in a 50,000-file project, changing 1 file only creates 1 new blob. The other 49,999 files are shared references!

# Verify how Git hashes file content deterministically: $ printf "blob 14\0hello systems " | sha1sum # Output matches: git hash-object -w filename
TOPIC 02 • ALGORITHMIC THEORY
The 3-Way Merge Algorithm & Lowest Common Ancestor (LCA)
▼
💡 Mental Model

The Common Grandparent: Git never compares Branch A directly against Branch B alone—that would cause chaos because Git wouldn't know who changed what. Git finds the Lowest Common Ancestor (Base) in the DAG using git merge-base branchA branchB.

Base (LCA) HEAD (Current) Incoming (Feature) Git Automatic Resolution Decision
port: 8000 port: 8080 (Modified) port: 8000 (Untouched) Take HEAD (Only current branch changed it)
port: 8000 port: 8000 (Untouched) port: 9090 (Modified) Take Incoming (Only incoming branch changed it)
port: 8000 port: 8080 (Modified) port: 9090 (Modified) CONFLICT! Both branches changed the same lines divergently.
TOPIC 03 • TOPOLOGY & GRAPH INVARIANTS
The Git Merge Invariant: Why Solved Conflicts Never Re-Occur
▼
💡 Mental Model

The New Master Copy: When you resolve a merge conflict today, the resulting Merge Commit has two parents (main & feature). In all future merges, that merge commit becomes the new Common Ancestor (Base). Because both branches already share that resolved state from the new base, the difference is 0 and no conflict is ever triggered again!

Commit History DAG: [Ancestor Base: B] / [Main: C] [Feature: D] <-- Conflict resolved here \ / [Merge Commit: M] <-- M has parents C and D!
TOPIC 04 • WORKFLOW & TRUNK-BASED ENGINEERING
Merge vs Rebase: Topology, Audit Trails, and the Golden Rule
▼
💡 Mental Model

Tying Ropes Together (Merge) vs Time-Traveling to Replay Commits (Rebase):

  • `git merge`: Tying two ropes together with a knot. Preserves the exact truth of when work was branched. Perfect for release branches and shared mainlines.
  • `git rebase`: Time travel. Pretentiously pretends you only started your work today on top of the latest code. Produces a single, beautiful straight line in git log.
⚠️ The Golden Rule of Rebasing

Never rebase commits that have been pushed to a public/shared branch! Rebasing rewrites history and changes commit SHA hashes. If teammates have built work on the old hashes, force-pushing creates duplicate commit loops and broken topologies for the team.

TOPIC 05 • DISASTER RECOVERY
Disaster Recovery: Head Traversal and `git reflog` Rescue Operations
▼
💡 Mental Model

The CCTV Security Camera: Did you accidentally run git reset --hard HEAD~1 and think your unpushed commit is gone forever? In Git, almost nothing is ever lost! Git has an append-only journal in .git/logs/HEAD recording every move your HEAD pointer ever made.

# Step 1: Look at the CCTV footage $ git reflog 7a9f1c4 (HEAD -> main) HEAD@{0}: reset: moving to HEAD~1 8f2a11b HEAD@{1}: commit: add production redis clustering <-- YOUR LOST CODE! # Step 2: Immediate zero-loss recovery $ git checkout -b recovery-branch 8f2a11b
TOPIC 06 • ENGINE MECHANICS
Detached HEAD Mechanics and Garbage Collection Safety
▼
💡 Mental Model

Floating in Space Without a Tether: Normally, HEAD points to a branch sticky note (ref: refs/heads/main). When you checkout a commit hash directly (git checkout 4b2e8d), HEAD points directly to the commit, detached from any branch name. Any new commits made here are "dangling" (untethered). If you switch branches, Git GC will eventually delete them unless you give them a sticky note: git branch saved-work HEAD.

# View dangling commits before garbage collection: $ git fsck --lost-found dangling commit e84b2c1...
TOPIC 07 • STATE MANAGEMENT
The `git reset` Matrix: Deep Comparison of `--soft`, `--mixed`, and `--hard`
▼
💡 Mental Model

The 3 Levels of Undo:
• `--soft`: Gentle Undo. Takes down the photo, but leaves everyone standing on the stage (staged in green).
• `--mixed` (Default): Normal Undo. Takes down the photo and tells everyone to step off the stage (unstaged in red).
• `--hard`: Nuclear Undo. Takes down the photo and wipes the files completely from your disk!

Command HEAD Pointer Staging Index (.git/index) Working Directory Primary Production Use Case
git reset --soft HEAD~1 Moves to target Preserved (Staged) Preserved (Unchanged) Squash commits or reword commit message.
git reset --mixed HEAD~1 (Default) Moves to target Reset to target Preserved (Unchanged) Unstage files and selectively re-add chunks.
git reset --hard HEAD~1 Moves to target Reset to target Wiped to target Completely discard broken local experiments.
TOPIC 08 • SURGICAL PATCHING
Patch Synthesis with `git cherry-pick` and Duplicate Commit Risks
▼
💡 Mental Model

The 10-Track Music Album and the Tweezers: Your teammate recorded a 10-song album on their branch. 9 songs are buggy experiments, but Track #4 is an urgent security patch. Instead of merging their whole branch, you reach in with tweezers and pluck only Track #4 onto your branch using git cherry-pick <hash>.

Architecture Nuance: The cherry-picked commit applies the exact same patch, but gets a new timestamp, new parent, and new SHA-1 hash.

TOPIC 09 • SYSTEMS TRIAGE
Regression Triage at Scale: Automated `git bisect run`
▼
💡 Mental Model

Sherlock Holmes & The "Guess My Number" Game: If a regression bug appeared somewhere across 1,000 commits, testing each commit manually takes days. git bisect cuts the commit history in half on every test iteration (\(O(\log_2 N)\)). Across 1,000 commits, you isolate the exact breaking commit in at most 10 test steps!

# Fully Automated CI Bisect using automated test scripts: $ git bisect start HEAD v2.4.0 $ git bisect run ./scripts/validate_kernel_benchmark.sh # Result: 3f1a77b819 is the first bad commit! $ git bisect reset
TOPIC 10 • DEVSECOPS & POLICY
Enterprise Integrity: Client-Side vs Server-Side Hook Enforcement
▼
💡 Mental Model

The Honor System vs Central Airport Security:
• Client-side hooks (.git/hooks/pre-commit) run on the developer's laptop. They are helpful for code formatting, but are not secure because any engineer can bypass them with git commit --no-verify.
• Server-side hooks (pre-receive) run centrally on GitHub/GitLab. They cannot be bypassed by clients and enforce strict compliance: cryptographically verified GPG signatures, secret key scanning (blocking leaked AWS/API keys), and branch policies.

MODULE 05 • KNOWLEDGE VERIFICATION

Systems Self-Assessment & Knowledge Check

Test your mastery of Git internals, recovery protocols, and merge algorithms. Select an answer to reveal the underlying architectural explanation.

ASSESSMENT PROGRESS: 0 of 5 answered
SCORE: 0 / 5
QUESTION 01 • STORAGE MODEL
How does Git store the contents of unchanged files across subsequent commits?
QUESTION 02 • DISASTER RECOVERY
An engineer runs git reset --hard HEAD~1 and loses an unpushed commit. What is the most reliable way to recover it?
QUESTION 03 • STATE RESET MATRIX
What happens to the Staging Index and Working Tree when executing git reset --soft HEAD~1?
QUESTION 04 • MERGE TOPOLOGY
Why does resolving a 3-way merge conflict once prevent it from re-prompting on that same code in future merges?
QUESTION 05 • REBASE SAFETY
What is the primary danger of running git rebase on commits that have already been pushed to a shared public branch?