Repository navigation
Run systrap fast path state machine inline - #16532
konstantin-s-bogom wants to merge 1 commit into
Conversation
|
On 8-vCPU GCE VM, Overloaded host: 40 sandboxes (host CPU 100%), 8 rounds × 30 s
|
EtiennePerot
left a comment
There was a problem hiding this comment.
A Claude finding I think is worth addressing:
maybeUpdate runs after ctx.startWaitingTS = now but before the ring buffer store and before waitOnState kicks a stub. That has two effects:
- The stub can't see the context until the evaluation finishes. So one context switch per period pays the full cost, where the old monitor goroutine ran in parallel.
- The evaluation time is counted in that context's stub-bound latency sample. The state machine then reads that sample in the next period. The median absorbs one outlier when there are many samples, but not when there are only 5–10.
Microbenchmark on an i7-12800H, copying the bucket operations of sentryOffStubOff and sentryOnStubOn, minus the time to fill the buckets:
┌────────┬──────────────┬─────────────────────────────┐
│ │ Idle buckets │ 4 cores writing the buckets │
├────────┼──────────────┼─────────────────────────────┤
│ OffOff │ ~1.3 µs │ ~6–12 µs │
├────────┼──────────────┼─────────────────────────────┤
│ OnOn │ ~0.9 µs │ ~4.5 µs │
└────────┴──────────────┴─────────────────────────────┘The second column is pessimistic, because real writers record far less often. Even so, a few µs on one switch every 400 µs is measurable on syscall-heavy loads.
Suggested fix: keep the cheap check and the idle reset before setFastPathDisabled, so the first context after an idle gap sees the flags off. Run the curState evaluation after the ring buffer store, where it overlaps with the stub running the app. Alternatively, take now again after
maybeUpdate for startWaitingTS.
Evaluate the fast path state machine at most once per recording period from the context submission path, instead of on a goroutine that wakes every 400us. contextQueue.add claims the update with one atomic load in the common case and a CAS once per period. The claiming context runs the evaluation in waitOnState after the stub is kicked, overlapping with the stub. The timer wakeups cost host CPU in every active sandbox, and on a loaded host the timer oversleeps, so fast path decisions lag the workload.
fd34daf to
1dd1daf
Compare
|
Fixed the inline execution to make metric evaluation happen in parallel. |
|
Did you benchmark this on macrobenchmarks? |
|
I ran hackbench which didn't show much movement under light load. I'll run some more under load, but it's pretty clear that this is a correctness fix vs. base for dense workloads because the signal to switch fastpath just comes too late. |
kerumeto
left a comment
There was a problem hiding this comment.
Do the tests cover this code?
| if !neverEnableFastPath { | ||
| ctx.fastPathUpdate = fastpath.claimUpdate(now) | ||
| } |
There was a problem hiding this comment.
Should this be moved after the check for context queue is full?
| update := ctx.fastPathUpdate | ||
| ctx.fastPathUpdate = fastPathNoUpdate | ||
| if s.dead.Load() { | ||
| // Run the update even subproc is dead -- fastpath update is sentry-global |
kerumeto
left a comment
There was a problem hiding this comment.
[🤖🐸🤖] 1 issue found:
- [minor · bug]
fastPathIdleResetdiscards metrics from the preceding active period without evaluatingcurState(pkg/sentry/platform/systrap/metrics.go:345, inline)
Automated review agent. Please address valid findings before human review, or close them with a reason.
| // claimUpdate cleared the flags without updateMu, so an | ||
| // evaluation that ran at the same time can have set one again. | ||
| s.clearFastPathFlags() | ||
| // Return to sentryOffStubOff, because the "On" states never set a | ||
| // flag again. Without this reset, an "On" state that the metrics | ||
| // cannot disable has no way out, because there are no metrics | ||
| // while idle. | ||
| s.curState = sentryOffStubOff | ||
| // The latencies recorded since the last update can come from a | ||
| // period with the fast path on. Drop them, so that they are not | ||
| // merged into the baselines. | ||
| latencies.stubBound.reset() | ||
| latencies.sentryBound.reset() | ||
| } | ||
| // Reset FP trackers. |
There was a problem hiding this comment.
[🤖🐸🤖] [minor · bug] fastPathIdleReset discards metrics from the preceding active period without evaluating curState
When a context submission claims an update after elapsed >= 2*recordingPeriod (fastPathIdleReset), runUpdate skips evaluating s.curState(s) for the preceding active recording period and unconditionally resets latencies.stubBound and latencies.sentryBound.
Because updates are driven by context submissions, metrics recorded during an active window [t0, t0 + recordingPeriod) wait to be evaluated by the first submission at now >= t0 + recordingPeriod. If the next submission arrives at now >= t0 + 2*recordingPeriod, fastPathIdleReset drops the preceding active period's metrics. Consequently, bursty workloads separated by pauses >= 2*recordingPeriod - burst never merge baseline latencies or decrement backoff counters, and an enabled fast path that causes high latency on an overloaded host followed by a >= 800µs scheduling delay is reset without calling disableStubFP()/disableSentryFP() or increasing backoff.
Suggested fix: In fastPathState.runUpdate, call s.curState(s) during fastPathIdleReset before clearing the fast path flags and resetting s.curState = sentryOffStubOff (every state function in s.curState(s) already resets latencies.stubBound and latencies.sentryBound):
switch u {
case fastPathEvaluate:
s.curState(s)
case fastPathIdleReset:
s.curState(s)
s.clearFastPathFlags()
s.curState = sentryOffStubOff
}Details (evidence, reproduction and test code)
Evidence: When an update is claimed at t0 (lastUpdateTS = t0), contexts submitted during (t0, t0 + recordingPeriod) record latencies into latencies.stubBound and latencies.sentryBound while claimUpdate returns fastPathNoUpdate (now - t0 < recordingPeriod). If no context is submitted during [t0 + recordingPeriod, t0 + 2*recordingPeriod) and the next submission arrives at now >= t0 + 2*recordingPeriod, two periods have elapsed since t0: the active period [t0, t0 + recordingPeriod) and the idle period [t0 + recordingPeriod, now).
In pkg/sentry/platform/systrap/metrics.go:341-358:
switch u {
case fastPathEvaluate:
s.curState(s)
case fastPathIdleReset:
s.clearFastPathFlags()
s.curState = sentryOffStubOff
latencies.stubBound.reset()
latencies.sentryBound.reset()
}Previously, fastPathGoroutine woke up every recordingPeriod (400µs): at t0 + recordingPeriod it ran s.curState(s) on the samples from [t0, t0 + recordingPeriod) (merging baselines in sentryOffStubOff, decrementing stubFPBackoff/sentryFPBackoff, or calling disableStubFP()/disableSentryFP() and increasing backoff up to maxBackoff = 1024 if an enabled fast path degraded latency), and only saw empty distributions at t0 + 2*recordingPeriod. With inline updates, skipping s.curState(s) on fastPathIdleReset loses the evaluation for [t0, t0 + recordingPeriod). Calling s.curState(s) before resetting in fastPathIdleReset evaluates any samples collected in [t0, t0 + recordingPeriod) and is a no-op if fewer than minRequiredSamples were recorded.
Reproduced with a test (pkg/sentry/platform/systrap/shared_context_test.go): bazel test //pkg/sentry/platform/systrap:systrap_test --test_filter=TestFastPathIdleResetPreservesPrecedingPeriodMetrics --nocache_test_results && bazel test //pkg/sentry/platform/systrap:systrap_test --test_filter=TestFastPathIdleResetPreservesPrecedingPeriodMetrics --nocache_test_results → Fails at PR head (stubBaseline.samples = 0, want >= 3; stubFPBackoff after degraded period + scheduler delay = 0, want > 0 (degraded fast path was not penalized)) and passes at merge-base.
Test code:
diff --git a/pkg/sentry/platform/systrap/shared_context_test.go b/pkg/sentry/platform/systrap/shared_context_test.go
index 6a2ca2d11..d20d527ed 100644
--- a/pkg/sentry/platform/systrap/shared_context_test.go
+++ b/pkg/sentry/platform/systrap/shared_context_test.go
@@ -27,6 +27,7 @@ import (
"gvisor.dev/gvisor/pkg/hostsyscall"
"gvisor.dev/gvisor/pkg/pool"
"gvisor.dev/gvisor/pkg/sentry/arch"
+ "gvisor.dev/gvisor/pkg/sentry/platform"
"gvisor.dev/gvisor/pkg/sentry/platform/systrap/sysmsg"
)
@@ -311,3 +312,251 @@ func TestStuckSubprocessHelper(t *testing.T) {
}
select {}
}
+
+func simulateSwitch(t *testing.T, sc *sharedContext, lat cpuTicks) {
+ t.Helper()
+ s := sc.subprocess
+ if err := s.contextQueue.add(sc); err != nil {
+ t.Fatalf("contextQueue.add failed: %v", err)
+ }
+ atomic.AddUint32(&s.contextQueue.start, 1)
+ atomic.AddUint32(&s.contextQueue.numActiveContexts, ^uint32(0))
+ atomic.StoreUint64(&sc.shared.AckedTime, uint64(sc.startWaitingTS)+uint64(lat))
+ now := uint64(cputicks())
+ if now > uint64(lat) {
+ atomic.StoreUint64(&sc.shared.StateChangedTime, now-uint64(lat))
+ } else {
+ atomic.StoreUint64(&sc.shared.StateChangedTime, 1)
+ }
+ sc.setState(sysmsg.ContextStateSyscall)
+ if err := s.waitOnState(sc); err != nil {
+ t.Fatalf("waitOnState failed: %v", err)
+ }
+}
+
+func setupFastPathTest(t *testing.T) *sharedContext {
+ t.Helper()
+ prevNever := neverEnableFastPath
+ neverEnableFastPath = false
+ if sys, err := New(platform.Options{
+ DisableSyscallPatching: true,
+ DisableFastPath: false,
+ }); err == nil {
+ sys.memoryFile.Destroy()
+ }
+ neverEnableFastPath = false
+ if maxSysmsgThreads < 4 {
+ maxSysmsgThreads = 4
+ }
+ fastPathContextLimit = uint32(maxSysmsgThreads * 2)
+ initSleepTimeouts()
+ t.Cleanup(func() {
+ neverEnableFastPath = prevNever
+ })
+
+ queue := &contextQueue{}
+ queue.init()
+ atomic.StoreUint32(&queue.numActiveThreads, 1000)
+ s := &subprocess{
+ contextQueue: queue,
+ }
+ shared := &sysmsg.ThreadContext{}
+ shared.Init(1)
+ sc := &sharedContext{
+ subprocess: s,
+ shared: shared,
+ }
+
+ // Wait for any previous recording period to become idle, then perform one
+ // warmup switch to start a fresh recording period before configuring
+ // fastpath state.
+ time.Sleep(2 * time.Millisecond)
+ simulateSwitch(t, sc, 2*bucketIncrements)
+
+ latencies.stubBound.reset()
+ latencies.sentryBound.reset()
+ fastpath.stubBoundBaselineLatency.reset()
+ fastpath.sentryBoundBaselineLatency.reset()
+ fastpath.stubFPBackoff = fastPathBackoffMin
+ fastpath.sentryFPBackoff = fastPathBackoffMin
+ fastpath.stubFPRecentFailures = 0
+ fastpath.sentryFPRecentFailures = 0
+ fastpath.consecutiveStubFPFailures = 0
+ fastpath.consecutiveSentryFPFailures = 0
+ fastpath.curState = sentryOffStubOff
+ fastpath.stubFastPathEnabled.Store(false)
+ fastpath.sentryFastPathEnabled.Store(false)
+ fastpath.usedStubFastPath.Store(false)
+ fastpath.usedSentryFastPath.Store(false)
+ fastpath.nrMaxAwakeStubThreads.Store(1)
+
+ return sc
+}
+
+func TestFastPathIdleResetPreservesPrecedingPeriodMetrics(t *testing.T) {
+ sc := setupFastPathTest(t)
+
+ // Run two active bursts (< recordingPeriod each) separated by idle gaps
+ // (> 2*recordingPeriod). Each burst records >= minNecessaryRecordings
+ // samples, so the active period before each idle gap should be evaluated:
+ // baselines should be populated and backoffs decremented to 0.
+ for burst := 0; burst < 2; burst++ {
+ for i := 0; i < minNecessaryRecordings+5; i++ {
+ simulateSwitch(t, sc, 2*bucketIncrements)
+ }
+ time.Sleep(1200 * time.Microsecond)
+ simulateSwitch(t, sc, 2*bucketIncrements)
+ }
+
+ if got := fastpath.stubBoundBaselineLatency.getMedian(); got == 0 {
+ t.Errorf("stubBoundBaselineLatency.getMedian() = 0 after active bursts followed by idle resets, want > 0")
+ }
+ if got := fastpath.sentryBoundBaselineLatency.getMedian(); got == 0 {
+ t.Errorf("sentryBoundBaselineLatency.getMedian() = 0 after active bursts followed by idle resets, want > 0")
+ }
+ if got := fastpath.sentryFPBackoff; got != 0 {
+ t.Errorf("sentryFPBackoff = %d after 2 active bursts, want 0", got)
... (144 more lines in the full patch)Automated review agent. Please address valid findings before human review, or close them with a reason.
Evaluate the fast path state machine from contextQueue.add at most once per recording period, instead of on a goroutine that wakes every 400us. contextQueue.add claims the update with one atomic load in the common case and a CAS once per period. The claiming context runs the evaluation in waitOnState after the stub is kicked, overlapping with the stub.
The timer wakeups cost host CPU in every active sandbox, and on a loaded host the timer oversleeps, so fast path decisions lag the workload. The decision lag is most relevant on overloaded hosts.
Fixes #16155.