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

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

## 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 (issue report + fix + regression tests)                         |
| Role                      | Contributor                                                             |
| Start Date                | 2026-08-12                                                              |
| End Date                  | 2026-09-02                                                              |
| Status                    | Completed (Merged)                                                      |
| Primary Language(s)       | Go                                                                      |
| Technologies / Frameworks | Go, Protocol Buffers (`google.golang.org/protobuf`), etcd, testify      |
| Area                      | Distributed Systems / Developer & Operator Tooling / Metadata Integrity |

---

## Project Context

### What the Project Is

Birdwatcher is the official debugging and operations CLI for Milvus, the open-source distributed vector database. It connects directly to the Milvus metadata store (etcd, or TiKV) and lets operators inspect, back up, restore and **repair** cluster metadata such as collections, segments, indexes and channels.

### My Contribution Context

While reading the `repair` command implementations, I noticed that one of the write paths logged a serialization error and then kept going instead of aborting. Because `repair` commands write directly into the metadata store of a live Milvus cluster, a silent bad write there can corrupt metadata. I opened the issue (#515), reproduced the failure, and submitted the fix.

### Relevant Component

`states/etcd/repair`: the `repair index_metric_type` command (`index_metric.go`, `writeRepairedIndex`) and the segment repair helper (`segment.go`, `writeRepairedSegment`).

---

# Contributions

## Contribution 1 — Abort repair write when `proto.Marshal` fails

**Type:** Bug Fix
**Status:** Merged
**Date:** 2026-09-02 (opened 2026-08-12)

### Problem

`writeRepairedIndex` printed the `proto.Marshal` error and then carried on to `cli.Save` anyway:

```go
bs, err := proto.Marshal(index)
if err != nil {
    fmt.Println("failed to marshal segment info", err.Error())
}
err = cli.Save(context.Background(), p, string(bs))
return err
```

I checked what `bs` holds after a marshal failure (the easiest trigger is invalid UTF-8 in a proto `string` field). It is a **non-empty buffer that doesn't round-trip**:

```
marshal err: string field contains invalid UTF-8 bytes: [10 17 8 42 26 11 255 254 0 128 ...]
unmarshal err: proto: cannot parse invalid wire-format data
```

That buffer was written to etcd, `Save` succeeded, and the function returned `nil`, so `repair index_metric_type` **reported success while writing unreadable metadata**. The next reader of that key (Birdwatcher itself or Milvus' index coordinator) would fail to unmarshal it, with nothing pointing back to the repair run that caused it.

`writeRepairedSegment` in `segment.go` had the same pattern. It isn't reachable today (its caller `RepairSegmentCommand` is commented out), but it would come back as soon as that command is finished.

### My Work

* Found the bug and filed issue #515 with the root-cause analysis.
* Reproduced the failure and confirmed that the marshal-failure buffer is non-empty and can't be unmarshalled, which made this a data-corruption bug rather than a harmless empty write.
* Fixed both `writeRepairedIndex` and `writeRepairedSegment`.
* Wrote regression tests for both functions using a `Save`-recording `kv.MetaKV` test double.
* Rebased twice as `main` moved (see Review / Discussion), including migrating the new tests' imports to the upgraded `milvus-proto` / `pkg/v3` proto packages.

### Technical Implementation

* Both functions now return the marshal error right away, wrapped with context, and never reach `Save`:
  ```go
  bs, err := proto.Marshal(index)
  if err != nil {
      return fmt.Errorf("failed to marshal repaired index %d: %w", index.GetIndexInfo().GetIndexID(), err)
  }
  return cli.Save(context.Background(), p, string(bs))
  ```
  (Same fix for segments, with `segment.GetID()` in the message.)
* **Tests** (`index_metric_test.go`, `segment_test.go`):
  * `saveRecordingKV` embeds `kv.MetaKV` and overrides only `Save`, recording the keys and values it receives.
  * *Marshal failure* case: builds a proto with invalid UTF-8 (`"\xff\xfe\x00\x80invalid"`) in a string field and asserts that an error is returned **and `Save` is never called**.
  * *Valid* case: asserts exactly one `Save` to the expected etcd key (`by-dev/meta/field-index/100/200`, `by-dev/meta/datacoord-meta/s/100/10/1`) and that the saved bytes unmarshal back to the original values.

### Technologies / Concepts

* Go error handling and error wrapping (`%w`)
* Protocol Buffers serialization (proto3 UTF-8 validation)
* etcd as a metadata store
* Test doubles via interface embedding
* Fail-fast / data-integrity design

### Result

The repair command now fails loudly on a serialization error instead of writing a corrupt value into the cluster's metadata store and reporting success.

### Impact

* Fixed a failure mode where `repair index_metric_type` could write an unreadable value to etcd while reporting success.
* Fixed the same latent bug in the segment repair path before it could become reachable.
* Added the first unit tests for these two write helpers (4 test cases).
* Diff: +118 / −6 across 4 files.

### Pull Request

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

### Issue

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

### Commit(s)

* PR commit: https://github.com/milvus-io/birdwatcher/commit/e89f1e9b5067b88a98ec1a325a312eefd03e8593
* Merge commit: https://github.com/milvus-io/birdwatcher/commit/8a91a3aa8c8a3894e9003178b6869a02acc49764

### Review / Discussion

* Maintainer **@congqixia** said the patch looked good but that the tests used an out-of-date proto package name that would break the pipeline after merge, and asked for a rebase. I rebased onto latest `main` the same day.
* `main` then upgraded to `milvus-proto/go-api/v3`, and @congqixia asked for another base update. The rebase itself was clean, but the new test files still imported pre-migration `pkg/v2/proto/...` paths. I updated them to `pkg/v3/proto/...` to match the rest of the package and re-verified `go build`, `go vet`, `gofmt` and `go test`.
* Approved with `/lgtm` by @congqixia and merged by the CI bot on 2026-09-02.

---

# Technical Depth

## Architecture / System Understanding

Birdwatcher builds a command tree (`states/...`) on top of a `kv.MetaKV` abstraction over etcd or TiKV. Repair commands load Milvus metadata protos (such as `indexpb.FieldIndex` and `datapb.SegmentInfo`) from well-known key prefixes under the instance's meta path, change them, re-serialize them, and write them back. Those keys are read by Milvus coordinators, so whatever Birdwatcher writes must be valid wire-format protobuf.

## Important Components

* **`states/etcd/repair/index_metric.go`:** implements `repair index_metric_type`; `writeRepairedIndex` persists the corrected `FieldIndex`.
* **`states/etcd/repair/segment.go`:** `writeRepairedSegment` persists `SegmentInfo` under `datacoord-meta/s/<coll>/<part>/<seg>`.
* **`states/kv.MetaKV`:** the storage interface I mocked in tests.

## APIs / Interfaces

* `kv.MetaKV.Save(ctx, key, value)`
* `proto.Marshal` / `proto.Unmarshal` (google.golang.org/protobuf)
* Birdwatcher CLI: `repair index_metric_type`

## Data Structures / Algorithms

Protobuf messages `indexpb.FieldIndex` / `indexpb.IndexInfo` and `datapb.SegmentInfo`; etcd key layout for index and segment metadata.

## Distributed Systems Concepts

* Metadata consistency: a coordinator depends on every key in the meta store being decodable.
* Fault tolerance: fail fast instead of persisting partial or corrupt state.
* Operator tooling that mutates the shared state of a distributed system.

## Performance Considerations

Not applicable; this is a correctness fix.

## Testing

Table-style subtests with `testify/require` and `assert`: a negative path (marshal failure means no write) and a positive path (key layout and round-trip check), for both index and segment. Ran the full `states/etcd/repair` package suite, `go vet` and `gofmt -l`.

---

# Engineering Decisions

## Decision 1 — Also fix the currently unreachable `writeRepairedSegment`

**Context:** The same bug existed in `segment.go`, but its only caller is commented out.

**Options Considered:**

* Fix only the reachable `index_metric` path.
* Fix both paths now.

**Decision:** Fix both, with tests.

**Reason:** The segment path would silently bring the bug back once `RepairSegmentCommand` is finished, and the fix is identical and low-risk.

**Trade-offs:** Slightly larger diff, and one test targets code that isn't reachable today.

## Decision 2 — Test with a recording mock instead of a real etcd

**Context:** I needed to prove `Save` is never called on the failure path.

**Decision:** A `saveRecordingKV` that embeds `kv.MetaKV` and overrides only `Save`.

**Reason:** Deterministic, no external dependencies, and it asserts directly on the "no write happened" property.

**Trade-offs:** Doesn't exercise a real etcd client, which isn't needed for this logic.

---

# Challenges

## Challenge 1

Showing the bug actually causes corruption rather than an empty write: an empty value might have been treated as harmless.

### How I Solved It

Triggered a real marshal failure with invalid UTF-8 and checked both the returned buffer and whether it could be unmarshalled. The buffer was non-empty and could not be parsed.

### What I Learned

Go's protobuf `Marshal` can return partial output together with an error, so on error the buffer has to be treated as undefined.

## Challenge 2

Upstream dependency migration (`pkg/v2` → `pkg/v3` proto packages, `milvus-proto/go-api/v3`) landed while the PR was open.

### How I Solved It

Rebased twice and updated the imports in the new test files to match the migrated package layout, then re-ran build, vet, fmt and tests.

### What I Learned

In fast-moving upstream repos, new files can break at compile time after a rebase even when git reports no conflicts. Re-run the build after every rebase.

---

# Collaboration

## Maintainer / Contributor Interaction

Worked with maintainer @congqixia through two rebase rounds and replied to each request within a day.

## Code Review

Feedback was about keeping the PR mergeable against a moving `main` (proto package migration). I addressed it and listed what I had verified in each reply.

## Design Discussions

None needed; the fix was accepted as proposed.

## Collaboration Skills Demonstrated

* Writing a clear, reproducible bug report with root-cause analysis
* Responding quickly to maintainer requests
* Rebasing and keeping PRs mergeable against a fast-moving upstream
* Following DCO sign-off requirements

---

# Outcomes

## Code

* Fixed error handling in `states/etcd/repair/index_metric.go` and `states/etcd/repair/segment.go`
* New `states/etcd/repair/index_metric_test.go` and `states/etcd/repair/segment_test.go`

## Project Impact

Removed a path where an operator repair tool could corrupt Milvus metadata, and added test coverage for the repair write helpers.

## User / Developer Impact

Operators running `repair index_metric_type` now get an explicit error instead of a false success followed by later decode failures in Milvus.

## Recognition

Approved (`/lgtm`) by maintainer @congqixia; merged into `main`.

---

# Skills Demonstrated

## Programming

* Go (error handling, interfaces, embedding, testing)
* Protocol Buffers

## Software Engineering

* Root-cause analysis
* Regression testing with test doubles
* Defensive, fail-fast error handling

## Systems

* Metadata stores (etcd) and serialization formats

## Distributed Systems

* Metadata integrity in a distributed database (Milvus)

## Infrastructure / Cloud

* Operator / SRE tooling for a cloud-native database

## Open Source

* Working with maintainers
* Code review
* Issue tracking
* Git/GitHub workflow (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/516                                                 | Contribution          |
| Issue        | https://github.com/milvus-io/birdwatcher/issues/515                                               | Bug report (mine)     |
| Commit       | https://github.com/milvus-io/birdwatcher/commit/e89f1e9b5067b88a98ec1a325a312eefd03e8593          | Implementation        |
| Merge commit | https://github.com/milvus-io/birdwatcher/commit/8a91a3aa8c8a3894e9003178b6869a02acc49764          | Merged into main      |
| Release      | Not yet in a tagged release (latest tag v1.2.2 predates the merge)                                | —                     |

---

# Key Technical Keywords

Go, Protocol Buffers, etcd, Milvus, vector database, metadata integrity, error handling, unit testing, testify, test doubles, CLI tooling, distributed systems

---

# Related Work

* milvus-io/birdwatcher PR #521: implemented `FileAuditKV.MultiSave` (separate file)
* milvus-io/birdwatcher PR #542: fixed a data race / swallowed error in `load-backup` (separate file)
* Apicurio/apicurio-registry PR #9380: XSD compatibility fix (separate file)

---

# Timeline

| Date       | Event                                                                 |
| ---------- | --------------------------------------------------------------------- |
| 2026-08-12 | Opened issue #515 and PR #516                                         |
| 2026-08-20 | Requested review (`/assign @congqixia`)                               |
| 2026-08-21 | Maintainer asked for rebase (outdated proto package); rebased same day |
| 2026-08-31 | Maintainer asked to rebase over `milvus-proto/go-api/v3` upgrade      |
| 2026-09-01 | Rebased; migrated test imports to `pkg/v3` protos                     |
| 2026-09-02 | Approved (`/lgtm`) and merged                                         |

---

# Notes

* This was my first merged contribution to milvus-io/birdwatcher and led directly to the follow-up bugs in #520/#521 and #540/#542.
* Every issue I fixed in this repo followed the same pattern: an error printed and then ignored, so a data-mutating command reported false success.
