Skip to content

Latest commit

 

History

History
78 lines (65 loc) · 16.8 KB

FAILURE-MODES.md

File metadata and controls

78 lines (65 loc) · 16.8 KB

Keep Mac Awake failure modes

This is the specification of what version 1.0 does when something fails: what detects the failure, what the expected outcome is, which timing constants apply and which automated tests cover it. Mechanisms are described in ARCHITECTURE.md. Read the Evidence section before relying on any row.

Timing constants

From ControlProtocol.swift (ControlConstants) unless noted.

Constant Value Meaning
leaseSeconds 12 s A session ends this long after the last Start or Renew
peerTimeoutSeconds 8 s A heartbeat older than this is not fresh; also the pause between recoveries
sessionEndGraceSeconds 4 s The watchdog lets a fresh controller end a timed session on its own after the deadline
supervisionSeconds 1 s Tick while a session, restoration or recovery exists
idleSupervisionSeconds 60 s Tick when idle
supervisionHoldSeconds 10 s Fast rate kept after the last state that needed it
watchdogWakeTimeoutSeconds 0.75 s Start waits this long for the watchdog's answer
idleControllerStallSeconds 180 s Unchanged idle controller heartbeat, in awake time, before a restart
Environmental release grace 2 s Literal in WatchdogAssessment (PeerSupervision.swift)
Kernel confirmation 1.5 s waitForKernelSleepDisabled (NativeSleepBackend.swift)
Lock attempts 5 x 20 ms Controller's lock retries (ServiceRuntime.swift, SecureState.swift)
launchctl bound 2 s Fencing command timeout (SecureState.swift)
ThrottleInterval, ExitTimeOut 3 s, 5 s LaunchDaemon plists (Helper, Watchdog)
Client values (closed source) renew every 2 s, request timeout 3 s, confirmation valid 6 s, interruption rechecks after 1, 2, 4, 8 s Coordinator; listed so the core values above can be read in context

Specification

Test names are Class.method; the files are listed under Test files. "Restored" means SleepDisabled is back to its original state and the journal is removed.

Failure Detected by Expected outcome Timing Automated tests
Menu bar app killed Nothing in the core: the app is a client of the coordinator, which keeps its own connection Session continues; a relaunched app shows it none None in this repository (client tests are closed source)
Coordinator killed Controller: the owning XPC connection is invalidated Session ends at once (disconnected), restored. Nothing restarts a session Next controller turn SessionPolicyTests.testUserSwitchWatchdogRestartAndDisconnectEndIntent
Coordinator hung Controller: no Renew; watchdog: lease in the heartbeat expired Session ends (leaseExpired), restored; watchdog fences if the controller does not 12 s after the last Renew, then 1 s tick SessionPolicyTests.testLeaseExpiryCannotBeRevivedByLateRenewal, PeerSupervisionTests.testWatchdogIndependentlyEnforcesACConsoleLeaseAndDeadline
Controller killed launchd restarts it; it is not ready until it has restored the journal. Watchdog: heartbeat stale or not ready Session ends, restored by the new controller or by the watchdog after fencing. Coordinator sees the connection drop Restart after up to 3 s; stale after 8 s PeerSupervisionTests.testHeartbeatRejectsFutureStaleNotReadyAndNonFiniteTimes, SleepTransactionTests.testRecoveryAfterMetadataDeletionIsIdempotent, SleepTransactionTests.testRestoreRetriesAfterKernelWriteFailure
Controller hung (SIGSTOP) Watchdog: heartbeat stale Watchdog kills the stopped controller before taking the lock, then restores. launchd restarts the controller Stale after 8 s, then the next 1 s tick PeerSupervisionTests.testRecoveryNeverWaitsOnLockBeforeFencingStoppedWriter, PeerSupervisionTests.testFailedFenceDoesNotAttemptRecovery, PeerSupervisionTests.testBusyLockRetriesWithoutUnfencingOldWriter, PeerSupervisionTests.testACLossAllowsBoundedReleaseGraceButCannotKeepStoppedWriter
Idle controller hung Watchdog: idle heartbeat unchanged in awake time Controller restarted, so later Starts work 180 s of awake time PeerSupervisionTests.testIdleControllerThatStopsPublishingIsStalledOnlyAfterAwakeTime, PeerSupervisionTests.testSleepAndNonIdleControllersNeverCountAsStalled
Watchdog killed Controller: watchdog heartbeat missing, not ready, stale or with a new generation. A restarted watchdog fences the controller at startup Session ends (watchdogUnavailable or watchdogRestarted), restored Next 1 s tick after the new watchdog publishes, at most 8 s SessionPolicyTests.testUserSwitchWatchdogRestartAndDisconnectEndIntent, SessionPolicyTests.testWatchdogAndConsoleCodesComeFromSeparateObservedChecks, SessionPolicyTests.testUnknownPowerAndStaleWatchdogNeverEnable
Watchdog hung (SIGSTOP) Controller: watchdog heartbeat stale Controller kills the watchdog before taking the lock, ends the session (watchdogUnavailable), restores Stale after 8 s, then the next 1 s tick PeerSupervisionTests.testRecoveryNeverWaitsOnLockBeforeFencingStoppedWriter, SessionPolicyTests.testUnknownPowerAndStaleWatchdogNeverEnable
Both services killed launchd restarts both. The controller restores before it is ready; the watchdog fences and recovers at startup Session ends, restored by whichever runs first Restart after up to 3 s each PeerObservationTests.testIdleOrMissingControllerWithJournalNeedsRecovery, SleepTransactionTests.testRecoveryAfterMetadataDeletionIsIdempotent
Both services hung Nothing while both stay stopped Not covered: the setting stays on. When they resume, the expired lease ends the session; a restart of the Mac runs startup recovery none None
AC lost, AC-only session Controller and watchdog, each with its own power reading Setting restored, session waits (waitingForAC) while renewed, turns on again when AC returns. While waiting the Mac can sleep; AC does not wake it Next 1 s tick; watchdog fences after 2 s if the controller still blocks SessionPolicyTests.testACLossRestoresAndFreshLeaseCanResumeOnAC, PeerSupervisionTests.testControllerCanPreserveWaitingACIntentAndResume, PeerSupervisionTests.testACLossAllowsBoundedReleaseGraceButCannotKeepStoppedWriter, BatterySessionPolicyTests.testDefaultStillRequiresACAndPreservesWaitingIntent
Unknown power reading Both services: no single present internal battery, or a missing or invalid source or level. A Mac with no internal battery entry, no lid state and no battery service in the kernel reads the source macOS says is providing power instead; macOS reports AC unless a UPS runs on its battery Start refused with the actual cause. AC-only session: waits as without AC. Battery session: ends (powerUnknown or batteryUnknown), restored Next 1 s tick; watchdog after 2 s PowerSnapshotTests.testMissingSourceIsUnknownEvenWhileCharging, PowerSnapshotTests.testExternalSourcesAloneCannotConfirmMacBookAC, PowerSnapshotTests.testAMacBookWithAFailedBatteryReadNeverCountsAsADesktop, PowerSnapshotTests.testFailedReadsNeverCountAsADesktop, PowerSnapshotTests.testABatteryServiceKeepsAMacBookOffTheDesktopPath, PowerSnapshotTests.testMultiplePresentInternalBatteriesAreExplicitlyAmbiguous, SessionPolicyTests.testUnknownPowerRefusalDoesNotClaimACIsDisconnected, BatterySessionPolicyTests.testUnknownOrMalformedBatteryNeverAuthorizesAndEndsRunningBatterySession, BatterySessionPolicyTests.testUnknownSourceAndThermalLimitEndBatterySession
Battery threshold reached Both services: level at or below the threshold while on battery Session ends (batteryThresholdReached), restored. Not resumed when AC returns or the level rises. Start on battery needs a level strictly above the threshold Next 1 s tick; watchdog after 2 s BatterySessionPolicyTests.testBatteryStartsOnlyStrictlyAboveSelectedThreshold, BatterySessionPolicyTests.testThresholdRestoresAndEndsIntentInsteadOfResumingOnACOrRebound, BatterySessionPolicyTests.testThreshold100AllowsFastACUnplugCutoffWithoutBatteryDrain, BatteryWatchdogTests.testObservedBatteryCutoffSurvivesPercentReboundOrACReconnect
Thermal state serious or critical Both services: ProcessInfo.thermalState, only while a battery session runs on battery Session ends (thermalUnsafe), restored. No effect on AC Next 1 s tick; watchdog after 2 s BatterySessionPolicyTests.testUnknownSourceAndThermalLimitEndBatterySession, BatterySessionPolicyTests.testRechecksPercentAndThermalConditionsInsideActivationLock, BatteryWatchdogTests.testWatchdogUsesIndependentBatteryAndThermalReading
User switch or logout Both services: console user differs from the session user Session ends (consoleUserChanged), restored; the watchdog gives no grace. Other users cannot connect Next 1 s tick SessionPolicyTests.testUserSwitchWatchdogRestartAndDisconnectEndIntent, SessionPolicyTests.testConsoleAndDurationAreValidated, PeerSupervisionTests.testACGraceNeverDelaysUserSwitchOrExpiredLease
Restart or crash of the Mac Both daemons start at boot (RunAtLoad). Heartbeats from the previous boot are rejected Restored from the durable journal before any session can start. No session starts by itself At daemon start PeerSupervisionTests.testPriorBootHeartbeatCannotAuthorizeWatchdog, RecoveryJournalTests.testSecureAtomicSaveRoundTripAndUpdate, SleepTransactionTests.testMissingContainerRestoresKernelBeforeRemovingContainer, SleepTransactionTests.testRecoveryAfterMetadataDeletionIsIdempotent
Sleep and wake During an active session SleepDisabled prevents sleep, also from the Apple menu. When the setting is off (idle, waiting for AC) the Mac can sleep. The lease clock counts sleep After a sleep while waiting for AC, the lease has expired on wake and the session ends (leaseExpired). Idle services are not fenced for heartbeat age after wake; Start after wake wakes the watchdog 12 s lease; stall check on uptime PeerSupervisionTests.testIdleControllerIsNeverFencedForItsAgeAlone, PeerSupervisionTests.testOnlyAReadyIdleControllerOfThisBootSkipsTheAgeCheck, PeerSupervisionTests.testSleepAndNonIdleControllersNeverCountAsStalled, SessionPolicyTests.testLeaseExpiryCannotBeRevivedByLateRenewal
Update or reinstall during a session preinstall App asked to quit (its Quit ends the session), coordinators stopped, both daemons killed and unloaded, then --recover restores. A failed recovery stops the installation. After install no session starts by itself (the app opens again only if it was running, or after a first installation); a mixed build fails the signature or version check App gets up to 10 s, then SIGKILL No test runs the scripts. The restore they call: SleepTransactionTests.testRestoreRetriesAfterMetadataWriteFailure, SleepTransactionTests.testRecoveryAfterMetadataDeletionIsIdempotent
Uninstall during a session uninstaller Same stop sequence and --recover before any file is removed. If recovery fails, removal stops and the files stay for another attempt; the daemon plists stay, so a restart also runs startup recovery App gets up to 10 s, then SIGKILL Same as above
Journal left behind Controller at startup; watchdog under the lock when the controller is not blocking Restored. A prepared journal is removed without touching the setting. While any journal exists, Start is refused. An invalid journal (wrong owner, mode, links, size or fields) is never trusted and keeps recovery pending; see support Startup, or the next watchdog tick (at most 60 s when idle) PeerObservationTests.testIdleOrMissingControllerWithJournalNeedsRecovery, PeerObservationTests.testAbsentJournalOrPublishedActivationDoesNotNeedOrphanRecovery, PeerObservationTests.testUnreadableHeartbeatOrJournalPropagatesToRecovery, PeerObservationTests.testActivationBeforeLockAcquisitionDoesNotOrphanNewSession, SleepTransactionTests.testPendingJournalBlocksNewActivation, SleepTransactionTests.testReadFailureIsPendingRecoveryAndBlocksActivation, RecoveryJournalTests.testRejectsMalformedUnsupportedAndInstructionBearingData, RecoveryJournalTests.testRejectsSymlinkForReadSaveAndRemoveWithoutTouchingTarget, RecoveryJournalTests.testRejectsHardLinkedJournal
Another tool changes SleepDisabled Start: the value is already on. During Start: repeated reads. During a session: verification on every tick. During restore: phase checks Already on: Start refused, the foreign lock is not taken over. Changed during Start: journal discarded, foreign value kept. Turned off during a session: session ends (backendVerificationFailed). Turned on again after kernel restore, or the original key removed: conflict, journal kept, retried every second. Other keys are kept Next 1 s tick SleepTransactionTests.testRejectsPreexistingTrueAndUnknownKernel, SleepTransactionTests.testConflictAfterJournalSyncDoesNotAuthorizeForeignRollback, SleepTransactionTests.testPreparedJournalNeverOverwritesForeignMutation, SleepTransactionTests.testForeignReenableAfterKernelRestorationIsConflict, SleepTransactionTests.testMergeReadsForeignKeysAddedDuringJournalSync, SleepTransactionTests.testFalseBaselineIsRestoredAndForeignKeysSurvive, SleepTransactionTests.testNewForeignKeyPreventsRemovalOfOriginallyMissingContainer, SessionPolicyTests.testVerificationFailureSurvivesFailedThenSuccessfulRestoration
Wall clock change Core: not affected; leases and heartbeats use mach_continuous_time, stall checks use uptime. Coordinator (closed source): judges confirmation age on the wall clock A backward step larger than the time since the last confirmation, or a forward step of more than about 6 s, makes the coordinator drop its connection; the session then ends (disconnected), restored Confirmation valid 6 s PeerSupervisionTests.testHeartbeatRejectsFutureStaleNotReadyAndNonFiniteTimes, PeerObservationTests.testObservationStillRejectsGenuinelyFutureAndExpiredHeartbeats, PeerSupervisionTests.testSupervisionWithoutAUsableClockStaysFast

Limits

  • Restoration needs at least one of the two services running, or a recovery run by the installer, the uninstaller or a restart. An administrator who stops or removes both services is outside automatic recovery.
  • CFPreferences has no compare-and-swap. A tool writing the same dictionary at the same moment as a Keep Mac Awake write is outside the guarantee.
  • The process glue (ServiceRuntime.swift, SecureState.swift) and the install scripts have no unit tests. The tests above cover the decisions they call.

Evidence

  • Automated tests. The behavior in each row is covered only to the extent of the tests listed there. They run with swift test on fake backends and never change power settings.
  • Hardware. Version 1.0 has no formal hardware test results for these failure modes. It was checked on hardware only in the developer's daily use: multi-day sessions with the lid closed, on AC and on battery, and command-line checks: the app killed while the session continues, and the coordinator killed ends the session at once with sleep restored.
  • No claim beyond that. Rows not named above, such as killed or hung services, restart, user switch, update and uninstall during a session, have no recorded hardware results for 1.0.

Test files