Skip to content

feat(sandboxpolicy): start gate pod-set writer and cgroup-gone check - #1165

Draft
matthyx wants to merge 46 commits into
omx/nri-s2-pending-ownerfrom
omx/nri-s3-podgate
Draft

matthyx wants to merge 46 commits into
omx/nri-s2-pending-ownerfrom
omx/nri-s3-podgate

Conversation

@matthyx

@matthyx matthyx commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Part 4 of the NRI start gate. It is based on #1162 (S2) and merges #1163 (S4), so review it after those two.

It joins the node-owner API and the pod classification into one writer for the pod set. Nothing enables it yet. With the gate off, the service makes exactly the backend calls it made before, and a call log recorded from the previous code checks that.

  • One writer for the pod set. It tracks the pods the NRI side joined, sandbox by sandbox.
    • Each joined sandbox keeps its own cgroup.
    • Sandboxes the gate can't classify or resolve still count.
    • Removing a sandbox the gate never joined only leaves a tombstone.
    • A missing informer entry never removes a joined pod.
  • A worker per pod. It runs marks, binds, unmarks and releases in order.
    • A handler waits until its deadline (WorkDeadline) and then returns. The worker's write still applies if its sequence is current.
    • Replies never wrap context errors, and they keep ErrStaleSequence.
  • A cgroup-gone check by kernfs ID.
    • A cgroup counts as gone only after ESTALE twice, at least a second apart.
    • A live path with the same inode vetoes the result.
    • Before enabling the gate, the service checks the capability, then checks that a live cgroup opens and an impossible ID answers ESTALE. If any check fails, the gate stays off.
  • Shutdown order. The service waits for the gate's workers before the backend closes.

Validation: go build; go vet, including the kernel tags; go test -race on pkg/sandboxpolicy/... (38 named S3 tests, no skips); gofmt; go mod tidy; golangci-lint 2.15.0 reports the same issues as the base. The kernel's ESTALE answers need CAP_DAC_READ_SEARCH, so they come with the VM qualification.

AI Review

Written with Claude Code (Claude Opus 5.5) and checked in four independent adversarial review rounds. The reviewers reproduced and fixed three high-severity and one medium-severity pod-lifecycle bugs: a live pod unbound when an old sandbox is removed, a release lost to deduplication, the gate enabled with a check that cannot answer, and an unresolved sandbox leaving a pod unbound. Each now has a regression test. The owner approved the design decisions.

🤖 Generated with Claude Code

AI-skills: none | cmds: /goal

matthyx and others added 3 commits November 24, 2026 12:10
Add the classification side of the NRI start gate. Nothing calls it yet;
the one existing PodPlans caller keeps its behaviour.

- The controller publishes an immutable classification snapshot (policies,
  classes, plans, cluster CIDRs, config error) from every reconcile path,
  stamped with a config sequence. Readers never take the controller lock,
  so a slow API server cannot stall them.
- ClassifyPod answers Unselected, Selected (per-section plan, mode, shape)
  or Unknown for an NRI pod. Unknown covers a config error, an errored
  policy in scope (a ClusterSandboxPolicy is in scope for every pod), an
  unknown or mismatched pod, more than 64 policies for a container, and an
  invalid container kind. The exemption annotation is checked first; an
  exempt pod that a policy selects is flagged.
- PodPlans reads the snapshot. PodPlansAt also returns its config
  sequence. Before the first snapshot it reports not ready.
- The pod cgroup resolver reads the pause process's cgroup through the
  pinned host cgroup namespace, guarded by a pidfd, and fails closed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Matthias Bertschy <matthias.bertschy@gmail.com>
Join the start gate's node-owner API and classification into one writer
for the pod set. Nothing enables it yet; with the gate off, the service
makes exactly the backend calls it made before (checked against a call log
recorded from the previous code).

- One writer keeps the pods the NRI side joined, by sandbox: each joined
  sandbox keeps its own cgroup, sandboxes the gate cannot classify or
  resolve are still counted, and a removal of a sandbox the gate never
  joined only leaves a tombstone. A missing informer entry never removes
  a joined pod. With the gate on, the refresh sends the joined pods with
  the snapshot's sequence.
- A worker per pod runs marks, binds, unmarks and releases in order. A
  handler waits until its deadline (WorkDeadline) and then returns; the
  worker's write still applies if its sequence is current. Replies never
  wrap context errors and keep ErrStaleSequence.
- A cgroup-gone check opens the cgroup by its kernfs ID. A cgroup counts as
  gone only after ESTALE twice, at least a second apart, and a live path
  with the same inode vetoes it. Enabling the gate first checks the
  capability and that a live cgroup opens and an impossible ID answers
  ESTALE; otherwise the gate stays off.
- The service waits for the gate's workers before the backend closes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Matthias Bertschy <matthias.bertschy@gmail.com>
@matthyx matthyx added ai-assisted Created through Armosec AI tooling (armosec-shared-rules plugin) ai-reviewed-local labels Nov 24, 2026
@coderabbitai

coderabbitai Bot commented Nov 24, 2026

Copy link
Copy Markdown

Important

Draft PR not reviewed

Draft PRs are not automatically reviewed by default.

  • Trigger a manual review

To automatically review draft PRs, update your CodeRabbit configuration:

reviews:
  auto_review:
    drafts: true
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@github-actions

Copy link
Copy Markdown

Performance Benchmark Results

Node-Agent Resource Usage
Metric BEFORE AFTER Delta
Avg CPU (cores) 0.040 0.038 -3.8%
Peak CPU (cores) 0.042 0.043 +2.6%
Peak CPU p95 (cores) 0.041 0.042 +0.9%
Avg Memory (MiB) 205.370 201.832 -1.7%
Peak Memory (MiB) 209.594 204.727 -2.3%
Dedup Effectiveness

No data available.

matthyx and others added 6 commits December 3, 2026 17:54
Conflicts: reconcile keeps both defers (file write activity and the
classification snapshot); sections.go keeps main's ExecPlan next to this
slice's sectionRevision refactor of split.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Matthias Bertschy <matthias.bertschy@gmail.com>
Conflicts: reconcile and sections.go as in the S4 merge (keep both
sides). Service.Close takes main's fence-aware reportStop and the fence
retirement join, then stops the pod gate before the backend closes, as
before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Matthias Bertschy <matthias.bertschy@gmail.com>
…3-podgate

Takes the S2 gofmt fix and the S4 merge of main. The gate-off golden test
now gives its Service the mapping verdict exporter that main's Close
drains.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Matthias Bertschy <matthias.bertschy@gmail.com>
…trict for the start gate

Main added the http section, which no pod mark can hold. An enforce policy
whose only section is http now selects the pod without making it Strict,
so the start gate lets it start (NotStartGated) and the gateway binds it
afterwards, as on main. Before, the gate refused such a pod (D1: no section
a pod mark can hold). http next to any other section keeps the pod Strict.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Matthias Bertschy <matthias.bertschy@gmail.com>
…classify

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Matthias Bertschy <matthias.bertschy@gmail.com>
… http not gate-Strict) into omx/nri-s3-podgate

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Matthias Bertschy <matthias.bertschy@gmail.com>
@github-actions

github-actions Bot commented Dec 3, 2026

Copy link
Copy Markdown

Performance Benchmark Results

Node-Agent Resource Usage
Metric BEFORE AFTER Delta
Avg CPU (cores) 0.038 0.138 +266.1%
Peak CPU (cores) 0.043 0.146 +240.8%
Peak CPU p95 (cores) 0.041 0.146 +257.6%
Avg Memory (MiB) 211.066 277.417 +31.4%
Peak Memory (MiB) 215.359 292.844 +36.0%
Dedup Effectiveness

No data available.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Critical lifecycle and sequencing flaws can remove live pods’ Strict bindings or leave obsolete bindings enforced indefinitely.

8 open issues
What changed in this PR

This PR connects pod classification and node-owner APIs into the NRI start gate’s pod-set writer. The gate remains disabled by default.

Changes:

  • Adds per-pod workers, sequenced writes, deadline handling, and coordinated shutdown.
  • Adds cgroup resolution and self-tested cgroup-removal checks.
  • Introduces classification snapshots and lifecycle regression tests, including gate-off compatibility checks.
File Description
pkg/​sandboxpolicy/​startgate/​deadline.go Calculates bounded work deadlines.
pkg/​sandboxpolicy/​startgate/​deadline_test.go Tests deadline boundaries.
pkg/​sandboxpolicy/​sequence.go Updates sequence documentation.
pkg/​sandboxpolicy/​sequence_test.go Tests ordering and input capture.
pkg/​sandboxpolicy/​sections.go Shares section digests and stale-error checks.
pkg/​sandboxpolicy/​sections_test.go Adapts tests to classification snapshots.
pkg/​sandboxpolicy/​integration/​service.go Integrates gate activation, refresh, and shutdown.
pkg/​sandboxpolicy/​integration/​podgate.go Implements pod membership and ordered workers.
pkg/​sandboxpolicy/​integration/​podgate_test.go Tests gate operations and service integration.
pkg/​sandboxpolicy/​integration/​podgate_review_v3_test.go Tests unresolved-sandbox cgroup retention.
pkg/​sandboxpolicy/​integration/​podgate_review_test.go Adds lifecycle regression coverage.
pkg/​sandboxpolicy/​integration/​podcgroup.go Resolves sandbox pod cgroups.
pkg/​sandboxpolicy/​integration/​podcgroup_test.go Tests resolution and process validation.
pkg/​sandboxpolicy/​integration/​podcgroup_linux.go Adds pidfd checks and namespace validation.
pkg/​sandboxpolicy/​integration/​gateoff_golden_test.go Checks unchanged gate-off backend calls.
pkg/​sandboxpolicy/​integration/​cgroupgone_linux.go Implements cgroup-removal checks and self-tests.
pkg/​sandboxpolicy/​integration/​cgroupgone_linux_test.go Tests removal evidence and live-path vetoes.
pkg/​sandboxpolicy/​igbackend/​releaseretry_s3_test.go Tests failed-release retries.
pkg/​sandboxpolicy/​igbackend/​nodeowner_podgate_test.go Adds unbind-failure injection.
pkg/​sandboxpolicy/​igbackend/​hostcgroup_linux.go Exposes host-namespace cgroup reads.
pkg/​sandboxpolicy/​igbackend/​hostcgroup_linux_test.go Tests procfs validation.
pkg/​sandboxpolicy/​controller.go Publishes sequenced classification snapshots.
pkg/​sandboxpolicy/​classify.go Adds lock-free pod classification.
pkg/​sandboxpolicy/​classify_test.go Tests classification and snapshot consistency.

Review effort: Balanced

matthyx and others added 9 commits December 3, 2026 21:17
…Strict

The exec fence and the kernel section slots treat a rule or default in
enforce mode as Strict, but classification reported Strict=false for an
Audit policy with such an override, so a pending binding would have
allowed faults. enforceOverride checks rule and default modes of the exec,
identity, privilege, network and file sections; gateStrict and section
Strict use it. The http-only exception (owner decision F2) is unchanged.

Addresses Copilot review on #1163 (r4790461052).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Matthias Bertschy <matthias.bertschy@gmail.com>
- cgroup gone: a noted path keeps its live veto while it names its ID and
  is dropped only on ENOENT/ENOTDIR or an ID mismatch; checks are
  serialized and re-probe the handle after the path veto, so a transient
  ESTALE cannot prove a live cgroup gone.
- pod gate: a refresh holds writeMu exclusively from the cgroup lookup to
  afterBind and worker jobs hold it shared, so a lifecycle write decided
  during a refresh lands after it (equal-sequence cgroup move).
- An unmark counts as done only while nothing newer is recorded; an
  unresolved joined sandbox stops prune; released entries without a
  cgroup are retired beyond maxTombstones once their release finished.
- cgroup handle test probes the mount root in a private cgroup namespace.

Addresses Copilot review on #1165 (r4790513329, r4790513401,
r4790513478, r4790513541, r4790513599, r4790513752, r4790513803) and the
independent review. r4790513686 is an owner question (design §5).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Matthias Bertschy <matthias.bertschy@gmail.com>
…-classify

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Matthias Bertschy <matthias.bertschy@gmail.com>
…3-podgate

Conflict in igbackend/nodeowner_podgate_test.go: the fake instance keeps
S3's unbindErrBy and S2's unbindErr and unbindBeforeErr.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Matthias Bertschy <matthias.bertschy@gmail.com>
…gate

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
When the gate is on and a refresh authoritatively classifies a
still-scheduled pod as Unselected (its last policy deleted, disabled or
no longer selecting it), it now queues a sequenced unmark through the
gate's unmark job, so the old Strict binding does not stay until the
cgroup is gone. An informer miss, Unknown, a config error or an exempt
pod keeps the binding; a newer mark or bind wins by sequence.

Owner decision (batch 8) on Copilot review #1165 r4790513686; replaces
design §5's keep-until-gone for this case.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Matthias Bertschy <matthias.bertschy@gmail.com>
…to gate-Strict

expandIdentity removes the identity section before classification, so an
enforce identity default, or an enforce imds/envRead rule that expands to
nothing, was invisible to gateStrict: an Audit policy with one was not
Strict. An Enforce policy with http plus an identity section also looked
http-only after expansion and took the http-only exception. The identity
report now records that the section existed and whether it asked for
enforce; gateStrict uses both. The http-only exception (owner F2) is
unchanged for true http-only policies.

Addresses Copilot review on #1163 (r4792143254).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Matthias Bertschy <matthias.bertschy@gmail.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@matthyx
matthyx requested a balanced review from Copilot December 3, 2026 22:13

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Unresolved issues can leave stale enforcement on static pods after policy deletion, lose attribution for retained cgroup bindings, and allow excessive compilation beyond the policy cap.

4 open issues
3 resolved since last review

Review effort: Balanced

Comment thread pkg/sandboxpolicy/classify.go Resolved
// NRI mark) stays in the backend until an accepted unmark, a release or
// the gone proof: its verdicts keep their pod (Copilot #1165
// 4796305772).
retained := gate.retainedBindings()

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in e843b86: the cgroup index exports every cgroup a gate entry marked, with the path recorded when it was marked, so the held cgroup 77 keeps its pod/namespace attribution after a refused mark on 88 and an informer miss; entries retire on an accepted unmark, a release or the gone proof. Test: TestIndexKeepsMarkedCgroups.

matthyx and others added 4 commits December 4, 2026 09:45
…y cap

classify counted each container's selecting policies but checked the
64-policy cap only at the end, so every policy past the 64th was still
class-checked and compiled although the result was Unknown anyway; an
over-limit policy set made every NRI classification expensive. Once any
container has more than 64 selecting policies, classify only counts the
remaining matches. The Unknown result and its reason (with the full
count) are unchanged; an error in a policy past the cap now reports the
cap reason.

Addresses Copilot review on #1165 (comment 4797461119).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Matthias Bertschy <matthias.bertschy@gmail.com>
… every marked cgroup

- A static pod joined under its kubelet UID was never found by the
  deselect refresh (the API lists its mirror pod's UID), so deleting its
  last policy left its Strict binding enforcing. The refresh now looks up
  the mirror pod by the static pod's NRI namespace and name, checks that
  its kubernetes.io/config.mirror annotation names the static pod's UID
  and that no other pod on the node claims that UID, and only then
  classifies the static pod with its own identity; any other or a second
  claim maps nothing (no unmark). Mirror pods are read at most once per
  input epoch, only when an NRI candidate is missing from the pod list.
- The cgroup index exports every cgroup a gate entry marked, with its
  path, so a refused newer mark does not drop the older held cgroup's
  attribution; prune keeps an entry while any marked cgroup is live and
  retires proven-gone marked cgroups.

Addresses Copilot review on #1165 (comments 4797461161, 4797461211, 4796605626).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Matthias Bertschy <matthias.bertschy@gmail.com>
…podgate

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@matthyx
matthyx requested a balanced review from Copilot December 4, 2026 08:58
@github-actions

github-actions Bot commented Dec 4, 2026

Copy link
Copy Markdown

Performance Benchmark Results

Node-Agent Resource Usage
Metric BEFORE AFTER Delta
Avg CPU (cores) 0.036 0.000 -100.0%
Peak CPU (cores) 0.040 0.000 -100.0%
Peak CPU p95 (cores) 0.040 0.000 -100.0%
Avg Memory (MiB) 211.199 0.000 -100.0%
Peak Memory (MiB) 213.922 0.000 -100.0%
Dedup Effectiveness

No data available.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

func appendOwner(owners []uint64, id uint64) []uint64 {
owners = slices.DeleteFunc(owners, func(o uint64) bool { return o == id })
owners = append(owners, id)
return owners[max(0, len(owners)-maxSentCgroups):]
if err == nil {
delete(g.sent, uid) // its binding is gone: nothing left to unmark
if p != nil && !p.released {
p.marked, p.markedPaths = nil, nil
Comment on lines +1443 to +1444
p.ref.Annotations = map[string]string{configSourceAnnotation: "file"}
p.facts.Annotations = map[string]string{corev1.MirrorPodAnnotationKey: string(uid)}
podCgroups[id] = r
}
}
s.podCgroups = podCgroups

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comment on lines +1505 to +1509
// mirrorPods are the pods of this node that carry a mirror annotation, read
// at most once per input epoch (a mirror annotation never changes; a new
// pod bumps the epoch).
func (s *Service) mirrorPods(ctx context.Context, epoch uint64) []*corev1.Pod {
if s.mirrorCache.ok && s.mirrorCache.epoch == epoch {
@github-actions

github-actions Bot commented Dec 4, 2026

Copy link
Copy Markdown

Performance Benchmark Results

Node-Agent Resource Usage
Metric BEFORE AFTER Delta
Avg CPU (cores) 0.037 0.036 -2.6%
Peak CPU (cores) 0.041 0.039 -4.1%
Peak CPU p95 (cores) 0.039 0.039 -1.6%
Avg Memory (MiB) 215.669 193.356 -10.3%
Peak Memory (MiB) 218.504 198.469 -9.2%
Dedup Effectiveness

No data available.

… into omx/nri-s3-podgate

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comment on lines +359 to +363
if cur, ok := c.paths[id]; ok != hadPath || cur != checked {
return false
}
delete(c.paths, id)
return true
Comment on lines +1362 to +1365
got, epoch := sandboxpolicy.CaptureInputs(s.inputEpoch.Load, func() podList {
scheduled, qos, started, err := s.scheduledPods(ctx)
return podList{scheduled, qos, started, err}
})
Comment on lines +1344 to +1345
gate := newPodGate(ctx, backend, checker.gone)
gate.notePath = checker.notePath

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@github-actions

github-actions Bot commented Dec 4, 2026

Copy link
Copy Markdown

Performance Benchmark Results

Node-Agent Resource Usage
Metric BEFORE AFTER Delta
Avg CPU (cores) 0.038 0.037 -2.5%
Peak CPU (cores) 0.043 0.041 -5.0%
Peak CPU p95 (cores) 0.042 0.041 -2.4%
Avg Memory (MiB) 208.451 200.781 -3.7%
Peak Memory (MiB) 210.316 203.645 -3.2%
Dedup Effectiveness

No data available.

matthyx and others added 2 commits December 4, 2026 13:12
drain closed a job's done channel while w.current still pointed at it,
so a same-key request (unmark, mark, hold retry) enqueued in that window
joined the finished job and got its old result without its own backend
call running; for example a retried unmark could report success after a
refresh had bound the pod again, leaving a Strict binding in place.
drain now clears w.current under podMu before it closes done, so only
requests issued while a job is queued or running can join it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Matthias Bertschy <matthias.bertschy@gmail.com>
…-podgate

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

// no pod binding is wanted any more (Copilot #1165 4796605589).
noPodSections := c.Class == sandboxpolicy.PodSelected && len(c.Sections) == 0 && c.Shape == 0
if (c.Class == sandboxpolicy.PodUnselected && !c.Exempt) || noPodSections {
gate.unmarkDeselected(uid, c.Seq)
@github-actions

github-actions Bot commented Dec 4, 2026

Copy link
Copy Markdown

Performance Benchmark Results

Node-Agent Resource Usage
Metric BEFORE AFTER Delta
Avg CPU (cores) 0.027 0.027 -2.4%
Peak CPU (cores) 0.031 0.031 +1.2%
Peak CPU p95 (cores) 0.030 0.029 -3.4%
Avg Memory (MiB) 215.927 196.386 -9.1%
Peak Memory (MiB) 224.969 199.328 -11.4%
Dedup Effectiveness

No data available.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ai-assisted Created through Armosec AI tooling (armosec-shared-rules plugin) ai-reviewed-local

Projects

Status: WIP

Development

Successfully merging this pull request may close these issues.

2 participants