kopf-conventions
Skill7 starsChanged 4 days agoMITView on GitHub
kopf mechanics for Python Kubernetes operators. TRIGGER when: code imports `kopf` or defines `@kopf.on.*`/`@kopf.timer` handlers; wiring `OperatorSettings`; emitting events from a Python operator; user asks why events don't show up, or about `kopf.event`, `kopf.TemporaryError` or `on.resume`. SKIP when: the operator is not kopf, or the question is framework-agnostic reconcile design (`kubernetes-operator-conventions`).
1 other project uses a version of this.
Adopted by
Most recently taken up by
- leroyguillaume/claudeword for word, first seen Nov 29, 2026
Other versions1 project uses a version of this.
Word for word · 1
- leroyguillaume/claude★ 7100% same
Edited · 0
None found.
Wrote their own version · 0
None found.
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository54 other files it gives its agents.
- adr-conventionsSkill
- api-conventionsSkill
- architecture-conventionsSkill
- argocd-conventionsSkill
- ci-conventionsSkill
- config-conventionsSkill
- contributing-conventionsSkill
- councilSkill
- cryptography-conventionsSkill
- dependency-update-conventionsSkill
- diagram-conventionsSkill
- docker-conventionsSkill
- documentation-conventionsSkill
- frontend-conventionsSkill
- github-actions-conventionsSkill
- github-issue-conventionsSkill
- github-pr-conventionsSkill
- github-repo-settingsSkill
- gitlab-ci-conventionsSkill
- helm-conventionsSkill
- herdr-core-delegationSkill
- herdr-delegationSkill
- herdr-tui-delegationSkill
- kubernetes-operator-conventionsSkill
- logging-conventionsSkill
- logo-conventionsSkill
- mise-conventionsSkill
- ollama-conventionsSkill
- openssf-conventionsSkill
- pr-conventionsSkill
- pre-commit-conventionsSkill
- project-metadata-conventionsSkill
- python-async-conventionsSkill
- python-conventionsSkill
- readme-conventionsSkill
- release-script-conventionsSkill
- release-supply-chain-conventionsSkill
- renovate-ci-conventionsSkill
- rest-conventionsSkill
- rust-build-conventionsSkill
- rust-conventionsSkill
- rust-http-conventionsSkill
- security-policy-conventionsSkill
- signal-handling-conventionsSkill
- sql-conventionsSkill
- starlight-conventionsSkill
- systemd-conventionsSkill
- system-user-conventionsSkill
- task-conventionsSkill
- terraform-conventionsSkill
- topic-splittingSkill
- ui-copy-conventionsSkill
- web-layout-conventionsSkill
- yaml-conventionsSkill
The file
We split this skill into the rules it gives an agent
5 rules. About 0 are common, 0 are distinctive, and 5 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈0
Distinctive · estimate
This author's own choices. Worth a look.
5
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 158
""/namespaces—list, watch: when running cluster-wide (clusterwide=True / cluster-scoped CRs), so kopf can enumerate namespaces. - Very specific: line 164
Put these in the operator's block of values.yaml as rbac.rules (plus extraRules: []), never hardcoded in the template (see …
- Very specific: line 171
Use explicit kopf.event for *transitions* (provisioned, created, failed-this-attempt) and status.conditions + phase (written via …
- Very specific: line 238
Default the Pod's memory request to 256Mi and limit to 512Mi.
- Very specific: line 242
If the Pod restarts with reason OOMKilled, raise the memory limit first.
≈ “Common” is an estimate: at least 1 in 5 of the 408,460 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
kopf conventions
kopf-specific implementation details for Python operators. The
framework-agnostic reconcile principles (always-requeue, idempotency,
finalizers, ownerReferences, field manager) live in
kubernetes-operator-conventions — this skill is the kopf wiring that those
principles compile down to, plus the sharp edges that bite in practice.
Errors — TemporaryError, never PermanentError
A failing handler raises kopf.TemporaryError with the delay= that
kubernetes-operator-conventions picks per error class: it logs and
re-schedules. Never kopf.PermanentError, which stops the retries. A bare
raise of an arbitrary exception also requeues, but TemporaryError controls
the message and the delay.
Events & posting — the model you must get right
kopf has two completely separate ways an event reaches the cluster, gated by two different settings. Confusing them is the #1 cause of "I had errors but no events showed up on the resource".
- Explicit calls —
kopf.event(body, type=..., reason=..., message=...)posts iffsettings.posting.enabledis True (the default), whateverposting.level. The shorthands also check the level:kopf.infoneedslevel <= INFO,kopf.exceptionlevel <= ERROR, andkopf.warnlevel <= WARNINGwhile ignoringenabled. Full control overtype/reason/message. - Log-record posting — kopf can mirror log lines made on the object
logger (
loggerinjected into a handler) as events. This is gated bysettings.posting.loggers, which defaults toFalse. When off,logger.error(...)/logger.warning(...)are logged but never posted.posting.enableddoes not turn this on — onlyposting.loggersdoes.
The trap
raise kopf.TemporaryError(...)does NOT, on its own, post a Kubernetes event. The error event you expect only exists if either (a) you post it explicitly withkopf.event, or (b)settings.posting.loggers = Trueso the framework's error log of the failure becomes an event.
Setting only settings.posting.enabled = True (a very common operator setup)
buys you nothing for errors raised via TemporaryError, because that path
surfaces through the logger, not an explicit kopf.event. Any docstring or
skill that says "kopf posts a Warning event for free when you raise
TemporaryError, provided posting.enabled is on" is wrong — it needs
posting.loggers.
kopf's log-to-event handler posts a record only when all of these hold: posting.enabled, record.levelno >= posting.level,
posting.loggers, and the record carrying a k8s_ref (i.e. it was logged
on the object logger, not a module-level logging.getLogger(...)).
Surfacing errors as events — post them explicitly
Explicit lifecycle events: the failure event. Post your own events at the reconcile level — good
reasons, one event per outcome, no framework duplication. Wrap the handler:@kopf.on.create(GROUP, VERSION, PLURAL) @kopf.on.resume(GROUP, VERSION, PLURAL) @kopf.on.update(GROUP, VERSION, PLURAL) async def reconcile(spec, body, name, logger, **_): try: changed = await _reconcile(spec, body, name, logger) except Exception as exc: logger.error("reconcile failed", extra={"cause": str(exc)}) kopf.event(body, type="Warning", reason="ReconcileFailed", message=f"Reconcile failed: {exc}") if isinstance(exc, kopf.TemporaryError): raise raise kopf.TemporaryError(f"reconcile failed: {exc}") from exc if changed: kopf.event(body, type="Normal", reason="Reconciled", message="Desired state applied.")Make the raised
TemporaryErrormessage carry the failing operation + cause (e.g."creating the backing database failed: 500 ...") so the single rolled-upReconcileFailedevent still names what broke; anything else is wrapped, never re-raised raw, and the requeue holds either way._reconcilereturns whether it changed anything:on.resumeruns it for every CR at each operator start, and a steady-state pass posts nothing.Log-posted events: extra detail, never the failure event. To add one event per failing operation from the requeue chokepoint without plumbing
bodyeverywhere, set all three in the startup handler:settings.posting.enabled = True settings.posting.loggers = True settings.posting.level = logging.WARNING # NOT the INFO defaultWithout raising the level off its
logging.INFOdefault, every info line becomes an event and floods the object. That level also silenceskopf.info, so post Normal events withkopf.event(type="Normal"), as the wrapper above does. Even then the posted events carryreason="Logging"(less descriptive than an explicit one), and the framework may also post its own error log — expect duplicates.
Log posting never replaces the explicit Warning that
kubernetes-operator-conventions requires: it hangs on three settings and on
logging through the object logger, so a settings refactor or a module-level
logger drops the event without a sound. Don't half-set it (enabled without
loggers) and assume errors post — they won't.
Cluster-scoped objects & other event gotchas
- Events are namespaced; cluster-scoped CRs are not. For a cluster-scoped
object kopf posts the event into the operator's own namespace
(
get_default_namespace(), falling back todefault), withinvolvedObjectpointing at the CR.kubectl describe <clusterscoped>still finds it by uid. RBAC. The operator's (Cluster)Role needs this rule; missing it is silent (see next point):
- apiGroups: - "" resources: - events verbs: - create - patch- POST failures are swallowed.
events.post_eventcatches API errors and only emitslogger.warning("Failed to post an event. ... Code: 403 ..."). Events never fail the handling cycle — so when events are mysteriously absent, grep the operator logs for "Failed to post an event" before suspecting your code. - Messages are truncated to 1024 chars by kopf; keep them short.
RBAC — the operator needs more than its own CRs
The (Cluster)Role must grant, beyond the obvious verbs on your own custom resources:
apiextensions.k8s.io/customresourcedefinitions—get, list, watch(cluster scope). kopf scans CRDs at startup to resolve every handled resource. Missing this, the operator never starts and crash-loops withcustomresourcedefinitions.apiextensions.k8s.io is forbidden: User "system:serviceaccount:…" cannot list resource "customresourcedefinitions" … at the cluster scope. This is the single most common first-boot RBAC failure — add the rule by default whenever you scaffold an operator chart.""/events—create, patch(post status events; see above).""/namespaces—list, watchwhen running cluster-wide (clusterwide=True/ cluster-scoped CRs), so kopf can enumerate namespaces.- Peering (if enabled):
get, list, watch, patchonkopf.dev/clusterkopfpeerings(orzalando.org/clusterkopfpeerings). Disable peering (settings.peering.standalone = True) to avoid needing it.
Put these in the operator's block of values.yaml as rbac.rules (plus
extraRules: []), never hardcoded in the template (see helm-conventions). When debugging a
crash-looping operator, read the first lines of the pod log — an RBAC
forbidden at boot points straight at a missing rule above.
Lifecycle events vs status conditions
Use explicit kopf.event for transitions (provisioned, created,
failed-this-attempt) and status.conditions + phase (written via
patch.status[...]) for ongoing state. Don't emit an event every reconcile
for steady-state — Events have no dedup (kopf posts with generateName, so
each call is a brand-new Event) and a per-interval timer posting the same
failure will spam. Steady "is it healthy right now" belongs in status; "it just
changed" belongs in an event.
Persistence — keep progress out of annotations
Route kopf's retry bookkeeping into the status subresource instead of the
default kopf.zalando.org/* metadata annotations, so the object's annotations
stay clean and failures surface through events/logs:
settings.persistence.finalizer = f"{GROUP}/finalizer"
settings.persistence.progress_storage = kopf.StatusProgressStorage()
settings.persistence.diffbase_storage = kopf.StatusDiffBaseStorage()This requires the CRD's status schema to allow the extra keys
(x-kubernetes-preserve-unknown-fields: true under status).
One reconcile handler for create + resume + update
Register the same handler for all three so the desired state is re-applied uniformly:
@kopf.on.create(GROUP, VERSION, PLURAL)
@kopf.on.resume(GROUP, VERSION, PLURAL) # fires on operator (re)start
@kopf.on.update(GROUP, VERSION, PLURAL)
async def reconcile(...): ...on.resume is what makes a version bump / Deployment roll re-apply the new
desired state to every existing CR — template changes shipped in a new operator
version reach CRs created by an older one. This only works if every step is
idempotent (server-side apply, treat 409/404 as success).
Handler argument injection
kopf injects by parameter name — declare only what you use and absorb the
rest with **_:
body(fullkopf.Body) — pass this tokopf.event(...)and readbody["metadata"]["uid"]for ownerReferences / child pruning.spec,name,namespace,uid,status,patch(write status viapatch.status[...]),logger(the object logger — use it, not a module logger, or you lose thek8s_refthat event-posting and structured object refs depend on),meta,old/new/diff(on updates).
Timers for post-provision state
Child/external health changes after the create/update events have fired. Use
@kopf.timer(GROUP, VERSION, PLURAL, interval=...) to roll that up into
status on a cadence. A timer that can't read its inputs should requeue like
any reconcile error (see kubernetes-operator-conventions) — but don't have it
post an event every tick (spam; use status for ongoing state).
Memory footprint — size the Pod above the kopf baseline
kopf carries a real resting memory cost: the framework plus the Kubernetes
client and its watch/peering caches idle well above a naive 128Mi, so a
chart that ships that as the limit gets the operator OOMKilled under normal
watch load — before any work happens.
- Default the Pod's memory request to
256Miand limit to512Mi. CPU stays uncapped (compressible) — set only a request (e.g.100m). These come on top of the requests and limitshelm-conventionsrequires (CPU and ephemeral storage included). - If the Pod restarts with reason
OOMKilled, raise the memory limit first; don't chase a leak prematurely — it's usually just the kopf baseline.
Anti-patterns to fix on sight
- Assuming
TemporaryErrorposts an event with onlyposting.enabledset. - Logging errors on a module logger (
logging.getLogger(__name__)) inside a handler and expecting events — nok8s_ref, so it can never post. - Setting
posting.loggers = Truebut leavingposting.levelat INFO (event flood). - Posting an event every reconcile for steady state instead of using
status.conditions. - Progress stored in
kopf.zalando.org/*annotations when the CRD could hold it instatus.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

