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

Branching, Merging, and Unscrewing Yourself

Merge vs rebase honestly (including when rebase is vandalism), conflict anatomy, and reflog as the undo button nobody taught you.

⏱ ~20 min read 🔧 Disaster recovery 🌿 History management

🎯 By the end you'll understand

Why branches are just pointers — not copies. The real difference between merge and rebase (and the exact moment rebase becomes vandalism against your teammates). How to read a conflict marker without panic. And how reflog makes "I deleted everything" into a five-second fix — the learner who recovers calmly from any git state is the one teammates trust.

KEY INSIGHTGit disasters are recoverable — if you understand the model

A branch is forty bytes on disk. The commit graph is append-only. "Lost" commits almost never are. The engineer who knows this stays calm when everyone else panics — and calm engineers get trusted with the production incident.

Lesson 2.2 showed you the git object model: blobs, trees, commits, the DAG. Hold that model in mind for this lesson, because every supposedly scary git operation — force-push, rebase, reset — is just manipulation of that DAG and the lightweight pointers that point into it. Once the model is clear, the disasters dissolve into navigation problems.

🔑 The frame for this lesson

We learn branching and merging through the lens of disasters: the force-push that ate a branch, the rebase in the middle of a code review, the "deleted" commit. This is not perverse. It is the fastest path to genuine fluency — because the learner who has practiced recovery owns git, while the learner who has only practiced the happy path is one bad Friday afternoon from losing someone else's work forever.

CORE CONCEPTBranches as pointers: the forty-byte truth

Open any git repository and look in .git/refs/heads/. Each file in there is a branch. Open one:

shell
$ cat .git/refs/heads/main
a3f8c2d1b9e047f6a5c3d2e1f0a9b8c7d6e5f4a3

That's it. A branch is a text file containing exactly one SHA-1 hash — the hash of the commit it points to. When you run git commit, git writes a new commit object and updates that text file to point to the new commit. When you run git checkout -b feature, git copies the current hash into a new file at .git/refs/heads/feature. Zero new objects are created. Zero content is copied. Creating a branch costs 40 bytes and a few microseconds.

HEAD is the pointer to the current branch (or directly to a commit, in "detached HEAD" state). Run cat .git/HEAD and you'll see either ref: refs/heads/main (attached) or a raw SHA (detached). Everything else in the branching model follows from this.

C1 C2 C3 C4 C5 C6 feature → main → HEAD shared history feature branch = one 40-byte ref
A branch is a pointer. C1–C3 are shared. feature points at C5; main points at C6. Every branch in the repo costs one text file — no data duplication.

This has an important corollary: when you delete a branch ref, you do not delete its commits. Those commit objects sit in .git/objects/ until git's garbage collector runs. The ref was your handle to them — but not the only handle. That's why reflog can find "deleted" commits. More on this in the reflog section.

COMPARISONMerge vs rebase: honestly, without the tribalism

The merge-vs-rebase debate generates more heat than almost any other git question, and most of it is wasted. Here's the accurate version:

OperationWhat it actually does to the DAGPreserves original SHA?Safe on shared branches?
git merge featureCreates a new merge commit with two parents; both histories intactYes — every commit unchangedYes — always
git rebase mainReplays your commits on top of main; writes new commits with new SHAsNo — every replayed commit is newNo — rewrites history
git merge --ff-onlyAdvances the pointer if no divergence; refuses if a merge commit would be neededYesYes
git merge --squashStages all changes as one new commit; discards individual commit chainNo — collapses historyUsually yes (explicit intent)

The real question is not "which is better" — it is "who else has these commits?"

🔑 The golden rule

Never rewrite history that has been pushed to a shared branch and fetched by someone else. When you rebase, each replayed commit gets a new SHA. If your teammate already has the old SHAs — fetched, built on top of, or reviewed — you have just given them commits whose parents have vanished. Their history diverges from yours. Any push now requires --force. And git push --force on a shared branch is the repository equivalent of overwriting someone's unsaved file.

When is rebase genuinely the right call? On your own local branch, before you push for the first time. You can tidy a messy history into a clean, reviewable sequence — "fix typo", "WIP WIP WIP", "oops revert" becomes a coherent story. Interactive rebase (git rebase -i HEAD~4) lets you squash, reorder, and reword. The result is a clean PR that's a pleasure to review. The caveat: once the branch is pushed and anyone has fetched it, the window is closed.

⚠ Rebase in the middle of a code review

This is a genuine anti-pattern that real teams suffer from. You push a branch for review. A teammate starts adding comments anchored to specific commit SHAs. You rebase to incorporate feedback from main. The reviewer's diff links are now pointing at ghost commits — their comments appear orphaned or on the wrong lines. The review dies. The polite thing to do mid-review: git merge main instead. Messy history, functional review. Clean up with squash at merge time if your team cares about linear history.

What a merge commit actually looks like in the graph

A merge commit has two (or more) parent SHAs in its metadata. That's the only thing distinguishing it from a regular commit. When you run git log --graph and see the lanes split and rejoin, you're seeing that parent pointer recorded in each merge commit's object. The merge commit itself introduces no file changes unless there were conflicts — it is purely structural.

git merge (adds a merge commit, preserves both lanes) A B F1 F2 merge both parents git rebase (replays commits — new SHAs, linear history) A B F1' new SHA F2' new SHA ⚠ if pushed before, force-push required
Merge preserves both branch histories, forming a DAG with two parents at the merge commit. Rebase replays commits onto the target — clean linear history, but every replayed commit has a new SHA. The dashed circles signal "contents same, identity different."

SEE ITGit disaster simulator

The five scenarios below let you watch a shared DAG — you and a simulated teammate — get into trouble and get out of it. The merge, rebase, force-push, and reflog steps run against a deterministic model; every button advances the simulation one step. Scenario 5 is the recovery drill: a "deleted" commit brought back from the reflog.

⚙ Interactive · Git branching & disaster simulator

Pick a scenario. Step through it. Watch the DAG and teammate state update. Conflicts require resolution before you can proceed.

Your branch
—
Teammate branch
—
Shared remote (origin/main)
—
Reflog (last 3 entries)
—

Notice what scenario 3 shows: after the force-push, your teammate's local main has commits that no longer exist on the remote. Their next git pull creates a diverged state — they now have a "future" main that nobody else recognizes. The only real fix is for them to throw away their local branch and re-clone, or to carefully use git reflog to locate which commits of theirs were actually new work (as opposed to the pre-force-push commits that were overwritten).

HOW IT WORKSConflict anatomy: what the markers actually mean

A merge conflict is git telling you that two branches changed the same region of the same file in ways it cannot automatically reconcile. It is not an error — it is a request for human judgment. The fear people have about conflicts usually evaporates on second contact, once they know how to read the markers.

tracelab/storage.pyafter a conflicting merge
def save_run(run):
<<<<<<< HEAD
    # your version: write to sqlite
    db.insert(run)
=======
    # teammate's version: write to parquet
    pq.append(run_path, run)
>>>>>>> feature/parquet-storage

The anatomy:

Resolution: delete all three marker lines and replace the region with whatever the correct answer is — maybe yours, maybe theirs, maybe a synthesis. Then git add storage.py to mark it resolved, and git commit or git rebase --continue.

💡 Use a real merge tool

For anything beyond a trivial conflict, git mergetool opens your configured three-way merge editor (VS Code, IntelliJ, vim-fugitive, vimdiff all work). You see base (the common ancestor), ours, and theirs side by side — which shows you not just what changed but in what direction. Resolving a conflict without the base view is solving a puzzle with a piece missing.

There is a category of conflict that looks trivial but is not: semantic conflicts. Two people rename a function in different ways; git's textual merge succeeds with no markers but the code is now inconsistent. Or one person adds a call site; the other deletes the function — git auto-resolves to a build error. Conflict resolution is textual; only the tests can catch semantic divergence. This is one of several reasons the TraceLab milestone requires a test suite.

IN PRACTICEReflog: the undo button nobody taught you

The reflog is git's journal of where HEAD (and branch tips) have pointed over time. Unlike the commit graph — which is shared state, pushed to remotes — the reflog is local only. It records your working session. Every checkout, commit, merge, rebase, and reset adds a line. Default retention is 90 days for reachable entries.

shell
$ git reflog
a3f8c2d (HEAD -> main) HEAD@{0}: commit: add csv escaping
b7e1f9a HEAD@{1}: commit: refactor log_run
d4c0a3b HEAD@{2}: reset: moving to HEAD~1
e2b9f1c HEAD@{3}: commit: add --force flag to compare
f5a8d2e HEAD@{4}: checkout: moving from feature to main

The highlighted line shows a git reset — the move that typically triggers "I deleted my commit!" panics. But notice: the SHA d4c0a3b is the state before the reset. The commit whose SHA was lost to your branch ref still exists as an object. To recover it:

shell
# option A: create a new branch at the lost commit
$ git checkout -b recovery d4c0a3b

# option B: move main back to it
$ git reset --hard d4c0a3b

# option C: cherry-pick specific commits back
$ git cherry-pick e2b9f1c

The reflog also saves you from a git rebase gone wrong. Every rebase checkpoint is logged. If a rebase produced a mess — wrong base, conflicts resolved incorrectly, squashes applied to the wrong range — git reflog shows you the SHA of your branch before the rebase started (look for the rebase (start) entry). git reset --hard <that SHA> and the rebase never happened.

📖 git reset --hard vs git reset --soft

--hard moves the branch pointer and overwrites your working directory and index. --soft moves only the pointer — your staged changes and working-tree files are untouched. --mixed (the default) moves the pointer and unstages changes but leaves files alone. --hard is the dangerous one: it discards uncommitted work. But committed work is always in the reflog.

One more recovery tool worth knowing: git cherry-pick <SHA> applies the diff of any commit — regardless of branch — onto your current branch as a new commit. Useful when you want a specific fix from another branch without pulling in all of its history, or when you need to transplant a bugfix from a feature branch back to main before the feature is ready to merge.

TRACELABTraceLab v1: the clean history with a deliberate disaster

TraceLab v1 is the Stage 2 milestone: v0's scruffy script restructured into a real package. The git history is part of the deliverable — and the milestone requires a recovered disaster in the reflog.

Here is the sequence you will execute to earn that reflog entry:

1

Create a clean tracelab/ package structure on a branch

On feature/v1-structure, reorganize the flat tracelab.py into src/tracelab/__init__.py, cli.py, storage.py. Commit the restructure. This is legitimate, reviewed history.

2

Introduce the "disaster"

Make a second commit on that branch that adds a debug_dump() function that prints raw run data to stdout — useful for development, catastrophic in production, and something you want to disappear from history before merging.

3

Recover cleanly with rebase -i (before push)

Run git rebase -i HEAD~2. In the editor, mark the debug commit as drop. The commit disappears from the branch — but git reflog still shows it at HEAD@{N}. Verify: git show HEAD@{N} recovers it. This is the proof of recovery.

4

Merge cleanly to main

git checkout main && git merge --no-ff feature/v1-structure. The --no-ff flag creates an explicit merge commit even if fast-forward is possible — making the branch's origin visible in the history, which is valuable context in a long-running project.

The resulting git log is your artifact: a clean package restructure merged with an explicit merge commit, and a reflog that proves you can recover from the debug disaster. A reviewer reading git log --oneline --graph sees a single coherent story. A reviewer running git reflog on your repo can verify you know how to recover from mistakes.

expected git log --oneline --graph
*   a3f8c2d (HEAD -> main) Merge branch 'feature/v1-structure'
|\
| * b7e1f9a (feature/v1-structure) restructure: src/tracelab package layout
|/
*   c4d5e6f add typed CLI skeleton (tracelab init/log/compare)
*   d7e8f9a v0 → tracked: add pyproject.toml, lock deps
*   e1f2a3b initial: tracelab.py v0 (the scruffy script)

What is absent from this log is as important as what is present: no "WIP", no "fix typo", no "oops revert commit from before". Every line tells a story. That discipline — a history that a future engineer could read to understand the project's evolution — is the whole point of Stage 2's git mandate.

WEAKNESSWhere this bites engineers at every level

✗ Force-pushing a shared branch

git push --force origin main on a branch anyone else has fetched is one of the most destructive things a developer can do without noticing. GitHub's "protected branches" feature exists entirely because of this failure mode. Even on your own repository: if a CI system has fetched and is running on those commits, a force-push mid-pipeline can produce test results attributed to the wrong code. Use --force-with-lease instead — it refuses to push if someone else has updated the remote since your last fetch. It's the force-push with a conscience.

✗ Rebasing a branch that is open for review

You've filed a PR. Your reviewer has opened the diff. You rebase to include two new commits from main. Every commit in your branch now has a new SHA. The GitHub diff view may re-request a full review. Comments anchored to specific lines drift or disappear. Your reviewer loses context and has to reconstruct their mental model. This happens constantly in real teams and is entirely preventable by the rule: once a PR is open, merge (don't rebase) to incorporate upstream changes. Squash at merge time if you want cleanliness.

✗ Assuming a "deleted" commit is truly gone

The opposite failure mode: a junior engineer drops a commit or accidentally resets and immediately spirals into panic or starts recreating work from memory. The correct response is: stop, run git reflog. The commit is almost certainly there, accessible by its SHA, recoverable in thirty seconds. The reflog expires (90 days by default), so the one real risk is running git's garbage collector on a repo you care about before you've recovered. The command git gc removes unreachable objects; git fsck --unreachable shows them before gc would remove them.

KEY INSIGHTHow this connects

  • 2.2 · Git, Actually: The Object Model — this lesson's branching model only works if you have the object model solid. Commits as content-addressed snapshots, the DAG as the graph of parent pointers — those are the foundations that make "branch as pointer" meaningful rather than metaphorical.
  • 2.4 · Errors Are Part of the API — TraceLab v1's error handling is designed in the next lesson. The clean package structure we just built (and its recovered disaster in the reflog) is the codebase that error-handling reform will target.

The disaster recovery drills in this lesson are not a sidetrack — they are the point. A team's git history is its institutional memory, and the engineer who can navigate, repair, and reason about that history without fear is genuinely more valuable than one who has only ever used the happy path.

GLOSSARYKey terms introduced

Branch ref
A text file in .git/refs/heads/ containing exactly one commit SHA. Creating a branch writes this file; deleting a branch removes it. The commits remain in the object store.
Merge commit
A commit with two or more parent pointers, created when git merge joins diverged histories. Records both lanes in the DAG without rewriting either.
Rebase
Replays a sequence of commits onto a new base commit, producing new commits with new SHAs. The original commits are abandoned (but reachable via reflog).
Fast-forward merge
When one branch is a direct ancestor of another, moving the pointer forward without creating a merge commit. --no-ff forces a merge commit even when fast-forward is possible.
Reflog
A local-only journal of where HEAD and branch tips have pointed. Records every checkout, commit, reset, and rebase. Default retention 90 days. The primary recovery tool for "lost" commits.
Conflict markers
The <<<<<<< / ======= / >>>>>>> lines git writes into a file when two branches change the same region. The two versions are shown; the human chooses the resolution.
--force-with-lease
A safer variant of git push --force that aborts if the remote has been updated since your last fetch — preventing accidental overwrite of a teammate's work.
Cherry-pick
Applies the diff of a specific commit from any branch onto the current branch as a new commit. Useful for transplanting a fix without merging an entire branch.

ACTIVE RECALLCheck your understanding

Answer in your own words first, then reveal.

1A branch is deleted with git branch -d feature. Are its commits gone?›

No. git branch -d deletes the ref file — the pointer — not the commit objects. The commits sit in .git/objects/ as unreachable objects until git gc prunes them (default 90-day grace period). git reflog will still show the SHA of the last commit on that branch. Recover with git checkout -b recovery <SHA>.

2Your teammate just ran git rebase -i on a branch that you've both fetched and built on top of. What is the actual problem?›

The rebase replaced each commit with a new one with a different SHA. Your branch still has the original SHAs as parents. The remote now has different SHAs at those positions. Your history and the remote's history have diverged — any push from you will be rejected, and pulling will create a messy merge of old and new history. The correct fix is for whoever rebased to have used merge instead; the practical fix now is to git fetch and carefully git reset --hard to the remote branch, rescuing any of your own commits via reflog and cherry-pick.

3What does a merge conflict marker show, and what do you actually have to do to resolve it?›

The file contains both versions of the conflicting region: your current branch's version between <<<<<<< HEAD and =======, and the incoming branch's version between ======= and >>>>>>> branch-name. Resolution: delete all three marker lines, replace the region with the correct content (yours, theirs, or a synthesis), then git add <file> to mark it resolved and git commit or git rebase --continue.

4You ran git reset --hard HEAD~3 and realized you needed those three commits. How do you recover them?›

Run git reflog. You will see an entry like HEAD@{1}: commit: <message> for the commit that was at HEAD before the reset (and further back for the two before it). Take the SHA of the commit you want to restore. Then either: git reset --hard <SHA> to move your branch back to it, or git checkout -b recovery <SHA> to create a new branch there. All three commits are still present as objects in the object store.

Next: designing errors as part of the API contract →