Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
87 changes: 79 additions & 8 deletions .claude/skills/banyan-code-quality-audit/quality-checklist.md
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,60 @@ For each `.proto` file:

---

## IDENT — Identity and Lookup Correctness

The M12 retrospective revealed a recurring pattern: using non-unique identifiers as lookup keys, then patching with increasingly complex heuristics when collisions appeared. The correct fix was always to use the unique identifier that was available from the start. Simplicity is not carelessness.

### IDENT-1: Lookup Key Uniqueness

For every function that finds/matches a record (task, container, node, deployment):

- [ ] The lookup key is **globally unique** (task ID, deployment ID) — not a display name (container name, service name) that can be reused across deployments or restart cycles
- [ ] If the caller has a unique ID available, it passes it — the function does not re-derive it from a non-unique name
- [ ] If a non-unique name must be used (e.g., user-facing CLI input), the code explicitly handles ambiguity (latest by CreatedAt, filter by status, etc.) rather than returning the first match

**Red flag**: Any function that matches records by iterating a list and returning the first name match. This is almost always wrong in a system where names are reused.

### IDENT-2: Caller Has More Context Than Receiver

When code calls an API or function, check:

- [ ] The caller passes **all available identifying information**, not just the minimum. If the caller knows the agent_id AND the container name, it passes both — even if the API only requires one.
- [ ] Proto request messages include optional fields for direct lookup (e.g., `agent_id`, `task_id`) alongside human-readable fields (e.g., `container_name`)
- [ ] The handler uses the most specific identifier available, falling back to scanning only when the specific ID is absent

**Red flag**: A web dashboard or API client that has the full task record (with task_id, agent_id) but only passes the container name to the backend. The backend then scans all nodes to guess which agent has the container.

### IDENT-3: No Scan When Direct Lookup Is Possible

For every function that iterates through a collection to find a match:

- [ ] A direct key lookup (`store.Get(key)`) was not possible with the available inputs. If a unique key could be constructed from the inputs, the scan is wrong.
- [ ] If the scan is necessary (only non-unique info available), it filters to the **smallest correct scope** (e.g., only healthy agents, only running deployments) — not all records.
- [ ] Among multiple matches, the function picks the **latest/most relevant** (by CreatedAt, by status) — not the first match in arbitrary order (etcd returns keys alphabetically, which has no semantic meaning).

**Red flag**: `for _, node := range allNodes { for _, task := range allTasks { if task.Name == target { return } } }` — scanning everything to find one record, when `store.Get("tasks/"+agentID+"/"+taskID)` would give the answer directly.

### IDENT-4: Proto Messages Support Direct Lookup

For every proto request message that triggers a server-side lookup:

- [ ] The message includes an optional field for the **unique identifier** (task_id, agent_id, deployment_id), not just the human-readable name
- [ ] The handler checks for the unique ID first, falls back to name-based search only if absent
- [ ] The frontend/CLI passes the unique ID when it has it (which is almost always — the data came from a previous API response that included it)

### IDENT-5: Historical Records Don't Shadow Current State

After restarts, redeployments, or scaling events, old records coexist with new ones in etcd:

- [ ] Queries that return "the current state" filter to the **latest record per logical entity** (latest task per replica, latest deployment per name) — not all historical records
- [ ] Cleanup/stop_and_remove tasks do not appear in results meant for container state (they are operational artifacts, not container identity)
- [ ] Health reports, status displays, and backend lists use the same "latest per entity" filter consistently

**Red flag**: A dashboard showing 4/6 containers healthy after one restart — the denominator should be 4 (current), not 6 (current + historical).

---

## SMELL — Code Smells

### SMELL-1: Error Handling
Expand Down Expand Up @@ -300,13 +354,30 @@ Check that the same error handling style is used across all packages:

During a time-constrained audit, check in this order:

1. **DOC-6** — Roadmap accuracy (fast check, high impact)
2. **DOC-1** — Landing page claims (user's first impression)
3. **INT-1** — Package import chain (catches VPC-style issues)
4. **INT-2/3** — Startup completeness (are new components wired in?)
5. **DEAD-1** — Unused packages (quick win)
6. **BUILD-1** — go.mod health (30-second check)
7. **TEST-1** — Coverage gaps (identifies risk)
8. Everything else
1. **IDENT-1/3** — Lookup key uniqueness (catches the "container name collision" class of bugs)
2. **DOC-6** ��� Roadmap accuracy (fast check, high impact)
3. **DOC-1** �� Landing page claims (user's first impression)
4. **INT-1** — Package import chain (catches VPC-style issues)
5. **INT-2/3** — Startup completeness (are new components wired in?)
6. **DEAD-1** — Unused packages (quick win)
7. **BUILD-1** — go.mod health (30-second check)
8. **TEST-1** — Coverage gaps (identifies risk)
9. Everything else

This order maximizes issue-finding per minute of audit time.

---

## Retrospective: The M12 Pattern (reference for auditors)

During Milestone 12 (self-healing deployments), the team hit the same bug pattern five times:

1. **Health reports** matched by container name → ghost containers after restart → fixed with task_id
2. **findContainerAgent** scanned all nodes by name → stale node returned → fixed with agent_id direct lookup
3. **collectServiceBackends** returned all tasks → stale IPs in proxy → fixed with latest-per-replica filter
4. **Dashboard counts** counted all historical tasks → inflated numbers → fixed with latestTasksPerReplica
5. **Cleanup tasks** shadowed exited containers in latestByReplica → reconciler lost track → fixed with type filter

Every instance was the same root cause: **using a non-unique display name as a lookup key when a unique ID was available**. Each quick fix added a heuristic that broke in the next edge case. The proper fix was always: pass the unique ID, do a direct lookup.

**The lesson**: When you see a function scanning a collection to match by name, ask: "Does the caller have a unique ID it could pass instead?" If yes, the scan is technical debt, not simplicity.
3 changes: 2 additions & 1 deletion cmd/banyan-cli/cmd/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,11 +118,12 @@ func (c *EngineClient) Info(ctx context.Context) (*banyanpb.GetInfoResponse, err
}

// StreamLogs streams logs for a container from the engine gRPC API.
func (c *EngineClient) StreamLogs(ctx context.Context, container string, follow bool, tail int) (io.ReadCloser, error) {
func (c *EngineClient) StreamLogs(ctx context.Context, container string, follow bool, tail int, agentID string) (io.ReadCloser, error) {
stream, err := c.client.GetLogs(ctx, &banyanpb.GetLogsRequest{
ContainerName: container,
Follow: follow,
Tail: int32(tail), //nolint:gosec // tail count is always small
AgentId: agentID,
})
if err != nil {
return nil, fmt.Errorf("failed to stream logs: %w", err)
Expand Down
2 changes: 1 addition & 1 deletion cmd/banyan-cli/cmd/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -743,7 +743,7 @@ func TestEngineClient_StreamLogs(t *testing.T) {
defer cleanup()

t.Run("reads log data via stream", func(t *testing.T) {
reader, err := client.StreamLogs(context.Background(), "myapp-web-0", false, 0)
reader, err := client.StreamLogs(context.Background(), "myapp-web-0", false, 0, "")
if err != nil {
t.Fatalf("StreamLogs failed: %v", err)
}
Expand Down
8 changes: 5 additions & 3 deletions cmd/banyan-cli/cmd/logs.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,9 @@ import (
)

var (
logsFollow bool
logsTail int
logsFollow bool
logsTail int
logsAgentID string
)

var logsCmd = &cobra.Command{
Expand All @@ -39,6 +40,7 @@ func init() {

logsCmd.Flags().BoolVarP(&logsFollow, "follow", "f", false, "Follow log output")
logsCmd.Flags().IntVar(&logsTail, "tail", 0, "Number of lines from end (0 means all)")
logsCmd.Flags().StringVar(&logsAgentID, "agent-id", "", "Agent running the container (skips scanning)")
}

func runLogs(cmd *cobra.Command, args []string) error {
Expand All @@ -65,7 +67,7 @@ func runLogs(cmd *cobra.Command, args []string) error {
}
defer client.Close()

reader, err := client.StreamLogs(ctx, containerName, logsFollow, logsTail)
reader, err := client.StreamLogs(ctx, containerName, logsFollow, logsTail, logsAgentID)
if err != nil {
return fmt.Errorf("failed to stream logs: %w", err)
}
Expand Down
9 changes: 9 additions & 0 deletions pkg/agent/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"os"
"os/exec"
"path/filepath"
"sort"
"strconv"
"strings"
"sync/atomic"
Expand Down Expand Up @@ -274,6 +275,13 @@ func (a *Agent) processTasks(ctx context.Context) {
return
}

// Sort tasks so stop_and_remove runs before create_and_start.
// This prevents name conflicts when the reconciler creates a cleanup
// task + restart task for the same container name.
sort.SliceStable(tasks, func(i, j int) bool {
return tasks[i].Type == types.TaskTypeStopAndRemove && tasks[j].Type != types.TaskTypeStopAndRemove
})

for _, pbTask := range tasks {
// Report running (best-effort)
if err := a.client.ReportTaskResult(ctx, pbTask.Id, pbTask.AgentId, types.StatusRunning, "", pbTask.ContainerName, nil); err != nil {
Expand Down Expand Up @@ -872,6 +880,7 @@ func (a *Agent) checkContainerHealth(ctx context.Context) {
status := containerStatusFunc(ctx, c.containerName)
cs := &banyanpb.ContainerStatus{
ContainerName: c.containerName,
TaskId: c.taskID,
Status: status,
Ip: c.containerIP,
}
Expand Down
11 changes: 4 additions & 7 deletions pkg/agent/vpc_networking.go
Original file line number Diff line number Diff line change
Expand Up @@ -259,18 +259,15 @@ func (a *Agent) addContainerToIsolation(ctx context.Context, containerIP, deploy
// cleanupStaleNetworking removes stale network interfaces and iptables rules
// from a previous agent run. Best-effort — all errors are ignored.
func (a *Agent) cleanupStaleNetworking() {
// Remove stale banyan-wg interface
// Remove stale WireGuard interface — will be recreated by initializeVPCNetworking.
// NOTE: do NOT delete banyan0 bridge. Running containers have veth pairs attached
// to it. Deleting the bridge orphans all container networking. The bridge persists
// across agent restarts by design (same as overlay.Cleanup).
if err := exec.Command("ip", "link", "show", "banyan-wg").Run(); err == nil { //nolint:gosec // fixed args
exec.Command("ip", "link", "delete", "banyan-wg").Run() //nolint:errcheck,gosec // best-effort
a.logger().Info("Removed stale banyan-wg interface")
}

// Remove stale banyan0 bridge
if err := exec.Command("ip", "link", "show", "banyan0").Run(); err == nil { //nolint:gosec // fixed args
exec.Command("ip", "link", "delete", "banyan0").Run() //nolint:errcheck,gosec // best-effort
a.logger().Info("Removed stale banyan0 bridge")
}

// Flush iptables rules from previous runs
ipt, err := iptablesFactory()
if err != nil {
Expand Down
4 changes: 3 additions & 1 deletion pkg/engine/agent_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@ import (
// No application-layer auth is needed — the agent verifies the caller is the engine
// by checking the peer IP matches the engine's control tunnel IP.
func streamAgentLogs(ctx context.Context, agentAddr, containerName string, follow bool, tail int32) (io.ReadCloser, error) {
conn, err := grpc.NewClient(agentAddr,
// Use passthrough scheme for direct IP:port addresses. grpc.NewClient defaults
// to the "dns" resolver which can silently fail on bare IP addresses.
conn, err := grpc.NewClient("passthrough:///"+agentAddr,
grpc.WithTransportCredentials(insecure.NewCredentials()),
)
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion pkg/engine/connect_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ func (a *connectAdapter) GetLogs(ctx context.Context, req *connect.Request[banya
return connect.NewError(connect.CodeInvalidArgument, nil)
}

task, node, err := a.srv.findContainerAgent(ctx, req.Msg.ContainerName)
task, node, err := a.srv.findContainerAgent(ctx, req.Msg.ContainerName, req.Msg.AgentId)
if err != nil {
return connect.NewError(connect.CodeNotFound, err)
}
Expand Down
18 changes: 10 additions & 8 deletions pkg/engine/connect_server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"net/http"
"net/http/httptest"
"testing"
"time"

"connectrpc.com/connect"

Expand Down Expand Up @@ -58,7 +59,7 @@ func TestConnectAdapter_GetDashboardData(t *testing.T) {
// Seed a node and deployment so the response is non-empty
_ = srv.store.Save(ctx, types.KeyNodes+"agent-1", &types.NodeRecord{
Name: "agent-1",
Status: "ready",
Status: "ready", LastSeen: time.Now(),
})
_ = srv.store.Save(ctx, types.KeyDeployments+"myapp-1", &types.DeploymentRecord{
ID: "myapp-1",
Expand Down Expand Up @@ -93,7 +94,7 @@ func TestConnectAdapter_Scale(t *testing.T) {
// Seed a running deployment with a service
_ = srv.store.Save(ctx, types.KeyNodes+"agent-1", &types.NodeRecord{
Name: "agent-1",
Status: "ready",
Status: "ready", LastSeen: time.Now(),
})
_ = srv.store.Save(ctx, types.KeyDeployments+"myapp-1", &types.DeploymentRecord{
ID: "myapp-1",
Expand Down Expand Up @@ -138,7 +139,7 @@ func TestConnectAdapter_Down(t *testing.T) {
// Seed a running deployment with a completed task
_ = srv.store.Save(ctx, types.KeyNodes+"agent-1", &types.NodeRecord{
Name: "agent-1",
Status: "ready",
Status: "ready", LastSeen: time.Now(),
})
_ = srv.store.Save(ctx, types.KeyDeployments+"myapp-1", &types.DeploymentRecord{
ID: "myapp-1",
Expand Down Expand Up @@ -177,7 +178,7 @@ func TestConnectAdapter_GetStatus(t *testing.T) {

_ = srv.store.Save(ctx, types.KeyNodes+"agent-1", &types.NodeRecord{
Name: "agent-1",
Status: "ready",
Status: "ready", LastSeen: time.Now(),
})

resp, err := client.GetStatus(ctx, connect.NewRequest(&banyanpb.GetStatusRequest{}))
Expand Down Expand Up @@ -227,7 +228,7 @@ func TestConnectAdapter_Deploy(t *testing.T) {
// Need at least one agent for scheduling
_ = srv.store.Save(ctx, types.KeyNodes+"agent-1", &types.NodeRecord{
Name: "agent-1",
Status: "ready",
Status: "ready", LastSeen: time.Now(),
})

resp, err := client.Deploy(ctx, connect.NewRequest(&banyanpb.DeployRPCRequest{
Expand Down Expand Up @@ -421,7 +422,7 @@ func TestConnectAdapter_PollTasks(t *testing.T) {
ctx := context.Background()
_ = srv.store.Save(ctx, types.KeyNodes+"agent-1", &types.NodeRecord{
Name: "agent-1",
Status: "ready",
Status: "ready", LastSeen: time.Now(),
})

resp, err := client.PollTasks(ctx, connect.NewRequest(&banyanpb.PollTasksRequest{
Expand All @@ -442,7 +443,7 @@ func TestConnectAdapter_ReportTaskResult(t *testing.T) {
ctx := context.Background()
_ = srv.store.Save(ctx, types.KeyNodes+"agent-1", &types.NodeRecord{
Name: "agent-1",
Status: "ready",
Status: "ready", LastSeen: time.Now(),
})
_ = srv.store.Save(ctx, types.KeyTasks+"agent-1/task-1", &types.TaskRecord{
ID: "task-1",
Expand Down Expand Up @@ -472,7 +473,7 @@ func TestConnectAdapter_ReportContainerHealth(t *testing.T) {
ctx := context.Background()
_ = srv.store.Save(ctx, types.KeyNodes+"agent-1", &types.NodeRecord{
Name: "agent-1",
Status: "ready",
Status: "ready", LastSeen: time.Now(),
})

resp, err := client.ReportContainerHealth(ctx, connect.NewRequest(&banyanpb.ReportContainerHealthRequest{
Expand Down Expand Up @@ -709,6 +710,7 @@ func TestConnectAdapter_GetLogs_Success(t *testing.T) {
Name: "agent-1",
Status: "ready",
APIAddress: agentAddr,
LastSeen: time.Now(),
})
_ = srv.store.Save(ctx, types.KeyTasks+"agent-1/task-1", &types.TaskRecord{
ID: "task-1",
Expand Down
9 changes: 6 additions & 3 deletions pkg/engine/engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -275,9 +275,12 @@ func (e *Engine) Run(ctx context.Context) error {
grpcAddr := grpcBindAddr + ":" + e.opts.GRPCPort
e.registerEngine(ctx, grpcAddr)

// Run startup reconciliation before entering the main loop
RunReconciliation(ctx, e.reconcilers, e.log)
e.emitEvent("engine.reconciliation.startup", "Startup reconciliation complete", "info")
// NOTE: No startup reconciliation here. The 10s reconcile loop handles it.
// Running reconciliation at startup is premature — agents haven't reconnected
// yet, so all agents appear stale. The AgentReconciler would mark healthy
// containers for cleanup, and when agents reconnect seconds later, they'd
// kill their own running containers. The 10s loop gives agents time to
// re-register and send heartbeats before reconciliation begins.

// Start the orchestration loop
go e.engineLoop(ctx)
Expand Down
Loading
Loading