8000 🛡️ Improve reliability and telemetry by abahmed · Pull Request #508 · abahmed/kwatch · GitHub
[go: up one dir, main page]

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
6 changes: 5 additions & 1 deletion .github/workflows/check.yml
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,11 @@ jobs:
go run ./cmd/providercatalog -output /tmp/kwatch-provider-catalog.tsv
cmp -s deploy/provider-catalog.tsv /tmp/kwatch-provider-catalog.tsv
- name: Test
run: go test -race --coverprofile=coverage.txt --covermode=atomic ./...
run: >-
go test -race --coverprofile=coverage.txt
--covermode=atomic ./...
- name: Enforce coverage thresholds
run: ./scripts/check-coverage.sh coverage.txt
- name: Integration tests
run: go test -race -tags integration ./internal/integration/...
- name: Upload coverage to Codecov
Expand Down
26 changes: 19 additions & 7 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,15 @@ source.
Every change must pass before you are done:

```sh
go build ./... && go vet ./... && go test ./... && golangci-lint run
make verify
```

The repository also enforces formatting and line length. Run the complete gate
with `make verify`; it includes `line-check` and `git diff --check` should be
clean before handoff.
with `make verify`; it includes race-enabled coverage enforcement, `line-check`,
and `git diff --check` should be clean before handoff.
Coverage enforcement requires at least 75% aggregate statement coverage and at
least 70% in every package listed as core runtime by
`scripts/check-coverage.sh`. Only generated deep-copy code is excluded.

## Reliability invariants

Expand Down Expand Up @@ -144,8 +147,16 @@ architecture unless a change explicitly expands its scope.
choose the smallest focused test command.
- Keep tests deterministic: use injected clocks and fake clients rather than
sleeps, wall-clock assertions, or live network calls.
- Add or update focused tests for every behavior change, especially lifecycle
transitions, suppression decisions, retries, and persisted-format migration.
- Add or update focused tests for every behavior change before the work is
complete, especially lifecycle transitions, suppression decisions, retries,
and persisted-format migration.
- Cover success, failure, cancellation, and recovery paths wherever the
changed behavior has those states. New long-running loops require tests for
cancellation, completion, progress, and bounded shutdown.
- Use targeted race tests for concurrency changes. Do not defer required tests
to a follow-up; documentation-only, generated-only, and truly mechanical
changes are the only exceptions, and the change rationale must record the
exception.
- Do not mechanically rewrite unrelated files. Review `git diff` after each
refactor and preserve user changes already present in the worktree.
- Remove transitional APIs once their callers are migrated. Confirm with
Expand Down Expand Up @@ -746,8 +757,9 @@ When changing a monitor, provider, filter, RCA rule, persistence field,
configuration field, metric, integration, RBAC rule, or deployment manifest:

1. Use the existing ownership seam and do not introduce an upward dependency.
2. Add deterministic focused tests for success, failure, cancellation, and
recovery where applicable.
2. Add or update deterministic focused tests for success, failure,
cancellation, and recovery where those paths exist. This is required for
behavior changes, not an optional follow-up.
3. Run `make architecture-check`, catalog checks, test-layout checks, and
`git diff --check` after the workstream rather than after every edit.
4. Update generated catalogs or manifests when their source metadata changes.
Expand Down
10 changes: 8 additions & 2 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,12 @@ make verify
```

The gate builds the binary, runs `go vet`, runs the tests, checks formatting and
line length, checks package boundaries, and runs `golangci-lint`.
line length, checks package boundaries, enforces coverage thresholds, and runs
`golangci-lint`. Use `make coverage-check` to run the coverage gate separately.
The coverage gate uses a race-enabled, repository-wide profile and requires at
least 75% aggregate statement coverage plus 70% for each core runtime package
listed in `scripts/check-coverage.sh`. Generated deep-copy code is the only
documented exclusion.

## 📐 Code and documentation rules

Expand All @@ -51,7 +56,8 @@ line length, checks package boundaries, and runs `golangci-lint`.
network/API call.
- Keep dependency direction explicit; use `make architecture-check` when
adding or moving packages.
- Add focused tests for behavior changes.
- Add focused tests for every behavior change, including success, failure,
cancellation, and recovery paths where they exist.
- Keep docs task-focused: explain the goal, show a complete command, and use
fake credentials.
- Explain Kubernetes terms the first time you use them.
Expand Down
16 changes: 14 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
verify-all verify-catalogs docs-verify line-check docker-build \
docker-build-latest architecture-check test-layout-check help \
verify-focused verify-fast verify-race verify-security \
verify-manifests verify-docs verify-operational
verify-manifests verify-docs verify-operational coverage coverage-check

# Binary names
BINARY_NAME := kwatch
Expand Down Expand Up @@ -54,6 +54,8 @@ help:
@echo " make line-check Check new Go lines for an 80-column maximum"
@echo " make verify-fmt Verify code formatting"
@echo " make verify-unit Run unit tests"
@echo " make coverage Run race-enabled tests and write coverage.txt"
@echo " make coverage-check Run tests and enforce coverage thresholds"
@echo " make verify-all Run all verification scripts"
@echo " make clean Clean build artifacts"
@echo ""
Expand Down Expand Up @@ -104,11 +106,21 @@ verify-unit:
@echo "Running unit tests..."
$(GOTEST) -short ./...

coverage:
@echo "Running race-enabled tests with coverage..."
$(GOTEST) -race --coverprofile=coverage.txt \
--covermode=atomic ./...

coverage-check: coverage
./scripts/check-coverage.sh coverage.txt

# Run the repository's required validation gate. Keep this in the same order
# as AGENTS.md so local verification and CI verification cannot drift.
verify: build vet test lint line-check architecture-check test-layout-check \
verify: build vet test lint coverage-check line-check architecture-check \
test-layout-check \
verify-catalogs \
docs-verify
@git diff --check

# Run the fast package-scoped gate during incremental refactors. The caller
# must provide Go package patterns, for example:
Expand Down
6 changes: 3 additions & 3 deletions docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -249,9 +249,9 @@ It is sent after startup and at most once per week to
|:---|:---|
| `telemetry.enabled` | ✅ Send adoption heartbeats (default: `true`) |

kwatch logs one line at startup naming the endpoint, the payload and this
setting, so the heartbeat is visible from the logs alone rather than only from
this page. Disable it with `telemetry.enabled: false`. Development builds and
kwatch logs one line at startup naming the endpoint and effective setting, so
the heartbeat is visible from the logs without exposing the payload. Disable
it with `telemetry.enabled: false`. Development builds and
recognized CI environments do not send telemetry. The service should use this
data only for aggregate adoption counts and version planning; no feature-usage
or cluster inventory is collected. Telemetry failures never affect monitoring
Expand Down
19 changes: 19 additions & 0 deletions internal/alert/catalog/providers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"testing"

"github.com/abahmed/kwatch/internal/config"
"github.com/abahmed/kwatch/internal/delivery/transport"
)

func TestProviderCatalogMatchesConfiguration(t *testing.T) {
Expand All @@ -18,3 +19,21 @@ func TestProviderCatalogMatchesConfiguration(t *testing.T) {
}
}
}

func TestProviderFactoriesConstructWithEmptyRuntimeValues(t *testing.T) {
for _, name := range ProviderNames() {
name := name
t.Run(name, func(t *testing.T) {
defer func() {
if recovered := recover(); recovered != nil {
t.Fatalf("factory panicked: %v", recovered)
}
}()
provider := NewProvider(name, map[string]interface{}{},
transport.ProviderContext{})
if provider == nil {
t.Fatal("factory returned nil provider")
}
})
} 10BC8
}
1 change: 1 addition & 0 deletions internal/app/background_components.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ func monitoredComponent(
progress := newComponentProgress(componentStartTime(deps))
return componentSpec{
name: name,
cleanStop: name == "heartbeat",
onError: degrade(deps, name),
onHealthy: recoverComponent(deps, name),
progress: progress,
Expand Down
84 changes: 84 additions & 0 deletions internal/app/background_coverage_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
package app

import (
"context"
"errors"
"testing"
"time"

"github.com/abahmed/kwatch/internal/config"
)

func TestBackgroundComponentHelpersReportHealthAndProgress(t *testing.T) {
if !componentStartTime(nil).IsZero() ||
!componentStartTime(&serverDeps{}).IsZero() {
t.Fatal("missing application clock produced a start time")
}
deps := testServerDeps()
degrade(deps, "worker")(errors.New("failed"))
status := deps.healthServer.ComponentStatuses()["worker"]
if status.Available {
t.Fatalf("degraded component status = %+v", status)
}
recoverComponent(deps, "worker")()
status = deps.healthServer.ComponentStatuses()["worker"]
if !status.Available {
t.Fatalf("recovered component status = %+v", status)
}
component := monitoredComponent(
deps, "heartbeat", func(context.Context, *serverDeps) error {
return nil
},
)
if component.name != "heartbeat" || !component.cleanStop ||
component.progress == nil || component.run == nil {
t.Fatal("monitored component was not fully configured")
}
progress := newComponentProgress(time.Now())
if err := runWithProgress(
context.Background(), deps, progress, nil,
); err != nil {
t.Fatal(err)
}
}

func TestBackgroundRunsStopOnCancellation(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
cancel()
deps := &serverDeps{initialized: make(chan struct{})}
if err := runPVCMonitor(ctx, deps); err != nil {
t.Fatal(err)
}
if err := runIncidentSnapshots(ctx, &serverDeps{
persistenceGate: newPersistenceGate(),
}); err != nil {
t.Fatal(err)
}
calls := 0
if err := runTLSSweep(ctx, &serverDeps{
tlsSweep: func() error { calls++; return nil },
}); err != nil || calls != 1 {
t.Fatalf("TLS sweep = %v, calls=%d", err, calls)
}
if err := runTLSSweep(ctx, &serverDeps{
tlsSweep: func() error { return errors.New("tls failed") },
}); err == nil {
t.Fatal("TLS sweep error was swallowed")
}
if got := activeProbesEnabled(config.ActiveProbeMonitor{}); got {
t.Fatal("empty active probe config was enabled")
}
}

func TestProgressHeartbeatHandlesNilAndCancellation(t *testing.T) {
stop := startProgressHeartbeat(context.Background(), nil)
stop()
ctx, cancel := context.WithCancel(context.Background())
calls := 0
stop = startProgressHeartbeat(ctx, func() { calls++ })
cancel()
stop()
if calls < 0 {
t.Fatal("unreachable progress count")
}
}
3 changes: 3 additions & 0 deletions internal/app/bootstrap.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ type bootstrap struct {
deliveryManager *delivery.Manager
clients client.ClientSet
telemetryRun func(context.Context) error
telemetryStatus *adoptionTelemetryStatus
upgradeRun func(context.Context) error
clock clock.Clock
activateOnce sync.Once
Expand Down Expand Up @@ -109,6 +110,7 @@ func newBootstrap(
healthServer: healthServer,
securityMonitor: securityMonitor,
deliveryManager: deliveryManager,
telemetryStatus: newAdoptionTelemetryStatus(),
upgradeRun: upgrader.CheckUpdates,
clock: clockSource,
}, nil
Expand All @@ -134,6 +136,7 @@ func (b *bootstrap) activate(ctx context.Context) error {
result.CurrentVersion,
b.clock.Now,
b.clients.HTTP,
b.telemetryStatus,
)
})
return b.activateErr
Expand Down
68 changes: 68 additions & 0 deletions internal/app/composition_coverage_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package app

import (
"testing"
"time"

"k8s.io/client-go/kubernetes/fake"

"github.com/abahmed/kwatch/internal/client"
"github.com/abahmed/kwatch/internal/clock"
"github.com/abahmed/kwatch/internal/config"
"github.com/abahmed/kwatch/internal/delivery"
"github.com/abahmed/kwatch/internal/incident"
)

func TestCompositionBuildsMonitorFamiliesAndOptionalBranches(t *testing.T) {
engine := incident.NewEngineWithClock(
incident.Config{}, clock.RealClock{},
)
deliveryManager := delivery.NewManagerWithDependencies(
delivery.Dependencies{Clock: clock.RealClock{}},
)
clientset := fake.NewSimpleClientset()
runtime := config.RuntimeConfigFor(&config.Config{})
components := composeMonitorComponents(
runtime, clientset, client.ClientSet{}, engine,
deliveryManager, time.Now,
)
if components.components.Pod.Processor == nil ||
components.components.Workload.SourceConfig == nil {
t.Fatal("monitor families were not composed")
}
if components.tlsProcessor != nil || components.controlPlane != nil {
t.Fatal("disabled optional monitors were composed")
}
if tls, tlsConfig := composeTLSRuntime(
runtime, engine, time.Now,
); tls != nil ||
tlsConfig != nil {
t.Fatal("disabled TLS monitor returned a runtime")
}
if newNetworkGraphRun(
runtime, nil, nil, nil, nil, nil,
) != nil {
t.Fatal("disabled network graph returned a runner")
}
if newStorageGraphRun(
runtime, nil, nil, nil, nil, nil, nil,
) != nil {
t.Fatal("disabled storage graph returned a runner")
}
}

func TestCompositionEnablesTLSAndIntegrationStatus(t *testing.T) {
cfg := &config.Config{TlsMonitor: config.TlsMonitor{Enabled: true}}
runtime := config.RuntimeConfigFor(cfg)
engine := incident.NewEngineWithClock(
incident.Config{}, clock.RealClock{},
)
tls, tlsConfig := composeTLSRuntime(runtime, engine, time.Now)
if tls == nil || tlsConfig == nil {
t.Fatal("enabled TLS monitor did not return both contracts")
}
integration, status := composeIntegrationRuntime(nil, tls, tlsConfig, nil)
if integration.TLS == nil || status != nil {
t.Fatal("integration runtime changed nil control-plane semantics")
}
}
Loading
Loading
0