carlos / platform Public

media: deadline wall leg, exact plan, re-exec SIGTERM test

Fix round 1 of plan 3 Task 1. The wait keeps its monotonic timer and adds
a 1 s ticker that exits 0 once the wall clock reaches the grant's expiry
less 30 s, so a forward step or a paused VM ends the run early and a
backward step cannot extend it. planDeadline is the pure decision
(sleep, wall end, exit) and its test pins both sides of the bound
exactly. The 10 ms timing asserts are gone; a re-exec test sends a real
SIGTERM to the deadline command and requires exit 143.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 7e75377f924368a6c2a31b03a5fee1c9b155eb03 parent db89b19
3 files changed, +308 −56
  • cmd/carlos-media/deadline.go +74 −18
  • cmd/carlos-media/deadline_test.go +228 −38
  • cmd/carlos-media/main.go +6 −0
diff --git a/cmd/carlos-media/deadline.go b/cmd/carlos-media/deadline.go
index 161f4c462..a634b77d6 100644
--- a/cmd/carlos-media/deadline.go
+++ b/cmd/carlos-media/deadline.go
@@ -33,35 +33,91 @@ const maxDeadlineS = int64(media.MaxDeadline / time.Second)
// wrap, so it is refused as bad input rather than trusted to wrap safely.
const maxExpiryUnix = 253402300799
-// runDeadline is the deadline container's whole program. getenv supplies
-// media.DeadlineEnv (whole seconds, 1..3000) and media.ExpiryEnv (Unix
-// seconds, 1..maxExpiryUnix), both as canonical decimal: no sign, no
-// leading zero, no space. now is read once, as the start. stop delivers
-// SIGTERM.
-func runDeadline(getenv func(string) string, now func() time.Time, stop <-chan os.Signal) int {
+// wallCheckEvery is how often the wait reads the wall clock against the
+// grant's wall end. 1 s: the wall leg overshoots by at most one period,
+// which stays far inside the 30 s stop grace, and one clock read a second
+// costs nothing measurable. A longer period would only widen the
+// overshoot after a VM pause or a forward clock step.
+const wallCheckEvery = time.Second
+
+// deadlinePlan is what the container decided from its two values and its
+// start, before any wait.
+type deadlinePlan struct {
+ // Wait is false when the container exits at once with Exit.
+ Wait bool
+ Exit int
+ // Sleep is media.DeadlineSleep from the start: the earlier of the
+ // relative deadline and the expiry less the stop grace. The wait
+ // times it on the monotonic clock.
+ Sleep time.Duration
+ // WallEnd is the expiry less the stop grace, an instant of the wall
+ // clock with no monotonic reading.
+ WallEnd time.Time
+}
+
+// planDeadline reads media.DeadlineEnv (whole seconds, 1..3000) and
+// media.ExpiryEnv (Unix seconds, 1..maxExpiryUnix), both canonical
+// decimal: no sign, no leading zero, no space. It reads now once, as the
+// start. Bad input exits DeadlineExitBadInput at once; a sleep of 0 or
+// less exits DeadlineExitReached at once.
+func planDeadline(getenv func(string) string, now func() time.Time) deadlinePlan {
deadlineS, ok := parseCanonical(getenv(media.DeadlineEnv), maxDeadlineS)
if !ok {
- return media.DeadlineExitBadInput
+ return deadlinePlan{Exit: media.DeadlineExitBadInput}
}
expiryUnix, ok := parseCanonical(getenv(media.ExpiryEnv), maxExpiryUnix)
if !ok {
- return media.DeadlineExitBadInput
+ return deadlinePlan{Exit: media.DeadlineExitBadInput}
}
+ expiry := time.Unix(expiryUnix, 0)
// The sleep is at most the relative deadline whatever the expiry
// says: DeadlineSleep takes the earlier of the two ends.
- d := media.DeadlineSleep(now(), time.Duration(deadlineS)*time.Second, time.Unix(expiryUnix, 0))
+ d := media.DeadlineSleep(now(), time.Duration(deadlineS)*time.Second, expiry)
if d <= 0 {
- return media.DeadlineExitReached
+ return deadlinePlan{Exit: media.DeadlineExitReached}
+ }
+ return deadlinePlan{Wait: true, Sleep: d, WallEnd: expiry.Add(-media.StopGrace)}
+}
+
+// runDeadline is the deadline container's whole program: plan, then
+// wait. stop delivers SIGTERM.
+func runDeadline(getenv func(string) string, now func() time.Time, stop <-chan os.Signal) int {
+ p := planDeadline(getenv, now)
+ if !p.Wait {
+ return p.Exit
}
- // time.Timer runs on the monotonic clock: once started, a step of
- // the wall clock neither shortens nor lengthens the sleep.
- t := time.NewTimer(d)
+ tick := time.NewTicker(wallCheckEvery)
+ defer tick.Stop()
+ return waitDeadline(p, now, tick.C, stop)
+}
+
+// waitDeadline waits on two legs and exits DeadlineExitReached on
+// whichever ends first:
+//
+// - the monotonic leg, a time.Timer of p.Sleep. A wall-clock step
+// neither shortens nor lengthens it, so a backward step cannot
+// extend the run past start plus the deadline.
+// - the wall leg: on each tick, now() at or past p.WallEnd. A forward
+// step, or a VM paused while the monotonic clock stood still, ends
+// the run early, never late, against the grant's expiry.
+//
+// SIGTERM on stop exits DeadlineExitStopped.
+func waitDeadline(p deadlinePlan, now func() time.Time, tick <-chan time.Time, stop <-chan os.Signal) int {
+ t := time.NewTimer(p.Sleep)
defer t.Stop()
- select {
- case <-t.C:
- return media.DeadlineExitReached
- case <-stop:
- return media.DeadlineExitStopped
+ for {
+ select {
+ case <-t.C:
+ return media.DeadlineExitReached
+ case <-stop:
+ return media.DeadlineExitStopped
+ case <-tick:
+ // Round(0) drops any monotonic reading, so the comparison
+ // is by the wall clock.
+ if !now().Round(0).Before(p.WallEnd) {
+ return media.DeadlineExitReached
+ }
+ }
}
}
diff --git a/cmd/carlos-media/deadline_test.go b/cmd/carlos-media/deadline_test.go
index ecc23e780..0e8f376b5 100644
--- a/cmd/carlos-media/deadline_test.go
+++ b/cmd/carlos-media/deadline_test.go
@@ -1,12 +1,17 @@
package main
import (
+ "bufio"
"bytes"
"go/ast"
"go/parser"
"go/token"
+ "io"
"os"
+ "os/exec"
+ "runtime"
"strconv"
+ "sync/atomic"
"syscall"
"testing"
"time"
@@ -61,8 +66,9 @@ func await(t *testing.T, limit time.Duration, getenv func(string) string, now fu
// TestDeadlineExitsAtOnceWhenExpired: when the expiry less the stop grace
// is at or before the start, the container exits 0 at once (spec §5.5,
// astra R7-1: a task that waited in PENDING past its grant never
-// converts). Repeated so that a version which reaches the wait with a
-// zero timer and a pending SIGTERM would answer 143 at least once.
+// converts). The stop channel already holds SIGTERM, so a version that
+// reached the wait could answer 143; repeated so that a zero timer racing
+// that SIGTERM would lose at least once.
func TestDeadlineExitsAtOnceWhenExpired(t *testing.T) {
for _, c := range []struct{ name, expiry string }{
{"long past", "1"},
@@ -71,22 +77,16 @@ func TestDeadlineExitsAtOnceWhenExpired(t *testing.T) {
{"inside the grace", unix(fakeStart.Add(media.StopGrace - time.Second))},
} {
for range 20 {
- began := time.Now()
- code := runDeadline(env("3000", c.expiry), fixedNow, preStopped())
- took := time.Since(began)
- if code != media.DeadlineExitReached {
+ if code := runDeadline(env("3000", c.expiry), fixedNow, preStopped()); code != media.DeadlineExitReached {
t.Fatalf("%s: exit %d, want %d", c.name, code, media.DeadlineExitReached)
}
- if took > 10*time.Millisecond {
- t.Fatalf("%s: took %s, want at once", c.name, took)
- }
}
}
}
// TestDeadlineBadInput: anything but a canonical decimal deadline in
-// 1..3000 and a canonical decimal expiry in 1..maxExpiryUnix exits 3 at
-// once, before any wait.
+// 1..3000 and a canonical decimal expiry in 1..maxExpiryUnix exits 3
+// before any wait (the pending SIGTERM would otherwise answer 143).
func TestDeadlineBadInput(t *testing.T) {
future := unix(fakeStart.Add(time.Hour))
for _, c := range []struct{ name, deadline, expiry string }{
@@ -113,18 +113,64 @@ func TestDeadlineBadInput(t *testing.T) {
{"int64 max expiry", "900", "9223372036854775807"},
{"both empty", "", ""},
} {
- began := time.Now()
- code := runDeadline(env(c.deadline, c.expiry), fixedNow, preStopped())
- took := time.Since(began)
- if code != media.DeadlineExitBadInput {
+ if code := runDeadline(env(c.deadline, c.expiry), fixedNow, preStopped()); code != media.DeadlineExitBadInput {
t.Errorf("%s (%q, %q): exit %d, want %d", c.name, c.deadline, c.expiry, code, media.DeadlineExitBadInput)
}
- if took > 10*time.Millisecond {
- t.Errorf("%s: took %s, want at once", c.name, took)
+ }
+}
+
+// TestDeadlinePlanExact pins both sides of the bound: the sleep is
+// exactly the earlier of the relative deadline and the expiry less the
+// 30 s grace, never more, and the wall end is exactly the expiry less
+// the grace.
+func TestDeadlinePlanExact(t *testing.T) {
+ hour := fakeStart.Add(time.Hour)
+ for _, c := range []struct {
+ name, deadline, expiry string
+ want deadlinePlan
+ }{
+ {"deadline 1", "1", unix(hour), deadlinePlan{Wait: true, Sleep: time.Second, WallEnd: hour.Add(-media.StopGrace)}},
+ {"deadline 3000", "3000", unix(hour), deadlinePlan{Wait: true, Sleep: 3000 * time.Second, WallEnd: hour.Add(-media.StopGrace)}},
+ {"expiry start+31s", "3000", unix(fakeStart.Add(31 * time.Second)), deadlinePlan{Wait: true, Sleep: time.Second, WallEnd: fakeStart.Add(time.Second)}},
+ {"expiry start+30s", "3000", unix(fakeStart.Add(30 * time.Second)), deadlinePlan{Exit: media.DeadlineExitReached}},
+ {"negative sleep", "3000", unix(fakeStart.Add(-time.Hour)), deadlinePlan{Exit: media.DeadlineExitReached}},
+ {"bad input", "3001", unix(hour), deadlinePlan{Exit: media.DeadlineExitBadInput}},
+ } {
+ got := planDeadline(env(c.deadline, c.expiry), fixedNow)
+ if got.Wait != c.want.Wait || got.Exit != c.want.Exit {
+ t.Errorf("%s: wait %v exit %d, want wait %v exit %d", c.name, got.Wait, got.Exit, c.want.Wait, c.want.Exit)
+ continue
+ }
+ if !c.want.Wait {
+ continue
+ }
+ if got.Sleep != c.want.Sleep {
+ t.Errorf("%s: sleep %s, want exactly %s", c.name, got.Sleep, c.want.Sleep)
+ }
+ if !got.WallEnd.Equal(c.want.WallEnd) {
+ t.Errorf("%s: wall end %s, want %s", c.name, got.WallEnd, c.want.WallEnd)
}
}
}
+// TestDeadlinePlanReadsTheClockOnce: the plan reads the start once.
+// (The wait then reads the wall clock on each tick, see
+// TestDeadlineWallClockJumpsForward.)
+func TestDeadlinePlanReadsTheClockOnce(t *testing.T) {
+ calls := 0
+ now := func() time.Time {
+ calls++
+ return fakeStart.Add(time.Duration(calls-1) * time.Hour)
+ }
+ p := planDeadline(env("900", unix(fakeStart.Add(time.Hour))), now)
+ if calls != 1 {
+ t.Fatalf("now called %d times, want 1", calls)
+ }
+ if !p.Wait || p.Sleep != 900*time.Second {
+ t.Fatalf("plan %+v, want a 900 s wait from the first reading", p)
+ }
+}
+
// TestDeadlineAcceptsTheBounds: the edges of the valid ranges reach the
// wait (and so answer the pending SIGTERM with 143).
func TestDeadlineAcceptsTheBounds(t *testing.T) {
@@ -165,7 +211,8 @@ func TestDeadlineStopped(t *testing.T) {
func ptr(v int) *int { return &v }
// TestDeadlineReached: a 1 s deadline from the fake start returns 0 after
-// the timer, not before, with no SIGTERM.
+// the timer, not before, with no SIGTERM. The fake wall clock never
+// moves, so only the monotonic leg can end it.
func TestDeadlineReached(t *testing.T) {
code, took := await(t, 5*time.Second, env("1", unix(fakeStart.Add(time.Hour))), fixedNow, nil)
if code != media.DeadlineExitReached {
@@ -179,34 +226,177 @@ func TestDeadlineReached(t *testing.T) {
}
}
-// TestDeadlineReachedAtExpiry: with a 3000 s deadline and the grant
-// expiring 31 s after the start, the sleep is the expiry less the 30 s
-// stop grace, 1 s. Fails (by the 5 s limit) if the expiry or the grace is
-// ignored.
-func TestDeadlineReachedAtExpiry(t *testing.T) {
- expiry := unix(fakeStart.Add(media.StopGrace + time.Second))
- code, took := await(t, 5*time.Second, env("3000", expiry), fixedNow, nil)
- if code != media.DeadlineExitReached {
+// handClock is a wall clock the test answers by hand: each now() call
+// blocks until the test hands it a reading, so the test knows exactly
+// which reading each tick saw.
+type handClock chan time.Time
+
+func (c handClock) now() time.Time { return <-c }
+
+// read hands the wait's pending now() call the reading v.
+func (c handClock) read(t *testing.T, v time.Time) {
+ t.Helper()
+ select {
+ case c <- v:
+ case <-time.After(5 * time.Second):
+ t.Fatalf("the wait did not read the clock (reading %s)", v)
+ }
+}
+
+// tickOnce hands the wait one tick. The tick channel is unbuffered, so a
+// send that completes means the wait was still waiting.
+func tickOnce(t *testing.T, tick chan<- time.Time, what string) {
+ t.Helper()
+ select {
+ case tick <- time.Time{}:
+ case <-time.After(5 * time.Second):
+ t.Fatalf("the wait had already returned before the tick %s", what)
+ }
+}
+
+// startWait runs waitDeadline in the background.
+func startWait(p deadlinePlan, now func() time.Time, tick <-chan time.Time) <-chan int {
+ done := make(chan int, 1)
+ go func() { done <- waitDeadline(p, now, tick, nil) }()
+ return done
+}
+
+func awaitCode(t *testing.T, done <-chan int, limit time.Duration, what string) int {
+ t.Helper()
+ select {
+ case code := <-done:
+ return code
+ case <-time.After(limit):
+ t.Fatalf("the wait did not return %s within %s", what, limit)
+ return 0
+ }
+}
+
+// TestDeadlineWallClockJumpsForward: the wall clock jumps past the wall
+// end mid-wait (a forward step, or a VM resumed after a pause); the wait
+// exits 0 on the next tick, long before its hour-long monotonic timer.
+// A tick 1 ns before the wall end does not end it.
+func TestDeadlineWallClockJumpsForward(t *testing.T) {
+ end := fakeStart.Add(time.Hour)
+ c := make(handClock)
+ tick := make(chan time.Time)
+ done := startWait(deadlinePlan{Wait: true, Sleep: time.Hour, WallEnd: end}, c.now, tick)
+
+ tickOnce(t, tick, "1 ns before the wall end")
+ c.read(t, end.Add(-time.Nanosecond))
+ tickOnce(t, tick, "at the wall end") // completing proves the first tick did not end it
+ c.read(t, end)
+ if code := awaitCode(t, done, 5*time.Second, "at the wall end"); code != media.DeadlineExitReached {
t.Fatalf("exit %d, want %d", code, media.DeadlineExitReached)
}
- if took < time.Second {
- t.Fatalf("returned after %s, before the expiry less the grace", took)
+}
+
+// TestDeadlineWallClockStepsBack: a backward step cannot extend the run;
+// the monotonic timer still ends it.
+func TestDeadlineWallClockStepsBack(t *testing.T) {
+ c := make(handClock)
+ tick := make(chan time.Time)
+ began := time.Now()
+ done := startWait(deadlinePlan{Wait: true, Sleep: 200 * time.Millisecond, WallEnd: fakeStart.Add(time.Hour)}, c.now, tick)
+ tickOnce(t, tick, "after the backward step")
+ c.read(t, fakeStart.Add(-24*time.Hour))
+ if code := awaitCode(t, done, 5*time.Second, "on the monotonic timer"); code != media.DeadlineExitReached {
+ t.Fatalf("exit %d, want %d", code, media.DeadlineExitReached)
+ }
+ if took := time.Since(began); took < 200*time.Millisecond {
+ t.Fatalf("returned after %s, before the timer", took)
}
}
-// TestDeadlineReadsTheClockOnce: the start is read once, before the
-// wait; a clock that moves on later calls changes nothing.
-func TestDeadlineReadsTheClockOnce(t *testing.T) {
- calls := 0
+// TestDeadlineWallLegThroughRun: runDeadline itself ticks. The fake wall
+// clock reads the start once and then two hours on; with a 3000 s
+// deadline and an hour's grant, only the wall leg can end the run
+// within the 5 s limit (it ends after one wallCheckEvery).
+func TestDeadlineWallLegThroughRun(t *testing.T) {
+ var calls atomic.Int64
now := func() time.Time {
- calls++
- return fakeStart.Add(time.Duration(calls-1) * time.Hour)
+ if calls.Add(1) == 1 {
+ return fakeStart
+ }
+ return fakeStart.Add(2 * time.Hour)
}
- if code, _ := await(t, 5*time.Second, env("900", unix(fakeStart.Add(time.Hour))), now, preStopped()); code != media.DeadlineExitStopped {
- t.Fatalf("exit %d, want %d", code, media.DeadlineExitStopped)
+ code, _ := await(t, 5*time.Second, env("3000", unix(fakeStart.Add(time.Hour))), now, nil)
+ if code != media.DeadlineExitReached {
+ t.Fatalf("exit %d, want %d", code, media.DeadlineExitReached)
}
- if calls != 1 {
- t.Fatalf("now called %d times, want 1", calls)
+}
+
+// childEnv marks the re-executed test binary as the deadline command.
+const childEnv = "CARLOS_MEDIA_TEST_DEADLINE_CHILD"
+
+// TestDeadlineHelperProcess is the child of TestDeadlineSIGTERMProcess.
+// Run normally, it does nothing.
+func TestDeadlineHelperProcess(t *testing.T) {
+ if os.Getenv(childEnv) != "1" {
+ return
+ }
+ signalsReady = func() { os.Stdout.WriteString("ready\n") }
+ os.Exit(dispatch([]string{media.DeadlineCommand}, io.Discard, io.Discard))
+}
+
+// TestDeadlineSIGTERMProcess re-executes the test binary as `deadline`
+// with a 3000 s deadline, sends a real SIGTERM once the child has caught
+// it, and expects the process to exit 143 by its own exit, not to die of
+// the signal. It fails if signal.Notify is removed or names another
+// signal, because the Go runtime then dies of the SIGTERM.
+func TestDeadlineSIGTERMProcess(t *testing.T) {
+ if runtime.GOOS == "windows" {
+ t.Skip("no SIGTERM on Windows")
+ }
+ cmd := exec.Command(os.Args[0], "-test.run=^TestDeadlineHelperProcess$", "-test.count=1")
+ cmd.Env = append(os.Environ(), childEnv+"=1",
+ media.DeadlineEnv+"=3000",
+ media.ExpiryEnv+"="+strconv.FormatInt(time.Now().Add(time.Hour).Unix(), 10))
+ out, err := cmd.StdoutPipe()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := cmd.Start(); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = cmd.Process.Kill() })
+
+ ready := make(chan bool, 1)
+ go func() {
+ sc := bufio.NewScanner(out)
+ for sc.Scan() {
+ if sc.Text() == "ready" {
+ ready <- true
+ return
+ }
+ }
+ ready <- false
+ }()
+ select {
+ case ok := <-ready:
+ if !ok {
+ t.Fatal("the child closed its stdout without catching SIGTERM")
+ }
+ case <-time.After(10 * time.Second):
+ t.Fatal("the child did not reach the wait within 10 s")
+ }
+
+ if err := cmd.Process.Signal(syscall.SIGTERM); err != nil {
+ t.Fatal(err)
+ }
+ waited := make(chan error, 1)
+ go func() { waited <- cmd.Wait() }()
+ select {
+ case <-waited:
+ case <-time.After(10 * time.Second):
+ t.Fatal("the child did not exit within 10 s of SIGTERM")
+ }
+ st := cmd.ProcessState
+ if ws, ok := st.Sys().(syscall.WaitStatus); ok && ws.Signaled() {
+ t.Fatalf("the child died of %s; want exit %d through signal.Notify", ws.Signal(), media.DeadlineExitStopped)
+ }
+ if st.ExitCode() != media.DeadlineExitStopped {
+ t.Fatalf("the child exited %d, want %d", st.ExitCode(), media.DeadlineExitStopped)
}
}
diff --git a/cmd/carlos-media/main.go b/cmd/carlos-media/main.go
index 99eb63b57..3070f6bbf 100644
--- a/cmd/carlos-media/main.go
+++ b/cmd/carlos-media/main.go
@@ -70,5 +70,11 @@ func deadlineCommand(rest []string) int {
stop := make(chan os.Signal, 1)
signal.Notify(stop, syscall.SIGTERM)
defer signal.Stop(stop)
+ signalsReady()
return runDeadline(os.Getenv, time.Now, stop)
}
+
+// signalsReady runs once SIGTERM is caught. It does nothing in the
+// binary; TestDeadlineSIGTERMProcess's child sets it to tell the parent
+// when a SIGTERM will reach runDeadline rather than kill the process.
+var signalsReady = func() {}