The Analogy: The Signal Box, the Train Register, and the Block Instrument
On a single-track railway worked under absolute block, the line is cut into sections and each section is guarded by a signal box. The signalman keeps two records in front of him. The train register is a ruled book in his own hand: every train that passed, the minute it entered the section ahead, the bell code he sent, the code that came back. It is his, and for his own stretch of line it is complete. Beside it stands the block instrument, a dial whose needle reads Line Clear, or Train On Line, or Normal, for the section ahead. He cannot see that section. It may be a mile of cutting and a tunnel on a curve. The needle is the only thing he has.
The needle is not the section. It is a repeater of a switch in the next box, and it moves when that signalman turns his commutator and rings a code, and at no other time. If the neighbour is busy, or the wire is down, or nobody thought to send a code, the needle holds whatever it was last set to, for a minute or for an hour, and there is no mark on the dial to say how old the reading is. A signalman who wants the state of the section now does not stare harder at the needle. He rings the box and asks, and the answer he gets back is a fresh statement rather than a remembered one.
Sending a train is a request, not an act. He does not put a train into the section and inform the neighbour afterwards. He rings Is Line Clear, and waits, and the neighbour either repeats the code back, which is acceptance and hands the section over, or does not. The condition attaches to the neighbour's knowledge, not to his own: he can want the section very much, and be entirely certain it is empty, and still be refused. The refusal is not a fault in the equipment. It is the equipment doing the one job it exists to do.
The failure has a name in the accident reports of the era. The needle stands at Line Clear because that is where it was last set; meanwhile a train has been admitted to the section from a siding, and no code was sent because the man who should have sent it was answering the telephone. The signalman reads Line Clear, accepts a train, and pulls his signal off. Nothing about his instrument was broken and nothing he did broke the rules as he understood them. He read a record of a past conversation as a report of the present, and both trains were in the same section before anyone knew.
Syntax or Core Structure
Git splits the same way. Your branches live in refs/heads and they are your register: you write them, nothing else does. A remote-tracking ref such as origin/main lives in refs/remotes and it is the needle -- a local file recording what the server said the last time you asked. It never moves on its own. And git push is Is Line Clear: a request the server may refuse, on a condition the server evaluates against its own refs rather than yours.
A remote is three pieces of configuration, not a connection. It has a name, a URL, and a refspec that says where fetched refs are filed. Nothing below needs a network; the "server" is a bare repository in the next directory, reached by a relative path so the output does not depend on where you put it.
git init -q --bare -b main depot.git
git init -q -b main alice
cd alice
git remote add origin ../depot.git
git remote
git remote get-url origin
git config --get remote.origin.fetch
git for-each-ref --format='%(refname)' | wc -l
printf 'v1\n' > VERSION
git add VERSION
git commit -qm 'chore: seed'
git push -q -u origin main
git for-each-ref --format='%(refname)'
git config --get branch.main.remote
git config --get branch.main.merge
git status -sb
Output:
origin
../depot.git
+refs/heads/*:refs/remotes/origin/*
0
refs/heads/main
refs/remotes/origin/main
origin
refs/heads/main
## main...origin/main
Read the refspec as a rule: take every ref under refs/heads on the server and file it under refs/remotes/origin here. The leading plus permits a non-fast-forward update of the local copy, which is right, because your copy is a record of what the server said and the server is allowed to change its mind.
The count of zero matters. Before the push, the repository has no refs at all -- not even the remote-tracking one. The needle does not exist until the first conversation, and git remote add is not a conversation. After the push there are two refs for one branch: refs/heads/main, which you wrote by committing, and refs/remotes/origin/main, which the push wrote as a record of what the server now holds.
The -u flag wrote two lines of configuration, branch.main.remote and branch.main.merge, and those two lines are the whole of what people call tracking. They are what lets a bare git push know where to go, what @{u} resolves to, and what the two dots in ## main...origin/main compare. Note what git status printed: no ahead or behind figure at all, because the two refs are equal. Everything git status says on that line is computed from the local needle, without a network.
Cloning does the same setup in one step, from the other direction. A second developer takes a copy of the depot:
git clone -q ./depot.git bob
cd bob
git rev-list --count HEAD
git branch --show-current
git config --get remote.origin.fetch
git branch -r
Output:
1
main
+refs/heads/*:refs/remotes/origin/*
origin/HEAD -> origin/main
origin/main
git clone is four operations wearing one name: create a repository, add a remote called origin with that URL and the standard refspec, fetch, then create a local branch from one of the fetched refs and check it out. The name origin is a default in exactly one place, the clone command, and it is a string like any other. The extra ref, origin/HEAD, records which branch the server's own HEAD symref pointed at, which is how clone decided to check out main rather than picking alphabetically.
Technical Depth: What Is Cached, What Is Asked, What Is Refused
The needle is not the section
Everything the previous lesson said about refs applies here with one addition: refs under refs/remotes are written by fetch and push, never by commit, and they are only as current as the last one of those you ran. Watch what happens when Alice pushes and Bob does not fetch.
# in alice
printf 'v2\n' > VERSION
git commit -qam 'chore: bump to v2'
git push -q origin main
# in bob
git rev-list --count origin/main
[ "$(git ls-remote origin main | awk '{print $1}')" = "$(git rev-parse origin/main)" ] && echo 'cache: current' || echo 'cache: stale'
git ls-remote --heads origin | awk '{print $2}'
git fetch -q origin
git rev-list --count origin/main
[ "$(git ls-remote origin main | awk '{print $1}')" = "$(git rev-parse origin/main)" ] && echo 'cache: current' || echo 'cache: stale'
git status -sb
Output:
1
cache: stale
refs/heads/main
2
cache: current
## main...origin/main [behind 1]
Bob's origin/main said one commit while the depot held two, and it said so without hesitation or warning. The comparison in the middle is the interesting command: git ls-remote is one of the very few porcelain commands that actually contacts the remote and reports what is there right now, and it reads nothing from refs/remotes. Comparing its answer to git rev-parse origin/main is how you ask whether your needle is current. Field 1 of each ls-remote line is the object id and field 2 is the full ref name, which is why the second call filters to {print $2} and prints names alone.
| Ref | Written by | Read by | Current as of |
|---|---|---|---|
refs/heads/main here | your commits, merges, rebases | everything you run locally | always |
refs/remotes/origin/main | fetch, push, clone | status, range syntax, @{u} | your last fetch or push |
refs/heads/main on the server | pushes the server accepted | git ls-remote, other clones | always, on the server |
origin/HEAD | clone, git remote set-head | clone's choice of branch | when it was last set |
The last row is worth a second look. origin/HEAD is set once by clone and never revisited; if the server's default branch is renamed a year later, your copy still names the old one until git remote set-head origin -a runs. It is a needle almost nobody remembers exists.
Fetch, pull, and the half that already ran
git fetch writes only to refs/remotes. It cannot touch your branch, your index, or your working tree, which is what makes it the safe half. git pull is that fetch followed immediately by an integration of the fetched ref into your current branch, and the integration is the half that can fail.
# alice pushes v3; bob has not integrated v2 either
git status -sb
out=$(git pull --ff-only 2>&1)
echo "exit=$?"
printf '%s\n' "$out" | sed -n 's/^fatal: //p'
git status -sb
git pull -q --rebase
echo "exit=$?"
git status -sb
git log --format='%s'
Output:
## main...origin/main [ahead 1, behind 1]
exit=128
Not possible to fast-forward, aborting.
## main...origin/main [ahead 1, behind 2]
exit=0
## main...origin/main [ahead 1]
docs: add notes
chore: bump to v3
chore: bump to v2
chore: seed
The pull failed, and the behind count went up anyway. Bob started one commit behind his cached view, the fetch half ran and revealed that he was in fact two commits behind the depot, and only then did the fast-forward check run and refuse. Exit 128 is a hard error, not a merge conflict; there is nothing to resolve and no state to abort, because the integration never started. But the needle moved, and that is the part people misread as "the pull did nothing".
git pull --rebase then replayed Bob's one commit on top of the fetched tip, which is the rebase from the previous lesson with the fetch bolted on the front. Only one ahead remains, and the history is linear.
| Command | Touches refs/remotes | Touches your branch | Fails when |
|---|---|---|---|
git fetch | yes | no | the remote is unreachable |
git pull --ff-only | yes | fast-forward only | your branch has its own commits |
git pull --no-rebase | yes | writes a merge commit | the merge conflicts |
git pull --rebase | yes | rewrites your commits | a replayed commit conflicts |
git push | yes, on success | no | the server's ref is not an ancestor |
Since Git 2.27 a bare git pull on a diverged branch refuses and asks you to choose rather than defaulting to a merge. Choose once per repository with git config pull.rebase true or pull.ff only, because the flag you forget is the one that writes a merge commit you did not want.
The refusal and the lease
Push is the request the server may refuse. The condition is precisely the one from the merge lesson: the server accepts an update only when its current ref is an ancestor of what you are offering, so that no commit it already published stops being reachable.
# alice pushes v4; bob commits again without fetching
out=$(git push origin main 2>&1)
echo "exit=$?"
printf '%s\n' "$out" | sed -n 's/^ ! \[rejected\] *//p'
out=$(git push --force-with-lease origin main 2>&1)
echo "exit=$?"
printf '%s\n' "$out" | sed -n 's/^ ! \[rejected\] *//p'
git fetch -q origin
git rebase -q origin/main
git push -q origin main
echo "exit=$?"
git status -sb
Output:
exit=1
main -> main (fetch first)
exit=1
main -> main (stale info)
exit=0
## main...origin/main
Two refusals, two different reasons, and the difference is the whole reason --force-with-lease exists. The first is the ordinary fast-forward check: the depot's main is not an ancestor of Bob's, so accepting would strand Alice's commit. The second is a check on Bob's own knowledge. A lease means "overwrite the server's ref, but only if it still points where my origin/main says it does". Bob's copy was stale, the lease did not match, and the push was refused for that reason alone, reported as stale info. Plain --force asks no such question and would have deleted Alice's commit from the branch without a word.
The cure is never a bigger hammer. Bob fetched, rebased onto the fetched tip, and pushed a fast-forward that exit 0 and an empty ahead-behind report confirm.
Refs that outlive their branches
A remote-tracking ref is a file, and files do not disappear because something on a server did. Deleting a branch on the server does not delete your copy of it, and a plain fetch will not either.
# alice pushed feature/spike, then ran: git push origin --delete feature/spike
git fetch -q origin
echo 'after the branch was pushed:'
git branch -r
git fetch -q origin
echo 'after the server deleted it, plain fetch:'
git branch -r
git fetch -q --prune origin
echo 'after fetch --prune:'
git branch -r
git fetch -q origin 'refs/heads/main:refs/remotes/snapshot/main'
git for-each-ref --format='%(refname)' refs/remotes/snapshot
git config --get-all remote.origin.fetch
Output:
after the branch was pushed:
origin/HEAD -> origin/main
origin/feature/spike
origin/main
after the server deleted it, plain fetch:
origin/HEAD -> origin/main
origin/feature/spike
origin/main
after fetch --prune:
origin/HEAD -> origin/main
origin/main
refs/remotes/snapshot/main
+refs/heads/*:refs/remotes/origin/*
Fetch adds and updates; only --prune removes. Set fetch.prune true once and every fetch in that repository cleans up after itself, which is the difference between a branch list you can read and the four hundred dead entries most long-lived clones accumulate.
The last two commands show that the refspec is an argument, not a law. Passing one explicitly filed the server's main under a namespace of your own choosing without disturbing the configured rule, which is how mirrors, release-tracking clones, and one-off comparisons against a colleague's fork are built.
Real World Example: An Audit That Trusts the Needle
Teams with more than a handful of branches want a standing report: which branches are ahead, which are behind, which would push cleanly. This script produces one. It is the kind of thing that ends up in a pre-push hook or a nightly job.
#!/usr/bin/env bash
# remote-audit.sh [remote] -- report how every local branch stands against its
# upstream, and whether pushing it would fast-forward.
set -u
remote=${1:-origin}
git config --get "remote.$remote.url" >/dev/null || { echo "audit: no remote named $remote"; exit 2; }
echo "remote=$remote"
printf '%-14s %-20s %5s %6s %s\n' BRANCH UPSTREAM AHEAD BEHIND PUSH
diverged=0
git for-each-ref --format='%(refname:short) %(upstream:short)' refs/heads | while read -r br up; do
if [ -z "$up" ]; then
printf '%-14s %-20s %5s %6s %s\n' "$br" "-" "-" "-" "no-upstream"
continue
fi
ahead=$(git rev-list --count "$up".."$br")
behind=$(git rev-list --count "$br".."$up")
if [ "$behind" -eq 0 ]; then
verdict=fast-forward
else
verdict=diverged
diverged=$((diverged + 1))
fi
printf '%-14s %-20s %5s %6s %s\n' "$br" "$up" "$ahead" "$behind" "$verdict"
done
echo "diverged=$diverged"
[ "$diverged" -gt 0 ] && exit 1
exit 0
Carol has one unpushed commit on main and a branch she has never pushed. Dana has pushed one commit to the depot in the meantime, and Carol has not fetched since.
bash ../remote-audit.sh origin
echo "exit=$?"
out=$(git push origin main 2>&1)
echo "push-exit=$?"
printf '%s\n' "$out" | sed -n 's/^ ! \[rejected\] *//p'
git fetch -q origin
bash ../remote-audit.sh origin
echo "exit=$?"
Output:
remote=origin
BRANCH UPSTREAM AHEAD BEHIND PUSH
docs/runbook - - - no-upstream
main origin/main 1 0 fast-forward
diverged=0
exit=0
push-exit=1
main -> main (fetch first)
remote=origin
BRANCH UPSTREAM AHEAD BEHIND PUSH
docs/runbook - - - no-upstream
main origin/main 1 1 diverged
diverged=0
exit=0
The report is assembled entirely from local refs. git for-each-ref walks refs/heads once and hands back each branch beside its configured upstream, so the script never has to parse git branch -vv or guess at names; a branch with no upstream comes back with an empty second field and is reported as such rather than skipped silently. For the rest, two counted ranges give the two numbers everyone actually wants -- upstream..branch is what you have that the upstream does not, and branch..upstream is the reverse -- and the verdict is a single question about the second number.
That structure is why the script is fast and safe to run anywhere. It opens no connection, so it works on a train, and it writes nothing, so a nightly job cannot damage a working tree. Reading the raw ref database rather than command output also means the format does not shift on a Git upgrade, the usual reason a homegrown status script quietly starts reporting nonsense.
It is also close to the right tool. In a pre-push hook it catches the everyday case where you have drifted behind a branch you were about to push to; run after git fetch --all --prune in a nightly job, the table is an accurate picture of the repository. The two commands it needs beside it are the two it does not run.
Which is the flaw. Every number in the table comes from $up, a remote-tracking ref, and the script never asks whether that ref is current. The first run reports fast-forward for main with confidence, and the push made three lines later is refused with fetch first -- the audit was reading a needle set before Dana's push existed. A one-line fix restores the guarantee: compare git ls-remote "$remote" "refs/heads/$br" against git rev-parse "$up" and label the row unknown when they differ, or run git fetch --prune first and accept the latency. The second flaw is visible in the same output. The row after the fetch correctly says diverged, and diverged=0 is printed anyway, and the script exits 0: the while loop runs in a subshell because it sits on the right of a pipe, so every increment is discarded when that subshell ends. Any CI job gating on this exit status passes unconditionally. Feed the loop with a process substitution or git for-each-ref into a here-string instead. Two smaller gaps: the existence check reads remote.$remote.url from configuration, so a remote whose URL is a typo passes it, and the header says remote=origin while the rows report whatever upstream each branch names -- after a stray git push -u mirror main that is a different server, and nothing says so.
Common Mistakes
- Reading
origin/mainas the server's current state. It is a local file recording what the server said the last time you asked. Nothing on the server can move it. Every ahead-and-behind number ingit status, every range likeorigin/main..HEAD, and every dashboard built on them inherits the age of your last fetch.
- Treating a failed pull as a no-op. The fetch half ran before the integration was attempted, so your remote-tracking refs moved even though the command exited non-zero. Re-reading
git statusafter a failed pull and finding different numbers is not a bug, and re-running the pull is not idempotent in the way people assume.
- Reaching for
--forcewhen a push is refused. The refusal means the server holds a commit you do not. Force does not resolve that; it discards it. Integrate first, and when a rewrite genuinely has to be published, use--force-with-leaseso the push fails if the server moved since your last fetch.
- Letting a bare
git pullchoose the integration. On a diverged branch modern Git refuses and asks you to pick, and the temptation is to answer with whichever flag ends the message. Decide once per repository withpull.rebaseorpull.ff, or your history will record which flag you were in the mood for.
- Running
git push -uat a second remote. The-urewritesbranch.<name>.remoteandbranch.<name>.merge, so a singlegit push -u mirror mainsilently repoints@{u}, every baregit push, and every ahead-behind figure at the mirror. Use-uon the first push of a branch and not again.
- Expecting a plain fetch to remove deleted branches. Fetch adds and updates refs; it never deletes them. A branch merged and deleted on the server lives on in your
refs/remotesuntil--pruneruns, and stale entries makegit branch -ruseless and range comparisons misleading.
- Thinking
git branch -d -r origin/topicdeleted anything on the server. It deleted your cached copy, which the next fetch restores. Deleting the real branch isgit push origin --delete topic, which is a request the server may refuse for its own reasons.
- Assuming a push carried your tags.
git pushsends branches. A tag you created locally stays local untilgit push --tagsor--follow-tagssends it, which is why a release tag is so often missing from the server while the release commit is present.
- Assuming
git fetchupdated every remote. With no argument it updates one remote, the current branch's, not all of them. A repository with anoriginand anupstreamneedsgit fetch --all, and the fork-versus-parent confusion that follows from forgetting is the most common reason a comparison againstupstream/mainreports nonsense.
Best Practices
- Fetch before you reason. Any conclusion drawn from
origin/*is a conclusion about the past, and a fetch costs a second.
- Set
fetch.prune trueand one ofpull.ff onlyorpull.rebase truein every repository you keep for more than a week. Two lines of configuration remove two whole classes of surprise.
- Prefer
--force-with-leaseto--forcewithout exception, and confine either to branches nobody else builds on. The lease is the difference between publishing a rewrite and deleting a colleague's commit.
- Ask the server directly with
git ls-remotewhenever a decision matters more than a second of latency. It is the only ordinary command that reports the present.
- Pass a refspec explicitly when you want refs filed somewhere other than the default namespace. Mirrors, release-tracking clones, and one-off fork comparisons are all one argument, not a new tool.
- Set an upstream once, with
-uon a branch's first push, then checkgit config --get branch.<name>.remoteafter adding any second remote.
- Treat remote names as configuration.
originis a default that exists only insidegit clone; name a mirrormirrorand a fork's parentupstreamand the intent of every later command reads itself.
- Push tags deliberately, with
--follow-tagson release pushes and never as an implicit side effect. A tag is a promise about a specific commit, and a promise nobody can fetch is not one.
Practice Exercises
- Build the depot and prove the needle is stale. Create a bare repository, two clones, and one commit pushed from the first clone. From the second, report
git rev-list --count origin/mainand the result of comparinggit ls-remote origin mainfield 1 againstgit rev-parse origin/main, both before and after a fetch. Then explain, in one sentence each, which ofgit status,git log origin/main..HEADandgit ls-remoteneeded the network.
- Earn both refusals. Reproduce
fetch firstandstale infoin the same repository and say precisely which condition each one tested. Then, on a throwaway copy, recordgit rev-list --count origin/main, rungit push --force, and record it again. Report the difference and name the commit that stopped being reachable.
- Fix the audit. Give
remote-audit.sha freshness check that labels a rowunknownwhengit ls-remotedisagrees with the cached ref, and move the loop out of the pipeline sodivergedsurvives. Rerun the scenario from the example and show the report ending indiverged=1with exit status 1. Then say why the pipeline version could never have worked, in terms of which process held the variable.
- Bend the refspec. Fetch the depot's
mainintorefs/remotes/snapshot/mainwith an explicit refspec and confirmremote.origin.fetchis unchanged. Add a second remote, push a branch to it with-u, and reportbranch.main.remotebefore and after. Restore the original upstream withgit branch --set-upstream-toand prove@{u}resolves where you expect by reporting both counted ranges against it.