Git Hour 7: Deep Troubleshooting and History Recovery
How to check and save when an accident occurs: GIT_TRACE to see clearly what Git is doing, reflog to retrieve "lost" commits, bisect binary positioning regression, filter-repo to clear secrets, fsck to repair damage, line breaks and case, performance and network issues
Git 2.56(2026-09)reflog · bisect · fsckgit-filter-repo 2.47Verified according to official documents · 2026-11
overall learning objectives
build a setRepeatable troubleshooting methods: Reproduce first, then narrow down the scope, then look at the evidence; know how to use itGIT_TRACE、GIT_TRACE_PACKET、GIT_CURL_VERBOSE/GIT_TRACE_CURL、GIT_SSH_COMMAND="ssh -v" with git config --show-origin --show-scope --listGet the evidence.
understand"Commits are almost never truly lost": branches are just pointers,reset --hardAfter deleting branches and discarding stash, the objects are still in the object library; you can usegit reflog、ORIG_HEAD、git fsck --lost-found / --unreachableRetrieve and know the expiration strategy of reflog and gc.
use git bisect(Handmade good/bad,skip、bisect runautomation,--first-parent) locates the commit that introduced the regression within log₂N steps.
inRotate secrets firstUnder the premise, usegit filter-repo(--invert-paths、--replace-text、--sensitive-data-removal) rewrite history, force push, notify collaborators to synchronize, and know how platform cache and PR references are handled; can compare filter-repo, BFG and filter-branch.
use git fsckDiagnose repository damage, restore objects from other clones, rebuild damaged indexes; handle newlines (.gitattributes、--renormalize), case-insensitive file systems, file permissions, long paths and UTF-8 file name issues.
Diagnosis is slowstatus(fsmonitor, untracked cache), slow fetch/clone (protocol v2, partial clone), and HTTP 413 / RPC failed / proxy and TLS issues, identifiedhttp.postBufferMisunderstanding.
10 tabs per module Principles · Diagrams · Animations · Commands · Experiments · Production Examples · Troubleshooting · Tests · Voice · Videos. The troubleshooting lesson suggests "break it first, then fix it": it can be used in every experimentbootstrap-git-lab.sh --forceRebuild in one second.
learning progress A test score ≥ 70% or clicking "Mark this module complete" will be counted as progress and saved in this browser (it will be cleared after refreshing when local storage is disabled).
Chinese voice The "Voice" tab uses the built-in Web Speech API (zh-CN) of the browser to read the explanation script; if there is no Chinese voice package, the explanation script can still be read or handed over to the TTS tool.
Safety firstThe "break" operation in this lesson (reset --hard, delete branches, damage objects, rewrite history, force push)only in~/git-labDo it in the practice repository below. Make a complete backup before troubleshooting the real repository:git clone --mirroror directlycp -a repo repo.bak(The latter is retained along with reflog, stash, and uncommitted changes).
Release NotesThis lesson is based onGit 2.56(2026-09) is the baseline, and most commands are available above 2.40:git bisect runThe exit code 125 is agreed upon,reflog with fsck --lost-foundIs a long-term stable feature; built-in fsmonitor daemon (core.fsmonitor=true) available on Windows and macOS since 2.37; protocol v2 is the default since 2.26;git add --renormalizeAvailable since 2.16.git-filter-repoIt is an independent tool (not distributed with Git). This lesson uses its latest version.2.47.0Writing, GitHub documentation requirements--sensitive-data-removalAt least 2.47. The default reftable reference store in Git 3.0 plan will change the reflogStorage method(no longer.git/logs/text file under), butgit reflogThe command usage remains unchanged - refer to git-scm.com/docs/BreakingChanges. The terminal output in the courseware: bootstrap and bisect are the actual results of running on Git 2.51 (the hashes are the same for everyone), and the rest are examples.
Module 0 · Preparation: Fault Injection into the Repository (Completed before class)
Rebuild the bootstrap repository of Lesson 1 and regenerate the regression commit sequence release/1.2 and bisect check script dedicated to this lesson.
Before class ≈ 6 minutesGit ≥ 2.40 (2.56 recommended)Local only, no cloud account required
Prerequisites
CompletedLesson 1(Object model: blob/tree/commit, branches are pointers) andLesson 2(merge / rebase / remote-tracking branch); understandLesson 6Partial cloning with sparse calling would be better.
Environment: Ubuntu 24.04 (Azure VM or WSL) / macOS / Windows Git Bash. All scripts in this lesson are POSIX shells.
Module 4 requiredgit-filter-repo(Python 3 script), see step 3 below for the installation method.
Step 1: Rebuild the practice repository
Lesson 1 Module 0 ofbootstrap-git-lab.shwill generate~/git-lab/myapp(12 commits, 4 branches, tagsv1.0.0/v1.1.0, false secrets committed by mistakeFAKE_SECRET), local bare repository~/git-lab/remote/myapp.git(acts as origin) and teammates clone~/git-lab/teammate. This lesson will intentionally "break" a lot of things, so first use--forceRebuild to clean state:
If you don't have this script yet, please go back toLesson 1 Module 0 Step 3Copy and save as~/bootstrap-git-lab.sh。
Step 2: Generate the regression commit sequence for this lesson (setup-part7.sh)
Script fromv1.1.0pull outrelease/1.2, make 10 commits: one of them (disguised as a "refactor") puts/healthzThe return fields fromstatuschanged toStatus, causing the load balancer probe to fail - this is what M3 is trying to find out with bisectReturn;awipCommit the function signature is broken (Unable to test, practiceskip); there is also one merged from the side branchfeature/metrics(PracticeCross-mergetwo points). Check script~/git-lab/check-healthz.shput in repositoryoutside, so that it exists when bisect switches to any historical commit.
#!/usr/bin/env bash
# setup-part7.sh - Lesson 7: Generate regression commit sequence release/1.2 on bootstrap repository with bisect check script
# Usage: bash ~/bootstrap-git-lab.sh --force && bash setup-part7.sh
set -euo pipefail
LAB="${LAB:-$HOME/git-lab}"; REPO="$LAB/myapp"
[ -d "$REPO/.git" ] || { echo "$REPO not found, please run first: bash ~/bootstrap-git-lab.sh"; exit 1; }
cd "$REPO"
export GIT_AUTHOR_NAME="Git Lab" GIT_AUTHOR_EMAIL="lab@example.com"
export GIT_COMMITTER_NAME="Git Lab" GIT_COMMITTER_EMAIL="lab@example.com"
T=1767603600 # 2026-01-05 09:00:00 UTC
tick(){ T=$((T+3600)); export GIT_AUTHOR_DATE="@$T +0000" GIT_COMMITTER_DATE="@$T +0000"; }
g(){ git -c commit.gpgsign=false -c core.autocrlf=false "$@"; }
git rev-parse -q --verify v1.1.0 >/dev/null || { echo "Missing tag v1.1.0, please rebuild with bootstrap --force"; exit 1; }
g switch -q -C release/1.2 v1.1.0
c(){ g add -A; tick; g commit -q -m "$1"; }
cat >> app.py <<'PY'
@app.route("/version")
def version():
return {"version": "1.2.0-dev"}
PY
c "feat: add /version endpoint"
echo '- GET /version' >> README.md; c "docs: document /version"
sed -i.bak 's/port=6379,/port=int(os.getenv("REDIS_PORT", "6379")),/' app.py && rm -f app.py.bak
c "refactor: read REDIS_PORT from env"
g switch -q -c feature/metrics
echo '# metrics stub' > metrics.py; c "feat(metrics): add metrics module"
echo 'METRICS_ENABLED = True' >> metrics.py; c "feat(metrics): enable flag"
g switch -q release/1.2
sed -i.bak 's/^def healthz():/def healthz(:/' app.py && rm -f app.py.bak
c "wip: split routes (does not start)"
sed -i.bak 's/^def healthz(:/def healthz():/' app.py && rm -f app.py.bak
c "fix: restore healthz signature"
sed -i.bak 's/"status": "ok"/"Status": "ok"/' app.py && rm -f app.py.bak
c "refactor: normalize response payloads"
sed -i.bak 's/gunicorn==23.0.0/gunicorn==23.0.1/' requirements.txt && rm -f requirements.txt.bak
c "chore: bump gunicorn"
tick; g merge -q --no-ff feature/metrics -m "Merge branch 'feature/metrics' into release/1.2"
printf '# Changelog\n\n## 1.2.0 (unreleased)\n- /version endpoint\n' > CHANGELOG.md; c "docs: add CHANGELOG"
echo '- GET /metrics (stub)' >> README.md; c "docs: mention /metrics"
g switch -q main
g branch -q -D feature/metrics
# The checking script used by bisect is placed outside the repository: it can be run on any historical commit.
cat > "$LAB/check-healthz.sh" <<'SH'
#!/usr/bin/env bash
# Exit code: 0 = good, 1 = bad, 125 = cannot be tested (git bisect run will automatically skip)
grep -q '^def healthz():' app.py || exit 125 # Even the function of this commit is broken and cannot be judged
grep -q '"status": "ok"' app.py # Load balancer probe requires lowercase status
SH
chmod +x "$LAB/check-healthz.sh"
echo "== release/1.2 has been generated; bisect check script: $LAB/check-healthz.sh"
g log --oneline --graph release/1.2 ^v1.0.0
Why is the hash the same for everyone?Like bootstrap, the script fixes the author and time (+1 hour per commit from 2026-01-05 10:00 UTC) and uses-c core.autocrlf=falseEnsure that the bytes stored in the repository on Windows are also LF. As long as you execute it firstbootstrap --force,18635feIt's the "first bad commit" in your repository. in scriptg add -AAll untracked files in the workspace will be committed together, so be sure to start from a clean bootstrap repository.
Step 3: Install git-filter-repo (used by module 4)
Platform
Recommended installation method
Description
Any (recommended)
pipx install git-filter-repo
Get the latest version (2.47.0) on PyPI; requires Python ≥ 3.6 and Git ≥ 2.36 (subject to project INSTALL.md)
macOS
brew install git-filter-repo
Homebrew usually follows the latest version
Ubuntu 24.04
sudo apt install git-filter-repo
The release repository may have an older version (less than 2.47)--sensitive-data-removal), use pipx instead when this parameter is required
Windows(Git Bash)
py -m pip install --user git-filter-repoor scoop
Confirmgit-filter-repoThe directory is in PATH; it is itself a Python file
installed package git-filter-repo 2.47.0, installed using Python 3.12.3
These apps are now globally available
- git-filter-repo
done! ✨ 🌟 ✨
a40bce548d2c
--versionThe build hash is printed instead of "2.47.0", which is normal; usepipx listorpip show git-filter-repoView the release version number.
Warm-up: Answer intuitively (30 seconds)
execute git reset --hard HEAD~3Afterwards, were those 3 commits deleted?
No.resetjust putPointer to the current branchMove back 3 commits; all three commit objects are still there.git/objects, and is referenced by reflog, it will not be cleaned by gc for at least 30 days by default. That’s all the basics of Module 2. What is really likely to be lost isWorkspace changes that have never been committed——reset --hardwill directly overwrite them, and that part of Git cannot be saved (unless it has beengit addOver, see the dangling blob of M2).
One of the 1000 commits introduces a bug, how many tests does it take to find it?
Binary search: ⌈log₂ 1000⌉ =10 times. this isgit bisectThe power, cooperationbisect runDon’t even do these 10 times manually (M3).
If I revert the commit containing the password and push it again, will the password be safe?
Not safe. revert just adds a "reverse" commit, the old commit is still in the history, anyonegit log -pEverybody can see it. The correct order is:Rotate/revoke password first(This step truly eliminates the risk), and then use filter-repo to rewrite history (M4) if necessary.
Module 1 · Troubleshooting Methodology and GIT_TRACE
00:00 – 06:00 · Protect the scene first, then collect evidence: the trace variable that comes with Git can tell you which subcommand it executed, which configuration it read, and what it said to the server
Press "Protect the scene → Reproduce → Reduce the scope → Obtain evidence → Repair → Prevention"Six steps to deal with any Git problem, the first step is always to back up and pause automatic gc.
Choose the correct trace variable based on the symptoms:GIT_TRACE(what was executed),GIT_TRACE_PACKET(agreement dialogue),GIT_TRACE_CURL/GIT_CURL_VERBOSE(HTTP layer),GIT_SSH_COMMAND="ssh -v"(SSH layer),GIT_TRACE2_PERF(time consuming).
use git config --show-origin --show-scope --listAnswer "Who set this configuration?"
Prerequisite knowledge:Lesson 1 configuration hierarchy (system/global/local).Importance:★★★★☆ (Each subsequent module uses these tools to collect evidence)
What: Six-step method for troubleshooting Git
steps
things to do
Specific actions in Git
① Protect the scene
Prevent "rescue" from destroying evidence and recoverable objects
cp -a repo repo.bak(Including reflog, stash, index, uncommitted changes);git config gc.auto 0Pause automatic gc;Don'tanxiousgit gc --prune=now, re-clone and overwrite the original directory
② Recurrence
Confirm that it can be triggered stably
Write down the complete command and complete error report;git --version、git version --build-options
③ Narrow down the scope
Local machine or server? This repository or all repositorys? Is this configuration still the default value?
git -c key=value …temporary coverage;GIT_CONFIG_NOSYSTEM=1、GIT_CONFIG_GLOBAL=/dev/nullExclude system/global configuration; try a new clone
Prefer non-destructive commands (git branch rescue <sha>"Pin" the commit first); back up again before destructive operations
⑥ Prevention and review
Let the same thing never happen again
Configure baselines, hooks, platform rules, and documentation;git bugreportGenerate reports that can be committed to upstream
Why: Why should we “protect the scene” first?
Most "disasters" in Git can be recovered because the objects remain in the object repository until they are cleaned up by gc. There are three enemies of recoverability: ①automatic gc(Some commands will trigger at the end ofgit gc --auto, possibly packaging and cleaning up unreachable objects after the grace period); ②Cover working tree(reset --hard、checkout -- .、clean -fdChanges that have never entered the object library will be lost); ③delete entire directoryRe-clone (local reflog, stash, and unpushed branches are all lost). So the first step is always to back up.
How:trace variable family
variable
Answered questions
Typical scenario
GIT_TRACE=1
What internal commands were executed by Git, what aliases were expanded into, and which subprocesses were started (ssh, credential helper, hook)
Alias or hook misbehaving; "Which ssh/credential helper did it call?"
GIT_TRACE_PACKET=1
pkt-line protocol messages between client and server (capabilities, referral notifications, want/have)
fetch/push stuck, missing references, protocol version issues
GIT_TRACE_CURL=1
HTTP request/response headers and data (defaultDesensitizationAuthorization and Cookies)
401/403/413, proxy, redirect, TLS handshake
GIT_CURL_VERBOSE=1
libcurl's own detailed log (older variables, information similar to above)
When comparing with old documents and old scripts
GIT_SSH_COMMAND="ssh -v"
SSH layer: which key is used, which configuration, host key verification
Permission denied (publickey), wrong key selected, port blocked
GIT_TRACE2_PERF=1 / GIT_TRACE2_EVENT=…
The time consumption of each stage (region), sub-process, and configuration; EVENT outputs JSON to facilitate machine analysis
Repository discovery and GIT_DIR, which packs were visited, shallow clone boundaries
"Why does Git think I'm not in the repository", shallow cloning problem
The values of these variables can be1/true/2(output to stderr),3–9(output to the corresponding file descriptor), orabsolute path(Append writes to file, suitable for collection in CI). All trace output goes to stderr and will not cause pollution.git logWait for the stdout result of the command.
When: Configuration source troubleshooting
Git configuration has multiple layers: system (/etc/gitconfig, Git for Windows inC:/Program Files/Git/etc/gitconfig)→ global(~/.gitconfigor~/.config/git/config)→ local(.git/config) → worktree → command line-c,What is read later overwrites what is read first;include.path/includeIfOther files will also be imported. There is only one reliable answer to "Where does this value come from":
git config --show-origin --show-scope --list # List all configurations and their files and levels
git config --show-origin --get-all core.autocrlf # Every source of a certain key (list all if there are multiple values)
git config list --show-origin # New subcommand writing method for 2.46+, equivalent
Common misunderstandings① "When trace is turned on, the output is too much to understand" - use2>trace.logSave it for latergrepkeyword (run_command、packet:、HTTP/). ② "The trace log can be directly posted to the work order"——GIT_TRACE_CURLDefault desensitized authentication header (GIT_TRACE_REDACTenabled by default), butGIT_TRACE_PACKETIt will contain information such as reference name, repository path, etc. Please check it yourself before sharing. ③ "git config --listThe last line in is the effective value" - this is roughly true for single-value keys, but multi-value keys (such ascredential.helper、remote.origin.fetch) will all take effect, empty valuehelper =The previous list will also be cleared.
Figure 1-1 Oncegit fetchThe layers passed through, and the trace tools corresponding to each layer
Figure 1-1 Check layer by layer from top to bottom: Each layer has a corresponding "perspective mirror"
Figure 1-2 Six-step troubleshooting method (loop)
Figure 1-2 Step ① is the easiest to skip, but it determines whether it can be recovered later.
Interaction: Select the trace tool by symptom to preview the output you will see
Click on a symptom, and the animation will highlight the variables that should be opened, the commands executed, and the most critical lines of the output (the output is in the typical format of Git 2.5x, and the timestamp and path are examples).
command
Select a symptom →
What to see first
Core commands and parameters
Command/Variable
function
Description
GIT_TRACE=1 git <cmd>
Universal tracking
show built-in、run_command、exec, alias expansion; you can also writeGIT_TRACE=/tmp/t.log
GIT_TRACE_PACKET=1
protocol message
Each line is shaped likepacket: fetch< …(< received, > sent)
GIT_TRACE_CURL=1、GIT_TRACE_CURL_NO_DATA=1
HTTP details
The latter only looks at the head and not the data;GIT_TRACE_REDACT=0Desensitization can be turned off (only when debugging on this machine)
GIT_SSH_COMMAND="ssh -v"
SSH details
-vvvMore detailed; also configurablecore.sshCommand
Architecture, SHA implementation, libcurl / OpenSSL version
git bugreport
Generate problem report
Collect version, system, enabled hooks, etc., writegit-bugreport-*.txt(You will be prompted to add the steps to reproduce)
cd ~/git-lab/myapp
git config alias.st "status -sb"
GIT_TRACE=1 git st
10:02:11.410211 git.c:758 trace: exec: git-st
10:02:11.410290 run-command.c:673 trace: run_command: git-st
10:02:11.410912 git.c:422 trace: alias expansion: st => status -sb
10:02:11.410935 git.c:806 trace: exec: git status -sb
10:02:11.410951 run-command.c:673 trace: run_command: git status -sb
10:02:11.413120 git.c:502 trace: built-in: git status -sb
## main...origin/main
Pronunciation: First try to find the namegit-stThe external command is not found and then expand the alias.st => status -sb, and finally execute the built-in commandstatus. This can be seen at a glance when troubleshooting "alias does not take effect" or "a script with the same name on PATH is preemptively executed".
GIT_TRACE_PACKET=1 git fetch origin 2>&1 | head -14
first lineversion 2Indicate that both parties use protocol v2 (M7);fetch=… filterNote that the server supports partial cloning; the client usesref-prefixOnly request the references you need. If the server only responds with a v0-style reference list, it means that it or the intermediary proxy does not support v2.
system file:C:/Program Files/Git/etc/gitconfig http.sslbackend=openssl
system file:C:/Program Files/Git/etc/gitconfig core.autocrlf=true
system file:C:/Program Files/Git/etc/gitconfig credential.helper=manager
global file:C:/Users/azureuser/.gitconfig core.autocrlf=input
How to verify:When the same key appears multiple times, for single-value keyslast line(This is globalinput) takes effect and is availablegit config --get core.autocrlfConfirm.Common mistakes:in the repositorygit config core.autocrlf falseLater I thought the overall situation had changed.Production use:Set up in CIGIT_TRACE2_EVENT=/tmp/git-trace.jsonAnd upload it as the construction product, and analyze the slow clone afterwards.
Lab 1: Answer three questions using trace and configuration sources (~4 minutes)
Habitual actions to protect the scene(Also do this before troubleshooting the real repository):
cd ~/git-lab
cp -a myapp myapp.bak # Back up together with .git, reflog, stash, and uncommitted changes
git -C myapp config gc.auto 0 # Pause automatic gc during troubleshooting (use --unset to resume after completion)
Question 1: Mygit stWhat exactly was executed?
cd ~/git-lab/myapp
git config alias.st "status -sb"
GIT_TRACE=1 git st 2>&1 | grep -E "alias|built-in"
Question 2: Which protocol version was used when fetching, and which references were requested?(Local files and remote files also use the upload-pack protocol)
Case 1: In the same repository, only a colleague clone reported SSL certificate problem
Symptoms:fatal: unable to access '…': SSL certificate problem: unable to get local issuer certificate。Evidence collection:git config --show-origin --list | grep -i sslfound his~/.gitconfigThere's an old line in ithttp.sslCAInfo=/old/path/ca.pem, overriding the system default CA package;GIT_TRACE_CURL=1visible inCAfile: /old/path/ca.pem。Fix:Remove this line and the enterprise TLS inspection environment uses the system certificate store instead (Windows:http.sslBackend schannel)。Lessons:"My machine is the only one that doesn't work." First check the configuration source.
Case 2: fetch occasionally gets stuck for 10 minutes in CI
Evidence collection:Set up in pipelineGIT_TRACE2_EVENT=$RUNNER_TEMP/trace2.json with GIT_TRACE_PACKET=$RUNNER_TEMP/packet.logAnd upload it as a product. The time it got stuck showed that negotiation sent thousands of lines.have--A large number of expired remote-tracking references accumulate in the cached workspace.Fix:fetch.prune=true, regularly clean the cache workspace, and use--depth/--filterFresh clones of (Lesson 5).
Case 3: Alias fails “randomly”
Symptoms:Developer'sgit syncBehavior is different in some directories.Evidence collection:GIT_TRACE=1 git sync show trace: exec: git-syncBy a third-party tool in PATHgit-syncExecutable files are executed first; in other directories,.git/configDifferent aliases with the same name are defined in .Fix:The alias is renamed, and the team agrees that the alias should be placed in the global configuration.
Common errors and solutions
GIT_TRACE is set but nothing is output
Reason:Windows cmd is written asGIT_TRACE=1 git …(That's POSIX syntax); PowerShell requires$env:GIT_TRACE=1;Or the output is redirected to a file path but using a relative path (Git only accepts absolute paths, otherwise it will warn and ignore).
# Git Bash / Linux / macOS
GIT_TRACE=1 git status
# PowerShell
$env:GIT_TRACE=1; git status; Remove-Item Env:GIT_TRACE
warning: unable to access '/home/u/.config/git/attributes': Permission denied
Reason:Run Git as another user (such as sudo or service account), and HOME still points to the original user directory.Diagnosis:git var -l | grep -i config、echo $HOME。Fix:use sudo -HOr correctly set the HOME of the service account; do not use sudo to operate the personal repository.
fatal: detected dubious ownership in repository at '/srv/repo'
Reason:Security check since 2.35.2: The owner of the repository directory is different from the current user (common for container mounted volumes, shared directories, CI caches).
ls -ld /srv/repo /srv/repo/.git
GIT_TRACE_SETUP=1 git status 2>&1 | head
Fix:Preferred Modified Ownership (chown); after confirming the trustworthiness,git config --global --add safe.directory /srv/repo(Don’t write it by hand*)。
I see Authorization: Basic <redacted> in the trace log. I suspect that the credentials are wrong but I can’t see them.
Description:Desensitization is intentional. Check the source of username and credentials with:
printf 'protocol=https\nhost=github.com\n\n' | git credential fill | sed 's/^password=.*/password=***/'
git config --show-origin --get-all credential.helper
In the trace output, I see that the configuration value is not as expected, but it is clearly written correctly in .git/config
Reason:environment variablesGIT_CONFIG_COUNT/GIT_CONFIG_KEY_0/GIT_CONFIG_VALUE_0orGIT_CONFIG_PARAMETERS(-cpassed to the child process) overwrites the file configuration; CI platforms often inject like thishttp.extraheader。
env | grep ^GIT_
git config --show-origin --show-scope --get-all http.extraheader # scope is displayed as command
Command line operation questions1. Want to seegit pushHow to write the status code of HTTP request, but I don’t want to see the uploaded data content?
Scenario analysis questionsA colleague said, "git pull suddenly asked me to enter my password. It was fine yesterday." How would you check according to the six-step method?
① On-site: non-destructive, do not move the credentials first. ② Recurrence:git pullLog the full prompt (is it an HTTPS username and password prompt or an SSH passphrase?). ③ Narrow down the scope:git remote -vCheck whether the URL has been changed to HTTPS; whether other repositories are normal;git config --show-origin --get-all credential.helperSee if the assistant is configured by a certain configuration (such as a new system configuration orhelper =empty value) is cleared. ④ Obtain evidence:GIT_TRACE=1 git pullSee if it is calledgit credential-manager;For HTTPSGIT_TRACE_CURLSee 401; use SSHGIT_SSH_COMMAND="ssh -v"See which key is provided. ⑤ Repair: Restore helper or log in to GCM again / restore SSH URL. ⑥ Prevention: token expiration reminder, team documentation describing helper configuration location.
This courseware cannot directly generate videos/MP3s. Storyboards and explanation scripts have been provided, which can be generated by video tools.
Shot 1 · 0–15s Screen: The terminal reports an error "fatal: ...", and the red "Re-Clone" button next to it has been crossed out and replaced with a green one.cp -a repo repo.bak。 Narrator: The first step in troubleshooting is not to repair, but to protect the site: back up and pause automatic gc.
Shot 2 · 15–40s Screen: Five layers of cake (configuration, subprocess, protocol, HTTP/SSH, server), with the corresponding environment variables lighting up next to each layer. Narrator: GIT_TRACE looks at what was executed, GIT_TRACE_PACKET looks at the protocol conversation, GIT_TRACE_CURL looks at HTTP, ssh minus v looks at the key, trace2 looks at the time taken.
Shot 3 · 40–60s Screen:git config --show-origin --listOutput, the same autocrlf appears twice, and the latter line is highlighted. Narrator: Configuration is hierarchical, and the ones read later overwrite the ones read first. "Who set it up?" Just ask show-origin.
Shot 4 · 60–75s Screen: Six-step circular diagram, with arrows going from "obtaining evidence" back to "narrowing down the scope". Narrator: When the evidence overturns the hypothesis, go back to the previous step. In the next module, we use reflog to rescue "lost" commits.
06:00 – 14:00 · Branches are just pointers. If the pointer is moved, the commit is still there; the reflog records every pointer movement, which is your “undo history”
8 minutesreflog · ORIG_HEAD · fsck --lost-foundreflog is local only and will not be pushed or cloned★★★★★
learning objectives
Explain what reflog records (old value, new value, time, reason for each ref update), understandHEAD@{2}、main@{yesterday}、@{-1}、ORIG_HEAD。
Recovery after three typical incidents:reset --hardThrow away commit,branch -DDelete unmerged branches,stash drop/stash clearThrow away staging area.
use git fsck --lost-found / --unreachableRetrieve dangling commits and blobs that are not recorded in reflog; know the expiration strategy of reflog and gc, and "under what circumstances it is really impossible to recover".
Prerequisite knowledge:Object Model from Lesson 1, reset/rebase from Lesson 2.Importance:★★★★★ (This is the most memorable life-saving command in Git)
What: what is reflog
reflog(reference log)is Git for each reference (HEAD, each local branch,refs/stash, as well as remote-tracking branches) maintained bylocalMobile log. Whenever the value of a reference changes—commit, reset, checkout/switch, merge, rebase, pull, amend, cherry-pick—Git appends a record:
git reflog(= git reflog show HEAD) to display it in reverse order asHEAD@{n}:HEAD@{0}is the current value,HEAD@{1}It is the value before the last move... These writing methods can be used anywhere that needs to be committed:git show HEAD@{3}、git diff main@{1} main、git branch rescue HEAD@{2}。
Writing method
meaning
Example
HEAD@{n}
The value of HEAD before the nth move
git reset --hard HEAD@{1}: Undo the latest HEAD move
main@{n}
Main branch's own movement history (only changes to main are recorded)
git log main@{1}..main: What did the last pull bring?
main@{yesterday}、@{2.hours.ago}
Check by time (only look at the local reflog, not the commit time)
git diff main@{yesterday}
@{-1}
The last checked out branch (git switch -principle)
git merge @{-1}
ORIG_HEAD
Perform "dangerous operations" such as reset, merge, and rebasebeforeThe position of HEAD (only the latest one is saved)
git reset --hard ORIG_HEAD: Undo the reset/merge/rebase just now
Why: Why the commit "cannot be lost"
The commit is an immutable object in the object library; the branch and HEAD are just pointers to it.reset --hard, delete branches, rebase, amend are justMove or delete pointer, the object will not be deleted. Objects will only be deleted if they meet the following conditions at the same timegit gc/git pruneTrue deletion: ① cannot be removed from any refor any reflog entryArrival; ② The grace period has expired (gc.pruneExpire, default 2 weeks).
Configuration
Default value
meaning
gc.reflogExpire
90 days
point tostill reachableHow long to retain reflog entries for a commit
gc.reflogExpireUnreachable
30 days
point toThe current branch is unreachableHow long will the entries of the commit (for example, those that were reset) be retained?
gc.pruneExpire
2.weeks.ago
The minimum length of time an unreachable loose object must exist before it is allowed to be deleted
core.logAllRefUpdates
Non-bare repository true;bare repository false
Whether to write reflog for the branch - so the bare repository on the server side defaultsNo reflog
Conclusion: Commits that were reset, defaultat least 30 daysIt can be retrieved from the reflog; even if the reflog entry is gone, it can still be used before gc actually prunesgit fsckFind "dangling" objects.
How: Recovery paths for three accidents
accident
where is the evidence
restore
git reset --hard HEAD~2Lost 2 commits
ORIG_HEAD;git refloginreset: moving to HEAD~2the next line of
Branch your own reflogDelete with branch;But the output when deleting(was fd29861)and HEAD's reflog(checkout: moving from experiment to main) contains it
git branch experiment fd29861
git stash drop / stash clear
stash is a special merge commit, which is changed fromrefs/stashRemoved from the reflog and turned into a dangling commit; output when dropDropped refs/stash@{0} (abc1234…)
git stash apply abc1234;If you forget the hash, just usegit fsck --unreachable | grep commitLook for “WIP on…”
Regret after rebase/amend
ORIG_HEAD(before rebase);main@{1}
git reset --hard ORIG_HEAD
git addPassed but never committedreset --hard
Not committed butgit addContent has been written as blob
git fsck --lost-found → .git/lost-found/other/files in
When: When is it really impossible to save someone?
nevergit addWorkspace changes that have been made arereset --hard、checkout -- file、restore、clean -fdOverwritten or deleted - they never make it into the object library (only IDE local history or file system backup can be resorted to).
Executedgit reflog expire --expire=now --all && git gc --prune=now(This is exactly what the M4 was ordered to "clean up" after rewriting history).
Deleted the entire repository directory, or in anew cloneFind inside - reflog will not be cloned or pushed. The server-side bare repository does not have a reflog by default. Commits that are overwritten by force push on the platform need to be cloned from the platform (GitHub's event API/support team, Azure Repos' push records, etc.) or other people.
Common misunderstandings① “git log --allCan see the commits that were reset" - No,--allOnly look at refs; to usegit log -g(traverse the reflog) orgit log --reflog. ② "Recovery is to reset again" - Yes, but the safer way is to firstgit branch rescue <sha>"Pin" the commit and confirm it is correct before moving the branch. ③ "reflog records all my operations" - it only records changes in ref; changes in the workspace and staging area are not included.
Figure 2-1 After reset --hard: where do the branch pointer, ORIG_HEAD, and reflog point to?
Figure 2-1 reset only moves main; the two "discarded" commits are still referenced by reflog and ORIG_HEAD
Figure 2-2 Deleting branches and discarding stash: where are the clues?
Figure 2-2 After the branch is deleted, its own reflog disappears, but HEAD's reflog often leaves clues; after stash is discarded, fsck is used to find the hanging WIP commits.
Core Animation: reset --hard discards commits and then uses reflog to retrieve them
Observe three things step by step:main/HEAD pointer、ORIG_HEAD, right sidereflog entries(New entries are inserted at the top, allHEAD@{n}The number is then increased by 1). The commit hash is consistent with the rest of the courseware (a3c9e10, 7b2d4f1 are examples).
referenced by branchOnly referenced by reflog / ORIG_HEADDeleted by gcChanges in this step
HEAD is now at f4ac97b Merge branch 'hotfix/redis-timeout'
f4ac97b (HEAD -> main, tag: v1.1.0, origin/main) HEAD@{0}: reset: moving to HEAD~2
7b2d4f1 HEAD@{1}: commit: feat: add limited() helper
a3c9e10 HEAD@{2}: commit: feat: add rate limit config
f4ac97b (HEAD -> main, tag: v1.1.0, origin/main) HEAD@{3}: checkout: moving from release/1.2 to main
git show --stat ORIG_HEAD | head -5 # Confirm that it is the commit you are looking for
git branch rescue ORIG_HEAD # Pin first
git reset --hard rescue && git branch -d rescue
git log --oneline -3
commit 7b2d4f1c0e5a…19a0
Author: Azure User <azureuser@example.com>
Date: Sun Nov 15 09:00:00 2026 +0000
feat: add limited() helper
HEAD is now at 7b2d4f1 feat: add limited() helper
Deleted branch rescue (was 7b2d4f1).
7b2d4f1 (HEAD -> main) feat: add limited() helper
a3c9e10 feat: add rate limit config
f4ac97b (tag: v1.1.0, origin/main) Merge branch 'hotfix/redis-timeout'
Incident 2: Unmerged branch deleted
git branch -d experiment # Lowercase -d will reject: not fully merged
git branch -D experiment # Forced deletion of uppercase letters
git reflog show experiment # The reflog of the branch has been deleted.
git log -g --oneline --grep-reflog="experiment" | head -3 # But there are clues in the reflog of HEAD
error: the branch 'experiment' is not fully merged
hint: If you are sure you want to delete it, run 'git branch -D experiment'
Deleted branch experiment (was fd29861).
fatal: ambiguous argument 'experiment': unknown revision or path not in the working tree.
f4ac97b HEAD@{7}: checkout: moving from experiment to main
Note:checkout: moving from experiment to mainThe hash of this line isAfter movingmain(f4ac97b); the last commit of the experiment to look atPrevious article(earlier) record, or directly use the one printed when deleting(was fd29861). When the bootstrap script created the experiment, it committed fd29861 and then switched back to main, sogit log -g --oneline | grep -A1 "moving from experiment"The second line of output (the earlier one) is it.
Incident 3: stash was discarded and hash was forgotten
echo 'DEBUG = True' >> app.py
git stash push -m "debug toggle"
git stash drop # There is actually a hash in the output, assuming you didn’t see it
git fsck --unreachable | grep commit | cut -d' ' -f3 | xargs git log --merges --no-walk --oneline --grep=WIP --grep="On main"
Saved working directory and index state On main: debug toggles
Dropped refs/stash@{0} (c0ffee1d2b9b4f1e8a7c6d5e4f3a2b1c0d9e8f7a)
c0ffee1 On main: debug toggles
How to read:"dangling" = nothing points to it (dangling); "unreachable" = unreachable from refs (dangling objects and their ancestors). Defaultgit fsckTreat the reflog as a "reachable starting point", so commits that have been reset but are still in the reflogNoShown as dangling; to list them too, add--no-reflogs。
Experiment 2: Three disasters, three recoveries (~7 minutes)
Prepare: Start with a clean repository and make sure reflog is turned on.
Case 1: Forced push covered main, and the commits of three colleagues "disappeared"
After:A developer executes after rebasegit push --force origin main, covering three remote commits that it does not have locally.Recovery:The platform bare repository does not have reflog by default, but ① the colleague who just fetched it locallyorigin/main@{1}(Remote tracking branches also have reflog) It is the value before being overwritten; ② The pusher’s own output+ 1a2b3c4...5d6e7f8 main -> main (forced update)The first hash in is the old value; ③ Push records can be checked on the platform side (such as GitHub repository Activity view, Azure Repos push history). usegit push origin < old hash >:main --force-with-leaseMerge correctly after recovery.Prevention:Protected branches are prohibited from being forced to push (lessons 3 and 4). Personally use them by default.--force-with-lease --force-if-includes。
Case 2: All tests failed after interactive rebase
After:For developersrebase -i12 commits were merged, and a piece of code was mistakenly deleted when resolving the conflict. When I discovered it, I had already done amend twice.Recovery:git reflogfoundrebase (start)The line before (rebase -i (finish) with rebase (start)will be recorded),git diff <rebase ex > HEADLocate missing code,git checkout <rebase former > -- pathretrieve.Lessons:Before large rebasegit branch backup/feature-$(date +%s)。
Case 3: "Yesterday's commit not found" on CI machine
After:Someone wants to use reflog in the working directory of CI to retrieve the commits used for a certain build, but CI is a new clone every time and the reflog is empty.Method:The commit hash is already in the build record; as long as the object is still on the server (referenced by a ref or PR), it's OKgit fetch origin <sha>(Requires server permissionuploadpack.allowReachableSHA1InWant, GitHub/Azure Repos support fetching objects by hash).Lessons:reflog is a tool on the developer's personal machine, not an audit log.
Common errors and solutions
fatal: ambiguous argument 'HEAD@{1}': unknown revision or path not in the working tree.
Reason:① The newly cloned repository has only one reflog (clone) and noHEAD@{1};② In PowerShell@{…}Interpreted as a hash table literal.
git reflog | head -3
# Quotes in PowerShell
git show 'HEAD@{1}'
git reflog is empty / has only a few entries (on the bare server repository)
Reason:Bare repository defaultcore.logAllRefUpdates=false. Self-built Git server can be opened:git config core.logAllRefUpdates always(Later updates will be recorded). Hosting platforms do not have direct access to their reflog, and instead use platform audit/push logging or other clones.
error: The branch 'x' is not fully merged.
This is a protection not a bug.Confirm that the commits on the branch have been merged in other ways (squash/rebase merge) before-D;When unsure, firstgit log main..x --onelineView unique commits, orgit branch archive/x xKeep the name change.
No stash entries found. (But I clearly stash it)
Possible:① Stash in another worktree/another clone (stash belongs to the repository, but the worktree shares the same refs/stash); ② Has beenpop(Automatically deleted after application) - If there is a conflict during pop, stash will be retained; ③ is dropped/cleared.
Files that have never been added are lost after reset --hard
Bad news:These contents never made it into the object repository and Git cannot recover. Try IDE's Local History (VS Code Timeline, JetBrains Local History), OS's file versions/snapshots.Prevention:Before dangerous operationsgit stash -u; Get used to committing in small steps; usegit reset --keepinstead of--hard(Conflicting local changes will be rejected instead of overwritten).
Command line operation questions1. You just did it oncegit pull(Merge), I want to see what commits this pull has brought to main.
Scenario analysis questionsA colleague deleted a branch that was never pushed 2 months ago and now wants to get it back. Is there still hope?
There is little hope, but it is worth checking in order: ① The branch's own reflog has disappeared with deletion; the "moving from that-branch" entry in HEAD's reflog can be retained for 90 days if it points to a reachable commit, but the branch's unique commit is an unreachable object, and its reflog entry expires after 30 days by default; ② After expiration, the object becomes a dangling object.git gc(auto gc also fires) prune them after a grace period of 2 weeks. 2 months > 30 days + 2 weeks, there is a high probability that it has been cleared. You can still try:git fsck --lost-found --no-reflogs(If gc has never been triggered, it is still there), check whether it is.git/objects/packof cruft pack (git fsckThis will also be checked), backups/time machine snapshots, and whether it has been pushed to a personal fork or CI.
This courseware cannot directly generate videos/MP3s. Storyboards and explanation scripts have been provided, which can be generated by video tools.
Shot 1 · 0–20s Screen: Three dots are committed, the main label is on the far right; entergit reset --hard HEAD~2, the label "swooshes" back two spaces, and the two dots turn into dotted lines. Narrator: reset only moves the pointer. The two commits are still in the object library, but there are no branches pointing to them.
Shot 2 · 20–45s Screen: A "Logbook" is opened on the right, a new entry "reset: moving to HEAD~2" is inserted at the top, and all numbers below are incremented by one. Narrator: The reflog records every pointer move. HEAD at 1 is the position before the last move.
Shot 3 · 45–70s Screen: Inputgit branch rescue HEAD@{1}, the dotted line becomes solid again, and the rescue label is attached. Narrator: Pin first, then move main. ORIG_HEAD can also directly undo the reset just now.
Shot 4 · 70–90s Screen: Timeline: 30 days reflog expiration → 2 weeks grace period → gc cleaning; a workspace file next to it was erased and marked "Never added, cannot be restored". Narrator: It is difficult to throw away things that have been committed, but changes that have never been added are really dangerous.
14:00 – 21:00 · “It was fine last week” – Give Git a good commit, a bad commit and a judgment script that uses binary search to find the first bad commit in log₂N steps
7 minutesbisect run · skip · --first-parent★★★★☆
learning objectives
Explain the bisection principle of bisect and how it handles historical graphs (including merging), and estimate the number of steps required.
Skilled use start / good / bad / skip / reset / log / replay / visualize, and--term-old/--term-newCustom terms.
Write a check script that meets the exit code convention (0 / 1–127 / 125 / >127), usegit bisect runFully automatic positioning; used in histories with more mergers--first-parent。
Prerequisite knowledge:Lesson 2 Commit Graphs and Merges.Importance:★★★★☆ (I only use it a few times a year, but I save a few hours every time)
What: bisect does
git bisectdo between "known good" commits and "known bad" commitsbinary search: Each time you check out the commit in the candidate set that "splits the remaining commits in half", let you (or the script) judge whether it is good or bad, and then discard half of the candidates. final outputfirst bad commit--The first commit that caused the problem to arise.
Number of candidate commits N
Maximum number of tests ⌈log₂(N+1)⌉
Manual testing one by one
10
4
up to 10 times
1 000
10
Up to 1,000 times
100 000 (one year for a large monorepo)
17
Impossible
Why: Why not look at the code/log directly?
Regressions often come from "seemingly unrelated" changes (dependency upgrades, refactorings, configurations), which are difficult to find by reading the diff - the regression in this lesson is disguised asrefactor: normalize response payloads。
bisect givesevidence: A test passed before a certain commit but failed afterward. After finding it,git showThe reason can usually be seen, and both fixing and writing regression tests have clear goals.
How: State machine of a bisect
git bisect start <bad> <good>…:Git in.git/write downBISECT_START、BISECT_LOG、BISECT_TERMS and refs/bisect/bad、refs/bisect/good-*。
Candidate set = commits reachable from bad but unreachable from any good (git rev-list bad --not good…). Git selects the commit that balances both sides as much as possible and checks it out (detached HEAD).
you markgood / bad / skip, Git updates refs/bisect/* and selects the next one; print after excluding all<sha> is the first bad commit。
git bisect resetGo back to the branch you started with (orreset <commit>stay somewhere) and remove the bisect state.
Exit code convention for bisect run
Script exit code
understanding of bisect
Typical writing
0
good
Test passed
1–127(except 125)
bad
Test failed (most test frameworks return 1 on failure)
125
skip: This commit cannot be tested
Failed to compile, missing dependencies, crashes unrelated to this problem
Others (>127, if killed by signal; or negative number)
abortthe whole bisect
Errors in the script itself - avoid "build failure" being misjudged as bad
key details"Build failed" does not equal "buggy". If the check script returns 1 when compilation fails, bisect will treat a commit that just "cannot compile temporarily" as a first bad commit. The correct approach is:Build failed → exit 125,test failed → exit 1, of this lessoncheck-healthz.shThe first line does just that.
Merge with --first-parent
By default bisect will go into the merged side branch (this lesson'sfeature/metrics). If a commit on a side branch is based on old code, it may "look good" or "look bad" to mislead judgment; if the first bad commit is amerge commit, indicating that there is no problem on both sides individually, but the problem occurs only after the combination.git bisect start --first-parent(2.29+) Only follow the first parent of each merge, suitable for teams where "every commit on main is a PR merge": first locate which PR it is, and then divide it into two within the PR.
Custom term
What you are looking for is not necessarily a bug, but also "which commitfixeda problem" or "which commit made performance faster". Usegit bisect start --term-old=fast --term-new=slowThen you cangit bisect fast/slow;Built-inold/newIt can also replace good/bad to avoid the confusion caused by semantic inversion in "repair" scenarios.
When: when applicable
suitable for
Not suitable
Able to write deterministic judgments (tests, grep, response codes, performance thresholds); have known good versions (previous release tag)
The problem reappears randomly (flaky) - make the recurrence stable first, or run it repeatedly in the script N times; a large number of commits in the history cannot be built (too many skips will result in a list of "may be one of these commits")
Common misunderstandings① "bisect can only handle linear history" - can handle any DAG, and merging only affects the candidate set and judgment difficulty. ② “If you make a wrong step, you can only start over from the beginning”——git bisect log > bisect.txt, edit and delete the wrong line,git bisect resetaftergit bisect replay bisect.txt. ③ "Just put the check script in the repository" - bisect will check out the old commit. At that time, the script may not exist or be an old version; put it outside the repository (this lesson method) or copy it to/tmp。
Figure 3-1 History and candidate set of release/1.2 (good = v1.1.0, bad = release/1.2)
Figure 3-1 The candidate set is the commits "reachable from bad and unreachable from good"; commits on side branches will also be tested by default
Figure 3-2 The actual path of a bisect run (good = ee3c787, actual running result)
Figure 3-2 skip just excludes the commit from the "optional intermediate point" and will not make the result wrong - unless the answer itself is in the skipped commit
Core Animation: binary search on release/1.2
Mode A plays back the reality of this lesson’s repositorygit bisect run(good = ee3c787, bad = release/1.2). Mode B allows you to divide it into two parts by yourself: a regression is randomly hidden among the 16 commits. Click "good/bad" to complete the search and see how many steps you took.
goodbadskipCurrent checkoutExcluded
Core commands and parameters
command
function
Description
git bisect start [<bad> [<good>…]] [-- <paths>]
start
Bad and multiple good can be given at one time;-- pathOnly commits that change these paths will be considered;--first-parent;--no-checkout(Move onlyBISECT_HEAD, suitable for bare repository)
git bisect good|bad [<rev>]
Mark the current (or specified) commit
Also availableold/newor custom term
git bisect skip [<rev>|<range>]
Skip untestable commits
git bisect skip v2.5..v2.6Skip a range
git bisect run <cmd> [args]
Automation
Press exit code 0 / 1–127 / 125 / other to determine
git bisect visualize(view)
View remaining candidates
Equivalent when there is no graphical interfacegit log, can be added--oneline
git bisect log / replay <file>
Save/Replay
Steps to correct marking errors
git bisect terms
Show current term
cooperate--term-old/--term-new
git bisect reset [<commit>]
end
Return to the branch before starting by default
Manual bisection (first two steps)
cd ~/git-lab/myapp
git bisect start
git bisect bad release/1.2
git bisect good v1.1.0
~/git-lab/check-healthz.sh; echo "exit=$?"
status: waiting for both good and bad commits
status: waiting for good commit(s), bad commit known
Bisecting: 5 revisions left to test after this (roughly 3 steps)
[18635fe5abc8003dbce4884cf9f83a20a81a8b59] refactor: normalize response payloads
exit=1
git bisect bad
~/git-lab/check-healthz.sh; echo "exit=$?"
git bisect good
Bisecting: 2 revisions left to test after this (roughly 2 steps)
[7003fa206b5c9d8b088ad1fc9799e2ae0d5f5af5] refactor: read REDIS_PORT from env
exit=0
Bisecting: 0 revisions left to test after this (roughly 1 step)
[c84423e2e4523c8bde88c5aa2934bd8e72a8a9e3] fix: restore healthz signature
Test again c84423e (exit=0 →git bisect good), Git will report that 18635fe is the first bad commit. After completing be sure togit bisect reset。
Bisecting: 4 revisions left to test after this (roughly 2 steps)
[af9767e5baa1de59be0a21e9420ee4acf202da09] chore: bump gunicorn
running '/home/azureuser/git-lab/check-healthz.sh'
Bisecting: 2 revisions left to test after this (roughly 1 step)
[63c8ca9966407c0a5ae0fdd61ace62776ad398ff] wip: split routes (does not start)
running '/home/azureuser/git-lab/check-healthz.sh'
Bisecting: 2 revisions left to test after this (roughly 1 step)
[c84423e2e4523c8bde88c5aa2934bd8e72a8a9e3] fix: restore healthz signature
running '/home/azureuser/git-lab/check-healthz.sh'
Bisecting: 0 revisions left to test after this (roughly 0 steps)
[18635fe5abc8003dbce4884cf9f83a20a81a8b59] refactor: normalize response payloads
running '/home/azureuser/git-lab/check-healthz.sh'
18635fe5abc8003dbce4884cf9f83a20a81a8b59 is the first bad commit
commit 18635fe5abc8003dbce4884cf9f83a20a81a8b59
Author: Git Lab <lab@example.com>
Date: Mon Jan 5 17:00:00 2026 +0000
refactor: normalize response payloads
app.py | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
bisect found first bad commit
[c84423e2e4523c8bde88c5aa2934bd8e72a8a9e3] fix: restore healthz signature
[af9767e5baa1de59be0a21e9420ee4acf202da09] chore: bump gunicorn
[18635fe5abc8003dbce4884cf9f83a20a81a8b59] refactor: normalize response payloads
18635fe5abc8003dbce4884cf9f83a20a81a8b59 is the first bad commit
How to verify:The parent commit of the first bad commit should pass the check:git checkout -q 18635fe^ && ~/git-lab/check-healthz.sh; echo $? → 0。Common mistakes:forgetbisect reset, subsequent commits fall on the detached HEAD (git status"You are currently bisecting" will be displayed).Production use:Automatically run nightly regressions in CIbisect run, and paste the result into the alarm.
Experiment 3: Find regressions in three ways: manual, automatic, and mainline (about 6 minutes)
Confirm the phenomenon: v1.1.0 is good, release/1.2 is bad.
Manual two points: Complete the paging steps according to "Command", run the check script yourself and mark each step. encounterwip: split routesWhen the script returns 125, please manuallygit bisect skip. After completiongit bisect log > ~/bisect-manual.txt and git bisect reset。
Deliberately marked a wrong step and then corrected it:
git bisect start release/1.2 v1.1.0
git bisect good # Deliberately mark 18635fe as good (error!)
git bisect log > /tmp/b.txt
sed -i '$d' /tmp/b.txt # Delete the last line (wrong mark), macOS uses sed -i ''
git bisect reset && git bisect replay /tmp/b.txt
git bisect bad # Continue after marking correctly
Understand the dangers of "returning 1 on build failure":Write a bug-checking script to see who bisect will wrong.
cat > /tmp/bad-check.sh <<'EOF'
#!/usr/bin/env bash
grep -q '^def healthz():' app.py || exit 1 # Error: Unable to test is considered bad
grep -q '"status": "ok"' app.py
EOF
chmod +x /tmp/bad-check.sh
git bisect start release/1.2 ee3c787 && git bisect run /tmp/bad-check.sh | grep "first bad"
git bisect reset
Expectation: bisect will63c8ca9 wip: split routesReported as first bad commit - A commit that was "temporarily broken but then fixed" was wrongly accused. That’s what 125 is about.
(Bonus points) Custom terms: Find out which commit introduced the /version endpoint.
git bisect start --term-old=absent --term-new=present release/1.2 v1.1.0
git bisect run sh -c '! grep -q "/version" app.py'
git bisect reset
The script is inNo/version returns 0 (= absent/old) and sometimes returns 1 (= present/new); the expected result is54f8214 feat: add /version endpoint。
Case 1: p95 latency doubled the day before launch
Background:There were over 600 commits between v3.4 and v3.5.Method:Writing a benchmark script: Build failsexit 125;Run 5 times to get the median, exceeding the thresholdexit 1, otherwiseexit 0; use--term-old=fast --term-new=slowAvoid semantic confusion.git bisect runIt took 10 rounds (about 40 minutes) to locate an ORM upgrade.Experience:Performance bisect must be sampled multiple times, otherwise the noise will bias the bisect.
Case 2: The first bad commit is a merge commit
Phenomenon:bisect points toMerge pull request #812, and the PR branch itself passes every commit test.Explanation:Both sides are correct independently, but conflict after combination (for example, main has changed the function signature, and PR has added a call to the old signature but there is no text conflict).Method:Execute on merge commitgit show --remerge-diff <merge>(2.36+) See "extra changes" when merging, or check both parents separately.Prevention:Merge Queue (Lesson 3) Run tests with the "latest main + PR" combination before merging.
Case 3: Only care about a certain service in monorepo
Method:git bisect start HEAD v2026.10 -- services/payments/Only the commits that changed the directory were divided into two points, and the number of candidates dropped from 3000 to 90; cooperate--first-parentTarget PR first.Note:If the regression is from a shared library (libs/), limiting it to just the service directory will miss it - don't limit the path when you're not sure.
Common errors and solutions
Some good revs are not ancestors of the bad rev. git bisect cannot work properly in this case.
Reason:The given good is not in bad's history (e.g. good is in another branch). Git will first test merge base; if the outputThe merge base … is bad. This means the bug has been fixed between … and [good], indicating that what you are looking for is actually a "fix" rather than a "regression" - use instead--term-old/--term-new。
There are only 'skip'ped commits left to test. The first bad commit could be any of: …
Reason:Commits near the answer have been skipped.Method:Go through the listed commits one by one; or modify the check script to make some of them testable (e.g. temporarily patch it so it compiles: in the scriptgit cherry-pick -n <fix>, after testinggit reset --hard)。
bisect run failed: exit code 126 / 127 from '…' is < 0 or >= 128
Reason:126 = Script does not have execute permission, 127 = Command not found - they are treated asbad, very covert; if the script is terminated by a signal (≥128), bisect will be aborted.
ls -l ~/git-lab/check-healthz.sh && chmod +x ~/git-lab/check-healthz.sh
git bisect run bash ~/git-lab/check-healthz.sh # Explicitly call with bash
git bisect log | tail -5 # Check whether it has been incorrectly marked
You need to start by "git bisect start" / already started again in bisect
error: Your local changes to the following files would be overwritten by checkout (bisect halfway)
Reason:Check that the script or build process modified the tracked files (make files, lock files).Fix:at the end of the scriptgit reset --hard -q; git clean -fdq(Note that only do this in a workspace dedicated to bisect), or usegit worktree add /tmp/bisectDivide into two separate workspaces.
Command line operation questions1. Write a function that can be used forbisect runScript:makeSkip on failure,make testIt is judged as bad when it fails.
#!/usr/bin/env bash
make -s >/dev/null 2>&1 || exit 125
make -s test
2. Only on the main line, only viewservices/api/The changes in the directory are divided into two parts, bad is HEAD and good is v2.0.0.
git bisect start --first-parent HEAD v2.0.0 -- services/api/
Scenario analysis questionsThe test is flaky (about 10% probability of failing randomly). If you still want to use bisect, how should you design a check script?
Make the misjudgment rate of a single judgment low enough: run the script repeatedly N times (such as 10 times), and only return 1 if there is one failure and the failure mode is consistent with the target bug (matching specific error information), otherwise 0 will be returned; 125 will be returned for failures unrelated to the target. The cost is that each step takes ×N. You can also first confirm that the "bad" end is really stable and bad (run it multiple times), and usegit bisect logKeep records, replay when results are suspicious and double-check key steps.
This courseware cannot directly generate videos/MP3s. Storyboards and explanation scripts have been provided, which can be generated by video tools.
Shot 1 · 0–15s Screen: A row of 12 commit dots, with green v1.1.0 on the far left and release/1.2 on the right. Narrator: One end is good, one end is bad, and somewhere in the middle something is wrong.
Shot 2 · 15–45s Picture: A dot in the middle is highlighted and checked out, the terminal runs check-healthz.sh, returns 1, the right half turns gray and is excluded; then a wip commit returns 125, yellow "skip". Narrator: With each test, the number of candidates is halved. Script exit 0 is good, 1 is bad, 125 is untestable.
Shot 3 · 45–65s Screen: Only 18635fe left, flashing red, popping upgit showThe diff: status becomes Status. Narrator: Four tests found regressions disguised as refactorings.
Shot 4 · 65–80s Graphics: Merge commits on mainline lit, side branches dimmed, subtitles --first-parent. Narrator: To merge multiple histories, first locate the PR along the main line, and then enter the PR interior.
Module 4 · Rewriting history: git filter-repo clears secrets and large files
21:00 – 30:00 · Once a secret is pushed, it must be treated as leaked: rotate first, and then decide whether to rewrite history; after rewriting, force push, collaborator synchronization, and platform caching are all indispensable
Handle breaches in the correct order:Revoke/Rotate→ Evaluate whether rewriting is needed → Rewrite in a fresh clone → Validate → Push → Collaborator synchronization → Platform side cleanup (cache views, PR references, fork).
use git filter-repo of --invert-paths --path(delete file),--replace-text(replace string),--strip-blobs-bigger-than(Delete large files),--analyze(Analysis),--sensitive-data-removal(2.47+)。
Explain the scope of the rewrite (changed hashes of affected commits and all their descendants, loss of signatures), compare filter-repo, BFG Repo-Cleaner,git filter-branch。
Prerequisite knowledge:M2’s reflog and gc, Lesson 2’s push and--force-with-lease。Importance:★★★★★ (Once it occurs, it is a security incident)
What: What does it mean to rewrite history?
The commit hash is calculated from "tree + parent + author + committer + message". As long as the content of a historical commit is modified (deleting a file, replacing a line of text), its hash will change; its sub-commits will change because of the parent, and the hash will also change... until it is passed to the end of all branches and tags.Rewrite = generate a new set of commits and point refs to the new commits;Old commits still exist in every old clone, fork, CI cache, and platform's cache.
Why: Why “rotate first” is the first step, not an option
Once a secret is pushed to a shared repository, it may have been cloned, forked, logged by CI, or crawled by secret scanning bots. You can't confirm that all copies have been cleaned.
Only revocation/rotationOnly then can the leaked value be invalidated; rewriting history only reduces the chance of being "seen in the future" and is very costly (everyone's hash changes, PR comments may be lost). GitHub documentation clearly states: If credentials are leaked, after rotationProbably not needed at allRewrite history.
Typical situations that require rewriting: Confidentials cannot be rotated (e.g., personally identifiable information, customer data), compliance requirements must be removed from history, large files committed by mistake render the repository unusable.
How: Tool comparison
git filter-repo
BFG Repo-Cleaner
git filter-branch
Status
Git official documentation recommended; Standalone Python script, latest 2.47.0
Java tools, mature but low maintenance
Git is built in butOfficially not recommended(There are numerous security and performance warnings in the documentation)
speed
Fast (based on fast-export/fast-import)
Fast
Extremely slow (forks multiple processes per commit)
Delete files
--invert-paths --path P(by full path)
--delete-files NAME(by file name, any directory)
--index-filter 'git rm --cached …'
replacement text
--replace-text expr.txt(Literal /regex: / glob:)
--replace-text
--tree-filter+ sed (slow and error-prone)
large files
--strip-blobs-bigger-than 10M
--strip-blobs-bigger-than 10M
handwritten script
latest commit
Same deal with
Protect HEAD commits by default(You need to manually delete the secret in the latest commit first)
Rewrite old hash references in commit messages;--analyzereport;--sensitive-data-removalOutput the first change commit and affected PR references
—
—
Safety guardrails for git filter-repo
Only run in a fresh clone: If the repository does not appear to be a new clone (has loose objects or more than one reflog), it will reportAborting: Refusing to destructively overwrite repo history since this does not look like a fresh clone., remind you not to operate on the only working copy (use only after confirmation)--force)。
DefaultDelete origin remote, to prevent you from pushing back the rewritten results before verification; use--sensitive-data-removalThe origin will be retained and all references will be grabbed from origin first to ensure that every branch and tag is covered by the rewrite.
Automatically after rewriting is completedreflog expire --expire=nowand repack, the old object fromThis clonedisappear.
After push: all other copies
copy
risk
Process
clone of collaborator
oncegit pull(merge) orgit pushwill bring back the old history
Re-clone preferred;otherwisefetch + reset --hard origin/main, branches based on old history userebase --ontomigrate and thenreflog expire --expire=now --all && gc --prune=now
PR citations on the platform (refs/pull/*) with cached views
PR diff pages and commit pages accessed by hash can still display old content;refs/pull/*Read only, cannot be pushed
GitHub: Contact support to provide the number of affected PRs and "First Changed Commit(s)"; GitLab: Remove blobs / Redact text functionality in repository settings; other platforms such as Azure Repos follow their documentation or contact support
fork
The platform will not clean up the fork for you
Contact the fork owner to delete or clean up
CI cache, artifacts, logs, mirror repository
May contain secrets in workspace or logs
Clean up one by one; this is also the reason for "must rotate first"
When: Which method to choose?
situation
practice
Not pushed yet
No filter-repo is required:git commit --amendorgit rebase -iJust delete it (lesson 2); the same goes for push protection blocking
Pushed credentials
Rotate now; Decide whether to rewrite after evaluation (most teams will still clean up after the rotation to avoid misleading audits and scan alarms from being triggered repeatedly)
Large files pushed
The team coordinates a window period,--strip-blobs-bigger-thanor--invert-paths, migrate to Git LFS if necessary (git lfs migrate import)
The file needs to be retained, only a certain line is sensitive
--replace-text(The situation of settings.env in this lesson)
Common misunderstandings① "Just delete the file and commit it again" - old versions in history are still visible (git log -p). ② "After rewriting and pushing it, it's over" - there are also collaborators, PR references, forks, and caches. ③ "Private repositorys don't matter" - everyone with read permissions and every CI machine has a complete history. ④ "git revertSecrets can be deleted" - revert is a new reverse commit, but the old content is still there.
Figure 4-1 Propagation of rewrites: when a commit is modified, all descendant hashes change
Figure 4-1 Rewrites propagate backward starting from the “first changed commit”; it’s this First Changed Commit that the GitHub support team needs
Figure 4-2 Leak response process
Figure 4-2 Each step after step ① is only "reducing exposure" and cannot replace rotation.
Interaction: Click a commit to simulate "rewrite from here"
The commit graph is taken from the bootstrap repository. Click on any commit, assuming it was modified by filter-repo: see which commits will get new hashes, which branches and tags will be moved, and which branches in the hands of collaborators need to be migrated. Then click "Force Push and Sync" to observe the status changes of the three copies (your new clone/remote/teammate).
Click one to commit in the image above.
Core commands and parameters
Command/parameter
function
Description
git filter-repo --analyze
Generate analysis report
write.git/filter-repo/analysis/: Largest blob, statistics by path/extension, deleted files
--invert-paths --path P
Remove path P from all history
Repeatable--path;--path-glob '*.pem'、--path-regex
--replace-text FILE
Replace text in all history file contents
One rule per line:literal(Replace with***REMOVED***)、old==>new、regex: pattern == > replacement、glob:…
--replace-message FILE
Replace text in commit message
The format is the same as above
--strip-blobs-bigger-than 10M
Delete blobs larger than threshold
Also available--strip-blobs-with-ids FILE
--sensitive-data-removal(--sdr,2.47+)
Confidential clear mode
First grab all references from origin, keep origin, and record.git/filter-repo/changed-refsWith "First Changed Commit(s)", reporting orphaned LFS objects
--refs、--force、--dry-run
Qualify references / skip new clone checks / only generate fast-export streams
--forceOnly use if you confirm you have a backup
git push --force --mirror origin
Push all citations
--mirrorAlso deletes references that are not local to the remote - must be executed in a clone that contains all references
Find out the scope of the leak
cd ~/git-lab/myapp
git log --all --oneline -S FAKE_SECRET #Introduce/remove the commit of this string (pickaxe)
git grep -n FAKE_SECRET $(git rev-list --all) | head -3 # Which committed files still contain it
git branch -a --contains bbc4ca6; git tag --contains bbc4ca6
abb417c fix: remove FAKE_SECRET from settings.env
bbc4ca6 config: add settings.env
bbc4ca6…:settings.env:2:FAKE_SECRET=fake-9f8e7d6c-not-a-real-key
experiment
feature/login
* main
release/1.2
remotes/origin/feature/login
remotes/origin/main
v1.1.0
Overwrite in fresh clone (text replacement + deletion of large files)
Parsed 14 commits
New history written in 0.11 seconds; now repacking/cleaning...
Repacking your repo and cleaning out old unneeded objects
HEAD is now at 3e1f0a2 docs: tuning notes
Enumerating objects: 52, done.
Counting objects: 100% (52/52), done.
…
NOTE: First Changed Commit(s) is/are:
5b7c9d1e…
Completely finished after 0.42 seconds.
--no-localHave the clones transferred via the pack protocol (instead of hard link copying the object directory), resulting in "new clones" recognized by filter-repo. Not added--sensitive-data-removalWhen, filter-repo will remove origin, you need togit remote add origin <url>。
Verify, then push
git log --all -p | grep -c 'FAKE_SECRET=fake' || true # expects 0
git rev-list --objects --all | grep db-dump.sql || echo "The large file is no longer in the history"
git log --oneline -3 --all
git push --force --mirror origin
0
Large files are no longer in history
…
+ 9d2e4b1...3e1f0a2 main -> main (forced update)
+ 912a321...7c4e8f0 feature/login -> feature/login (forced update)
+ 3a9c2e1...8b1d0f3 v1.1.0 -> v1.1.0 (forced update)
Bare repository of self-built server: clear old objects
Collaborator synchronization (choose one of three)
# A. The simplest and most reliable: re-clone (first export unpushed changes as patches)
git -C ~/git-lab/teammate format-patch origin/main@{1}..main -o /tmp/mate-patches 2>/dev/null
rm -rf ~/git-lab/teammate && git clone ~/git-lab/remote/myapp.git ~/git-lab/teammate
# B. No local work: direct alignment
cd ~/git-lab/teammate && git fetch origin && git reset --hard origin/main
# C. Have a local branch based on old history: only move your own commits
git fetch origin
git rebase --onto origin/main < old origin/main hash > my-feature
#Finally: completely clear old objects from local
git reflog expire --expire=now --all && git gc --prune=now
git log --all -p | grep -c 'FAKE_SECRET=fake' || true # expects 0
NeverExecute in the collaborator's old clonegit pull(merge) orgit push: Merging will bring back the old history as the second parent, and everything will be in vain after pushing.
Lab 4: Clean up fake secrets and mistakenly committed large files, and synchronize teammates (~8 minutes)
Make a "Pushed Large File"(One more question in addition to bootstrap's FAKE_SECRET):
cd ~/git-lab/myapp && git switch -q main
mkdir -p backup && head -c 3000000 /dev/urandom > backup/db-dump.sql
git add backup && git commit -qm "chore: add db dump (oops)"
git rm -q -r backup && git commit -qm "chore: remove db dump"
git push -q origin main 2>&1 || git pull -q --rebase origin main && git push -q origin main
git -C ~/git-lab/teammate pull -q --rebase
git -C ~/git-lab/remote/myapp.git count-objects -vH | grep size-pack
① Rotation(Real-life scenario): Revoke the old value, publish the new value, and confirm that the service has been switched in the key management system. The value of this experiment is false, just record "rotated" - but remember that it is always the first step.
If your filter-repo is lower than 2.47 (reportunrecognized arguments: --sensitive-data-removal), remove this parameter, rewrite and executegit remote add origin ~/git-lab/remote/myapp.git。
⑥ Teammate synchronization: Demonstrate the consequences of "wrong practices" first, and then synchronize correctly.
cd ~/git-lab/teammate
git fetch origin
git status -sb | head -1 # Show ahead N, behind M - history has been forked
git log --oneline --left-right main...origin/main | head
# Correct: no local work, align and clean directly
git reset --hard origin/main
git reflog expire --expire=now --all && git gc -q --prune=now
git log --all -p | grep -c 'FAKE_SECRET=fake' || true
Your myapp is also an old clone: It also needs to be synchronized (or usedbootstrap --forcereconstruction). Note that there are still things in myapp that have not been pushedexperiment、release/1.2branches - they are based on old history, usinggit rebase --ontoMigrate, or rebuild directly after this experiment.
Case 1: The cloud access key was pushed to the public repository, and an abnormal call occurred a few minutes later
After:Developers put.envPush it to the public repository, and within minutes the automated program will scan it and start calling the cloud API.Disposal:① Immediately deactivate and delete the key in the cloud console, check CloudTrail/activity logs, and recycle abnormal resources; ② Use filter-repo to rewrite, force push, and contact platform support to clear the cache; ③ Enable push protection and pre-commit confidential scanning (lessons 3 and 5).Lessons:Rewriting history is much slower than rotation, and attackers won't wait for you.
Case 2: A 2 GB model file was mistakenly committed, causing everyone’s clone to slow down.
Method:git filter-repo --analyzeConfirm the maximum blob; agree on a window period with the team to merge or close ongoing PRs;--strip-blobs-bigger-than 50Mrewrite and usegit lfs migrate import --include="*.bin" --everythingMigrate the models that need to be retained to LFS; force push and notify everyone to re-clone; request gc on the platform side (GitHub support; Remove blobs in GitLab repository settings).Effect:Repository size reduced from 2.3 GB to 40 MB.
Case 3: “Secrets are back” after rewriting
After:One week after rewriting and pushing it, the scanning alarm appeared again.Reason:A colleague who returned from vacation was in the old clonegit pullAfter (merging) his branch was pushed, the old history was pushed back as the secondary parent of the merge.Fix:Rewrite again; this time use a rule set to temporarily block push on the platform (or turn on push protection so that push containing the secret will be rejected directly), and confirm that everyone has been re-cloned one by one.
Common errors and solutions
Aborting: Refusing to destructively overwrite repo history since this does not look like a fresh clone.
Reason:The current repository has loose objects, multiple reflogs or stash - filter-repo is worried that you are operating on the only copy.
git clone --no-local /path/to/repo /tmp/fresh # To clone the local path, add --no-local
# Or after confirming that there is a backup
git filter-repo --force …
git: 'filter-repo' is not a git command. See 'git --help'.
Reason:Not installed or not on PATH.git filter-repoWhat is actually called is the file named in PATHgit-filter-repoexecutable file.
Reason:--mirrorInclude platform read-only PR references when pushing. This is expected: after the remaining citations are successfully pushed, the PR citations are handed over to platform support for processing. If other branches are rejected due to protection rules, the rules will be temporarily adjusted and then re-posted.
After rewriting, secrets can still be found in git log -p
Troubleshooting:① The secret appears inCommit informationinside → use--replace-message;② The file has been renamed → Each historical path must--path(git log --all --name-only --follow -- fileCheck the name); ③ The regular expression is not matched (if it contains+//base64) → use literal rules first; ④ inold cloneSearch in (reflog, old remote-tracking branches still refer to old objects).
2. Write a replacements file: put the literalhunter2Replace with default placeholders, put allAKIAThe first 20 digits of the access key ID are replaced withAKIA-REDACTED。
hunter2
regex:AKIA[0-9A-Z]{16}==>AKIA-REDACTED
Scenario analysis questionsA database password committed 3 years ago was discovered in a repository with 40 contributors and 200 open PRs. Your plan of action?
① Immediately rotate database passwords and audit access logs—this step addresses the real risk. ② Assessment: The password has been rotated, does it still need to be rewritten? Consider compliance requirements and alert noise; rewriting will invalidate old diffs of 200 open PRs and comments may be lost. ③ If you decide to rewrite: Announce the window in advance and try to merge/close the PR; in the new clonefilter-repo --sensitive-data-removal --replace-text;checkchanged-refsNumber of affected PRs; after verificationpush --force --mirror; Commit the number of affected PRs and First Changed Commit to platform support; require everyone to re-clone and use branches based on old historyrebase --ontoMigrate, disable merging old branches; notify fork owner. ④ Prevention: push protection, pre-commit secret scanning, secret key management service.
Instructional video
No verified, dedicated explanation foundgit filter-repoClear confidential YouTube videos (search results are mostly text tutorials or mirror pages that cannot be verified by oEmbed). Please refer to the official documentation and the storyboard below.
This courseware cannot directly generate videos/MP3s. Storyboards and explanation scripts have been provided, which can be generated by video tools.
Shot 1 · 0–20s Screen: Scan the alarm pop-up window "FAKE_SECRET detected". Use one hand to click the "Rotate Key" button. The "Rewrite History" button next to it is temporarily grayed out. Narrator: Once a secret is pushed out, it will be treated as if it has been leaked. The first step is always rotation.
Shot 2 · 20–45s Screen: A red commit on the commit chain is replaced by a new yellow commit. The subsequent commits turn yellow one after another like dominoes, and the branches and tags jump to the new commit. Narrator: Change a historical commit and it and all its descendants will get the new hash.
Shot 3 · 45–70s Screen: Terminal:git clone --no-local → git filter-repo --sensitive-data-removal --replace-text → git push --force --mirror。 Narrator: Rewrite in a new clone and push all references after verification.
Shot 4 · 70–90s Image: Three laptop icons (teammates), one of which is trying togit pullBlocked by a red cross, replace it with "re-clone"; the PR page and fork icon in the corner are labeled "Contact Platform". Narrator: Collaborators are re-clone, platform cache and PR references are handed over to the support team, and forks need to be contacted individually.
30:00 – 37:00 · Power outages, full disks, anti-virus software, sync disks, and virtual machine crashes can all damage .git; the good news is that object contents have built-in validation and can almost always be restored from another copy
7 minutesfsck · alternates · hash-object -w★★★☆☆
learning objectives
understandgit fsckOutput: what does corrupt / missing / broken link / dangling / bad ref mean respectively, which ones need to be processed and which ones can be ignored.
Follow the process of "Backup → Locate → Recover from other copies → Verify" to repair damaged or missing objects:hash-object -w, temporary alternates,unpack-objects、update-ref。
in index file corrupt, residueindex.lockRebuild the index safely and know the last resort.
Prerequisite knowledge:Lesson 1's object model (blob/tree/commit, loose objects, and pack).Importance:★★★☆☆ (Not common, but when it occurs, it is most likely to cause panic and expand losses)
What: What will break?
parts
location
Typical error reports of damage
recoverability
loose objects
.git/objects/ab/cdef…(zlib compression)
error: inflate: data stream error、object file … is empty、loose object … is corrupt
High: Any copy that owns the object can make up for it (content addressing, the same hash means the same content)
packfile
.git/objects/pack/*.pack + .idx
packfile … cannot be accessed、bad packed object CRC
High: make up from other copies;.idxAvailable if brokengit index-packrebuild
refs/heads/main does not point to a valid object!、bad object HEAD
High: Correct hash found from reflog or remotely,git update-ref
index (staging area)
.git/index
index file corrupt、bad signature 0x…、index file smaller than expected
High: index can be rebuilt from HEAD (only the "staged but not committed" distinction is lost)
workspace file
Repository directory
None (Git doesn’t know what content you want)
Committed cangit restore;Uncommitted cannot be recovered
Why: Why object damage can usually be repaired
The name of the object is the hash of its content (SHA-1 or SHA-256), so: ① Any object with the same name in any copyThe content must be the same, can be directly replaced; ② Git will verify when reading the object, and bad objects will not be quietly used as correct data; ③ If there is still the original content of the file in the workspace,git hash-object -w filecan be regeneratedexactly the sameblob.
How: fsck output classification
output
meaning
Does it need to be processed?
dangling commit/blob/tree
Dangling object: nothing points to it (M2)
No need; they are remnants of reset/rebase/stash that gc will clean up, or are exactly what you want to get back
missing blob <sha>
The object referenced by a tree does not exist
need: Make up for it from other copies
broken link from tree X to blob Y
ditto, indicating who is quoting it
need;git fsck --name-objectsThe path will be displayed, such asmain:NOTES.txt
error: … object corrupt or missing、inflateError
File exists but content is corrupted
need: Remove the bad files first and then replace them
error: refs/… does not point to a valid object
Reference points to non-existent object
need: Use reflog/remote to restore the reference, or delete the reference
warning in commit …: badDate / missingEmail …
The format is not standardized (mostly generated by old tools), and the object itself is intact
Usually not required; only if--strictor serverreceive.fsckObjectsHandling when push is rejected
Repair process
backup:cp -a repo repo.broken. don't run firstgit gc/prune(They may delete objects you still need or fail on bad packs).
Positioning:git fsck --full --name-objects, note the bad/missing object hash and the path that references it.
Remove bad files: Corrupted loose object files will "take space" to make Git think the object exists - move it out.git/objects(Empty files can be deleted directly).
Make up for it(optional): Workspace original file →git hash-object -w; another clone →git -C other cat-file <type> <sha> | git hash-object -t <type> -w --stdin;A large number of objects → temporarily add another cloned object directory to.git/objects/info/alternatesaftergit repack -a -d, and delete alternates; orgit -C other pack-objects --stdout <list | git unpack-objects。
Verify: againgit fsck --full, until there is no error/missing; then you cangit gc。
When: The last resort
No replica owns the lost object (for example, corrupted by a local commit that was never pushed): ① Export the readable part as much as possible (git format-patch, copy the workspace); ② Re-clone, copy the workspace files back and recommit; ③ If only one historical blob is damaged, you can usegit replaceOr filter-repo overwrites the commits that reference it (at the cost of rewriting history).
Common misunderstandings① "Seeing dangling means the repository is broken" - No, that's normal. ② "git fetchMissing objects will be automatically filled in" - not necessarily: if the local reference already points to that commit, during the negotiation phase Git will think "I already have it" and will not download it; you need to fill it in according to the above method. ③ "It is safe to put the repository in the OneDrive/Dropbox synchronization disk" - the synchronization tool will copy half of the file during the Git writing process, resulting in conflicting copies, which is a common source of damage; use a remote repository to synchronize code, do not use a file synchronization disk to synchronize.git。
Figure 5-1 Four paths from “bad object” to “recovery”
Figure 5-1 Content addressing makes "complementing" simple: objects with the same name must have the same content
Figure 5-2 Index is damaged: why it is safe to delete and rebuild
Figure 5-2 index is reproducible; do not use itreset --hardto "fix" the index - that will overwrite the workspace
Interaction: fsck report interpreter
Click on a line of error reporting in true format to see its meaning, whether it needs to be processed, and repair commands.
← Select a line to report an error
Core commands and parameters
command
function
Description
git fsck --full
Check integrity and connectivity of all objects (loose + pack)
blob
f1ae23f3e4454d807fd582ef4a0e12617215ab95
Checking object directories: 100% (256/256), done.
fsck OK
hash-objectThe output hash is the same as$OBJThe same, proving that the supplementary content is completely correct. If it is tree or commit, usegit cat-file tree $OBJ | git hash-object -t tree -w --stdin(cat-file <type>Output in original format,-pis a prettified format and cannot be used for writeback).
Large number of missing objects: temporary alternates
echo "$HOME/git-lab/remote/myapp.git/objects" >> .git/objects/info/alternates
git fsck --full --no-dangling # should pass after borrowing
git repack -a -d # Copy the required objects into pack of this repository
rm .git/objects/info/alternates
git fsck --full --no-dangling && echo "Independent and complete"
Empty object files (most common after power outage/disk full)
find .git/objects -type f -empty -print # Look first
find .git/objects -type f -empty -delete # Delete again (empty files do not contain any information)
git fsck --full
Reference points to invalid object
git fsck 2>&1 | grep "does not point"
git reflog show main -3 # Previous valid value in reflog
git update-ref refs/heads/main < Valid hash > # Or use remote: git update-ref refs/heads/main origin/main
Index damage and residual locks
git status
error: bad signature 0x6e6f7420
fatal: index file corrupt
mv .git/index /tmp/index.broken
git reset # mixed: Rebuild index from HEAD without touching the workspace
git status -s
# fatal: Unable to create '…/.git/index.lock': File exists.
pgrep -a git || rm -f .git/index.lock # Make sure there is no running git process before deleting it
Experiment 5: Damage with your own hands and repair with your own hands (about 6 minutes)
Prepare a new commit that has been pushed(Its object is loose and also exists remotely):
cd ~/git-lab/myapp && git switch -q main
git pull -q --rebase origin main
echo "release checklist" > NOTES.txt && git add NOTES.txt && git commit -qm "docs: add release notes"
git push -q origin main
cp -a ~/git-lab/myapp ~/git-lab/myapp.bak # Back up first!
OBJ=$(git rev-parse HEAD:NOTES.txt); echo $OBJ
echo "work in progress" >> README.md # An uncommitted change
printf 'not an index' > .git/index
git status 2>&1 | tail -1
rm .git/index && git reset -q && git status -s # README.md changes are still there
Case 1: “error: object file … is empty” after VM crashes
After:Build machine ingit fetchIt was down during the period, and after restarting, all Git commands reported empty object files.Processing:Backup →find .git/objects -type f -empty -delete → git fetch(At this time, the reference has not been updated to the new commit, fetch will download it again) →git fsck. If the commit pointed to by HEAD also becomes an empty file:git update-ref HEAD origin/mainOr directly delete the working directory and clone again (there is no local work that needs to be retained on the build machine).Prevention:File system and Git persistence configuration (since 2.36core.fsyncseries options, subject to official documentation), the build machine gives priority to using the disposable workspace.
Case 2: The repository is placed in the synchronization disk, and "main 2.lock" and damaged pack appear.
After:The developer puts the repository in the cloud synchronization directory and works alternately on the two computers..git/refs/heads/main 2Conflicting copies, pack file truncation.Processing:On one of the machines usegit fsckFind the missing objects and replace them from the remote (or a copy on another machine, through temporary alternates); then move the repository out of the synchronization directory and synchronize through the remote repository instead.
Case 3: Server-side receive.fsckObjects rejects push
Phenomenon:Push notification when migrating old repositoryremote: fatal: fsck error in packed object、missingSpaceBeforeDate。Reason:In the history, there are commits generated by old tools in irregular formats, but the objects are not damaged.Processing:After confirming that it is just a format warning, temporarily relax it on the receiving end (self-built server)receive.fsck.<msg-id> = ignoreorwarn, rather than turning off the entire check; the hosting platform can contact support per its documentation or use its import tool.
Common errors and solutions
error: object file .git/objects/ab/cd… is empty
Write to an empty file left behind by an interruption.find .git/objects -type f -empty -deleteaftergit fsck --full, fill in missing objects from remote or other copies.
fatal: bad object HEAD / fatal: your current branch appears to be broken
cat .git/HEAD # Current branch
git reflog show main -5 2>/dev/null || tail -5 .git/logs/refs/heads/main
git update-ref refs/heads/main < Previous valid hash > # or origin/main
When the reflog file itself is corrupted, usegit fsck --lost-foundFind the latest dangling commit, or use the remote value directly.
fatal: index file smaller than expected / bad signature 0x00000000
index is truncated or cleared.rm .git/index && git reset. If you have a carefully selected partial staging in the index (add -p), this part of the distinction will be lost and needs to be re-add -p。
fatal: Unable to create '…/.git/index.lock': File exists.
Reason:Another Git process is running (IDE background fetch/status), or the lock is left from the last process crash. First make sure there is no Git process (pgrep -a git, Windows Task Manager), thenrm .git/index.lock. The same principle applies torefs/heads/xxx.lock、HEAD.lock、packed-refs.lock。
error: packfile .git/objects/pack/pack-….pack does not match index
When pack itself is damaged, remove it and replace the missing objects from other copies (alternates + repack).
Command line operation questions1. Clone from a colleague/srv/mate/appFill in a missing tree object9f8e…。
git -C /srv/mate/app cat-file tree 9f8e… | git hash-object -t tree -w --stdin
2. Only check connectivity (without unpacking each object) and hide dangling objects.
git fsck --connectivity-only --no-dangling
Scenario analysis questionsA development machine's repository has 3 local unpushed commits, one of which references a corrupted blob and the workspace has modified that file. How to keep your job as much as possible?
① cp -aBack up the entire repository. ②git fsck --full --name-objectsConfirm that only this blob and its path are broken. ③ Check other sources: whether that version of the file has beengit addGo elsewhere (stash, other branches), IDE local history, colleagues have the same content (the same content means the hash is the same,hash-objectJust verify). ④ If it cannot be found: Export the readable commit (git format-patchWill fail on bad commits, availablegit diffExclude the file and export it) and reapply on the new clone; bad files are rewritten according to memory and recommitted. ⑤ After repairgit fsckContinue working by then and push as soon as possible.
No dedicated demo foundgit fsckDamage repair videos that can be verified by oEmbed; the above two object model videos (title and channel verified) can be used as background.
This courseware cannot directly generate videos/MP3s. Storyboards and explanation scripts have been provided, which can be generated by video tools.
Shot 1 · 0–20s Screen:git showAn inflate error is reported, and the object file icon appears cracked. Narrator: Don't panic yet, and don't gc. Make a backup and let fsck tell you what's broken.
Shot 2 · 20–45s Picture: Bad files are dragged to the "quarantine" outside the trash can; objects with the same name are copied from another repository and the hash check is checked. Narrator: The object name is the hash of the content, and any object with the same name in the copy can be directly replaced.
Shot 3 · 45–70s Picture: index file is broken,git resetRebuild from HEAD; workspace files remain unchanged. Narrator: Index can be regenerated; use mixed reset, not hard reset.
Module 6 · Line breaks, case, permissions and encoding issues
37:00 – 45:00 · “I haven’t changed anything, but git status says the entire file has changed” – the four most common types of “ghost changes” in cross-platform teams
Understand that end-of-line transitions occur whenCommit(clean)withCheck out (smudge)Two directions, distinguishcore.autocrlf(Personal Machine Settings) vs..gitattributes(Team agreement to follow the repository), use* text=auto eol=lfUnify line endings and usegit add --renormalize .Repair existing files.
Correctly case-only rename on case-insensitive file systems (Windows, macOS default), handling "collided" warnings.
Diagnosis old mode 100644 / new mode 100755、Filename too long、invalid path, the file name is displayed as\346\265\213…etc. questions.
Prerequisite knowledge:Lesson 1 bootstrap in.gitattributesWarning with Windows end of line.Importance:★★★★☆ (mixed Windows/macOS/Linux teams are almost bound to encounter)
What: Two directions of end-of-line conversion
Windows text files use CRLF (\r\n) at the end, Linux/macOS uses LF (\n). Git can switch between two moments:When writing to the object library(git add, clean direction: CRLF → LF, "normalized") andWhen writing out to the workspace(checkout, smudge direction: LF → CRLF or stay LF). Best practices are:Always keep LF in the repository, the workspace is converted as needed.
settings
When committing
When checking out
Applicable
core.autocrlf=true
CRLF → LF
LF → CRLF
Windows personal machine (Git for Windows installer writes system configuration by default)
core.autocrlf=input
CRLF → LF
No conversion
Linux/macOS personal machine to prevent accidental introduction of CRLF
core.autocrlf YesEveryone on their own machineThe team cannot guarantee consistency in settings;.gitattributesThe commit is in the repository, takes effect on all clones, and is set totextproperties file,take precedence overcore.autocrlf. Recommended repository root directory.gitattributes:
* text=auto eol=lf
*.{cmd,bat,ps1} text eol=crlf
*.{png,jpg,gif,ico,zip,pdf,jar} binary
Note:.gitattributesThe pattern syntax is not supported{a,b}Curly brace expansion, the above is just for illustration; in the actual file, it must be written line by line.*.cmd text eol=crlf、*.bat text eol=crlf……
How: Repair existing files—renormalize
Add or modify.gitattributesNoAutomatically overwrite files already in the repository. There will be two situations for files that have been stored in CRLF in history:
"Automatic" rules(text=auto、text=auto eol=lf, when there is no attributecore.autocrlf): Git has a protection measure - if the version in indexAlready contains CRLF, the file will not be standardized to avoid a large number of changes at once. The result is that the status is clean, but the fileSilently still stored as CRLF, the problem still occurs on Linux.
explicittext rules(as in bootstrap*.sh text eol=lf): Git always performs clean conversion, and the workspace converted to LF is inconsistent with the CRLF in the index.git statusAlways displays "Modified",git checkout -- fileIt is also "unrecoverable" - this is a "ghost change".
The fix is the same in both cases:
git add --renormalize . # 2.16+: Renormalize all tracked files by current attributes
git status -s # List the files whose line endings were actually rewritten
git commit -m "chore: normalize line endings"
After others in the team pull it, you may need to refresh the workspace:git rm --cached -r -q . && git reset --hard(Uncommitted changes will be overwritten, commit or stash first). usegit ls-files --eolView each file at index(i/), workspace (w/) and the effective attributes (attr/)。
When: case, permissions, long path, encoding
question
root cause
practice
Renaming that only changes case will not take effect
The default file system of Windows/macOS is not case sensitive.core.ignorecase=true(Automatically detected during init/clone)
The repository (commit on Linux) also hasFile.txt with file.txt, the case-insensitive system can only detect one of them
Rename one on case-sensitive systems; or on Windows usegit rm --cachedOnly operate on index
old mode 100644 / new mode 100755
File permission bit changes (copy from Windows/NTFS/FAT mount,chmod -R)
Confirm whether you really want to change it; you don’t want to track permissions:core.fileMode=false(Windows default); Set the executable bit on Windows:git update-index --chmod=+x deploy.sh
Filename too long
Windows legacy 260 character path limit
git config --system core.longpaths true(Git for Windows) and enable long path support in Windows; or shorten the clone path
error: invalid path 'aux.txt' / 'docs/notes.'
Windows reserved names (CON, PRN, AUX, NUL, COM1...), ending with a dot or space, containing:path;core.protectNTFSDefault protection
Rename these files on other systems; do not turn off protectNTFS (it protects against known security vulnerabilities)
The file name appears as"\346\265\213\350\257\225.txt"
core.quotePath=true(Default) Display non-ASCII bytes as octal escapes
git config --global core.quotePath false
Files with accented/Chinese combination characters appear as untracked "duplicate" files on macOS
macOS file system returns NFD decomposed form, Linux commits NFC
core.precomposeUnicode=true(enabled by default on macOS), old clones need to be explicitly set and then checked out again
Common misunderstandings① "Putcore.autocrlfSet it to false and there will be no line ending problems" - it just won't be converted, the CRLF generated by the Windows editor will enter the repository as it is, and the problem will be transferred to colleagues and CI on Linux (/bin/bash^M: bad interpreter). ② "It will take effect immediately after adding .gitattributes" - required for existing files--renormalize. ③ "warning: LF will be replaced by CRLF is an error" - this just prompts that the workspace will use CRLF, and the repository will still be LF.
Figure 6-1 clean / smudge: bytes of the same file in three places
Figure 6-1 There is only one type of line ending (LF) in the repository, and conversion only occurs at the boundaries of "in" and "out"
Figure 6-2 Renaming on a case-insensitive file system
Figure 6-2 To let index know the case renaming, use git mv
Interactive: End of line conversion simulator
Select the original line ending of the workspace, personal settings and repository .gitattributes to seegit addBytes in the object library after checkout, bytes after checkout, and whether "ghost changes" will occur.
Line endings saved by the editor
core.autocrlf
.gitattributes
Core commands and parameters
command
function
Description
git ls-files --eol [path]
Display index/workspace line end and effective attributes
i/lf w/crlf attr/text=auto
git check-attr -a path
Display all attributes in effect for a path
Troubleshooting rule matching order (later lines override previous ones)
How to read:CHANGELOG.mdLF in the index and CRLF in the Windows workspace (checkout transformation for autocrlf=true), which isnormal; the danger signal isi/crlfori/mixed——CRLF is stored in the repository.deploy.shMatches in bootstrap*.sh text eol=lf。
Diagnosing and fixing ghost changes
git status -s
git diff --stat ops/run.sh
git diff --ignore-cr-at-eol --stat ops/run.sh # No difference after ignoring CR → Pure line ending problem
git ls-files --eol ops/run.sh
git add --renormalize . && git status -s && git commit -qm "chore: normalize line endings"
git ls-files --eol ops/run.sh
Create a CRLF file that is stored in the repository "before the rule takes effect"(Same technique as blind box failure #7: bypassing the clean filter and writing directly to the object):
bootstrap.gitattributes Yes *.sh text eol=lf, so Git cleans the workspace file into LF and compares it with the CRLF in the index - it is always "modified". Also runs on Linuxsh ops/run.shnewspaper$'\r': command not found。
Repair and verify:
git checkout -- ops/run.sh; git status -s # checkout also "cannot be restored"
git add --renormalize . && git commit -qm "chore: normalize line endings"
rm ops/run.sh && git checkout -- ops/run.sh
git ls-files --eol ops/run.sh; git status -s; sh ops/run.sh
Case renaming(You can best appreciate the difference by doing it on Windows/macOS; you can also practice commands on Linux):
mv README.md readme.md 2>/dev/null; git status -s # On case-insensitive systems: no changes
mv readme.md README.md 2>/dev/null
git mv README.md tmp.md && git mv tmp.md Readme.md && git status -s
git commit -qm "docs: rename README" && git show --stat --oneline HEAD | head -3
executable bit:
git ls-files -s ops/run.sh #100644
git update-index --chmod=+x ops/run.sh && git commit -qm "ops: make run.sh executable"
git ls-files -s ops/run.sh #100755
git config --get core.fileMode # Usually false on Windows
(Linux/macOS) Simulate case conflicts, and then think about what your Windows colleagues would see when they clone:
Case 1: Container startup report /bin/sh^M: bad interpreter
After:Windows developers setcore.autocrlf=false, the editor saves it as CRLFentrypoint.shAnd commit; the image built by Linux CI fails to start:exec /entrypoint.sh: no such file or directory(shebang at the end of the line\rLet the interpreter path become/bin/sh\r)。Fix:Repository added* text=auto eol=lf,git add --renormalize .; CI added checkgit ls-files --eol | grep -E 'i/(crlf|mixed)'If there is output, it fails;.editorconfig settings end_of_line = lf。
Case 2: After cloning on Windows, there are always two files "modified" in git status
Reason:exist in the repository at the same timedocs/Setup.md with docs/setup.md(Linux users create separately), a collided warning appears when cloning, and the two paths compete for the same file.Fix:Merge into one file on Linux and commit; add push rules or CI checks on the platform:git ls-files | sort -f | uniq -diFail if there is output.
Case 3: monorepo checkout fails on Windows: Filename too long
After:node_modulesThe style's deep path exceeds 260 characters.Fix:git config --system core.longpaths trueAnd enable the Windows long path through Group Policy/Registry; clone the repository to the short path (such asC:\src\app); in the long run use sparse checkout (Lesson 6) to check out only the directories you need.
Common errors and solutions
warning: in the working copy of 'app.py', LF will be replaced by CRLF the next time Git touches it
Description:Just a hint (on Windowscore.autocrlf=trueortextattribute): The next time the file is checked out, it becomes CRLF in the workspace and remains LF in the repository. To keep the workspace LF as well:.gitattributes Medium settings eol=lf。
git status shows that the entire file has been modified, but git diff cannot see the difference (or every line has changed)
git diff --ignore-cr-at-eol --stat # If empty: pure end-of-line difference
git ls-files --eol FILE
git diff --summary | grep "mode change" # It may also be a permission change
end of line →.gitattributes + --renormalize;Permissions →core.fileModeorupdate-index --chmod。
warning: the following paths have collided (e.g. case-sensitive paths on a case-insensitive filesystem) and only one from the same colliding group is in the working tree
There are paths in the repository that differ only in case. On case-sensitive systems (Linux, WSL's ext4 directory), rename or delete it and push it together; on Windows, you can also only operate the index:git rm --cached Path.txtCommit later.
error: unable to create file very/long/path/…: Filename too long
git config --system core.longpaths true # Requires administrator privileges; or --global
git restore --source=HEAD :/ # Recheck out failed files
error: invalid path 'con.txt' / fatal: unable to checkout working tree
Windows reserved name or illegal character. Rename and push on Linux/macOS/WSL; temporarily only want to get the rest of the files: exclude this path from sparse checkout. don't closecore.protectNTFS。
Command line operation questions1. Write a CI check that fails whenever there are any text files stored with CRLF or mixed line endings in the repository.
! git ls-files --eol | grep -E '^i/(crlf|mixed)'
2. On Windowsscripts/build.shMark as executable and commit.
Scenario analysis questionsA 5 year old repository with confusing line endings to introduce* text=auto eol=lf. How to implement it with as little disruption to the team as possible?
① Choose a low-peak time and notify in advance; ② Single PR: add.gitattributes + git add --renormalize ., only the end of the line changes in the PR (for review purposesgit diff --ignore-cr-at-eolConfirmed to be empty); ③ Add this commit.git-blame-ignore-revs, and let the team configureblame.ignoreRevsFile, to avoid blame being polluted by this big commit; ④ Notify everyone after the merge: commit/stash local changes, refresh the workspace if necessary; available when rebase of ongoing branches-X renormalizeReduce conflicts; ⑤ CI adds end-of-line checks to prevent rollbacks. Don't rewrite history.
No specific explanation found.gitattributesVideos with normalized line endings that can be verified by oEmbed. Please refer to the official documentation.
This courseware cannot directly generate videos/MP3s. Storyboards and explanation scripts have been provided, which can be generated by video tools.
Shot 1 · 0–20s Screen: Hidden characters ␍␊ and ␊ are displayed at the end of a line of text, and an object library is in the middle of two computers (Windows, Linux). Narrator: Same line of text, two line endings. Git transforms on the boundary into and out of the object repository.
Shot 2 · 20–45s Screen:.gitattributesFiles flew into the repository, and all three computers turned green at the same time; the personal autocrlf switch was marked "Local only." Narrator: The team agreed to write it into gitattributes, which will follow the repository and take precedence over personal settings.
Shot 3 · 45–65s Screen: A file that is always red M in status, executegit add --renormalize .Then disappear. Narrator: The existing CRLF needs to be renormalized once, and the ghost changes disappear.
Shot 4 · 65–80s Screen: readme.md is renamed README.md, the index remains unchanged after ordinary mv, and R is displayed after git mv. Narrator: On systems that are not case-sensitive, use git mv to change case.
Module 7 · Performance Diagnostics and Network/Protocol Issues
45:00 – 52:00 · “git status takes 8 seconds” “breaks when clone reaches 90%” “push reports 413” - measure first (trace2), then treat symptoms (fsmonitor, partial clones, server restrictions), don’t adjust http.postBuffer randomly
7 minutestrace2 · fsmonitor · untracked cache · protocol v2 · --filterhttp.postBuffer is not a panacea★★★★☆
learning objectives
use GIT_TRACE2_PERFSplit the slow command into time-consuming stages and determine whether the bottleneck is index refresh, untracked file scanning, ahead/behind calculations, or the network.
Enable by scenecore.fsmonitor、core.untrackedCache、feature.manyFiles、git maintenance;Using protocol v2,--filter=blob:none、--depth、--single-branchAccelerate clone/fetch of large repositories.
Diagnosis HTTP 413、RPC failed; curl 18/56/92、early EOF, proxy 407, TLS certificate error, and explain whyhttp.postBufferUsually not the answer.
Prerequisite knowledge:M1's trace tool; Partial cloning and sparse callout in Lesson 6.Importance:★★★★☆
What: git status is slow
git statusTwo questions need to be answered: ① Whether the tracked file has been modified (for each index entrylstat()Compare the timestamp and size, re-hash if necessary); ② What untracked files are there (traverse the entire working directory tree and match .gitignore one by one). In a repository with more than 100,000 files, both steps are the same asNumber of filesProportional; additionallystatusThe default also calculates ahead/behind with upstream, which can also be slow on long-forked branches.
bottleneck
Region in trace2
Countermeasures
Refresh index (lstat per file)
index / refresh
core.fsmonitor=true: File system monitor tells Git which files have changed since last time, check only those; built-in daemon supports Windows and macOS (2.37+), Watchman hook is available for Linux
Scan untracked files
status / untracked(And prompts "It took N seconds to enumerate untracked files")
core.untrackedCache=trueCaching directory scan results;status.showUntrackedFiles=noorgit status -uno;Perfect .gitignore
ahead/behind calculation
(Prompt "It took N seconds to compute the branch ahead/behind values")
status.aheadBehind=false;or regularly rebase long-term branches;git maintenanceMaintain commit-graph
index itself is huge
index / do_read_index
feature.manyFiles=true(enable index v4 and untracked cache, etc.); sparse checkout + sparse index (Lesson 6)
What: Where is clone/fetch slow?
Citation Notice: The server under protocol v0/v1 starts withallCitations (perhaps hundreds of thousands of PR/tag citations) are sent to clients;Protocol v2(Default since 2.26) Let the client usels-refs + ref-prefixOnly request the references you need.
negotiation:Sent by clienthaveline tells the server what it has; too many local references will increase the number of negotiation rounds (fetch.negotiationAlgorithm=skipping、--negotiation-tip)。
Object transfer volume: Complete history of all blobs. usepartial clone--filter=blob:none(download history blob on demand),Shallow clone--depth=1(CI is commonly used, but affectsdescribe/Change Detection, see Lesson 5),--single-branch, bundle URI (prefetched from CDN, server needs to support).
Why: What HTTP errors really mean
Report an error
usually means
right direction
error: RPC failed; HTTP 413 curl 22 The requested URL returned error: 413
The request body exceeds the size of the server orintermediary agentsize limit (like nginxclient_max_body_size, platform single push limit)
Adjust server/proxy limits; push in batches; remove large files (M4)/use LFS; use SSH instead
RPC failed; curl 18 transfer closed with outstanding read data remaining、curl 56 … Connection reset、curl 92 HTTP/2 stream … was not closed cleanly、fatal: early EOF、fetch-pack: invalid index-pack output
First use trace to confirm where the break is; reduce the amount of single transfer (partial/shallow cloning and thenfetch --unshallow); try-c http.version=HTTP/1.1;Change SSH;Check proxy timeout
Received HTTP code 407 from proxy after CONNECT
Agent needs certification
Proper configurationhttp.proxy(Including authentication methodhttp.proxyAuthMethod) or system agent
SSL certificate problem: unable to get local issuer certificate
Enterprise TLS checks use an internal CA, which is not included in Git's CA package
http.sslCAInfoPoints to the enterprise CA package; on Windowshttp.sslBackend=schannelUse the system certificate store;Don'tclosehttp.sslVerify
How: http.postBuffer misunderstanding
The most common advice online is “git config http.postBuffer 524288000". The official documentation explains it as follows: This is the buffer size used by smart HTTP during POST (default 1 MiB); when the request body exceeds the buffer, Git switches to HTTP/1.1.Chunked transfer encoding (chunked)。Turning it up has only one purpose: to avoid chunked transfers--Only required if the server or proxy does not support chunked (only supports HTTP/1.0 or is not standards compliant). The documentation clearly states that to turn it upNot effective for most push issues, but each request will occupy a corresponding amount of memory. So:
413 → is the size limit, postBuffer cannot change the server limit (after increasing the size, the entire request is sent out at once, but it may be easier to exceed the limit).
curl 18/56/92, early EOF → The connection is cut off and has nothing to do with the buffer.
Only seen in traceTransfer-Encoding: chunkedWhen the request is rejected by the proxy (such as returning 411 Length Required), the temporary increase will be considered, and only for that URL:git config http.https://git.corp.example.com/.postBuffer 157286400。
When pushing large amounts of history (migration) 413
Push in batches (push gradually according to the commit interval), increase the server limit, and clean up large files first
Common misunderstandings① “git gc --aggressiveIt can make status faster" - the bottleneck of status is file system traversal, which has little to do with object packaging; gc mainly affects object access and transmission. ② "Closehttp.sslVerifyCan solve the certificate problem" - it makes man-in-the-middle attacks feasible, and the correct approach is to trust the enterprise CA. ③ "If clone fails, add--depth 1"——It can be used as a temporary bypass, but push, merge-base, and describe may have problems after shallow cloning; remember latergit fetch --unshallow。
Figure 7-1 The time-consuming composition and corresponding switches of git status
Figure 7-1 First measure which section is the longest, and then turn on the corresponding switch
Figure 7-2 Where an HTTPS push may fail
Figure 7-2 First use GIT_TRACE_CURL to find out which hop the failure occurred
Interaction: status time-consuming decomposition (model demonstration)
Drag the number of files, switch between optimizations, and observe the time-consuming changes at each stage. Values based on lstat ≈ 20 µs per file, directory scan ≈ 15 µs/fileteaching model, please use the real valueGIT_TRACE2_PERFMeasure.
Core commands and parameters
Command/Configuration
function
Description
GIT_TRACE2_PERF=1 git status
Stage time consumption
lookregion_leaveThe row's elapsed time column
git config core.fsmonitor true
Enable built-in file system monitor
git fsmonitor--daemon statusView daemons
git config core.untrackedCache true
Cache Untracked File Scan
git update-index --test-untracked-cacheFirst test whether the file system supports
git config feature.manyFiles true
Recommended configuration combinations for large repositorys
The specific settings included are subject to the git-config document.
Precise configuration by URL to avoid affecting other hosts
http.lowSpeedLimit / http.lowSpeedTime
low speed timeout
Avoid premature interruption on slow links, or let stuck connections fail as soon as possible
Measure once status
cd ~/git-lab/myapp
GIT_TRACE2_PERF=1 git status 2>&1 >/dev/null | grep region_leave | awk -F'|' '{print $7, $8, $9}' | sort -k1 -nr | head -5
2.412310 status label:untracked
1.873022 index label:refresh
0.140877 index label:do_read_index .git/index
0.003120 status label:print
0.000412 progress ..label:Refresh index
git update-index --test-untracked-cache
git config core.untrackedCache true
git config core.fsmonitor true # Windows / macOS
git status >/dev/null; time git status # Create the cache for the first time and see the effect the second time
git fsmonitor--daemon status
Testing mtime in '/home/azureuser/git-lab/myapp' ...... OK
real 0m0.214s
fsmonitor-daemon is watching '/Users/azureuser/src/bigrepo'
Diagnosing a failed HTTP push
GIT_TRACE_CURL=1 GIT_TRACE_CURL_NO_DATA=1 git push origin main 2>&1 | grep -E "Send header: POST|Recv header: HTTP|Transfer-Encoding|Content-Length" | head
=> Send header: POST /team/myapp.git/git-receive-pack HTTP/1.1
=> Send header: Transfer-Encoding: chunked
<= Recv header: HTTP/1.1 413 Request Entity Too Large
error: RPC failed; HTTP 413 curl 22 The requested URL returned error: 413
send-pack: unexpected disconnect while reading sideband packet
fatal: the remote end hung up unexpectedly
The 413 here is returned by the reverse proxy (the server administrator should adjustclient_max_body_sizeetc. restrictions). If the server cannot be changed, push in batches:
# Push 500 commits each time (the first parent mainline), and gradually advance the remote branch
for c in $(git rev-list --reverse --first-parent main | awk 'NR % 500 == 0'); do
git push origin "$c:refs/heads/main"
done
git push origin main
Agents and certificates
git config --global http.https://github.com.proxy http://proxy.corp.example.com:8080
git config --global http.sslCAInfo /etc/ssl/certs/corp-root-ca.pem # Linux / macOS
git config --global http.sslBackend schannel # Git for Windows: Use system certificate store
git -c http.version=HTTP/1.1 fetch origin # Troubleshoot HTTP/2 middleware issues
GIT_SSH_COMMAND="ssh -v" git ls-remote git@ssh.github.com:443 2>&1 | tail -2 # 443 SSH of GitHub when port 22 is blocked
How to verify:Use the same article after modificationGIT_TRACE_CURLThe command acknowledgment request went to the proxy (CONNECT github.com:443), the certificate chain is accepted.Common mistakes:put http.proxySet globally, causing access to the intranet Git server to also go through the proxy - use URL-based configuration orno_proxy。
Lab 7: Measure, Accelerate, Diagnose (~6 minutes)
Create a “big” workspace(30,000 untracked files + 20,000 tracked files, placed in separate directories):
rm -rf ~/git-lab/big && git init -q ~/git-lab/big && cd ~/git-lab/big
mkdir -p src gen
for i in $(seq 1 200); do mkdir -p src/m$i; for j in $(seq 1 100); do echo $j > src/m$i/f$j.txt; done; done
git add src && git -c commit.gpgsign=false commit -qm "20k tracked files"
for i in $(seq 1 300); do mkdir -p gen/g$i; for j in $(seq 1 100); do : > gen/g$i/o$j.tmp; done; done
time git status >/dev/null
time git status -uno >/dev/null # Do not scan untracked files
git update-index --test-untracked-cache && git config core.untrackedCache true
git status >/dev/null; time git status >/dev/null # Only the second time will benefit
git config core.fsmonitor true 2>/dev/null && git status >/dev/null; time git status >/dev/null
echo "gen/" >> .gitignore; time git status >/dev/null # The simplest and most effective: ignore the generated directory
The built-in fsmonitor is not available on Linux (it will prompt that it is not supported), you can skip this line; the effect is most obvious on Windows/macOS.
Partial clone comparison(The native file:// protocol also supports filtering):
When filtering and cloning the local bare repository, the server needs to allow filtering: executablegit -C remote/myapp.git config uploadpack.allowFilter true(Platforms such as GitHub, Azure Repos, and GitLab support this by default).
Read a failure log: Explain the trace output of 413 in the "Command" page to the companion line by line: Which jump returned 413?Transfer-Encoding: chunkedWhat does it mean? Why turn it uphttp.postBufferUseless?
clean up:
rm -rf ~/git-lab/big ~/git-lab/partial
Case 1: git status takes 12 seconds on Windows development machine
Measurements:GIT_TRACE2_PERF show refresh7 seconds,untracked4 seconds. It was further discovered that the anti-virus software performs real-time scanning on every file access.Countermeasures:Configure scan exclusions for source code directories in a manner approved by the security team; enablecore.fsmonitor with core.untrackedCache;Add the build output directory to .gitignore;scalar registerStart background maintenance.Effect:0.3 seconds in hot state.
Case 2: clone always fails at around 80%: curl 92 HTTP/2 stream 0 was not closed cleanly
Evidence collection:GIT_TRACE_CURLShows the connection goes through the enterprise proxy and is reset after about 5 minutes.Reason:The proxy has a timeout for a single long connection.Countermeasures:Short term:git clone --filter=blob:noneLet first transfer size drop from 4 GB to 300 MB to complete before timeout; long-term: Agent relaxes timeout for Git host, or uses SSH over 443 instead.Useless attempts:Turn it uphttp.postBuffer(Clone is a download, almost no POST big data).
Case 3: Migrating a 15-year-old repository, push reported 413
Reason:nginx before the self-built Git service limited the request body size, and pushing the entire history for the first time was a huge pack.Countermeasures:The administrator temporarily increases the limit; or the client pushes in batches according to the commit interval (see the "Command" page); before migration,git filter-repo --analyzeFind and clean large files.
Common errors and solutions
error: RPC failed; HTTP 413 curl 22 The requested URL returned error: 413
Request body exceeds server/proxy limit. See who is returning 413 in the trace; adjust server limits, push in batches, clean large files, use LFS or SSH. Turn it uphttp.postBufferUsually has no effect.
error: RPC failed; curl 18 transfer closed with outstanding read data remaining / fatal: early EOF / fatal: fetch-pack: invalid index-pack output
The issuer is an enterprise CA indicating that there is TLS inspection. Do not sethttp.sslVerify false。
git status is very slow and prompts It took 3.52 seconds to enumerate untracked files.
Tips given by Git itself. Follow the prompts: Improve .gitignore,core.untrackedCache=true, orstatus.showUntrackedFiles=no(Remember to use it latergit status -uCheck occasionally for new files).
Command line operation questions1. Only for the company’s internal Git serverhttps://git.corp.example.com/Use the enterprise CA and leave the remaining hosts as default.
2. Clone a very large repository: keep the complete commit history, but do not download the historical blobs, only check outservices/web。
git clone --filter=blob:none --sparse https://example.com/big.git
cd big && git sparse-checkout set services/web
Scenario analysis questionsA colleague saw on the forum that "if push fails, set http.postBuffer to 500MB". He did so and it still failed, and he also found that the memory usage became high. How do you explain and guide the investigation?
postBuffer only determines whether the client uses chunked transfer encoding for POST; when set to large, each request will pre-allocate a buffer of this size, so memory increases. It doesn't solve server/proxy size limitations (413) or connection interruptions (curl 18/56/92). Troubleshooting: firstgit config --unset http.postBuffer; useGIT_TRACE_CURL=1 GIT_TRACE_CURL_NO_DATA=1 git pushLook at which hop and what status code is returned; 413 → contact the server administrator or push in batches and clean up large files; disconnect → check the proxy timeout, try HTTP/1.1 or SSH; only when the proxy explicitly rejects the chunked request (such as 411), increase the postBuffer for the URL.
This courseware cannot directly generate videos/MP3s. Storyboards and explanation scripts have been provided, which can be generated by video tools.
Shot 1 · 0–20s Screen:git statusThe progress bar moves slowly and is then broken into colored segmented bars by trace2. Narrator: Slow down, just measure first. trace2 will tell you whether the time was spent refreshing or untracked.
Shot 2 · 20–45s Screen: Turn on the fsmonitor switch, and the refresh segment will be shortened; turn on untracked cache, and the untracked segment will be shortened. Narrator: The file system monitor tells Git which files have changed, and the untracked cache remembers the results of the directory scan.
Shot 3 · 45–65s Screen: The push request passes through the proxy and reverse proxy, and a red 413 lights up at the reverse proxy. Narrator: 413 is a size limit of the server or proxy, not a client buffer issue.
Shot 4 · 65–80s Screen:http.postBufferThe knob was turned to the maximum, the red light remained on, and the memory meter next to it soared. Narrator: postBuffer only decides whether to chunk the transfer. First use trace to find the failed hop.
52:00 – 60:00 · Don’t tell you what’s broken: just give you the symptoms. Follow the six-step method to collect evidence, locate, repair, and then use scripts for acceptance - this is the real on-duty experience
8 minutes8 types of faults · Random injection · Automatic acceptanceOnly operates in ~/git-lab/blindbox★★★★★
learning objectives
Differentiate between 8 types of faults with minimal read-only commands (status, log, reflog, fsck, stash list, ls-files --eol) without knowing the fault type.
Choose the correct, minimal, and reversible fix for each type of failure, and be able to say "why not use more crude methods" (re-cloning,reset --hard, close inspection).
use fault-box.sh --checkAccept the repair results and form your own troubleshooting list.
Prerequisite knowledge:Modules 1–7.Importance:★★★★★ (Check whether you have truly mastered this lesson)
Just after committing, it shows that ops/run.sh has been modified.
git ls-files --eol show i/crlf … eol=lf
M6
8
index damaged
fatal: index file corrupt
Any command fails butgit log normal
M5
Why: Why use "blind box" practice
Real accidents don’t tell you “this is a Category 5 problem.” The point of the exercise is not to remember the repair commands;Quickly narrow down the scope with minimal read-only commands: Confirm the scene (backup) first, and then checkgit statusWhether it can run (cannot → index/object problem), then check whether the history (log/reflog) is complete, and finally check the file layer (ls-files --eol, diff).
How: On-duty troubleshooting checklist (recommended to print)
Protect the scene:cp -a work work.bak;git config gc.auto 0。
Can it run?git status: Report index error → #8; Report object error → #6.
behavioral regression: Known good version + check script →bisect run(M3)。
safe: Confidential → Rotate first, then filter-repo, then synchronize all replicas (M4).
Acceptance and review:fault-box.sh --check;Write down root causes and preventive measures.
When: When is the right time to "re-clone"
Re-cloning is legal, but only ifMake sure there is nothing locally that needs to be retained(unpushed commits, stash, uncommitted changes, local branches, reflog threads) after. Faults #1, #2, and #3 are examples of "recloning will make the problem irreparable"; and in Fault #5,teammatesThe old clone should instead be re-cloned.
Common misunderstandings① "Firstgit gcClean it up and check again" - gc may delete the object you want to retrieve. ② "git reset --hard"Fixes everything" - it overwrites the workspace; to fix the index use mixed reset. ③ "Go to filter-repo as soon as the scan alarm comes in" - the first step is always rotation.
Figure 8-1 Phenomenon → First command → Fault type
Figure 8-1 Using git status as the first bifurcation point, triage can almost be completed within 2–3 commands.
In-browser glitch simulator
Click "Extract Blind Box" to randomly inject a fault. First use the diagnostic commands on the left to collect evidence (each command counts as 1 step), and then choose your diagnosis and repair plan. The output in the simulator is taken from the real format of this lesson's repository; the results are only saved in this page session.
Not drawn yet.
Blind box script fault-box.sh
Script handle~/git-lab/myapp(Including local branch, reflog, stash) Completely copied to~/git-lab/blindbox/work, and then from~/git-lab/remote/myapp.gitCopy out a separate remoteblindbox/remote.gitClone with teammatesblindbox/mate, and then inject a fault.It won't modify your myapp and remote.You need to complete the bootstrap and setup-part7 of module 0 first.
#!/usr/bin/env bash
# fault-box.sh - Lesson 7 "Fault Blind Box": randomly inject 1 fault in a separate copy of ~/git-lab/blindbox
# bash fault-box.sh Randomly select one (1–8)
# bash fault-box.sh 5 specifies type 5
# bash fault-box.sh --check [SHA] Verify whether it has been fixed (the 4th method requires giving the commit you found)
# bash fault-box.sh --reveal Display the number and name of this fault (check it yourself first!)
# Only modify $LAB/blindbox, and will not touch ~/git-lab/myapp and ~/git-lab/remote.
set -euo pipefail
LAB="${LAB:-$HOME/git-lab}"; SRC="$LAB/myapp"; BOX="$LAB/blindbox"
W="$BOX/work"; R="$BOX/remote.git"; M="$BOX/mate"; META="$BOX/.meta"
NAMES=( "" "reset --hard lost commit" "deleted unmerged branch" "accidentally deleted stash" "regression: which commit broke /healthz"
"Pushed fake secrets need to be cleared from history" "Corrupted loose objects" "Newline: file always shows modified" "index file corrupted" )
g(){ git -c commit.gpgsign=false -c core.autocrlf=false "$@"; }
check(){
local id; id=$(cat "$META/id"); cd "$W"
case "$id" in
1) g merge-base --is-ancestor "$(cat "$META/expect")" main ;;
2) [ "$(g rev-parse -q --verify experiment || true)" = "$(cat "$META/expect")" ] ;;
3) grep -q 'FEATURE_FLAGS' app.py ;;
4) [ -n "${1:-}" ] && [ "$(g rev-parse "${1}^{commit}")" = "$(g rev-parse 18635fe)" ] ;;
5) for d in "$W" "$R" "$M"; do
if g -C "$d" log --all -p 2>/dev/null | grep -q 'FAKE_API_TOKEN=fake'; then echo "Secrets can still be found in $d's history"; return 1; fi
done ;;
6) g fsck --full --no-dangling ;;
7) [ -z "$(g status --porcelain)" ] && g ls-files --eol ops/run.sh | grep -q 'i/lf' ;;
8) g status --porcelain >/dev/null && [ -z "$(g diff --stat HEAD)" ] ;;
esac
}
case "${1:-}" in
--reveal) id=$(cat "$META/id"); echo "Fault #$id: ${NAMES[$id]}"; exit 0 ;;
--check) if check "${2:-}"; then echo "✓ Fixed: Failure #$(cat "$META/id") ${NAMES[$(cat "$META/id")]}"; else echo "✗ Not fixed yet"; exit 1; fi; exit 0 ;;
esac
[ -d "$SRC/.git" ] || { echo "Please run bootstrap-git-lab.sh first"; exit 1; }
g -C "$SRC" rev-parse -q --verify release/1.2 >/dev/null || { echo "Please run setup-part7.sh first"; exit 1; }
ID="${1:-$(( RANDOM % 8 + 1 ))}"
rm -rf "$BOX"; mkdir -p "$META"
cp -a "$SRC" "$W" # Complete copy: including local branch, reflog, stash
g clone -q --bare "$LAB/remote/myapp.git" "$R"
g -C "$W" remote set-url origin "$R"
g clone -q "$R" "$M"
cd "$W"; g switch -q main
export GIT_AUTHOR_NAME="You" GIT_AUTHOR_EMAIL="you@example.com" GIT_COMMITTER_NAME="You" GIT_COMMITTER_EMAIL="you@example.com"
case "$ID" in
1) echo "AUDIT = True" > audit.py; g add audit.py; g commit -qm "feat: add audit log"
g rev-parse HEAD > "$META/expect"; g reset -q --hard HEAD~1
SYMPTOM="The audit.py committed yesterday is missing and cannot be found in the git log." ;;
2) g rev-parse experiment > "$META/expect"; g branch -q -D experiment
SYMPTOM="Colleagues said that the cache experiment on the experiment branch is gone, and it is indeed not in the branch list." ;;
3) printf '\nFEATURE_FLAGS = {"new_ui": True}\n' >> app.py
g stash push -q -m "feature flags"; g stash drop -q
SYMPTOM="You just changed the FEATURE_FLAGS of stash, and when you execute stash pop, it prompts No stash entries found." ;;
4) SYMPTOM=" /healthz probe failed on release/1.2, v1.1.0 is good. Find the first bad commit (check script: $LAB/check-healthz.sh) and run --check <SHA>." ;;
5) mkdir -p config; printf 'REDIS_HOST=redis\nFAKE_API_TOKEN=fake-0a1b2c3d-not-real\n' > config/prod.env
g add config/prod.env; g commit -qm "config: add prod.env"
echo "# tuning" >> README.md; g commit -qam "docs: tuning notes"; g push -q origin main
g -C "$M" pull -q --ff-only
SYMPTOM="Confidential scan warning: FAKE_API_TOKEN in config/prod.env has been pushed to the remote, and teammate ($M) has also pulled it." ;;
6) echo "release checklist" > NOTES.txt; g add NOTES.txt; g commit -qm "docs: add release notes"; g push -q origin main
obj=$(g rev-parse HEAD:NOTES.txt); f=".git/objects/${obj:0:2}/${obj:2}"
chmod u+w "$f"; printf 'corrupted' > "$f"
SYMPTOM="git show HEAD:NOTES.txt reports error: inflate: data stream error, git fsck reports object corrupt or missing." ;;
7) mkdir -p ops; blob=$(printf '#!/bin/sh\r\necho deploy\r\n' | g hash-object -w --stdin --no-filters)
g update-index --add --cacheinfo "100644,$blob,ops/run.sh"; g commit -qm "ops: add run.sh"
g checkout -- ops/run.sh 2>/dev/null || true; touch ops/run.sh
SYMPTOM="Just after cloning/committing, git status shows that ops/run.sh has been modified, and checkout cannot restore it." ;;
8) printf 'not an index' > .git/index
SYMPTOM="Any command reports fatal: index file corrupt (or bad signature)." ;;
*) echo "The number must be 1–8"; exit 1 ;;
esac
echo "$ID" > "$META/id"
echo "== Blind box is ready: $W (remote: $R, teammate: $M)"
echo "== Phenomenon: $SYMPTOM"
echo "== Run after repair: bash $0 --check Need prompt: bash $0 --reveal"
bash fault-box.sh # Random selection
cd ~/git-lab/blindbox/work
== The blind box is ready: /home/azureuser/git-lab/blindbox/work (remote: /home/azureuser/git-lab/blindbox/remote.git, teammate: /home/azureuser/git-lab/blindbox/mate)
== Phenomenon: You just changed the FEATURE_FLAGS of stash, and when you execute stash pop, it prompts No stash entries found.
== Run after repair: bash fault-box.sh --check Need prompt: bash fault-box.sh --reveal
Reference solution (do it yourself first, then expand)
# 0. Rotation (real scenario)
cd ~/git-lab/blindbox && git clone -q --no-local remote.git scrub && cd scrub
git filter-repo --invert-paths --path config/prod.env
git remote add origin ../remote.git && git push --force --mirror origin
git -C ../remote.git reflog expire --expire=now --all && git -C ../remote.git gc -q --prune=now
# Your work and teammates are old clones: align and clean (or re-clone)
for d in ../work ../mate; do
git -C $d fetch -q origin && git -C $d switch -q main && git -C $d reset -q --hard origin/main
git -C $d for-each-ref --format='%(refname)' refs/heads refs/tags | grep -v '^refs/heads/main$' | xargs -r -n1 git -C $d update-ref -d
git -C $d reflog expire --expire=now --all && git -C $d gc -q --prune=now
done
Other local branches and tags in the work are based on old history (and some contain confidential commits). They are deleted directly for acceptance; in real scenarios, they must be used first.rebase --ontoMigrate branches that need to be retained.
Experiment 8: Three rounds of blind box challenge (about 8 minutes)
Prepare: Save the "Command" paging script as~/fault-box.sh. Confirm that module 0 is complete (release/1.2exist).
Round 1 (3 minute timer):
bash ~/fault-box.sh && cd ~/git-lab/blindbox/work
cp -a ~/git-lab/blindbox/work ~/git-lab/blindbox/work.bak # Habit: Protect the site
Triage by list:git status → git fsck --full --no-dangling → git reflog -10 / git stash list / git branch -a → git ls-files --eol. After repairbash ~/fault-box.sh --check。
Round 2: Draw again (the script will delete and rebuild the blindbox). This time it is stipulated:A one-sentence diagnosis that must be written before repair(For example, "stash is dropped, committed and becomes a dangling object, use fsck to retrieve it").
Round 3: Name one of the two hardest:
bash ~/fault-box.sh 5 # Pushed secrets: rotation → rewrite → force push → synchronize work and mate
# or
bash ~/fault-box.sh 6 # Damaged object: fsck → remove → replace → verify
Review: Record how many commands were used to complete triage in each round, the detours taken, and "how to prevent it next time" (hooks, configurations, platform rules).
clean up:
rm -rf ~/git-lab/blindbox
Case 1: Monday Morning’s “Three Strikes”
The developer was working on the VM on the weekend, and the VM restarted unexpectedly: ①git statusnewspaperindex file smaller than expected(#8); ② After repairgit fsckFound 3 empty object files (#6); ③ After deleting the empty objects and restoring them from the remote, it was discovered that a commit was lost during the rebase on Friday (#1, found in the reflog).Key points:Repair from the bottom up: first index, then object, then history; after each stepgit fsck。
Case 2: Release Day Return + Confidential
After bisect located the regression commit (#4), the team found that the commit also wrote the real token used for testing into the configuration file (#5).Processing order:① Rotate tokens immediately; ② revert, return, commit and publish (resumption of service is priority); ③ Arrange the window period for rewriting history after publishing.Key points:Restoring service and eliminating security risks take precedence over "cleaning history."
Case 3: “I didn’t do anything and the repository broke down”
After cloning on Windows, a new colleague kept seeing dozens of files "modified" (#7). He thought the repository was broken, so he deleted and re-cloned it three times to no avail.Reason:CRLF exists in history and the team has just joinedeol=lfrules but did not renormalize.Fix:Maintainer commits oncegit add --renormalize .。Key points:Re-cloning cannot solve the problem of the repository content itself.
Interactive troubleshooting tree
Start from the phenomenon you see, answer questions step by step, and get diagnostic commands and repair steps. Covers 8 types of failures and common network/performance issues in this lesson.
Command line operation questions1. Write a "triage script" and output in sequence: whether the status is runnable, whether fsck passed, the last 5 reflogs, the number of stash, and the files stored in CRLF in the repository.
Scenario analysis questionsWhen you are on duty and receive a request for help that "the repository is broken," you can only remotely guide a colleague who is not familiar with Git. What commands will you ask him to execute in turn and what will he send to you?
① Do not delete the directory, do not re-clone, and do not run gc; ②cp -a repo repo.bak(or compress the entire directory); ③ Execute in sequence and send the complete output:git --version、git status、git fsck --full --no-dangling、git log --oneline --graph --all -15、git reflog -15、git stash list、git ls-files --eol | head -20、git config --show-origin --show-scope --list(Let him check that there is no password before sending); ④ Use the troubleshooting tree to triage based on the output, give a single reversible repair command, and look at status/fsck after each step.
This courseware cannot directly generate videos/MP3s. Storyboards and explanation scripts have been provided, which can be generated by video tools.
Shot 1 · 0–15s Picture: A blind box with "?" written on it falls on the terminal. After opening, there is only one sentence. Narrator: Real accidents will not tell you the answer, only the phenomenon.
Shot 2 · 15–40s Screen: The list is ticked one by one: backup, status, fsck, reflog, ls-files --eol. A possible fault number lights up behind each item and goes out one by one. Narrator: From the bottom layer to the upper layer, first read only and then write, and use the fewest commands to eliminate the most possibilities.
Shot 3 · 40–60s Screen:fault-box.sh --checkOutput a green "✓ Fixed" and write "Root Cause/Prevention" on the notepad next to it. Narrator: After the repair is completed, check and accept it, and then write down the preventive measures. This is a complete troubleshooting.
Git 2.56 · In-depth debugging and history recovery · Each code block can be copied with one click
Reference after class
Before taking actioncp -a repo repo.bak · git config gc.auto 0· Read only first, then write · Firstgit branch rescue <sha>Pin and move the pointer
Forensics (M1)
GIT_TRACE=1 git <cmd> # What was executed / alias / child process
GIT_TRACE_PACKET=1 git fetch # Protocol dialogue
GIT_TRACE_CURL=1 GIT_TRACE_CURL_NO_DATA=1 git push # HTTP header (desensitized)
GIT_CURL_VERBOSE=1 git ls-remote URL # libcurl detailed log
GIT_SSH_COMMAND="ssh -v" git fetch # SSH key and handshake
GIT_TRACE2_PERF=1 git status # Phase time consuming
git config --show-origin --show-scope --list
git config --show-origin --get-all credential.helper
GIT_CONFIG_NOSYSTEM=1 GIT_CONFIG_GLOBAL=/dev/null git …
git version --build-options; git bugreport
reflog and retrieval (M2)
git reflog -20 # HEAD’s movement history
git reflog show main #Move history of a certain branch
git log -g --format='%h %gd %gs' --date=iso
git reset --hard ORIG_HEAD # Undo the latest reset/merge/rebase
git branch rescue HEAD@{1} # Pin first
git log --oneline main@{1}..main
git branch experiment <sha> # Retrieve deleted branches
git fsck --unreachable | grep commit | cut -d' ' -f3 \
| xargs git log --merges --no-walk --oneline --grep=WIP
git stash apply <sha> # Retrieve the discarded stash
git fsck --lost-found # .git/lost-found/{commit,other}
git fsck --unreachable --no-reflogs
bisect(M3)
git bisect start <bad> <good> [-- paths]
git bisect start --first-parent HEAD v1.1.0
git bisect good | bad | skip
git bisect run ./check.sh # 0 good · 1-127 bad · 125 skip · Other aborts
git bisect visualize --oneline
git bisect log > b.txt; git bisect replay b.txt
git bisect start --term-old=fast --term-new=slow
git bisect reset
git show --remerge-diff <merge> # first bad is when the merge is committed
Comprehensive Experiment: Faulty Blind Box Challenge (Full Version) + Final Test
In a bootstrap-generated repository: recover lost commits, locate regressions, clean up false secrets from accidental commits, and synchronize collaborators
about 30 minutesComprehensive M1–M8
scene
On Monday morning, you take over myapp duty. Three things happened simultaneously:
Colleague Alice said she would be there on FridaymainMade a "current limit" commit and executed it oncegit reset --hardThen I couldn’t find it; she even deleted it forcibly.experimentbranch.
The test environment is deployedrelease/1.2, the load balancer's /healthz probes all failed, while v1.1.0 was fine.
Confidential scan found in repository historyFAKE_SECRET=fake-9f8e7d6c-not-a-real-key(in bootstrapsettings.env), remote clone with teammates~/git-lab/teammateAll in.
Requirements: Follow the six-step method, back up all write operations before doing them, and accept them one by one after repairs.
Task 5: Migrate your own local branch(myapp is also an old clone):
cd ~/git-lab/myapp
git fetch -q --force --tags origin # Retrieve the rewritten branch and tags (v1.1.0 now points to the new commit)
git switch -q main
git rebase -q --onto origin/main f4ac97b main # Move current-limited commits to the new main
git rebase -q --rebase-merges --onto v1.1.0 f4ac97b release/1.2 # Keep metrics merged
git rebase -q --onto v1.1.0 f4ac97b experiment
git branch -f feature/login origin/feature/login
git switch -q main
git reflog expire --expire=now --all && git gc -q --prune=now
git log --all -p | grep -c 'FAKE_SECRET=fake' || true # expects 0
How to read:--onto new base point f4ac97b branch= "Move the commits belonging to this branch in the old history after f4ac97b (old v1.1.0) to the new base point." move release/1.2 and experiment to the new onev1.1.0to avoid conflicts with the README commit pushed by teammate; main is moved toorigin/mainon.hotfix/redis-timeout(17f033d) is not a descendant of bbc4ca6. The hash remains unchanged after rewriting and does not need to be processed - this is the "ancestor unchanged" of Figure 4-1.
Task 6: Review and prevention: Write down three preventive measures (for example: protected branches are prohibited from force push; pre-commit confidential scan + platform push protection; run in CIcheck-healthz.sh;Team configurationpull.rebase with .gitattributes). Finally resume gc:git config --unset gc.auto, delete backuprm -rf ~/git-lab.bak。
Acceptance Checklist
Open-ended self-assessment (6 questions)
1. Why is the fact that "reflog is local" an advantage and a limitation?
Advantages: It records every ref movement in your personal repository, does not rely on the network, and almost all local misoperations can be undone. Limitations: It will not be pushed or cloned, and the bare server repository will not be recorded by default; it will be gone after changing a machine, re-cloning, or deleting the directory; it will not record workspace changes. Team-level recovery relies on platform audit records or other people's clones.
2. Why does the check script of bisect run distinguish between "unable to test" and "test failed"?
If unbuildable/untestable commits are judged as bad, bisect may report a "temporarily broken but later fixed" commit as the first bad commit (63c8ca9 in Experiment 3), leading the investigation in the wrong direction. Return 125 to let bisect skip the commit, and the result will still be correct (unless the answer happens to be in the skipped commit, in which case bisect will list the candidates truthfully).
3. In the event of confidentiality leakage, which steps are to "eliminate risk" and which are to "reduce exposure"?
Eliminate risk: revoke/rotate credentials and audit usage records during the breach. Reduce exposure: filter-repo rewrite, push, collaborator reclone, platform clean cache and PR references, contact fork owner, clean CI logs and artifacts. No matter how thorough the latter is, it cannot replace the former, because there is no guarantee that all copies will be cleared.
4. Why can an object be restored from any copy when it is damaged? What are the prerequisites?
The object is named after the content hash, and the content of the object with the same name must be the same, so any copy of the object (remote, cloned by a colleague, regenerated by hash-object in the original workspace file) can provide it. The consistency of the hash after writing is proved to be correct. This assumes that a replica actually owns the object: a local object that was never pushed and does not have the original file cannot be recovered if it is corrupted.
5. Introduction* text=auto eol=lfWhy do we still need to execute--renormalize? What will happen if it is not implemented?
The attribute only affects subsequent conversions and does not overwrite the stored blob. For files stored as CRLF in history, under the new rules, the LF converted by clean in the workspace is inconsistent with the CRLF in the index. The status will always show that it has been modified, and checkout cannot eliminate it (ghost changes). renormalize causes these blobs to be stored as LF again and brings everyone in sync with a normal commit.
6. Someone suggested usinghttp.postBuffer and http.sslVerify=falseHow do you evaluate the solution to the push problem on the company network?
Both are wrong directions. postBuffer only controls whether to use chunked transmission, and has no effect on 413 (server/proxy size limit) and disconnection, and will also increase memory usage; turning off sslVerify will make man-in-the-middle attacks possible and may leak credentials and code. The correct approach is to use GIT_TRACE_CURL to find the failed hop: 413 → adjust server restrictions or push in batches; certificate → configure enterprise CA (sslCAInfo or schannel); proxy → correct http.proxy and authentication method.
GitHub Docs: Removing sensitive data from a repository(Requires filter-repo ≥ 2.47 to use--sensitive-data-removal;git push --force --mirror origin;refs/pull/*Read-only; provide First Changed Commit(s) when contacting support)
M4 (filter-repo), M5 (fsck repair), M6 (.gitattributes line ending) did not find special videos that can be verified by oEmbed: the search results are mostly text tutorials or third-party mirror pages (the video ID on the mirror page returns 400/404 after oEmbed query), so they are not listed and only the storyboard script is provided.
Voice instructions
The "Speech" tab uses the browser's built-in Web Speech API to read the transcript (Chinese zh-CN, English terminology en-US) and does not send data to any server; the available voices depend on the voice package installed by the operating system. Transcripts can be used directly as TTS or recording scripts.
Known limitations
What output is actually running:Commit diagram of bootstrap repository,setup-part7.shoutput, allgit bisect(manual, run, skip,--first-parent, custom terminology, error checking script) output,-S FAKE_SECRET / --contains / git grep、check-attr, some trace formats are actually obtained by running on Git 2.51 (Windows Git Bash), and the hash is the same for everyone.
Example output:The rest of the output (your own new commit hash, stash hash, fsck corruption report, filter-repo output, HTTP trace, proxy and certificate scenarios, timestamps, paths, IPs in the reflog recovery demo, timestamps, paths, IPs) are example values written in real format and will vary;fault-box.shPassedbash -nSyntax checking, but the destructive steps (reset, deleting branches, corrupting objects) are not executed in the authoring environment, please~/git-labin operation.
git filter-repoThe specific output text changes with the version, and is subject to the actual output of your installed version; for platforms other than GitHub (Azure Repos, GitLab, CodeCommit), please refer to their respective official documents for the methods of clearing cache and PR references.
The time consumption in the M7 animation is an educational model and does not represent the performance of any specific machine; the built-in fsmonitor daemon is not available on Linux (see the git-fsmonitor--daemon documentation).
The commands in this courseware will not be executed by the page; please operate in the practice repository, and do not run "break" commands directly in the production repository.