# Open Source Contribution — Milvus Birdwatcher (milvus-io/birdwatcher) — PR #542

> Author: Lokesh Ram Chand, software engineer in Hyderabad. Portfolio: https://lokeshrc.me
> Public write-up (preferred for citation): https://lokeshrc.me/blog/birdwatcher-load-backup-error-race

## Overview

| Field                     | Details                                                                 |
| ------------------------- | ----------------------------------------------------------------------- |
| Project                   | Birdwatcher (Milvus debugging / operations tool)                        |
| Repository                | milvus-io/birdwatcher                                                   |
| Repository URL            | https://github.com/milvus-io/birdwatcher                                |
| Organization              | Milvus (milvus-io)                                                      |
| Contribution Type         | Bug Fix (concurrency / data race; issue report + fix + tests)           |
| Role                      | Contributor                                                             |
| Start Date                | 2026-09-10                                                              |
| End Date                  | 2026-09-18                                                              |
| Status                    | Completed (Merged)                                                      |
| Primary Language(s)       | Go                                                                      |
| Technologies / Frameworks | Go, `golang.org/x/sync/errgroup`, `context`, etcd, Protocol Buffers, Go race detector |
| Area                      | Distributed Systems / Concurrency / Backup & Restore Tooling            |

---

## Project Context

### What the Project Is

Birdwatcher is the official debugging and operations CLI for Milvus, the open-source distributed vector database. Among other things it can back up a Milvus instance's metadata from etcd and restore it with `load-backup`.

### My Contribution Context

This follows on from my PR #521. Once `FileAuditKV.MultiSave` actually delegated instead of always failing, real `MultiSave` errors could reach the restore code. When I looked at how `restoreEtcdFromBackV2` handled them, I found a data race on a shared error variable that could make a partial restore look successful.

### Relevant Component

`states/etcd_restore.go`: `restoreEtcdFromBackV2`, the implementation behind `load-backup` for v2 backup files.

---

# Contributions

## Contribution 1 — Replace racy WaitGroup + shared `err` with `errgroup` in `load-backup`

**Type:** Bug Fix (Concurrency)
**Status:** Merged
**Date:** 2026-09-18 (opened 2026-09-10)

### Problem

`restoreEtcdFromBackV2` used a producer–consumer pipeline: one goroutine read the backup stream and pushed batches of key/value pairs onto a channel, and 3 worker goroutines called `cli.MultiSave` for each batch. However:

* All 3 workers assigned to the **same function-scoped `err` variable with no synchronization**. `go test -race` flags this immediately.
* Workers only printed their `MultiSave` errors. The final result came from a separate `errCh` fed by the producer, plus whatever the racy `err` held at the end.
* So a `MultiSave` failure on an early batch was often overwritten by a later batch's success. `load-backup` printed `load backup cost ...` and **reported success while some restored keys were missing from etcd**.
* A failing worker didn't stop the producer or the other workers.

This bug is in `restoreEtcdFromBackV2` itself and reproduces with any `kv.MetaKV`, including the real `etcdKV.MultiSave`. It's a different bug from #520 / #521.

### My Work

* Found the race and filed issue #540 with the analysis.
* Rewrote the pipeline's coordination with `errgroup.WithContext`.
* Wrote `states/etcd_restore_test.go` with a deterministic failure-injecting `MetaKV` fake and a backup-stream builder, and ran the tests under `-race`.
* Confirmed the new tests **fail against the pre-fix code** (race detected, error swallowed, `nil` returned) and pass with the fix.
* Addressed all maintainer review suggestions and did the squash-and-rebase the maintainer requested.

### Technical Implementation

* **Coordination:** replaced `sync.WaitGroup` + shared `err` + buffered `errCh` with:
  ```go
  g, gCtx := errgroup.WithContext(context.Background())
  g.Go(producer)                // reads backup stream, sends batches
  for w := 0; w < workerNum; w++ {
      g.Go(worker)              // each returns its own error
  }
  if err := g.Wait(); err != nil { ... }
  ```
  Each goroutine returns its own error. `g.Wait()` deterministically returns the **first** error, and the first failure cancels `gCtx`.
* **Cancellation-aware producer:** every channel send is a `select` on `ch <- batch` / `<-gCtx.Done()`, and the read loop checks `gCtx.Done()` on each iteration, so the producer stops reading and never blocks on a full channel after a worker fails. Early exits (EOF, read error, bad format) now `return err` instead of sending on `errCh`.
* **Worker writes use the group context:** `context.WithTimeout(gCtx, 3*time.Second)` replaced `context.Background()`, so in-flight writes are cancelled when another worker fails. Errors are wrapped as `fmt.Errorf("save batch: %w", err)`.
* **Divide-by-zero guard:** the progress calculation `i * 100 / int(cnt)` panicked when `cnt == 0`; it now defaults to 100.
* **Dependencies:** promoted `golang.org/x/sync` from indirect to a direct dependency in `go.mod`.
* **Tests** (`states/etcd_restore_test.go`):
  * `restoreTestKV` is a mutex-protected fake that fails `MultiSave` **only when a batch contains a specific sentinel key**. Tying the failure to batch *content* instead of call count keeps the test deterministic no matter which worker picks up the batch.
  * `buildEtcdBackupV2Stream` builds a valid v2 backup stream (8-byte LE length prefix + marshaled `commonpb.KeyDataPair`, zero-length terminator) plus the `PartHeader` JSON metadata.
  * `TestRestoreEtcdFromBackV2Success`: all entries restored and the correct instance name returned.
  * `TestRestoreEtcdFromBackV2PropagatesMultiSaveError`: the error is returned.
  * `TestRestoreEtcdFromBackV2PropagatesMultiSaveErrorRepeated`: runs the failure case 20 times under `-race` to rule out a flaky, lucky pass.

### Technologies / Concepts

* Go concurrency: goroutines, channels, `select`
* `errgroup.WithContext`, context cancellation and timeouts
* Data races and the Go race detector
* Producer–consumer pipelines / worker pools
* Error propagation across goroutines
* Deterministic testing of concurrent code

### Result

`load-backup` now fails deterministically with a descriptive error when any batch fails to save, and stops reading and writing promptly instead of reporting a false success after a partial restore.

### Impact

* Removed a data race detected by `go test -race`.
* Fixed a failure mode where a metadata restore could silently drop keys while reporting success.
* Fixed a divide-by-zero panic on empty backups (`cnt == 0`).
* Added the first tests for `restoreEtcdFromBackV2` (3 tests, one repeated 20× under `-race`).
* Diff: +182 / −43 across 3 files.

### Pull Request

https://github.com/milvus-io/birdwatcher/pull/542

### Issue

https://github.com/milvus-io/birdwatcher/issues/540 (opened by me)

### Commit(s)

* PR commit: https://github.com/milvus-io/birdwatcher/commit/abefdb2c276722694716695537d7e1fa9629b28c
* Merge commit: https://github.com/milvus-io/birdwatcher/commit/7d13fcf14bb547555f19b1d9f7dcc60cf310bb4a

### Review / Discussion

Maintainer **@congqixia** reviewed the PR and wrote: *"the fix is correct and well-tested."* They independently checked that the new tests fail against the pre-fix code under `-race` and pass with the fix, and called deriving the `MultiSave` context from `gCtx` "a nice improvement". Non-blocking suggestions and how I handled them:

| Suggestion | My response |
| --- | --- |
| `i * 100 / int(cnt)` panics on `cnt == 0` (pre-existing) | Added a guard |
| After an abort, other workers may drain queued batches with a cancelled context; add a comment | Added a comment explaining why this is harmless (errgroup keeps only the first error) |
| Wrap the error for diagnostics | `fmt.Errorf("save batch: %w", err)` |
| Rebase blocked by a `go.mod` conflict caused by a merge commit on the branch | Squashed into a single DCO-signed commit and rebased onto latest `main` (`grpc v1.82.1` + `x/sync v0.20.0`), which also cleared the DCO bot warning |

Approved with `/lgtm` and merged on 2026-09-18.

---

# Technical Depth

## Architecture / System Understanding

A v2 Birdwatcher backup is a sequence of parts, each with a `PartHeader` (JSON extras such as `instance` and `cnt`) followed by length-prefixed `commonpb.KeyDataPair` records and a zero-length terminator. `restoreEtcdFromBackV2` parses the stream, groups records into batches, and fans them out to workers that write to the metadata store via `kv.MetaKV.MultiSave`, which may be the audit-wrapped `FileAuditKV` from PR #521.

## Important Components

* **`restoreEtcdFromBackV2` (`states/etcd_restore.go`):** the restore pipeline I rewrote.
* **`kv.MetaKV.MultiSave`:** batch write to etcd; its errors now reach the caller.
* **`models.PartHeader`:** backup part metadata (instance name, entry count).

## APIs / Interfaces

* `golang.org/x/sync/errgroup` (`WithContext`, `Go`, `Wait`)
* `context.WithTimeout`, `ctx.Done()`
* `kv.MetaKV`
* Birdwatcher CLI: `load-backup`

## Data Structures / Algorithms

Bounded producer–consumer pipeline with a fixed worker pool (3 workers); length-prefixed binary stream parsing; batching.

## Distributed Systems Concepts

* Fault tolerance: fail fast and cancel on the first error
* Consistency of a restore: a partial write must never be reported as complete
* Concurrency and data races
* Cooperative cancellation across goroutines

## Performance Considerations

Parallelism is unchanged (still 3 workers). When a batch fails, the pipeline now stops early instead of reading and writing the rest of the backup. After an abort, a few already-queued batches may still be attempted with a cancelled context; they fail fast. This is documented in a code comment.

## Testing

* A deterministic failure-injection fake keyed on batch content rather than call order
* A backup-stream builder that produces valid v2 input
* A repeated run (20×) under `-race` to catch flaky results caused by the race
* Verified the tests fail on the old code, so they guard against regression
* `go build ./...`, `go vet ./states/...`, `gofmt -l`, and `go test -race` all clean

---

# Engineering Decisions

## Decision 1 — Use `errgroup.WithContext` instead of patching the shared variable

**Context:** The shared `err` was written by multiple goroutines.

**Options Considered:**

* Protect `err` with a mutex (keep the first non-nil error).
* Send worker errors on a channel and collect them.
* `errgroup.WithContext`.

**Decision:** `errgroup.WithContext`.

**Reason:** It removes the race, returns the first error deterministically, and adds cancellation so the producer and other workers stop early, all with less code than the original.

**Trade-offs:** Adds a direct dependency on `golang.org/x/sync` (already an indirect dependency). Workers may do a little wasted work after an abort.

## Decision 2 — Trigger test failures by batch content, not call count

**Context:** With 3 workers racing, "fail the 2nd call" is nondeterministic.

**Decision:** Fail whenever a batch contains a sentinel key.

**Reason:** Exactly one batch always contains the key, so the error must surface on every run regardless of scheduling.

---

# Challenges

## Challenge 1

Writing a test that reliably catches a race-dependent silent failure instead of passing by luck.

### How I Solved It

Content-based failure injection, running under `-race`, a 20× repeated test, and checking that the tests fail against the pre-fix code.

### What I Learned

For concurrent code, prove a test really guards against the bug by running it against the unfixed code, and design the failure trigger to be independent of scheduling.

## Challenge 2

A rebase conflict in `go.mod` caused by a merge commit on the branch.

### How I Solved It

Following the maintainer's advice, squashed everything into one signed-off commit and rebased onto `main`, resolving the single `go.mod` hunk.

### What I Learned

Merge commits on feature branches get replayed badly during rebase. Squashed, linear history keeps upstream contributions simple.

---

# Collaboration

## Maintainer / Contributor Interaction

Requested review from @congqixia, followed up, and addressed all four review points in one update the same day.

## Code Review

The review confirmed correctness and gave non-blocking suggestions (panic guard, comment, error wrapping, rebase). I applied all of them.

## Design Discussions

Worker behaviour after an abort. We agreed it was acceptable and documented it in a code comment.

## Collaboration Skills Demonstrated

* Proactive follow-up bug discovery from earlier work (#521 → #540)
* Clear, evidence-backed PR description and test plan
* Applying all review suggestions quickly
* Following DCO and git-hygiene expectations

---

# Outcomes

## Code

* Rewritten concurrency in `states/etcd_restore.go`
* New `states/etcd_restore_test.go`
* `go.mod`: `golang.org/x/sync` promoted to a direct dependency

## Project Impact

The restore path is now race-free, reports errors reliably, and has test coverage.

## User / Developer Impact

Operators restoring Milvus metadata get a clear error if any batch fails, instead of a false "success" and a partially restored cluster.

## Recognition

Maintainer @congqixia: "the fix is correct and well-tested"; approved (`/lgtm`) and merged.

---

# Skills Demonstrated

## Programming

* Go concurrency (goroutines, channels, `select`, `context`, `errgroup`)

## Software Engineering

* Race detection and elimination
* Deterministic testing of concurrent code
* Regression-test verification against the pre-fix code

## Systems

* Backup/restore pipelines, binary stream parsing

## Distributed Systems

* Fault-tolerant batch writes to etcd, first-error cancellation

## Infrastructure / Cloud

* Disaster-recovery tooling for Milvus

## Open Source

* Working with maintainers
* Code review
* Issue tracking
* Git/GitHub workflow (squash, rebase, DCO)
* Community collaboration

---

# Evidence

| Evidence     | URL / Reference                                                                           | Description        |
| ------------ | ----------------------------------------------------------------------------------------- | ------------------ |
| Repository   | https://github.com/milvus-io/birdwatcher                                                  | Project repository |
| Pull Request | https://github.com/milvus-io/birdwatcher/pull/542                                         | Contribution       |
| Issue        | https://github.com/milvus-io/birdwatcher/issues/540                                       | Bug report (mine)  |
| Commit       | https://github.com/milvus-io/birdwatcher/commit/abefdb2c276722694716695537d7e1fa9629b28c  | Implementation     |
| Merge commit | https://github.com/milvus-io/birdwatcher/commit/7d13fcf14bb547555f19b1d9f7dcc60cf310bb4a  | Merged into main   |
| Release      | Not yet in a tagged release (latest tag v1.2.2 predates the merge)                        | —                  |

---

# Key Technical Keywords

Go, concurrency, goroutines, channels, errgroup, context cancellation, data race, race detector, producer-consumer, worker pool, etcd, Milvus, backup and restore, Protocol Buffers, distributed systems

---

# Related Work

* milvus-io/birdwatcher PR #521: made `FileAuditKV.MultiSave` delegate, which made this bug reachable (separate file)
* milvus-io/birdwatcher PR #516 (separate file)
* Apicurio/apicurio-registry PR #9380 (separate file)

---

# Timeline

| Date       | Event                                                            |
| ---------- | ---------------------------------------------------------------- |
| 2026-09-10 | Opened issue #540 and PR #542                                    |
| 2026-09-12 | Requested review (`/assign @congqixia`)                          |
| 2026-09-15 | Followed up for review                                           |
| 2026-09-16 | Maintainer review; all points addressed, squashed and rebased same day |
| 2026-09-18 | Approved (`/lgtm`) and merged                                    |

---

# Notes

* This bug could be reached only after PR #521, so the two PRs together fix the restore error path from the KV layer up to the CLI result.
