8000 🧠 Rebuild kwatch around a problem-centric core by abahmed · Pull Request #525 · abahmed/kwatch · GitHub
[go: up one dir, main page]

Skip to content

🧠 Rebuild kwatch around a problem-centric core - #525

Merged
abahmed merged 60 commits into
mainfrom
feat/kwatch-plan
Oct 2, 2026
Merged

abahmed merged 60 commits into
mainfrom
feat/kwatch-plan

Conversation

@abahmed
@abahmed abahmed commented Sep 29, 2026 •
Copy link
Copy Markdown
Owner

Summary

kwatch is rebuilt around a problem-centric core. Instead of one
alert per failing object, kwatch keeps a model of the cluster, explains each
failure by its most likely root cause, and sends one message per problem,
updated in place as it changes and closed when everything recovers.

This is a breaking release candidate: alert format, configuration, state
storage, RBAC and the deployment shape all change. There are no users on a
stable release yet, so there is no migration; install fresh.

What changes for users

Alerts

  • One problem, one conversation. Related failures (pods of a rollout,
    workloads on a lost node, consumers of a missing Secret) are grouped under
    their root cause. Updates go to the same thread (Slack) or issue (GitHub,
    GitLab, Gitea, Jira, ClickUp); paging providers get one alert keyed by the
    problem and resolved with it.
  • Why, not just what. Each message says what broke, the likely cause with
    a confidence and its evidence, what is affected, a timeline of related
    changes (including who changed them), a redacted log excerpt, and next
    steps with read-only kubectl commands.
  • Less noise. New problems settle briefly so the first message is
    complete; only material changes are re-sent; flapping and routine daily
    problems are recognised; a cold start sends one summary instead of many
    alerts; restarts never repeat a message.
  • Changes while kwatch was down are detected at startup and attributed as
    such.

Coverage

Pods and containers, all workload kinds, nodes (readiness, pressure,
draining, usage from kubelet stats), storage (claims, volumes, attachments,
volumes filling up), Services, Ingress, NetworkPolicy, admission webhooks and
policies, quotas and limit ranges, certificates, control plane (API server,
etcd, DNS, scheduler, controller-manager), custom resources that report
status conditions, and optional HTTP/TCP/DNS probes.

Configuration (breaking)

kwatch always watches every supported resource. Scope settings only filter
what is delivered.

  • Kept: namespaces, reasons, namespaceSelector, silences (every
    field in a rule must match), the deprecated ignore* shorthands,
    severityByReason, severityByOwnerKind, runbooks, maintenance
    (annotations kwatch.io/maintenance and kwatch.io/maintenance-until),
    activeProbeMonitor, heartbeatMonitor, healthCheck 8000 , auditLog,
    templates, resyncSeconds, app, upgrader, telemetry, crd,
    alert and provider routes.
  • Removed: every per-monitor section except the two above,
    correlation.*, smartGrouping.*, inhibition.*, maxRecentLogLines,
    workers, includeLogs, includeEvents, ignoreLogPatterns and
    silences[].logPatterns, containerRestartThreshold,
    reportStartupBaseline, adaptiveThresholds,
    ignoreFailedGracefulShutdown, ignoreDisruptionTerminations,
    message.*, crd.failureConditions, crd.graphReferences.
  • Templates receive .Message (the structured problem) and .Text.

Deployment and operations (breaking)

  • State on disk: a kwatch-data PVC (2Gi) mounted at /var/lib/kwatch
    replaces all state ConfigMaps. The PVC is kept on uninstall.
  • One replica, Recreate strategy, no PodDisruptionBudget. The Lease is
    only a lock that prevents two writers.
  • Least-privilege RBAC derived from what kwatch watches; no ConfigMap
    write access; kube-system Leases are read through a Role. Missing
    permissions are reported in /health as rbac with a reason code.
  • Endpoints: /incidents is now /problems (token protected, a safe
    summary of live problems); /persistence is removed; there is no standby
    role.
  • Audit log: one JSON line per problem decision; kwatch-scorecard
    reads the new format.

Implementation notes

  • New packages: knowledge (model, kube sources, bbolt store), signal
    (detectors), reason (rules and scored hypotheses), problem, story,
    notice, core, filter (scope, silences, maintenance).
  • Deleted the incident engine and its supporting packages (controller,
    incident, persistence, monitor/*, insight, observe, statuswatch and
    others).
  • Coverage gate now covers the new core packages; aggregate coverage 83.8%.

Known gaps before stable

  • The end-to-end scenario suite still asserts the old incident messages and
    will be rewritten separately.
  • Digest-tier problems are delivered immediately as low-severity messages;
    batching them into a periodic digest is planned.
  • Public documentation on kwatch.dev is updated separately.

Test plan

  • make verify (build, vet, lint, race tests, coverage, architecture,
    catalogs, docs, line length)
  • Helm template tests and helm lint
  • CI on this PR
  • RC smoke test on a real cluster: pod Ready, /health shows rbac
    running, break a Deployment and receive one message that resolves

Still landing on this branch

Fixes from the final pre-PR review are in progress and will be pushed here
before this leaves draft: CI and Kind scripts for the single-replica design,
removal of remaining dead incident-era code and metrics, diagnostics
endpoints (/test-alert, /deadletters, /security), redaction and
shutdown hardening, and wording.

Derive the anonymous cluster ID from a salted hash of the kube-system
UID so reinstalls keep one identity. Stop re-sending a heartbeat when
saving the send time fails. Add a KWATCH_TELEMETRY=false opt-out and a
startup notice. The payload stays the cluster ID and kwatch version.
Releases up to v1.0.0-rc.10 stay under MIT; the MIT notice is kept in
docs/licensing.md. Update image, chart, and README license metadata.
Security: broader secret redaction including termination messages and
hints; heartbeat URL redaction; no alert proxy on the Kubernetes client;
Secret data stripped from the informer cache; env expansion inside
parsed YAML values; unknown subcommands exit instead of starting.

Reliability: parallel saver shutdown; dedicated Lease client; Slack
stale-thread fallback and bounded state; oldest-first thread trimming;
baseline debounce; audit rotation; late CRD rediscovery; async
statuswatch with denied backoff; bounded log fetches; go and process
metrics; legacy shard prefix on restore.

Providers: email relay/username/tls, Feishu signing, Opsgenie EU,
Discord threads, Teams plain cards, SendGrid string recipients,
SES/SNS session tokens, GoAlert example-host rejection.

Detectors: scaled-to-zero Services, LoadBalancer-only conditions,
sustained port mismatch, autoscaler resolve and node attribution,
empty DaemonSets, control-plane resolve, timely NotReady/Pending,
deduplicated availability, ordered log hints, parallel filesystem
reads, lease-free mass failures, consistent qualified names.
Entities, typed relations, attributes with value history, and bounded
change history, maintained from facts with indexes in both directions.
Relations are reference-counted per source; deleted entities keep their
history as tombstones until pruned.
Implements ADR 0010's pipeline: Kubernetes schemas translate informer
objects into facts; the knowledge model tracks entities, relations and
meaningful changes; detectors raise signals; reasoning rules prove root
causes (node, rollout, config change, missing dependency, backend,
scheduling, failing pods) with scored evidence; problems group signals
per root with settle, material-change updates, adaptive hysteresis and
flap detection; stories write per-case messages. Problems persist in a
bbolt state file claimed with the Lease epoch.

Scenario tests: node pressure (one problem for three workloads), bad
rollout (one message naming the image change), application crash (no
invented cause), missing Secret (Secret is the root), flapping workload
(three messages across six cycles).
Replace the two-replica HA layout with a single writer: Recreate
strategy, a ReadWriteOnce PVC for the state store mounted at
/var/lib/kwatch, 30s not-ready/unreachable tolerations, and no PDB. The
chart gains persistence settings (size, storageClass, existingClaim,
emptyDir for evaluation) and drops replicaCount.
Warning events become notes and signals; admission webhooks, PDBs,
quotas, NetworkPolicies and volume attachments are modelled; kubelet
stats add node disk, inode and pressure-stall signals and PVC usage with
fill-time prediction; a dynamic source watches APIServices and every CRD
with status (Gateway API, snapshots, operators), rediscovering new ones.
Probes check the API server and cluster DNS. New rules connect
admission, quota, network policy, metrics API, DNS and zone or node-pool
failures, and group a rollout with the configuration it changed.
Draining or departing nodes are expected disruption and go to the digest.
Announcements carry redacted crash output; changes made while kwatch was
down are recovered from saved fingerprints; a cold start sends one
summary of existing problems. Telemetry, upgrade checks, RBAC audit and
the heartbeat keep running with the new core.
Containers that keep restarting and repeated OOMs, pods in Unknown or
gated state, a shared-registry root for image pulls; Ingress backends,
LoadBalancer provisioning, degraded backends, Service port mismatches
and deny-all egress policies (informational); missed CronJob runs,
suspended CronJobs and Jobs, ReplicaSet failures; stuck namespaces and
nodes, invalid Pod Security labels and LimitRanges, and condition-based
built-in APIs (CSRs, API priority and fairness, admission policies,
resource claims); etcd, scheduler and controller-manager health and API
latency; container CPU, memory and ephemeral-storage pressure, CPU
throttling, node network and runtime error rates and limit overcommit;
and user-configured HTTP, TCP and DNS probes. Routine same-time-of-day
problems are learned and go to the digest. ADR 0010 lists the old
reasons the core expresses differently.
Stories move to the leaf notice package so providers can render them.
Delivery gains a story job: providers implementing SendStory render it
natively, paging providers receive an alert event keyed by the problem
so updates and resolves hit one alert, and all others receive the text
rendering within their size limit. Provider routes match a story's
namespaces, reasons and severity. The webhook sends one JSON schema for
every problem message; Slack posts one root per problem, edits it in
place and threads every update.
- Remove the KWATCH_CORE flag; the problem-centric core is the only engine
- Delete insight, graphcontext, change and message report builders
- Slack keeps one story thread map; fix queue coalescing keeping stale stories
- Apply namespace, reason, selector and silence scope per problem
- Write audit entries from core decisions; scorecard reads problems
- Drop the flat suppression index and log-pattern silences
- Port or remove tests that targeted the deleted engine
- kube declares the access its sources use; the RBAC audit checks that list
  and reports through health instead of never running
- ClusterRole is least privilege; the ConfigMap state Role is gone and
  kube-system leases are read through a Role
- Remove monitor toggles, correlation, grouping, inhibition, log and worker
  settings the core never read; runtime config has scope, policy,
  delivery, lifecycle and active probe views
- Trim the KwatchConfig API, CRD schema, chart schema and catalogs to match
Rename the protected diagnostics HTTP endpoint from /incidents to /problems.
Update related Go identifiers in internal/health and callers in internal/app:
- Interface: IncidentLister -> ProblemLister
- Handler: incidentsHandler -> problemsHandler
- Fields: incidentAPI -> problemAPI, Incident -> Problems

Update tests and documentation to reflect the endpoint rename.
Comment thread internal/knowledge/store/collection.go Dismissed
Change wording in comments, docs, and configuration descriptions from
"incidents" to "problems" to reflect the current messaging that kwatch sends
one alert per root cause.

- Update README.md with problem-centric language
- Update provider documentation
- Refresh comments in provider packages and core delivery logic
- Update persistent state descriptions
- Regenerate configuration catalogs
…t/kwatch-plan

# Conflicts:
#	README.md
#	deploy/chart/values.yaml
#	deploy/config-catalog.meta.tsv
#	deploy/config-catalog.tsv
#	deploy/deploy.yaml
#	internal/alert/alerta/alerta.go
#	internal/alert/gitea/gitea.go
#	internal/alert/gitlab/gitlab.go
#	internal/alert/ilert/ilert.go
#	internal/alert/newrelic/newrelic.go
#	internal/alert/signl4/signl4.go
#	internal/alert/splunkoncall/splunkoncall.go
#	internal/alert/squadcast/squadcast.go
#	internal/event/event.go
#	internal/knowledge/store/doc.go
Remove the ADRs and the website sync checklist, which are maintainer
history rather than user or contributor guidance, and drop every
reference to them from docs, scripts, manifests and code comments.
@abahmed
abahmed marked this pull request as ready for review October 2, 2026 12:47
@abahmed
abahmed merged commit 3483373 into main Oct 2, 2026
11 of 12 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants

0