Skip to content

fix(control): supervise the control tick and commit a trial after the first tick - #1880

Merged
frahlg merged 2 commits into
masterfrom
a7-tick-supervisor
Oct 27, 2026
Merged

frahlg merged 2 commits into
masterfrom
a7-tick-supervisor

Conversation

@frahlg

@frahlg frahlg commented Oct 27, 2026 •

Copy link
Copy Markdown
Member

Item A7 of the stable plan.

Problem

The control tick runs every safety check itself: the driver watchdog, the stale-meter stop and the fuse guard. Nothing watches the tick from outside.

  • If the tick blocks after it has sent battery commands, for example in forecastCurtail.PendingDrivers waiting for a free SQLite connection (the pool holds 4), the battery keeps its last setpoint with no time limit. A Sungrow leaves forced mode only through its default (sungrow.lua:839). The HTTP server and drivers keep running, so systemd sees a healthy process.
  • ctrlMu is taken without defer around ComputeDispatch (main.go:3149-3161). A panic there leaves the lock held. Shutdown then runs mpcSvc.Stop first, which waits for a replan that needs ctrlMu, so the process never reaches reg.ShutdownAll and never exits.
  • A native trial commits as soon as HTTP is up (main.go:2668), before the first tick. A release whose control loop hangs is committed, and probation only counts restarts, so it never falls back.

Change

  • A supervisor goroutine checks the time of the last completed tick every second. When it is older than max(3 × interval, 10 s), it sends every driver its default in parallel, through the same sendDriverDefault the watchdog uses (observe-only drivers are skipped). When it is older than max(60 s, twice that), it calls os.Exit(1). No clean-exit mark is written, so probation counts the exit. A tick that recovers re-arms the supervisor.
  • The supervisor measures the tick's age on the monotonic clock: it keeps a base time from time.Now and stores each tick as the time since that base. A Pi without an RTC boots on a stale clock, and the unit orders only after network-online.target, so NTP often steps the clock while the loop runs. A wall-clock age would make a healthy Core exit after a forward step of 60 s or more, and a backward step would hide a stall.
  • Every path out of a tick records it: the normal end, the stale-meter continue and the setup-measurement continue. A blocked-by-stale-meter tick therefore counts as healthy.
  • The first completed tick commits the native trial. The 6 h trial timer stays as the backstop.
  • ComputeDispatch and SelfTuneDispatch run in withCtrlLock, which unlocks with defer.
  • docs/self-update.md now says a trial becomes current after its first control tick.

The audit's source-order repro also asked for systemd WatchdogSec with sd_notify. The plan picked the in-process supervisor, so that half is replaced by real tests of a blocked tick. The audit noted that 10 s may be tight for a slow but healthy tick; I kept the plan's value. A false trip sends defaults once, and the next tick dispatches again.

Tests

  • go test -race -count=1 ./cmd/ftw/: ok (261 s).
  • New in go/cmd/ftw/tick_supervisor_test.go:
    • TestTickSupervisorDefaultsThenExitsOnBlockedTick: one tick completes, the next blocks. No defaults at 9 s, one default at 11 s, none more at 30 s, exit at 61 s.
    • TestTickSupervisorRearmsAfterTheTickRecovers, TestTickSupervisorThresholdsFollowTheInterval (2 s → 10/60 s, 5 s → 15/60 s, 30 s → 90/180 s).
    • TestTickSupervisorIgnoresWallClockStep (2 s of real time, 10 min forward step: no defaults, no exit) and TestTickSupervisorSeesStallAfterBackwardStep (70 s stall, 1 h backward step: defaults and exit). Both move only the wall clock of a time.Now value and keep its monotonic reading. Both fail without the monotonic base.
    • TestSendDefaultsInParallelDoesNotWaitOnOneSlowDriver, TestWithCtrlLockReleasesTheLockOnPanic.
    • TestNativeTrialCommitsOnlyAfterFirstControlTick: the audit repro (caa-81), adapted. It fails on master. It checks that the commit lives only in tickDone and that every continue out of the tick, and its end, calls tickDone().
  • go vet ./... and go build ./...: clean.
  • I did not run the site rig; the runner runs it on this PR. W0-6 will check the commit order end to end.

Risk

Medium. The supervisor only sends defaults and exits; it takes no control lock, so a wedged tick cannot block it. A tick slower than 10 s now sends defaults once, which is the safe state. The trial commit moves from "HTTP up" to about one control interval later.

🤖 Generated with Claude Code

… first tick

A supervisor goroutine watches the time of the last completed tick. When
it is older than max(3 x interval, 10 s), every driver gets its default
mode in parallel; observe-only drivers are skipped. When it is older than
max(60 s, twice that), Core exits 1 so the service restarts it and
probation counts the exit.

Every path out of a tick records it, including the stale-meter and
setup-measurement paths. The first completed tick commits a native
trial, instead of the moment HTTP is up. ComputeDispatch and
SelfTuneDispatch run under a deferred ctrlMu unlock.

Item A7 of the stable plan.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 27, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-27T13:13:14.799540Z d30d2e8 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d30d2e8ea9

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread go/cmd/ftw/tick_supervisor.go Outdated
// per stall; exit stays true while the stall lasts past tickExitAfter.
func (s *tickSupervisor) check(now time.Time) (sendDefaults, exit bool, age time.Duration) {
interval := time.Duration(s.intervalNs.Load())
age = now.Sub(time.Unix(0, s.lastNs.Load()))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Measure tick age with a monotonic clock

When the host clock is corrected while a tick is running, converting the heartbeat to UnixNano and reconstructing it with time.Unix makes this subtraction use wall-clock time rather than Go's monotonic clock. A forward correction of at least 60 seconds can therefore terminate a healthy Core on the next supervisor check, while a backward correction can postpone defaults and restart for a genuinely blocked tick until the clock catches up. Preserve the monotonic component of the heartbeat, for example by storing the original time.Time under a mutex, so clock synchronization cannot change these safety deadlines.

Useful? React with 👍 / 👎.

The supervisor stored the last tick as wall-clock nanoseconds, so its age
followed the wall clock. A Pi without an RTC boots on a stale clock and NTP
steps it forward, often while the loop already runs. A forward step of 60 s
or more made a healthy Core send defaults and exit; a backward step hid a
real stall.

The supervisor now keeps a base time from newTickSupervisor and stores each
tick as the time since that base, so ages use the monotonic reading.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@frahlg
frahlg merged commit c51f64b into master Oct 27, 2026
23 checks passed
@frahlg
frahlg deleted the a7-tick-supervisor branch November 11, 2026 09:12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant