Skip to content

hypervisor/kubevirt: base halted state on the whole workload - #6529

Closed
andrewd-zededa wants to merge 1 commit into
lf-edge:masterfrom
andrewd-zededa:eve-k-halted-state
Closed

andrewd-zededa wants to merge 1 commit into
lf-edge:masterfrom
andrewd-zededa:eve-k-halted-state

Conversation

@andrewd-zededa

@andrewd-zededa andrewd-zededa commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Description

Info() reported HALTED as soon as the VMIRS Get returned NotFound. The three objects form an ownership chain: the VMIRS owns the VMI, and the VMI owns the virt-launcher pod. EVE deletes only the VMIRS, so it is the first to go, and Kubernetes then collects its dependents in the background. The pod holds the RWO disk until it goes away.

A domain was therefore reported as halted while its workload still ran. A peer that stands in for a downed node reads that state to decide if an app is really down, and a controller reads it to decide the app can move. Both can act too early.

Info() now takes the state from the existence of the VMIRS, the VMI and the pod, each found by its App-Domain-Name label. An absent VMIRS with a surviving dependent gives HALTING and keeps a non-zero DomainId, because a zero DomainId is the confirmed-absent token. HALTED with a zero DomainId needs all three to be absent. The dependent lookup runs only on the absent-VMIRS branch, so a steady-state poll makes no more API calls than it did before.

A config apply must not wait for this. A kubevirt deactivate now publishes HALTING, deletes the VMIRS, and returns. verifyStatus settles the state and releases the resources when Info reports all three objects absent. Kubernetes owns how long that takes, and on a node that is off it has no end, so no budget on the config path is the correct one.

The paths that must finish before they return keep their behavior, because impatient is already true for them: handleDelete unpublishes DomainStatus as soon as it returns, and a purge or a restart advances its counter only after the teardown clears status.Activated.

Two other reads of HALTING had to be separated from this one. waitForDomainGone took it for a guest that powered off while its hypervisor process stayed parked and held resources, a qemu -no-shutdown condition, so it stopped waiting and let the caller reap the domain. verifyStatus took it for a teardown to finish now. Under kubevirt HALTING is the reverse of both: nothing is parked, and Kubernetes is still at work. Both short circuits now apply to the other hypervisors only.

Start() already waits for a stale generation to disappear, object and pods, before it creates the next one, because generations share the disk and the veth names. That is what keeps an asynchronous deactivate safe beside a create.

PR dependencies

None

How to test and validate this PR

pillar go-test:

make -C pkg/pillar TESTPKGS='./hypervisor/... ./cmd/domainmgr/...' test

Covers the VMIRS/VMI/pod state combinations, the async-deactivate hand-off, and the resulting HALTED/HALTING transitions without a live cluster.

evetest

Coming in PR #6505

Changelog notes

EVE could report an application halted before Kubernetes had actually torn it down (its VM instance or pod could still be running). App halted/running status now reflects the real state of the workload, and deactivating an app no longer blocks device configuration while Kubernetes finishes the teardown in the background.

PR Backports

  • 17.0-stable: To be backported.
  • 16.0-stable: No, as the feature is not available there.
  • 14.5-stable: No, as the feature is not available there.
  • 13.4-stable: No, as the feature is not available there.

Checklist

  • I've provided a proper description
  • I've added the proper documentation
  • I've tested my PR on amd64 device
  • I've tested my PR on arm64 device
  • I've written the test verification instructions
  • I've set the proper labels to this PR

And the last but not least:

  • I've checked the boxes above, or I've provided a good reason why I didn't
    check them.

Please, check the boxes above after submitting the PR in interactive mode.

Info() reported HALTED as soon as the VMIRS Get returned NotFound. The
three objects form an ownership chain: the VMIRS owns the VMI, and the VMI
owns the virt-launcher pod. EVE deletes only the VMIRS, so it is the first
to go, and Kubernetes then collects its dependents in the background. The
pod holds the RWO disk until it goes away.

A domain was therefore reported as halted while its workload still ran. A
peer that stands in for a downed node reads that state to decide if an app
is really down, and a controller reads it to decide the app can move. Both
can act too early.

Info() now takes the state from the existence of the VMIRS, the VMI and
the pod, each found by its App-Domain-Name label. An absent VMIRS with a
surviving dependent gives HALTING and keeps a non-zero DomainId, because a
zero DomainId is the confirmed-absent token. HALTED with a zero DomainId
needs all three to be absent. The dependent lookup runs only on the
absent-VMIRS branch, so a steady-state poll makes no more API calls than
it did before.

A config apply must not wait for this. A kubevirt deactivate now publishes
HALTING, deletes the VMIRS, and returns. verifyStatus settles the state
and releases the resources when Info reports all three objects absent.
Kubernetes owns how long that takes, and on a node that is off it has no
end, so no budget on the config path is the correct one.

The paths that must finish before they return keep their behavior, because
impatient is already true for them: handleDelete unpublishes DomainStatus
as soon as it returns, and a purge or a restart advances its counter only
after the teardown clears status.Activated.

Two other reads of HALTING had to be separated from this one.
waitForDomainGone took it for a guest that powered off while its
hypervisor process stayed parked and held resources, a qemu -no-shutdown
condition, so it stopped waiting and let the caller reap the domain.
verifyStatus took it for a teardown to finish now. Under kubevirt HALTING
is the reverse of both: nothing is parked, and Kubernetes is still at
work. Both short circuits now apply to the other hypervisors only.

Start() already waits for a stale generation to disappear, object and
pods, before it creates the next one, because generations share the disk
and the veth names. That is what keeps an asynchronous deactivate safe
beside a create.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Signed-off-by: Andrew Durbin <andrewd@zededa.com>
@andrewd-zededa andrewd-zededa added stable Should be backported to stable release(s) next-17.0.x-rc PR must be present in the next 17.0.x-lts release labels Sep 11, 2026
@codecov

codecov Bot commented Sep 11, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 62.66667% with 28 lines in your changes missing coverage. Please review.
✅ Project coverage is 26.31%. Comparing base (0c954e8) to head (ff6f34d).
⚠️ Report is 60 commits behind head on master.

Files with missing lines Patch % Lines
pkg/pillar/cmd/domainmgr/domainmgr.go 14.28% 17 Missing and 1 partial ⚠️
pkg/pillar/hypervisor/kubevirt.go 81.48% 5 Missing and 5 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #6529      +/-   ##
==========================================
+ Coverage   25.96%   26.31%   +0.35%     
==========================================
  Files         514      524      +10     
  Lines       94543    96324    +1781     
==========================================
+ Hits        24547    25349     +802     
- Misses      68103    68880     +777     
- Partials     1893     2095     +202     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@andrewd-zededa
andrewd-zededa marked this pull request as ready for review September 11, 2026 17:07
@eriknordmark

Copy link
Copy Markdown
Contributor

@claude

@github-actions

github-actions Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @eriknordmark's task in 4m 27s —— View job


Code review

I reviewed the state-derivation logic in kubevirt.go and the async-deactivate hand-off in domainmgr.go. The overall approach — deriving HALTED only when VMIRS + VMI + pod are all absent, keeping a non-zero DomainId otherwise, and handing the teardown to Kubernetes off the config path — is sound and well tested. Two concerns, posted inline:

  • Read the diff
  • Analyze kubevirt.go Info()/confirmedAbsent state logic
  • Analyze domainmgr.go async-deactivate hand-off
  • Review tests
  • Post review

Findings

  1. verifyStatus can still zero DomainId without confirmed absence during an async kubevirt deactivate (inline, domainmgr.go:1250). When Info returns (DomainId, UNKNOWN, err) because the VMIRS is gone but the VMI/pod dependent check transiently fails, confirmedAbsent deliberately preserves the id — but verifyStatus falls through the err != nil branch to the unconditional status.DomainId = 0 and publishes the confirmed-absent token anyway. This re-introduces the exact premature "workload gone" signal the PR fixes, and it's sticky for the rest of the reap. Suggest guarding the zeroing when ctx.hvTypeKube && !configActivate && err != nil.

  2. Failed DomainShutdown in the async path isn't retried (inline, domainmgr.go:2307). A transient VMIRS-delete failure is only logged; the function returns and verifyStatus takes its rescheduling/running arm instead of re-driving the teardown, so a deactivated app can silently keep running until the next config change.

Everything else — dependentsPresent selectors (verified against the labels CreateReplicaVMIConfig/CreateReplicaPodConfig actually stamp), the dependent lookup running only on the absent-VMIRS branch, and the kubevirtStillReaping / waitForDomainGone separation from the qemu -no-shutdown meaning — looks correct.
• branch eve-k-halted-state

status.DomainId = 0
doCleanup(ctx, status)
}
status.DomainId = 0

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This unconditional status.DomainId = 0 defeats the very invariant this PR builds. During an async kubevirt deactivate, Info can return (DomainId, UNKNOWN, err) when the VMIRS is gone but the VMI/pod dependent check itself fails (transient API error) — confirmedAbsent deliberately preserves the id in that case. But here in verifyStatus, err != nil enters the outer if, configActivate is false so the recovery branch is skipped, and kubevirtDeactivateComplete is false (state is UNKNOWN, not HALTED), so control falls straight through to this line and publishes a zero DomainId — the confirmed-absent token — without absence ever being confirmed.

That exposes exactly the premature "workload gone" signal to peers/controller that the PR is meant to prevent, and it's sticky: once status.DomainId is 0, confirmedAbsent returns 0 for the rest of the reap (it echoes t.status.DomainId), so the domain reports gone for the whole remaining teardown window.

Consider guarding the zeroing for kubevirt when absence is not confirmed, e.g. skip it when ctx.hvTypeKube && !configActivate && err != nil (hold the id and let a later tick settle via kubevirtDeactivateComplete).

Fix this →

Comment on lines +2307 to +2310
if err := DomainShutdown(ctx, *status, false); err != nil {
log.Errorf("doInactivate(%s) Shutdown failed: %s", status.Key(), err)
}
return

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

In the async path a failed DomainShutdown (VMIRS delete) is only logged, then the function returns with State=HALTING and Activated=true while the VMIRS still exists. verifyStatus will then observe SCHEDULING/RUNNING (not absent) and take its rescheduling/running arm rather than retrying the delete, and nothing re-drives the teardown until the next config change — so a transient delete failure can silently leave a deactivated app running. Worth reconsidering whether the async path should retry or leave Activated/state such that the teardown is re-attempted.

@eriknordmark eriknordmark left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Andrew, some comments from claude to look at, where at least the first one looks like a real concern.

@eriknordmark

Copy link
Copy Markdown
Contributor

Measured on hardware: this eliminates the zero-byte data loss in #6495

I have been tracking the failure #6495 describes — a tight write-then-restart of a
VM app instance reads the file back as 0 bytes — on a single-node EVE-k device
(Supermicro SYS-E300-8D, Ubuntu 18.04 guest). This PR appears to fix it.

Baseline, image without this change, measured over six days of soaking:

tight cycles losses
20 6 (30 %)

With this PR cherry-picked onto the same base, same device, same guest OS, same
controller-driven restart path:

tight cycles losses
30 0

P(0 losses in 30) at the baseline rate is 2.3e-05.

A "tight cycle" is write → restart-request with a sub-second-to-few-second gap; the
distribution here was 0 s x2, 1 s x18, 2 s x5, 3 s x4, 5 s x1, i.e. including the
hardest case where the restart is requested in the same second as the write. All 30
read back 128889 bytes with a matching sha.

Method, so the result can be discounted appropriately:

  • Driven by a loop that writes the file in the guest, calls
    zcli edge-app-instance restart, waits for the controller to report the app
    Online again, then reads the file back.
  • The detector was positive-controlled: truncating the file in the guest makes
    the loss branch fire (stat succeeds, reports 0), so it is not a detector that
    has only ever seen the healthy case.
  • A cycle where the guest was unreachable is recorded as skipped and not counted
    either way. There were zero skips in this run.

Caveat: the image under test carries this PR and an unrelated local change raising
kube-init's k3s start deadlines. That change only affects cluster startup
convergence and cannot plausibly influence whether a running app's disk flush
completes before the domain is declared halted, but it is two changes rather than
one.

The mechanism matches: dependentsPresent() keeps the domain from being reported
halted while a virt-launcher pod still holds the RWO disk, which is exactly the
window in which the guest's writeback was being lost.

@eriknordmark eriknordmark left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Note that this passes my previously failing tests - see details. Kicking off regression tests.

But still need to look at claude's review comments.

@eriknordmark

Copy link
Copy Markdown
Contributor

Correction to my 2026-09-19 measurement comment

My earlier comment reported 30 driven tight cycles with 0 losses as evidence this PR eliminates the zero-byte read in #6495. That result does not test this PR, and I am withdrawing it.

The driver defaults to SYNC=1, which appends ; sync to the guest write. ztest does not sync, and neither does the workload #6495 describes. The run therefore made the data durable before the restart was even requested — it is a strong test of sync and no test of this change.

The arithmetic in that comment is sound but attaches to the wrong cause. The cycles were genuinely in the loss regime: all 29 derivable ages land at 150–174 s, inside the 123–174 s band where the baseline losses occur, so the zero is not explained by cycles being too slow to reach the window.

What replaces it

A SYNC=0 re-run is set up on the same device and image. No cycle has yet met the classifier, which was fixed in writing before any data was collected under it: a cycle counts only if a domain destroy is observed for its VMI within D = (dirty_expire_centisecs + dirty_writeback_centisecs)/100, read from the guest at engagement, and the stop was a forced kill rather than a clean shutdown. A clean shutdown syncs, so an in-window clean stop tests nothing.

Kill-vs-clean is decided host-side, from virt-launcher's repeated Signaled graceful shutdown for <vmi> (manager.go:2225). The retry count is bimodal across 187 stops: at most 5 retries and the guest reaches power-down (160/163), 7 or more and it never does (0/24), with nothing in between. Forced kills are 24 of 187 stops (12.8 %), so tested cycles accumulate slowly even with a restart loop driving them.

One methodological note for anyone reproducing this: the guest's own journal cannot be used to tell a kill from a clean stop. journald's SyncIntervalSec default is 5 minutes and it fsyncs immediately only for CRIT, ALERT or EMERG, so a guest killed at the grace boundary loses the tail of its journal — any shutdown record included — to the same page cache this bug is about, while a clean shutdown flushes its own tail on the way out. Comparing shutdown records between clean and killed boots is a selection effect rather than a measurement.

At least one loss among tested cycles would confirm the mechanism. Zero would not refute it: there is no baseline loss rate under this classifier to test against, and establishing one would mean running the baseline image the same way.

Two figures above are not re-derived in this pass and should not be mixed: the in-band loss rate I quote is 6 losses in 18 in-band reads of ztest's own textFile.txt (of 124 total), which is a different denominator from the 20-cycle baseline in the original comment.

@andrewd-zededa

Copy link
Copy Markdown
Contributor Author

This merged via #6505. I'll rebase with just the fixes requested in review and update comments/description

@eriknordmark

Copy link
Copy Markdown
Contributor

This landed in master through #6505 — this change was its second commit, and #6505 merged on 2026-09-23 as cbb17f4c7.

Master carries it one refactor further: the pod lookup is anyPodMatches (kubevirt.go:946), dependentsPresent is at :966, and confirmedAbsent (:1647) is the single place Info may report a workload gone, reached from "existence check" (:1689), "existence check race" (:1740) and "scheduling lookup" (:1772). domainmgr.go is byte-identical between this PR and master (blob 708890f20b58820bde957747db5536abf482387c).

The only thing here that master lacks is TestDependentsPresent. Master's TestInfoStateFromWorkloadObjects asserts the same four vmi/pod combinations — all three absent, pod outlives the vmirs, vmi outlives the vmirs, both outlive — through Info() rather than directly on dependentsPresent.

So rebasing this would re-apply the halted-state change and revert the anyPodMatches refactor. Unless you want the direct dependentsPresent unit test back on top of master, I think this can be closed.

@rene

rene commented Sep 25, 2026

Copy link
Copy Markdown
Contributor

@andrewd-zededa so per @eriknordmark's comments, can we close it?

@andrewd-zededa

Copy link
Copy Markdown
Contributor Author

yes I'll close it.

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

Labels

next-17.0.x-rc PR must be present in the next 17.0.x-lts release stable Should be backported to stable release(s)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants