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

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

## 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 + tests)                                    |
| Role                      | Contributor                                                             |
| Start Date                | 2026-08-23                                                              |
| End Date                  | 2026-09-08                                                              |
| Status                    | Completed (Merged)                                                      |
| Primary Language(s)       | Go                                                                      |
| Technologies / Frameworks | Go, etcd (`mvccpb`), Protocol Buffers, testify                          |
| Area                      | Distributed Systems / Developer & Operator Tooling / Audit Logging      |

---

## Project Context

### What the Project Is

Birdwatcher is the official debugging and operations CLI for Milvus, the open-source distributed vector database. It connects to the Milvus metadata store (etcd or TiKV) to inspect, back up, restore and repair cluster metadata.

### My Contribution Context

After my first fix (#516), I kept auditing Birdwatcher's write paths. I found that the audit-logging KV wrapper, which Birdwatcher uses by default whenever an audit log file is open, had a stub `MultiSave` that always returned `"not implemented"`. During review I also found that several command components were built with the raw client and bypassed the audit wrapper entirely.

### Relevant Component

* `states/kv/kv_audit.go`: `FileAuditKV`, a decorator over `kv.MetaKV` that writes an audit trail of every mutation to a file.
* `states/instance.go`: `GetInstanceState`, which wires the show / remove / repair / reset / set components to a KV client.

---

# Contributions

## Contribution 1 — Implement `FileAuditKV.MultiSave` and route all mutating components through the audit wrapper

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

### Problem

* `FileAuditKV.MultiSave` was a stub: `return errors.New("not implemented")`. Every other mutating method (`Save`, `Remove`, ...) writes audit records and then delegates to the wrapped client. `MultiSave` did neither.
* Because `FileAuditKV` is the default write wrapper, batch writes through it always failed. On the `restore` / `load-backup` path, the `MultiSave` error was only printed inside a worker goroutine and never returned, so **a restore could report success while writing zero keys to etcd**.
* A reviewer found, and I confirmed, a second, related bug: `GetInstanceState` built `ComponentShow`, `ComponentRemove`, `ComponentRepair`, `ComponentReset` and `ComponentSet` with the **unwrapped** client `cli` instead of the audit-wrapped `kv`. Mutations from `repair`, `remove`, `set` and `reset` were **never audited**.

### My Work

* Filed issue #520 describing the stub and the call sites it affected.
* Implemented `FileAuditKV.MultiSave` following the existing `Save()` audit protocol.
* Added input validation for mismatched `keys` / `values` lengths.
* In response to review, wired all mutating components through the audit-wrapped client (second commit).
* Wrote `states/kv/kv_audit_test.go` (227 lines): a full in-memory `MetaKV` fake plus a parser that replays the on-disk audit log format.
* Resolved two merge conflicts with upstream features (#523 "reset checkpoint", #535 "reset wal") that had added the new `ComponentReset` wired to the unwrapped client. That was the same audit-bypass bug, so I fixed it during conflict resolution.

### Technical Implementation

**`MultiSave` implementation** (same audit protocol as `Save`):

```go
if len(keys) != len(values) {
    return errors.Newf("keys and values length mismatch, keys: %d, values: %d", len(keys), len(values))
}
c.writeHeader(models.AuditOpType_OpPut, int32(len(keys)))
err := c.cli.MultiSave(ctx, keys, values)
if err == nil {
    c.writeHeader(models.AuditOpType_OpPutBefore, int32(len(keys)))
    for i, key := range keys {
        c.writeKeyValue(key, values[i])
    }
}
c.writeHeader(models.AuditOpType_OpPutAfter, int32(len(keys)))
return err
```

The audit log is a sequence of length-prefixed records (8-byte little-endian length followed by the protobuf payload). A successful batch write produces `OpPut` header → `OpPutBefore` header → N `mvccpb.KeyValue` records → `OpPutAfter` header. A failed write produces only `OpPut` → `OpPutAfter`, so the log never claims keys were written when they weren't.

**Component wiring** (`states/instance.go`): changed `show`, `remove`, `repair`, `reset` and `set` `NewComponent(...)` calls from `cli` to the audit-wrapped `kv`.

**Tests** (`TestFileAuditKVMultiSave`, 5 subtests):

1. Delegates and persists values: the wrapped client receives the exact keys and values, and the data is stored.
2. Propagates the underlying error: `errors.Is` matches the injected failure and nothing is stored.
3. Rejects mismatched keys and values: the wrapped client is never called.
4. Writes `OpPut` / `OpPutBefore` / `OpPutAfter` headers and key/value records: replays the temp audit file and asserts the exact 5-record sequence, header op types, `EntriesNum`, and key/value bytes.
5. Writes only the `OpPutAfter` header when the underlying save fails: asserts exactly 2 header records and no leaked key/value records.

The file-replay helpers (`readAuditRecords`, `decodeAuditHeader`, `decodeKeyValue`) parse the binary format directly, so the tests pin down the on-disk format rather than just the delegation behavior.

### Technologies / Concepts

* Decorator pattern (audit wrapper over a KV interface)
* Audit logging, binary length-prefixed record formats
* Protocol Buffers (`models.AuditHeader`, etcd `mvccpb.KeyValue`, `protoadapt` for v1/v2 message interop)
* Dependency wiring / composition root
* Error propagation with `cockroachdb/errors`

### Result

* Batch writes through the audit wrapper now work and are recorded in the audit log.
* Every mutating Birdwatcher component (repair, remove, set, reset) now goes through the audit log, closing a gap where metadata changes left no audit trail.

### Impact

* Fixed a failure mode where `restore` could report success while writing zero keys.
* Mutations from 5 command components are now audited; before the fix they bypassed the audit log.
* Added the first tests for `FileAuditKV`, including tests of the on-disk format.
* Diff: +245 / −6.

### Pull Request

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

### Issue

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

### Commit(s)

* https://github.com/milvus-io/birdwatcher/commit/5eaf10fe99adafa8e0d44e6a2be203c8d2771171: implement `FileAuditKV.MultiSave`
* https://github.com/milvus-io/birdwatcher/commit/5608688886a8dad11fe1a0fb2d67128530a1cf56: wire repair/remove/show/set components through audit-wrapped kv
* Merge commit: https://github.com/milvus-io/birdwatcher/commit/bc64249b1faec0c8e285f65394306a68f7c2afef

### Review / Discussion

* **@yhmo (Medium):** pointed out that `repair segment-storage-layout` ran on `ComponentRepair`, which was built with the *unwrapped* client, so the `MultiSave` fix alone wouldn't reach it. They also noted that on TiKV the "not implemented" error comes from `txnTiKV.MultiSave`.
  * **My response:** agreed on both points. I clarified that I had reproduced the bug on the `restore` / `load-backup` path, which does use the audit-wrapped client. I found the real repair bug was one step earlier, in `GetInstanceState`'s wiring, and fixed it by routing all components through the wrapped `kv`. I proposed handling `txnTiKV.MultiSave` (a different backend) as a separate follow-up to keep the PR focused.
* **@yhmo (Low):** the tests only checked delegation and never read the audit file back, so a regression in headers or record counts would go unnoticed.
  * **My response:** added two subtests that replay the raw audit file and assert the exact record sequence for both success and failure.
* @yhmo confirmed both threads fixed. After two conflict-resolving rebases (upstream #523 and #535), maintainer **@congqixia** approved with `/lgtm` and the PR was merged on 2026-09-08.

---

# Technical Depth

## Architecture / System Understanding

`GetInstanceState` (`states/instance.go`) is where Birdwatcher's per-instance state is assembled. It receives a raw `MetaKV` (etcd or TiKV). When an audit file is open, it wraps that client in `FileAuditKV`. Command components (`show`, `remove`, `repair`, `reset`, `set`) each receive a client at construction time. Which client each gets decides whether its writes are audited. The `restore` / `load-backup` path writes through the instance's `state.client`, which is the audit-wrapped `kv`.

## Important Components

* **`FileAuditKV` (`states/kv/kv_audit.go`):** a decorator that writes audit headers and before/after values to a file around each mutation. I implemented `MultiSave`.
* **`GetInstanceState` (`states/instance.go`):** wires components to clients. I fixed the audit-bypass wiring.
* **`models.AuditHeader` / `AuditOpType`:** protobuf schema for audit-log headers.
* **`restoreEtcdFromBackV2` (`states/etcd_restore.go`):** the restore path affected by the stub (see PR #542 for the follow-up fix there).

## APIs / Interfaces

* `kv.MetaKV` interface (Load, LoadWithPrefix, Save, MultiSave, Remove, RemoveWithPrefix, GetAllRootPath, BackupKV, WalkWithPrefix, Close)
* Audit log binary format (8-byte LE length prefix + protobuf)
* Birdwatcher CLI: `restore` / `load-backup`, `repair segment-storage-layout`, `remove`, `set`, `reset`

## Data Structures / Algorithms

Length-prefixed binary record stream; protobuf `AuditHeader{OpType, EntriesNum}` and `mvccpb.KeyValue`.

## Distributed Systems Concepts

* Auditability of operator changes to a distributed database's metadata
* Batch (multi-key) writes to etcd
* Error propagation across goroutines (the swallowed error in restore, fixed fully in #542)

## Performance Considerations

Not applicable; this is a correctness and auditability fix.

## Testing

Wrote a full in-memory `fakeMetaKV` implementing the whole interface, plus binary-format replay helpers. The 5 subtests cover the success, error, validation, on-disk success-format and on-disk failure-format cases. Verified `go build ./...` and `go vet ./states/...`, and ran the tests for every package I touched (`states/kv`, `states/etcd/repair`, `remove`, `show`, `reset`, `states`).

---

# Engineering Decisions

## Decision 1 — Mirror `Save()`'s audit protocol exactly

**Context:** `MultiSave` needed audit semantics consistent with the rest of `FileAuditKV`.

**Options Considered:**

* Pass through to the wrapped client without auditing.
* Write one `Save`-style record per key.
* Write a single batch with the same header protocol as `Save`.

**Decision:** Same `OpPut` / `OpPutBefore` / `OpPutAfter` framing with `EntriesNum = len(keys)`.

**Reason:** Tools that read the audit log already understand this framing, and a batch stays one logical audited operation.

**Trade-offs:** Key/value records are written only after a successful save, so a failed batch records the attempt but not the values.

## Decision 2 — Keep `txnTiKV.MultiSave` out of scope

**Context:** The reviewer noted that TiKV also lacks `MultiSave`.

**Decision:** Proposed a separate follow-up instead of bundling it.

**Reason:** Different backend and different risk; keeping the PR focused made it easier to review.

**Trade-offs:** TiKV batch writes remain unsupported until the follow-up is done.

## Decision 3 — Fix the audit bypass for new upstream components during conflict resolution

**Context:** Upstream #523 and #535 added and changed `ComponentReset` wired to the raw client.

**Decision:** Resolved the conflicts by wiring `ComponentReset` to the audited `kv`, keeping the new `instanceName` argument.

**Reason:** Otherwise the PR would have fixed the bug for four components and left it in the fifth.

---

# Challenges

## Challenge 1

The reviewer found that the PR's stated motivation (a broken repair path) didn't match the client wiring on `main`.

### How I Solved It

Traced the client wiring in `GetInstanceState`, confirmed the reviewer was right, and found the underlying wiring bug. I fixed that as well, and clarified which path I had actually reproduced (restore).

### What I Learned

Trace the actual call path from the composition root before claiming which user-facing commands a bug affects.

## Challenge 2

`main` moved twice during review, each time touching the same lines in `states/instance.go`.

### How I Solved It

Rebased twice, resolved each conflict so the new upstream components were also audited, and re-ran build, vet and tests on every touched package.

### What I Learned

Conflict resolution can introduce a bug that the PR is meant to fix. Check new upstream code against the invariant the PR establishes.

---

# Collaboration

## Maintainer / Contributor Interaction

Worked with reviewers @yhmo and @congqixia. I acknowledged the review findings directly, fixed both, and summarized the state of the PR after each push.

## Code Review

Received one Medium finding (wiring / motivation mismatch) and one Low finding (test gap). Both were fixed and confirmed resolved by the reviewer.

## Design Discussions

Scoping: whether `txnTiKV.MultiSave` belonged in this PR. I proposed a follow-up to keep this PR focused.

## Collaboration Skills Demonstrated

* Accepting a correction and expanding the fix to the real root cause
* Scoping PRs to stay reviewable
* Clear written status updates listing what was verified
* Keeping a PR mergeable across multiple upstream changes

---

# Outcomes

## Code

* `FileAuditKV.MultiSave` implemented (`states/kv/kv_audit.go`)
* Audit-wrapped client wired into all mutating components (`states/instance.go`)
* New `states/kv/kv_audit_test.go` with a MetaKV fake and audit-log replay helpers

## Project Impact

Birdwatcher's audit log now covers batch writes and every mutating component.

## User / Developer Impact

Operators get a complete audit trail of what Birdwatcher changed in their cluster metadata, and batch restores no longer fail inside the audit wrapper.

## Recognition

Reviewer @yhmo confirmed both findings fixed; approved (`/lgtm`) by maintainer @congqixia; merged into `main`.

---

# Skills Demonstrated

## Programming

* Go (interfaces, decorators, binary I/O, protobuf)

## Software Engineering

* Decorator pattern, dependency wiring
* Format-level testing of binary outputs
* Root-cause analysis in response to review

## Systems

* Audit logging, binary serialization formats

## Distributed Systems

* Metadata mutation auditing for a distributed vector database
* Multi-key writes to etcd

## Infrastructure / Cloud

* Operator / SRE tooling for Milvus

## Open Source

* Working with maintainers
* Code review
* Issue tracking
* Git/GitHub workflow (rebase, conflict resolution, 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/521                                         | Contribution                    |
| Issue        | https://github.com/milvus-io/birdwatcher/issues/520                                       | Bug report (mine)               |
| Commit       | https://github.com/milvus-io/birdwatcher/commit/5eaf10fe99adafa8e0d44e6a2be203c8d2771171  | MultiSave implementation        |
| Commit       | https://github.com/milvus-io/birdwatcher/commit/5608688886a8dad11fe1a0fb2d67128530a1cf56  | Component wiring fix            |
| Merge commit | https://github.com/milvus-io/birdwatcher/commit/bc64249b1faec0c8e285f65394306a68f7c2afef  | Merged into main                |
| Discussion   | https://github.com/milvus-io/birdwatcher/pull/521/files                                   | Inline review threads with @yhmo     |
| Release      | Not yet in a tagged release (latest tag v1.2.2 predates the merge)                        | —                               |

---

# Key Technical Keywords

Go, etcd, TiKV, Milvus, audit logging, decorator pattern, Protocol Buffers, binary file formats, dependency injection, unit testing, testify, distributed systems, CLI tooling

---

# Related Work

* milvus-io/birdwatcher PR #516: repair marshal-failure fix (separate file)
* milvus-io/birdwatcher PR #542: follow-up race / swallowed-error fix in `restoreEtcdFromBackV2`, reachable only after this PR made `MultiSave` actually delegate (separate file)
* Apicurio/apicurio-registry PR #9380 (separate file)

---

# Timeline

| Date       | Event                                                                  |
| ---------- | ---------------------------------------------------------------------- |
| 2026-08-23 | Opened issue #520 and PR #521                                          |
| 2026-08-24 | Requested review (`/assign @congqixia`)                                |
| 2026-08-27 | @yhmo review (Medium + Low findings); fixes pushed same day            |
| 2026-08-28 | @yhmo confirmed both findings fixed                                    |
| 2026-09-01 | Rebased over upstream #523; wired new `ComponentReset` through audit kv |
| 2026-09-05 | Rebased over upstream #535 (`reset.NewComponent` signature change)     |
| 2026-09-08 | Approved (`/lgtm`) and merged                                          |

---

# Notes

* A follow-up for `txnTiKV.MultiSave` (TiKV backend) was proposed during review and was not part of this PR.
* This PR exposed the race in `restoreEtcdFromBackV2`, which I then fixed in #542.
