From 0c8351c2f09a0e074effffd000c2d59819e195f0 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 23 Nov 2026 09:43:18 -0800 Subject: [PATCH 01/16] fix(clock): the env clock follows any date to 9999, past 2262 The clock page held the universe as one signed 64-bit count of nanoseconds, which runs out on 2262-04-11: a later date made every follower crash-loop with nothing saying why. The page (version 3) holds whole seconds and nanoseconds in the same 80 bytes; agent-env's libfaketime keeps universe times as 128-bit nanoseconds in its waits and computes clock reads with 64-bit operations alone, in one place both share; the egress proxy reads the new page and no longer overflows on a certificate ending past 2262; a page of another version is replaced at boot and never read. The gateway names 9999-12-31T23:59:59Z, the latest it reaches, in every error about the range. The clock gates run at 1950, across 2262, in 3026 and in 9999. Co-Authored-By: Claude Opus 5.5 --- .../artifacts/ubuntu-24.04/clock-panel | 10 +- src/agent_env/env/gateway/clock.py | 14 ++- .../utils/agent_clock/agent_egress.py | 9 +- src/agent_env/utils/egress_proxy/clock.go | 30 +++-- .../utils/egress_proxy/clock_test.go | 39 +++++- .../utils/egress_proxy/proxy_test.go | 13 ++ .../egress_proxy/testdata/page-armed.hex | 2 +- .../utils/egress_proxy/testdata/page-far.hex | 1 + .../utils/egress_proxy/testdata/page-past.hex | 1 + .../egress_proxy/testdata/page-unarmed.hex | 2 +- .../egress_proxy/testdata/page-version2.hex | 1 + src/agent_env/utils/egress_proxy/upstream.go | 9 +- .../faketime_clock/agentenv_clock_page.c | 80 ++++++++++-- .../faketime_clock/agentenv_clock_waits.c | 69 +++++++---- .../utils/faketime_clock/clockpage.py | 72 ++++++++--- .../utils/faketime_clock/libfaketime.patch | 30 ++--- tst/clock/harness.py | 41 ++++--- tst/clock/programs/cancel.c | 4 +- tst/clock/programs/jumpwaits.c | 26 ++-- tst/clock/programs/rtbase.h | 23 ++++ tst/clock/programs/rtread.c | 6 +- tst/clock/programs/tfdalias.c | 3 +- tst/clock/programs/torn.c | 16 ++- tst/clock/range_test.py | 101 +++++++++++++++ tst/unit/agents/test_agent_egress.py | 2 + .../env/envs/test_computer_clock_follower.py | 3 +- tst/unit/env/envs/test_computer_clock_page.py | 116 ++++++++++++++++++ .../env/envs/test_computer_clock_panel.py | 2 +- .../env/envs/test_computer_egress_base.py | 15 ++- tst/unit/env/gateway/clock_range_test.py | 38 ++++++ 30 files changed, 622 insertions(+), 156 deletions(-) create mode 100644 src/agent_env/utils/egress_proxy/testdata/page-far.hex create mode 100644 src/agent_env/utils/egress_proxy/testdata/page-past.hex create mode 100644 src/agent_env/utils/egress_proxy/testdata/page-version2.hex create mode 100644 tst/clock/programs/rtbase.h create mode 100644 tst/clock/range_test.py create mode 100644 tst/unit/env/envs/test_computer_clock_page.py create mode 100644 tst/unit/env/gateway/clock_range_test.py diff --git a/src/agent_env/computers/artifacts/ubuntu-24.04/clock-panel b/src/agent_env/computers/artifacts/ubuntu-24.04/clock-panel index 76da015cb..fe27c0984 100755 --- a/src/agent_env/computers/artifacts/ubuntu-24.04/clock-panel +++ b/src/agent_env/computers/artifacts/ubuntu-24.04/clock-panel @@ -36,14 +36,10 @@ def log(event: str, **fields) -> None: def read(fd: int) -> tuple | None: """The page's (armed, universe_ns, anchor_ns, rate), None while it's being written or isn't a page.""" - raw = os.pread(fd, clockpage.LAYOUT.size, 0) - if len(raw) < clockpage.LAYOUT.size: - return None - magic, version, seq, universe, anchor, rate, armed, _, generation, check, mono_universe, mono_anchor = ( - clockpage.LAYOUT.unpack(raw)) - if (magic, version) != (clockpage.MAGIC, clockpage.VERSION) or seq & 1 or check != clockpage.check( - seq, universe, anchor, rate, armed, generation, mono_universe, mono_anchor): + state = clockpage.read(os.pread(fd, clockpage.LAYOUT.size, 0)) + if state is None: return None + _, armed, universe, anchor, rate, _ = state return armed, universe, anchor, rate diff --git a/src/agent_env/env/gateway/clock.py b/src/agent_env/env/gateway/clock.py index 5f575c86e..273992b02 100644 --- a/src/agent_env/env/gateway/clock.py +++ b/src/agent_env/env/gateway/clock.py @@ -24,6 +24,9 @@ class ClockError(ValueError): # exempt). Not the overflow guarantee — reads still saturate (_advance) if the gateway outlives it. _OVERFLOW_HORIZON_S = 86400.0 _MAX_T0 = datetime.max.replace(tzinfo=timezone.utc) +# The latest time the clock reaches, as its errors name it: what a datetime holds, which the computers and agents that +# follow it hold too. +LATEST = "9999-12-31T23:59:59Z" def _parse_rate(rate) -> float: @@ -59,6 +62,8 @@ def _parse_rfc3339(text: str) -> datetime: raise ClockError(f"virtual_time must be an RFC3339 string, got {type(text).__name__}") # Don't strip: a whitespace-wrapped value would slip through the anchored grammar (a 200 the contract calls a 400). raw = text + if re.match(r"^\d{5,}-", raw): + raise ClockError(f"virtual_time {text!r} is past {LATEST}, the latest the env clock reaches") if not _RFC3339_RE.match(raw): raise ClockError(f"invalid RFC3339 virtual_time {text!r}: expected {_RFC3339_SHAPE}") if raw.endswith(("Z", "z")): @@ -190,7 +195,8 @@ def set_time(self, virtual_time: str, rate=1.0, time_zone: str | None = None) -> if time_zone is not None and _zone(time_zone) is None: raise ClockError(f"unknown time zone {time_zone!r}: pass an IANA time zone name such as 'America/New_York'") if t0 > _MAX_T0 - timedelta(seconds=_OVERFLOW_HORIZON_S * r): - raise ClockError(f"virtual_time {virtual_time!r} at rate {r:g} would overflow datetime near the max") + raise ClockError(f"virtual_time {virtual_time!r} at rate {r:g} would pass {LATEST}, the latest the env clock " + f"reaches, within a real day") with self._lock: self._bank(t0) self._t0 = t0 @@ -213,7 +219,8 @@ def set_rate(self, rate) -> dict: now = self._now() ran = (now - self._anchor) * self._rate if _advance(self._t0, ran + self._ahead) > _MAX_T0 - timedelta(seconds=_OVERFLOW_HORIZON_S * r): - raise ClockError(f"rate {r:g} would overflow datetime near the max") + raise ClockError(f"rate {r:g} would carry the clock past {LATEST}, the latest it reaches, within a real " + f"day") self._lived += ran self._ahead += ran self._anchor = now @@ -228,7 +235,8 @@ def advance(self, virtual_time: str) -> dict: if not self._armed or self._t0 is None: raise ClockError("clock is not armed") if target > _MAX_T0 - timedelta(seconds=_OVERFLOW_HORIZON_S * self._rate): - raise ClockError(f"virtual_time {virtual_time!r} at rate {self._rate:g} would overflow datetime near the max") + raise ClockError(f"virtual_time {virtual_time!r} at rate {self._rate:g} would pass {LATEST}, the latest " + f"the env clock reaches, within a real day") current = _advance(self._t0, (self._now() - self._anchor) * self._rate + self._ahead) jump = (target - current).total_seconds() if jump < 0: diff --git a/src/agent_env/utils/agent_clock/agent_egress.py b/src/agent_env/utils/agent_clock/agent_egress.py index 8fad38ef2..dae8398bf 100644 --- a/src/agent_env/utils/agent_clock/agent_egress.py +++ b/src/agent_env/utils/agent_clock/agent_egress.py @@ -26,13 +26,12 @@ def clock_armed(page_path: str | None = None) -> bool: raw = page.read(clockpage.LAYOUT.size) if len(raw) < clockpage.LAYOUT.size: return False - magic, version, seq, universe, anchor, rate, armed, _, generation, checked, mono_u, mono_a = \ - clockpage.LAYOUT.unpack(raw) + magic, version, *_ = fields = clockpage.LAYOUT.unpack(raw) if (magic, version) != (clockpage.MAGIC, clockpage.VERSION): return False - if seq % 2 == 0 and checked == clockpage.check(seq, universe, anchor, rate, armed, generation, mono_u, - mono_a): - return bool(armed) + if (state := clockpage.read(raw)) is not None: + return bool(state[1]) + armed = fields[6] time.sleep(_RETRY_S) except OSError: return False diff --git a/src/agent_env/utils/egress_proxy/clock.go b/src/agent_env/utils/egress_proxy/clock.go index 30cb880c1..94407dab2 100644 --- a/src/agent_env/utils/egress_proxy/clock.go +++ b/src/agent_env/utils/egress_proxy/clock.go @@ -9,12 +9,14 @@ import ( "time" ) -// The clock page the follower writes (clockpage.py, version 2): magic version seq universe_ns anchor_ns rate armed -// reserved generation check mono_universe_ns mono_anchor_ns, little-endian, 80 bytes, seq odd while it's written. +// The clock page the follower writes (clockpage.py, version 3): magic version seq universe_s anchor_ns rate armed +// universe_nsec generation check mono_universe_ns mono_anchor_ns, little-endian, 80 bytes, seq odd while it's written. +// The universe at the anchor is universe_s seconds and universe_nsec nanoseconds, so it reaches past 2262. const ( - pageSize = 80 - pageMagic = 0x4B434541 - checkSalt = 0x9E3779B97F4A7C15 + pageSize = 80 + pageMagic = 0x4B434541 + pageVersion = 3 + checkSalt = 0x9E3779B97F4A7C15 ) // state is the universe as the session reads it: armed, the universe at the anchor (seconds), the anchor (real @@ -38,35 +40,39 @@ func (s state) at(t float64) float64 { return s.V + (t-s.Anchor)*s.Rate } -func pageCheck(seq uint64, u, a int64, rate float64, armed uint32, generation uint64, mu, ma int64) uint64 { - return seq ^ uint64(u) ^ uint64(a) ^ math.Float64bits(rate) ^ uint64(armed) ^ generation ^ uint64(mu) ^ - uint64(ma) ^ checkSalt +func pageCheck(seq uint64, us int64, unsec uint32, a int64, rate float64, armed uint32, generation uint64, + mu, ma int64) uint64 { + return seq ^ uint64(us) ^ uint64(unsec)<<32 ^ uint64(a) ^ math.Float64bits(rate) ^ uint64(armed) ^ generation ^ + uint64(mu) ^ uint64(ma) ^ checkSalt } // readPage reads a consistent state from the page's bytes, or false when it's being written, torn or not a page. func readPage(b []byte) (state, bool) { - if len(b) < pageSize || binary.LittleEndian.Uint32(b[0:]) != pageMagic { + if len(b) < pageSize || binary.LittleEndian.Uint32(b[0:]) != pageMagic || + binary.LittleEndian.Uint32(b[4:]) != pageVersion { return state{}, false } seq := binary.LittleEndian.Uint64(b[8:]) if seq&1 == 1 { return state{}, false } - u := int64(binary.LittleEndian.Uint64(b[16:])) + us := int64(binary.LittleEndian.Uint64(b[16:])) a := int64(binary.LittleEndian.Uint64(b[24:])) rate := math.Float64frombits(binary.LittleEndian.Uint64(b[32:])) armed := binary.LittleEndian.Uint32(b[40:]) + unsec := binary.LittleEndian.Uint32(b[44:]) generation := binary.LittleEndian.Uint64(b[48:]) check := binary.LittleEndian.Uint64(b[56:]) mu := int64(binary.LittleEndian.Uint64(b[64:])) ma := int64(binary.LittleEndian.Uint64(b[72:])) - if check != pageCheck(seq, u, a, rate, armed, generation, mu, ma) || binary.LittleEndian.Uint64(b[8:]) != seq { + if unsec >= 1e9 || check != pageCheck(seq, us, unsec, a, rate, armed, generation, mu, ma) || + binary.LittleEndian.Uint64(b[8:]) != seq { return state{}, false } if armed == 0 { return unarmed, true } - return state{Armed: true, V: float64(u) / 1e9, Anchor: float64(a) / 1e9, Rate: rate}, true + return state{Armed: true, V: float64(us) + float64(unsec)/1e9, Anchor: float64(a) / 1e9, Rate: rate}, true } // Universe follows the clock page, read every PagePoll, so a change is seen and the universe it left is held for Hold. diff --git a/src/agent_env/utils/egress_proxy/clock_test.go b/src/agent_env/utils/egress_proxy/clock_test.go index 22bb41503..8f303df28 100644 --- a/src/agent_env/utils/egress_proxy/clock_test.go +++ b/src/agent_env/utils/egress_proxy/clock_test.go @@ -13,20 +13,21 @@ import ( func page(seq uint64, universe, anchor time.Time, rate float64, armed bool) []byte { b := make([]byte, pageSize) - u, a := universe.UnixNano(), anchor.UnixNano() + us, unsec, a := universe.Unix(), uint32(universe.Nanosecond()), anchor.UnixNano() var on uint32 if armed { on = 1 } binary.LittleEndian.PutUint32(b[0:], pageMagic) - binary.LittleEndian.PutUint32(b[4:], 2) + binary.LittleEndian.PutUint32(b[4:], pageVersion) binary.LittleEndian.PutUint64(b[8:], seq) - binary.LittleEndian.PutUint64(b[16:], uint64(u)) + binary.LittleEndian.PutUint64(b[16:], uint64(us)) binary.LittleEndian.PutUint64(b[24:], uint64(a)) binary.LittleEndian.PutUint64(b[32:], math.Float64bits(rate)) binary.LittleEndian.PutUint32(b[40:], on) + binary.LittleEndian.PutUint32(b[44:], unsec) binary.LittleEndian.PutUint64(b[48:], 7) - binary.LittleEndian.PutUint64(b[56:], pageCheck(seq, u, a, rate, on, 7, a, a)) + binary.LittleEndian.PutUint64(b[56:], pageCheck(seq, us, unsec, a, rate, on, 7, a, a)) binary.LittleEndian.PutUint64(b[64:], uint64(a)) binary.LittleEndian.PutUint64(b[72:], uint64(a)) return b @@ -54,6 +55,27 @@ func TestAPageReadsAsTheUniverseItHoldsAndATornOneNot(t *testing.T) { } } +func TestAPageReachesPast2262AndBefore1970(t *testing.T) { + anchor := time.Unix(time.Now().Unix(), 0) + far := time.Date(9999, 6, 1, 12, 0, 0, 500000000, time.UTC) + s, ok := readPage(page(4, far, anchor, 3600, true)) + if !ok || s.V != float64(far.Unix())+0.5 { + t.Fatalf("9999: %+v %v", s, ok) + } + if got := s.at(float64(anchor.Unix()) + 1); got != float64(far.Unix())+3600.5 { + t.Fatalf("1 s on at rate 3600: %v", got) + } + past := time.Date(1949, 12, 31, 23, 59, 59, 750000000, time.UTC) + if s, ok := readPage(page(4, past, anchor, 1, true)); !ok || s.V != float64(past.Unix())+0.75 { + t.Fatalf("1949: %+v %v", s, ok) + } + old := page(4, far, anchor, 1, true) + binary.LittleEndian.PutUint32(old[4:], 2) + if _, ok := readPage(old); ok { + t.Fatal("a version 2 page read as one of this version") + } +} + func TestTheUniverseFollowsThePageFileAndHoldsTheOneItLeft(t *testing.T) { path := filepath.Join(t.TempDir(), "page") if err := os.WriteFile(path, page(2, time.Time{}, time.Time{}, 1, false), 0o644); err != nil { @@ -109,4 +131,13 @@ func TestThePagesTheFollowersWriterWritesReadAsTheUniverseTheyHold(t *testing.T) if s, ok := readPage(golden(t, "unarmed")); !ok || s != unarmed { t.Fatalf("unarmed: %+v %v", s, ok) } + if s, ok := readPage(golden(t, "far")); !ok || s.V != 253402214400.5 || s.Rate != 3600 { + t.Fatalf("far: %+v %v", s, ok) + } + if s, ok := readPage(golden(t, "past")); !ok || s.V != -631152000.25 || s.Rate != 1 { + t.Fatalf("past: %+v %v", s, ok) + } + if _, ok := readPage(golden(t, "version2")); ok { + t.Fatal("a version 2 page read as one of this version") + } } diff --git a/src/agent_env/utils/egress_proxy/proxy_test.go b/src/agent_env/utils/egress_proxy/proxy_test.go index 772afe1f8..fa2abfc85 100644 --- a/src/agent_env/utils/egress_proxy/proxy_test.go +++ b/src/agent_env/utils/egress_proxy/proxy_test.go @@ -373,6 +373,19 @@ func TestEveryCertificateOfTheVerifiedChainBoundsPassingThrough(t *testing.T) { } } +func TestACertificateEndingPast2262BoundsPassingThroughAsWritten(t *testing.T) { + year := func(y int) time.Time { return time.Date(y, 1, 1, 0, 0, 0, 0, time.UTC) } + from, until := year(2020), time.Date(9999, 12, 31, 23, 59, 59, 0, time.UTC) + for _, y := range []int{2027, 2300, 9000} { + if !inside(from, until, []float64{float64(year(y).Unix())}) { + t.Fatalf("a universe in %d, inside a certificate to 9999, didn't pass through", y) + } + } + if inside(from, until, []float64{float64(year(2019).Unix())}) { + t.Fatal("a universe before the certificate passed through") + } +} + func TestASiteAskingForTheClientsCertificateIsPassedThroughForTheClientToAnswer(t *testing.T) { s := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "hello %d certificate", len(r.TLS.PeerCertificates)) diff --git a/src/agent_env/utils/egress_proxy/testdata/page-armed.hex b/src/agent_env/utils/egress_proxy/testdata/page-armed.hex index 2aecf27e8..072dbab8e 100644 --- a/src/agent_env/utils/egress_proxy/testdata/page-armed.hex +++ b/src/agent_env/utils/egress_proxy/testdata/page-armed.hex @@ -1 +1 @@ -4145434b02000000040000000000000000008ab9359ae51515cd68be7e91e51800000000000000400100000000000000070000000000000002b1a878f27237d300f2052a0100000000f2052a01000000 +4145434b03000000040000000000000000e10b5e0000000015cd68be7e91e5180000000000000040010000000000000007000000000000000250299fc7e8d2c600f2052a0100000000f2052a01000000 diff --git a/src/agent_env/utils/egress_proxy/testdata/page-far.hex b/src/agent_env/utils/egress_proxy/testdata/page-far.hex new file mode 100644 index 000000000..59a1f883e --- /dev/null +++ b/src/agent_env/utils/egress_proxy/testdata/page-far.hex @@ -0,0 +1 @@ +4145434b03000000060000000000000000f0f2ff3a00000000000db77e91e518000000000020ac40010000000065cd1d09000000000000001b8cb537fdadb3db00f2052a0100000000f2052a01000000 diff --git a/src/agent_env/utils/egress_proxy/testdata/page-past.hex b/src/agent_env/utils/egress_proxy/testdata/page-past.hex new file mode 100644 index 000000000..9a22bad94 --- /dev/null +++ b/src/agent_env/utils/egress_proxy/testdata/page-past.hex @@ -0,0 +1 @@ +4145434b0300000008000000000000007f6261daffffffff00000db77e91e518000000000000f03f010000008017b42c0b00000000000000681e2612b800696a00f2052a0100000000f2052a01000000 diff --git a/src/agent_env/utils/egress_proxy/testdata/page-unarmed.hex b/src/agent_env/utils/egress_proxy/testdata/page-unarmed.hex index 7f6a95f54..382ad612b 100644 --- a/src/agent_env/utils/egress_proxy/testdata/page-unarmed.hex +++ b/src/agent_env/utils/egress_proxy/testdata/page-unarmed.hex @@ -1 +1 @@ -4145434b02000000020000000000000000000000000000000000000000000000000000000000f03f00000000000000000300000000000000147c4a7fb979c7a100000000000000000000000000000000 +4145434b03000000020000000000000000000000000000000000000000000000000000000000f03f00000000000000000300000000000000147c4a7fb979c7a100000000000000000000000000000000 diff --git a/src/agent_env/utils/egress_proxy/testdata/page-version2.hex b/src/agent_env/utils/egress_proxy/testdata/page-version2.hex new file mode 100644 index 000000000..2aecf27e8 --- /dev/null +++ b/src/agent_env/utils/egress_proxy/testdata/page-version2.hex @@ -0,0 +1 @@ +4145434b02000000040000000000000000008ab9359ae51515cd68be7e91e51800000000000000400100000000000000070000000000000002b1a878f27237d300f2052a0100000000f2052a01000000 diff --git a/src/agent_env/utils/egress_proxy/upstream.go b/src/agent_env/utils/egress_proxy/upstream.go index bad2ea7db..717078bb4 100644 --- a/src/agent_env/utils/egress_proxy/upstream.go +++ b/src/agent_env/utils/egress_proxy/upstream.go @@ -227,8 +227,8 @@ func (p *Proxy) forget(dst, sni string) { // inside is whether every universe lies inside [from + Margin, until - Margin]. func inside(from, until time.Time, universes []float64) bool { - lo := float64(from.Add(Margin).UnixNano()) / 1e9 - hi := float64(until.Add(-Margin).UnixNano()) / 1e9 + lo := seconds(from.Add(Margin)) + hi := seconds(until.Add(-Margin)) for _, u := range universes { if u < lo || u > hi { return false @@ -237,6 +237,11 @@ func inside(from, until time.Time, universes []float64) bool { return true } +// seconds is t as Unix seconds at any date; UnixNano overflows past 2262, where a certificate may still end. +func seconds(t time.Time) float64 { + return float64(t.Unix()) + float64(t.Nanosecond())/1e9 +} + // dialAny dials each address in turn until one answers: which, or every one's error. func (p *Proxy) dialAny(dsts []string) (net.Conn, string, error) { var problems []string diff --git a/src/agent_env/utils/faketime_clock/agentenv_clock_page.c b/src/agent_env/utils/faketime_clock/agentenv_clock_page.c index 9167f7ede..c2b77ef1c 100644 --- a/src/agent_env/utils/faketime_clock/agentenv_clock_page.c +++ b/src/agent_env/utils/faketime_clock/agentenv_clock_page.c @@ -186,8 +186,10 @@ static bool ft_deadline_moved(const struct timespec *fake_abs, struct timespec * } /* - * the clock page. 64 bytes, little-endian, rewritten in place by the follower: seq odd while it writes, - * then even; check is the xor of the other words and a constant. A realtime read in a faked process copies it + * the clock page (version 3). 80 bytes, little-endian, rewritten in place by the follower: seq odd while it writes, + * then even; check is the xor of the other words and a constant. The universe at the anchor is universe_s seconds and + * universe_nsec nanoseconds (floored: before 1970 the seconds are negative, the nanoseconds not), so it reaches any date + * a 64-bit time_t holds; the anchor is real time. A realtime read in a faked process copies it * lock-free and computes universe + (now - anchor) * rate (rate 0: universe), so every process agrees with no shared * start; the first thread to see a new generation also hands it to libfaketime's own state (rates of sleeps, the * time an absolute spec gives) under the MT lock. The page must be owned by AGENTENV_CLOCK_PAGE_UID (0 by default) and @@ -197,14 +199,14 @@ struct ft_clock_page { uint32_t magic, version; uint64_t seq; - int64_t universe_ns, anchor_ns; + int64_t universe_s, anchor_ns; double rate; - uint32_t armed, reserved; + uint32_t armed, universe_nsec; uint64_t generation, check; int64_t mono_universe_ns, mono_anchor_ns; }; #define FT_PAGE_MAGIC 0x4B434541u -#define FT_PAGE_VERSION 2u +#define FT_PAGE_VERSION 3u static const volatile struct ft_clock_page *ft_page = NULL; static uint64_t ft_page_applied = 0; static time_t ft_page_last_try = 0; @@ -214,8 +216,9 @@ static uint64_t ft_page_check(const struct ft_clock_page *p) { uint64_t rate_bits; memcpy(&rate_bits, &p->rate, sizeof rate_bits); - return p->seq ^ (uint64_t) p->universe_ns ^ (uint64_t) p->anchor_ns ^ rate_bits ^ p->armed ^ p->generation - ^ (uint64_t) p->mono_universe_ns ^ (uint64_t) p->mono_anchor_ns ^ 0x9E3779B97F4A7C15ull; + return p->seq ^ (uint64_t) p->universe_s ^ ((uint64_t) p->universe_nsec << 32) ^ (uint64_t) p->anchor_ns ^ rate_bits + ^ p->armed ^ p->generation ^ (uint64_t) p->mono_universe_ns ^ (uint64_t) p->mono_anchor_ns + ^ 0x9E3779B97F4A7C15ull; } static bool ft_page_snapshot(struct ft_clock_page *out) @@ -226,7 +229,8 @@ static bool ft_page_snapshot(struct ft_clock_page *out) if (s1 & 1) continue; out->magic = ft_page->magic; out->seq = s1; - out->universe_ns = ft_page->universe_ns; + out->universe_s = ft_page->universe_s; + out->universe_nsec = ft_page->universe_nsec; out->anchor_ns = ft_page->anchor_ns; out->rate = ft_page->rate; out->armed = ft_page->armed; @@ -237,7 +241,7 @@ static bool ft_page_snapshot(struct ft_clock_page *out) out->mono_anchor_ns = ft_page->mono_anchor_ns; __atomic_thread_fence(__ATOMIC_ACQUIRE); if (__atomic_load_n(&ft_page->seq, __ATOMIC_RELAXED) == s1 && out->magic == FT_PAGE_MAGIC - && out->version == FT_PAGE_VERSION + && out->version == FT_PAGE_VERSION && out->universe_nsec < 1000000000u && ft_page_check(out) == out->check) return true; } @@ -272,17 +276,67 @@ static void ft_page_open(void) ft_page = map; } +/* the universe's realtime at real realtime t (ns): seconds and nanoseconds (0 to 999,999,999); before the anchor, and + while frozen, the anchor's. Clock reads and every wait compute it here alike, so a wait never ends before a read + shows its deadline. */ +static inline void ft_page_at(const struct ft_clock_page *s, int64_t t, int64_t *sec, int64_t *nsec) +{ + int64_t add, q, r; + *sec = s->universe_s; + *nsec = s->universe_nsec; + if (s->rate == 0 || t <= s->anchor_ns) return; + if (s->rate == 1.0) + add = t - s->anchor_ns; + else + { + double x = (double) (t - s->anchor_ns) * s->rate; + if (x >= 9e18 || x <= -9e18) + { /* centuries of universe since the anchor: whole seconds */ + *sec += (int64_t) (x / 1e9); + return; + } + add = (int64_t) x; + } + q = add / 1000000000LL; + r = add % 1000000000LL; + if (r < 0) + { + q -= 1; + r += 1000000000LL; + } + *sec += q; + *nsec += r; + if (*nsec >= 1000000000LL) + { + *sec += 1; + *nsec -= 1000000000LL; + } +} + +/* a time as libfaketime reads one: "seconds.nanoseconds", the sign written once in front. */ +static void ft_spec_time(char *out, size_t size, int64_t s, uint32_t ns) +{ + if (s < 0 && ns > 0) + snprintf(out, size, "-%llu.%09u", (unsigned long long) -(s + 1), 1000000000u - ns); + else + snprintf(out, size, "%s%llu.%09u", s < 0 ? "-" : "", (unsigned long long) (s < 0 ? -s : s), ns); +} + /* libfaketime's own state set to the page's clock; called with the MT lock held. */ static void ft_page_apply_locked(const struct ft_clock_page *s) { - char spec[160]; + char spec[160], universe[48], anchor[48]; if (s->generation == ft_page_applied) return; if (!s->armed) snprintf(spec, sizeof spec, "+0 x1"); else - snprintf(spec, sizeof spec, "@%lld.%09lld x%.17g ^%lld.%09lld", - (long long) (s->universe_ns / 1000000000LL), (long long) (s->universe_ns % 1000000000LL), s->rate, - (long long) (s->anchor_ns / 1000000000LL), (long long) (s->anchor_ns % 1000000000LL)); + { + int64_t anchor_ns = s->anchor_ns; + int64_t anchor_s = anchor_ns / 1000000000LL - (anchor_ns % 1000000000LL < 0); + ft_spec_time(universe, sizeof universe, s->universe_s, s->universe_nsec); + ft_spec_time(anchor, sizeof anchor, anchor_s, (uint32_t) (anchor_ns - anchor_s * 1000000000LL)); + snprintf(spec, sizeof spec, "@%s x%.17g ^%s", universe, s->rate, anchor); + } parse_ft_string(spec); __atomic_store_n(&ft_page_applied, s->generation, __ATOMIC_RELEASE); } diff --git a/src/agent_env/utils/faketime_clock/agentenv_clock_waits.c b/src/agent_env/utils/faketime_clock/agentenv_clock_waits.c index 5d8237705..aae429693 100644 --- a/src/agent_env/utils/faketime_clock/agentenv_clock_waits.c +++ b/src/agent_env/utils/faketime_clock/agentenv_clock_waits.c @@ -56,6 +56,9 @@ static long ft_raw_syscall6(long n, long a, long b, long c, long d, long e, long #define FT_NS 1000000000LL #define FT_NEVER INT64_MAX +/* a universe time in nanoseconds: 128 bits, so it reaches any date a 64-bit time_t holds (64 bits run out in 2262). + Real times, and elapsed and universe durations, stay 64-bit. */ +typedef __int128 ft_uns_t; static __thread struct ft_clock_page ft_tl_snap; static __thread bool ft_tl_snap_ok = false; @@ -140,6 +143,19 @@ static inline int64_t ft_ns(const struct timespec *t) if (t->tv_sec < -9000000000LL) return -(FT_NEVER / 2); return (int64_t) t->tv_sec * FT_NS + t->tv_nsec; } +static inline ft_uns_t ft_uns(const struct timespec *t) +{ + return (ft_uns_t) t->tv_sec * FT_NS + t->tv_nsec; +} +static inline ft_uns_t ft_page_universe(const struct ft_clock_page *s) +{ + return (ft_uns_t) s->universe_s * FT_NS + s->universe_nsec; +} +/* a universe duration as 64 bits, saturated. */ +static inline int64_t ft_clamp64(ft_uns_t v) +{ + return v > (ft_uns_t) FT_NEVER ? FT_NEVER : v < -(ft_uns_t) FT_NEVER ? -FT_NEVER : (int64_t) v; +} static inline struct timespec ft_ts(int64_t ns) { struct timespec t; @@ -177,26 +193,27 @@ static inline bool ft_universe_clock(clockid_t c) } /* the universe's realtime at real realtime t; before the anchor, the anchor's. */ -static int64_t ft_page_rt(const struct ft_clock_page *s, int64_t t) +static ft_uns_t ft_page_rt(const struct ft_clock_page *s, int64_t t) { + int64_t sec, nsec; if (!s->armed) return t; - if (s->rate == 0 || t <= s->anchor_ns) return s->universe_ns; - if (s->rate == 1.0) return s->universe_ns + (t - s->anchor_ns); - return s->universe_ns + (int64_t) ((double) (t - s->anchor_ns) * s->rate); + ft_page_at(s, t, &sec, &nsec); + return (ft_uns_t) sec * FT_NS + nsec; } /* the real realtime at which the universe reaches ``due``; 0 (the past) once it has, FT_NEVER while frozen short of it. */ -static int64_t ft_real_of(const struct ft_clock_page *s, int64_t due) +static int64_t ft_real_of(const struct ft_clock_page *s, ft_uns_t due) { + ft_uns_t u = ft_page_universe(s); double r; - if (!s->armed) return due < 1 ? 1 : due; - if (due <= s->universe_ns) return 1; + if (!s->armed) return due < 1 ? 1 : ft_clamp64(due); + if (due <= u) return 1; if (s->rate <= 0) return FT_NEVER; - r = (double) (due - s->universe_ns) / s->rate; + r = (double) (due - u) / s->rate; if (r > 4e18) return FT_NEVER; return s->anchor_ns + (int64_t) r + 1; } -static inline bool ft_reached(const struct ft_clock_page *s, int64_t due) +static inline bool ft_reached(const struct ft_clock_page *s, ft_uns_t due) { return ft_page_rt(s, ft_real_rt()) >= due; } @@ -236,7 +253,8 @@ struct ft_timer int clock; int flags; /* the caller's flags, TFD_TIMER_CANCEL_ON_SET kept */ int real_set; /* the kernel timer is armed */ - int64_t due, interval; /* universe ns */ + ft_uns_t due; /* universe ns */ + int64_t interval; /* universe ns */ struct ft_clock_page pg; /* the page it was last armed from */ }; #define FT_TIMERS_MAX 1024 @@ -280,9 +298,9 @@ static int ft_timer_real_get(struct ft_timer *t, struct itimerspec *cur) return t->kind == 1 ? (*real_timerfd_gettime)(t->fds[0], cur) : (*real_timer_gettime_new)(t->id, cur); } /* the next expiration at or after ``after``. */ -static int64_t ft_timer_next(const struct ft_timer *t, int64_t after) +static ft_uns_t ft_timer_next(const struct ft_timer *t, ft_uns_t after) { - int64_t next = t->due; + ft_uns_t next = t->due; if (t->interval > 0 && next < after) next += ((after - next + t->interval - 1) / t->interval) * t->interval; return next; } @@ -292,7 +310,8 @@ static int ft_timer_arm(struct ft_timer *t, const struct ft_clock_page *s, bool { struct itimerspec real, cur; double rate = s->armed ? s->rate : 1.0; - int64_t next = t->due, at; + ft_uns_t next = t->due; + int64_t at; int r; memset(&real, 0, sizeof real); if (!first && t->real_set && t->interval == 0 && ft_timer_real_get(t, &cur) == 0 && cur.it_value.tv_sec == 0 @@ -339,8 +358,8 @@ static void ft_timer_value(struct ft_timer *t, struct itimerspec *out) out->it_interval = ft_ts(t->interval); if (ft_snap(&s)) { - int64_t now = ft_page_rt(&s, ft_real_rt()), next = ft_timer_next(t, now); - out->it_value = ft_ts(next - now < 1 ? 1 : next - now); + ft_uns_t now = ft_page_rt(&s, ft_real_rt()), next = ft_timer_next(t, now); + out->it_value = ft_ts(next - now < 1 ? 1 : ft_clamp64(next - now)); } } @@ -354,7 +373,8 @@ struct ft_cw { pthread_cond_t *cond; int used, woken; - int64_t due, real_due; + ft_uns_t due; + int64_t real_due; uint64_t gen; /* the page generation its real_due came from; FT_CW_UNPLANNED before */ }; #define FT_CW_MAX 512 @@ -501,7 +521,7 @@ static inline void ft_deferred_cancel(int old) } /* a sleep until the universe reaches ``due``, on the page's seq. 0, or EINTR. */ -static int ft_rt_sleep(const struct ft_clock_page *first, int64_t due) +static int ft_rt_sleep(const struct ft_clock_page *first, ft_uns_t due) { struct ft_clock_page s = *first; pthread_testcancel(); @@ -575,7 +595,7 @@ static int ft_wait2(uint32_t *word, uint32_t val, bool private_word, uint32_t se static long ft_u_futex_rt(uint32_t *uaddr, int op, uint32_t val, const struct timespec *abs, bool *handled) { struct ft_clock_page s; - int64_t due = ft_ns(abs); + ft_uns_t due = ft_uns(abs); *handled = false; if (!ft_snap(&s)) return 0; *handled = true; @@ -619,7 +639,7 @@ static void ft_sem_unwait(void *sem) } /* as one of the semaphore's waiters (counted in data's high word): 0 with a token taken, or the error. A cancelled wait leaves the waiters it joined, as glibc's does. */ -static int ft_sem_wait_slow(struct ft_new_sem *sem, struct ft_clock_page *s, int64_t due) +static int ft_sem_wait_slow(struct ft_new_sem *sem, struct ft_clock_page *s, ft_uns_t due) { volatile int err = 0; pthread_cleanup_push(ft_sem_unwait, sem); @@ -656,7 +676,7 @@ static int ft_sem_wait_slow(struct ft_new_sem *sem, struct ft_clock_page *s, int pthread_cleanup_pop(err != 0); return err; } -static int ft_u_sem_wait(sem_t *sem_, int64_t due, bool *handled) +static int ft_u_sem_wait(sem_t *sem_, ft_uns_t due, bool *handled) { struct ft_new_sem *sem = (struct ft_new_sem *) sem_; struct ft_clock_page s; @@ -700,7 +720,8 @@ static int ft_u_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex, const st struct ft_cw *w = NULL; struct timespec end; sigset_t old; - int64_t due = ft_ns(abstime), real_due; + ft_uns_t due = ft_uns(abstime); + int64_t real_due; int r, woken; if (!ft_snap(&s)) return -1; if (ft_reached(&s, due)) return ETIMEDOUT; @@ -744,7 +765,7 @@ static int ft_u_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex, const st /* a realtime mutex wait: glibc's mutex has no way in, so slices (AGENTENV_WAIT_SLICE_MS) of a real CLOCK_MONOTONIC wait, which loses nothing when it times out, with the page read between them. */ -static int ft_u_mutex_lock(pthread_mutex_t *mutex, int64_t due, bool *handled) +static int ft_u_mutex_lock(pthread_mutex_t *mutex, ft_uns_t due, bool *handled) { struct ft_clock_page s; *handled = false; @@ -846,7 +867,7 @@ static int ft_u_timerfd_settime(int fd, int flags, const struct itimerspec *nv, } t->clock = clock; t->flags = flags; - t->due = ft_ns(&nv->it_value); + t->due = ft_uns(&nv->it_value); t->interval = ft_ns(&nv->it_interval); t->tracked = 1; if (ov != NULL) @@ -1144,7 +1165,7 @@ int timer_settime(timer_t id, int flags, const struct itimerspec *nv, struct iti else (*real_timer_gettime_new)(id, ov); } - t->due = ft_ns(&nv->it_value); + t->due = ft_uns(&nv->it_value); t->interval = ft_ns(&nv->it_interval); t->tracked = 1; r = ft_timer_arm(t, &s, true); diff --git a/src/agent_env/utils/faketime_clock/clockpage.py b/src/agent_env/utils/faketime_clock/clockpage.py index 4002bb6c2..72c238b69 100644 --- a/src/agent_env/utils/faketime_clock/clockpage.py +++ b/src/agent_env/utils/faketime_clock/clockpage.py @@ -1,5 +1,6 @@ -"""The follower's side of the clock page (version 2) and of the clock file: writes the universe's realtime -clock to both. Elapsed time is real, so the page's monotonic fields are written as the real monotonic clock (identity) +"""The follower's side of the clock page (version 3) and of the clock file: writes the universe's realtime +clock to both. The page holds the universe at the anchor as whole seconds and nanoseconds, so it reaches any date the +gateway's clock takes (to 9999-12-31); version 2's one signed 64-bit count of nanoseconds ran out on 2262-04-11. Elapsed time is real, so the page's monotonic fields are written as the real monotonic clock (identity) and no library reads them; they stay so the page keeps its 80-byte layout. clockpage.py set UNIVERSE RATE [ANCHOR] armed: UNIVERSE (epoch s) at real time ANCHOR (default now), at RATE @@ -30,9 +31,12 @@ PAGE = os.environ.get("AGENTENV_CLOCK_PAGE", "/dev/shm/agentenv-clock") FILE = os.environ.get("AGENTENV_CLOCK_FILE", "/run/agentenv-clock/clock") -MAGIC, VERSION = 0x4B434541, 2 -# magic version seq universe_ns anchor_ns rate armed reserved generation check mono_universe_ns mono_anchor_ns +MAGIC, VERSION = 0x4B434541, 3 +# magic version seq universe_s anchor_ns rate armed universe_nsec generation check mono_universe_ns mono_anchor_ns: +# the universe at the anchor is universe_s seconds and universe_nsec (0 to 999,999,999) nanoseconds, floored, so a time +# before 1970 has negative seconds and positive nanoseconds; the anchor is this machine's real time. LAYOUT = struct.Struct(" int: +def check(seq, universe_s, universe_nsec, anchor_ns, rate, armed, generation, mono_universe_ns, mono_anchor_ns) -> int: rate_bits = struct.unpack(" bytes: - """The page's bytes for these fields, its check among them: what every write writes and every reader checks, - agent-env's libfaketime and the egress proxy (its egress/testdata pins them).""" - return LAYOUT.pack(MAGIC, VERSION, seq, universe_ns, anchor_ns, rate, armed, 0, generation, - check(seq, universe_ns, anchor_ns, rate, armed, generation, mono_universe_ns, mono_anchor_ns), + """The page's bytes for these fields, the universe given in nanoseconds of any size, its check among them: what + every write writes and every reader checks, agent-env's libfaketime and the egress proxy (its egress/testdata pins + them).""" + universe_s, universe_nsec = divmod(universe_ns, NS) + return LAYOUT.pack(MAGIC, VERSION, seq, universe_s, anchor_ns, rate, armed, universe_nsec, generation, + check(seq, universe_s, universe_nsec, anchor_ns, rate, armed, generation, mono_universe_ns, + mono_anchor_ns), mono_universe_ns, mono_anchor_ns) +def read(raw: bytes) -> tuple | None: + """A page's (seq, armed, universe_ns, anchor_ns, rate, generation), or None while it's being written, torn, or not a + version 3 page.""" + if len(raw) < LAYOUT.size: + return None + magic, version, seq, universe_s, anchor_ns, rate, armed, universe_nsec, generation, checked, mono_u, mono_a = \ + LAYOUT.unpack(raw[:LAYOUT.size]) + if (magic, version) != (MAGIC, VERSION) or seq & 1 or universe_nsec >= NS or checked != check( + seq, universe_s, universe_nsec, anchor_ns, rate, armed, generation, mono_u, mono_a): + return None + return seq, armed, universe_s * NS + universe_nsec, anchor_ns, rate, generation + + +def spec(armed: int, universe_ns: int, rate: float, anchor_ns: int) -> str: + """libfaketime's specification of this clock, exact at any date: "@seconds.nanoseconds", the sign written once in + front, as libfaketime reads a time before 1970.""" + if not armed: + return "+0 x1" + return f"@{_seconds(universe_ns)} x{rate:g} ^{_seconds(anchor_ns)}" + + +def _seconds(ns: int) -> str: + whole, part = divmod(abs(ns), NS) + return f"{'-' if ns < 0 else ''}{whole}.{part:09d}" + + def open_page() -> mmap.mmap: try: fd = os.open(PAGE, os.O_RDWR | os.O_CREAT | os.O_EXCL, 0o644) @@ -64,7 +97,7 @@ def open_page() -> mmap.mmap: fd = os.open(PAGE, os.O_RDWR) if os.fstat(fd).st_uid != os.getuid(): raise SystemExit(f"{PAGE} isn't ours") - if os.fstat(fd).st_size < LAYOUT.size: + if os.fstat(fd).st_size < LAYOUT.size or os.pread(fd, 8, 0) != struct.pack(" int: def write(armed: int, universe: float, rate: float, anchor: float) -> dict: m = open_page() - _, _, seq, o_u, o_a, o_rate, o_armed, _, generation, _, _, _ = LAYOUT.unpack(m[:LAYOUT.size]) - universe_ns, anchor_ns = int(Decimal(str(universe)) * 10**9), int(Decimal(str(anchor)) * 10**9) + _, _, seq, o_us, o_a, o_rate, o_armed, o_unsec, generation, _, _, _ = LAYOUT.unpack(m[:LAYOUT.size]) + o_u = o_us * NS + o_unsec + universe_ns, anchor_ns = int(Decimal(str(universe)) * NS), int(Decimal(str(anchor)) * NS) if not armed: rate = 1.0 generation += 1 @@ -115,12 +149,12 @@ def write(armed: int, universe: float, rate: float, anchor: float) -> dict: m[8:16] = struct.pack(" 1 else 0, + return {"generation": generation, "spec": written, "jump_ns": new_now - old_now if generation > 1 else 0, "continued": bool(continued), "universe_ns": universe_ns, "anchor_ns": anchor_ns} @@ -130,7 +164,9 @@ def create(owner: str) -> None: try: st = os.lstat(PAGE) if stat.S_ISREG(st.st_mode) and st.st_uid == user.pw_uid and st.st_size == LAYOUT.size: - return + with open(PAGE, "rb") as f: + if f.read(8) == struct.pack(" None: print(write(0, 0.0, 1.0, time.time())) else: with open(PAGE, "rb") as f: - print(LAYOUT.unpack(f.read(LAYOUT.size))) + print(read(f.read(LAYOUT.size))) diff --git a/src/agent_env/utils/faketime_clock/libfaketime.patch b/src/agent_env/utils/faketime_clock/libfaketime.patch index 17555d2b8..458798e09 100644 --- a/src/agent_env/utils/faketime_clock/libfaketime.patch +++ b/src/agent_env/utils/faketime_clock/libfaketime.patch @@ -167,7 +167,7 @@ diff -ruN a/src/libfaketime.c b/src/libfaketime.c + if (ft_uw_active() && ft_valid_ts(req)) + { + struct ft_clock_page s; -+ if (ft_snap(&s)) return ft_rt_sleep(&s, ft_ns(req)); ++ if (ft_snap(&s)) return ft_rt_sleep(&s, ft_uns(req)); + } if (real_clock_nanosleep == NULL) { @@ -356,7 +356,7 @@ diff -ruN a/src/libfaketime.c b/src/libfaketime.c - DONT_FAKE_TIME(result = (*real_sem_clockwait)(sem, clockid, abstime)); - return result; + bool handled; -+ result = ft_u_sem_wait(sem, ft_ns(abs_timeout), &handled); ++ result = ft_u_sem_wait(sem, ft_uns(abs_timeout), &handled); + if (handled) return result; } - @@ -402,7 +402,7 @@ diff -ruN a/src/libfaketime.c b/src/libfaketime.c - } - real_abstime_pt = &real_abstime; + bool handled; -+ result = ft_u_sem_wait(sem, ft_ns(abstime), &handled); ++ result = ft_u_sem_wait(sem, ft_uns(abstime), &handled); + if (handled) return result; } - else @@ -992,7 +992,7 @@ diff -ruN a/src/libfaketime.c b/src/libfaketime.c if ((faketimerc = open(custom_filename, O_RDONLY)) != -1 || (faketimerc = open(filename, O_RDONLY)) != -1 || (faketimerc = open("/etc/faketimerc", O_RDONLY)) != -1) -@@ -3248,6 +3277,48 @@ +@@ -3248,6 +3277,38 @@ tp_save.tv_nsec = tp->tv_nsec; if (dont_fake) return 0; @@ -1020,20 +1020,10 @@ diff -ruN a/src/libfaketime.c b/src/libfaketime.c + ft_tl_scale = (s.armed && s.rate > 0) ? 1.0 / s.rate : 1.0; + if (s.armed) + { -+ int64_t now = (int64_t) tp->tv_sec * 1000000000LL + tp->tv_nsec, fake; -+ if (s.rate == 0 || now <= s.anchor_ns) -+ fake = s.universe_ns; -+ else if (s.rate == 1.0) -+ fake = s.universe_ns + (now - s.anchor_ns); -+ else -+ fake = s.universe_ns + (int64_t) ((double) (now - s.anchor_ns) * s.rate); -+ tp->tv_sec = fake / 1000000000LL; -+ tp->tv_nsec = fake % 1000000000LL; -+ if (tp->tv_nsec < 0) -+ { -+ tp->tv_sec -= 1; -+ tp->tv_nsec += 1000000000LL; -+ } ++ int64_t now = (int64_t) tp->tv_sec * 1000000000LL + tp->tv_nsec, sec, nsec; ++ ft_page_at(&s, now, &sec, &nsec); ++ tp->tv_sec = (time_t) sec; ++ tp->tv_nsec = (long) nsec; + } + return 0; + } @@ -1394,7 +1384,7 @@ diff -ruN a/src/libfaketime.c b/src/libfaketime.c + if (ft_uw_active() && ft_translates_wait(abstime) && real_pthread_mutex_clocklock != NULL) + { + bool handled; -+ int r = ft_u_mutex_lock(mutex, ft_ns(abstime), &handled); ++ int r = ft_u_mutex_lock(mutex, ft_uns(abstime), &handled); + if (handled) return r; + } + if (!ft_translates_wait(abstime) || real_pthread_mutex_clocklock == NULL) @@ -1411,7 +1401,7 @@ diff -ruN a/src/libfaketime.c b/src/libfaketime.c + if (ft_uw_active() && ft_translates_wait(abstime) && clockid == CLOCK_REALTIME) + { + bool handled; -+ int r = ft_u_mutex_lock(mutex, ft_ns(abstime), &handled); ++ int r = ft_u_mutex_lock(mutex, ft_uns(abstime), &handled); + if (handled) return r; + } + if (clockid != CLOCK_REALTIME || !ft_translates_wait(abstime)) diff --git a/tst/clock/harness.py b/tst/clock/harness.py index 1bd599966..6b831b715 100644 --- a/tst/clock/harness.py +++ b/tst/clock/harness.py @@ -72,11 +72,11 @@ def user_cmd(argv, env=None): def page(): with open(clockpage.PAGE, "rb") as f: - return clockpage.LAYOUT.unpack(f.read(clockpage.LAYOUT.size)) + return clockpage.read(f.read(clockpage.LAYOUT.size)) def universe_now() -> tuple[float, float]: - _, _, _, u, a, rate, armed, _, _, _, _, _ = page() + _, armed, u, a, rate, _ = page() now = time.time() return (now, 1.0) if not armed else (u / 1e9 + (now - a / 1e9) * rate, rate) @@ -97,6 +97,13 @@ def set_rate(rate: float) -> dict: return set_clock(u, rate) +def start(days: float = -182) -> float: + """The universe a gate starts at: ``days`` from now, or the time CLOCK_BASE names (epoch seconds), which runs the + gates far past 2262, or before 1970, as well.""" + base = os.environ.get("CLOCK_BASE") + return float(base) if base else time.time() + days * DAY + + def fresh_page() -> None: if os.path.exists(clockpage.PAGE): os.remove(clockpage.PAGE) @@ -182,7 +189,7 @@ def result(p, change=None) -> dict: def scenario(name, start_rate, seconds, change=None, change_at=None, limit=8.0, start_universe=None, apis=APIS): - set_clock(start_universe if start_universe is not None else time.time() - 180 * DAY, start_rate) + set_clock(start_universe if start_universe is not None else start(-180), start_rate) t0 = raw() procs = [spawn(a, seconds) for a in apis] ran = collect(procs, t0 + limit, [(t0 + change_at, change, "change")] if change else []) @@ -208,7 +215,7 @@ def ratechange(): clock = [a for a in APIS if a in CLOCK_TIME] out = [scenario("rate 1, rate 60 at 1.0 s", 1, 10.0, lambda: set_rate(60), 1.0, limit=4.0, apis=clock), scenario("rate 1, set_time -182 d at 0.5 s", 1, 2.0, lambda: set_clock(universe_now()[0] - 182 * DAY, 1), - 0.5, limit=4.0, start_universe=time.time(), apis=clock)] + 0.5, limit=4.0, start_universe=start(0), apis=clock)] preload(None) return out @@ -219,7 +226,7 @@ def jumps(rounds=30, seed=5420): rng = random.Random(seed) preload() fresh_page() - set_clock(time.time() - 182 * DAY, 1) + set_clock(start(), 1) p = subprocess.Popen(user_cmd(["jumpwaits"]), stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True, bufsize=1, cwd="/tmp") out = [] @@ -284,7 +291,7 @@ def cancel(): keeps no waiter for one, and after 600 cancelled condvar waits a condvar wait still ends at a jump past its deadline.""" preload() fresh_page() - set_clock(time.time() - 182 * DAY, 1) + set_clock(start(), 1) r = _jumped(["cancel"], 2 * 3600) preload(None) return {**r["before"], "rc": r["after"]["rc"], **_after_write(r["after"]["fired_raw"], r)} @@ -295,7 +302,7 @@ def timerfds(): ones where a vfork child (Python's subprocess among them, tfdspawn.py) closes it, each jumped 2 h.""" preload() fresh_page() - set_clock(time.time() - 182 * DAY, 1) + set_clock(start(), 1) out = {} for how in ("dup", "dup2", "dup3", "fcntl", "close_range", "failed", "vfork_close", "vfork_close_range", "python_subprocess"): @@ -326,7 +333,7 @@ def condstress(seconds=10.0): for gap in (1000, 100000): for changes in (False, True): fresh_page() - set_clock(time.time() - 182 * DAY, 1) + set_clock(start(), 1) p = subprocess.Popen(user_cmd(["condstress2", "stress", str(seconds), str(gap)]), stdout=subprocess.PIPE, text=True) n = _with_page_changes(p) if changes else 0 @@ -335,7 +342,7 @@ def condstress(seconds=10.0): def single(wait_s, label, during=None): fresh_page() - set_clock(time.time() - 182 * DAY, 1) + set_clock(start(), 1) p = subprocess.Popen(user_cmd(["condstress2", "single", "20", str(wait_s)]), stdout=subprocess.PIPE, text=True) writes = during(p) if during else 0 o, _ = p.communicate(timeout=120) @@ -366,7 +373,7 @@ def semstress(seconds=10.0): for gap in (1000, 100000): for changes in (False, True): fresh_page() - set_clock(time.time() - 182 * DAY, 1) + set_clock(start(), 1) p = subprocess.Popen(user_cmd(["semstress", str(seconds), str(gap)]), stdout=subprocess.PIPE, text=True) n = _with_page_changes(p) if changes else 0 o, _ = p.communicate(timeout=seconds + 60) @@ -391,7 +398,7 @@ def clock_gettime_ns(self, clock): preload() fresh_page() - set_clock(time.time() - 182 * DAY, 1) + set_clock(start(), 1) seconds = writes * 0.0055 + 2 readers = [subprocess.Popen(user_cmd(["rtread", str(seconds), "1", f"/tmp/rtread_{k}.json"]), cwd="/tmp") for k in range(4)] @@ -417,11 +424,13 @@ def clock_gettime_ns(self, clock): def torn(seconds=10.0): - """The page rewritten as fast as possible, alternating universes 182 days back and 21 days ahead, while 4 threads - read CLOCK_REALTIME as fast as they can: every read must be one of the two (torn.c).""" + """The page rewritten as fast as possible, alternating universes 182 days back and 21 days ahead (or the start and + 203 days after it), while 4 threads read CLOCK_REALTIME as fast as they can: every read must be one of the two + (torn.c).""" preload() fresh_page() - off_a, off_b = -182 * DAY, 21 * DAY + off_a = start() - time.time() + off_b = off_a + 203 * DAY set_clock(time.time() + off_a, 1) p = subprocess.Popen(user_cmd(["torn", str(seconds), "4", str(off_a), str(off_b)]), stdout=subprocess.PIPE, text=True, cwd="/tmp") @@ -448,7 +457,7 @@ def deadwriter(): written = set_clock(time.time() + 21 * DAY, 1) after = float(subprocess.run(user_cmd(["date", "+%s.%N"]), capture_output=True, text=True).stdout) preload(None) - return {"dead_seq": seq, "seq": page()[2], "continued": written["continued"], + return {"dead_seq": seq, "seq": page()[0], "continued": written["continued"], "read": _classify(after, before, 21 * DAY)} @@ -525,7 +534,7 @@ def chromium(variant="agentenv", launches=40, parallel=8, limit=20.0): f.write(f"@{int(time.time() - 182 * DAY)}\n") os.chmod("/tmp/stockclock", 0o644) fresh_page() - set_clock(time.time() - 182 * DAY, 1) + set_clock(start(), 1) preload(LIB if variant == "agentenv" else None) def launch(k: int) -> dict: diff --git a/tst/clock/programs/cancel.c b/tst/clock/programs/cancel.c index 7140d30db..409a166fa 100644 --- a/tst/clock/programs/cancel.c +++ b/tst/clock/programs/cancel.c @@ -14,12 +14,13 @@ #include #include #include +#include "rtbase.h" #define CONDS 600 static int64_t ns(clockid_t c) { struct timespec t; clock_gettime(c, &t); return (int64_t)t.tv_sec * 1000000000LL + t.tv_nsec; } static struct timespec ts_of(int64_t v) { struct timespec t = {v / 1000000000LL, v % 1000000000LL}; return t; } -static struct timespec hour_ahead(void) { return ts_of(ns(CLOCK_REALTIME) + 3600000000000LL); } +static struct timespec hour_ahead(void) { return rt_ts(rt_ns() + 3600000000000LL); } static sem_t sem; static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER; @@ -76,6 +77,7 @@ static long misaligned(double *ms) { } int main(void) { + rt_ns(); int sem_ok, cns_ok, cond_ok = 0; uint64_t waiters; double ms; diff --git a/tst/clock/programs/jumpwaits.c b/tst/clock/programs/jumpwaits.c index 19e98b970..3242ae43b 100644 --- a/tst/clock/programs/jumpwaits.c +++ b/tst/clock/programs/jumpwaits.c @@ -21,6 +21,7 @@ #include #include #include +#include "rtbase.h" static int64_t ns(clockid_t c) { struct timespec t; clock_gettime(c, &t); return (int64_t)t.tv_sec * 1000000000LL + t.tv_nsec; } static struct timespec ts_of(int64_t v) { struct timespec t = {v / 1000000000LL, v % 1000000000LL}; return t; } @@ -47,7 +48,7 @@ static void on_thread_timer(union sigval v) { sem_post((sem_t *)v.sival_ptr); } static long tfd_wait(int64_t due, int how) { int fd = timerfd_create(CLOCK_REALTIME, 0); unsigned long long n = 0; - struct itimerspec it = {{0, 0}, ts_of(due)}; + struct itimerspec it = {{0, 0}, rt_ts(due)}; if (timerfd_settime(fd, TFD_TIMER_ABSTIME, &it, NULL)) return errno; __atomic_add_fetch(&ready, 1, __ATOMIC_SEQ_CST); if (how == 1) { struct pollfd p = {fd, POLLIN, 0}; poll(&p, 1, -1); } @@ -60,7 +61,7 @@ static long ptimer_thread(int64_t due) { sem_t s; sem_init(&s, 0, 0); timer_t id; struct sigevent sev = {.sigev_notify = SIGEV_THREAD}; sev.sigev_notify_function = on_thread_timer; sev.sigev_value.sival_ptr = &s; if (timer_create(CLOCK_REALTIME, &sev, &id)) return -errno; - struct itimerspec it = {{0, 0}, ts_of(due)}; + struct itimerspec it = {{0, 0}, rt_ts(due)}; if (timer_settime(id, TIMER_ABSTIME, &it, NULL)) return -errno; __atomic_add_fetch(&ready, 1, __ATOMIC_SEQ_CST); while (sem_wait(&s) != 0) ; @@ -68,10 +69,10 @@ static long ptimer_thread(int64_t due) { return 0; } static long cond_loop(pthread_cond_t *c, int64_t due) { - struct timespec t = ts_of(due); long n = 0; + struct timespec t = rt_ts(due); long n = 0; pthread_mutex_lock(&m); __atomic_add_fetch(&ready, 1, __ATOMIC_SEQ_CST); - for (;;) { int r = pthread_cond_timedwait(c, &m, &t); n++; if (r == ETIMEDOUT || ns(CLOCK_REALTIME) >= due) break; } + for (;;) { int r = pthread_cond_timedwait(c, &m, &t); n++; if (r == ETIMEDOUT || rt_ns() >= due) break; } pthread_mutex_unlock(&m); return n; /* calls it took */ } @@ -79,7 +80,7 @@ static long cond_loop(pthread_cond_t *c, int64_t due) { static void *run(void *arg) { struct waiter *w = arg; long r = 0; struct timespec t; uint32_t word = 0; const char *n = w->name; - if (!strcmp(n, "cns_in") || !strcmp(n, "cns_after")) { t = ts_of(w->kind == IN ? D_in : D_after); __atomic_add_fetch(&ready, 1, __ATOMIC_SEQ_CST); r = clock_nanosleep(CLOCK_REALTIME, TIMER_ABSTIME, &t, NULL); } + if (!strcmp(n, "cns_in") || !strcmp(n, "cns_after")) { t = rt_ts(w->kind == IN ? D_in : D_after); __atomic_add_fetch(&ready, 1, __ATOMIC_SEQ_CST); r = clock_nanosleep(CLOCK_REALTIME, TIMER_ABSTIME, &t, NULL); } else if (!strcmp(n, "tfd_poll_in")) r = tfd_wait(D_in, 1); else if (!strcmp(n, "tfd_poll_after")) r = tfd_wait(D_after, 1); else if (!strcmp(n, "tfd_read_in")) r = tfd_wait(D_in, 0); @@ -90,16 +91,16 @@ static void *run(void *arg) { sigset_t set; sigemptyset(&set); sigaddset(&set, SIGRTMIN + 1); timer_t id; siginfo_t si; struct sigevent sev = {.sigev_notify = SIGEV_THREAD_ID, .sigev_signo = SIGRTMIN + 1}; sev._sigev_un._tid = gettid(); if (timer_create(CLOCK_REALTIME, &sev, &id)) r = -errno; - else { struct itimerspec it = {{0, 0}, ts_of(D_in)}; timer_settime(id, TIMER_ABSTIME, &it, NULL); __atomic_add_fetch(&ready, 1, __ATOMIC_SEQ_CST); + else { struct itimerspec it = {{0, 0}, rt_ts(D_in)}; timer_settime(id, TIMER_ABSTIME, &it, NULL); __atomic_add_fetch(&ready, 1, __ATOMIC_SEQ_CST); r = sigwaitinfo(&set, &si) == SIGRTMIN + 1 ? 0 : -errno; timer_delete(id); } } - else if (!strcmp(n, "cond_rt_in")) { t = ts_of(D_in); pthread_mutex_lock(&m); __atomic_add_fetch(&ready, 1, __ATOMIC_SEQ_CST); r = pthread_cond_timedwait(&c_rt, &m, &t); pthread_mutex_unlock(&m); } - else if (!strcmp(n, "cond_clock_rt_in")) { t = ts_of(D_in); pthread_mutex_lock(&m); __atomic_add_fetch(&ready, 1, __ATOMIC_SEQ_CST); r = pthread_cond_clockwait(&c_rt2, &m, CLOCK_REALTIME, &t); pthread_mutex_unlock(&m); } + else if (!strcmp(n, "cond_rt_in")) { t = rt_ts(D_in); pthread_mutex_lock(&m); __atomic_add_fetch(&ready, 1, __ATOMIC_SEQ_CST); r = pthread_cond_timedwait(&c_rt, &m, &t); pthread_mutex_unlock(&m); } + else if (!strcmp(n, "cond_clock_rt_in")) { t = rt_ts(D_in); pthread_mutex_lock(&m); __atomic_add_fetch(&ready, 1, __ATOMIC_SEQ_CST); r = pthread_cond_clockwait(&c_rt2, &m, CLOCK_REALTIME, &t); pthread_mutex_unlock(&m); } else if (!strcmp(n, "cond_loop_in")) r = cond_loop(&c_rt3, D_in); else if (!strcmp(n, "cond_loop_after")) r = cond_loop(&c_rt4, D_after); - else if (!strcmp(n, "sem_rt_in")) { t = ts_of(D_in); __atomic_add_fetch(&ready, 1, __ATOMIC_SEQ_CST); r = sem_timedwait(&sem, &t) ? errno : 0; } - else if (!strcmp(n, "futex_rt_in")) { t = ts_of(D_in); __atomic_add_fetch(&ready, 1, __ATOMIC_SEQ_CST); r = syscall(SYS_futex, &word, FUTEX_WAIT_BITSET_PRIVATE | FUTEX_CLOCK_REALTIME, 0, &t, NULL, FUTEX_BITSET_MATCH_ANY) ? errno : 0; } - else if (!strcmp(n, "mutex_rt_in")) { t = ts_of(D_in); __atomic_add_fetch(&ready, 1, __ATOMIC_SEQ_CST); r = pthread_mutex_timedlock(&held, &t); } + else if (!strcmp(n, "sem_rt_in")) { t = rt_ts(D_in); __atomic_add_fetch(&ready, 1, __ATOMIC_SEQ_CST); r = sem_timedwait(&sem, &t) ? errno : 0; } + else if (!strcmp(n, "futex_rt_in")) { t = rt_ts(D_in); __atomic_add_fetch(&ready, 1, __ATOMIC_SEQ_CST); r = syscall(SYS_futex, &word, FUTEX_WAIT_BITSET_PRIVATE | FUTEX_CLOCK_REALTIME, 0, &t, NULL, FUTEX_BITSET_MATCH_ANY) ? errno : 0; } + else if (!strcmp(n, "mutex_rt_in")) { t = rt_ts(D_in); __atomic_add_fetch(&ready, 1, __ATOMIC_SEQ_CST); r = pthread_mutex_timedlock(&held, &t); } else if (!strcmp(n, "nanosleep_rel")) { t = ts_of(3000000000LL); __atomic_add_fetch(&ready, 1, __ATOMIC_SEQ_CST); r = nanosleep(&t, NULL); } else if (!strcmp(n, "poll_rel")) { __atomic_add_fetch(&ready, 1, __ATOMIC_SEQ_CST); r = poll(NULL, 0, 3000); } else if (!strcmp(n, "cond_mono_rel")) { t = ts_of(ns(CLOCK_MONOTONIC) + 3000000000LL); pthread_mutex_lock(&m); __atomic_add_fetch(&ready, 1, __ATOMIC_SEQ_CST); r = pthread_cond_timedwait(&c_mono, &m, &t); pthread_mutex_unlock(&m); } @@ -123,6 +124,7 @@ static void *reader(void *a) { } int main(void) { + rt_ns(); pthread_condattr_t at; pthread_condattr_init(&at); pthread_condattr_setclock(&at, CLOCK_MONOTONIC); pthread_cond_init(&c_mono, &at); sem_init(&sem, 0, 0); sigset_t set; sigemptyset(&set); sigaddset(&set, SIGRTMIN + 1); pthread_sigmask(SIG_BLOCK, &set, NULL); @@ -133,7 +135,7 @@ int main(void) { while (fgets(line, sizeof line, stdin)) { double din, dafter; if (sscanf(line, "arm %lf %lf", &din, &dafter) != 2) break; - int64_t u0 = ns(CLOCK_REALTIME), t0 = ns(CLOCK_MONOTONIC_RAW); + int64_t u0 = rt_ns(), t0 = ns(CLOCK_MONOTONIC_RAW); D_in = u0 + (int64_t)(din * 1e9); D_after = u0 + (int64_t)(dafter * 1e9); ready = 0; pthread_t t[64]; diff --git a/tst/clock/programs/rtbase.h b/tst/clock/programs/rtbase.h new file mode 100644 index 000000000..2e015e665 --- /dev/null +++ b/tst/clock/programs/rtbase.h @@ -0,0 +1,23 @@ +/* rtbase.h: the universe's realtime as 64-bit nanoseconds counted from the second it was first read, so the values fit + at any date the clock reaches (a count from 1970 runs out in 2262); rt_ts turns one back into a time. Read it once + before starting threads. */ +#include +#include +static int64_t rt_base_s; +static int rt_based; +static inline int64_t rt_ns(void) +{ + struct timespec t; + clock_gettime(CLOCK_REALTIME, &t); + if (!rt_based) { rt_base_s = t.tv_sec; rt_based = 1; } + return (int64_t) (t.tv_sec - rt_base_s) * 1000000000LL + t.tv_nsec; +} +static inline struct timespec rt_ts(int64_t v) +{ + int64_t s = v / 1000000000LL, n = v % 1000000000LL; + struct timespec t; + if (n < 0) { s -= 1; n += 1000000000LL; } + t.tv_sec = (time_t) (rt_base_s + s); + t.tv_nsec = (long) n; + return t; +} diff --git a/tst/clock/programs/rtread.c b/tst/clock/programs/rtread.c index 3ef8efbe3..8db9747c4 100644 --- a/tst/clock/programs/rtread.c +++ b/tst/clock/programs/rtread.c @@ -7,6 +7,7 @@ #include #include #include +#include "rtbase.h" static double dur; static int64_t ns(clockid_t c) { struct timespec t; clock_gettime(c, &t); return (int64_t)t.tv_sec * 1000000000LL + t.tv_nsec; } struct res { long reads, rt_back, mono_back; int64_t rt_max_back, mono_max_back; double mono_rate; }; @@ -14,9 +15,9 @@ static struct res R[16]; static void *reader(void *arg) { struct res *r = arg; int64_t raw0 = ns(CLOCK_MONOTONIC_RAW), mono0 = ns(CLOCK_MONOTONIC), end = raw0 + (int64_t)(dur * 1e9); - int64_t lrt = ns(CLOCK_REALTIME), lmo = mono0; + int64_t lrt = rt_ns(), lmo = mono0; for (;;) { - int64_t rt = ns(CLOCK_REALTIME), mo = ns(CLOCK_MONOTONIC); + int64_t rt = rt_ns(), mo = ns(CLOCK_MONOTONIC); r->reads++; if (rt < lrt) { r->rt_back++; if (lrt - rt > r->rt_max_back) r->rt_max_back = lrt - rt; } if (mo < lmo) { r->mono_back++; if (lmo - mo > r->mono_max_back) r->mono_max_back = lmo - mo; } @@ -28,6 +29,7 @@ static void *reader(void *arg) { } int main(int argc, char **argv) { dur = atof(argv[1]); int n = atoi(argv[2]); pthread_t t[16]; + rt_ns(); for (int i = 0; i < n; i++) pthread_create(&t[i], NULL, reader, &R[i]); for (int i = 0; i < n; i++) pthread_join(t[i], NULL); FILE *f = fopen(argv[3], "w"); diff --git a/tst/clock/programs/tfdalias.c b/tst/clock/programs/tfdalias.c index c90d9cbe0..e317d12ff 100644 --- a/tst/clock/programs/tfdalias.c +++ b/tst/clock/programs/tfdalias.c @@ -15,6 +15,7 @@ #include #include #include +#include "rtbase.h" static int64_t ns(clockid_t c) { struct timespec t; clock_gettime(c, &t); return (int64_t)t.tv_sec * 1000000000LL + t.tv_nsec; } static struct timespec ts_of(int64_t v) { struct timespec t = {v / 1000000000LL, v % 1000000000LL}; return t; } @@ -22,7 +23,7 @@ static struct timespec ts_of(int64_t v) { struct timespec t = {v / 1000000000LL, int main(int argc, char **argv) { const char *how = argc > 1 ? argv[1] : "dup"; int o = timerfd_create(CLOCK_MONOTONIC, 0), a = timerfd_create(CLOCK_REALTIME, 0), a2, o2; - struct itimerspec ten = {{0, 0}, ts_of(10000000000LL)}, hour = {{0, 0}, ts_of(ns(CLOCK_REALTIME) + 3600000000000LL)}; + struct itimerspec ten = {{0, 0}, ts_of(10000000000LL)}, hour = {{0, 0}, rt_ts(rt_ns() + 3600000000000LL)}; unsigned long long count = 0; int64_t fired = 0; int failed = 0; diff --git a/tst/clock/programs/torn.c b/tst/clock/programs/torn.c index 0f80aff0a..016fd1b06 100644 --- a/tst/clock/programs/torn.c +++ b/tst/clock/programs/torn.c @@ -11,16 +11,20 @@ #include #include "rawsys.h" #define NS 1000000000LL -static double seconds; static int64_t off_a, off_b, rt0, raw0; +/* offsets of 128 bits: a universe in 9999 is some 8,000 years from real time, past 64 bits of nanoseconds */ +typedef __int128 off_t128; +static double seconds; static off_t128 off_a, off_b; static int64_t rt0, raw0; static int64_t ns(clockid_t c) { struct timespec t; clock_gettime(c, &t); return (int64_t)t.tv_sec * NS + t.tv_nsec; } -static int64_t far(int64_t d) { return d < 0 ? -d : d; } -struct res { long reads, a, b, torn; int64_t worst; }; +static off_t128 ns128(clockid_t c) { struct timespec t; clock_gettime(c, &t); return (off_t128)t.tv_sec * NS + t.tv_nsec; } +static off_t128 far(off_t128 d) { return d < 0 ? -d : d; } +struct res { long reads, a, b, torn; off_t128 worst; }; static struct res R[16]; static void *reader(void *arg) { struct res *r = arg; int64_t end = ns(CLOCK_MONOTONIC_RAW) + (int64_t)(seconds * NS); for (;;) { - int64_t raw = ns(CLOCK_MONOTONIC_RAW), off = ns(CLOCK_REALTIME) - (rt0 + raw - raw0); + int64_t raw = ns(CLOCK_MONOTONIC_RAW); + off_t128 off = ns128(CLOCK_REALTIME) - (rt0 + raw - raw0); r->reads++; if (far(off - off_a) <= NS) r->a++; else if (far(off - off_b) <= NS) r->b++; @@ -31,12 +35,12 @@ static void *reader(void *arg) { } int main(int argc, char **argv) { if (argc != 5) { fprintf(stderr, "usage: torn SECONDS THREADS OFF_A_S OFF_B_S\n"); return 2; } - seconds = atof(argv[1]); int n = atoi(argv[2]); off_a = (int64_t)(atof(argv[3]) * NS); off_b = (int64_t)(atof(argv[4]) * NS); + seconds = atof(argv[1]); int n = atoi(argv[2]); off_a = (off_t128)(atof(argv[3]) * NS); off_b = (off_t128)(atof(argv[4]) * NS); if (n < 1 || n > 16) return 2; struct timespec t; raw_clock_gettime(CLOCK_REALTIME, &t); raw0 = ns(CLOCK_MONOTONIC_RAW); rt0 = (int64_t)t.tv_sec * NS + t.tv_nsec; pthread_t th[16]; for (int i = 0; i < n; i++) pthread_create(&th[i], NULL, reader, &R[i]); - long reads = 0, a = 0, b = 0, torn = 0; int64_t worst = 0; + long reads = 0, a = 0, b = 0, torn = 0; off_t128 worst = 0; for (int i = 0; i < n; i++) { pthread_join(th[i], NULL); reads += R[i].reads; a += R[i].a; b += R[i].b; torn += R[i].torn; diff --git a/tst/clock/range_test.py b/tst/clock/range_test.py new file mode 100644 index 000000000..1e5e13f8f --- /dev/null +++ b/tst/clock/range_test.py @@ -0,0 +1,101 @@ +"""The clock's range: the page holds the universe as whole seconds and nanoseconds, so clock reads and every kind of wait +follow it before 1970, across 2262-04-11 (where a signed 64-bit count of nanoseconds runs out), and far past it, to +9999. Each gate runs as its own gate does at the date CLOCK_BASE names, held to the same bounds.""" +from datetime import datetime, timezone + +import pytest + +from tst.clock.bounds import LATE_MS, LATE_S, clock_time_bound +from tst.clock.waits_test import JUMP_RC, at_jump, failed, within + +BASES = { + "1950": datetime(1950, 1, 1, 12, tzinfo=timezone.utc), + # Six seconds short of 2262-04-11T23:47:16.854775807Z, the last time 64 bits of nanoseconds hold: each gate crosses it. + "2262": datetime(2262, 4, 11, 23, 47, 10, tzinfo=timezone.utc), + "3026": datetime(3026, 11, 23, 12, tzinfo=timezone.utc), + "9999": datetime(9999, 6, 1, 12, tzinfo=timezone.utc), +} +JUMP_ROUNDS = 8 + + +@pytest.fixture(scope="module", params=list(BASES)) +def at(request, gate): + """``gate``, with the universe starting at one of BASES.""" + env = ["-e", f"CLOCK_BASE={int(BASES[request.param].timestamp())}"] + + def run(name: str, *args, timeout: float = 600): + return gate(name, *args, timeout=timeout, docker_args=env) + + run.base = request.param + return run + + +@pytest.fixture(scope="module") +def waits(at): + return {sc["scenario"]: sc["results"] for sc in at("waits")} + + +@pytest.mark.parametrize("rate", [1, 2, 60]) +def test_a_wait_is_real_elapsed_time_or_a_clock_time_reached_at_the_rate_at_any_date(waits, rate): + results = waits[f"rate {rate}"] + assert len(results) == 64 and not [r for r in results if "status" in r] + elapsed = {r["api"]: r["real"] for r in results if r["class"] == "elapsed"} + clock = {r["api"]: r["real"] for r in results if r["class"] == "clock_time"} + assert len(clock) == 19 and failed(results) == {} + assert {api: s for api, s in elapsed.items() if not 0.99 <= s <= 1 + LATE_S} == {} + assert {api: s for api, s in clock.items() if not 1 / rate - 0.01 <= s <= clock_time_bound(rate)} == {} + + +def test_frozen_at_any_date_a_clock_time_wait_ends_at_the_advance(waits): + results = waits["frozen, +1 h at 2.5 s"] + assert len(results) == 64 and not [r for r in results if "status" in r] and failed(results) == {} + assert {r["api"]: r["end_after_change_ms"] for r in results + if r["class"] == "clock_time" and not within(r, -1, LATE_MS)} == {} + + +def test_a_jump_at_any_date_ends_the_waits_it_passes_and_none_other(at): + jumps = at("jumps", JUMP_ROUNDS, 5420) + assert len(jumps["rounds"]) == JUMP_ROUNDS and jumps["mono_back_total"] == 0 + wrong = [] + for row in jumps["rounds"]: + assert row["waiters"].keys() == JUMP_RC.keys() + for name, w in row["waiters"].items(): + if w["rc"] not in JUMP_RC[name]: + wrong.append((row["round"], name, w)) + elif w["kind"] == "in" and not at_jump(w): + wrong.append((row["round"], name, w)) + elif w["kind"] == "after" and not -1 <= w["vs_expected_ms"] <= LATE_MS: + wrong.append((row["round"], name, w)) + elif w["kind"] == "rel" and not 2.999 <= w["real_s"] <= 3 + LATE_S: + wrong.append((row["round"], name, w)) + assert wrong == [] + + +def test_a_timerfd_at_any_date_is_followed_through_its_duplicates(at): + for how, r in at("timerfds").items(): + expected = (0, 3) if how == "failed" else (0, 0) if how.startswith(("vfork_", "python_")) else (1, 0) + assert (r["same_number"], r["failed_calls"]) == expected, (how, r) + assert (r["a2_count"], r["o_fired_early"]) == (1, 0), (how, r) + assert at_jump(r), (how, r) + + +def test_a_cancelled_wait_at_any_date_goes_at_once(at): + r = at("cancel") + assert (r["sem_cancelled"], r["sem_waiters"], r["cns_cancelled"], r["cond_cancelled"]) == (1, 0, 1, 600), r + assert r["rc"] == 110 and at_jump(r), r + + +def test_realtime_never_steps_back_under_a_stalled_writer_at_any_date(at): + r = at("stall", 500) + assert r["writes"] == 500 and r["reads"] > 100_000 + assert (r["rt_back"], r["mono_back"]) == (0, 0), r + + +def test_a_read_at_any_date_is_never_torn_between_two_pages(at): + r = at("torn", 5.0) + assert r["writes"] > 500 and r["universe_a"] > 0 and r["universe_b"] > 0 and r["torn"] == 0, r + + +def test_chrome_runs_every_launch_past_2262(gate): + r = gate("chromium", "agentenv", 16, 8, 20.0, docker_args=["-e", f"CLOCK_BASE={int(BASES['9999'].timestamp())}"]) + assert (r["launches"], r["failed"]) == (16, 0), r diff --git a/tst/unit/agents/test_agent_egress.py b/tst/unit/agents/test_agent_egress.py index 49e02ec19..6364bcc87 100644 --- a/tst/unit/agents/test_agent_egress.py +++ b/tst/unit/agents/test_agent_egress.py @@ -97,6 +97,8 @@ def _torn(page: bytes) -> bytes: pytest.param(_torn(_page(1)), True, id="torn-armed"), pytest.param(_torn(_page(0)), False, id="torn-unarmed"), pytest.param(_page(1)[:40], False, id="short"), + pytest.param(clockpage.encode(2, 253402300799 * 10**9, 0, 1.0, 1, 1, 0, 0), True, id="armed-in-9999"), + pytest.param(_page(1)[:4] + (2).to_bytes(4, "little") + _page(1)[8:], False, id="version-2"), pytest.param(b"\0" * 80, False, id="no-magic"), pytest.param(bytes(range(80)), False, id="garbage"), pytest.param(None, False, id="no-page"), diff --git a/tst/unit/env/envs/test_computer_clock_follower.py b/tst/unit/env/envs/test_computer_clock_follower.py index 9f57d3f2d..7eb085e4f 100644 --- a/tst/unit/env/envs/test_computer_clock_follower.py +++ b/tst/unit/env/envs/test_computer_clock_follower.py @@ -109,8 +109,7 @@ def status(self) -> dict: def universe(self) -> float: with open(page.PAGE, "rb") as f: - fields = page.LAYOUT.unpack(f.read(page.LAYOUT.size)) - _, _, _, universe_ns, anchor_ns, rate, armed, *_ = fields + _, armed, universe_ns, anchor_ns, rate, _ = page.read(f.read(page.LAYOUT.size)) return page._universe_at(armed, universe_ns, anchor_ns, rate, time.time_ns()) / 1e9 def until(self, check, within: float = 5.0): diff --git a/tst/unit/env/envs/test_computer_clock_page.py b/tst/unit/env/envs/test_computer_clock_page.py new file mode 100644 index 000000000..0e3d458bc --- /dev/null +++ b/tst/unit/env/envs/test_computer_clock_page.py @@ -0,0 +1,116 @@ +"""The clock page's format (version 3, utils/faketime_clock/clockpage.py): the universe at the anchor as whole seconds +and nanoseconds, so a page holds any date the gateway's clock takes, from before 1970 to 9999-12-31, where version 2's +signed 64-bit count of nanoseconds ran out on 2262-04-11; the specification libfaketime reads from the clock file is +exact at any of them; and a page of another version is never read as this one's.""" + +from __future__ import annotations + +import getpass +import importlib.util +import struct +import time +from datetime import datetime, timedelta, timezone +from pathlib import Path + +import pytest + +import agent_env + +CLOCK = Path(agent_env.__file__).parent / "utils" / "faketime_clock" +NS = 10**9 +INT64_MAX_NS = 2**63 - 1 +EPOCH = datetime(1970, 1, 1, tzinfo=timezone.utc) + + +@pytest.fixture +def clockpage(tmp_path): + spec = importlib.util.spec_from_file_location("clockpage_v3", CLOCK / "clockpage.py") + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + module.PAGE, module.FILE = str(tmp_path / "agentenv-clock"), str(tmp_path / "run" / "clock") + return module + + +def _ns(text: str) -> int: + whole, _, part = text.partition(".") + seconds = (datetime.fromisoformat(whole).replace(tzinfo=timezone.utc) - EPOCH) // timedelta(seconds=1) + return seconds * NS + int((part or "0").ljust(9, "0")) + + +@pytest.mark.parametrize("universe_ns", [ + pytest.param(0, id="1970"), + pytest.param(-1, id="a-nanosecond-before-1970"), + pytest.param(_ns("1949-12-31T23:59:59.75"), id="1949-fractional"), + pytest.param(_ns("1900-01-01T00:00:00"), id="1900"), + pytest.param(INT64_MAX_NS, id="version-2s-last-nanosecond"), + pytest.param(INT64_MAX_NS + 1, id="past-2262"), + pytest.param(_ns("3026-11-23T12:00:00"), id="3026"), + pytest.param(_ns("9999-12-31T23:59:59.999999999"), id="9999-12-31"), +]) +def test_a_page_holds_the_universe_exactly_at_any_date(clockpage, universe_ns): + page = clockpage.encode(4, universe_ns, 1_794_000_000 * NS, 3600.0, 1, 9, 5 * NS, 5 * NS) + + assert len(page) == clockpage.LAYOUT.size == 80 + assert clockpage.read(page) == (4, 1, universe_ns, 1_794_000_000 * NS, 3600.0, 9) + assert 0 <= struct.unpack_from("= now + + +def test_a_page_of_another_version_is_refused_by_the_writer_and_replaced_at_boot(clockpage): + old = clockpage.encode(2, 0, 0, 1.0, 0, 1, 0, 0) + Path(clockpage.PAGE).write_bytes(old[:4] + (2).to_bytes(4, "little") + old[8:]) + with pytest.raises(SystemExit, match="older page"): + clockpage.open_page() + + clockpage.create(getpass.getuser()) + with open(clockpage.PAGE, "rb") as f: + assert clockpage.read(f.read(clockpage.LAYOUT.size)) == (0, 0, 0, 0, 1.0, 0) diff --git a/tst/unit/env/envs/test_computer_clock_panel.py b/tst/unit/env/envs/test_computer_clock_panel.py index a89249ff0..bf6e584fc 100644 --- a/tst/unit/env/envs/test_computer_clock_panel.py +++ b/tst/unit/env/envs/test_computer_clock_panel.py @@ -103,7 +103,7 @@ def set(self, universe: float, rate: float) -> float: def reanchor(self, by: float) -> None: with open(page.PAGE, "rb") as f: - _, _, _, universe_ns, anchor_ns, rate, armed, *_ = page.LAYOUT.unpack(f.read(page.LAYOUT.size)) + _, armed, universe_ns, anchor_ns, rate, _ = page.read(f.read(page.LAYOUT.size)) now = time.time_ns() page.write(armed, (universe_ns + (now - anchor_ns) * rate) / 1e9 + by, rate, now / 1e9) diff --git a/tst/unit/env/envs/test_computer_egress_base.py b/tst/unit/env/envs/test_computer_egress_base.py index 3d102165d..ca0aec78d 100644 --- a/tst/unit/env/envs/test_computer_egress_base.py +++ b/tst/unit/env/envs/test_computer_egress_base.py @@ -85,11 +85,16 @@ def test_the_pages_the_proxy_is_tested_on_are_the_ones_the_followers_writer_writ page = importlib.util.module_from_spec(spec) spec.loader.exec_module(page) golden = {name: bytes.fromhex((EGRESS / "testdata" / f"page-{name}.hex").read_text().strip()) - for name in ("armed", "unarmed")} - - assert golden == { - "armed": page.encode(4, 1577836800_000000000, 1794000000_123456789, 2.0, 1, 7, 5_000_000_000, 5_000_000_000), - "unarmed": page.encode(2, 0, 0, 1.0, 0, 3, 0, 0)} + for name in ("armed", "unarmed", "far", "past", "version2")} + anchor, mono = 1794000000_000000000, 5_000_000_000 + + assert {name: golden[name] for name in ("armed", "unarmed", "far", "past")} == { + "armed": page.encode(4, 1577836800_000000000, 1794000000_123456789, 2.0, 1, 7, mono, mono), + "unarmed": page.encode(2, 0, 0, 1.0, 0, 3, 0, 0), + # 9999-12-31T00:00:00.5Z at rate 3600, past 2262; and 1949-12-31T23:59:59.75Z, before 1970. + "far": page.encode(6, 253402214400_500000000, anchor, 3600.0, 1, 9, mono, mono), + "past": page.encode(8, -631152000_250000000, anchor, 1.0, 1, 11, mono, mono)} + assert golden["version2"][4:8] == (2).to_bytes(4, "little") and page.read(golden["version2"]) is None def test_every_chromium_build_goes_out_through_the_proxy_by_a_policy_that_bypasses_what_the_session_does(): diff --git a/tst/unit/env/gateway/clock_range_test.py b/tst/unit/env/gateway/clock_range_test.py new file mode 100644 index 000000000..68d344fee --- /dev/null +++ b/tst/unit/env/gateway/clock_range_test.py @@ -0,0 +1,38 @@ +"""The env clock's range: the gateway's clock arms and runs at any date a datetime holds, before 1970 and past 2262 +(where the computers and agents that follow it now follow too), and refuses a date past 9999-12-31, or one it would run +past within a real day, naming that latest time.""" +from __future__ import annotations + +import pytest + +from agent_env.env.gateway.clock import LATEST, Clock, ClockError +from tst.unit.env.gateway.triggers_time_test import FakeNow + + +@pytest.mark.parametrize("virtual_time", ["1900-01-01T00:00:00Z", "1949-12-31T23:59:59.750000Z", "2262-04-11T23:47:17Z", + "3026-11-23T12:00:00Z", "9999-06-01T12:00:00Z"]) +def test_the_clock_arms_and_runs_at_any_date_a_datetime_holds(virtual_time): + now = FakeNow() + clock = Clock(now_fn=now) + + assert clock.set_time(virtual_time, rate=60)["virtual_time"] == virtual_time + now.tick(1) + assert clock.read()["virtual_time"] > virtual_time + + +@pytest.mark.parametrize("virtual_time", ["10000-01-01T00:00:00Z", "123456-01-01T00:00:00Z"]) +def test_a_date_past_9999_is_refused_naming_the_latest_the_clock_reaches(virtual_time): + with pytest.raises(ClockError, match=f"past {LATEST}, the latest the env clock reaches"): + Clock(now_fn=FakeNow()).set_time(virtual_time) + + +def test_arming_advancing_or_speeding_a_clock_that_would_run_past_9999_within_a_day_names_the_latest(): + clock = Clock(now_fn=FakeNow()) + with pytest.raises(ClockError, match=f"would pass {LATEST}"): + clock.set_time("9999-12-31T12:00:00Z") + + clock.set_time("9999-06-01T00:00:00Z") + with pytest.raises(ClockError, match=f"would pass {LATEST}"): + clock.advance("9999-12-31T12:00:00Z") + with pytest.raises(ClockError, match=f"past {LATEST}"): + clock.set_rate(86400) From 651121d76c99c4d29171e9f1375d153eb67b9a7d Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 23 Nov 2026 09:52:33 -0800 Subject: [PATCH 02/16] fix(computers): an absolute realtime deadline before 1970 follows the universe clock Co-Authored-By: Claude Opus 5.5 --- .../faketime_clock/agentenv_clock_waits.c | 18 ++++++++++++------ .../utils/faketime_clock/libfaketime.patch | 4 ++-- 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/src/agent_env/utils/faketime_clock/agentenv_clock_waits.c b/src/agent_env/utils/faketime_clock/agentenv_clock_waits.c index aae429693..cf2cddccc 100644 --- a/src/agent_env/utils/faketime_clock/agentenv_clock_waits.c +++ b/src/agent_env/utils/faketime_clock/agentenv_clock_waits.c @@ -182,6 +182,12 @@ static inline bool ft_valid_ts(const struct timespec *t) { return t != NULL && t->tv_nsec >= 0 && t->tv_nsec < FT_NS && t->tv_sec >= 0; } +/* an absolute deadline on the universe's realtime, which is before 1970 only while the universe is set: on a real clock + the kernel refuses a negative time, so an unarmed page leaves such a deadline to it. */ +static inline bool ft_valid_due(const struct timespec *t, const struct ft_clock_page *s) +{ + return t != NULL && t->tv_nsec >= 0 && t->tv_nsec < FT_NS && (t->tv_sec >= 0 || s->armed); +} static inline bool ft_rt_clock(clockid_t c) { return c == CLOCK_REALTIME || c == CLOCK_REALTIME_ALARM; @@ -597,7 +603,7 @@ static long ft_u_futex_rt(uint32_t *uaddr, int op, uint32_t val, const struct ti struct ft_clock_page s; ft_uns_t due = ft_uns(abs); *handled = false; - if (!ft_snap(&s)) return 0; + if (!ft_snap(&s) || !ft_valid_due(abs, &s)) return 0; *handled = true; for (;;) { @@ -807,7 +813,7 @@ long syscall(long number, ...) { int op = (int) a[1]; const struct timespec *ts = (const struct timespec *) a[3]; - if ((op & FUTEX_CMD_MASK) == FUTEX_WAIT_BITSET && (op & FUTEX_CLOCK_REALTIME) && ft_valid_ts(ts) + if ((op & FUTEX_CMD_MASK) == FUTEX_WAIT_BITSET && (op & FUTEX_CLOCK_REALTIME) && ts != NULL && (uint32_t) a[5] == FUTEX_BITSET_MATCH_ANY) { bool handled; @@ -845,8 +851,8 @@ static int ft_u_timerfd_settime(int fd, int flags, const struct itimerspec *nv, } ft_tab_unlock(&old); } - if (!ft_rt_clock(clock) || !(flags & TFD_TIMER_ABSTIME) || !ft_valid_ts(&nv->it_value) - || !ft_valid_ts(&nv->it_interval) || (nv->it_value.tv_sec == 0 && nv->it_value.tv_nsec == 0) || !ft_snap(&s)) + if (!ft_rt_clock(clock) || !(flags & TFD_TIMER_ABSTIME) || !ft_valid_ts(&nv->it_interval) + || (nv->it_value.tv_sec == 0 && nv->it_value.tv_nsec == 0) || !ft_snap(&s) || !ft_valid_due(&nv->it_value, &s)) { r = (*real_timerfd_settime)(fd, flags, nv, ov); if (r == 0 && ov != NULL && was) *ov = prev; @@ -1150,8 +1156,8 @@ int timer_settime(timer_t id, int flags, const struct itimerspec *nv, struct iti t->tracked = 0; } ft_tab_unlock(&old); - if (t == NULL || !ft_uw_active() || !(flags & TIMER_ABSTIME) || !ft_valid_ts(&nv->it_value) - || !ft_valid_ts(&nv->it_interval) || (nv->it_value.tv_sec == 0 && nv->it_value.tv_nsec == 0) || !ft_snap(&s)) + if (t == NULL || !ft_uw_active() || !(flags & TIMER_ABSTIME) || !ft_valid_ts(&nv->it_interval) + || (nv->it_value.tv_sec == 0 && nv->it_value.tv_nsec == 0) || !ft_snap(&s) || !ft_valid_due(&nv->it_value, &s)) { r = (*real_timer_settime_new)(id, flags, nv, ov); if (r == 0 && ov != NULL && was) *ov = prev; diff --git a/src/agent_env/utils/faketime_clock/libfaketime.patch b/src/agent_env/utils/faketime_clock/libfaketime.patch index 458798e09..8f7254b65 100644 --- a/src/agent_env/utils/faketime_clock/libfaketime.patch +++ b/src/agent_env/utils/faketime_clock/libfaketime.patch @@ -164,10 +164,10 @@ diff -ruN a/src/libfaketime.c b/src/libfaketime.c ftpl_init(); + if (real_clock_nanosleep != NULL && (!(flags & TIMER_ABSTIME) || !ft_rt_clock(clock_id) || !ft_faked())) + return (*real_clock_nanosleep)(clock_id, flags, req, rem); -+ if (ft_uw_active() && ft_valid_ts(req)) ++ if (ft_uw_active()) + { + struct ft_clock_page s; -+ if (ft_snap(&s)) return ft_rt_sleep(&s, ft_uns(req)); ++ if (ft_snap(&s) && ft_valid_due(req, &s)) return ft_rt_sleep(&s, ft_uns(req)); + } if (real_clock_nanosleep == NULL) { From 9fb87bb6a2e53a8d26464295ab4e573952734840 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 23 Nov 2026 10:35:41 -0800 Subject: [PATCH 03/16] fix(clock): limit the env clock to 1677-09-21..2262-04-11, the times Python and the clock page hold CPython keeps time as 64-bit nanoseconds (time.time() raises, datetime.now() sticks at 2262-04-11 outside them), so the gateway refuses a time outside that range, or one it would run past the end from within a real hour, with a message naming the range. The page, C and Go go back to main; the pre-1970 deadline fix stays, with libfaketime's spec written with its sign once before 1970. Co-Authored-By: Claude Opus 5.5 --- .../artifacts/ubuntu-24.04/clock-panel | 10 +- src/agent_env/env/gateway/clock.py | 45 ++++--- .../utils/agent_clock/agent_egress.py | 9 +- src/agent_env/utils/egress_proxy/clock.go | 30 ++--- .../utils/egress_proxy/clock_test.go | 39 +----- .../utils/egress_proxy/proxy_test.go | 13 -- .../egress_proxy/testdata/page-armed.hex | 2 +- .../utils/egress_proxy/testdata/page-far.hex | 1 - .../utils/egress_proxy/testdata/page-past.hex | 1 - .../egress_proxy/testdata/page-unarmed.hex | 2 +- .../egress_proxy/testdata/page-version2.hex | 1 - src/agent_env/utils/egress_proxy/upstream.go | 9 +- .../faketime_clock/agentenv_clock_page.c | 79 +++--------- .../faketime_clock/agentenv_clock_waits.c | 69 ++++------- .../utils/faketime_clock/clockpage.py | 72 +++-------- .../utils/faketime_clock/libfaketime.patch | 30 +++-- tst/clock/harness.py | 8 +- tst/clock/programs/rtbase.h | 6 +- tst/clock/programs/torn.c | 2 +- tst/clock/range_test.py | 51 ++++---- tst/unit/agents/test_agent_egress.py | 2 - .../env/envs/test_computer_clock_follower.py | 3 +- tst/unit/env/envs/test_computer_clock_page.py | 116 ------------------ .../env/envs/test_computer_clock_panel.py | 2 +- .../env/envs/test_computer_egress_base.py | 15 +-- tst/unit/env/gateway/clock_range_test.py | 57 +++++---- tst/unit/env/gateway/get_time_test.py | 14 ++- 27 files changed, 228 insertions(+), 460 deletions(-) delete mode 100644 src/agent_env/utils/egress_proxy/testdata/page-far.hex delete mode 100644 src/agent_env/utils/egress_proxy/testdata/page-past.hex delete mode 100644 src/agent_env/utils/egress_proxy/testdata/page-version2.hex delete mode 100644 tst/unit/env/envs/test_computer_clock_page.py diff --git a/src/agent_env/computers/artifacts/ubuntu-24.04/clock-panel b/src/agent_env/computers/artifacts/ubuntu-24.04/clock-panel index fe27c0984..76da015cb 100755 --- a/src/agent_env/computers/artifacts/ubuntu-24.04/clock-panel +++ b/src/agent_env/computers/artifacts/ubuntu-24.04/clock-panel @@ -36,10 +36,14 @@ def log(event: str, **fields) -> None: def read(fd: int) -> tuple | None: """The page's (armed, universe_ns, anchor_ns, rate), None while it's being written or isn't a page.""" - state = clockpage.read(os.pread(fd, clockpage.LAYOUT.size, 0)) - if state is None: + raw = os.pread(fd, clockpage.LAYOUT.size, 0) + if len(raw) < clockpage.LAYOUT.size: + return None + magic, version, seq, universe, anchor, rate, armed, _, generation, check, mono_universe, mono_anchor = ( + clockpage.LAYOUT.unpack(raw)) + if (magic, version) != (clockpage.MAGIC, clockpage.VERSION) or seq & 1 or check != clockpage.check( + seq, universe, anchor, rate, armed, generation, mono_universe, mono_anchor): return None - _, armed, universe, anchor, rate, _ = state return armed, universe, anchor, rate diff --git a/src/agent_env/env/gateway/clock.py b/src/agent_env/env/gateway/clock.py index 273992b02..8f99bd2d4 100644 --- a/src/agent_env/env/gateway/clock.py +++ b/src/agent_env/env/gateway/clock.py @@ -20,13 +20,14 @@ class ClockError(ValueError): MAX_RATE = 86400.0 # 1 real second = 1 virtual day (the max virtual-time speed) -# Fast-fail a t0 that would overflow within a real day of advancement at `rate` (frozen clocks -# exempt). Not the overflow guarantee — reads still saturate (_advance) if the gateway outlives it. -_OVERFLOW_HORIZON_S = 86400.0 +# Fast-fail a t0 that would pass LATEST within a real hour of advancement at `rate` (frozen clocks exempt): an hour, so +# a day per second still arms at today's dates. Not the overflow guarantee — reads still saturate (_advance) past it. +_OVERFLOW_HORIZON_S = 3600.0 _MAX_T0 = datetime.max.replace(tzinfo=timezone.utc) -# The latest time the clock reaches, as its errors name it: what a datetime holds, which the computers and agents that -# follow it hold too. -LATEST = "9999-12-31T23:59:59Z" +# The times the clock holds: those 64 bits of nanoseconds since 1970 hold, as Python and the computers' clock page keep +# time, so every program that follows the clock can read it (Python's time.time() raises outside them). +EARLIEST = datetime(1677, 9, 21, 0, 12, 44, tzinfo=timezone.utc) +LATEST = datetime(2262, 4, 11, 23, 47, 16, tzinfo=timezone.utc) def _parse_rate(rate) -> float: @@ -63,7 +64,7 @@ def _parse_rfc3339(text: str) -> datetime: # Don't strip: a whitespace-wrapped value would slip through the anchored grammar (a 200 the contract calls a 400). raw = text if re.match(r"^\d{5,}-", raw): - raise ClockError(f"virtual_time {text!r} is past {LATEST}, the latest the env clock reaches") + raise ClockError(_outside(text)) if not _RFC3339_RE.match(raw): raise ClockError(f"invalid RFC3339 virtual_time {text!r}: expected {_RFC3339_SHAPE}") if raw.endswith(("Z", "z")): @@ -78,6 +79,17 @@ def _parse_rfc3339(text: str) -> datetime: raise ClockError(f"invalid RFC3339 virtual_time {text!r}: out of representable range") +_WHY = "the times a 64-bit count of nanoseconds since 1970 holds, as Python and the computers that follow the clock keep time" + + +def _outside(virtual_time: str) -> str: + return f"virtual_time {virtual_time!r} is outside the env clock's range, {_iso(EARLIEST)} to {_iso(LATEST)} ({_WHY})" + + +def _past_end(what: str) -> str: + return f"{what} would pass {_iso(LATEST)}, the end of the env clock's range, within a real hour ({_WHY})" + + def _iso(dt: datetime) -> str: return dt.astimezone(timezone.utc).isoformat().replace("+00:00", "Z") @@ -194,9 +206,10 @@ def set_time(self, virtual_time: str, rate=1.0, time_zone: str | None = None) -> r = _parse_rate(1.0 if rate is None else rate) if time_zone is not None and _zone(time_zone) is None: raise ClockError(f"unknown time zone {time_zone!r}: pass an IANA time zone name such as 'America/New_York'") - if t0 > _MAX_T0 - timedelta(seconds=_OVERFLOW_HORIZON_S * r): - raise ClockError(f"virtual_time {virtual_time!r} at rate {r:g} would pass {LATEST}, the latest the env clock " - f"reaches, within a real day") + if not EARLIEST <= t0 <= LATEST: + raise ClockError(_outside(virtual_time)) + if t0 > LATEST - timedelta(seconds=_OVERFLOW_HORIZON_S * r): + raise ClockError(_past_end(f"virtual_time {virtual_time!r} at rate {r:g}")) with self._lock: self._bank(t0) self._t0 = t0 @@ -218,9 +231,8 @@ def set_rate(self, rate) -> dict: raise ClockError("clock is not armed") now = self._now() ran = (now - self._anchor) * self._rate - if _advance(self._t0, ran + self._ahead) > _MAX_T0 - timedelta(seconds=_OVERFLOW_HORIZON_S * r): - raise ClockError(f"rate {r:g} would carry the clock past {LATEST}, the latest it reaches, within a real " - f"day") + if _advance(self._t0, ran + self._ahead) > LATEST - timedelta(seconds=_OVERFLOW_HORIZON_S * r): + raise ClockError(_past_end(f"rate {r:g}")) self._lived += ran self._ahead += ran self._anchor = now @@ -234,9 +246,10 @@ def advance(self, virtual_time: str) -> dict: with self._lock: if not self._armed or self._t0 is None: raise ClockError("clock is not armed") - if target > _MAX_T0 - timedelta(seconds=_OVERFLOW_HORIZON_S * self._rate): - raise ClockError(f"virtual_time {virtual_time!r} at rate {self._rate:g} would pass {LATEST}, the latest " - f"the env clock reaches, within a real day") + if target > LATEST: + raise ClockError(_outside(virtual_time)) + if target > LATEST - timedelta(seconds=_OVERFLOW_HORIZON_S * self._rate): + raise ClockError(_past_end(f"virtual_time {virtual_time!r} at rate {self._rate:g}")) current = _advance(self._t0, (self._now() - self._anchor) * self._rate + self._ahead) jump = (target - current).total_seconds() if jump < 0: diff --git a/src/agent_env/utils/agent_clock/agent_egress.py b/src/agent_env/utils/agent_clock/agent_egress.py index dae8398bf..8fad38ef2 100644 --- a/src/agent_env/utils/agent_clock/agent_egress.py +++ b/src/agent_env/utils/agent_clock/agent_egress.py @@ -26,12 +26,13 @@ def clock_armed(page_path: str | None = None) -> bool: raw = page.read(clockpage.LAYOUT.size) if len(raw) < clockpage.LAYOUT.size: return False - magic, version, *_ = fields = clockpage.LAYOUT.unpack(raw) + magic, version, seq, universe, anchor, rate, armed, _, generation, checked, mono_u, mono_a = \ + clockpage.LAYOUT.unpack(raw) if (magic, version) != (clockpage.MAGIC, clockpage.VERSION): return False - if (state := clockpage.read(raw)) is not None: - return bool(state[1]) - armed = fields[6] + if seq % 2 == 0 and checked == clockpage.check(seq, universe, anchor, rate, armed, generation, mono_u, + mono_a): + return bool(armed) time.sleep(_RETRY_S) except OSError: return False diff --git a/src/agent_env/utils/egress_proxy/clock.go b/src/agent_env/utils/egress_proxy/clock.go index 94407dab2..30cb880c1 100644 --- a/src/agent_env/utils/egress_proxy/clock.go +++ b/src/agent_env/utils/egress_proxy/clock.go @@ -9,14 +9,12 @@ import ( "time" ) -// The clock page the follower writes (clockpage.py, version 3): magic version seq universe_s anchor_ns rate armed -// universe_nsec generation check mono_universe_ns mono_anchor_ns, little-endian, 80 bytes, seq odd while it's written. -// The universe at the anchor is universe_s seconds and universe_nsec nanoseconds, so it reaches past 2262. +// The clock page the follower writes (clockpage.py, version 2): magic version seq universe_ns anchor_ns rate armed +// reserved generation check mono_universe_ns mono_anchor_ns, little-endian, 80 bytes, seq odd while it's written. const ( - pageSize = 80 - pageMagic = 0x4B434541 - pageVersion = 3 - checkSalt = 0x9E3779B97F4A7C15 + pageSize = 80 + pageMagic = 0x4B434541 + checkSalt = 0x9E3779B97F4A7C15 ) // state is the universe as the session reads it: armed, the universe at the anchor (seconds), the anchor (real @@ -40,39 +38,35 @@ func (s state) at(t float64) float64 { return s.V + (t-s.Anchor)*s.Rate } -func pageCheck(seq uint64, us int64, unsec uint32, a int64, rate float64, armed uint32, generation uint64, - mu, ma int64) uint64 { - return seq ^ uint64(us) ^ uint64(unsec)<<32 ^ uint64(a) ^ math.Float64bits(rate) ^ uint64(armed) ^ generation ^ - uint64(mu) ^ uint64(ma) ^ checkSalt +func pageCheck(seq uint64, u, a int64, rate float64, armed uint32, generation uint64, mu, ma int64) uint64 { + return seq ^ uint64(u) ^ uint64(a) ^ math.Float64bits(rate) ^ uint64(armed) ^ generation ^ uint64(mu) ^ + uint64(ma) ^ checkSalt } // readPage reads a consistent state from the page's bytes, or false when it's being written, torn or not a page. func readPage(b []byte) (state, bool) { - if len(b) < pageSize || binary.LittleEndian.Uint32(b[0:]) != pageMagic || - binary.LittleEndian.Uint32(b[4:]) != pageVersion { + if len(b) < pageSize || binary.LittleEndian.Uint32(b[0:]) != pageMagic { return state{}, false } seq := binary.LittleEndian.Uint64(b[8:]) if seq&1 == 1 { return state{}, false } - us := int64(binary.LittleEndian.Uint64(b[16:])) + u := int64(binary.LittleEndian.Uint64(b[16:])) a := int64(binary.LittleEndian.Uint64(b[24:])) rate := math.Float64frombits(binary.LittleEndian.Uint64(b[32:])) armed := binary.LittleEndian.Uint32(b[40:]) - unsec := binary.LittleEndian.Uint32(b[44:]) generation := binary.LittleEndian.Uint64(b[48:]) check := binary.LittleEndian.Uint64(b[56:]) mu := int64(binary.LittleEndian.Uint64(b[64:])) ma := int64(binary.LittleEndian.Uint64(b[72:])) - if unsec >= 1e9 || check != pageCheck(seq, us, unsec, a, rate, armed, generation, mu, ma) || - binary.LittleEndian.Uint64(b[8:]) != seq { + if check != pageCheck(seq, u, a, rate, armed, generation, mu, ma) || binary.LittleEndian.Uint64(b[8:]) != seq { return state{}, false } if armed == 0 { return unarmed, true } - return state{Armed: true, V: float64(us) + float64(unsec)/1e9, Anchor: float64(a) / 1e9, Rate: rate}, true + return state{Armed: true, V: float64(u) / 1e9, Anchor: float64(a) / 1e9, Rate: rate}, true } // Universe follows the clock page, read every PagePoll, so a change is seen and the universe it left is held for Hold. diff --git a/src/agent_env/utils/egress_proxy/clock_test.go b/src/agent_env/utils/egress_proxy/clock_test.go index 8f303df28..22bb41503 100644 --- a/src/agent_env/utils/egress_proxy/clock_test.go +++ b/src/agent_env/utils/egress_proxy/clock_test.go @@ -13,21 +13,20 @@ import ( func page(seq uint64, universe, anchor time.Time, rate float64, armed bool) []byte { b := make([]byte, pageSize) - us, unsec, a := universe.Unix(), uint32(universe.Nanosecond()), anchor.UnixNano() + u, a := universe.UnixNano(), anchor.UnixNano() var on uint32 if armed { on = 1 } binary.LittleEndian.PutUint32(b[0:], pageMagic) - binary.LittleEndian.PutUint32(b[4:], pageVersion) + binary.LittleEndian.PutUint32(b[4:], 2) binary.LittleEndian.PutUint64(b[8:], seq) - binary.LittleEndian.PutUint64(b[16:], uint64(us)) + binary.LittleEndian.PutUint64(b[16:], uint64(u)) binary.LittleEndian.PutUint64(b[24:], uint64(a)) binary.LittleEndian.PutUint64(b[32:], math.Float64bits(rate)) binary.LittleEndian.PutUint32(b[40:], on) - binary.LittleEndian.PutUint32(b[44:], unsec) binary.LittleEndian.PutUint64(b[48:], 7) - binary.LittleEndian.PutUint64(b[56:], pageCheck(seq, us, unsec, a, rate, on, 7, a, a)) + binary.LittleEndian.PutUint64(b[56:], pageCheck(seq, u, a, rate, on, 7, a, a)) binary.LittleEndian.PutUint64(b[64:], uint64(a)) binary.LittleEndian.PutUint64(b[72:], uint64(a)) return b @@ -55,27 +54,6 @@ func TestAPageReadsAsTheUniverseItHoldsAndATornOneNot(t *testing.T) { } } -func TestAPageReachesPast2262AndBefore1970(t *testing.T) { - anchor := time.Unix(time.Now().Unix(), 0) - far := time.Date(9999, 6, 1, 12, 0, 0, 500000000, time.UTC) - s, ok := readPage(page(4, far, anchor, 3600, true)) - if !ok || s.V != float64(far.Unix())+0.5 { - t.Fatalf("9999: %+v %v", s, ok) - } - if got := s.at(float64(anchor.Unix()) + 1); got != float64(far.Unix())+3600.5 { - t.Fatalf("1 s on at rate 3600: %v", got) - } - past := time.Date(1949, 12, 31, 23, 59, 59, 750000000, time.UTC) - if s, ok := readPage(page(4, past, anchor, 1, true)); !ok || s.V != float64(past.Unix())+0.75 { - t.Fatalf("1949: %+v %v", s, ok) - } - old := page(4, far, anchor, 1, true) - binary.LittleEndian.PutUint32(old[4:], 2) - if _, ok := readPage(old); ok { - t.Fatal("a version 2 page read as one of this version") - } -} - func TestTheUniverseFollowsThePageFileAndHoldsTheOneItLeft(t *testing.T) { path := filepath.Join(t.TempDir(), "page") if err := os.WriteFile(path, page(2, time.Time{}, time.Time{}, 1, false), 0o644); err != nil { @@ -131,13 +109,4 @@ func TestThePagesTheFollowersWriterWritesReadAsTheUniverseTheyHold(t *testing.T) if s, ok := readPage(golden(t, "unarmed")); !ok || s != unarmed { t.Fatalf("unarmed: %+v %v", s, ok) } - if s, ok := readPage(golden(t, "far")); !ok || s.V != 253402214400.5 || s.Rate != 3600 { - t.Fatalf("far: %+v %v", s, ok) - } - if s, ok := readPage(golden(t, "past")); !ok || s.V != -631152000.25 || s.Rate != 1 { - t.Fatalf("past: %+v %v", s, ok) - } - if _, ok := readPage(golden(t, "version2")); ok { - t.Fatal("a version 2 page read as one of this version") - } } diff --git a/src/agent_env/utils/egress_proxy/proxy_test.go b/src/agent_env/utils/egress_proxy/proxy_test.go index fa2abfc85..772afe1f8 100644 --- a/src/agent_env/utils/egress_proxy/proxy_test.go +++ b/src/agent_env/utils/egress_proxy/proxy_test.go @@ -373,19 +373,6 @@ func TestEveryCertificateOfTheVerifiedChainBoundsPassingThrough(t *testing.T) { } } -func TestACertificateEndingPast2262BoundsPassingThroughAsWritten(t *testing.T) { - year := func(y int) time.Time { return time.Date(y, 1, 1, 0, 0, 0, 0, time.UTC) } - from, until := year(2020), time.Date(9999, 12, 31, 23, 59, 59, 0, time.UTC) - for _, y := range []int{2027, 2300, 9000} { - if !inside(from, until, []float64{float64(year(y).Unix())}) { - t.Fatalf("a universe in %d, inside a certificate to 9999, didn't pass through", y) - } - } - if inside(from, until, []float64{float64(year(2019).Unix())}) { - t.Fatal("a universe before the certificate passed through") - } -} - func TestASiteAskingForTheClientsCertificateIsPassedThroughForTheClientToAnswer(t *testing.T) { s := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "hello %d certificate", len(r.TLS.PeerCertificates)) diff --git a/src/agent_env/utils/egress_proxy/testdata/page-armed.hex b/src/agent_env/utils/egress_proxy/testdata/page-armed.hex index 072dbab8e..2aecf27e8 100644 --- a/src/agent_env/utils/egress_proxy/testdata/page-armed.hex +++ b/src/agent_env/utils/egress_proxy/testdata/page-armed.hex @@ -1 +1 @@ -4145434b03000000040000000000000000e10b5e0000000015cd68be7e91e5180000000000000040010000000000000007000000000000000250299fc7e8d2c600f2052a0100000000f2052a01000000 +4145434b02000000040000000000000000008ab9359ae51515cd68be7e91e51800000000000000400100000000000000070000000000000002b1a878f27237d300f2052a0100000000f2052a01000000 diff --git a/src/agent_env/utils/egress_proxy/testdata/page-far.hex b/src/agent_env/utils/egress_proxy/testdata/page-far.hex deleted file mode 100644 index 59a1f883e..000000000 --- a/src/agent_env/utils/egress_proxy/testdata/page-far.hex +++ /dev/null @@ -1 +0,0 @@ -4145434b03000000060000000000000000f0f2ff3a00000000000db77e91e518000000000020ac40010000000065cd1d09000000000000001b8cb537fdadb3db00f2052a0100000000f2052a01000000 diff --git a/src/agent_env/utils/egress_proxy/testdata/page-past.hex b/src/agent_env/utils/egress_proxy/testdata/page-past.hex deleted file mode 100644 index 9a22bad94..000000000 --- a/src/agent_env/utils/egress_proxy/testdata/page-past.hex +++ /dev/null @@ -1 +0,0 @@ -4145434b0300000008000000000000007f6261daffffffff00000db77e91e518000000000000f03f010000008017b42c0b00000000000000681e2612b800696a00f2052a0100000000f2052a01000000 diff --git a/src/agent_env/utils/egress_proxy/testdata/page-unarmed.hex b/src/agent_env/utils/egress_proxy/testdata/page-unarmed.hex index 382ad612b..7f6a95f54 100644 --- a/src/agent_env/utils/egress_proxy/testdata/page-unarmed.hex +++ b/src/agent_env/utils/egress_proxy/testdata/page-unarmed.hex @@ -1 +1 @@ -4145434b03000000020000000000000000000000000000000000000000000000000000000000f03f00000000000000000300000000000000147c4a7fb979c7a100000000000000000000000000000000 +4145434b02000000020000000000000000000000000000000000000000000000000000000000f03f00000000000000000300000000000000147c4a7fb979c7a100000000000000000000000000000000 diff --git a/src/agent_env/utils/egress_proxy/testdata/page-version2.hex b/src/agent_env/utils/egress_proxy/testdata/page-version2.hex deleted file mode 100644 index 2aecf27e8..000000000 --- a/src/agent_env/utils/egress_proxy/testdata/page-version2.hex +++ /dev/null @@ -1 +0,0 @@ -4145434b02000000040000000000000000008ab9359ae51515cd68be7e91e51800000000000000400100000000000000070000000000000002b1a878f27237d300f2052a0100000000f2052a01000000 diff --git a/src/agent_env/utils/egress_proxy/upstream.go b/src/agent_env/utils/egress_proxy/upstream.go index 717078bb4..bad2ea7db 100644 --- a/src/agent_env/utils/egress_proxy/upstream.go +++ b/src/agent_env/utils/egress_proxy/upstream.go @@ -227,8 +227,8 @@ func (p *Proxy) forget(dst, sni string) { // inside is whether every universe lies inside [from + Margin, until - Margin]. func inside(from, until time.Time, universes []float64) bool { - lo := seconds(from.Add(Margin)) - hi := seconds(until.Add(-Margin)) + lo := float64(from.Add(Margin).UnixNano()) / 1e9 + hi := float64(until.Add(-Margin).UnixNano()) / 1e9 for _, u := range universes { if u < lo || u > hi { return false @@ -237,11 +237,6 @@ func inside(from, until time.Time, universes []float64) bool { return true } -// seconds is t as Unix seconds at any date; UnixNano overflows past 2262, where a certificate may still end. -func seconds(t time.Time) float64 { - return float64(t.Unix()) + float64(t.Nanosecond())/1e9 -} - // dialAny dials each address in turn until one answers: which, or every one's error. func (p *Proxy) dialAny(dsts []string) (net.Conn, string, error) { var problems []string diff --git a/src/agent_env/utils/faketime_clock/agentenv_clock_page.c b/src/agent_env/utils/faketime_clock/agentenv_clock_page.c index c2b77ef1c..e55e011cd 100644 --- a/src/agent_env/utils/faketime_clock/agentenv_clock_page.c +++ b/src/agent_env/utils/faketime_clock/agentenv_clock_page.c @@ -186,10 +186,8 @@ static bool ft_deadline_moved(const struct timespec *fake_abs, struct timespec * } /* - * the clock page (version 3). 80 bytes, little-endian, rewritten in place by the follower: seq odd while it writes, - * then even; check is the xor of the other words and a constant. The universe at the anchor is universe_s seconds and - * universe_nsec nanoseconds (floored: before 1970 the seconds are negative, the nanoseconds not), so it reaches any date - * a 64-bit time_t holds; the anchor is real time. A realtime read in a faked process copies it + * the clock page. 64 bytes, little-endian, rewritten in place by the follower: seq odd while it writes, + * then even; check is the xor of the other words and a constant. A realtime read in a faked process copies it * lock-free and computes universe + (now - anchor) * rate (rate 0: universe), so every process agrees with no shared * start; the first thread to see a new generation also hands it to libfaketime's own state (rates of sleeps, the * time an absolute spec gives) under the MT lock. The page must be owned by AGENTENV_CLOCK_PAGE_UID (0 by default) and @@ -199,14 +197,14 @@ struct ft_clock_page { uint32_t magic, version; uint64_t seq; - int64_t universe_s, anchor_ns; + int64_t universe_ns, anchor_ns; double rate; - uint32_t armed, universe_nsec; + uint32_t armed, reserved; uint64_t generation, check; int64_t mono_universe_ns, mono_anchor_ns; }; #define FT_PAGE_MAGIC 0x4B434541u -#define FT_PAGE_VERSION 3u +#define FT_PAGE_VERSION 2u static const volatile struct ft_clock_page *ft_page = NULL; static uint64_t ft_page_applied = 0; static time_t ft_page_last_try = 0; @@ -216,9 +214,8 @@ static uint64_t ft_page_check(const struct ft_clock_page *p) { uint64_t rate_bits; memcpy(&rate_bits, &p->rate, sizeof rate_bits); - return p->seq ^ (uint64_t) p->universe_s ^ ((uint64_t) p->universe_nsec << 32) ^ (uint64_t) p->anchor_ns ^ rate_bits - ^ p->armed ^ p->generation ^ (uint64_t) p->mono_universe_ns ^ (uint64_t) p->mono_anchor_ns - ^ 0x9E3779B97F4A7C15ull; + return p->seq ^ (uint64_t) p->universe_ns ^ (uint64_t) p->anchor_ns ^ rate_bits ^ p->armed ^ p->generation + ^ (uint64_t) p->mono_universe_ns ^ (uint64_t) p->mono_anchor_ns ^ 0x9E3779B97F4A7C15ull; } static bool ft_page_snapshot(struct ft_clock_page *out) @@ -229,8 +226,7 @@ static bool ft_page_snapshot(struct ft_clock_page *out) if (s1 & 1) continue; out->magic = ft_page->magic; out->seq = s1; - out->universe_s = ft_page->universe_s; - out->universe_nsec = ft_page->universe_nsec; + out->universe_ns = ft_page->universe_ns; out->anchor_ns = ft_page->anchor_ns; out->rate = ft_page->rate; out->armed = ft_page->armed; @@ -241,7 +237,7 @@ static bool ft_page_snapshot(struct ft_clock_page *out) out->mono_anchor_ns = ft_page->mono_anchor_ns; __atomic_thread_fence(__ATOMIC_ACQUIRE); if (__atomic_load_n(&ft_page->seq, __ATOMIC_RELAXED) == s1 && out->magic == FT_PAGE_MAGIC - && out->version == FT_PAGE_VERSION && out->universe_nsec < 1000000000u + && out->version == FT_PAGE_VERSION && ft_page_check(out) == out->check) return true; } @@ -276,65 +272,26 @@ static void ft_page_open(void) ft_page = map; } -/* the universe's realtime at real realtime t (ns): seconds and nanoseconds (0 to 999,999,999); before the anchor, and - while frozen, the anchor's. Clock reads and every wait compute it here alike, so a wait never ends before a read - shows its deadline. */ -static inline void ft_page_at(const struct ft_clock_page *s, int64_t t, int64_t *sec, int64_t *nsec) +/* a time in ns as libfaketime's spec reads it (ft_parse_epoch): its sign once, before the whole value, so a time before + 1970 isn't written "-1.-5". */ +static void ft_spec_time(char *out, size_t size, int64_t ns) { - int64_t add, q, r; - *sec = s->universe_s; - *nsec = s->universe_nsec; - if (s->rate == 0 || t <= s->anchor_ns) return; - if (s->rate == 1.0) - add = t - s->anchor_ns; - else - { - double x = (double) (t - s->anchor_ns) * s->rate; - if (x >= 9e18 || x <= -9e18) - { /* centuries of universe since the anchor: whole seconds */ - *sec += (int64_t) (x / 1e9); - return; - } - add = (int64_t) x; - } - q = add / 1000000000LL; - r = add % 1000000000LL; - if (r < 0) - { - q -= 1; - r += 1000000000LL; - } - *sec += q; - *nsec += r; - if (*nsec >= 1000000000LL) - { - *sec += 1; - *nsec -= 1000000000LL; - } -} - -/* a time as libfaketime reads one: "seconds.nanoseconds", the sign written once in front. */ -static void ft_spec_time(char *out, size_t size, int64_t s, uint32_t ns) -{ - if (s < 0 && ns > 0) - snprintf(out, size, "-%llu.%09u", (unsigned long long) -(s + 1), 1000000000u - ns); - else - snprintf(out, size, "%s%llu.%09u", s < 0 ? "-" : "", (unsigned long long) (s < 0 ? -s : s), ns); + uint64_t magnitude = ns < 0 ? -(uint64_t) ns : (uint64_t) ns; + snprintf(out, size, "%s%llu.%09llu", ns < 0 ? "-" : "", (unsigned long long) (magnitude / 1000000000u), + (unsigned long long) (magnitude % 1000000000u)); } /* libfaketime's own state set to the page's clock; called with the MT lock held. */ static void ft_page_apply_locked(const struct ft_clock_page *s) { - char spec[160], universe[48], anchor[48]; + char spec[160], universe[32], anchor[32]; if (s->generation == ft_page_applied) return; if (!s->armed) snprintf(spec, sizeof spec, "+0 x1"); else { - int64_t anchor_ns = s->anchor_ns; - int64_t anchor_s = anchor_ns / 1000000000LL - (anchor_ns % 1000000000LL < 0); - ft_spec_time(universe, sizeof universe, s->universe_s, s->universe_nsec); - ft_spec_time(anchor, sizeof anchor, anchor_s, (uint32_t) (anchor_ns - anchor_s * 1000000000LL)); + ft_spec_time(universe, sizeof universe, s->universe_ns); + ft_spec_time(anchor, sizeof anchor, s->anchor_ns); snprintf(spec, sizeof spec, "@%s x%.17g ^%s", universe, s->rate, anchor); } parse_ft_string(spec); diff --git a/src/agent_env/utils/faketime_clock/agentenv_clock_waits.c b/src/agent_env/utils/faketime_clock/agentenv_clock_waits.c index cf2cddccc..04a49e15e 100644 --- a/src/agent_env/utils/faketime_clock/agentenv_clock_waits.c +++ b/src/agent_env/utils/faketime_clock/agentenv_clock_waits.c @@ -56,9 +56,6 @@ static long ft_raw_syscall6(long n, long a, long b, long c, long d, long e, long #define FT_NS 1000000000LL #define FT_NEVER INT64_MAX -/* a universe time in nanoseconds: 128 bits, so it reaches any date a 64-bit time_t holds (64 bits run out in 2262). - Real times, and elapsed and universe durations, stay 64-bit. */ -typedef __int128 ft_uns_t; static __thread struct ft_clock_page ft_tl_snap; static __thread bool ft_tl_snap_ok = false; @@ -143,19 +140,6 @@ static inline int64_t ft_ns(const struct timespec *t) if (t->tv_sec < -9000000000LL) return -(FT_NEVER / 2); return (int64_t) t->tv_sec * FT_NS + t->tv_nsec; } -static inline ft_uns_t ft_uns(const struct timespec *t) -{ - return (ft_uns_t) t->tv_sec * FT_NS + t->tv_nsec; -} -static inline ft_uns_t ft_page_universe(const struct ft_clock_page *s) -{ - return (ft_uns_t) s->universe_s * FT_NS + s->universe_nsec; -} -/* a universe duration as 64 bits, saturated. */ -static inline int64_t ft_clamp64(ft_uns_t v) -{ - return v > (ft_uns_t) FT_NEVER ? FT_NEVER : v < -(ft_uns_t) FT_NEVER ? -FT_NEVER : (int64_t) v; -} static inline struct timespec ft_ts(int64_t ns) { struct timespec t; @@ -199,27 +183,26 @@ static inline bool ft_universe_clock(clockid_t c) } /* the universe's realtime at real realtime t; before the anchor, the anchor's. */ -static ft_uns_t ft_page_rt(const struct ft_clock_page *s, int64_t t) +static int64_t ft_page_rt(const struct ft_clock_page *s, int64_t t) { - int64_t sec, nsec; if (!s->armed) return t; - ft_page_at(s, t, &sec, &nsec); - return (ft_uns_t) sec * FT_NS + nsec; + if (s->rate == 0 || t <= s->anchor_ns) return s->universe_ns; + if (s->rate == 1.0) return s->universe_ns + (t - s->anchor_ns); + return s->universe_ns + (int64_t) ((double) (t - s->anchor_ns) * s->rate); } /* the real realtime at which the universe reaches ``due``; 0 (the past) once it has, FT_NEVER while frozen short of it. */ -static int64_t ft_real_of(const struct ft_clock_page *s, ft_uns_t due) +static int64_t ft_real_of(const struct ft_clock_page *s, int64_t due) { - ft_uns_t u = ft_page_universe(s); double r; - if (!s->armed) return due < 1 ? 1 : ft_clamp64(due); - if (due <= u) return 1; + if (!s->armed) return due < 1 ? 1 : due; + if (due <= s->universe_ns) return 1; if (s->rate <= 0) return FT_NEVER; - r = (double) (due - u) / s->rate; + r = (double) (due - s->universe_ns) / s->rate; if (r > 4e18) return FT_NEVER; return s->anchor_ns + (int64_t) r + 1; } -static inline bool ft_reached(const struct ft_clock_page *s, ft_uns_t due) +static inline bool ft_reached(const struct ft_clock_page *s, int64_t due) { return ft_page_rt(s, ft_real_rt()) >= due; } @@ -259,8 +242,7 @@ struct ft_timer int clock; int flags; /* the caller's flags, TFD_TIMER_CANCEL_ON_SET kept */ int real_set; /* the kernel timer is armed */ - ft_uns_t due; /* universe ns */ - int64_t interval; /* universe ns */ + int64_t due, interval; /* universe ns */ struct ft_clock_page pg; /* the page it was last armed from */ }; #define FT_TIMERS_MAX 1024 @@ -304,9 +286,9 @@ static int ft_timer_real_get(struct ft_timer *t, struct itimerspec *cur) return t->kind == 1 ? (*real_timerfd_gettime)(t->fds[0], cur) : (*real_timer_gettime_new)(t->id, cur); } /* the next expiration at or after ``after``. */ -static ft_uns_t ft_timer_next(const struct ft_timer *t, ft_uns_t after) +static int64_t ft_timer_next(const struct ft_timer *t, int64_t after) { - ft_uns_t next = t->due; + int64_t next = t->due; if (t->interval > 0 && next < after) next += ((after - next + t->interval - 1) / t->interval) * t->interval; return next; } @@ -316,8 +298,7 @@ static int ft_timer_arm(struct ft_timer *t, const struct ft_clock_page *s, bool { struct itimerspec real, cur; double rate = s->armed ? s->rate : 1.0; - ft_uns_t next = t->due; - int64_t at; + int64_t next = t->due, at; int r; memset(&real, 0, sizeof real); if (!first && t->real_set && t->interval == 0 && ft_timer_real_get(t, &cur) == 0 && cur.it_value.tv_sec == 0 @@ -364,8 +345,8 @@ static void ft_timer_value(struct ft_timer *t, struct itimerspec *out) out->it_interval = ft_ts(t->interval); if (ft_snap(&s)) { - ft_uns_t now = ft_page_rt(&s, ft_real_rt()), next = ft_timer_next(t, now); - out->it_value = ft_ts(next - now < 1 ? 1 : ft_clamp64(next - now)); + int64_t now = ft_page_rt(&s, ft_real_rt()), next = ft_timer_next(t, now); + out->it_value = ft_ts(next - now < 1 ? 1 : next - now); } } @@ -379,8 +360,7 @@ struct ft_cw { pthread_cond_t *cond; int used, woken; - ft_uns_t due; - int64_t real_due; + int64_t due, real_due; uint64_t gen; /* the page generation its real_due came from; FT_CW_UNPLANNED before */ }; #define FT_CW_MAX 512 @@ -527,7 +507,7 @@ static inline void ft_deferred_cancel(int old) } /* a sleep until the universe reaches ``due``, on the page's seq. 0, or EINTR. */ -static int ft_rt_sleep(const struct ft_clock_page *first, ft_uns_t due) +static int ft_rt_sleep(const struct ft_clock_page *first, int64_t due) { struct ft_clock_page s = *first; pthread_testcancel(); @@ -601,7 +581,7 @@ static int ft_wait2(uint32_t *word, uint32_t val, bool private_word, uint32_t se static long ft_u_futex_rt(uint32_t *uaddr, int op, uint32_t val, const struct timespec *abs, bool *handled) { struct ft_clock_page s; - ft_uns_t due = ft_uns(abs); + int64_t due = ft_ns(abs); *handled = false; if (!ft_snap(&s) || !ft_valid_due(abs, &s)) return 0; *handled = true; @@ -645,7 +625,7 @@ static void ft_sem_unwait(void *sem) } /* as one of the semaphore's waiters (counted in data's high word): 0 with a token taken, or the error. A cancelled wait leaves the waiters it joined, as glibc's does. */ -static int ft_sem_wait_slow(struct ft_new_sem *sem, struct ft_clock_page *s, ft_uns_t due) +static int ft_sem_wait_slow(struct ft_new_sem *sem, struct ft_clock_page *s, int64_t due) { volatile int err = 0; pthread_cleanup_push(ft_sem_unwait, sem); @@ -682,7 +662,7 @@ static int ft_sem_wait_slow(struct ft_new_sem *sem, struct ft_clock_page *s, ft_ pthread_cleanup_pop(err != 0); return err; } -static int ft_u_sem_wait(sem_t *sem_, ft_uns_t due, bool *handled) +static int ft_u_sem_wait(sem_t *sem_, int64_t due, bool *handled) { struct ft_new_sem *sem = (struct ft_new_sem *) sem_; struct ft_clock_page s; @@ -726,8 +706,7 @@ static int ft_u_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex, const st struct ft_cw *w = NULL; struct timespec end; sigset_t old; - ft_uns_t due = ft_uns(abstime); - int64_t real_due; + int64_t due = ft_ns(abstime), real_due; int r, woken; if (!ft_snap(&s)) return -1; if (ft_reached(&s, due)) return ETIMEDOUT; @@ -771,7 +750,7 @@ static int ft_u_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex, const st /* a realtime mutex wait: glibc's mutex has no way in, so slices (AGENTENV_WAIT_SLICE_MS) of a real CLOCK_MONOTONIC wait, which loses nothing when it times out, with the page read between them. */ -static int ft_u_mutex_lock(pthread_mutex_t *mutex, ft_uns_t due, bool *handled) +static int ft_u_mutex_lock(pthread_mutex_t *mutex, int64_t due, bool *handled) { struct ft_clock_page s; *handled = false; @@ -873,7 +852,7 @@ static int ft_u_timerfd_settime(int fd, int flags, const struct itimerspec *nv, } t->clock = clock; t->flags = flags; - t->due = ft_uns(&nv->it_value); + t->due = ft_ns(&nv->it_value); t->interval = ft_ns(&nv->it_interval); t->tracked = 1; if (ov != NULL) @@ -1171,7 +1150,7 @@ int timer_settime(timer_t id, int flags, const struct itimerspec *nv, struct iti else (*real_timer_gettime_new)(id, ov); } - t->due = ft_uns(&nv->it_value); + t->due = ft_ns(&nv->it_value); t->interval = ft_ns(&nv->it_interval); t->tracked = 1; r = ft_timer_arm(t, &s, true); diff --git a/src/agent_env/utils/faketime_clock/clockpage.py b/src/agent_env/utils/faketime_clock/clockpage.py index 72c238b69..4002bb6c2 100644 --- a/src/agent_env/utils/faketime_clock/clockpage.py +++ b/src/agent_env/utils/faketime_clock/clockpage.py @@ -1,6 +1,5 @@ -"""The follower's side of the clock page (version 3) and of the clock file: writes the universe's realtime -clock to both. The page holds the universe at the anchor as whole seconds and nanoseconds, so it reaches any date the -gateway's clock takes (to 9999-12-31); version 2's one signed 64-bit count of nanoseconds ran out on 2262-04-11. Elapsed time is real, so the page's monotonic fields are written as the real monotonic clock (identity) +"""The follower's side of the clock page (version 2) and of the clock file: writes the universe's realtime +clock to both. Elapsed time is real, so the page's monotonic fields are written as the real monotonic clock (identity) and no library reads them; they stay so the page keeps its 80-byte layout. clockpage.py set UNIVERSE RATE [ANCHOR] armed: UNIVERSE (epoch s) at real time ANCHOR (default now), at RATE @@ -31,12 +30,9 @@ PAGE = os.environ.get("AGENTENV_CLOCK_PAGE", "/dev/shm/agentenv-clock") FILE = os.environ.get("AGENTENV_CLOCK_FILE", "/run/agentenv-clock/clock") -MAGIC, VERSION = 0x4B434541, 3 -# magic version seq universe_s anchor_ns rate armed universe_nsec generation check mono_universe_ns mono_anchor_ns: -# the universe at the anchor is universe_s seconds and universe_nsec (0 to 999,999,999) nanoseconds, floored, so a time -# before 1970 has negative seconds and positive nanoseconds; the anchor is this machine's real time. +MAGIC, VERSION = 0x4B434541, 2 +# magic version seq universe_ns anchor_ns rate armed reserved generation check mono_universe_ns mono_anchor_ns LAYOUT = struct.Struct(" int: +def check(seq, universe_ns, anchor_ns, rate, armed, generation, mono_universe_ns, mono_anchor_ns) -> int: rate_bits = struct.unpack(" bytes: - """The page's bytes for these fields, the universe given in nanoseconds of any size, its check among them: what - every write writes and every reader checks, agent-env's libfaketime and the egress proxy (its egress/testdata pins - them).""" - universe_s, universe_nsec = divmod(universe_ns, NS) - return LAYOUT.pack(MAGIC, VERSION, seq, universe_s, anchor_ns, rate, armed, universe_nsec, generation, - check(seq, universe_s, universe_nsec, anchor_ns, rate, armed, generation, mono_universe_ns, - mono_anchor_ns), + """The page's bytes for these fields, its check among them: what every write writes and every reader checks, + agent-env's libfaketime and the egress proxy (its egress/testdata pins them).""" + return LAYOUT.pack(MAGIC, VERSION, seq, universe_ns, anchor_ns, rate, armed, 0, generation, + check(seq, universe_ns, anchor_ns, rate, armed, generation, mono_universe_ns, mono_anchor_ns), mono_universe_ns, mono_anchor_ns) -def read(raw: bytes) -> tuple | None: - """A page's (seq, armed, universe_ns, anchor_ns, rate, generation), or None while it's being written, torn, or not a - version 3 page.""" - if len(raw) < LAYOUT.size: - return None - magic, version, seq, universe_s, anchor_ns, rate, armed, universe_nsec, generation, checked, mono_u, mono_a = \ - LAYOUT.unpack(raw[:LAYOUT.size]) - if (magic, version) != (MAGIC, VERSION) or seq & 1 or universe_nsec >= NS or checked != check( - seq, universe_s, universe_nsec, anchor_ns, rate, armed, generation, mono_u, mono_a): - return None - return seq, armed, universe_s * NS + universe_nsec, anchor_ns, rate, generation - - -def spec(armed: int, universe_ns: int, rate: float, anchor_ns: int) -> str: - """libfaketime's specification of this clock, exact at any date: "@seconds.nanoseconds", the sign written once in - front, as libfaketime reads a time before 1970.""" - if not armed: - return "+0 x1" - return f"@{_seconds(universe_ns)} x{rate:g} ^{_seconds(anchor_ns)}" - - -def _seconds(ns: int) -> str: - whole, part = divmod(abs(ns), NS) - return f"{'-' if ns < 0 else ''}{whole}.{part:09d}" - - def open_page() -> mmap.mmap: try: fd = os.open(PAGE, os.O_RDWR | os.O_CREAT | os.O_EXCL, 0o644) @@ -97,7 +64,7 @@ def open_page() -> mmap.mmap: fd = os.open(PAGE, os.O_RDWR) if os.fstat(fd).st_uid != os.getuid(): raise SystemExit(f"{PAGE} isn't ours") - if os.fstat(fd).st_size < LAYOUT.size or os.pread(fd, 8, 0) != struct.pack(" int: def write(armed: int, universe: float, rate: float, anchor: float) -> dict: m = open_page() - _, _, seq, o_us, o_a, o_rate, o_armed, o_unsec, generation, _, _, _ = LAYOUT.unpack(m[:LAYOUT.size]) - o_u = o_us * NS + o_unsec - universe_ns, anchor_ns = int(Decimal(str(universe)) * NS), int(Decimal(str(anchor)) * NS) + _, _, seq, o_u, o_a, o_rate, o_armed, _, generation, _, _, _ = LAYOUT.unpack(m[:LAYOUT.size]) + universe_ns, anchor_ns = int(Decimal(str(universe)) * 10**9), int(Decimal(str(anchor)) * 10**9) if not armed: rate = 1.0 generation += 1 @@ -149,12 +115,12 @@ def write(armed: int, universe: float, rate: float, anchor: float) -> dict: m[8:16] = struct.pack(" 1 else 0, + return {"generation": generation, "spec": spec, "jump_ns": new_now - old_now if generation > 1 else 0, "continued": bool(continued), "universe_ns": universe_ns, "anchor_ns": anchor_ns} @@ -164,9 +130,7 @@ def create(owner: str) -> None: try: st = os.lstat(PAGE) if stat.S_ISREG(st.st_mode) and st.st_uid == user.pw_uid and st.st_size == LAYOUT.size: - with open(PAGE, "rb") as f: - if f.read(8) == struct.pack(" None: print(write(0, 0.0, 1.0, time.time())) else: with open(PAGE, "rb") as f: - print(read(f.read(LAYOUT.size))) + print(LAYOUT.unpack(f.read(LAYOUT.size))) diff --git a/src/agent_env/utils/faketime_clock/libfaketime.patch b/src/agent_env/utils/faketime_clock/libfaketime.patch index 8f7254b65..df8bafb54 100644 --- a/src/agent_env/utils/faketime_clock/libfaketime.patch +++ b/src/agent_env/utils/faketime_clock/libfaketime.patch @@ -167,7 +167,7 @@ diff -ruN a/src/libfaketime.c b/src/libfaketime.c + if (ft_uw_active()) + { + struct ft_clock_page s; -+ if (ft_snap(&s) && ft_valid_due(req, &s)) return ft_rt_sleep(&s, ft_uns(req)); ++ if (ft_snap(&s) && ft_valid_due(req, &s)) return ft_rt_sleep(&s, ft_ns(req)); + } if (real_clock_nanosleep == NULL) { @@ -356,7 +356,7 @@ diff -ruN a/src/libfaketime.c b/src/libfaketime.c - DONT_FAKE_TIME(result = (*real_sem_clockwait)(sem, clockid, abstime)); - return result; + bool handled; -+ result = ft_u_sem_wait(sem, ft_uns(abs_timeout), &handled); ++ result = ft_u_sem_wait(sem, ft_ns(abs_timeout), &handled); + if (handled) return result; } - @@ -402,7 +402,7 @@ diff -ruN a/src/libfaketime.c b/src/libfaketime.c - } - real_abstime_pt = &real_abstime; + bool handled; -+ result = ft_u_sem_wait(sem, ft_uns(abstime), &handled); ++ result = ft_u_sem_wait(sem, ft_ns(abstime), &handled); + if (handled) return result; } - else @@ -992,7 +992,7 @@ diff -ruN a/src/libfaketime.c b/src/libfaketime.c if ((faketimerc = open(custom_filename, O_RDONLY)) != -1 || (faketimerc = open(filename, O_RDONLY)) != -1 || (faketimerc = open("/etc/faketimerc", O_RDONLY)) != -1) -@@ -3248,6 +3277,38 @@ +@@ -3248,6 +3277,48 @@ tp_save.tv_nsec = tp->tv_nsec; if (dont_fake) return 0; @@ -1020,10 +1020,20 @@ diff -ruN a/src/libfaketime.c b/src/libfaketime.c + ft_tl_scale = (s.armed && s.rate > 0) ? 1.0 / s.rate : 1.0; + if (s.armed) + { -+ int64_t now = (int64_t) tp->tv_sec * 1000000000LL + tp->tv_nsec, sec, nsec; -+ ft_page_at(&s, now, &sec, &nsec); -+ tp->tv_sec = (time_t) sec; -+ tp->tv_nsec = (long) nsec; ++ int64_t now = (int64_t) tp->tv_sec * 1000000000LL + tp->tv_nsec, fake; ++ if (s.rate == 0 || now <= s.anchor_ns) ++ fake = s.universe_ns; ++ else if (s.rate == 1.0) ++ fake = s.universe_ns + (now - s.anchor_ns); ++ else ++ fake = s.universe_ns + (int64_t) ((double) (now - s.anchor_ns) * s.rate); ++ tp->tv_sec = fake / 1000000000LL; ++ tp->tv_nsec = fake % 1000000000LL; ++ if (tp->tv_nsec < 0) ++ { ++ tp->tv_sec -= 1; ++ tp->tv_nsec += 1000000000LL; ++ } + } + return 0; + } @@ -1384,7 +1394,7 @@ diff -ruN a/src/libfaketime.c b/src/libfaketime.c + if (ft_uw_active() && ft_translates_wait(abstime) && real_pthread_mutex_clocklock != NULL) + { + bool handled; -+ int r = ft_u_mutex_lock(mutex, ft_uns(abstime), &handled); ++ int r = ft_u_mutex_lock(mutex, ft_ns(abstime), &handled); + if (handled) return r; + } + if (!ft_translates_wait(abstime) || real_pthread_mutex_clocklock == NULL) @@ -1401,7 +1411,7 @@ diff -ruN a/src/libfaketime.c b/src/libfaketime.c + if (ft_uw_active() && ft_translates_wait(abstime) && clockid == CLOCK_REALTIME) + { + bool handled; -+ int r = ft_u_mutex_lock(mutex, ft_uns(abstime), &handled); ++ int r = ft_u_mutex_lock(mutex, ft_ns(abstime), &handled); + if (handled) return r; + } + if (clockid != CLOCK_REALTIME || !ft_translates_wait(abstime)) diff --git a/tst/clock/harness.py b/tst/clock/harness.py index 6b831b715..f3dbd2aea 100644 --- a/tst/clock/harness.py +++ b/tst/clock/harness.py @@ -72,11 +72,11 @@ def user_cmd(argv, env=None): def page(): with open(clockpage.PAGE, "rb") as f: - return clockpage.read(f.read(clockpage.LAYOUT.size)) + return clockpage.LAYOUT.unpack(f.read(clockpage.LAYOUT.size)) def universe_now() -> tuple[float, float]: - _, armed, u, a, rate, _ = page() + _, _, _, u, a, rate, armed, _, _, _, _, _ = page() now = time.time() return (now, 1.0) if not armed else (u / 1e9 + (now - a / 1e9) * rate, rate) @@ -99,7 +99,7 @@ def set_rate(rate: float) -> dict: def start(days: float = -182) -> float: """The universe a gate starts at: ``days`` from now, or the time CLOCK_BASE names (epoch seconds), which runs the - gates far past 2262, or before 1970, as well.""" + gates near either end of the clock's range as well.""" base = os.environ.get("CLOCK_BASE") return float(base) if base else time.time() + days * DAY @@ -457,7 +457,7 @@ def deadwriter(): written = set_clock(time.time() + 21 * DAY, 1) after = float(subprocess.run(user_cmd(["date", "+%s.%N"]), capture_output=True, text=True).stdout) preload(None) - return {"dead_seq": seq, "seq": page()[0], "continued": written["continued"], + return {"dead_seq": seq, "seq": page()[2], "continued": written["continued"], "read": _classify(after, before, 21 * DAY)} diff --git a/tst/clock/programs/rtbase.h b/tst/clock/programs/rtbase.h index 2e015e665..f7062462e 100644 --- a/tst/clock/programs/rtbase.h +++ b/tst/clock/programs/rtbase.h @@ -1,6 +1,6 @@ -/* rtbase.h: the universe's realtime as 64-bit nanoseconds counted from the second it was first read, so the values fit - at any date the clock reaches (a count from 1970 runs out in 2262); rt_ts turns one back into a time. Read it once - before starting threads. */ +/* rtbase.h: the universe's realtime as 64-bit nanoseconds counted from the second it was first read, so a deadline + computed near either end of the clock's range stays inside 64 bits, and rt_ts turns one back into a valid time before + 1970 too (its nanoseconds floored, never negative). Read it once before starting threads. */ #include #include static int64_t rt_base_s; diff --git a/tst/clock/programs/torn.c b/tst/clock/programs/torn.c index 016fd1b06..2b3e194f6 100644 --- a/tst/clock/programs/torn.c +++ b/tst/clock/programs/torn.c @@ -11,7 +11,7 @@ #include #include "rawsys.h" #define NS 1000000000LL -/* offsets of 128 bits: a universe in 9999 is some 8,000 years from real time, past 64 bits of nanoseconds */ +/* offsets of 128 bits: a universe in 1677 is some 350 years from real time, past 64 bits of nanoseconds */ typedef __int128 off_t128; static double seconds; static off_t128 off_a, off_b; static int64_t rt0, raw0; static int64_t ns(clockid_t c) { struct timespec t; clock_gettime(c, &t); return (int64_t)t.tv_sec * NS + t.tv_nsec; } diff --git a/tst/clock/range_test.py b/tst/clock/range_test.py index 1e5e13f8f..f78ac10d0 100644 --- a/tst/clock/range_test.py +++ b/tst/clock/range_test.py @@ -1,6 +1,7 @@ -"""The clock's range: the page holds the universe as whole seconds and nanoseconds, so clock reads and every kind of wait -follow it before 1970, across 2262-04-11 (where a signed 64-bit count of nanoseconds runs out), and far past it, to -9999. Each gate runs as its own gate does at the date CLOCK_BASE names, held to the same bounds.""" +"""The clock's range, 1677-09-21T00:12:44Z to 2262-04-11T23:47:16Z, the times 64 bits of nanoseconds since 1970 hold +(as the page and Python keep time): clock reads and every kind of wait follow the universe near either end, before 1970 +and in the last hour the gateway arms at rate 1. Each gate runs as its own gate does at the date CLOCK_BASE names, held +to the same bounds.""" from datetime import datetime, timezone import pytest @@ -9,34 +10,37 @@ from tst.clock.waits_test import JUMP_RC, at_jump, failed, within BASES = { + "1677": datetime(1677, 9, 22, tzinfo=timezone.utc), "1950": datetime(1950, 1, 1, 12, tzinfo=timezone.utc), - # Six seconds short of 2262-04-11T23:47:16.854775807Z, the last time 64 bits of nanoseconds hold: each gate crosses it. - "2262": datetime(2262, 4, 11, 23, 47, 10, tzinfo=timezone.utc), - "3026": datetime(3026, 11, 23, 12, tzinfo=timezone.utc), - "9999": datetime(9999, 6, 1, 12, tzinfo=timezone.utc), + # Far enough before the end for the gates that move the universe on: the jumps' 8 weeks, the torn reads' 203 days. + "2261": datetime(2261, 8, 1, tzinfo=timezone.utc), } +# The latest the gateway arms at rate 1: an hour before the end of the range. +LAST_HOUR = datetime(2262, 4, 11, 22, 47, 16, tzinfo=timezone.utc) JUMP_ROUNDS = 8 +def _base(when: datetime) -> list[str]: + return ["-e", f"CLOCK_BASE={int(when.timestamp())}"] + + @pytest.fixture(scope="module", params=list(BASES)) def at(request, gate): """``gate``, with the universe starting at one of BASES.""" - env = ["-e", f"CLOCK_BASE={int(BASES[request.param].timestamp())}"] - def run(name: str, *args, timeout: float = 600): - return gate(name, *args, timeout=timeout, docker_args=env) + return gate(name, *args, timeout=timeout, docker_args=_base(BASES[request.param])) - run.base = request.param return run -@pytest.fixture(scope="module") -def waits(at): - return {sc["scenario"]: sc["results"] for sc in at("waits")} +@pytest.fixture(scope="module", params=[*BASES, "last hour"]) +def waits(request, gate): + when = LAST_HOUR if request.param == "last hour" else BASES[request.param] + return {sc["scenario"]: sc["results"] for sc in gate("waits", docker_args=_base(when))} @pytest.mark.parametrize("rate", [1, 2, 60]) -def test_a_wait_is_real_elapsed_time_or_a_clock_time_reached_at_the_rate_at_any_date(waits, rate): +def test_a_wait_is_real_elapsed_time_or_a_clock_time_reached_at_the_rate_near_either_end(waits, rate): results = waits[f"rate {rate}"] assert len(results) == 64 and not [r for r in results if "status" in r] elapsed = {r["api"]: r["real"] for r in results if r["class"] == "elapsed"} @@ -46,14 +50,14 @@ def test_a_wait_is_real_elapsed_time_or_a_clock_time_reached_at_the_rate_at_any_ assert {api: s for api, s in clock.items() if not 1 / rate - 0.01 <= s <= clock_time_bound(rate)} == {} -def test_frozen_at_any_date_a_clock_time_wait_ends_at_the_advance(waits): +def test_frozen_near_either_end_a_clock_time_wait_ends_at_the_advance(waits): results = waits["frozen, +1 h at 2.5 s"] assert len(results) == 64 and not [r for r in results if "status" in r] and failed(results) == {} assert {r["api"]: r["end_after_change_ms"] for r in results if r["class"] == "clock_time" and not within(r, -1, LATE_MS)} == {} -def test_a_jump_at_any_date_ends_the_waits_it_passes_and_none_other(at): +def test_a_jump_near_either_end_ends_the_waits_it_passes_and_none_other(at): jumps = at("jumps", JUMP_ROUNDS, 5420) assert len(jumps["rounds"]) == JUMP_ROUNDS and jumps["mono_back_total"] == 0 wrong = [] @@ -71,7 +75,7 @@ def test_a_jump_at_any_date_ends_the_waits_it_passes_and_none_other(at): assert wrong == [] -def test_a_timerfd_at_any_date_is_followed_through_its_duplicates(at): +def test_a_timerfd_near_either_end_is_followed_through_its_duplicates(at): for how, r in at("timerfds").items(): expected = (0, 3) if how == "failed" else (0, 0) if how.startswith(("vfork_", "python_")) else (1, 0) assert (r["same_number"], r["failed_calls"]) == expected, (how, r) @@ -79,23 +83,24 @@ def test_a_timerfd_at_any_date_is_followed_through_its_duplicates(at): assert at_jump(r), (how, r) -def test_a_cancelled_wait_at_any_date_goes_at_once(at): +def test_a_cancelled_wait_near_either_end_goes_at_once(at): r = at("cancel") assert (r["sem_cancelled"], r["sem_waiters"], r["cns_cancelled"], r["cond_cancelled"]) == (1, 0, 1, 600), r assert r["rc"] == 110 and at_jump(r), r -def test_realtime_never_steps_back_under_a_stalled_writer_at_any_date(at): +def test_realtime_never_steps_back_under_a_stalled_writer_near_either_end(at): r = at("stall", 500) assert r["writes"] == 500 and r["reads"] > 100_000 assert (r["rt_back"], r["mono_back"]) == (0, 0), r -def test_a_read_at_any_date_is_never_torn_between_two_pages(at): +def test_a_read_near_either_end_is_never_torn_between_two_pages(at): r = at("torn", 5.0) assert r["writes"] > 500 and r["universe_a"] > 0 and r["universe_b"] > 0 and r["torn"] == 0, r -def test_chrome_runs_every_launch_past_2262(gate): - r = gate("chromium", "agentenv", 16, 8, 20.0, docker_args=["-e", f"CLOCK_BASE={int(BASES['9999'].timestamp())}"]) +@pytest.mark.parametrize("when", [BASES["1677"], LAST_HOUR], ids=["1677", "last hour"]) +def test_chrome_runs_every_launch_near_either_end(gate, when): + r = gate("chromium", "agentenv", 16, 8, 20.0, docker_args=_base(when)) assert (r["launches"], r["failed"]) == (16, 0), r diff --git a/tst/unit/agents/test_agent_egress.py b/tst/unit/agents/test_agent_egress.py index 6364bcc87..49e02ec19 100644 --- a/tst/unit/agents/test_agent_egress.py +++ b/tst/unit/agents/test_agent_egress.py @@ -97,8 +97,6 @@ def _torn(page: bytes) -> bytes: pytest.param(_torn(_page(1)), True, id="torn-armed"), pytest.param(_torn(_page(0)), False, id="torn-unarmed"), pytest.param(_page(1)[:40], False, id="short"), - pytest.param(clockpage.encode(2, 253402300799 * 10**9, 0, 1.0, 1, 1, 0, 0), True, id="armed-in-9999"), - pytest.param(_page(1)[:4] + (2).to_bytes(4, "little") + _page(1)[8:], False, id="version-2"), pytest.param(b"\0" * 80, False, id="no-magic"), pytest.param(bytes(range(80)), False, id="garbage"), pytest.param(None, False, id="no-page"), diff --git a/tst/unit/env/envs/test_computer_clock_follower.py b/tst/unit/env/envs/test_computer_clock_follower.py index 7eb085e4f..9f57d3f2d 100644 --- a/tst/unit/env/envs/test_computer_clock_follower.py +++ b/tst/unit/env/envs/test_computer_clock_follower.py @@ -109,7 +109,8 @@ def status(self) -> dict: def universe(self) -> float: with open(page.PAGE, "rb") as f: - _, armed, universe_ns, anchor_ns, rate, _ = page.read(f.read(page.LAYOUT.size)) + fields = page.LAYOUT.unpack(f.read(page.LAYOUT.size)) + _, _, _, universe_ns, anchor_ns, rate, armed, *_ = fields return page._universe_at(armed, universe_ns, anchor_ns, rate, time.time_ns()) / 1e9 def until(self, check, within: float = 5.0): diff --git a/tst/unit/env/envs/test_computer_clock_page.py b/tst/unit/env/envs/test_computer_clock_page.py deleted file mode 100644 index 0e3d458bc..000000000 --- a/tst/unit/env/envs/test_computer_clock_page.py +++ /dev/null @@ -1,116 +0,0 @@ -"""The clock page's format (version 3, utils/faketime_clock/clockpage.py): the universe at the anchor as whole seconds -and nanoseconds, so a page holds any date the gateway's clock takes, from before 1970 to 9999-12-31, where version 2's -signed 64-bit count of nanoseconds ran out on 2262-04-11; the specification libfaketime reads from the clock file is -exact at any of them; and a page of another version is never read as this one's.""" - -from __future__ import annotations - -import getpass -import importlib.util -import struct -import time -from datetime import datetime, timedelta, timezone -from pathlib import Path - -import pytest - -import agent_env - -CLOCK = Path(agent_env.__file__).parent / "utils" / "faketime_clock" -NS = 10**9 -INT64_MAX_NS = 2**63 - 1 -EPOCH = datetime(1970, 1, 1, tzinfo=timezone.utc) - - -@pytest.fixture -def clockpage(tmp_path): - spec = importlib.util.spec_from_file_location("clockpage_v3", CLOCK / "clockpage.py") - module = importlib.util.module_from_spec(spec) - spec.loader.exec_module(module) - module.PAGE, module.FILE = str(tmp_path / "agentenv-clock"), str(tmp_path / "run" / "clock") - return module - - -def _ns(text: str) -> int: - whole, _, part = text.partition(".") - seconds = (datetime.fromisoformat(whole).replace(tzinfo=timezone.utc) - EPOCH) // timedelta(seconds=1) - return seconds * NS + int((part or "0").ljust(9, "0")) - - -@pytest.mark.parametrize("universe_ns", [ - pytest.param(0, id="1970"), - pytest.param(-1, id="a-nanosecond-before-1970"), - pytest.param(_ns("1949-12-31T23:59:59.75"), id="1949-fractional"), - pytest.param(_ns("1900-01-01T00:00:00"), id="1900"), - pytest.param(INT64_MAX_NS, id="version-2s-last-nanosecond"), - pytest.param(INT64_MAX_NS + 1, id="past-2262"), - pytest.param(_ns("3026-11-23T12:00:00"), id="3026"), - pytest.param(_ns("9999-12-31T23:59:59.999999999"), id="9999-12-31"), -]) -def test_a_page_holds_the_universe_exactly_at_any_date(clockpage, universe_ns): - page = clockpage.encode(4, universe_ns, 1_794_000_000 * NS, 3600.0, 1, 9, 5 * NS, 5 * NS) - - assert len(page) == clockpage.LAYOUT.size == 80 - assert clockpage.read(page) == (4, 1, universe_ns, 1_794_000_000 * NS, 3600.0, 9) - assert 0 <= struct.unpack_from("= now - - -def test_a_page_of_another_version_is_refused_by_the_writer_and_replaced_at_boot(clockpage): - old = clockpage.encode(2, 0, 0, 1.0, 0, 1, 0, 0) - Path(clockpage.PAGE).write_bytes(old[:4] + (2).to_bytes(4, "little") + old[8:]) - with pytest.raises(SystemExit, match="older page"): - clockpage.open_page() - - clockpage.create(getpass.getuser()) - with open(clockpage.PAGE, "rb") as f: - assert clockpage.read(f.read(clockpage.LAYOUT.size)) == (0, 0, 0, 0, 1.0, 0) diff --git a/tst/unit/env/envs/test_computer_clock_panel.py b/tst/unit/env/envs/test_computer_clock_panel.py index bf6e584fc..a89249ff0 100644 --- a/tst/unit/env/envs/test_computer_clock_panel.py +++ b/tst/unit/env/envs/test_computer_clock_panel.py @@ -103,7 +103,7 @@ def set(self, universe: float, rate: float) -> float: def reanchor(self, by: float) -> None: with open(page.PAGE, "rb") as f: - _, armed, universe_ns, anchor_ns, rate, _ = page.read(f.read(page.LAYOUT.size)) + _, _, _, universe_ns, anchor_ns, rate, armed, *_ = page.LAYOUT.unpack(f.read(page.LAYOUT.size)) now = time.time_ns() page.write(armed, (universe_ns + (now - anchor_ns) * rate) / 1e9 + by, rate, now / 1e9) diff --git a/tst/unit/env/envs/test_computer_egress_base.py b/tst/unit/env/envs/test_computer_egress_base.py index ca0aec78d..3d102165d 100644 --- a/tst/unit/env/envs/test_computer_egress_base.py +++ b/tst/unit/env/envs/test_computer_egress_base.py @@ -85,16 +85,11 @@ def test_the_pages_the_proxy_is_tested_on_are_the_ones_the_followers_writer_writ page = importlib.util.module_from_spec(spec) spec.loader.exec_module(page) golden = {name: bytes.fromhex((EGRESS / "testdata" / f"page-{name}.hex").read_text().strip()) - for name in ("armed", "unarmed", "far", "past", "version2")} - anchor, mono = 1794000000_000000000, 5_000_000_000 - - assert {name: golden[name] for name in ("armed", "unarmed", "far", "past")} == { - "armed": page.encode(4, 1577836800_000000000, 1794000000_123456789, 2.0, 1, 7, mono, mono), - "unarmed": page.encode(2, 0, 0, 1.0, 0, 3, 0, 0), - # 9999-12-31T00:00:00.5Z at rate 3600, past 2262; and 1949-12-31T23:59:59.75Z, before 1970. - "far": page.encode(6, 253402214400_500000000, anchor, 3600.0, 1, 9, mono, mono), - "past": page.encode(8, -631152000_250000000, anchor, 1.0, 1, 11, mono, mono)} - assert golden["version2"][4:8] == (2).to_bytes(4, "little") and page.read(golden["version2"]) is None + for name in ("armed", "unarmed")} + + assert golden == { + "armed": page.encode(4, 1577836800_000000000, 1794000000_123456789, 2.0, 1, 7, 5_000_000_000, 5_000_000_000), + "unarmed": page.encode(2, 0, 0, 1.0, 0, 3, 0, 0)} def test_every_chromium_build_goes_out_through_the_proxy_by_a_policy_that_bypasses_what_the_session_does(): diff --git a/tst/unit/env/gateway/clock_range_test.py b/tst/unit/env/gateway/clock_range_test.py index 68d344fee..de0a93b9e 100644 --- a/tst/unit/env/gateway/clock_range_test.py +++ b/tst/unit/env/gateway/clock_range_test.py @@ -1,38 +1,51 @@ -"""The env clock's range: the gateway's clock arms and runs at any date a datetime holds, before 1970 and past 2262 -(where the computers and agents that follow it now follow too), and refuses a date past 9999-12-31, or one it would run -past within a real day, naming that latest time.""" +"""The env clock's range, the times 64 bits of nanoseconds since 1970 hold, as Python and the computers that follow the +clock keep time: the gateway arms and runs anywhere in it, before 1970 too and a day per second at today's dates, and +refuses a time outside it, or one it would run past the end from within a real hour, up front, naming the range.""" from __future__ import annotations import pytest -from agent_env.env.gateway.clock import LATEST, Clock, ClockError +from agent_env.env.gateway.clock import EARLIEST, LATEST, Clock, ClockError from tst.unit.env.gateway.triggers_time_test import FakeNow +RANGE = "the env clock's range, 1677-09-21T00:12:44Z to 2262-04-11T23:47:16Z" +END = "would pass 2262-04-11T23:47:16Z, the end of the env clock's range, within a real hour" -@pytest.mark.parametrize("virtual_time", ["1900-01-01T00:00:00Z", "1949-12-31T23:59:59.750000Z", "2262-04-11T23:47:17Z", - "3026-11-23T12:00:00Z", "9999-06-01T12:00:00Z"]) -def test_the_clock_arms_and_runs_at_any_date_a_datetime_holds(virtual_time): + +def test_the_range_is_the_whole_seconds_64_bits_of_nanoseconds_since_1970_hold(): + first, last = int(EARLIEST.timestamp()), int(LATEST.timestamp()) + assert (first - 1) * 10**9 < -2**63 <= first * 10**9 + assert last * 10**9 <= 2**63 - 1 < (last + 1) * 10**9 + + +@pytest.mark.parametrize("virtual_time, rate", [ + ("1677-09-21T00:12:44Z", 1), ("1900-01-01T00:00:00Z", 60), ("1949-12-31T23:59:59.750000Z", 1), + ("2026-11-23T12:00:00Z", 86400), ("2262-04-11T22:47:16Z", 1), ("2262-04-11T23:47:16Z", 0)]) +def test_the_clock_arms_and_runs_anywhere_in_its_range(virtual_time, rate): now = FakeNow() clock = Clock(now_fn=now) - assert clock.set_time(virtual_time, rate=60)["virtual_time"] == virtual_time + assert clock.set_time(virtual_time, rate=rate)["virtual_time"] == virtual_time now.tick(1) - assert clock.read()["virtual_time"] > virtual_time + assert clock.read()["virtual_time"] >= virtual_time -@pytest.mark.parametrize("virtual_time", ["10000-01-01T00:00:00Z", "123456-01-01T00:00:00Z"]) -def test_a_date_past_9999_is_refused_naming_the_latest_the_clock_reaches(virtual_time): - with pytest.raises(ClockError, match=f"past {LATEST}, the latest the env clock reaches"): - Clock(now_fn=FakeNow()).set_time(virtual_time) +@pytest.mark.parametrize("virtual_time", ["0001-01-01T00:00:00Z", "1600-01-01T00:00:00Z", "1677-09-21T00:12:43Z", + "2262-04-11T23:47:17Z", "3026-11-23T12:00:00Z", "9999-12-31T23:59:59Z", + "10000-01-01T00:00:00Z"]) +def test_a_time_outside_the_range_is_refused_naming_it(virtual_time): + with pytest.raises(ClockError, match=f"virtual_time '{virtual_time}' is outside {RANGE}"): + Clock(now_fn=FakeNow()).set_time(virtual_time, rate=0) -def test_arming_advancing_or_speeding_a_clock_that_would_run_past_9999_within_a_day_names_the_latest(): +def test_arming_advancing_or_speeding_a_clock_that_would_pass_the_end_within_a_real_hour_names_it(): clock = Clock(now_fn=FakeNow()) - with pytest.raises(ClockError, match=f"would pass {LATEST}"): - clock.set_time("9999-12-31T12:00:00Z") - - clock.set_time("9999-06-01T00:00:00Z") - with pytest.raises(ClockError, match=f"would pass {LATEST}"): - clock.advance("9999-12-31T12:00:00Z") - with pytest.raises(ClockError, match=f"past {LATEST}"): - clock.set_rate(86400) + with pytest.raises(ClockError, match=f"virtual_time '2262-04-11T23:00:00Z' at rate 1 {END}"): + clock.set_time("2262-04-11T23:00:00Z") + + clock.set_time("2262-04-01T00:00:00Z") + with pytest.raises(ClockError, match=f"virtual_time '2262-04-11T23:00:00Z' at rate 1 {END}"): + clock.advance("2262-04-11T23:00:00Z") + with pytest.raises(ClockError, match=f"rate 3600 {END}"): + clock.set_rate(3600) + assert clock.read()["virtual_time"] == "2262-04-01T00:00:00Z" diff --git a/tst/unit/env/gateway/get_time_test.py b/tst/unit/env/gateway/get_time_test.py index 65be7d6c4..d586c15a4 100644 --- a/tst/unit/env/gateway/get_time_test.py +++ b/tst/unit/env/gateway/get_time_test.py @@ -20,6 +20,7 @@ from agent_env.env.gateway.constants import DEFAULT_ROLE from agent_env.env.gateway.get_time import GET_TIME_TOOL_DESCRIPTION, GET_TIME_TOOL_NAME from agent_env.env.gateway.gateway import Gateway +from tst.unit.env.gateway.triggers_time_test import FakeNow T = "2019-06-15T12:00:00Z" @@ -274,12 +275,13 @@ def test_local_time_is_the_same_reading_at_second_precision(gw): @pytest.mark.asyncio -@pytest.mark.parametrize("now, zone", [ - ("9999-12-31T20:00:00Z", "Asia/Tokyo"), - ("0001-01-01T02:00:00Z", "America/New_York"), -], ids=["after-the-last-date", "before-the-first-date"]) -async def test_a_time_the_zone_cannot_show_is_a_tool_error_naming_it(gw, now, zone): - gw._clock.set_time(now, 0) +async def test_a_time_the_zone_cannot_show_is_a_tool_error_naming_it(gw): + """A gateway that outlives its clock's range reads the last time a datetime holds, which Tokyo's clock can't show.""" + now, zone = "9999-12-31T23:59:59Z", "Asia/Tokyo" + real = FakeNow() + gw._clock = Clock(now_fn=real) + gw._clock.set_time("2026-01-01T00:00:00Z", 86400) + real.tick(1e9) gw._register_get_time_tool() message = f"the current time {now} can't be shown in time zone {zone!r}: its local date is out of range" From cb969825fc0558013f609359e62aebac3ea70c2a Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 23 Nov 2026 11:07:07 -0800 Subject: [PATCH 04/16] fix(computers): exact deadlines and saturating universe arithmetic at either end of the clock's range ft_ns clamped any deadline past +-9e9 s (1684..2255) to +-4.6e18 ns, so near either end of the range an absolute wait ended at once or never; it's now exact and saturates beyond 64 bits. A deadline and the universe at opposite ends no longer overflow in ft_real_of or the timers, and the universe at a real time (reads and waits share ft_universe_at) stops at the end of 64 bits rather than wrapping when a gateway outlives its range. Co-Authored-By: Claude Opus 5.5 --- .../faketime_clock/agentenv_clock_page.c | 13 +++++++ .../faketime_clock/agentenv_clock_waits.c | 31 ++++++++-------- .../utils/faketime_clock/libfaketime.patch | 36 ++++++++----------- tst/clock/harness.py | 17 ++++++++- tst/clock/range_test.py | 4 +++ 5 files changed, 64 insertions(+), 37 deletions(-) diff --git a/src/agent_env/utils/faketime_clock/agentenv_clock_page.c b/src/agent_env/utils/faketime_clock/agentenv_clock_page.c index e55e011cd..987c430aa 100644 --- a/src/agent_env/utils/faketime_clock/agentenv_clock_page.c +++ b/src/agent_env/utils/faketime_clock/agentenv_clock_page.c @@ -272,6 +272,19 @@ static void ft_page_open(void) ft_page = map; } +/* the universe in ns at real realtime t on armed page s, saturated at the end of 64 bits: the gateway keeps the clock + inside them, and one that outlives its range stops at the end rather than wrapping. Reads and waits share it, so a wait + never ends before a read shows its deadline. */ +static inline int64_t ft_universe_at(const struct ft_clock_page *s, int64_t t) +{ + int64_t fake; + double ran; + if (s->rate == 0 || t <= s->anchor_ns) return s->universe_ns; + if (s->rate == 1.0) return __builtin_add_overflow(s->universe_ns, t - s->anchor_ns, &fake) ? INT64_MAX : fake; + ran = (double) (t - s->anchor_ns) * s->rate; + return ran >= 9.2e18 || __builtin_add_overflow(s->universe_ns, (int64_t) ran, &fake) ? INT64_MAX : fake; +} + /* a time in ns as libfaketime's spec reads it (ft_parse_epoch): its sign once, before the whole value, so a time before 1970 isn't written "-1.-5". */ static void ft_spec_time(char *out, size_t size, int64_t ns) diff --git a/src/agent_env/utils/faketime_clock/agentenv_clock_waits.c b/src/agent_env/utils/faketime_clock/agentenv_clock_waits.c index 04a49e15e..4703e0fa3 100644 --- a/src/agent_env/utils/faketime_clock/agentenv_clock_waits.c +++ b/src/agent_env/utils/faketime_clock/agentenv_clock_waits.c @@ -134,11 +134,13 @@ static bool ft_snap_at(clockid_t clock, struct ft_clock_page *s, struct timespec return true; } +/* a time in ns, exact anywhere in the clock's range, which is what 64 bits hold, and saturated beyond it */ static inline int64_t ft_ns(const struct timespec *t) { - if (t->tv_sec > 9000000000LL) return FT_NEVER / 2; - if (t->tv_sec < -9000000000LL) return -(FT_NEVER / 2); - return (int64_t) t->tv_sec * FT_NS + t->tv_nsec; + int64_t ns; + if (__builtin_mul_overflow((int64_t) t->tv_sec, FT_NS, &ns) || __builtin_add_overflow(ns, (int64_t) t->tv_nsec, &ns)) + return t->tv_sec < 0 ? INT64_MIN : INT64_MAX; + return ns; } static inline struct timespec ft_ts(int64_t ns) { @@ -185,10 +187,7 @@ static inline bool ft_universe_clock(clockid_t c) /* the universe's realtime at real realtime t; before the anchor, the anchor's. */ static int64_t ft_page_rt(const struct ft_clock_page *s, int64_t t) { - if (!s->armed) return t; - if (s->rate == 0 || t <= s->anchor_ns) return s->universe_ns; - if (s->rate == 1.0) return s->universe_ns + (t - s->anchor_ns); - return s->universe_ns + (int64_t) ((double) (t - s->anchor_ns) * s->rate); + return s->armed ? ft_universe_at(s, t) : t; } /* the real realtime at which the universe reaches ``due``; 0 (the past) once it has, FT_NEVER while frozen short of it. */ @@ -198,7 +197,7 @@ static int64_t ft_real_of(const struct ft_clock_page *s, int64_t due) if (!s->armed) return due < 1 ? 1 : due; if (due <= s->universe_ns) return 1; if (s->rate <= 0) return FT_NEVER; - r = (double) (due - s->universe_ns) / s->rate; + r = (double) ((__int128) due - s->universe_ns) / s->rate; if (r > 4e18) return FT_NEVER; return s->anchor_ns + (int64_t) r + 1; } @@ -285,12 +284,13 @@ static int ft_timer_real_get(struct ft_timer *t, struct itimerspec *cur) { return t->kind == 1 ? (*real_timerfd_gettime)(t->fds[0], cur) : (*real_timer_gettime_new)(t->id, cur); } -/* the next expiration at or after ``after``. */ -static int64_t ft_timer_next(const struct ft_timer *t, int64_t after) +/* the next expiration at or after ``after``, in 128 bits, since a deadline and the universe may be at either end of the + range. */ +static int64_t ft_timer_next(const struct ft_timer *t, __int128 after) { - int64_t next = t->due; + __int128 next = t->due; if (t->interval > 0 && next < after) next += ((after - next + t->interval - 1) / t->interval) * t->interval; - return next; + return next > INT64_MAX ? INT64_MAX : (int64_t) next; } /* the kernel timer set from page ``s``. A periodic timer goes on from its first expiration past the universe's time on the page it was armed from, so a jump delivers what it passed at once. Lock held. */ @@ -307,7 +307,7 @@ static int ft_timer_arm(struct ft_timer *t, const struct ft_clock_page *s, bool t->tracked = 0; /* fired: the expiration is the kernel's to hand over */ return 0; } - if (!first && t->interval > 0) next = ft_timer_next(t, ft_page_rt(&t->pg, ft_real_rt()) + 1); + if (!first && t->interval > 0) next = ft_timer_next(t, (__int128) ft_page_rt(&t->pg, ft_real_rt()) + 1); at = ft_real_of(s, next); if (at != FT_NEVER) { @@ -345,8 +345,9 @@ static void ft_timer_value(struct ft_timer *t, struct itimerspec *out) out->it_interval = ft_ts(t->interval); if (ft_snap(&s)) { - int64_t now = ft_page_rt(&s, ft_real_rt()), next = ft_timer_next(t, now); - out->it_value = ft_ts(next - now < 1 ? 1 : next - now); + int64_t now = ft_page_rt(&s, ft_real_rt()); + __int128 left = (__int128) ft_timer_next(t, now) - now; + out->it_value = ft_ts(left < 1 ? 1 : left > INT64_MAX ? INT64_MAX : (int64_t) left); } } diff --git a/src/agent_env/utils/faketime_clock/libfaketime.patch b/src/agent_env/utils/faketime_clock/libfaketime.patch index df8bafb54..ae588a173 100644 --- a/src/agent_env/utils/faketime_clock/libfaketime.patch +++ b/src/agent_env/utils/faketime_clock/libfaketime.patch @@ -992,7 +992,7 @@ diff -ruN a/src/libfaketime.c b/src/libfaketime.c if ((faketimerc = open(custom_filename, O_RDONLY)) != -1 || (faketimerc = open(filename, O_RDONLY)) != -1 || (faketimerc = open("/etc/faketimerc", O_RDONLY)) != -1) -@@ -3248,6 +3277,48 @@ +@@ -3248,6 +3277,42 @@ tp_save.tv_nsec = tp->tv_nsec; if (dont_fake) return 0; @@ -1020,13 +1020,7 @@ diff -ruN a/src/libfaketime.c b/src/libfaketime.c + ft_tl_scale = (s.armed && s.rate > 0) ? 1.0 / s.rate : 1.0; + if (s.armed) + { -+ int64_t now = (int64_t) tp->tv_sec * 1000000000LL + tp->tv_nsec, fake; -+ if (s.rate == 0 || now <= s.anchor_ns) -+ fake = s.universe_ns; -+ else if (s.rate == 1.0) -+ fake = s.universe_ns + (now - s.anchor_ns); -+ else -+ fake = s.universe_ns + (int64_t) ((double) (now - s.anchor_ns) * s.rate); ++ int64_t fake = ft_universe_at(&s, (int64_t) tp->tv_sec * 1000000000LL + tp->tv_nsec); + tp->tv_sec = fake / 1000000000LL; + tp->tv_nsec = fake % 1000000000LL; + if (tp->tv_nsec < 0) @@ -1041,7 +1035,7 @@ diff -ruN a/src/libfaketime.c b/src/libfaketime.c /* Per process timers are only sped up or slowed down */ if ((clk_id == CLOCK_PROCESS_CPUTIME_ID ) || (clk_id == CLOCK_THREAD_CPUTIME_ID)) { -@@ -3262,7 +3333,6 @@ +@@ -3262,7 +3327,6 @@ volatile int ret = INT_MAX; #ifdef PTHREAD_SINGLETHREADED_TIME @@ -1049,7 +1043,7 @@ diff -ruN a/src/libfaketime.c b/src/libfaketime.c // block all signals while locked. prevents deadlocks if signal interrupts in in mid-operation. sigset_t all_signals, original_mask; -@@ -3367,6 +3437,19 @@ +@@ -3367,6 +3431,19 @@ force_cache_expiration = 0; } @@ -1069,7 +1063,7 @@ diff -ruN a/src/libfaketime.c b/src/libfaketime.c if (cache_expired == 1) { static char user_faked_time[BUFFERLEN]; /* changed to static for caching in v0.6 */ -@@ -3377,7 +3460,7 @@ +@@ -3377,7 +3454,7 @@ fprintf(stderr, "***************++ Cache expired ++**************\n"); */ @@ -1078,7 +1072,7 @@ diff -ruN a/src/libfaketime.c b/src/libfaketime.c { strncpy(user_faked_time, tmp_env, BUFFERLEN - 1); user_faked_time[BUFFERLEN - 1] = 0; -@@ -3401,6 +3484,9 @@ +@@ -3401,6 +3478,9 @@ get_fake_monotonic_setting(&fake_monotonic_clock); } /* cache had expired */ @@ -1088,7 +1082,7 @@ diff -ruN a/src/libfaketime.c b/src/libfaketime.c if (infile_set) { if (load_time(tp)) -@@ -3520,6 +3606,7 @@ +@@ -3520,6 +3600,7 @@ { struct timespec ts; int ret; @@ -1096,7 +1090,7 @@ diff -ruN a/src/libfaketime.c b/src/libfaketime.c ts.tv_sec = tv->tv_sec; ts.tv_nsec = tv->tv_usec * 1000 + ftpl_starttime.real.tv_nsec % 1000; -@@ -3627,6 +3714,8 @@ +@@ -3627,6 +3708,8 @@ DONT_FAKE_TIME(result = (*real___clock_gettime)(clk_id, tp)); if (result == -1) return result; /* original function failed */ @@ -1105,7 +1099,7 @@ diff -ruN a/src/libfaketime.c b/src/libfaketime.c /* pass the real current time to our faking version, overwriting it */ if (fake_monotonic_clock || (clk_id != CLOCK_MONOTONIC && clk_id != CLOCK_MONOTONIC_RAW #ifdef CLOCK_MONOTONIC_COARSE -@@ -3723,238 +3812,124 @@ +@@ -3723,238 +3806,124 @@ #ifdef FAKE_PTHREAD @@ -1433,7 +1427,7 @@ diff -ruN a/src/libfaketime.c b/src/libfaketime.c #endif /* -@@ -4005,15 +3980,15 @@ +@@ -4005,15 +3974,15 @@ /* If FAKETIME_TIMESTAMP_FILE was given in environment, * and if FAKETIME_UPDATE_TIMESTAMP_FILE=1, then update it. * This allows other process instances to share the same time. */ @@ -1454,7 +1448,7 @@ diff -ruN a/src/libfaketime.c b/src/libfaketime.c if ((envfile = fopen(custom_filename, "wt")) != NULL) { -@@ -4034,7 +4009,7 @@ +@@ -4034,7 +4003,7 @@ { fprintf(stderr, "libfaketime: In clock_settime(), failed to " "%s while updating FAKETIME_TIMESTAMP_FILE (`%s'): %s\n", @@ -1463,7 +1457,7 @@ diff -ruN a/src/libfaketime.c b/src/libfaketime.c } } -@@ -4125,7 +4100,7 @@ +@@ -4125,7 +4094,7 @@ /* return 0 if no FAKERANDOM_SEED was seen */ static int bypass_randomness(void* buf, size_t buflen) { @@ -1472,7 +1466,7 @@ diff -ruN a/src/libfaketime.c b/src/libfaketime.c char *b = buf; if (seedstring != NULL) { -@@ -4169,7 +4144,7 @@ +@@ -4169,7 +4138,7 @@ #else pid_t getpid() { #endif @@ -1481,7 +1475,7 @@ diff -ruN a/src/libfaketime.c b/src/libfaketime.c if (pidstring != NULL) { long int pid = strtol(pidstring, NULL, 0); return (pid_t)(pid); -@@ -4270,7 +4245,7 @@ +@@ -4270,7 +4239,7 @@ va_list ap; va_start(ap, number); #ifdef FAKE_RANDOM @@ -1490,7 +1484,7 @@ diff -ruN a/src/libfaketime.c b/src/libfaketime.c void *buf; size_t buflen; unsigned int flags; -@@ -4282,7 +4257,7 @@ +@@ -4282,7 +4251,7 @@ } #endif // static int (*real_clock_gettime) (clockid_t clk_id, struct timespec *tp); diff --git a/tst/clock/harness.py b/tst/clock/harness.py index f3dbd2aea..9805d4551 100644 --- a/tst/clock/harness.py +++ b/tst/clock/harness.py @@ -461,6 +461,21 @@ def deadwriter(): "read": _classify(after, before, 21 * DAY)} +def end(): + """The clock a second short of the end of 64 bits of nanoseconds at rate 1, as a gateway that outlives its range + leaves it: two seconds on, reads in C, Python and Node show the end rather than wrap to 1677.""" + preload() + fresh_page() + set_clock(9223372035.0, 1) + time.sleep(2.5) + reads = {name: subprocess.run(user_cmd(argv), capture_output=True, text=True).stdout.strip() for name, argv in ( + ("date", ["date", "-u", "+%s.%N"]), + ("python", ["python3", "-c", "import time; print(time.time_ns())"]), + ("node", ["node", "-e", "console.log(Date.now())"]))} + preload(None) + return reads + + def _classify(value: float, before: float, universe_offset: float) -> object: if abs(value - before) < 30: return "real" @@ -684,7 +699,7 @@ def probe(): GATES = {f.__name__: f for f in (waits, ratechange, jumps, cancel, timerfds, condstress, semstress, stall, torn, - deadwriter, marker, identity, envrace, forklock, chromium, tls, probe)} + deadwriter, end, marker, identity, envrace, forklock, chromium, tls, probe)} if __name__ == "__main__": gate = GATES[sys.argv[1]] diff --git a/tst/clock/range_test.py b/tst/clock/range_test.py index f78ac10d0..a71901ea7 100644 --- a/tst/clock/range_test.py +++ b/tst/clock/range_test.py @@ -104,3 +104,7 @@ def test_a_read_near_either_end_is_never_torn_between_two_pages(at): def test_chrome_runs_every_launch_near_either_end(gate, when): r = gate("chromium", "agentenv", 16, 8, 20.0, docker_args=_base(when)) assert (r["launches"], r["failed"]) == (16, 0), r + + +def test_a_clock_that_outlives_its_range_stops_at_the_end_rather_than_wrapping(gate): + assert gate("end") == {"date": "9223372036.854775807", "python": "9223372036854775807", "node": "9223372036854"} From cad73171ff296c9bb5b8b863c11ca890b27334d2 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 23 Nov 2026 13:47:46 -0800 Subject: [PATCH 05/16] fix(clock): a clock that outlives its range stands at its end, and every refusal names the range where it's read The gateway's clock stopped refusing times outside 1677-09-21..2262-04-11, but a clock armed within its last real hour still ran past the end: the gateway's reads went on toward 9999, a computer's follower then wrote a universe the page can't hold and crash-looped with the page left mid-write, and the session's clock stopped at the end of 64 bits, where any deadline computed from now was already reached, so waits in a loop spun. - The gateway's clock stands at LATEST: its reads, state and watch stop there, and its state says rate 0 there, so followers stop with it. It can still be frozen or advanced to the time it shows, and set back. - A write is refused for passing the end within a real hour only when it brings the end closer: an advance to the time the clock shows (as always_on's settle makes) or a rate no faster goes through in the last hour. The check compares seconds, so a rate too slow for a microsecond an hour is refused too. - Every out-of-range spelling names the range: a UTC instant past datetime's ends (0001 at +01:00, 9999 at -01:00) and year 0000; a string that isn't RFC3339 at all is refused as one, five digits or not. - sync_env_clock reports a time or rate the gateway would refuse as a config problem, before anything deploys, naming the time as the task wrote it, its zone included; a zoned wall time no date holds names the range too. - The clock/v1 card states the range. - The protocol client takes a bare-string error as the message, so a refused clock write read through invoke (the hooks, always_on) says why instead of "400 error: Bad Request". - clockpage.py writes a universe outside the range at its end, so a write never fails halfway. - agent-env's libfaketime: the universe stops at FT_END, the range's last second, as the gateway's does, and a deadline past it is never reached; a page before 1970 runs on exactly however far it runs (128-bit sum); a periodic realtime timer armed on a frozen clock gets no kernel interval, where x86_64 got 1 ns from interval / 0; timerfd_gettime gives the whole time left to a deadline at the other end of the range. - get_time drops its zone-overflow error, which a clock inside the range can't reach. Tests: unit tests for each gateway case, the card, sync_env_clock's config problems, the client's string error and the page writer's bounds; tst/env's stale 9999 tests moved to the range; clock gates for waits at the end (running into it and frozen there), a page before 1970 left to run 29.7 h, timers on a frozen clock, and a page written past the end. Co-Authored-By: Claude Opus 5.5 --- .../src/agentenv_protocol/client.py | 4 +- .../agentenv-protocol/tests/test_client.py | 3 + src/agent_env/env/gateway/clock.py | 82 ++++++++++------ src/agent_env/env/gateway/constants.py | 2 +- src/agent_env/env/gateway/get_time.py | 6 +- .../task_step/task_steps/sync_env_clock.py | 32 +++++-- .../faketime_clock/agentenv_clock_page.c | 20 ++-- .../faketime_clock/agentenv_clock_waits.c | 18 ++-- .../utils/faketime_clock/clockpage.py | 15 ++- tst/clock/harness.py | 74 +++++++++++++-- tst/clock/programs/endwaits.py | 30 ++++++ tst/clock/programs/tfdfrozen.py | 38 ++++++++ tst/clock/range_test.py | 19 +++- tst/env/gateway/clock_test.py | 26 ++--- .../env/envs/test_computer_clock_follower.py | 31 ++++++ tst/unit/env/gateway/clock_range_test.py | 94 +++++++++++++++++-- tst/unit/env/gateway/get_time_test.py | 23 ++--- tst/unit/task_step/sync_env_clock_test.py | 31 ++++++ 18 files changed, 438 insertions(+), 110 deletions(-) create mode 100644 tst/clock/programs/endwaits.py create mode 100644 tst/clock/programs/tfdfrozen.py diff --git a/packages/agentenv-protocol/src/agentenv_protocol/client.py b/packages/agentenv-protocol/src/agentenv_protocol/client.py index 0d76ad4aa..75f52a483 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/client.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/client.py @@ -36,12 +36,14 @@ def __init__(self, response: httpx.Response) -> None: def _error_fields(response: httpx.Response) -> dict: + """The error object the body carries; an error that is a bare string, as an env gateway's own routes send, is its + message.""" try: body = response.json() except ValueError: return {} error = body.get("error") if isinstance(body, dict) else None - return error if isinstance(error, dict) else {} + return error if isinstance(error, dict) else {"message": error} if isinstance(error, str) else {} def control_headers(token: str | None) -> dict[str, str]: diff --git a/packages/agentenv-protocol/tests/test_client.py b/packages/agentenv-protocol/tests/test_client.py index 3c6d3c570..1b63c62ec 100644 --- a/packages/agentenv-protocol/tests/test_client.py +++ b/packages/agentenv-protocol/tests/test_client.py @@ -338,6 +338,9 @@ def _error_response(status: int, **kwargs) -> httpx.Response: # A server from before the structured fields: its code, and nothing claimed about the effect. (_error_response(500, json={"ok": False, "error": {"code": "extension_failed", "message": "kaboom"}}), ("extension_failed", "kaboom", False, "unknown", None)), + # A route whose error is a bare string, as an env gateway's clock refusals are: it is the message. + (_error_response(400, json={"ok": False, "error": "virtual_time '3026-01-01T00:00:00Z' is outside the range"}), + (None, "virtual_time '3026-01-01T00:00:00Z' is outside the range", False, "unknown", None)), # A proxy's own error page. (_error_response(502, text="Bad Gateway"), (None, "Bad Gateway", False, "unknown", None)), (_error_response(404, json=["not", "an", "object"]), (None, "Not Found", False, "unknown", None)), diff --git a/src/agent_env/env/gateway/clock.py b/src/agent_env/env/gateway/clock.py index 8f99bd2d4..9c000222a 100644 --- a/src/agent_env/env/gateway/clock.py +++ b/src/agent_env/env/gateway/clock.py @@ -20,8 +20,8 @@ class ClockError(ValueError): MAX_RATE = 86400.0 # 1 real second = 1 virtual day (the max virtual-time speed) -# Fast-fail a t0 that would pass LATEST within a real hour of advancement at `rate` (frozen clocks exempt): an hour, so -# a day per second still arms at today's dates. Not the overflow guarantee — reads still saturate (_advance) past it. +# Fast-fail a write that would bring the clock to LATEST within a real hour at `rate` (frozen clocks exempt): an hour, +# so a day per second still arms at today's dates. Not the guarantee: a clock that runs to LATEST stands there. _OVERFLOW_HORIZON_S = 3600.0 _MAX_T0 = datetime.max.replace(tzinfo=timezone.utc) # The times the clock holds: those 64 bits of nanoseconds since 1970 hold, as Python and the computers' clock page keep @@ -47,7 +47,7 @@ def _parse_rate(rate) -> float: # fromisoformat is looser than RFC3339 (accepts basic format, week/ordinal dates, sub-minute # offsets), so gate on the grammar first and let it do only the arithmetic. A space separator is ok. _RFC3339_RE = re.compile( - r"""^\d{4}-\d{2}-\d{2} + r"""^(\d{4,})-\d{2}-\d{2} # a year past four digits is read, to be refused as outside the range [Tt ] \d{2}:\d{2}:\d{2} # seconds are mandatory (?:\.\d+)? @@ -63,10 +63,11 @@ def _parse_rfc3339(text: str) -> datetime: raise ClockError(f"virtual_time must be an RFC3339 string, got {type(text).__name__}") # Don't strip: a whitespace-wrapped value would slip through the anchored grammar (a 200 the contract calls a 400). raw = text - if re.match(r"^\d{5,}-", raw): - raise ClockError(_outside(text)) - if not _RFC3339_RE.match(raw): + grammar = _RFC3339_RE.match(raw) + if not grammar: raise ClockError(f"invalid RFC3339 virtual_time {text!r}: expected {_RFC3339_SHAPE}") + if len(grammar.group(1)) > 4 or grammar.group(1) == "0000": + raise ClockError(outside_range(f"virtual_time {text!r}")) if raw.endswith(("Z", "z")): raw = raw[:-1] + "+00:00" try: @@ -76,20 +77,39 @@ def _parse_rfc3339(text: str) -> datetime: try: return dt.astimezone(timezone.utc) except OverflowError: - raise ClockError(f"invalid RFC3339 virtual_time {text!r}: out of representable range") + raise ClockError(outside_range(f"virtual_time {text!r}")) _WHY = "the times a 64-bit count of nanoseconds since 1970 holds, as Python and the computers that follow the clock keep time" -def _outside(virtual_time: str) -> str: - return f"virtual_time {virtual_time!r} is outside the env clock's range, {_iso(EARLIEST)} to {_iso(LATEST)} ({_WHY})" +def outside_range(what: str) -> str: + """The refusal of ``what``, a time the clock can't hold, naming its range and why.""" + return f"{what} is outside the env clock's range, {_iso(EARLIEST)} to {_iso(LATEST)} ({_WHY})" def _past_end(what: str) -> str: return f"{what} would pass {_iso(LATEST)}, the end of the env clock's range, within a real hour ({_WHY})" +def _ends_within_an_hour(at: datetime, rate: float) -> bool: + """Whether a clock at ``at``, running at ``rate``, reaches LATEST within _OVERFLOW_HORIZON_S real seconds.""" + return (LATEST - at).total_seconds() < _OVERFLOW_HORIZON_S * rate + + +def check_arm(virtual_time: str, rate=1.0, what: str | None = None) -> tuple[datetime, float]: + """``virtual_time`` and ``rate`` as set_time arms the clock at them, or the ClockError it refuses them with, which + names the time as ``what`` (``virtual_time ''`` by default).""" + t0 = _parse_rfc3339(virtual_time) + r = _parse_rate(1.0 if rate is None else rate) + what = what or f"virtual_time {virtual_time!r}" + if not EARLIEST <= t0 <= LATEST: + raise ClockError(outside_range(what)) + if _ends_within_an_hour(t0, r): + raise ClockError(_past_end(f"{what} at rate {r:g}")) + return t0, r + + def _iso(dt: datetime) -> str: return dt.astimezone(timezone.utc).isoformat().replace("+00:00", "Z") @@ -130,11 +150,8 @@ def _parse_duration(text) -> timedelta: def _advance(t0: datetime, seconds: float) -> datetime: - """t0 + seconds, saturating at datetime.min/max instead of raising. - - set_time's horizon check can't bound a gateway that outlives _OVERFLOW_HORIZON_S, so reads - saturate rather than 500 — an armed clock always returns a (monotonic) time. - """ + """t0 + seconds, saturating at datetime.min/max instead of raising, as a trigger's mark far past the clock's range + may need; the clock's own time stops at LATEST (Clock._upto_end).""" try: return t0 + timedelta(seconds=seconds) except (OverflowError, ValueError, OSError): @@ -202,14 +219,9 @@ def t0(self) -> datetime | None: def set_time(self, virtual_time: str, rate=1.0, time_zone: str | None = None) -> dict: """Arm/re-arm: anchor t0=virtual_time to now, advancing at `rate` virtual s per real s, in the universe's `time_zone` (its users' IANA zone), or none.""" - t0 = _parse_rfc3339(virtual_time) - r = _parse_rate(1.0 if rate is None else rate) + t0, r = check_arm(virtual_time, rate) if time_zone is not None and _zone(time_zone) is None: raise ClockError(f"unknown time zone {time_zone!r}: pass an IANA time zone name such as 'America/New_York'") - if not EARLIEST <= t0 <= LATEST: - raise ClockError(_outside(virtual_time)) - if t0 > LATEST - timedelta(seconds=_OVERFLOW_HORIZON_S * r): - raise ClockError(_past_end(f"virtual_time {virtual_time!r} at rate {r:g}")) with self._lock: self._bank(t0) self._t0 = t0 @@ -224,14 +236,14 @@ def set_time(self, virtual_time: str, rate=1.0, time_zone: str | None = None) -> def set_rate(self, rate) -> dict: """Change an armed clock's rate from its time at the call, keeping t0 and generation as an advance does, so time triggers keep their marks and a rate change can't step the clock back by a time read a moment earlier; 0 freezes - the clock.""" + the clock. A faster rate that would bring it to the end of its range within a real hour is refused.""" r = _parse_rate(rate) with self._lock: if not self._armed or self._t0 is None: raise ClockError("clock is not armed") now = self._now() ran = (now - self._anchor) * self._rate - if _advance(self._t0, ran + self._ahead) > LATEST - timedelta(seconds=_OVERFLOW_HORIZON_S * r): + if r > self._rate and _ends_within_an_hour(self._upto_end(ran + self._ahead), r): raise ClockError(_past_end(f"rate {r:g}")) self._lived += ran self._ahead += ran @@ -241,19 +253,20 @@ def set_rate(self, rate) -> dict: return self.state() def advance(self, virtual_time: str) -> dict: - """Jump forward to virtual_time on the current arm, keeping t0, rate and generation, so marks stay put.""" + """Jump forward to virtual_time on the current arm, keeping t0, rate and generation, so marks stay put; one that + would bring the clock to the end of its range within a real hour is refused, but not one to the time it shows.""" target = _parse_rfc3339(virtual_time) with self._lock: if not self._armed or self._t0 is None: raise ClockError("clock is not armed") if target > LATEST: - raise ClockError(_outside(virtual_time)) - if target > LATEST - timedelta(seconds=_OVERFLOW_HORIZON_S * self._rate): - raise ClockError(_past_end(f"virtual_time {virtual_time!r} at rate {self._rate:g}")) - current = _advance(self._t0, (self._now() - self._anchor) * self._rate + self._ahead) + raise ClockError(outside_range(f"virtual_time {virtual_time!r}")) + current = self._upto_end((self._now() - self._anchor) * self._rate + self._ahead) jump = (target - current).total_seconds() if jump < 0: raise ClockError(f"advance only moves forward: {virtual_time!r} is before the current {_iso(current)}") + if jump > 0 and _ends_within_an_hour(target, self._rate): + raise ClockError(_past_end(f"virtual_time {virtual_time!r} at rate {self._rate:g}")) self._ahead += jump self._lived += jump self._count += 1 @@ -282,7 +295,7 @@ def now(self) -> datetime | None: if not self._armed or self._t0 is None: return None elapsed = self._now() - self._anchor - return _advance(self._t0, elapsed * self._rate + self._ahead) + return self._upto_end(elapsed * self._rate + self._ahead) @property def time_zone(self) -> str | None: @@ -305,14 +318,21 @@ def read(self) -> dict: return {"virtual_time": _iso(current)} def state(self) -> dict: + """The clock as its followers take it up; one at the end of its range stands there, at rate 0.""" with self._lock: if not self._armed or self._t0 is None: return {"armed": False, "version": self.version} - elapsed = self._now() - self._anchor - return {"armed": True, "t0": _iso(self._t0), "virtual_seconds_per_real_second": self._rate, - "virtual_time": _iso(_advance(self._t0, elapsed * self._rate + self._ahead)), + current = self._upto_end((self._now() - self._anchor) * self._rate + self._ahead) + return {"armed": True, "t0": _iso(self._t0), + "virtual_seconds_per_real_second": 0.0 if current == LATEST else self._rate, + "virtual_time": _iso(current), **({"time_zone": self._time_zone} if self._time_zone else {}), "version": self.version} + def _upto_end(self, seconds: float) -> datetime: + """The current arm's time ``seconds`` after t0, standing at LATEST: no check at a write can bound a gateway that + outlives it, so the clock stops at the end of its range rather than leave it. Lock held.""" + return min(_advance(self._t0, seconds), LATEST) + def _bank(self, t0: datetime | None = None) -> None: """Fold the stretch since the last arm/clear into `_lived` at its rate, and start the next one now.""" now = self._now() diff --git a/src/agent_env/env/gateway/constants.py b/src/agent_env/env/gateway/constants.py index 35e4d6957..115e40db6 100644 --- a/src/agent_env/env/gateway/constants.py +++ b/src/agent_env/env/gateway/constants.py @@ -268,7 +268,7 @@ def random_mcp_server_name() -> str: }, { "uri": EXT_CLOCK_URI, - "description": "Virtual clock (urn:agentenv:clock/v1): read the gateway's virtual time (wall-clock-derived, rate-scaled) via get_time; set_time/set_rate/advance/clear are the harness control path, each changing the clock's opaque version and, given wait_followers_s, answering 504 naming the followers that don't show it in time (set_rate keeps t0, as advance does, so time triggers keep their marks; rate 0 freezes the clock); declare_follower adds a follower after the gateway started (an agent the run deploys), with the read token its watches carry, and retire_follower removes one so writes stop waiting for it (an agent the run tears down); a follower follows it through watch, a long poll naming the version it shows and held up to hold_s; state's followers block is diagnostic, not part of the contract.", + "description": "Virtual clock (urn:agentenv:clock/v1): read the gateway's virtual time (wall-clock-derived, rate-scaled) via get_time; set_time/set_rate/advance/clear are the harness control path, each changing the clock's opaque version and, given wait_followers_s, answering 504 naming the followers that don't show it in time (set_rate keeps t0, as advance does, so time triggers keep their marks; rate 0 freezes the clock); the clock holds 1677-09-21T00:12:44Z to 2262-04-11T23:47:16Z, the times 64 bits of nanoseconds since 1970 hold: set_time and advance refuse a time outside it, a write that would bring the clock to its end within a real hour is refused, and a clock that runs to its end stands there, at rate 0; declare_follower adds a follower after the gateway started (an agent the run deploys), with the read token its watches carry, and retire_follower removes one so writes stop waiting for it (an agent the run tears down); a follower follows it through watch, a long poll naming the version it shows and held up to hold_s; state's followers block is diagnostic, not part of the contract.", "params": {"endpoint": "/clock/time", "methods": { "get_time": {"method": "GET", "endpoint": "/clock/time"}, "set_time": {"method": "PUT", "endpoint": "/clock/set-time", "request": {"type": "object", "properties": {"virtual_time": {"type": "string"}, "virtual_seconds_per_real_second": {"type": "number"}, "time_zone": {"type": "string"}, **_WAIT_FOLLOWERS}, "required": ["virtual_time"]}}, diff --git a/src/agent_env/env/gateway/get_time.py b/src/agent_env/env/gateway/get_time.py index fa66a1a5a..34919905e 100644 --- a/src/agent_env/env/gateway/get_time.py +++ b/src/agent_env/env/gateway/get_time.py @@ -74,11 +74,7 @@ async def get_time(time_zone: str | None = None) -> dict[str, str] | CallToolRes return _tool_error(f"unknown time zone {time_zone!r}: pass an IANA time zone name such as " "'America/New_York'") reading = read_time(clock) - try: - local = datetime.fromisoformat(reading["current_time"]).astimezone(zone) - except OverflowError: - return _tool_error(f"the current time {reading['current_time']} can't be shown in time zone " - f"{time_zone!r}: its local date is out of range") + local = datetime.fromisoformat(reading["current_time"]).astimezone(zone) return {**reading, "time_zone": time_zone, "local_time": local.isoformat()} return FastMCPTool( diff --git a/src/agent_env/task_step/task_steps/sync_env_clock.py b/src/agent_env/task_step/task_steps/sync_env_clock.py index f14876926..90782215e 100644 --- a/src/agent_env/task_step/task_steps/sync_env_clock.py +++ b/src/agent_env/task_step/task_steps/sync_env_clock.py @@ -28,6 +28,7 @@ from agent_env.a2a_agent.clock import follow_agents, on_deployment, torn_down from agent_env.env.env import Env, EnvCapabilityUnsupported, gateway_url_of +from agent_env.env.gateway.clock import ClockError, check_arm, outside_range from agent_env.env.gateway.constants import EXT_CLOCK_URI from agent_env.task_step.context import StepContextError, TaskStepContext from agent_env.entity.refs import EntityRef @@ -55,15 +56,19 @@ def resolve_virtual_time(virtual_time: str, timezone: Optional[str]) -> str: parsed = datetime.fromisoformat(virtual_time) except ValueError as e: raise ValueError(f"virtual_time {virtual_time!r} is not an ISO 8601 / RFC3339 timestamp") from e - if parsed.tzinfo is None: - local = parsed.replace(tzinfo=zone) - if local.astimezone(_utc_tz.utc).astimezone(zone).replace(tzinfo=None) != parsed: - raise ValueError(f"virtual_time {virtual_time!r} does not exist in {zone.key} (clock skips it)") - return local.astimezone(_utc_tz.utc).isoformat().replace("+00:00", "Z") - if parsed.astimezone(zone).utcoffset() != parsed.utcoffset(): - raise ValueError(f"virtual_time {virtual_time!r} carries offset {parsed.utcoffset()} but {zone.key} is at " - f"{parsed.astimezone(zone).utcoffset()} at that instant; drop the offset or fix the timezone") - return parsed.astimezone(_utc_tz.utc).isoformat().replace("+00:00", "Z") + try: + if parsed.tzinfo is None: + local = parsed.replace(tzinfo=zone) + if local.astimezone(_utc_tz.utc).astimezone(zone).replace(tzinfo=None) != parsed: + raise ValueError(f"virtual_time {virtual_time!r} does not exist in {zone.key} (clock skips it)") + return local.astimezone(_utc_tz.utc).isoformat().replace("+00:00", "Z") + if parsed.astimezone(zone).utcoffset() != parsed.utcoffset(): + raise ValueError(f"virtual_time {virtual_time!r} carries offset {parsed.utcoffset()} but {zone.key} is at " + f"{parsed.astimezone(zone).utcoffset()} at that instant; drop the offset or fix the " + "timezone") + return parsed.astimezone(_utc_tz.utc).isoformat().replace("+00:00", "Z") + except OverflowError as e: + raise ValueError(outside_range(f"virtual_time {virtual_time!r} in {zone.key}")) from e class SyncEnvClockTaskStep(TaskStep): @@ -113,6 +118,15 @@ def __init__( self.timezone = timezone.strip() if isinstance(timezone, str) else timezone self.armed_virtual_time = resolve_virtual_time(virtual_time, self.timezone) + def config_problems(self) -> list[str]: + """A time or rate the gateway's clock would refuse to arm at, said before anything deploys.""" + shown = f"virtual_time {self.virtual_time!r}" + (f" in {self.timezone}" if self.timezone else "") + try: + check_arm(self.armed_virtual_time, self.virtual_seconds_per_real_second, what=shown) + except ClockError as e: + return [f"step {self.id!r}: {e}"] + return [] + def to_dict(self) -> dict: base = super().to_dict() base["env_id"] = self.env_id diff --git a/src/agent_env/utils/faketime_clock/agentenv_clock_page.c b/src/agent_env/utils/faketime_clock/agentenv_clock_page.c index 987c430aa..a998b4ff6 100644 --- a/src/agent_env/utils/faketime_clock/agentenv_clock_page.c +++ b/src/agent_env/utils/faketime_clock/agentenv_clock_page.c @@ -272,17 +272,21 @@ static void ft_page_open(void) ft_page = map; } -/* the universe in ns at real realtime t on armed page s, saturated at the end of 64 bits: the gateway keeps the clock - inside them, and one that outlives its range stops at the end rather than wrapping. Reads and waits share it, so a wait - never ends before a read shows its deadline. */ +/* the end of the env clock's range, 2262-04-11T23:47:16Z, the last whole second 64 bits of ns hold (the gateway's + LATEST, and clockpage.py's) */ +#define FT_END 9223372036000000000LL + +/* the universe in ns at real realtime t on armed page s, standing at FT_END: the gateway keeps the clock inside its + range, and one that outlives it stops at the end rather than wrapping, as the gateway's own clock does. Summed in 128 + bits, so a page before 1970 runs on exactly however far it runs (the gateway's rates, at most a day per second, keep + the run inside them). Reads and waits share it, so a wait never ends before a read shows its deadline. */ static inline int64_t ft_universe_at(const struct ft_clock_page *s, int64_t t) { - int64_t fake; - double ran; + __int128 fake; if (s->rate == 0 || t <= s->anchor_ns) return s->universe_ns; - if (s->rate == 1.0) return __builtin_add_overflow(s->universe_ns, t - s->anchor_ns, &fake) ? INT64_MAX : fake; - ran = (double) (t - s->anchor_ns) * s->rate; - return ran >= 9.2e18 || __builtin_add_overflow(s->universe_ns, (int64_t) ran, &fake) ? INT64_MAX : fake; + fake = (__int128) s->universe_ns + + (s->rate == 1.0 ? (__int128) (t - s->anchor_ns) : (__int128) ((double) (t - s->anchor_ns) * s->rate)); + return fake > FT_END ? FT_END : (int64_t) fake; } /* a time in ns as libfaketime's spec reads it (ft_parse_epoch): its sign once, before the whole value, so a time before diff --git a/src/agent_env/utils/faketime_clock/agentenv_clock_waits.c b/src/agent_env/utils/faketime_clock/agentenv_clock_waits.c index 4703e0fa3..b9120df4c 100644 --- a/src/agent_env/utils/faketime_clock/agentenv_clock_waits.c +++ b/src/agent_env/utils/faketime_clock/agentenv_clock_waits.c @@ -168,8 +168,8 @@ static inline bool ft_valid_ts(const struct timespec *t) { return t != NULL && t->tv_nsec >= 0 && t->tv_nsec < FT_NS && t->tv_sec >= 0; } -/* an absolute deadline on the universe's realtime, which is before 1970 only while the universe is set: on a real clock - the kernel refuses a negative time, so an unarmed page leaves such a deadline to it. */ +/* an absolute deadline on the universe's realtime, which is before 1970 only while the universe is set: a real clock has + no time before 1970, so an unarmed page leaves such a deadline to the real call. */ static inline bool ft_valid_due(const struct timespec *t, const struct ft_clock_page *s) { return t != NULL && t->tv_nsec >= 0 && t->tv_nsec < FT_NS && (t->tv_sec >= 0 || s->armed); @@ -190,13 +190,13 @@ static int64_t ft_page_rt(const struct ft_clock_page *s, int64_t t) return s->armed ? ft_universe_at(s, t) : t; } /* the real realtime at which the universe reaches ``due``; 0 (the past) once it has, FT_NEVER while frozen - short of it. */ + short of it or for a time past the end of the range, where the universe stops. */ static int64_t ft_real_of(const struct ft_clock_page *s, int64_t due) { double r; if (!s->armed) return due < 1 ? 1 : due; if (due <= s->universe_ns) return 1; - if (s->rate <= 0) return FT_NEVER; + if (s->rate <= 0 || due > FT_END) return FT_NEVER; r = (double) ((__int128) due - s->universe_ns) / s->rate; if (r > 4e18) return FT_NEVER; return s->anchor_ns + (int64_t) r + 1; @@ -228,8 +228,8 @@ static void ft_tab_unlock(const sigset_t *old) /* * ---- timers for a realtime clock time: timerfds and POSIX timers armed at TIMER_ABSTIME on a realtime clock. The * kernel timer is armed at the real realtime the universe reaches the deadline at (in the past once it has, so it fires - * now), its interval at interval / rate, and disarmed while frozen short of it; the helper arms it again on each change. - * A one-shot timer that has fired is left alone. ---- + * now), its interval at interval / rate (none while frozen, which brings no later expiration), and disarmed while frozen + * short of it; the helper arms it again on each change. A one-shot timer that has fired is left alone. ---- */ #define FT_TIMER_FDS 8 struct ft_timer @@ -313,7 +313,7 @@ static int ft_timer_arm(struct ft_timer *t, const struct ft_clock_page *s, bool { real.it_value = ft_ts(at); if (real.it_value.tv_sec == 0 && real.it_value.tv_nsec == 0) real.it_value.tv_nsec = 1; - if (t->interval > 0) + if (t->interval > 0 && rate > 0) { int64_t iv = (int64_t) ((double) t->interval / rate); real.it_interval = ft_ts(iv < 1 ? 1 : iv); @@ -347,7 +347,9 @@ static void ft_timer_value(struct ft_timer *t, struct itimerspec *out) { int64_t now = ft_page_rt(&s, ft_real_rt()); __int128 left = (__int128) ft_timer_next(t, now) - now; - out->it_value = ft_ts(left < 1 ? 1 : left > INT64_MAX ? INT64_MAX : (int64_t) left); + if (left < 1) left = 1; + out->it_value.tv_sec = (time_t) (left / FT_NS); + out->it_value.tv_nsec = (long) (left % FT_NS); } } diff --git a/src/agent_env/utils/faketime_clock/clockpage.py b/src/agent_env/utils/faketime_clock/clockpage.py index 4002bb6c2..15e483f4e 100644 --- a/src/agent_env/utils/faketime_clock/clockpage.py +++ b/src/agent_env/utils/faketime_clock/clockpage.py @@ -16,7 +16,11 @@ A write that would put the universe less than CONTINUITY_NS behind where the page has it now (a rate change computed from a universe read a moment before the write) continues it from where it is instead: the write's real time is taken last, while seq is odd, and the universe at it read from the page being replaced, so no reader of either page ever sees -the clock step back. A larger step back is a set_time and is written as given.""" +the clock step back. A larger step back is a set_time and is written as given. + +A universe outside the env clock's range (EARLIEST_NS to LATEST_NS, the gateway's), given or run on to, is written at +its end, where the gateway's clock and agent-env's libfaketime stop too, so a write never fails halfway and leaves the +page mid-write, and a session program's deadline past the end is never reached rather than reached at once.""" import ctypes import mmap import os @@ -34,6 +38,7 @@ # magic version seq universe_ns anchor_ns rate armed reserved generation check mono_universe_ns mono_anchor_ns LAYOUT = struct.Struct(" None: del buf +def _held(ns: int) -> int: + return max(EARLIEST_NS, min(ns, LATEST_NS)) + + def _universe_at(armed, universe_ns, anchor_ns, rate, now_ns) -> int: if not armed: return now_ns if rate == 0 or now_ns <= anchor_ns: return universe_ns - return universe_ns + int((now_ns - anchor_ns) * rate) + return _held(universe_ns + int((now_ns - anchor_ns) * rate)) def write(armed: int, universe: float, rate: float, anchor: float) -> dict: m = open_page() _, _, seq, o_u, o_a, o_rate, o_armed, _, generation, _, _, _ = LAYOUT.unpack(m[:LAYOUT.size]) - universe_ns, anchor_ns = int(Decimal(str(universe)) * 10**9), int(Decimal(str(anchor)) * 10**9) + universe_ns, anchor_ns = _held(int(Decimal(str(universe)) * 10**9)), int(Decimal(str(anchor)) * 10**9) if not armed: rate = 1.0 generation += 1 diff --git a/tst/clock/harness.py b/tst/clock/harness.py index 9805d4551..cc8a4905e 100644 --- a/tst/clock/harness.py +++ b/tst/clock/harness.py @@ -2,9 +2,9 @@ processes real, so this driver is on real time while it writes the clock page as the follower would, and every program under test runs as the session user, whom the library fakes. Each gate prints one JSON document on stdout. - harness.py waits | ratechange | jumps [ROUNDS] | cancel | timerfds | condstress [SECONDS] | semstress [SECONDS] - | stall | torn [SECONDS] | deadwriter | marker | identity | envrace [SECONDS] | forklock [FORKS] | tls - | chromium [agentenv|stock LAUNCHES PARALLEL LIMIT] | probe + harness.py waits | ratechange | jumps [ROUNDS] | cancel | timerfds | frozen_timers | condstress [SECONDS] + | semstress [SECONDS] | stall | torn [SECONDS] | deadwriter | end | end_waits | span | marker | identity + | envrace [SECONDS] | forklock [FORKS] | tls | chromium [agentenv|stock LAUNCHES PARALLEL LIMIT] | probe """ import ctypes import json @@ -315,6 +315,19 @@ def timerfds(): return out +def frozen_timers(): + """On a clock frozen a day into its range: a periodic timerfd armed at its now, every second, has expired once 1.5 s + later, since a frozen clock brings no other; and one armed for an hour short of the end of the range has all of the + 584 years between left (tfdfrozen.py).""" + preload() + fresh_page() + set_clock(-9223286400.0, 0) + r = subprocess.run(user_cmd(["python3", f"{PROGRAMS}/tfdfrozen.py", "9223368436"]), capture_output=True, text=True, + cwd="/tmp", timeout=30) + preload(None) + return json.loads(r.stdout) + + def _with_page_changes(p) -> int: """+10 min every 0.5 s while ``p`` runs; how many.""" n = 0 @@ -462,18 +475,60 @@ def deadwriter(): def end(): - """The clock a second short of the end of 64 bits of nanoseconds at rate 1, as a gateway that outlives its range - leaves it: two seconds on, reads in C, Python and Node show the end rather than wrap to 1677.""" + """The clock a second short of the end of its range at rate 1, as a gateway that outlives its range leaves it: two + seconds on, reads in C, Python and Node show the end rather than run past it or wrap to 1677; and so they do after + the page is written with a universe past the end.""" preload() fresh_page() set_clock(9223372035.0, 1) time.sleep(2.5) - reads = {name: subprocess.run(user_cmd(argv), capture_output=True, text=True).stdout.strip() for name, argv in ( + reads = _end_reads() + set_clock(9223372100.0, 1) + after = _end_reads() + preload(None) + return {**reads, "after_write": after, "seq": page()[2]} + + +def _end_reads() -> dict: + return {name: subprocess.run(user_cmd(argv), capture_output=True, text=True).stdout.strip() for name, argv in ( ("date", ["date", "-u", "+%s.%N"]), ("python", ["python3", "-c", "import time; print(time.time_ns())"]), ("node", ["node", "-e", "console.log(Date.now())"]))} + + +def end_waits(): + """At the end of the range, run into it and then frozen there, as a follower writes the clock of a gateway that + outlived it: an absolute wait for a second past the time a read shows never ends, rather than at once, so a program + that waits in a loop doesn't spin (endwaits.py).""" + preload() + fresh_page() + set_clock(9223372035.0, 1) + time.sleep(2.5) + out = {"running": _waits_at_end()} + set_clock(9223372036.0, 0) + out["frozen"] = _waits_at_end() + preload(None) + return out + + +def _waits_at_end() -> dict: + r = subprocess.run(user_cmd(["python3", f"{PROGRAMS}/endwaits.py"]), capture_output=True, text=True, cwd="/tmp", + timeout=30) + return json.loads(r.stdout) + + +def span(): + """A page from the start of the range run on at a day per second for 29.7 real hours without a rewrite (its follower + gone): its universe, 1970-06-17, is read where it ran to, not at the end of 64 bits.""" + preload() + fresh_page() + anchor = time.time() - 29.7 * 3600 + clockpage.write(1, -9223372036.0, 86400.0, anchor) + before = time.time() + read = float(subprocess.run(user_cmd(["date", "-u", "+%s.%N"]), capture_output=True, text=True).stdout) + after = time.time() preload(None) - return reads + return {"read": read, "from": -9223372036 + (before - anchor) * DAY, "to": -9223372036 + (after - anchor) * DAY} def _classify(value: float, before: float, universe_offset: float) -> object: @@ -698,8 +753,9 @@ def probe(): return {"futex_waitv_errno": ctypes.get_errno() if r == -1 else 0} -GATES = {f.__name__: f for f in (waits, ratechange, jumps, cancel, timerfds, condstress, semstress, stall, torn, - deadwriter, end, marker, identity, envrace, forklock, chromium, tls, probe)} +GATES = {f.__name__: f for f in (waits, ratechange, jumps, cancel, timerfds, frozen_timers, condstress, semstress, + stall, torn, deadwriter, end, end_waits, span, marker, identity, envrace, forklock, + chromium, tls, probe)} if __name__ == "__main__": gate = GATES[sys.argv[1]] diff --git a/tst/clock/programs/endwaits.py b/tst/clock/programs/endwaits.py new file mode 100644 index 000000000..055e0503a --- /dev/null +++ b/tst/clock/programs/endwaits.py @@ -0,0 +1,30 @@ +"""At the end of the clock's range: absolute realtime waits for a second past the time a read shows, through +clock_nanosleep and a timerfd, each given 2 s of real time. Prints the read and whether each ended.""" +import ctypes +import json +import select +import threading +import time + +libc = ctypes.CDLL(None, use_errno=True) + + +class Timespec(ctypes.Structure): + _fields_ = [("tv_sec", ctypes.c_long), ("tv_nsec", ctypes.c_long)] + + +class Itimerspec(ctypes.Structure): + _fields_ = [("it_interval", Timespec), ("it_value", Timespec)] + + +CLOCK_REALTIME, TIMER_ABSTIME, TFD_TIMER_ABSTIME = 0, 1, 1 +now = time.time_ns() +due = Timespec(now // 10**9 + 1, 0) +sleeper = threading.Thread(target=libc.clock_nanosleep, args=(CLOCK_REALTIME, TIMER_ABSTIME, ctypes.byref(due), None), + daemon=True) +sleeper.start() +fd = libc.timerfd_create(CLOCK_REALTIME, 0) +assert libc.timerfd_settime(fd, TFD_TIMER_ABSTIME, ctypes.byref(Itimerspec(Timespec(0, 0), due)), None) == 0 +fired = bool(select.select([fd], [], [], 2.0)[0]) +sleeper.join(0.1) +print(json.dumps({"now": now, "clock_nanosleep_ended": not sleeper.is_alive(), "timerfd_fired": fired})) diff --git a/tst/clock/programs/tfdfrozen.py b/tst/clock/programs/tfdfrozen.py new file mode 100644 index 000000000..18c03d7d0 --- /dev/null +++ b/tst/clock/programs/tfdfrozen.py @@ -0,0 +1,38 @@ +"""Two realtime timerfds armed through libc for clock times on a frozen clock: a periodic one at the universe's now, +every second, read 1.5 s later; and a one-shot at the realtime the argument names (epoch seconds), whose time left +timerfd_gettime gives. Prints the periodic one's expirations and the other's seconds left.""" +import ctypes +import json +import os +import select +import sys +import time + +libc = ctypes.CDLL(None, use_errno=True) + + +class Timespec(ctypes.Structure): + _fields_ = [("tv_sec", ctypes.c_long), ("tv_nsec", ctypes.c_long)] + + +class Itimerspec(ctypes.Structure): + _fields_ = [("it_interval", Timespec), ("it_value", Timespec)] + + +CLOCK_REALTIME, TFD_TIMER_ABSTIME = 0, 1 + + +def armed(value: Timespec, interval: Timespec) -> int: + fd = libc.timerfd_create(CLOCK_REALTIME, 0) + assert libc.timerfd_settime(fd, TFD_TIMER_ABSTIME, ctypes.byref(Itimerspec(interval, value)), None) == 0 + return fd + + +periodic = armed(Timespec(*divmod(time.time_ns(), 10**9)), Timespec(1, 0)) +far = armed(Timespec(int(sys.argv[1]), 0), Timespec(0, 0)) +left = Itimerspec() +assert libc.timerfd_gettime(far, ctypes.byref(left)) == 0 +time.sleep(1.5) +count = int.from_bytes(os.read(periodic, 8), "little") if select.select([periodic], [], [], 0)[0] else 0 +print(json.dumps({"periodic_count": count, + "far_left_s": left.it_value.tv_sec + left.it_value.tv_nsec / 1e9})) diff --git a/tst/clock/range_test.py b/tst/clock/range_test.py index a71901ea7..efd084a93 100644 --- a/tst/clock/range_test.py +++ b/tst/clock/range_test.py @@ -107,4 +107,21 @@ def test_chrome_runs_every_launch_near_either_end(gate, when): def test_a_clock_that_outlives_its_range_stops_at_the_end_rather_than_wrapping(gate): - assert gate("end") == {"date": "9223372036.854775807", "python": "9223372036854775807", "node": "9223372036854"} + end = {"date": "9223372036.000000000", "python": "9223372036000000000", "node": "9223372036000"} + r = gate("end") + assert r == {**end, "after_write": end, "seq": r["seq"]} and r["seq"] % 2 == 0, r + + +def test_at_the_end_a_wait_for_a_time_past_it_never_ends_rather_than_ending_at_once(gate): + waited = {"now": 9223372036000000000, "clock_nanosleep_ended": False, "timerfd_fired": False} + assert gate("end_waits") == {"running": waited, "frozen": waited} + + +def test_a_page_before_1970_left_to_run_for_a_day_reads_where_it_ran_to(gate): + r = gate("span") + assert r["from"] - 1 <= r["read"] <= r["to"] + 1, r + + +def test_a_frozen_clocks_timers_expire_once_and_tell_all_the_time_left(gate): + r = gate("frozen_timers") + assert r["periodic_count"] == 1 and abs(r["far_left_s"] - (9223368436 + 9223286400)) < 1, r diff --git a/tst/env/gateway/clock_test.py b/tst/env/gateway/clock_test.py index b5969d898..9a04538d9 100644 --- a/tst/env/gateway/clock_test.py +++ b/tst/env/gateway/clock_test.py @@ -234,32 +234,32 @@ def test_set_time_rejects_overflowing_t0(): c.set_time("9999-12-31T00:00:00Z", rate=1.0) -def test_set_time_allows_max_t0_when_frozen(): +def test_set_time_allows_the_last_t0_when_frozen(): c = Clock(now_fn=FakeNow()) - c.set_time("9999-12-31T00:00:00Z", rate=0) # frozen never advances - assert c.read()["virtual_time"] == "9999-12-31T00:00:00Z" + c.set_time("2262-04-11T23:47:16Z", rate=0) # frozen never advances + assert c.read()["virtual_time"] == "2262-04-11T23:47:16Z" -def test_read_saturates_past_the_arm_time_horizon(): - """A t0 accepted by the horizon check still overflows if the gateway outlives it — reads saturate, not 500.""" +def test_read_stops_at_the_end_of_the_range_past_the_arm_time_horizon(): + """A t0 accepted by the horizon check still runs to the end if the gateway outlives it: reads stop there, not 500.""" now = FakeNow() c = Clock(now_fn=now) - c.set_time("9999-12-30T00:00:00Z", rate=1.0) # accepted: >1 real day of headroom - now.tick(86400.0 * 2) # ...but still up two real days later - assert c.read()["virtual_time"] == "9999-12-31T23:59:59.999999Z" - assert c.state()["virtual_time"] == "9999-12-31T23:59:59.999999Z" + c.set_time("2262-04-11T22:47:16Z", rate=1.0) # accepted: a real hour of headroom + now.tick(3600.0 * 2) # ...but still up two real hours later + assert c.read()["virtual_time"] == "2262-04-11T23:47:16Z" + assert c.state()["virtual_time"] == "2262-04-11T23:47:16Z" -def test_saturated_clock_stays_monotonic(): +def test_a_clock_at_the_end_stays_monotonic(): now = FakeNow() c = Clock(now_fn=now) - c.set_time("9999-12-30T00:00:00Z", rate=1.0) + c.set_time("2262-04-11T22:47:16Z", rate=1.0) seen = [] for _ in range(4): - now.tick(86400.0) + now.tick(1800.0) seen.append(c.read()["virtual_time"]) assert seen == sorted(seen) - assert seen[-1] == "9999-12-31T23:59:59.999999Z" + assert seen[-1] == "2262-04-11T23:47:16Z" def test_elapsed_runs_at_each_arm_s_rate_and_counts_a_re_arm_forward_but_not_back(): diff --git a/tst/unit/env/envs/test_computer_clock_follower.py b/tst/unit/env/envs/test_computer_clock_follower.py index 9f57d3f2d..86ee623a0 100644 --- a/tst/unit/env/envs/test_computer_clock_follower.py +++ b/tst/unit/env/envs/test_computer_clock_follower.py @@ -19,6 +19,7 @@ import pytest import agent_env +from agent_env.env.gateway.clock import EARLIEST, LATEST from agentenv_protocol.computer import clock as protocol_clock CLOCK = Path(agent_env.__file__).parent / "utils" / "faketime_clock" @@ -146,6 +147,36 @@ def test_the_clock_file_the_follower_writes_reads_as_its_universe_to_a_server_on assert protocol_clock.session_time() == pytest.approx(time.time(), abs=1) +def test_the_page_holds_the_env_clocks_range(): + clockpage = _clockpage(Path("/nonexistent")) + assert (clockpage.EARLIEST_NS, clockpage.LATEST_NS) == (int(EARLIEST.timestamp()) * 10**9, + int(LATEST.timestamp()) * 10**9) + + +def test_a_universe_outside_the_range_is_written_at_its_end_and_the_page_left_whole(tmp_path): + """As a follower writes the clock of a gateway that outlives its range: a universe given past either end, or one + the page has run on past the end to when a re-anchoring continues it, is written at the end, where the gateway's + clock stops, and a write never fails halfway with the page left mid-write (seq odd).""" + clockpage = _clockpage(tmp_path / "page") + clockpage.FILE = str(tmp_path / "clock") + end = int(LATEST.timestamp()) * 10**9 + + def page() -> tuple[int, int, float]: + fields = clockpage.LAYOUT.unpack((tmp_path / "page").read_bytes()) + return fields[2], fields[3], fields[5] + + clockpage.write(1, 9223372100.0, 1.0, time.time()) + seq, universe_ns, _ = page() + assert (seq % 2, universe_ns) == (0, end) + clockpage.write(1, -9223372100.0, 1.0, time.time()) + assert page()[1] == int(EARLIEST.timestamp()) * 10**9 + + clockpage.write(1, 9223372035.0, 1.0, time.time() - 1.95) + clockpage.write(1, 9223372036.0, 0.0, time.time()) + seq, universe_ns, rate = page() + assert (seq % 2, universe_ns, rate) == (0, end, 0.0) + + def test_it_follows_the_gateway_its_config_names_and_acknowledges_each_version_with_its_next_watch(follower): gateway = Gateway() try: diff --git a/tst/unit/env/gateway/clock_range_test.py b/tst/unit/env/gateway/clock_range_test.py index de0a93b9e..61c9bf6c2 100644 --- a/tst/unit/env/gateway/clock_range_test.py +++ b/tst/unit/env/gateway/clock_range_test.py @@ -1,17 +1,26 @@ """The env clock's range, the times 64 bits of nanoseconds since 1970 hold, as Python and the computers that follow the clock keep time: the gateway arms and runs anywhere in it, before 1970 too and a day per second at today's dates, and -refuses a time outside it, or one it would run past the end from within a real hour, up front, naming the range.""" +refuses a time outside it, however it's spelled, or a write that would bring the clock to the end within a real hour, up +front, naming the range. A clock that runs to the end anyway, on a gateway that outlives it, stands there.""" from __future__ import annotations +import re +from datetime import datetime, timezone + import pytest -from agent_env.env.gateway.clock import EARLIEST, LATEST, Clock, ClockError +from agent_env.env.gateway.clock import EARLIEST, LATEST, Clock, ClockError, _iso, check_arm +from agent_env.env.gateway.constants import EXT_CLOCK_URI, GATEWAY_EXTENSIONS from tst.unit.env.gateway.triggers_time_test import FakeNow RANGE = "the env clock's range, 1677-09-21T00:12:44Z to 2262-04-11T23:47:16Z" END = "would pass 2262-04-11T23:47:16Z, the end of the env clock's range, within a real hour" +def _refused(message: str): + return pytest.raises(ClockError, match=re.escape(message)) + + def test_the_range_is_the_whole_seconds_64_bits_of_nanoseconds_since_1970_hold(): first, last = int(EARLIEST.timestamp()), int(LATEST.timestamp()) assert (first - 1) * 10**9 < -2**63 <= first * 10**9 @@ -30,22 +39,87 @@ def test_the_clock_arms_and_runs_anywhere_in_its_range(virtual_time, rate): assert clock.read()["virtual_time"] >= virtual_time -@pytest.mark.parametrize("virtual_time", ["0001-01-01T00:00:00Z", "1600-01-01T00:00:00Z", "1677-09-21T00:12:43Z", - "2262-04-11T23:47:17Z", "3026-11-23T12:00:00Z", "9999-12-31T23:59:59Z", - "10000-01-01T00:00:00Z"]) -def test_a_time_outside_the_range_is_refused_naming_it(virtual_time): - with pytest.raises(ClockError, match=f"virtual_time '{virtual_time}' is outside {RANGE}"): +@pytest.mark.parametrize("virtual_time", [ + "0001-01-01T00:00:00Z", "1600-01-01T00:00:00Z", "1677-09-21T00:12:43Z", "2262-04-11T23:47:17Z", + "3026-11-23T12:00:00Z", "9999-12-31T23:59:59Z", "10000-01-01T00:00:00Z", "0000-01-01T00:00:00Z", + "0001-01-01T00:00:00+01:00", "9999-12-31T23:59:59-01:00", "1677-09-21T00:12:44+00:01"]) +def test_a_time_outside_the_range_is_refused_naming_it_however_its_spelled(virtual_time): + with _refused(f"virtual_time '{virtual_time}' is outside {RANGE}"): + Clock(now_fn=FakeNow()).set_time(virtual_time, rate=0) + + +@pytest.mark.parametrize("virtual_time", ["10000-junk", "999-01-01T00:00:00Z", "2026-13-01T00:00:00Z"]) +def test_a_string_that_isnt_a_time_is_refused_as_one(virtual_time): + with _refused(f"invalid RFC3339 virtual_time '{virtual_time}'"): Clock(now_fn=FakeNow()).set_time(virtual_time, rate=0) def test_arming_advancing_or_speeding_a_clock_that_would_pass_the_end_within_a_real_hour_names_it(): clock = Clock(now_fn=FakeNow()) - with pytest.raises(ClockError, match=f"virtual_time '2262-04-11T23:00:00Z' at rate 1 {END}"): + with _refused(f"virtual_time '2262-04-11T23:00:00Z' at rate 1 {END}"): clock.set_time("2262-04-11T23:00:00Z") clock.set_time("2262-04-01T00:00:00Z") - with pytest.raises(ClockError, match=f"virtual_time '2262-04-11T23:00:00Z' at rate 1 {END}"): + with _refused(f"virtual_time '2262-04-11T23:00:00Z' at rate 1 {END}"): clock.advance("2262-04-11T23:00:00Z") - with pytest.raises(ClockError, match=f"rate 3600 {END}"): + with _refused(f"rate 3600 {END}"): clock.set_rate(3600) assert clock.read()["virtual_time"] == "2262-04-01T00:00:00Z" + + +def test_however_slow_a_clock_runs_from_the_end_it_would_pass_it(): + with _refused(f"virtual_time '2262-04-11T23:47:16Z' at rate 1e-10 {END}"): + Clock(now_fn=FakeNow()).set_time("2262-04-11T23:47:16Z", rate=1e-10) + clock = Clock(now_fn=FakeNow()) + clock.set_time("2262-04-11T23:47:16Z", rate=0) + with _refused(f"rate 1e-10 {END}"): + clock.set_rate(1e-10) + + +def test_in_its_last_real_hour_a_clock_takes_every_write_that_doesnt_bring_the_end_closer(): + """An advance to the time it shows (as a settle does to set a due event going) and a rate no faster go through; a + jump or a faster rate doesn't.""" + now = FakeNow() + clock = Clock(now_fn=now) + clock.set_time("2262-04-11T22:00:00Z") + now.tick(50 * 60) + + assert clock.advance("2262-04-11T22:50:00Z")["virtual_time"] == "2262-04-11T22:50:00Z" + assert clock.set_rate(1)["virtual_seconds_per_real_second"] == 1 + with _refused(f"virtual_time '2262-04-11T22:50:01Z' at rate 1 {END}"): + clock.advance("2262-04-11T22:50:01Z") + with _refused(f"rate 2 {END}"): + clock.set_rate(2) + assert clock.set_rate(0.5)["virtual_seconds_per_real_second"] == 0.5 + + +def test_a_clock_that_outlives_its_range_stands_at_the_end_and_can_still_be_frozen_or_set_back(): + """Its reads and state stop at the end, at rate 0, so the computers that follow it stop there too rather than run + past what their clock page holds.""" + now = FakeNow() + clock = Clock(now_fn=now) + clock.set_time("2262-04-11T22:47:16Z") + now.tick(3601) + assert clock.read() == {"virtual_time": "2262-04-11T23:47:16Z"} + state = clock.state() + assert (state["virtual_time"], state["virtual_seconds_per_real_second"]) == ("2262-04-11T23:47:16Z", 0.0) + now.tick(10**9) + assert clock.now() == LATEST + + assert clock.advance("2262-04-11T23:47:16Z")["virtual_time"] == "2262-04-11T23:47:16Z" + assert clock.set_rate(1)["virtual_time"] == "2262-04-11T23:47:16Z" + assert clock.set_rate(0)["virtual_time"] == "2262-04-11T23:47:16Z" + with _refused("advance only moves forward"): + clock.advance("2262-04-11T23:00:00Z") + assert clock.set_time("2026-11-23T12:00:00Z")["virtual_time"] == "2026-11-23T12:00:00Z" + + +def test_a_check_names_the_time_as_its_caller_wrote_it(): + with _refused(f"virtual_time '1677-09-21T05:00:00' in Asia/Tokyo is outside {RANGE}"): + check_arm("1677-09-20T19:41:01Z", 0, what="virtual_time '1677-09-21T05:00:00' in Asia/Tokyo") + assert check_arm("2026-11-23T12:00:00Z", 60) == (datetime(2026, 11, 23, 12, tzinfo=timezone.utc), 60.0) + + +def test_the_clock_card_states_the_range(): + clock = next(ext for ext in GATEWAY_EXTENSIONS if ext["uri"] == EXT_CLOCK_URI) + assert f"{_iso(EARLIEST)} to {_iso(LATEST)}" in clock["description"] diff --git a/tst/unit/env/gateway/get_time_test.py b/tst/unit/env/gateway/get_time_test.py index d586c15a4..ad9f734e6 100644 --- a/tst/unit/env/gateway/get_time_test.py +++ b/tst/unit/env/gateway/get_time_test.py @@ -275,21 +275,22 @@ def test_local_time_is_the_same_reading_at_second_precision(gw): @pytest.mark.asyncio -async def test_a_time_the_zone_cannot_show_is_a_tool_error_naming_it(gw): - """A gateway that outlives its clock's range reads the last time a datetime holds, which Tokyo's clock can't show.""" - now, zone = "9999-12-31T23:59:59Z", "Asia/Tokyo" +@pytest.mark.parametrize("arm, rate, real_s, zone, now", [ + ("2026-01-01T00:00:00Z", 86400, 1e9, "Asia/Tokyo", "2262-04-11T23:47:16Z"), + ("1677-09-21T00:12:44Z", 0, 0, "America/New_York", "1677-09-21T00:12:44Z"), +], ids=["a-gateway-that-outlives-the-range", "the-start-of-the-range"]) +async def test_every_time_the_clock_holds_shows_in_any_zone(gw, arm, rate, real_s, zone, now): + """The clock stays within its range, even on a gateway that outlives it, and every zone's clock shows its ends.""" real = FakeNow() gw._clock = Clock(now_fn=real) - gw._clock.set_time("2026-01-01T00:00:00Z", 86400) - real.tick(1e9) + gw._clock.set_time(arm, rate) + real.tick(real_s) gw._register_get_time_tool() - message = f"the current time {now} can't be shown in time zone {zone!r}: its local date is out of range" - assert await _mcp_call(gw, {"time_zone": zone}) == { - "content": [{"type": "text", "text": message}], "isError": True} - status, body = await _step_call(gw, {"time_zone": zone}) - assert (status, json.loads(body)) == ( - 200, {"content": [{"type": "text", "text": message}], "isError": True, "changelog_id": None}) + payload = await _mcp_call(gw, {"time_zone": zone}) + reading = json.loads(payload["content"][0]["text"]) + assert reading["current_time"] == now and reading["time_zone"] == zone + assert datetime.fromisoformat(reading["local_time"]) == datetime.fromisoformat(now) def test_the_description_keeps_tool_dates_in_utc_and_gives_the_users_clock_when_their_zone_is_known(): diff --git a/tst/unit/task_step/sync_env_clock_test.py b/tst/unit/task_step/sync_env_clock_test.py index 191247b98..c7f8565f1 100644 --- a/tst/unit/task_step/sync_env_clock_test.py +++ b/tst/unit/task_step/sync_env_clock_test.py @@ -1,5 +1,6 @@ """Unit tests for SyncEnvClockTaskStep — round-trip + the per-server sync_time fan-out (mocked).""" import json +import re from types import SimpleNamespace import pytest @@ -12,6 +13,7 @@ T0 = "2026-01-01T00:00:00Z" CLOCK_URL = "http://gateway:9000/clock/time" +RANGE = "the env clock's range, 1677-09-21T00:12:44Z to 2262-04-11T23:47:16Z" def _step(**kw): @@ -341,6 +343,35 @@ def test_a_time_that_disagrees_with_the_zone_is_refused(virtual_time, zone, matc _zoned(virtual_time, zone) +@pytest.mark.parametrize("virtual_time, zone", [("0001-01-01T00:00:00", "Asia/Kolkata"), + ("9999-12-31T23:00:00", "America/Chicago")]) +def test_a_wall_time_whose_instant_no_date_holds_is_refused_naming_the_clocks_range(virtual_time, zone): + with pytest.raises(ValueError, match=re.escape(f"virtual_time '{virtual_time}' in {zone} is outside {RANGE}")): + _zoned(virtual_time, zone) + + +@pytest.mark.parametrize("kwargs, problem", [ + ({"virtual_time": "3026-01-01T00:00:00Z"}, f"virtual_time '3026-01-01T00:00:00Z' is outside {RANGE}"), + ({"virtual_time": "1677-09-21T05:00:00", "timezone": "Asia/Tokyo"}, + f"virtual_time '1677-09-21T05:00:00' in Asia/Tokyo is outside {RANGE}"), + ({"virtual_time": "2262-04-11T23:00:00Z"}, + "virtual_time '2262-04-11T23:00:00Z' at rate 1 would pass 2262-04-11T23:47:16Z, the end of the env clock's range"), + ({"virtual_time": "2026-01-01T12:00:00"}, "invalid RFC3339 virtual_time '2026-01-01T12:00:00'"), + ({"virtual_time": T0, "virtual_seconds_per_real_second": -1}, "rate must be non-negative"), +]) +def test_a_time_or_rate_the_gateway_would_refuse_is_a_problem_before_anything_deploys(kwargs, problem): + problems = SyncEnvClockTaskStep(id="sync", version=1, env_id="e1", depends_on=[], **kwargs).config_problems() + assert len(problems) == 1 and problems[0].startswith(f"step 'sync': {problem}"), problems + + +def test_a_time_the_gateway_arms_at_is_no_problem(): + assert _step().config_problems() == [] + assert _step(virtual_seconds_per_real_second=0).config_problems() == [] + assert SyncEnvClockTaskStep(id="sync", version=1, env_id="e1", virtual_time="2262-04-11T23:47:16Z", + virtual_seconds_per_real_second=0).config_problems() == [] + assert _zoned("1677-09-21T09:31:43", "Asia/Tokyo").config_problems() == [] + + def test_without_a_zone_virtual_time_is_passed_through_untouched(): assert _step().armed_virtual_time == T0 assert resolve_virtual_time("2026-01-01T12:00:00", None) == "2026-01-01T12:00:00" From ffec8b61bf20bfe4b66232d4b7b778e4953a7a52 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 23 Nov 2026 15:40:55 -0800 Subject: [PATCH 06/16] test(clock): a periodic timer armed on a frozen clock ticks every second once the clock runs again Co-Authored-By: Claude Opus 5.5 --- tst/clock/harness.py | 13 ++++++++----- tst/clock/programs/tfdfrozen.py | 18 ++++++++++++++---- tst/clock/range_test.py | 3 ++- 3 files changed, 24 insertions(+), 10 deletions(-) diff --git a/tst/clock/harness.py b/tst/clock/harness.py index cc8a4905e..e4bc5fcc0 100644 --- a/tst/clock/harness.py +++ b/tst/clock/harness.py @@ -317,15 +317,18 @@ def timerfds(): def frozen_timers(): """On a clock frozen a day into its range: a periodic timerfd armed at its now, every second, has expired once 1.5 s - later, since a frozen clock brings no other; and one armed for an hour short of the end of the range has all of the - 584 years between left (tfdfrozen.py).""" + later, since a frozen clock brings no other, and ticks every second once the clock runs again; and one armed for an + hour short of the end of the range has all of the 584 years between left (tfdfrozen.py).""" preload() fresh_page() set_clock(-9223286400.0, 0) - r = subprocess.run(user_cmd(["python3", f"{PROGRAMS}/tfdfrozen.py", "9223368436"]), capture_output=True, text=True, - cwd="/tmp", timeout=30) + p = subprocess.Popen(user_cmd(["python3", f"{PROGRAMS}/tfdfrozen.py", "9223368436"]), stdin=subprocess.PIPE, + stdout=subprocess.PIPE, text=True, cwd="/tmp") + frozen = json.loads(p.stdout.readline()) + set_rate(1) + resumed, _ = p.communicate("go\n", timeout=30) preload(None) - return json.loads(r.stdout) + return {**frozen, **json.loads(resumed)} def _with_page_changes(p) -> int: diff --git a/tst/clock/programs/tfdfrozen.py b/tst/clock/programs/tfdfrozen.py index 18c03d7d0..f0834ef69 100644 --- a/tst/clock/programs/tfdfrozen.py +++ b/tst/clock/programs/tfdfrozen.py @@ -1,6 +1,7 @@ """Two realtime timerfds armed through libc for clock times on a frozen clock: a periodic one at the universe's now, every second, read 1.5 s later; and a one-shot at the realtime the argument names (epoch seconds), whose time left -timerfd_gettime gives. Prints the periodic one's expirations and the other's seconds left.""" +timerfd_gettime gives. Prints the periodic one's expirations and the other's seconds left, then, once a line on stdin +says the clock runs again, the periodic one's expirations over the next 2.5 s.""" import ctypes import json import os @@ -33,6 +34,15 @@ def armed(value: Timespec, interval: Timespec) -> int: left = Itimerspec() assert libc.timerfd_gettime(far, ctypes.byref(left)) == 0 time.sleep(1.5) -count = int.from_bytes(os.read(periodic, 8), "little") if select.select([periodic], [], [], 0)[0] else 0 -print(json.dumps({"periodic_count": count, - "far_left_s": left.it_value.tv_sec + left.it_value.tv_nsec / 1e9})) + + +def expirations() -> int: + return int.from_bytes(os.read(periodic, 8), "little") if select.select([periodic], [], [], 0)[0] else 0 + + +print(json.dumps({"periodic_count": expirations(), + "far_left_s": left.it_value.tv_sec + left.it_value.tv_nsec / 1e9}), flush=True) +sys.stdin.readline() +expirations() +time.sleep(2.5) +print(json.dumps({"resumed_count": expirations()}), flush=True) diff --git a/tst/clock/range_test.py b/tst/clock/range_test.py index efd084a93..c6dc3d814 100644 --- a/tst/clock/range_test.py +++ b/tst/clock/range_test.py @@ -122,6 +122,7 @@ def test_a_page_before_1970_left_to_run_for_a_day_reads_where_it_ran_to(gate): assert r["from"] - 1 <= r["read"] <= r["to"] + 1, r -def test_a_frozen_clocks_timers_expire_once_and_tell_all_the_time_left(gate): +def test_a_frozen_clocks_timers_expire_once_tell_all_the_time_left_and_tick_again_once_it_runs(gate): r = gate("frozen_timers") assert r["periodic_count"] == 1 and abs(r["far_left_s"] - (9223368436 + 9223286400)) < 1, r + assert 2 <= r["resumed_count"] <= 3, r From bbe3e0505cb14e15ba9569f5e24cdcf71bcf37da Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 23 Nov 2026 17:23:04 -0800 Subject: [PATCH 07/16] fix(clock): a clock frozen in its last real hour starts again, and lint names a sync_env_clock step once set_rate refused any rate faster than the current one, and advance any jump, that would bring the clock to the end of its range within a real hour. A clock armed an hour or more before the end and frozen, as always_on freezes it between turns (or a harness that pauses it, or sync_env_clock at rate 0 then set_env_clock_rate), couldn't be started again there: always_on failed mid-run at a time inside the range, where main completes, and a hook's advance to an event in that hour failed too. Only set_time, which arms the clock, still refuses that hour; set_rate takes any rate and advance any time up to the end, and a clock that reaches the end stands there at rate 0, as one that outlives its range does. A clock armed frozen at the end now answers set_rate as one that ran there does. sync_env_clock's config problem no longer names its step itself, as the verifiers' don't: lint, which adds the step, printed "step 'clock': step 'clock': ...". Co-Authored-By: Claude Opus 5.5 --- src/agent_env/env/gateway/clock.py | 16 ++--- src/agent_env/env/gateway/constants.py | 2 +- .../task_step/task_steps/sync_env_clock.py | 2 +- tst/unit/env/gateway/clock_range_test.py | 64 +++++++++++-------- tst/unit/task_step/sync_env_clock_test.py | 11 +++- 5 files changed, 56 insertions(+), 39 deletions(-) diff --git a/src/agent_env/env/gateway/clock.py b/src/agent_env/env/gateway/clock.py index 9c000222a..383438874 100644 --- a/src/agent_env/env/gateway/clock.py +++ b/src/agent_env/env/gateway/clock.py @@ -20,8 +20,8 @@ class ClockError(ValueError): MAX_RATE = 86400.0 # 1 real second = 1 virtual day (the max virtual-time speed) -# Fast-fail a write that would bring the clock to LATEST within a real hour at `rate` (frozen clocks exempt): an hour, -# so a day per second still arms at today's dates. Not the guarantee: a clock that runs to LATEST stands there. +# Fast-fail arming a clock that would reach LATEST within a real hour at `rate` (frozen clocks exempt): an hour, so a +# day per second still arms at today's dates. Not the guarantee: a clock that runs to LATEST stands there. _OVERFLOW_HORIZON_S = 3600.0 _MAX_T0 = datetime.max.replace(tzinfo=timezone.utc) # The times the clock holds: those 64 bits of nanoseconds since 1970 hold, as Python and the computers' clock page keep @@ -236,15 +236,14 @@ def set_time(self, virtual_time: str, rate=1.0, time_zone: str | None = None) -> def set_rate(self, rate) -> dict: """Change an armed clock's rate from its time at the call, keeping t0 and generation as an advance does, so time triggers keep their marks and a rate change can't step the clock back by a time read a moment earlier; 0 freezes - the clock. A faster rate that would bring it to the end of its range within a real hour is refused.""" + the clock. No rate is refused for nearing the end of the range, which the clock stands at once it gets there, so + a harness that froze it near the end can always start it again.""" r = _parse_rate(rate) with self._lock: if not self._armed or self._t0 is None: raise ClockError("clock is not armed") now = self._now() ran = (now - self._anchor) * self._rate - if r > self._rate and _ends_within_an_hour(self._upto_end(ran + self._ahead), r): - raise ClockError(_past_end(f"rate {r:g}")) self._lived += ran self._ahead += ran self._anchor = now @@ -253,8 +252,9 @@ def set_rate(self, rate) -> dict: return self.state() def advance(self, virtual_time: str) -> dict: - """Jump forward to virtual_time on the current arm, keeping t0, rate and generation, so marks stay put; one that - would bring the clock to the end of its range within a real hour is refused, but not one to the time it shows.""" + """Jump forward to virtual_time on the current arm, keeping t0, rate and generation, so marks stay put; a time + past the end of the range is refused, one in its last real hour isn't, and the clock stands at the end once + there.""" target = _parse_rfc3339(virtual_time) with self._lock: if not self._armed or self._t0 is None: @@ -265,8 +265,6 @@ def advance(self, virtual_time: str) -> dict: jump = (target - current).total_seconds() if jump < 0: raise ClockError(f"advance only moves forward: {virtual_time!r} is before the current {_iso(current)}") - if jump > 0 and _ends_within_an_hour(target, self._rate): - raise ClockError(_past_end(f"virtual_time {virtual_time!r} at rate {self._rate:g}")) self._ahead += jump self._lived += jump self._count += 1 diff --git a/src/agent_env/env/gateway/constants.py b/src/agent_env/env/gateway/constants.py index 115e40db6..4cc716039 100644 --- a/src/agent_env/env/gateway/constants.py +++ b/src/agent_env/env/gateway/constants.py @@ -268,7 +268,7 @@ def random_mcp_server_name() -> str: }, { "uri": EXT_CLOCK_URI, - "description": "Virtual clock (urn:agentenv:clock/v1): read the gateway's virtual time (wall-clock-derived, rate-scaled) via get_time; set_time/set_rate/advance/clear are the harness control path, each changing the clock's opaque version and, given wait_followers_s, answering 504 naming the followers that don't show it in time (set_rate keeps t0, as advance does, so time triggers keep their marks; rate 0 freezes the clock); the clock holds 1677-09-21T00:12:44Z to 2262-04-11T23:47:16Z, the times 64 bits of nanoseconds since 1970 hold: set_time and advance refuse a time outside it, a write that would bring the clock to its end within a real hour is refused, and a clock that runs to its end stands there, at rate 0; declare_follower adds a follower after the gateway started (an agent the run deploys), with the read token its watches carry, and retire_follower removes one so writes stop waiting for it (an agent the run tears down); a follower follows it through watch, a long poll naming the version it shows and held up to hold_s; state's followers block is diagnostic, not part of the contract.", + "description": "Virtual clock (urn:agentenv:clock/v1): read the gateway's virtual time (wall-clock-derived, rate-scaled) via get_time; set_time/set_rate/advance/clear are the harness control path, each changing the clock's opaque version and, given wait_followers_s, answering 504 naming the followers that don't show it in time (set_rate keeps t0, as advance does, so time triggers keep their marks; rate 0 freezes the clock); the clock holds 1677-09-21T00:12:44Z to 2262-04-11T23:47:16Z, the times 64 bits of nanoseconds since 1970 hold: set_time and advance refuse a time outside it, set_time also one from which its rate would reach the end within a real hour, and a clock that runs to its end stands there, at rate 0; declare_follower adds a follower after the gateway started (an agent the run deploys), with the read token its watches carry, and retire_follower removes one so writes stop waiting for it (an agent the run tears down); a follower follows it through watch, a long poll naming the version it shows and held up to hold_s; state's followers block is diagnostic, not part of the contract.", "params": {"endpoint": "/clock/time", "methods": { "get_time": {"method": "GET", "endpoint": "/clock/time"}, "set_time": {"method": "PUT", "endpoint": "/clock/set-time", "request": {"type": "object", "properties": {"virtual_time": {"type": "string"}, "virtual_seconds_per_real_second": {"type": "number"}, "time_zone": {"type": "string"}, **_WAIT_FOLLOWERS}, "required": ["virtual_time"]}}, diff --git a/src/agent_env/task_step/task_steps/sync_env_clock.py b/src/agent_env/task_step/task_steps/sync_env_clock.py index 90782215e..f9537d2f2 100644 --- a/src/agent_env/task_step/task_steps/sync_env_clock.py +++ b/src/agent_env/task_step/task_steps/sync_env_clock.py @@ -124,7 +124,7 @@ def config_problems(self) -> list[str]: try: check_arm(self.armed_virtual_time, self.virtual_seconds_per_real_second, what=shown) except ClockError as e: - return [f"step {self.id!r}: {e}"] + return [str(e)] return [] def to_dict(self) -> dict: diff --git a/tst/unit/env/gateway/clock_range_test.py b/tst/unit/env/gateway/clock_range_test.py index 61c9bf6c2..5b3d88840 100644 --- a/tst/unit/env/gateway/clock_range_test.py +++ b/tst/unit/env/gateway/clock_range_test.py @@ -1,7 +1,8 @@ """The env clock's range, the times 64 bits of nanoseconds since 1970 hold, as Python and the computers that follow the clock keep time: the gateway arms and runs anywhere in it, before 1970 too and a day per second at today's dates, and -refuses a time outside it, however it's spelled, or a write that would bring the clock to the end within a real hour, up -front, naming the range. A clock that runs to the end anyway, on a gateway that outlives it, stands there.""" +refuses a time outside it, however it's spelled, or arming the clock where it would run to the end within a real hour, +up front, naming the range. A clock that runs to the end anyway, on a gateway that outlives it or sped up in its last +hour, stands there.""" from __future__ import annotations import re @@ -54,43 +55,52 @@ def test_a_string_that_isnt_a_time_is_refused_as_one(virtual_time): Clock(now_fn=FakeNow()).set_time(virtual_time, rate=0) -def test_arming_advancing_or_speeding_a_clock_that_would_pass_the_end_within_a_real_hour_names_it(): - clock = Clock(now_fn=FakeNow()) - with _refused(f"virtual_time '2262-04-11T23:00:00Z' at rate 1 {END}"): - clock.set_time("2262-04-11T23:00:00Z") - - clock.set_time("2262-04-01T00:00:00Z") +def test_arming_a_clock_that_would_pass_the_end_within_a_real_hour_names_it(): with _refused(f"virtual_time '2262-04-11T23:00:00Z' at rate 1 {END}"): - clock.advance("2262-04-11T23:00:00Z") - with _refused(f"rate 3600 {END}"): - clock.set_rate(3600) - assert clock.read()["virtual_time"] == "2262-04-01T00:00:00Z" + Clock(now_fn=FakeNow()).set_time("2262-04-11T23:00:00Z") def test_however_slow_a_clock_runs_from_the_end_it_would_pass_it(): with _refused(f"virtual_time '2262-04-11T23:47:16Z' at rate 1e-10 {END}"): Clock(now_fn=FakeNow()).set_time("2262-04-11T23:47:16Z", rate=1e-10) - clock = Clock(now_fn=FakeNow()) - clock.set_time("2262-04-11T23:47:16Z", rate=0) - with _refused(f"rate 1e-10 {END}"): - clock.set_rate(1e-10) -def test_in_its_last_real_hour_a_clock_takes_every_write_that_doesnt_bring_the_end_closer(): - """An advance to the time it shows (as a settle does to set a due event going) and a rate no faster go through; a - jump or a faster rate doesn't.""" +def test_a_clock_frozen_in_its_last_real_hour_starts_again_and_runs_to_the_end(): + """As always_on runs one: frozen between turns, advanced while frozen to a due event, then run at the task's rate + for the next turn.""" now = FakeNow() clock = Clock(now_fn=now) - clock.set_time("2262-04-11T22:00:00Z") - now.tick(50 * 60) + clock.set_time("2262-04-11T22:40:00Z") + now.tick(60) + clock.set_rate(0) + clock.advance("2262-04-11T23:00:00Z") - assert clock.advance("2262-04-11T22:50:00Z")["virtual_time"] == "2262-04-11T22:50:00Z" assert clock.set_rate(1)["virtual_seconds_per_real_second"] == 1 - with _refused(f"virtual_time '2262-04-11T22:50:01Z' at rate 1 {END}"): - clock.advance("2262-04-11T22:50:01Z") - with _refused(f"rate 2 {END}"): - clock.set_rate(2) - assert clock.set_rate(0.5)["virtual_seconds_per_real_second"] == 0.5 + now.tick(40 * 60) + assert clock.read() == {"virtual_time": "2262-04-11T23:40:00Z"} + now.tick(10 * 60) + state = clock.state() + assert (state["virtual_time"], state["virtual_seconds_per_real_second"]) == ("2262-04-11T23:47:16Z", 0.0) + + +def test_in_its_last_real_hour_a_running_clock_takes_any_advance_or_rate_and_stands_at_the_end(): + now = FakeNow() + clock = Clock(now_fn=now) + clock.set_time("2262-04-11T22:47:16Z") + + assert clock.advance("2262-04-11T23:30:00Z")["virtual_time"] == "2262-04-11T23:30:00Z" + assert clock.set_rate(86400)["virtual_seconds_per_real_second"] == 86400 + now.tick(1) + assert clock.now() == LATEST + with _refused(f"virtual_time '2262-04-11T23:47:17Z' is outside {RANGE}"): + clock.advance("2262-04-11T23:47:17Z") + + +def test_a_clock_armed_frozen_at_the_end_takes_a_rate_as_one_that_ran_there_does(): + clock = Clock(now_fn=FakeNow()) + clock.set_time("2262-04-11T23:47:16Z", rate=0) + state = clock.set_rate(1e-10) + assert (state["virtual_time"], state["virtual_seconds_per_real_second"]) == ("2262-04-11T23:47:16Z", 0.0) def test_a_clock_that_outlives_its_range_stands_at_the_end_and_can_still_be_frozen_or_set_back(): diff --git a/tst/unit/task_step/sync_env_clock_test.py b/tst/unit/task_step/sync_env_clock_test.py index c7f8565f1..01ce8a924 100644 --- a/tst/unit/task_step/sync_env_clock_test.py +++ b/tst/unit/task_step/sync_env_clock_test.py @@ -6,7 +6,10 @@ import pytest from agent_env.env.env import DeployedEnv, DeployedGatewayEnv, DeployedSandboxEnv +from agent_env.env.gateway.clock import outside_range from agent_env.env.gateway.constants import EXT_CLOCK_URI, WELL_KNOWN_PATH +from agent_env.task import Task +from agent_env.task.lint import lint from agent_env.task_step.context import StepContextError, TaskStepContext from agent_env.task_step.task_steps import sync_env_clock as mod from agent_env.task_step.task_steps.sync_env_clock import SyncEnvClockTaskStep, resolve_virtual_time @@ -361,7 +364,13 @@ def test_a_wall_time_whose_instant_no_date_holds_is_refused_naming_the_clocks_ra ]) def test_a_time_or_rate_the_gateway_would_refuse_is_a_problem_before_anything_deploys(kwargs, problem): problems = SyncEnvClockTaskStep(id="sync", version=1, env_id="e1", depends_on=[], **kwargs).config_problems() - assert len(problems) == 1 and problems[0].startswith(f"step 'sync': {problem}"), problems + assert len(problems) == 1 and problems[0].startswith(problem), problems + + +def test_lint_names_the_step_of_a_time_the_gateway_would_refuse_once(): + step = SyncEnvClockTaskStep(id="clock", version=1, env_id="e1", virtual_time="3026-01-01T00:00:00Z", depends_on=[]) + found = [finding.text for finding in lint(Task(id="t", version=1, steps=[step])) if finding.rule == "step-config"] + assert found == ["step 'clock': " + outside_range("virtual_time '3026-01-01T00:00:00Z'")] def test_a_time_the_gateway_arms_at_is_no_problem(): From 9dc3a3c7ed5bfcf6ce391b3f943b25d8f9fe5171 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 23 Nov 2026 19:18:20 -0800 Subject: [PATCH 08/16] fix(clock): periodic timers stop at the end of the range when the clock gets there, and session_time stands there too A clock running into the end stood still for reads but not for a periodic timer the kernel held, which ticked on until the follower wrote the standing page: libfaketime's helper now wakes when the clock reaches the end and stops them there, and a timer armed past it gets no interval. agentenv_protocol's session_time, which stamps an agent's trajectory, stops at the end as well. Co-Authored-By: Claude Opus 5.5 --- .../src/agentenv_protocol/computer/clock.py | 5 ++- .../tests/test_a2a_agent_clock.py | 1 + .../faketime_clock/agentenv_clock_waits.c | 33 ++++++++++++++++++- tst/clock/harness.py | 18 ++++++++-- tst/clock/programs/tfdend.py | 28 ++++++++++++++++ tst/clock/range_test.py | 4 +++ 6 files changed, 84 insertions(+), 5 deletions(-) create mode 100644 tst/clock/programs/tfdend.py diff --git a/packages/agentenv-protocol/src/agentenv_protocol/computer/clock.py b/packages/agentenv-protocol/src/agentenv_protocol/computer/clock.py index d87233c9f..8b69d06b3 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/computer/clock.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/computer/clock.py @@ -27,6 +27,9 @@ #: The follower's clock file, replaced whole at each write: ``@ x ^`` while the clock is #: armed (the universe at real time ``anchor``, running at ``rate``), ``+0 x1`` on real time. CLOCK_FILE = "/run/agentenv-clock/clock" +#: The end of the env clock's range, 2262-04-11T23:47:16Z in epoch seconds: a clock that runs to it stands there, as the +#: gateway's and the computers' do, before the follower writes it standing. +END = 9223372036.0 #: What a disk form's guest has, made from the computer's container image: core's root channel reaches its launcher, #: not the guest, so it can't configure a follower there, and a disk computer stays on real time for now. DISK_GUEST = "/etc/agentenv/vm/image.env" @@ -53,7 +56,7 @@ def session_time() -> float: if not spec[0].startswith("@"): return now universe, rate, anchor = float(spec[0][1:]), float(spec[1][1:]), float(spec[2][1:]) - return universe if rate == 0 or now <= anchor else universe + (now - anchor) * rate + return universe if rate == 0 or now <= anchor else min(universe + (now - anchor) * rate, END) def session_zone() -> str: diff --git a/packages/agentenv-protocol/tests/test_a2a_agent_clock.py b/packages/agentenv-protocol/tests/test_a2a_agent_clock.py index 492800497..0231bc632 100644 --- a/packages/agentenv-protocol/tests/test_a2a_agent_clock.py +++ b/packages/agentenv-protocol/tests/test_a2a_agent_clock.py @@ -198,6 +198,7 @@ def test_a_server_starting_without_a_saved_zone_keeps_its_own(image, monkeypatch ("@1748768400.000000000 x2 ^{past}\n", 1748768400.0 + 20), ("@1748768400.000000000 x1 ^{future}\n", 1748768400.0), ("@1748768400.000000000 x0 ^{past}\n", 1748768400.0), + ("@9223372030.000000000 x1 ^{past}\n", 9223372036.0), ]) def test_the_session_time_is_the_universe_while_the_clock_is_armed_and_real_time_otherwise( tmp_path, monkeypatch, spec, expected): diff --git a/src/agent_env/utils/faketime_clock/agentenv_clock_waits.c b/src/agent_env/utils/faketime_clock/agentenv_clock_waits.c index b9120df4c..fe5ffeb83 100644 --- a/src/agent_env/utils/faketime_clock/agentenv_clock_waits.c +++ b/src/agent_env/utils/faketime_clock/agentenv_clock_waits.c @@ -313,7 +313,7 @@ static int ft_timer_arm(struct ft_timer *t, const struct ft_clock_page *s, bool { real.it_value = ft_ts(at); if (real.it_value.tv_sec == 0 && real.it_value.tv_nsec == 0) real.it_value.tv_nsec = 1; - if (t->interval > 0 && rate > 0) + if (t->interval > 0 && rate > 0 && ft_page_rt(s, ft_real_rt()) < FT_END) { int64_t iv = (int64_t) ((double) t->interval / rate); real.it_interval = ft_ts(iv < 1 ? 1 : iv); @@ -425,16 +425,36 @@ static bool ft_on_change(const struct ft_clock_page *s, bool rebroadcast) return pending; } +/* the clock reached the end of its range on page ``s`` at real realtime ``end`` before any page said so: its periodic + timers stop there, as its reads do, rather than tick on until the follower writes the page that stands at the end. */ +static void ft_at_end(const struct ft_clock_page *s, int64_t end) +{ + struct ft_clock_page stood = *s; + sigset_t old; + stood.universe_ns = FT_END; + stood.anchor_ns = end; + stood.rate = 0; + ft_tab_lock(&old); + for (int i = 0; i < ft_timers_top; i++) + { + struct ft_timer *t = &ft_timers[i]; + if (t->kind != 0 && t->tracked && t->interval > 0) ft_timer_arm(t, &stood, false); + } + ft_tab_unlock(&old); +} + static void *ft_helper_main(void *arg) { struct ft_clock_page s; uint64_t gen = UINT64_MAX; /* the first pass catches a change made while it started */ + uint64_t ended = UINT64_MAX; /* the generation whose run to the end of the range ft_at_end has handled */ int backoff_ms = 0; (void) arg; for (;;) { uint32_t seq32 = ft_seq32(); bool pending = false; + int64_t end = FT_NEVER; if (ft_snap(&s)) { if (s.generation != gen) @@ -448,12 +468,23 @@ static void *ft_helper_main(void *arg) pending = ft_on_change(&s, true); backoff_ms = pending ? (backoff_ms < 64 ? backoff_ms * 2 : 100) : 0; } + if (s.armed && s.rate > 0 && s.universe_ns < FT_END && s.generation != ended) end = ft_real_of(&s, FT_END); } if (backoff_ms > 0) { struct timespec ts = {0, (long) backoff_ms * 1000000L}; ft_raw_syscall6(SYS_futex, (long) &ft_page->seq, FUTEX_WAIT, (long) seq32, (long) &ts, 0, 0); } + else if (end != FT_NEVER) + { + struct timespec ts = ft_ts(end); + if (ft_raw_syscall6(SYS_futex, (long) &ft_page->seq, FUTEX_WAIT_BITSET | FUTEX_CLOCK_REALTIME, (long) seq32, + (long) &ts, 0, FUTEX_BITSET_MATCH_ANY) == -1 && errno == ETIMEDOUT && ft_seq32() == seq32) + { + ft_at_end(&s, end); + ended = s.generation; + } + } else ft_raw_syscall6(SYS_futex, (long) &ft_page->seq, FUTEX_WAIT, (long) seq32, 0, 0, 0); } diff --git a/tst/clock/harness.py b/tst/clock/harness.py index e4bc5fcc0..6182b94ad 100644 --- a/tst/clock/harness.py +++ b/tst/clock/harness.py @@ -331,6 +331,18 @@ def frozen_timers(): return {**frozen, **json.loads(resumed)} +def end_periodic(): + """A periodic timer ticking into the end of the clock's range, with no page written after the clock was set running + toward it: it stops at the end, as reads do (tfdend.py).""" + preload() + fresh_page() + set_clock(9223372034.5, 1) + r = subprocess.run(user_cmd(["python3", f"{PROGRAMS}/tfdend.py"]), capture_output=True, text=True, cwd="/tmp", + timeout=30) + preload(None) + return json.loads(r.stdout) + + def _with_page_changes(p) -> int: """+10 min every 0.5 s while ``p`` runs; how many.""" n = 0 @@ -756,9 +768,9 @@ def probe(): return {"futex_waitv_errno": ctypes.get_errno() if r == -1 else 0} -GATES = {f.__name__: f for f in (waits, ratechange, jumps, cancel, timerfds, frozen_timers, condstress, semstress, - stall, torn, deadwriter, end, end_waits, span, marker, identity, envrace, forklock, - chromium, tls, probe)} +GATES = {f.__name__: f for f in (waits, ratechange, jumps, cancel, timerfds, frozen_timers, end_periodic, condstress, + semstress, stall, torn, deadwriter, end, end_waits, span, marker, identity, envrace, + forklock, chromium, tls, probe)} if __name__ == "__main__": gate = GATES[sys.argv[1]] diff --git a/tst/clock/programs/tfdend.py b/tst/clock/programs/tfdend.py new file mode 100644 index 000000000..4a1ceeafd --- /dev/null +++ b/tst/clock/programs/tfdend.py @@ -0,0 +1,28 @@ +"""A periodic realtime timerfd armed through libc for a clock time a second before the end of the clock's range, every +0.3 s, on a clock running into the end with no page written after: read 3 s later, it has expired at the four ticks +before the end and none after, as reads stand at the end. Prints its expirations and the time read then (ns).""" +import ctypes +import json +import os +import select +import time + +libc = ctypes.CDLL(None, use_errno=True) + + +class Timespec(ctypes.Structure): + _fields_ = [("tv_sec", ctypes.c_long), ("tv_nsec", ctypes.c_long)] + + +class Itimerspec(ctypes.Structure): + _fields_ = [("it_interval", Timespec), ("it_value", Timespec)] + + +CLOCK_REALTIME, TFD_TIMER_ABSTIME, END = 0, 1, 9223372036 + +fd = libc.timerfd_create(CLOCK_REALTIME, 0) +every = Itimerspec(Timespec(0, 300_000_000), Timespec(END - 1, 0)) +assert libc.timerfd_settime(fd, TFD_TIMER_ABSTIME, ctypes.byref(every), None) == 0 +time.sleep(3) +count = int.from_bytes(os.read(fd, 8), "little") if select.select([fd], [], [], 0)[0] else 0 +print(json.dumps({"expirations": count, "now": time.time_ns()})) diff --git a/tst/clock/range_test.py b/tst/clock/range_test.py index c6dc3d814..9a0324d69 100644 --- a/tst/clock/range_test.py +++ b/tst/clock/range_test.py @@ -126,3 +126,7 @@ def test_a_frozen_clocks_timers_expire_once_tell_all_the_time_left_and_tick_agai r = gate("frozen_timers") assert r["periodic_count"] == 1 and abs(r["far_left_s"] - (9223368436 + 9223286400)) < 1, r assert 2 <= r["resumed_count"] <= 3, r + + +def test_a_periodic_timer_ticking_into_the_end_stops_there_with_no_page_written(gate): + assert gate("end_periodic") == {"expirations": 4, "now": 9223372036000000000} From 0d6ebf9089d530f98a2321cfe6573785c7c77bcc Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 23 Nov 2026 19:36:25 -0800 Subject: [PATCH 09/16] test(clock): the end-periodic gate reads its timer as it ticks, as a program's loop does Co-Authored-By: Claude Opus 5.5 --- tst/clock/programs/tfdend.py | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/tst/clock/programs/tfdend.py b/tst/clock/programs/tfdend.py index 4a1ceeafd..e8134bbd3 100644 --- a/tst/clock/programs/tfdend.py +++ b/tst/clock/programs/tfdend.py @@ -1,6 +1,8 @@ """A periodic realtime timerfd armed through libc for a clock time a second before the end of the clock's range, every -0.3 s, on a clock running into the end with no page written after: read 3 s later, it has expired at the four ticks -before the end and none after, as reads stand at the end. Prints its expirations and the time read then (ns).""" +0.3 s, on a clock running into the end with no page written after: read as it ticks for 3 s, as a program's loop reads +it (a re-arm, at the end as at any clock change, drops what isn't read yet, as the kernel's timerfd_settime does), it +has expired at the four ticks before the end and none after, as reads stand at the end. Prints its expirations and the +time read then (ns).""" import ctypes import json import os @@ -23,6 +25,8 @@ class Itimerspec(ctypes.Structure): fd = libc.timerfd_create(CLOCK_REALTIME, 0) every = Itimerspec(Timespec(0, 300_000_000), Timespec(END - 1, 0)) assert libc.timerfd_settime(fd, TFD_TIMER_ABSTIME, ctypes.byref(every), None) == 0 -time.sleep(3) -count = int.from_bytes(os.read(fd, 8), "little") if select.select([fd], [], [], 0)[0] else 0 +deadline, count = time.monotonic() + 3, 0 +while (left := deadline - time.monotonic()) > 0: + if select.select([fd], [], [], left)[0]: + count += int.from_bytes(os.read(fd, 8), "little") print(json.dumps({"expirations": count, "now": time.time_ns()})) From d15240652c1a0427e3b0f02277030486134cad1a Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Mon, 23 Nov 2026 19:53:31 -0800 Subject: [PATCH 10/16] docs(clock): say why stopping a periodic timer at the end drops its unread expirations Co-Authored-By: Claude Opus 5.5 --- src/agent_env/utils/faketime_clock/agentenv_clock_waits.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/agent_env/utils/faketime_clock/agentenv_clock_waits.c b/src/agent_env/utils/faketime_clock/agentenv_clock_waits.c index fe5ffeb83..83526c683 100644 --- a/src/agent_env/utils/faketime_clock/agentenv_clock_waits.c +++ b/src/agent_env/utils/faketime_clock/agentenv_clock_waits.c @@ -426,7 +426,10 @@ static bool ft_on_change(const struct ft_clock_page *s, bool rebroadcast) } /* the clock reached the end of its range on page ``s`` at real realtime ``end`` before any page said so: its periodic - timers stop there, as its reads do, rather than tick on until the follower writes the page that stands at the end. */ + timers stop there, as its reads do, rather than tick on until the follower writes the page that stands at the end. + Stopping one drops the expirations a timerfd holds unread, as every clock change's re-arm does and as the follower's + page would a moment later: timerfd_settime zeroes them, and nothing restores them without racing the program's own + reads. */ static void ft_at_end(const struct ft_clock_page *s, int64_t end) { struct ft_clock_page stood = *s; From 811274d3219a799237a2d9e8154cdf4b6e68f9f3 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Tue, 24 Nov 2026 08:25:01 -0800 Subject: [PATCH 11/16] refactor(clock): a follower that holds only a range of times declares it, and the gateway keeps to it The gateway no longer limits every clock to 1677..2262: an MCP-only env's clock reaches what a datetime holds, as before. A computer's card and a clock-following agent's declare clock/v1's range (what 64 bits of nanoseconds since 1970 hold, as their clock page and Python keep time); core passes a computer's to the gateway (CLOCK_FOLLOWER_RANGES) and an agent brings its own to declare_follower. While the clock has such a follower, set_time and advance refuse a time outside its range, naming it, set_time one it would run past the end of from within a real hour, and declare_follower one the clock is outside now (an agent then can't follow: skipped, or the step fails under require_agent_clock). A follower that declares none leaves the clock as it was. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- .../agentenv_protocol/a2a_agent/framework.py | 4 +- .../src/agentenv_protocol/computer/card.py | 6 +- .../src/agentenv_protocol/computer/clock.py | 8 +- .../tests/test_a2a_agent_clock.py | 1 + .../tests/test_computer_clock.py | 1 + src/agent_env/a2a_agent/clock.py | 20 +- src/agent_env/env/envs/_multi_computers.py | 3 +- .../env/envs/computer/utils/clock.py | 8 + src/agent_env/env/gateway/__init__.py | 4 +- src/agent_env/env/gateway/clock.py | 136 ++++++------ src/agent_env/env/gateway/clock_followers.py | 33 ++- src/agent_env/env/gateway/constants.py | 7 +- src/agent_env/env/gateway/entrypoint.py | 20 +- src/agent_env/env/gateway/gateway.py | 13 +- src/agent_env/env/gateway/get_time.py | 6 +- .../env_providers/env_gateway_provider.py | 11 +- .../task_step/task_steps/sync_env_clock.py | 10 +- tst/env/gateway/clock_test.py | 26 +-- .../env/envs/test_computer_clock_follower.py | 19 +- tst/unit/env/envs/test_multi_env_computers.py | 12 ++ tst/unit/env/gateway/clock_range_test.py | 203 ++++++++---------- tst/unit/env/gateway/get_time_test.py | 27 ++- .../env_gateway_provider_test.py | 18 ++ tst/unit/task_step/agent_clock_test.py | 59 +++++ tst/unit/task_step/sync_env_clock_test.py | 23 +- 26 files changed, 420 insertions(+), 260 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 9da4ced94..9b1b2fa3b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -149,7 +149,7 @@ and deserialized through a registry. | Package | Contents | |---|---| -| `env/` | `Env` base class: a subclass declares `type`, implements `from_dict` and `async deploy(...) -> DeployedEnv`, and may override `reset`, `close` and `load_file_artifact_universe`; teardown closes each env a run deployed before terminating its sandboxes by id. Built-ins in `env/envs/`: `MCPServerEnv` (`mcp_server`), `MultiEnv` (`multi`, MCP servers plus websites and computers; its website browser is the one its `browser_envs` names, none for `[]`, else the run's when it has websites: an MCP server env such as `playwright-mcp` runs among the gateway's MCP servers, and a browser computer such as `chromium` on a sandbox of its own as one more computer child, sized by its `child_envs` entry, its tools under its name and `_`, routing the multi env's synthetic sites unless that entry's `site_routing` says, its network its own env's, as any computer child's; a website env deployed alone refuses a browser computer as the run's browser), `ServiceDBEnv` (`service_db`, PostgreSQL), `WebsiteEnv` (`website`, one site: a server image, `backend_image` in its env.toml, serving the pages and API, ready when its card's `website/v1` `ready` answers a `WebsiteReadiness` that says so, as `agentenv_protocol.website` (`website_readiness`, `env_readiness`) defines a website env's health for the deploy and `DeployedEnv.readiness()` alike, or, for a card without `ready`, when its `health` path answers 200, which is deprecated; its env.toml's `ready_timeout_s`, how long it may take from its server's container starting to ready, is that container's health check `start_period` and what the deploy waits, or its card's `ready` timeout if longer, and its `shm_mb` is the container's `shm_size`, each left to the gateway and Docker without them; the gateway container's `env/gateway/constants.py` mirrors the URI and op, a test keeping them equal; a separate frontend image is deprecated, warned of at put and optional in a bundle, and a stored `backend_docker_image_artifact` reads as the server image; a live one, `live = true`, is a real site whose server serves none of its pages, its `live`, `domains` and `allow_hosts` read at put from its server's `@website(...)` (`utils/card_naming.py` `WebsiteSource`) unless given, its `settings`' secrets only as references the gateway resolves as it writes the site's container (`WEBSITE_SETTINGS_ENV`); the gateway gives it no site route, a computer's site table leaves it out, a computer whose network is an allowlist is let reach its names (`MultiEnv.live_hosts`), a browser alone's forward port takes them straight to the real site (`site_proxy.py` `direct`), as the browser base's stand-in proxy takes any host, refusing nothing, each proxy logging each such connection as a JSON line, and a run that deploys one is marked live, `reproducible: false`), `GatewayEnv` (`gateway_server`), `ComputerDriverEnv` (`computer_driver`, `env/envs/computer/driver_env.py`: a computer driver's files and what its class declares for each platform it supports, read at put in a process of its own, `agentenv_protocol.computer._declare`, where the driver's own dependencies needn't be installed, with the `port` it serves on and its install by OS, `[install.]`, or for one distribution `[install."/"]`, which replaces its OS type's there, as its `known_failures` do (`env/envs/computer/utils/install.py`): files, apt `packages` with extra `sources`, a `python` requirements file for a venv, `downloads` by URL and sha256, `run` scripts, the services the base's init runs, and `ports`; it deploys only as a computer env's driver), `ComputerEnv` (`computer`, in `env/envs/computer/`: a base computer and a driver, matched at put by gate 1 before anything is stored, then composed by `composer.py` into an image for each form and arch on a builder of the put's sandbox provider, by default the env's (`utils/builder.py`; `--sandbox` on `env build`): this machine's Docker for `local`, else a VM of the provider, which fetches the put's stored files by signed URL, takes the rest inline and pushes to the image store itself, so it builds only with stores a remote VM reaches; each arch goes to the first link that runs it natively, else one that emulates it (a VM registers QEMU; `--no-emulate` leaves it `skipped` instead, for a later put), and its pair records the provider that built it (`builder`); a run or register composes only the computer envs its tasks deploy (`materialize._composed_envs`: each env a task's steps name, and each env those hold but a computer env's own apps and driver, which run inside it) and those it pulls in from an installed bundle, whose one write every bundle shares, every one for a plan with no tasks, any other composing at its first deploy; one that reuses a computer env composes what it has left (`pending`), a run, and a register given a `--sandbox`, only the forms its sandbox's deploys boot (`booted_forms`: on each link, the first form it boots natively, by the deploy's own rule, `boot.first_native`; a compose of a disk adds its container), and a deploy composes first what it boots that no compose started, and a container it runs natively that was built but not probed, as one whose probe a setting that didn't resolve stopped, booting it only once ready (`ComputerEnv.compose_unstarted`); tagged `agentenv-computers:` in the image store by a key of the image's Dockerfile, build context and lock so any env with the same inputs reuses it; every layer's packages, requirements and downloads are resolved at put in a container of the base for each arch (`utils/packages.py`, `utils/resolve_in_base.py`), stored in the object store by sha256 under `agentenv-packages/`, and listed in a lock stored by a digest of its inputs, which any env with the same inputs reuses, and builds install only the lock's files, every install step `RUN --network=none`; each pair's status goes into its metadata, `composed`, the arches built are written as its computer, a `computer` artifact over one index, and `agent-env env build` resumes what a put left; gate 3 (`utils/probing.py`) then boots each native build on the put's sandbox provider and probes it at `full`, making it `ready` or `failed`, and a build no provider runs natively stays `unverified`. Its deploy, through the `computer` env provider (`providers/env_providers/env_computer_provider.py`), boots its first `ready` build on a sandbox provider that runs its arch natively (`native_platforms()`), with no gateway in front and the driver's card as the env card, its `/dev/shm` the most its apps' Linux installs ask for (`shm_mb`, in MiB, which its composed computer and the deploy record keep; `--shm-size` on a container, `AGENTENV_SHM_MB` read by a Linux disk's init, passed only to a provider whose `SHARED_MEMORY` says it gives that much, else the sandbox's default, which the deploy logs), then checks its `display`; `deploy_env` `env_params` take a `form`, `computer_settings` (deploy-phase values of the base's settings; a secret one, here or on the env, only as a bare `secret:`/`env:` reference) and `driver_settings` (the driver's `ComputerSettings`, such as its default coordinate space); a `network` that allows nothing runs it on local Docker's internal network behind a relay (`providers/sandbox_providers/local_docker/relay/`); `reset` and `close` have the driver end its recordings first (`computer-recording/v1` `end_all`, each uploading what's left and its manifest under the grant it started with), and `reset` then boots a fresh container in its place (`reset_container`), keeping the computer's address but not an agent's MCP session to the old driver; its `load_file_artifact_universe` writes files under the session user's home through the driver's `data/add`, `Downloads` by default, each file's bytes through a read grant when the store's grants reach it and its network allows everything, else inline (`env/envs/computer/utils/inside.py`)), `ComputerAppEnv` (`computer_app`, `env/envs/computer/app_env.py`: an app on a computer, a `ComputerAppEnvironment` class its env.toml's `module` names, read at put by the same `_declare`, which declares each OS with its own decorator (`@linux(...)`, or `@install(os_type, spec)` for any OS type; `@linux(distribution=...)` or `@install("/", spec)` for one distribution, which replaces its OS type's there) holding its install, its launch and, optionally, a skill and settings and build settings that add to the class's there, and install steps and ready checks for every OS or those their `os=` names; everything that reads its settings, launch or steps asks for the computer's OS type; deployed alone it is a one-app computer env, a `ComputerEnv` of the computer and driver its env.toml names, the composer installing it under `/opt/agentenv/apps//` with its services as supervisord programs beside its own server (`agentenv_protocol.computer.serve_app`, in a venv with the protocol's `app` extra, on `.agentenv/server.sock` in its folder), which adds its launcher, launches a `boot` app once per boot and says through `computer-app/v1` whether it's ready, as the driver's `computer-ready` asks, its card named after it, and `env_params` `app_settings` handing it values of its `Settings` in `AGENTENV_APP_SETTINGS`, a secret one only as a bare reference, over its env.toml's `[settings]` and a computer env's `settings` beside it in `apps`, each by top-level field (`params.app_settings`; checked at put, a required one left to the deploy; the deploy record keeps the merged values as `app_settings`, secrets withheld); its env.toml's `build_settings`, values of its `BuildSettings` checked at put, are written to `.agentenv/build_settings.json` in its folder, so they're part of the image's key, its install steps read them, and a deploy can't change them). An env type whose services take environment data defines `load_environment_artifact` and `load_environment_universe_artifact`; `load_artifact` refuses an environment artifact aimed at a type that doesn't, at save and before it loads. An env built on the protocol SDK can serve agents a skill (`@agent_skill`, `skill/v1`), which `add_skills` `env_ids` installs under its environment name (behind a gateway, each server's under that server's name); a skill with files beside its SKILL.md goes as a bundle stored once per content under `agentenv-env-skills/` in the object store. `env/gateway/gateway.py` is the env-side gateway server, container-only code. Its site route, `/website//`, never forwards a site's data plane or card (`/agentenv/…`, `/.well-known/agent-env.json`), which agentenv reaches through `/svc//`; a site with no frontend image is served by its server image there. A request from a computer's site proxy names its computer (`AgentEnv-Computer`, sent from the proxy's private upstream headers, a page's own copy and any `AgentEnv-Role` it sends dropped) and takes the role driving that computer now (the gateway's computers being those `COMPUTERS` names, a multi env's, with or without a control token): the last to make an input call to its tools, as the call starts, through `/mcp`, `/step` or a trigger action under its `as` (`Gateway._drive`); without one, or from a computer the gateway doesn't front, it is `default`, the role read once per request. `changes/v1` (`ChangeAttribution`) counts no write window for a call to a computer's tools, a trigger action's included, so a write the computer's browser made goes to its request and one another party made during the call to that party. Its CDP route, `/browser//cdp//` (`env/gateway/browser_proxy.py`), reaches the website browser behind the `/svc` child ``, found from that child's card (it, or an app among its children, offering `browser/v1` `cdp` with `/cdp/` in its `computer-app/v1` `agent_routes`): it relays the browser's discovery and WebSocket both ways, each leg pinged every 20 s, and every CDP address the browser hands out, in `json/version`, `json/list` and its `cdp` answer through `/svc//`, comes back at the gateway, everything before `/cdp//` becoming the address the caller reached the gateway at and `/browser/`, keeping the https or wss of an address the browser minted under an origin its caller named, as `browser_connect_cdp` names the agent's, since a tunnel that ends TLS, as Modal's, may send no `X-Forwarded-Proto`; each connection is a `browser_connection` trajectory event, without its token. Its clock (`env/gateway/clock.py`) has one opaque version, a per-boot id and a count, that every `set_time`, `advance` and `clear` changes; `set_rate` (`/clock/set-rate`) changes an armed clock's rate from its time at the write, keeping its `t0` and generation as `advance` does, so time triggers keep their marks. Every clock change goes through `Gateway._change_clock`, which wakes the triggers when the change kept the clock's generation, answers the held watches and waits for the followers. Its followers, the computers on it (`CLOCK_FOLLOWER_TOKENS`, each child whose card serves `clock/v1` `sync_time`, by its read token, its control token for now), long-poll `/clock/watch` naming the version they show, each watch held up to the card's `hold_s` (`env/gateway/clock_followers.py`), and a write given `wait_followers_s` waits for each, answering 504 naming those behind, but not for one that hasn't watched for longer than a hold and a reconnect (`ClockFollowers.QUIET_S`), which it names at once with when each last watched; a restarted gateway is unarmed. While its clock is armed it serves agents `get_time` (`env/gateway/get_time.py`), which answers in UTC and also in the universe's zone, the one `sync_env_clock`'s `timezone` armed it in, or in an IANA `time_zone` it's given; executors' working `hours` (`env/gateway/triggers.py`) take a fixed `utc_offset` or an IANA `time_zone`. | +| `env/` | `Env` base class: a subclass declares `type`, implements `from_dict` and `async deploy(...) -> DeployedEnv`, and may override `reset`, `close` and `load_file_artifact_universe`; teardown closes each env a run deployed before terminating its sandboxes by id. Built-ins in `env/envs/`: `MCPServerEnv` (`mcp_server`), `MultiEnv` (`multi`, MCP servers plus websites and computers; its website browser is the one its `browser_envs` names, none for `[]`, else the run's when it has websites: an MCP server env such as `playwright-mcp` runs among the gateway's MCP servers, and a browser computer such as `chromium` on a sandbox of its own as one more computer child, sized by its `child_envs` entry, its tools under its name and `_`, routing the multi env's synthetic sites unless that entry's `site_routing` says, its network its own env's, as any computer child's; a website env deployed alone refuses a browser computer as the run's browser), `ServiceDBEnv` (`service_db`, PostgreSQL), `WebsiteEnv` (`website`, one site: a server image, `backend_image` in its env.toml, serving the pages and API, ready when its card's `website/v1` `ready` answers a `WebsiteReadiness` that says so, as `agentenv_protocol.website` (`website_readiness`, `env_readiness`) defines a website env's health for the deploy and `DeployedEnv.readiness()` alike, or, for a card without `ready`, when its `health` path answers 200, which is deprecated; its env.toml's `ready_timeout_s`, how long it may take from its server's container starting to ready, is that container's health check `start_period` and what the deploy waits, or its card's `ready` timeout if longer, and its `shm_mb` is the container's `shm_size`, each left to the gateway and Docker without them; the gateway container's `env/gateway/constants.py` mirrors the URI and op, a test keeping them equal; a separate frontend image is deprecated, warned of at put and optional in a bundle, and a stored `backend_docker_image_artifact` reads as the server image; a live one, `live = true`, is a real site whose server serves none of its pages, its `live`, `domains` and `allow_hosts` read at put from its server's `@website(...)` (`utils/card_naming.py` `WebsiteSource`) unless given, its `settings`' secrets only as references the gateway resolves as it writes the site's container (`WEBSITE_SETTINGS_ENV`); the gateway gives it no site route, a computer's site table leaves it out, a computer whose network is an allowlist is let reach its names (`MultiEnv.live_hosts`), a browser alone's forward port takes them straight to the real site (`site_proxy.py` `direct`), as the browser base's stand-in proxy takes any host, refusing nothing, each proxy logging each such connection as a JSON line, and a run that deploys one is marked live, `reproducible: false`), `GatewayEnv` (`gateway_server`), `ComputerDriverEnv` (`computer_driver`, `env/envs/computer/driver_env.py`: a computer driver's files and what its class declares for each platform it supports, read at put in a process of its own, `agentenv_protocol.computer._declare`, where the driver's own dependencies needn't be installed, with the `port` it serves on and its install by OS, `[install.]`, or for one distribution `[install."/"]`, which replaces its OS type's there, as its `known_failures` do (`env/envs/computer/utils/install.py`): files, apt `packages` with extra `sources`, a `python` requirements file for a venv, `downloads` by URL and sha256, `run` scripts, the services the base's init runs, and `ports`; it deploys only as a computer env's driver), `ComputerEnv` (`computer`, in `env/envs/computer/`: a base computer and a driver, matched at put by gate 1 before anything is stored, then composed by `composer.py` into an image for each form and arch on a builder of the put's sandbox provider, by default the env's (`utils/builder.py`; `--sandbox` on `env build`): this machine's Docker for `local`, else a VM of the provider, which fetches the put's stored files by signed URL, takes the rest inline and pushes to the image store itself, so it builds only with stores a remote VM reaches; each arch goes to the first link that runs it natively, else one that emulates it (a VM registers QEMU; `--no-emulate` leaves it `skipped` instead, for a later put), and its pair records the provider that built it (`builder`); a run or register composes only the computer envs its tasks deploy (`materialize._composed_envs`: each env a task's steps name, and each env those hold but a computer env's own apps and driver, which run inside it) and those it pulls in from an installed bundle, whose one write every bundle shares, every one for a plan with no tasks, any other composing at its first deploy; one that reuses a computer env composes what it has left (`pending`), a run, and a register given a `--sandbox`, only the forms its sandbox's deploys boot (`booted_forms`: on each link, the first form it boots natively, by the deploy's own rule, `boot.first_native`; a compose of a disk adds its container), and a deploy composes first what it boots that no compose started, and a container it runs natively that was built but not probed, as one whose probe a setting that didn't resolve stopped, booting it only once ready (`ComputerEnv.compose_unstarted`); tagged `agentenv-computers:` in the image store by a key of the image's Dockerfile, build context and lock so any env with the same inputs reuses it; every layer's packages, requirements and downloads are resolved at put in a container of the base for each arch (`utils/packages.py`, `utils/resolve_in_base.py`), stored in the object store by sha256 under `agentenv-packages/`, and listed in a lock stored by a digest of its inputs, which any env with the same inputs reuses, and builds install only the lock's files, every install step `RUN --network=none`; each pair's status goes into its metadata, `composed`, the arches built are written as its computer, a `computer` artifact over one index, and `agent-env env build` resumes what a put left; gate 3 (`utils/probing.py`) then boots each native build on the put's sandbox provider and probes it at `full`, making it `ready` or `failed`, and a build no provider runs natively stays `unverified`. Its deploy, through the `computer` env provider (`providers/env_providers/env_computer_provider.py`), boots its first `ready` build on a sandbox provider that runs its arch natively (`native_platforms()`), with no gateway in front and the driver's card as the env card, its `/dev/shm` the most its apps' Linux installs ask for (`shm_mb`, in MiB, which its composed computer and the deploy record keep; `--shm-size` on a container, `AGENTENV_SHM_MB` read by a Linux disk's init, passed only to a provider whose `SHARED_MEMORY` says it gives that much, else the sandbox's default, which the deploy logs), then checks its `display`; `deploy_env` `env_params` take a `form`, `computer_settings` (deploy-phase values of the base's settings; a secret one, here or on the env, only as a bare `secret:`/`env:` reference) and `driver_settings` (the driver's `ComputerSettings`, such as its default coordinate space); a `network` that allows nothing runs it on local Docker's internal network behind a relay (`providers/sandbox_providers/local_docker/relay/`); `reset` and `close` have the driver end its recordings first (`computer-recording/v1` `end_all`, each uploading what's left and its manifest under the grant it started with), and `reset` then boots a fresh container in its place (`reset_container`), keeping the computer's address but not an agent's MCP session to the old driver; its `load_file_artifact_universe` writes files under the session user's home through the driver's `data/add`, `Downloads` by default, each file's bytes through a read grant when the store's grants reach it and its network allows everything, else inline (`env/envs/computer/utils/inside.py`)), `ComputerAppEnv` (`computer_app`, `env/envs/computer/app_env.py`: an app on a computer, a `ComputerAppEnvironment` class its env.toml's `module` names, read at put by the same `_declare`, which declares each OS with its own decorator (`@linux(...)`, or `@install(os_type, spec)` for any OS type; `@linux(distribution=...)` or `@install("/", spec)` for one distribution, which replaces its OS type's there) holding its install, its launch and, optionally, a skill and settings and build settings that add to the class's there, and install steps and ready checks for every OS or those their `os=` names; everything that reads its settings, launch or steps asks for the computer's OS type; deployed alone it is a one-app computer env, a `ComputerEnv` of the computer and driver its env.toml names, the composer installing it under `/opt/agentenv/apps//` with its services as supervisord programs beside its own server (`agentenv_protocol.computer.serve_app`, in a venv with the protocol's `app` extra, on `.agentenv/server.sock` in its folder), which adds its launcher, launches a `boot` app once per boot and says through `computer-app/v1` whether it's ready, as the driver's `computer-ready` asks, its card named after it, and `env_params` `app_settings` handing it values of its `Settings` in `AGENTENV_APP_SETTINGS`, a secret one only as a bare reference, over its env.toml's `[settings]` and a computer env's `settings` beside it in `apps`, each by top-level field (`params.app_settings`; checked at put, a required one left to the deploy; the deploy record keeps the merged values as `app_settings`, secrets withheld); its env.toml's `build_settings`, values of its `BuildSettings` checked at put, are written to `.agentenv/build_settings.json` in its folder, so they're part of the image's key, its install steps read them, and a deploy can't change them). An env type whose services take environment data defines `load_environment_artifact` and `load_environment_universe_artifact`; `load_artifact` refuses an environment artifact aimed at a type that doesn't, at save and before it loads. An env built on the protocol SDK can serve agents a skill (`@agent_skill`, `skill/v1`), which `add_skills` `env_ids` installs under its environment name (behind a gateway, each server's under that server's name); a skill with files beside its SKILL.md goes as a bundle stored once per content under `agentenv-env-skills/` in the object store. `env/gateway/gateway.py` is the env-side gateway server, container-only code. Its site route, `/website//`, never forwards a site's data plane or card (`/agentenv/…`, `/.well-known/agent-env.json`), which agentenv reaches through `/svc//`; a site with no frontend image is served by its server image there. A request from a computer's site proxy names its computer (`AgentEnv-Computer`, sent from the proxy's private upstream headers, a page's own copy and any `AgentEnv-Role` it sends dropped) and takes the role driving that computer now (the gateway's computers being those `COMPUTERS` names, a multi env's, with or without a control token): the last to make an input call to its tools, as the call starts, through `/mcp`, `/step` or a trigger action under its `as` (`Gateway._drive`); without one, or from a computer the gateway doesn't front, it is `default`, the role read once per request. `changes/v1` (`ChangeAttribution`) counts no write window for a call to a computer's tools, a trigger action's included, so a write the computer's browser made goes to its request and one another party made during the call to that party. Its CDP route, `/browser//cdp//` (`env/gateway/browser_proxy.py`), reaches the website browser behind the `/svc` child ``, found from that child's card (it, or an app among its children, offering `browser/v1` `cdp` with `/cdp/` in its `computer-app/v1` `agent_routes`): it relays the browser's discovery and WebSocket both ways, each leg pinged every 20 s, and every CDP address the browser hands out, in `json/version`, `json/list` and its `cdp` answer through `/svc//`, comes back at the gateway, everything before `/cdp//` becoming the address the caller reached the gateway at and `/browser/`, keeping the https or wss of an address the browser minted under an origin its caller named, as `browser_connect_cdp` names the agent's, since a tunnel that ends TLS, as Modal's, may send no `X-Forwarded-Proto`; each connection is a `browser_connection` trajectory event, without its token. Its clock (`env/gateway/clock.py`) keeps to the range of times each of its followers holds when that follower's card declares one (clock/v1's `range`; a computer's and a clock-following agent's is 1677-09-21T00:12:44Z to 2262-04-11T23:47:16Z, what 64 bits of nanoseconds since 1970 hold, as their clock page and Python keep time, core passing a computer's as `CLOCK_FOLLOWER_RANGES` and an agent bringing its own to `declare_follower`): `set_time` and `advance` refuse a time outside it, naming the follower, `set_time` one it would run past the end of from within a real hour, and `declare_follower` one the clock is outside now; a follower that declares none, or no follower, leaves the clock what a datetime holds. Its clock has one opaque version, a per-boot id and a count, that every `set_time`, `advance` and `clear` changes; `set_rate` (`/clock/set-rate`) changes an armed clock's rate from its time at the write, keeping its `t0` and generation as `advance` does, so time triggers keep their marks. Every clock change goes through `Gateway._change_clock`, which wakes the triggers when the change kept the clock's generation, answers the held watches and waits for the followers. Its followers, the computers on it (`CLOCK_FOLLOWER_TOKENS`, each child whose card serves `clock/v1` `sync_time`, by its read token, its control token for now), long-poll `/clock/watch` naming the version they show, each watch held up to the card's `hold_s` (`env/gateway/clock_followers.py`), and a write given `wait_followers_s` waits for each, answering 504 naming those behind, but not for one that hasn't watched for longer than a hold and a reconnect (`ClockFollowers.QUIET_S`), which it names at once with when each last watched; a restarted gateway is unarmed. While its clock is armed it serves agents `get_time` (`env/gateway/get_time.py`), which answers in UTC and also in the universe's zone, the one `sync_env_clock`'s `timezone` armed it in, or in an IANA `time_zone` it's given; executors' working `hours` (`env/gateway/triggers.py`) take a fixed `utc_offset` or an IANA `time_zone`. | | `artifact/` | Immutable versioned artifacts; every `put()` creates a new version. The document goes to the document store, binary payloads to the object store. Every artifact but an environment universe, whose `metadata` key holds its legacy metadata file ids, carries a `metadata` dict outside its versioned fields, changed by compare-and-swap (`merge_metadata`). Built-ins: `CliArtifact` (`cli`), `ComputerArtifact` (`computer`, a base computer: its architectures, OS, session user, settings and container form, whose image `put` reads from its registry into `metadata.validated_images`), `FileArtifact` (`file`), `FileArtifactUniverse` (`file_artifact_universe`), `DockerImageArtifact` (`docker_image`), `EnvironmentArtifact` (`environment`: its environment's files by path, stored as the one wrapped `file_artifact_ref` every environment artifact had when it has one file at its filename, else as `file_artifact_refs`; `get_file_artifacts()` reads either, and a load hands each file to the env's `data/add` with its path, which a pre-v1 load, taking one file, refuses), `EnvironmentUniverseArtifact` (`environment_universe`), `SkillArtifact` (`skill`); `[artifacts] type_aliases` maps another stored spelling of a type onto one of them. A `DockerImageArtifact` holds a tar.gz of its image, or, written by `put_ref` (`--image-ref` on `env mcp-server put` and `a2a-agent put`), only a registry reference with its tag pinned to a digest, which sandboxes pull, or a published image's tag with its `image_digest` and its build context, which sandboxes pull by the digest and build from the context when they can't (the infra images, and a bundle agent built from a shipped agent's sources, `Plan.published`), or, written by `put_context`, only its build context, which a VM sandbox builds before running it (`VmSandbox.load_docker_images`) and Modal builds before creating its container (`ModalSandboxProvider.prepare_image`, outside a fallback chain's deadline); anything else that runs images by name (a container on the local provider, a lone server on any provider but Modal) refuses such an image. A build context (`utils/docker/context.py`) is what `docker build` would send, `.dockerignore` applied, written so equal files give equal bytes and an equal `source_digest`. | | `task/`, `task_step/` | A `Task` holds its `TaskStep`s inline; `Task.run()` executes them as a DAG. Its `headline_verifiers`, step ids saved only when set, name the grades that are its reward: one is the reward, several a multi-reward over them, none a multi-reward over every grade; it refuses one that names no step of the task, or one named twice. `depends_on` (None means all prior steps) gates a step, independent steps run concurrently, `fail_task_on_error` makes a failure fatal or tolerated, `retry_config` rolls a failed span back through the step journal and re-dispatches it. `task/lint.py` is `agent-env task lint` (a bundle folder, a task file or a stored task): an error is what a task gets wrong before it runs (a field its step doesn't read, a step's own `config_problems`, a headline that grades nothing, an aggregate source no verifier writes) and refuses `agent-env run`, `bundle register`, `task create`, `task validate` and `eval run`, and the bundle plans `openenv`'s `build_app` and the trainers make (`run`, `register`, `build_app`, `prepare_bundle` and the trainers take `--skip-lint`/`skip_lint`, which lifts lint's own rules but not a step's `config_problems`, which refused a bundle before lint; `eval run`'s lifts every error, since it checked none before); a warning is what may be wrong (a step's `config_warnings`, a store entity read with no version, no verifier, several and no headline, a judge that runs in the solver's own agent, which training refuses) and is only printed, each kind once by a run (`task.lint.said`), an eval run's unpinned references as one count (`unpinned_summary`), every one by `task lint`. `aggregate_verifiers` names its sources by step id (`sources`, `gates`) and reads their named grades: `combine` `pooled` (the default) pools their rows, `weighted_mean` weighs their scores, equally unless `weights` gives every source one, and a failing gate scores it 0; a failed or missing source fails it, and its older `verifier_ids` pools legacy entries as it always has. Built-in steps live in `task_step/task_steps/` (`deploy_env`, `deploy_agent`, `prompt_agent`, the verifiers under `verifiers/`, among them `start_computer_recording` (its driver draws each input over the frames in its caller's colour, and a pointer per role where the frames lack one, unless `annotation_settings` says `is_enabled: false`; a driver whose card lists no `annotate` records it plain, with a warning, and the run's recording entry says `annotated`) and `end_computer_recording`, `start_browser_recording` and `end_browser_recording` (`browser-recording/v1`: one recording per context, a lease's or the default one's, with a video of the tab its agent is on, its context's log, the browser's network log as HAR and opt-in frames keyed to the action log, the contexts its agents make recorded with it, one universe per recording, anything missing failing the run), and more). Every built-in verifier is on the `VerifierTaskStep` base (`verifiers/verifier.py`): it implements `verify` and returns a `Verification`, and the base writes the step's named grade to `context.metadata["grades"][]` (score, `min_passing_score`, `passed`, `verifier_status` graded, skipped or failed, criteria rows, type, version, and `verifier_settings`, the values the run graded with, its overrides applied and named in `overridden`, with `scoring_rules`) beside the legacy `verifications` entries every reader still takes; an exception from `verify` or a `Verification` with an `error`, as a timed-out `run_container_unit_tests_verifier`, is a failed grade, and `rubrics_verifier` still writes its `-trajectory-mistakes` entry itself. On an env whose card serves computer-exec/v1 (a computer), `run_code` with `env_id` and `run_container_unit_tests_verifier` with `env_id` run inside it as its session user through the driver: files staged with `data/add` and read with `data/get`, commands run with `run`; `computer_exec` runs one command there through `run` (a program and its arguments, or a string through `sh -c`; in a multi env, the computer it names), recorded under `computer_exec` in the run's metadata, a non-zero exit or a timeout failing it unless `check` is off, or with `background` starts it and leaves it running, as an app launched for the agent, a program that isn't there exiting 127; with `scope: "system"` it runs as root instead, through the computer's sandbox (`RootChannel`, `docker exec -u 0`), in the session user's folder and `HOME`, its output capped in the computer, never with `background` and not on a computer booted from a disk; on a Windows computer, which has no `sh`, a string or `background` command is refused; on a multi env, `load_artifact` with `env_id` puts an environment artifact named after one of its computers, or after an app of one, into that computer, the computer's own as files at their paths under the session user's home; `env_outcome_verifier` hands a `verify` that takes an `env_url` keyword the env's address. A computer's framework-only routes (everything but MCP and the card) take the per-deploy control token its provider boots it with (`DeployedEnv.control_token`, `AGENTENV_CONTROL_TOKEN`), a multi env's computers the multi env's own, which its gateway passes on only on their `/svc` routes and its clock watch (`CONTROL_TOKEN_CHILDREN`); framework calls send `deployed.control_headers`, `Task.run` runs every step under `protocol_v1.authorized` with each deployed env's (a `verify` included), and a `run_code` script inside the computer gets `input["env"]["headers"]`. `teardown_run` and the `teardown_sandboxes` step share one core (`task/teardown.py` `tear_down`): the recordings the run left open end with fresh grants, each env still up closes (`Env.close`; a computer env ends any recording still open), what stayed open is registered from its namespace, then every sandbox is terminated by id. A run whose teardown leaves sandboxes up, stopped by a second signal or failing, keeps on its instance the context it ended with (`record_teardown`), and `agent-env run` and `task run --keep` name `agent-env task teardown --instance `, which tears down what that context still records up, a running one only with `--force`. `task/episode/` runs a task with some of its agents played from outside, as a training loop does (`EpisodeSpec`). | | `store/` | Four store ABCs with local and cloud implementations: `DocumentStore` (SQLite, MongoDB, DynamoDB, Firestore with MongoDB compatibility), `ObjectStore` (filesystem, S3, Cloud Storage), `ImageStore` (local OCI registry, ECR), `SecretStore` (env vars or file, AWS Secrets Manager, Google Cloud Secret Manager). `VersionedEntityStore` implements the shared versioned get/put logic, `QueryBuilder` is the immutable chained query API, `store/base.py` holds the error types. `store/routing.py` is the local namespaces, `@local` and `@hf` (`is_local_id`), each with a documents file of its own: while the CLI or a `build_app` server runs, a local id and what a local task's run records go to local stores beside the configured ones, and that run's writes to the configured stores are refused. A new backend must pass the conformance kits in `tst/store/`. | diff --git a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/framework.py b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/framework.py index ba3dca805..3de38e80b 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/framework.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/a2a_agent/framework.py @@ -78,6 +78,7 @@ TriggerRegisterRequest, enable, ) +from ..computer.clock import RANGE as CLOCK_RANGE from ..computer.errors import ComputerError from ..errors import AgentEnvError from ..types import error_body @@ -1080,7 +1081,8 @@ def _with_clock(definition: _AgentDefinition) -> _AgentDefinition: if not agent_clock.follows() or any(a.definition.uri == CLOCK_V1.uri for a in definition.extensions): return definition agent_clock.restore_zone() # a server restarted mid-run takes back the task's zone - return dataclasses.replace(definition, extensions=(*definition.extensions, ExtensionActivation(CLOCK_V1))) + clock = ExtensionActivation(CLOCK_V1, wire_params={"range": dict(CLOCK_RANGE)}) + return dataclasses.replace(definition, extensions=(*definition.extensions, clock)) class DefaultExtensionHandlers: diff --git a/packages/agentenv-protocol/src/agentenv_protocol/computer/card.py b/packages/agentenv-protocol/src/agentenv_protocol/computer/card.py index 2f99ca982..1ac5b8dc4 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/computer/card.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/computer/card.py @@ -56,8 +56,10 @@ def served_extensions(driver: ComputerDriverEnvironment, continue if extension.uri == COMPUTER_RECORDING and driver.recording is None: continue - if extension.uri == clock.CLOCK and not clock.follows(): - continue + if extension.uri == clock.CLOCK: + if not clock.follows(): + continue + extension = extension.model_copy(update={"params": {**extension.params, "range": dict(clock.RANGE)}}) dropped = {op for (uri, op), need in _METHOD_NEEDS.items() if uri == extension.uri and not driver.has(need)} if dropped: methods = {op: entry for op, entry in extension.params["methods"].items() if op not in dropped} diff --git a/packages/agentenv-protocol/src/agentenv_protocol/computer/clock.py b/packages/agentenv-protocol/src/agentenv_protocol/computer/clock.py index 8b69d06b3..c10ab8b74 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/computer/clock.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/computer/clock.py @@ -27,8 +27,12 @@ #: The follower's clock file, replaced whole at each write: ``@ x ^`` while the clock is #: armed (the universe at real time ``anchor``, running at ``rate``), ``+0 x1`` on real time. CLOCK_FILE = "/run/agentenv-clock/clock" -#: The end of the env clock's range, 2262-04-11T23:47:16Z in epoch seconds: a clock that runs to it stands there, as the -#: gateway's and the computers' do, before the follower writes it standing. +#: The times a computer's and a clock-following agent's session programs hold: what 64 bits of nanoseconds since 1970 +#: hold, as the clock page and Python keep time (outside them ``time.time()`` raises). Their cards declare it as clock/v1's +#: ``range``, and a gateway refuses to take its clock outside the range of a follower it has. +RANGE = {"earliest": "1677-09-21T00:12:44Z", "latest": "2262-04-11T23:47:16Z"} +#: The end of that range in epoch seconds: a clock that runs to it stands there, as the computers' do, before the follower +#: writes it standing. END = 9223372036.0 #: What a disk form's guest has, made from the computer's container image: core's root channel reaches its launcher, #: not the guest, so it can't configure a follower there, and a disk computer stays on real time for now. diff --git a/packages/agentenv-protocol/tests/test_a2a_agent_clock.py b/packages/agentenv-protocol/tests/test_a2a_agent_clock.py index 0231bc632..345162a74 100644 --- a/packages/agentenv-protocol/tests/test_a2a_agent_clock.py +++ b/packages/agentenv-protocol/tests/test_a2a_agent_clock.py @@ -95,6 +95,7 @@ def test_every_agent_in_an_image_with_the_follower_serves_sync_time(image): assert served is not None request = served["params"]["methods"]["sync_time"]["request"] assert request == {"required": ["env_get_time_url"], "optional": ["timezone", "watch_url", "name", "read_token"]} + assert served["params"]["range"] == {"earliest": "1677-09-21T00:12:44Z", "latest": "2262-04-11T23:47:16Z"} def test_an_agent_in_an_image_without_the_follower_serves_no_clock(image, monkeypatch): diff --git a/packages/agentenv-protocol/tests/test_computer_clock.py b/packages/agentenv-protocol/tests/test_computer_clock.py index 253f1e360..835ab3662 100644 --- a/packages/agentenv-protocol/tests/test_computer_clock.py +++ b/packages/agentenv-protocol/tests/test_computer_clock.py @@ -47,6 +47,7 @@ async def test_the_card_serves_sync_time_where_the_base_runs_the_follower_and_it assert set(served["params"]["methods"]) == {"sync_time"} assert set(served["params"]["methods"]["sync_time"]["request"]["properties"]) == {"env_get_time_url", "timezone"} + assert served["params"]["range"] == {"earliest": "1677-09-21T00:12:44Z", "latest": "2262-04-11T23:47:16Z"} assert on_a_disk is None and await _clock_extension(FakeDriver()) is None diff --git a/src/agent_env/a2a_agent/clock.py b/src/agent_env/a2a_agent/clock.py index c9f6be0b9..4e819e11f 100644 --- a/src/agent_env/a2a_agent/clock.py +++ b/src/agent_env/a2a_agent/clock.py @@ -19,6 +19,8 @@ import httpx +from agentenv_protocol.client import ExtensionCallError + from agent_env.a2a_agent.a2a_agent import A2AAgent from agent_env.env.env import EnvCapabilityUnsupported, gateway_url_of from agent_env.env.gateway.constants import CLOCK_WATCH_PATH, EXT_CLOCK_URI @@ -51,6 +53,13 @@ def follower_name(agent: DeployedAgent) -> str: return f"agent-{agent.agent_name}" +def held_range(agent: DeployedAgent) -> Optional[dict]: + """The times ``agent`` holds, when its card declares it holds only a range of them (clock/v1's ``range``); a card + from before it declares none.""" + held = (A2AAgent.find_extension(agent.a2a_card or {}, EXT_CLOCK_URI) or {}).get("params", {}).get("range") + return held if isinstance(held, dict) and held.get("earliest") and held.get("latest") else None + + def _sync_time(agent: DeployedAgent) -> tuple[Optional[dict], Optional[str]]: return A2AAgent.operation(A2AAgent.find_extension(agent.a2a_card or {}, EXT_CLOCK_URI), "sync_time") @@ -72,7 +81,8 @@ async def follow(agent: DeployedAgent, env: DeployedEnv, *, env_get_time_url: Op timezone: Optional[str], timeout: float) -> dict: """Have ``agent`` follow ``env``'s gateway clock. ``{"synced": False, "reason": ...}`` for an agent that can't: its card serves no ``sync_time`` (``not_advertised``) or one without the follower's fields - (``no_follower_fields``), or the gateway takes no followers after it starts (``gateway_takes_no_followers``); raises + (``no_follower_fields``), the gateway takes no followers after it starts (``gateway_takes_no_followers``), or the + clock is outside the range of times the agent's card says it holds (``outside_range: ``); raises for one that serves it and fails, having retired the follower it declared, or can't take the task's zone, as for a server.""" method, path = _sync_time(agent) @@ -85,10 +95,16 @@ async def follow(agent: DeployedAgent, env: DeployedEnv, *, env_get_time_url: Op raise StepContextError(f"agent '{agent.agent_name}' serves {EXT_CLOCK_URI} sync_time without a timezone; " f"rebuild its image or drop timezone={timezone!r} from the task") name, token = follower_name(agent), secrets.token_urlsafe(READ_TOKEN_BYTES) + held = held_range(agent) try: - await env.invoke(EXT_CLOCK_URI, "declare_follower", {"name": name, "read_token": token}, timeout=timeout) + await env.invoke(EXT_CLOCK_URI, "declare_follower", + {"name": name, "read_token": token, **({"range": held} if held else {})}, timeout=timeout) except EnvCapabilityUnsupported: return {"synced": False, "reason": "gateway_takes_no_followers"} + except ExtensionCallError as e: + if held is None or e.response.status_code != 400: + raise + return {"synced": False, "reason": f"outside_range: {e.detail}"} body = {"env_get_time_url": env_get_time_url or "", "watch_url": watch_url_for(agent, env), "name": name, "read_token": token, **({"timezone": timezone} if timezone is not None else {})} url = (agent.a2a_url or agent.api_url).rstrip("/") + path diff --git a/src/agent_env/env/envs/_multi_computers.py b/src/agent_env/env/envs/_multi_computers.py index 86f17f731..3d3e628fb 100644 --- a/src/agent_env/env/envs/_multi_computers.py +++ b/src/agent_env/env/envs/_multi_computers.py @@ -223,7 +223,8 @@ async def deploy(reach: Optional[str], control_token: Optional[str]) -> list[Ext for error in failed[1:]: logger.warning(f"multi env '{self._owner}': another computer failed to deploy too: {error!r}") raise failed[0] - return [ExternalChild(env.environment_name, record.mcp_url, record.environment_url, _clock_read_token(record)) + return [ExternalChild(env.environment_name, record.mcp_url, record.environment_url, _clock_read_token(record), + computer_clock.held_range(record)) for env, record in zip(self.every, results)] return deploy diff --git a/src/agent_env/env/envs/computer/utils/clock.py b/src/agent_env/env/envs/computer/utils/clock.py index db2ef6840..c43341dc5 100644 --- a/src/agent_env/env/envs/computer/utils/clock.py +++ b/src/agent_env/env/envs/computer/utils/clock.py @@ -18,6 +18,7 @@ from typing import TYPE_CHECKING, Optional import httpx +from agentenv_protocol import client as protocol_v1 from agentenv_protocol.client import ExtensionCallError from agentenv_protocol.computer.clock import CONFIG, FOLLOWER_USER @@ -39,6 +40,13 @@ def follows(record: DeployedEnv) -> bool: return record.supports(EXT_CLOCK_URI, "sync_time") +def held_range(record: DeployedEnv) -> Optional[dict]: + """The times the computer ``record`` deployed holds, when its card declares it holds only a range of them + (clock/v1's ``range``, ``{"earliest": ..., "latest": ...}``); a card from before it declares none.""" + held = protocol_v1.extension_params(record.environment_card or {}, EXT_CLOCK_URI).get("range") + return held if follows(record) and isinstance(held, dict) and held.get("earliest") and held.get("latest") else None + + def recorded(record: DeployedEnv) -> Optional[dict]: """The follower's config ``record`` keeps, its token aside: the watch URL and the computer's name.""" clock = ((record.metadata or {}).get("computer") or {}).get("clock") diff --git a/src/agent_env/env/gateway/__init__.py b/src/agent_env/env/gateway/__init__.py index 33a49e3df..46d88c761 100644 --- a/src/agent_env/env/gateway/__init__.py +++ b/src/agent_env/env/gateway/__init__.py @@ -31,12 +31,14 @@ class InternalMCPServer: class ExternalChild: """A child env on a sandbox of its own, which the gateway fronts as it does an MCP server: its name, and its MCP endpoint and base URL as the process holding it reaches them. A child that is a clock follower has the read token its - clock watch carries, and the gateway's clock writes wait for it.""" + clock watch carries, and the gateway's clock writes wait for it; one that holds only a range of times has that range + (``{"earliest": ..., "latest": ...}``), which the gateway's clock keeps to.""" name: str mcp_url: str base_url: str clock_read_token: str | None = None + clock_range: dict | None = None __all__ = [ diff --git a/src/agent_env/env/gateway/clock.py b/src/agent_env/env/gateway/clock.py index 383438874..d6e17e06f 100644 --- a/src/agent_env/env/gateway/clock.py +++ b/src/agent_env/env/gateway/clock.py @@ -10,6 +10,8 @@ import secrets import threading import time +from collections.abc import Callable, Mapping +from dataclasses import dataclass from datetime import datetime, timedelta, timezone from zoneinfo import ZoneInfo, ZoneInfoNotFoundError @@ -20,14 +22,42 @@ class ClockError(ValueError): MAX_RATE = 86400.0 # 1 real second = 1 virtual day (the max virtual-time speed) -# Fast-fail arming a clock that would reach LATEST within a real hour at `rate` (frozen clocks exempt): an hour, so a -# day per second still arms at today's dates. Not the guarantee: a clock that runs to LATEST stands there. -_OVERFLOW_HORIZON_S = 3600.0 +# Fast-fail a t0 that would overflow within a real day of advancement at `rate` (frozen clocks +# exempt). Not the overflow guarantee — reads still saturate (_advance) if the gateway outlives it. +_OVERFLOW_HORIZON_S = 86400.0 _MAX_T0 = datetime.max.replace(tzinfo=timezone.utc) -# The times the clock holds: those 64 bits of nanoseconds since 1970 hold, as Python and the computers' clock page keep -# time, so every program that follows the clock can read it (Python's time.time() raises outside them). -EARLIEST = datetime(1677, 9, 21, 0, 12, 44, tzinfo=timezone.utc) -LATEST = datetime(2262, 4, 11, 23, 47, 16, tzinfo=timezone.utc) +# Fast-fail arming a clock that a follower would see run past the latest time it holds within a real hour at `rate`: an +# hour, so a day per second still arms at today's dates on a computer, whose range ends in 2262. +_FOLLOWER_HORIZON_S = 3600.0 + + +@dataclass(frozen=True) +class FollowerRange: + """The times a clock follower holds, as its card declares them (clock/v1's ``range``): a computer's and a + clock-following agent's are what 64 bits of nanoseconds since 1970 hold, as their clock page and Python keep time.""" + + earliest: datetime + latest: datetime + + +def parse_follower_range(value) -> FollowerRange: + """A follower's declared range, ``{"earliest": , "latest": }``.""" + if not isinstance(value, dict): + raise ClockError(f"a follower's range takes earliest and latest RFC3339 times, got {value!r}") + held = FollowerRange(_parse_rfc3339(value.get("earliest")), _parse_rfc3339(value.get("latest"))) + if held.earliest > held.latest: + raise ClockError(f"a follower's range ends before it starts: {value!r}") + return held + + +def check_arm(virtual_time: str, rate=1.0) -> tuple[datetime, float]: + """``virtual_time`` and ``rate`` as the clock arms at them, or the ClockError it refuses them with whatever its + followers, as sync_env_clock checks them before anything deploys.""" + t0 = _parse_rfc3339(virtual_time) + r = _parse_rate(1.0 if rate is None else rate) + if t0 > _MAX_T0 - timedelta(seconds=_OVERFLOW_HORIZON_S * r): + raise ClockError(f"virtual_time {virtual_time!r} at rate {r:g} would overflow datetime near the max") + return t0, r def _parse_rate(rate) -> float: @@ -47,7 +77,7 @@ def _parse_rate(rate) -> float: # fromisoformat is looser than RFC3339 (accepts basic format, week/ordinal dates, sub-minute # offsets), so gate on the grammar first and let it do only the arithmetic. A space separator is ok. _RFC3339_RE = re.compile( - r"""^(\d{4,})-\d{2}-\d{2} # a year past four digits is read, to be refused as outside the range + r"""^\d{4}-\d{2}-\d{2} [Tt ] \d{2}:\d{2}:\d{2} # seconds are mandatory (?:\.\d+)? @@ -63,11 +93,8 @@ def _parse_rfc3339(text: str) -> datetime: raise ClockError(f"virtual_time must be an RFC3339 string, got {type(text).__name__}") # Don't strip: a whitespace-wrapped value would slip through the anchored grammar (a 200 the contract calls a 400). raw = text - grammar = _RFC3339_RE.match(raw) - if not grammar: + if not _RFC3339_RE.match(raw): raise ClockError(f"invalid RFC3339 virtual_time {text!r}: expected {_RFC3339_SHAPE}") - if len(grammar.group(1)) > 4 or grammar.group(1) == "0000": - raise ClockError(outside_range(f"virtual_time {text!r}")) if raw.endswith(("Z", "z")): raw = raw[:-1] + "+00:00" try: @@ -77,37 +104,7 @@ def _parse_rfc3339(text: str) -> datetime: try: return dt.astimezone(timezone.utc) except OverflowError: - raise ClockError(outside_range(f"virtual_time {text!r}")) - - -_WHY = "the times a 64-bit count of nanoseconds since 1970 holds, as Python and the computers that follow the clock keep time" - - -def outside_range(what: str) -> str: - """The refusal of ``what``, a time the clock can't hold, naming its range and why.""" - return f"{what} is outside the env clock's range, {_iso(EARLIEST)} to {_iso(LATEST)} ({_WHY})" - - -def _past_end(what: str) -> str: - return f"{what} would pass {_iso(LATEST)}, the end of the env clock's range, within a real hour ({_WHY})" - - -def _ends_within_an_hour(at: datetime, rate: float) -> bool: - """Whether a clock at ``at``, running at ``rate``, reaches LATEST within _OVERFLOW_HORIZON_S real seconds.""" - return (LATEST - at).total_seconds() < _OVERFLOW_HORIZON_S * rate - - -def check_arm(virtual_time: str, rate=1.0, what: str | None = None) -> tuple[datetime, float]: - """``virtual_time`` and ``rate`` as set_time arms the clock at them, or the ClockError it refuses them with, which - names the time as ``what`` (``virtual_time ''`` by default).""" - t0 = _parse_rfc3339(virtual_time) - r = _parse_rate(1.0 if rate is None else rate) - what = what or f"virtual_time {virtual_time!r}" - if not EARLIEST <= t0 <= LATEST: - raise ClockError(outside_range(what)) - if _ends_within_an_hour(t0, r): - raise ClockError(_past_end(f"{what} at rate {r:g}")) - return t0, r + raise ClockError(f"invalid RFC3339 virtual_time {text!r}: out of representable range") def _iso(dt: datetime) -> str: @@ -150,8 +147,11 @@ def _parse_duration(text) -> timedelta: def _advance(t0: datetime, seconds: float) -> datetime: - """t0 + seconds, saturating at datetime.min/max instead of raising, as a trigger's mark far past the clock's range - may need; the clock's own time stops at LATEST (Clock._upto_end).""" + """t0 + seconds, saturating at datetime.min/max instead of raising. + + set_time's horizon check can't bound a gateway that outlives _OVERFLOW_HORIZON_S, so reads + saturate rather than 500 — an armed clock always returns a (monotonic) time. + """ try: return t0 + timedelta(seconds=seconds) except (OverflowError, ValueError, OSError): @@ -163,8 +163,10 @@ class Clock: BOOT_ID_BYTES = 6 # a version's per-boot id, random, so a restarted gateway's versions never repeat its last boot's - def __init__(self, now_fn=time.monotonic): + def __init__(self, now_fn=time.monotonic, + follower_ranges: Callable[[], Mapping[str, FollowerRange]] = dict): self._now = now_fn + self._follower_ranges = follower_ranges self._lock = threading.Lock() self._armed = False self._t0: datetime | None = None @@ -222,6 +224,7 @@ def set_time(self, virtual_time: str, rate=1.0, time_zone: str | None = None) -> t0, r = check_arm(virtual_time, rate) if time_zone is not None and _zone(time_zone) is None: raise ClockError(f"unknown time zone {time_zone!r}: pass an IANA time zone name such as 'America/New_York'") + self._check_followers(f"virtual_time {virtual_time!r}", t0, r) with self._lock: self._bank(t0) self._t0 = t0 @@ -233,17 +236,28 @@ def set_time(self, virtual_time: str, rate=1.0, time_zone: str | None = None) -> self._count += 1 return self.state() + def _check_followers(self, what: str, t: datetime, rate: float | None) -> None: + """Refuse ``t``, a time the clock would be set or advanced to, outside the range of a follower it has, or, armed + at ``rate``, one it would run past the end of that range from within a real hour.""" + for name, held in sorted(self._follower_ranges().items()): + where = f"clock follower {name!r} holds, {_iso(held.earliest)} to {_iso(held.latest)}" + if not held.earliest <= t <= held.latest: + raise ClockError(f"{what} is outside the times {where}") + if rate and (held.latest - t).total_seconds() < _FOLLOWER_HORIZON_S * rate: + raise ClockError(f"{what} at rate {rate:g} would pass the end of the times {where}, within a real hour") + def set_rate(self, rate) -> dict: """Change an armed clock's rate from its time at the call, keeping t0 and generation as an advance does, so time triggers keep their marks and a rate change can't step the clock back by a time read a moment earlier; 0 freezes - the clock. No rate is refused for nearing the end of the range, which the clock stands at once it gets there, so - a harness that froze it near the end can always start it again.""" + the clock.""" r = _parse_rate(rate) with self._lock: if not self._armed or self._t0 is None: raise ClockError("clock is not armed") now = self._now() ran = (now - self._anchor) * self._rate + if _advance(self._t0, ran + self._ahead) > _MAX_T0 - timedelta(seconds=_OVERFLOW_HORIZON_S * r): + raise ClockError(f"rate {r:g} would overflow datetime near the max") self._lived += ran self._ahead += ran self._anchor = now @@ -252,16 +266,15 @@ def set_rate(self, rate) -> dict: return self.state() def advance(self, virtual_time: str) -> dict: - """Jump forward to virtual_time on the current arm, keeping t0, rate and generation, so marks stay put; a time - past the end of the range is refused, one in its last real hour isn't, and the clock stands at the end once - there.""" + """Jump forward to virtual_time on the current arm, keeping t0, rate and generation, so marks stay put.""" target = _parse_rfc3339(virtual_time) with self._lock: if not self._armed or self._t0 is None: raise ClockError("clock is not armed") - if target > LATEST: - raise ClockError(outside_range(f"virtual_time {virtual_time!r}")) - current = self._upto_end((self._now() - self._anchor) * self._rate + self._ahead) + if target > _MAX_T0 - timedelta(seconds=_OVERFLOW_HORIZON_S * self._rate): + raise ClockError(f"virtual_time {virtual_time!r} at rate {self._rate:g} would overflow datetime near the max") + self._check_followers(f"virtual_time {virtual_time!r}", target, None) + current = _advance(self._t0, (self._now() - self._anchor) * self._rate + self._ahead) jump = (target - current).total_seconds() if jump < 0: raise ClockError(f"advance only moves forward: {virtual_time!r} is before the current {_iso(current)}") @@ -293,7 +306,7 @@ def now(self) -> datetime | None: if not self._armed or self._t0 is None: return None elapsed = self._now() - self._anchor - return self._upto_end(elapsed * self._rate + self._ahead) + return _advance(self._t0, elapsed * self._rate + self._ahead) @property def time_zone(self) -> str | None: @@ -316,21 +329,14 @@ def read(self) -> dict: return {"virtual_time": _iso(current)} def state(self) -> dict: - """The clock as its followers take it up; one at the end of its range stands there, at rate 0.""" with self._lock: if not self._armed or self._t0 is None: return {"armed": False, "version": self.version} - current = self._upto_end((self._now() - self._anchor) * self._rate + self._ahead) - return {"armed": True, "t0": _iso(self._t0), - "virtual_seconds_per_real_second": 0.0 if current == LATEST else self._rate, - "virtual_time": _iso(current), + elapsed = self._now() - self._anchor + return {"armed": True, "t0": _iso(self._t0), "virtual_seconds_per_real_second": self._rate, + "virtual_time": _iso(_advance(self._t0, elapsed * self._rate + self._ahead)), **({"time_zone": self._time_zone} if self._time_zone else {}), "version": self.version} - def _upto_end(self, seconds: float) -> datetime: - """The current arm's time ``seconds`` after t0, standing at LATEST: no check at a write can bound a gateway that - outlives it, so the clock stops at the end of its range rather than leave it. Lock held.""" - return min(_advance(self._t0, seconds), LATEST) - def _bank(self, t0: datetime | None = None) -> None: """Fold the stretch since the last arm/clear into `_lived` at its rate, and start the next one now.""" now = self._now() diff --git a/src/agent_env/env/gateway/clock_followers.py b/src/agent_env/env/gateway/clock_followers.py index 190c58b3c..05c3df68a 100644 --- a/src/agent_env/env/gateway/clock_followers.py +++ b/src/agent_env/env/gateway/clock_followers.py @@ -1,6 +1,7 @@ """The followers of the gateway's clock (the computers on it, declared at its start, and the agents a run declares after it, ``declare``, and retires when it tears one down, ``retire``): each long-polls ``/clock/watch`` with the version it -shows, which is its acknowledgement, and a clock write can wait until every one shows the write's version.""" +shows, which is its acknowledgement, and a clock write can wait until every one shows the write's version. A follower +may hold only a range of times (its card's clock/v1 ``range``), which the clock keeps to while it follows.""" from __future__ import annotations import asyncio @@ -9,7 +10,7 @@ import time from collections.abc import Callable, Mapping -from .clock import Clock, ClockError +from .clock import Clock, ClockError, FollowerRange, _iso from .constants import CLOCK_MAX_WAIT_FOLLOWERS_S, CLOCK_WATCH_HOLD_S @@ -37,23 +38,33 @@ class ClockFollowers: #: to reconnect, so its connection is gone. A write doesn't wait for a quiet follower; it names it at once. QUIET_S = CLOCK_WATCH_HOLD_S + 5 - def __init__(self, clock: Callable[[], Clock], tokens: Mapping[str, str]): + def __init__(self, clock: Callable[[], Clock], tokens: Mapping[str, str], + held: Mapping[str, FollowerRange] | None = None): self._clock = clock self._tokens = dict(tokens) + self._held = {name: span for name, span in (held or {}).items() if name in self._tokens} self._shown: dict[str, int | None] = dict.fromkeys(self._tokens) self._seen: dict[str, float] = {} self._declared: set[str] = set() self._changed = asyncio.Event() self._acks = asyncio.Condition() - def declare(self, name: str, token: str) -> None: - """Declare ``name`` a follower, with the read token its watch carries, after the gateway started: an agent the - run deploys. Declared again, as a redeploy does, it takes the new token and is waited for afresh.""" + def declare(self, name: str, token: str, held: FollowerRange | None = None) -> None: + """Declare ``name`` a follower, with the read token its watch carries and the range of times it holds if it + holds only some, after the gateway started: an agent the run deploys. Declared again, as a redeploy does, it takes + the new token and range and is waited for afresh. One whose range the clock is outside now is refused.""" if not name or not token: raise ClockError("a follower takes a name and a read token") if name in self._tokens and name not in self._declared: raise ClockError(f"{name!r} is a follower this gateway started with, which a declaration doesn't replace") + if held is not None and (now := self._clock().now()) is not None and not held.earliest <= now <= held.latest: + raise ClockError(f"the clock, at {_iso(now)}, is outside the times clock follower {name!r} holds, " + f"{_iso(held.earliest)} to {_iso(held.latest)}") self._tokens[name] = token + if held is None: + self._held.pop(name, None) + else: + self._held[name] = held self._shown[name] = None self._seen.pop(name, None) self._declared.add(name) @@ -66,11 +77,15 @@ async def retire(self, name: str) -> bool: return False async with self._acks: self._declared.discard(name) - for followers in (self._tokens, self._shown, self._seen): + for followers in (self._tokens, self._shown, self._seen, self._held): followers.pop(name, None) self._acks.notify_all() return True + def held(self) -> dict[str, FollowerRange]: + """Each follower that holds only a range of times, by name, with its range: the clock keeps to them.""" + return dict(self._held) + def changed(self) -> None: """Answer every held watch: the clock has a new version.""" self._changed.set() @@ -134,5 +149,7 @@ def state(self) -> dict: """Each follower's last shown version and how long ago it last watched, for ``/clock/state``.""" now, clock = time.monotonic(), self._clock() return {name: {"version": None if shown is None else clock.version_of(shown), - "seen_s_ago": round(now - self._seen[name], 3) if name in self._seen else None} + "seen_s_ago": round(now - self._seen[name], 3) if name in self._seen else None, + **({"range": {"earliest": _iso(held.earliest), "latest": _iso(held.latest)}} + if (held := self._held.get(name)) else {})} for name, shown in self._shown.items()} diff --git a/src/agent_env/env/gateway/constants.py b/src/agent_env/env/gateway/constants.py index 4cc716039..b932fa9e8 100644 --- a/src/agent_env/env/gateway/constants.py +++ b/src/agent_env/env/gateway/constants.py @@ -72,6 +72,9 @@ def data_plane_load_timeout_s(size_bytes: int | None) -> int: # The computers that follow the gateway's clock, each as `name=read token`, comma-separated; TOKEN in the name keeps # it out of logged compose files. CLOCK_FOLLOWERS_ENV = "CLOCK_FOLLOWER_TOKENS" +# The times each of those computers holds, when its card declares it holds only a range of them (clock/v1's range), as +# `name=earliest/latest` (RFC3339), comma-separated; the clock keeps to them. +CLOCK_FOLLOWER_RANGES_ENV = "CLOCK_FOLLOWER_RANGES" # The children the gateway passes its control token on to, comma-separated: a multi env's computers, which boot with it. CONTROL_TOKEN_CHILDREN_ENV = "CONTROL_TOKEN_CHILDREN" # The gateway's computers, comma-separated: a multi env's, each a child on a sandbox of its own, whose input calls set @@ -268,7 +271,7 @@ def random_mcp_server_name() -> str: }, { "uri": EXT_CLOCK_URI, - "description": "Virtual clock (urn:agentenv:clock/v1): read the gateway's virtual time (wall-clock-derived, rate-scaled) via get_time; set_time/set_rate/advance/clear are the harness control path, each changing the clock's opaque version and, given wait_followers_s, answering 504 naming the followers that don't show it in time (set_rate keeps t0, as advance does, so time triggers keep their marks; rate 0 freezes the clock); the clock holds 1677-09-21T00:12:44Z to 2262-04-11T23:47:16Z, the times 64 bits of nanoseconds since 1970 hold: set_time and advance refuse a time outside it, set_time also one from which its rate would reach the end within a real hour, and a clock that runs to its end stands there, at rate 0; declare_follower adds a follower after the gateway started (an agent the run deploys), with the read token its watches carry, and retire_follower removes one so writes stop waiting for it (an agent the run tears down); a follower follows it through watch, a long poll naming the version it shows and held up to hold_s; state's followers block is diagnostic, not part of the contract.", + "description": "Virtual clock (urn:agentenv:clock/v1): read the gateway's virtual time (wall-clock-derived, rate-scaled) via get_time; set_time/set_rate/advance/clear are the harness control path, each changing the clock's opaque version and, given wait_followers_s, answering 504 naming the followers that don't show it in time (set_rate keeps t0, as advance does, so time triggers keep their marks; rate 0 freezes the clock); declare_follower adds a follower after the gateway started (an agent the run deploys), with the read token its watches carry and, for one that holds only a range of times (its card's clock/v1 range), that range, refused when the clock is outside it now; set_time and advance refuse a time outside the range of a follower the clock has, naming it, and set_time one it would run past that range's end from within a real hour; retire_follower removes one so writes stop waiting for it (an agent the run tears down); a follower follows it through watch, a long poll naming the version it shows and held up to hold_s; state's followers block is diagnostic, not part of the contract.", "params": {"endpoint": "/clock/time", "methods": { "get_time": {"method": "GET", "endpoint": "/clock/time"}, "set_time": {"method": "PUT", "endpoint": "/clock/set-time", "request": {"type": "object", "properties": {"virtual_time": {"type": "string"}, "virtual_seconds_per_real_second": {"type": "number"}, "time_zone": {"type": "string"}, **_WAIT_FOLLOWERS}, "required": ["virtual_time"]}}, @@ -276,7 +279,7 @@ def random_mcp_server_name() -> str: "advance": {"method": "PUT", "endpoint": "/clock/advance", "request": {"type": "object", "properties": {"virtual_time": {"type": "string"}, **_WAIT_FOLLOWERS}, "required": ["virtual_time"]}}, "clear": {"method": "POST", "endpoint": "/clock/clear", "request": {"type": "object", "properties": {**_WAIT_FOLLOWERS}}}, "state": {"method": "GET", "endpoint": "/clock/state", "request": {"type": "object", "properties": {}}}, - "declare_follower": {"method": "PUT", "endpoint": CLOCK_FOLLOWERS_PATH, "request": {"type": "object", "properties": {"name": {"type": "string"}, "read_token": {"type": "string"}}, "required": ["name", "read_token"]}}, + "declare_follower": {"method": "PUT", "endpoint": CLOCK_FOLLOWERS_PATH, "request": {"type": "object", "properties": {"name": {"type": "string"}, "read_token": {"type": "string"}, "range": {"type": "object", "properties": {"earliest": {"type": "string"}, "latest": {"type": "string"}}, "required": ["earliest", "latest"]}}, "required": ["name", "read_token"]}}, "retire_follower": {"method": "DELETE", "endpoint": CLOCK_FOLLOWERS_PATH, "request": {"type": "object", "properties": {"name": {"type": "string"}}, "required": ["name"]}}, "watch": {"method": "GET", "endpoint": CLOCK_WATCH_PATH, "hold_s": CLOCK_WATCH_HOLD_S, "request": {"type": "object", "properties": {"after": {"type": "string"}, "follower": {"type": "string"}}}}}}, "required": False, diff --git a/src/agent_env/env/gateway/entrypoint.py b/src/agent_env/env/gateway/entrypoint.py index e2b402cbc..7b8ab6ef4 100644 --- a/src/agent_env/env/gateway/entrypoint.py +++ b/src/agent_env/env/gateway/entrypoint.py @@ -8,8 +8,9 @@ import httpx from . import AGENT_ENV_GATEWAY_MCP_PORT, GatewayMode, InternalMCPServer +from .clock import ClockError, FollowerRange, parse_follower_range from .console_session import frame_ancestor_problem -from .constants import (CLOCK_FOLLOWERS_ENV, COMPUTERS_ENV, CONSOLE_FRAME_ANCESTORS_ENV, CONSOLE_URLS_ENV, CONTROL_TOKEN_CHILDREN_ENV, CONTROL_TOKEN_ENV, DEFAULT_MCP_SERVER_NAME, +from .constants import (CLOCK_FOLLOWER_RANGES_ENV, CLOCK_FOLLOWERS_ENV, COMPUTERS_ENV, CONSOLE_FRAME_ANCESTORS_ENV, CONSOLE_URLS_ENV, CONTROL_TOKEN_CHILDREN_ENV, CONTROL_TOKEN_ENV, DEFAULT_MCP_SERVER_NAME, GATEWAY_PROVIDER_HEADERS_ENV, MCP_TRANSPORT, WEBSITE_LISTED_BY_NAME_ENV, WEBSITE_NAMES_ENV, WELL_KNOWN_PATH) from .gateway import Gateway, card_url @@ -212,6 +213,22 @@ def parse_clock_followers(spec: str) -> dict[str, str]: return followers +def parse_clock_follower_ranges(spec: str) -> dict[str, FollowerRange]: + """``CLOCK_FOLLOWER_RANGES``: the times each computer that holds only a range of them holds, as + ``name=earliest/latest`` (RFC3339), comma-separated.""" + held: dict[str, FollowerRange] = {} + for entry in filter(None, (part.strip() for part in spec.split(","))): + name, _, span = (part.strip() for part in entry.partition("=")) + earliest, _, latest = span.partition("/") + if not name or not earliest or not latest: + raise ValueError(f"invalid {CLOCK_FOLLOWER_RANGES_ENV} entry {entry!r}: expected 'name=earliest/latest'") + try: + held[name] = parse_follower_range({"earliest": earliest, "latest": latest}) + except ClockError as e: + raise ValueError(f"invalid {CLOCK_FOLLOWER_RANGES_ENV} entry for {name!r}: {e}") from e + return held + + def parse_site_names(env_str: str) -> dict[str, tuple[str, ...]]: """Each site's names from ``WEBSITE_NAMES``: ``shop=shop.test|www.shop.test,docs=docs.test``.""" names: dict[str, tuple[str, ...]] = {} @@ -259,6 +276,7 @@ def parse_site_names(env_str: str) -> dict[str, tuple[str, ...]]: computers=[name.strip() for name in os.environ.get(COMPUTERS_ENV, "").split(",") if name.strip()], provider_headers=os.environ.get(GATEWAY_PROVIDER_HEADERS_ENV, "").split(","), clock_followers=parse_clock_followers(os.environ.get(CLOCK_FOLLOWERS_ENV, "")), + clock_follower_ranges=parse_clock_follower_ranges(os.environ.get(CLOCK_FOLLOWER_RANGES_ENV, "")), site_names=parse_site_names(os.environ.get(WEBSITE_NAMES_ENV, "")), listed_by_name=[site.strip() for site in os.environ.get(WEBSITE_LISTED_BY_NAME_ENV, "").split(",") if site.strip()], diff --git a/src/agent_env/env/gateway/gateway.py b/src/agent_env/env/gateway/gateway.py index ae2af8ed6..6f8ace1d0 100644 --- a/src/agent_env/env/gateway/gateway.py +++ b/src/agent_env/env/gateway/gateway.py @@ -80,7 +80,7 @@ from .caller import Caller from .changes import ChangeAttribution from .child_sessions import ChildSessions, is_dead_session -from .clock import Clock, ClockError, _iso +from .clock import Clock, ClockError, FollowerRange, _iso, parse_follower_range from .clock_followers import ClockFollowers, parse_wait from .console_session import ConsoleSession, LinkRedaction, without_session_cookie from .get_time import GET_TIME_TOOL_NAME, build_get_time_tool @@ -182,6 +182,7 @@ def __init__( computers: Iterable[str] = (), provider_headers: Iterable[str] = (), clock_followers: Mapping[str, str] | None = None, + clock_follower_ranges: Mapping[str, FollowerRange] | None = None, site_names: dict[str, Iterable[str]] | None = None, listed_by_name: Iterable[str] = (), console_urls: Mapping[str, str] | None = None, @@ -189,7 +190,8 @@ def __init__( ): """`provider_headers` names the headers the sandbox provider in front of the gateway is sent, its credentials, which the gateway takes off every request it forwards to a service behind it. `clock_followers` names the - followers of its clock, each with the read token its watch carries. `site_names` are each site's names as its + followers of its clock, each with the read token its watch carries, and `clock_follower_ranges` the times each + that holds only a range of them holds, which the clock keeps to. `site_names` are each site's names as its env stores them, the names its card declares standing in for a site's that stores none: a site reached at one takes it as its ``Host``. ``list_website_urls`` gives each site `listed_by_name` at its first name, as a browser computer opens it, and the others at their ``website_urls``. `control_token_children` are the children its @@ -272,8 +274,8 @@ async def list_website_urls() -> list[str]: inputSchema={"type": "object", "properties": {}}, ) ) - self._clock = Clock() - self._clock_followers = ClockFollowers(lambda: self._clock, clock_followers or {}) + self._clock = Clock(follower_ranges=lambda: self._clock_followers.held()) + self._clock_followers = ClockFollowers(lambda: self._clock, clock_followers or {}, clock_follower_ranges) self._notifications = Notifications(lambda: self._clock) self._user_chat = UserChat(lambda: self._clock) self._env_get_time_url_cache: str | None = None @@ -433,7 +435,8 @@ async def clock_declare_follower(request: Request) -> Response: if not isinstance(body, dict): return self._json_response({"ok": False, "error": "body must be a JSON object"}, 400) try: - self._clock_followers.declare(str(body.get("name") or ""), str(body.get("read_token") or "")) + held = None if body.get("range") is None else parse_follower_range(body["range"]) + self._clock_followers.declare(str(body.get("name") or ""), str(body.get("read_token") or ""), held) except ClockError as e: return self._json_response({"ok": False, "error": str(e)}, 400) return self._json_response({"ok": True, "followers": self._clock_followers.state()}, 200) diff --git a/src/agent_env/env/gateway/get_time.py b/src/agent_env/env/gateway/get_time.py index 34919905e..fa66a1a5a 100644 --- a/src/agent_env/env/gateway/get_time.py +++ b/src/agent_env/env/gateway/get_time.py @@ -74,7 +74,11 @@ async def get_time(time_zone: str | None = None) -> dict[str, str] | CallToolRes return _tool_error(f"unknown time zone {time_zone!r}: pass an IANA time zone name such as " "'America/New_York'") reading = read_time(clock) - local = datetime.fromisoformat(reading["current_time"]).astimezone(zone) + try: + local = datetime.fromisoformat(reading["current_time"]).astimezone(zone) + except OverflowError: + return _tool_error(f"the current time {reading['current_time']} can't be shown in time zone " + f"{time_zone!r}: its local date is out of range") return {**reading, "time_zone": time_zone, "local_time": local.isoformat()} return FastMCPTool( diff --git a/src/agent_env/providers/env_providers/env_gateway_provider.py b/src/agent_env/providers/env_providers/env_gateway_provider.py index 922f4d230..17f8c3454 100644 --- a/src/agent_env/providers/env_providers/env_gateway_provider.py +++ b/src/agent_env/providers/env_providers/env_gateway_provider.py @@ -37,6 +37,7 @@ from agent_env.env.gateway import AGENT_ENV_GATEWAY_MCP_PORT, ExternalChild, GatewayMode from agent_env.env.gateway.console_session import frame_ancestor_problem from agent_env.env.gateway.constants import ( + CLOCK_FOLLOWER_RANGES_ENV, CLOCK_FOLLOWERS_ENV, COMPUTERS_ENV, CONSOLE_FRAME_ANCESTORS_ENV, @@ -1861,9 +1862,13 @@ def _redact_compose_secrets(compose_content: str) -> str: def clock_followers_environment(children: Iterable[ExternalChild]) -> dict[str, str]: - """The gateway's declared clock followers: each child that is one, by the read token its watch carries.""" - followers = ",".join(f"{child.name}={child.clock_read_token}" for child in children if child.clock_read_token) - return {CLOCK_FOLLOWERS_ENV: followers} if followers else {} + """The gateway's declared clock followers: each child that is one, by the read token its watch carries, and the + times each that holds only a range of them holds.""" + children = [child for child in children if child.clock_read_token] + followers = ",".join(f"{child.name}={child.clock_read_token}" for child in children) + held = ",".join(f"{child.name}={child.clock_range['earliest']}/{child.clock_range['latest']}" + for child in children if child.clock_range) + return {**({CLOCK_FOLLOWERS_ENV: followers} if followers else {}), **({CLOCK_FOLLOWER_RANGES_ENV: held} if held else {})} def control_token_children_environment(children: Iterable[ExternalChild], control_token: str | None) -> dict[str, str]: diff --git a/src/agent_env/task_step/task_steps/sync_env_clock.py b/src/agent_env/task_step/task_steps/sync_env_clock.py index f9537d2f2..f0e1e6927 100644 --- a/src/agent_env/task_step/task_steps/sync_env_clock.py +++ b/src/agent_env/task_step/task_steps/sync_env_clock.py @@ -28,7 +28,7 @@ from agent_env.a2a_agent.clock import follow_agents, on_deployment, torn_down from agent_env.env.env import Env, EnvCapabilityUnsupported, gateway_url_of -from agent_env.env.gateway.clock import ClockError, check_arm, outside_range +from agent_env.env.gateway.clock import ClockError, check_arm from agent_env.env.gateway.constants import EXT_CLOCK_URI from agent_env.task_step.context import StepContextError, TaskStepContext from agent_env.entity.refs import EntityRef @@ -68,7 +68,7 @@ def resolve_virtual_time(virtual_time: str, timezone: Optional[str]) -> str: "timezone") return parsed.astimezone(_utc_tz.utc).isoformat().replace("+00:00", "Z") except OverflowError as e: - raise ValueError(outside_range(f"virtual_time {virtual_time!r} in {zone.key}")) from e + raise ValueError(f"virtual_time {virtual_time!r} in {zone.key} is outside the times a datetime holds") from e class SyncEnvClockTaskStep(TaskStep): @@ -119,10 +119,10 @@ def __init__( self.armed_virtual_time = resolve_virtual_time(virtual_time, self.timezone) def config_problems(self) -> list[str]: - """A time or rate the gateway's clock would refuse to arm at, said before anything deploys.""" - shown = f"virtual_time {self.virtual_time!r}" + (f" in {self.timezone}" if self.timezone else "") + """A time or rate the gateway's clock would refuse to arm at whatever its followers, said before anything + deploys; a follower that holds only a range of times refuses one outside it when the step runs.""" try: - check_arm(self.armed_virtual_time, self.virtual_seconds_per_real_second, what=shown) + check_arm(self.armed_virtual_time, self.virtual_seconds_per_real_second) except ClockError as e: return [str(e)] return [] diff --git a/tst/env/gateway/clock_test.py b/tst/env/gateway/clock_test.py index 9a04538d9..b5969d898 100644 --- a/tst/env/gateway/clock_test.py +++ b/tst/env/gateway/clock_test.py @@ -234,32 +234,32 @@ def test_set_time_rejects_overflowing_t0(): c.set_time("9999-12-31T00:00:00Z", rate=1.0) -def test_set_time_allows_the_last_t0_when_frozen(): +def test_set_time_allows_max_t0_when_frozen(): c = Clock(now_fn=FakeNow()) - c.set_time("2262-04-11T23:47:16Z", rate=0) # frozen never advances - assert c.read()["virtual_time"] == "2262-04-11T23:47:16Z" + c.set_time("9999-12-31T00:00:00Z", rate=0) # frozen never advances + assert c.read()["virtual_time"] == "9999-12-31T00:00:00Z" -def test_read_stops_at_the_end_of_the_range_past_the_arm_time_horizon(): - """A t0 accepted by the horizon check still runs to the end if the gateway outlives it: reads stop there, not 500.""" +def test_read_saturates_past_the_arm_time_horizon(): + """A t0 accepted by the horizon check still overflows if the gateway outlives it — reads saturate, not 500.""" now = FakeNow() c = Clock(now_fn=now) - c.set_time("2262-04-11T22:47:16Z", rate=1.0) # accepted: a real hour of headroom - now.tick(3600.0 * 2) # ...but still up two real hours later - assert c.read()["virtual_time"] == "2262-04-11T23:47:16Z" - assert c.state()["virtual_time"] == "2262-04-11T23:47:16Z" + c.set_time("9999-12-30T00:00:00Z", rate=1.0) # accepted: >1 real day of headroom + now.tick(86400.0 * 2) # ...but still up two real days later + assert c.read()["virtual_time"] == "9999-12-31T23:59:59.999999Z" + assert c.state()["virtual_time"] == "9999-12-31T23:59:59.999999Z" -def test_a_clock_at_the_end_stays_monotonic(): +def test_saturated_clock_stays_monotonic(): now = FakeNow() c = Clock(now_fn=now) - c.set_time("2262-04-11T22:47:16Z", rate=1.0) + c.set_time("9999-12-30T00:00:00Z", rate=1.0) seen = [] for _ in range(4): - now.tick(1800.0) + now.tick(86400.0) seen.append(c.read()["virtual_time"]) assert seen == sorted(seen) - assert seen[-1] == "2262-04-11T23:47:16Z" + assert seen[-1] == "9999-12-31T23:59:59.999999Z" def test_elapsed_runs_at_each_arm_s_rate_and_counts_a_re_arm_forward_but_not_back(): diff --git a/tst/unit/env/envs/test_computer_clock_follower.py b/tst/unit/env/envs/test_computer_clock_follower.py index 86ee623a0..b07827cd4 100644 --- a/tst/unit/env/envs/test_computer_clock_follower.py +++ b/tst/unit/env/envs/test_computer_clock_follower.py @@ -19,7 +19,7 @@ import pytest import agent_env -from agent_env.env.gateway.clock import EARLIEST, LATEST +from agentenv_protocol.computer.clock import RANGE from agentenv_protocol.computer import clock as protocol_clock CLOCK = Path(agent_env.__file__).parent / "utils" / "faketime_clock" @@ -147,19 +147,22 @@ def test_the_clock_file_the_follower_writes_reads_as_its_universe_to_a_server_on assert protocol_clock.session_time() == pytest.approx(time.time(), abs=1) -def test_the_page_holds_the_env_clocks_range(): +def _range_ns(end: str) -> int: + return int(datetime.fromisoformat(RANGE[end].replace("Z", "+00:00")).timestamp()) * 10**9 + + +def test_the_page_holds_the_range_computers_declare(): clockpage = _clockpage(Path("/nonexistent")) - assert (clockpage.EARLIEST_NS, clockpage.LATEST_NS) == (int(EARLIEST.timestamp()) * 10**9, - int(LATEST.timestamp()) * 10**9) + assert (clockpage.EARLIEST_NS, clockpage.LATEST_NS) == (_range_ns("earliest"), _range_ns("latest")) def test_a_universe_outside_the_range_is_written_at_its_end_and_the_page_left_whole(tmp_path): """As a follower writes the clock of a gateway that outlives its range: a universe given past either end, or one - the page has run on past the end to when a re-anchoring continues it, is written at the end, where the gateway's - clock stops, and a write never fails halfway with the page left mid-write (seq odd).""" + the page has run on past the end to when a re-anchoring continues it, is written at the end, where libfaketime + stops too, and a write never fails halfway with the page left mid-write (seq odd).""" clockpage = _clockpage(tmp_path / "page") clockpage.FILE = str(tmp_path / "clock") - end = int(LATEST.timestamp()) * 10**9 + end = _range_ns("latest") def page() -> tuple[int, int, float]: fields = clockpage.LAYOUT.unpack((tmp_path / "page").read_bytes()) @@ -169,7 +172,7 @@ def page() -> tuple[int, int, float]: seq, universe_ns, _ = page() assert (seq % 2, universe_ns) == (0, end) clockpage.write(1, -9223372100.0, 1.0, time.time()) - assert page()[1] == int(EARLIEST.timestamp()) * 10**9 + assert page()[1] == _range_ns("earliest") clockpage.write(1, 9223372035.0, 1.0, time.time() - 1.95) clockpage.write(1, 9223372036.0, 0.0, time.time()) diff --git a/tst/unit/env/envs/test_multi_env_computers.py b/tst/unit/env/envs/test_multi_env_computers.py index 817dd1c63..ac11a9c94 100644 --- a/tst/unit/env/envs/test_multi_env_computers.py +++ b/tst/unit/env/envs/test_multi_env_computers.py @@ -331,6 +331,18 @@ async def test_deploy_hands_the_gateway_each_computer_deployed_under_its_name_wi ("gw", "modal_vm"), ("gw", "modal_vm"), ("sb-desktop", "modal_vm"), ("sb-laptop", "modal_vm")] +def test_a_computer_whose_card_declares_the_times_it_holds_hands_the_gateway_that_range(): + from agent_env.env.envs.computer.utils import clock as computer_clock + + held = {"earliest": "1677-09-21T00:12:44Z", "latest": "2262-04-11T23:47:16Z"} + ranged = dataclasses.replace(_record("desktop", clock=True), environment_card={"name": "desktop", "capabilities": { + "extensions": [{**CLOCK_CARD["capabilities"]["extensions"][0], "params": { + **CLOCK_CARD["capabilities"]["extensions"][0]["params"], "range": held}}]}}) + assert computer_clock.held_range(ranged) == held + assert computer_clock.held_range(_record("old", clock=True)) is None + assert computer_clock.held_range(_record("laptop")) is None + + def test_a_computer_whose_card_follows_a_clock_hands_the_gateway_its_control_token_as_its_read_token(): from agent_env.env.envs._multi_computers import _clock_read_token diff --git a/tst/unit/env/gateway/clock_range_test.py b/tst/unit/env/gateway/clock_range_test.py index 5b3d88840..9e4c2fbc3 100644 --- a/tst/unit/env/gateway/clock_range_test.py +++ b/tst/unit/env/gateway/clock_range_test.py @@ -1,135 +1,116 @@ -"""The env clock's range, the times 64 bits of nanoseconds since 1970 hold, as Python and the computers that follow the -clock keep time: the gateway arms and runs anywhere in it, before 1970 too and a day per second at today's dates, and -refuses a time outside it, however it's spelled, or arming the clock where it would run to the end within a real hour, -up front, naming the range. A clock that runs to the end anyway, on a gateway that outlives it or sped up in its last -hour, stands there.""" +"""The clock's followers that hold only a range of times (a computer's and a clock-following agent's card declare +clock/v1's ``range``, what 64 bits of nanoseconds since 1970 hold): while the clock has one, it refuses a set_time or an +advance outside that range, naming the follower, and a set_time it would run past the range's end from within a real +hour; a declaration the clock is outside now is refused. Without such a follower the clock is as it always was.""" from __future__ import annotations -import re -from datetime import datetime, timezone +import asyncio import pytest +from agentenv_protocol.computer.clock import RANGE -from agent_env.env.gateway.clock import EARLIEST, LATEST, Clock, ClockError, _iso, check_arm -from agent_env.env.gateway.constants import EXT_CLOCK_URI, GATEWAY_EXTENSIONS +from agent_env.env.gateway.clock import Clock, ClockError, parse_follower_range +from agent_env.env.gateway.clock_followers import ClockFollowers +from agent_env.env.gateway.entrypoint import parse_clock_follower_ranges from tst.unit.env.gateway.triggers_time_test import FakeNow -RANGE = "the env clock's range, 1677-09-21T00:12:44Z to 2262-04-11T23:47:16Z" -END = "would pass 2262-04-11T23:47:16Z, the end of the env clock's range, within a real hour" +HELD = parse_follower_range(RANGE) +DESKTOP = "clock follower 'desktop' holds, 1677-09-21T00:12:44Z to 2262-04-11T23:47:16Z" -def _refused(message: str): - return pytest.raises(ClockError, match=re.escape(message)) +def _clock(held: dict | None = None, tokens: dict | None = None) -> tuple[Clock, ClockFollowers, FakeNow]: + now = FakeNow() + followers: ClockFollowers | None = None + clock = Clock(now_fn=now, follower_ranges=lambda: followers.held()) + followers = ClockFollowers(lambda: clock, tokens if tokens is not None else dict.fromkeys(held or {}, "token"), held) + return clock, followers, now -def test_the_range_is_the_whole_seconds_64_bits_of_nanoseconds_since_1970_hold(): - first, last = int(EARLIEST.timestamp()), int(LATEST.timestamp()) +def test_the_range_computers_and_agents_declare_is_what_64_bits_of_nanoseconds_since_1970_hold(): + first, last = int(HELD.earliest.timestamp()), int(HELD.latest.timestamp()) assert (first - 1) * 10**9 < -2**63 <= first * 10**9 assert last * 10**9 <= 2**63 - 1 < (last + 1) * 10**9 -@pytest.mark.parametrize("virtual_time, rate", [ - ("1677-09-21T00:12:44Z", 1), ("1900-01-01T00:00:00Z", 60), ("1949-12-31T23:59:59.750000Z", 1), - ("2026-11-23T12:00:00Z", 86400), ("2262-04-11T22:47:16Z", 1), ("2262-04-11T23:47:16Z", 0)]) -def test_the_clock_arms_and_runs_anywhere_in_its_range(virtual_time, rate): - now = FakeNow() - clock = Clock(now_fn=now) - - assert clock.set_time(virtual_time, rate=rate)["virtual_time"] == virtual_time - now.tick(1) - assert clock.read()["virtual_time"] >= virtual_time +@pytest.mark.parametrize("virtual_time", ["1600-01-01T00:00:00Z", "2262-04-11T23:47:17Z", "3026-11-23T12:00:00Z", + "9999-06-01T12:00:00Z"]) +def test_without_a_follower_that_holds_a_range_the_clock_arms_anywhere_a_datetime_holds(virtual_time): + for clock in (_clock()[0], _clock(tokens={"desktop": "token"})[0]): + assert clock.set_time(virtual_time)["virtual_time"] == virtual_time -@pytest.mark.parametrize("virtual_time", [ - "0001-01-01T00:00:00Z", "1600-01-01T00:00:00Z", "1677-09-21T00:12:43Z", "2262-04-11T23:47:17Z", - "3026-11-23T12:00:00Z", "9999-12-31T23:59:59Z", "10000-01-01T00:00:00Z", "0000-01-01T00:00:00Z", - "0001-01-01T00:00:00+01:00", "9999-12-31T23:59:59-01:00", "1677-09-21T00:12:44+00:01"]) -def test_a_time_outside_the_range_is_refused_naming_it_however_its_spelled(virtual_time): - with _refused(f"virtual_time '{virtual_time}' is outside {RANGE}"): - Clock(now_fn=FakeNow()).set_time(virtual_time, rate=0) +def test_without_one_the_clock_still_refuses_what_it_always_did(): + with pytest.raises(ClockError, match="would overflow datetime near the max"): + _clock()[0].set_time("9999-12-31T12:00:00Z") -@pytest.mark.parametrize("virtual_time", ["10000-junk", "999-01-01T00:00:00Z", "2026-13-01T00:00:00Z"]) -def test_a_string_that_isnt_a_time_is_refused_as_one(virtual_time): - with _refused(f"invalid RFC3339 virtual_time '{virtual_time}'"): - Clock(now_fn=FakeNow()).set_time(virtual_time, rate=0) +@pytest.mark.parametrize("virtual_time", ["0001-01-01T00:00:00Z", "1677-09-21T00:12:43Z", "2262-04-11T23:47:17Z", + "3026-11-23T12:00:00Z", "9999-06-01T12:00:00Z"]) +def test_a_time_outside_a_followers_range_is_refused_naming_it(virtual_time): + clock, _, _ = _clock({"desktop": HELD}) + with pytest.raises(ClockError, match=f"virtual_time '{virtual_time}' is outside the times {DESKTOP}"): + clock.set_time(virtual_time, rate=0) + assert not clock.state()["armed"] -def test_arming_a_clock_that_would_pass_the_end_within_a_real_hour_names_it(): - with _refused(f"virtual_time '2262-04-11T23:00:00Z' at rate 1 {END}"): - Clock(now_fn=FakeNow()).set_time("2262-04-11T23:00:00Z") - - -def test_however_slow_a_clock_runs_from_the_end_it_would_pass_it(): - with _refused(f"virtual_time '2262-04-11T23:47:16Z' at rate 1e-10 {END}"): - Clock(now_fn=FakeNow()).set_time("2262-04-11T23:47:16Z", rate=1e-10) - - -def test_a_clock_frozen_in_its_last_real_hour_starts_again_and_runs_to_the_end(): - """As always_on runs one: frozen between turns, advanced while frozen to a due event, then run at the task's rate - for the next turn.""" - now = FakeNow() - clock = Clock(now_fn=now) - clock.set_time("2262-04-11T22:40:00Z") - now.tick(60) - clock.set_rate(0) - clock.advance("2262-04-11T23:00:00Z") - - assert clock.set_rate(1)["virtual_seconds_per_real_second"] == 1 - now.tick(40 * 60) - assert clock.read() == {"virtual_time": "2262-04-11T23:40:00Z"} - now.tick(10 * 60) - state = clock.state() - assert (state["virtual_time"], state["virtual_seconds_per_real_second"]) == ("2262-04-11T23:47:16Z", 0.0) - - -def test_in_its_last_real_hour_a_running_clock_takes_any_advance_or_rate_and_stands_at_the_end(): - now = FakeNow() - clock = Clock(now_fn=now) - clock.set_time("2262-04-11T22:47:16Z") - - assert clock.advance("2262-04-11T23:30:00Z")["virtual_time"] == "2262-04-11T23:30:00Z" - assert clock.set_rate(86400)["virtual_seconds_per_real_second"] == 86400 +@pytest.mark.parametrize("virtual_time, rate", [("1677-09-21T00:12:44Z", 1), ("1949-12-31T23:59:59.750000Z", 1), + ("2026-11-23T12:00:00Z", 86400), ("2262-04-11T22:47:16Z", 1), + ("2262-04-11T23:47:16Z", 0)]) +def test_the_clock_arms_anywhere_in_a_followers_range(virtual_time, rate): + clock, _, now = _clock({"desktop": HELD}) + assert clock.set_time(virtual_time, rate=rate)["virtual_time"] == virtual_time now.tick(1) - assert clock.now() == LATEST - with _refused(f"virtual_time '2262-04-11T23:47:17Z' is outside {RANGE}"): - clock.advance("2262-04-11T23:47:17Z") - - -def test_a_clock_armed_frozen_at_the_end_takes_a_rate_as_one_that_ran_there_does(): - clock = Clock(now_fn=FakeNow()) - clock.set_time("2262-04-11T23:47:16Z", rate=0) - state = clock.set_rate(1e-10) - assert (state["virtual_time"], state["virtual_seconds_per_real_second"]) == ("2262-04-11T23:47:16Z", 0.0) + assert clock.read()["virtual_time"] >= virtual_time -def test_a_clock_that_outlives_its_range_stands_at_the_end_and_can_still_be_frozen_or_set_back(): - """Its reads and state stop at the end, at rate 0, so the computers that follow it stop there too rather than run - past what their clock page holds.""" - now = FakeNow() - clock = Clock(now_fn=now) - clock.set_time("2262-04-11T22:47:16Z") - now.tick(3601) - assert clock.read() == {"virtual_time": "2262-04-11T23:47:16Z"} - state = clock.state() - assert (state["virtual_time"], state["virtual_seconds_per_real_second"]) == ("2262-04-11T23:47:16Z", 0.0) - now.tick(10**9) - assert clock.now() == LATEST - - assert clock.advance("2262-04-11T23:47:16Z")["virtual_time"] == "2262-04-11T23:47:16Z" - assert clock.set_rate(1)["virtual_time"] == "2262-04-11T23:47:16Z" - assert clock.set_rate(0)["virtual_time"] == "2262-04-11T23:47:16Z" - with _refused("advance only moves forward"): - clock.advance("2262-04-11T23:00:00Z") - assert clock.set_time("2026-11-23T12:00:00Z")["virtual_time"] == "2026-11-23T12:00:00Z" - - -def test_a_check_names_the_time_as_its_caller_wrote_it(): - with _refused(f"virtual_time '1677-09-21T05:00:00' in Asia/Tokyo is outside {RANGE}"): - check_arm("1677-09-20T19:41:01Z", 0, what="virtual_time '1677-09-21T05:00:00' in Asia/Tokyo") - assert check_arm("2026-11-23T12:00:00Z", 60) == (datetime(2026, 11, 23, 12, tzinfo=timezone.utc), 60.0) - - -def test_the_clock_card_states_the_range(): - clock = next(ext for ext in GATEWAY_EXTENSIONS if ext["uri"] == EXT_CLOCK_URI) - assert f"{_iso(EARLIEST)} to {_iso(LATEST)}" in clock["description"] +def test_arming_a_clock_that_would_run_past_a_followers_range_within_a_real_hour_is_refused(): + clock, _, _ = _clock({"desktop": HELD}) + with pytest.raises(ClockError, match=f"at rate 1 would pass the end of the times {DESKTOP}, within a real hour"): + clock.set_time("2262-04-11T23:00:00Z") + with pytest.raises(ClockError, match="at rate 86400 would pass the end"): + clock.set_time("2255-01-01T00:00:00Z", rate=86400) + + +def test_an_advance_past_a_followers_range_is_refused_and_one_into_its_last_hour_or_a_rate_change_is_not(): + clock, _, _ = _clock({"desktop": HELD}) + clock.set_time("2262-04-01T00:00:00Z") + with pytest.raises(ClockError, match=f"virtual_time '2262-04-12T00:00:00Z' is outside the times {DESKTOP}"): + clock.advance("2262-04-12T00:00:00Z") + assert clock.read()["virtual_time"] == "2262-04-01T00:00:00Z" + assert clock.advance("2262-04-11T23:00:00Z")["virtual_time"] == "2262-04-11T23:00:00Z" + assert clock.set_rate(3600)["virtual_seconds_per_real_second"] == 3600 + + +def test_a_declared_agent_brings_its_range_and_takes_it_away_when_retired(): + clock, followers, _ = _clock() + clock.set_time("2026-11-23T12:00:00Z") + followers.declare("agent-solver", "token", HELD) + assert followers.state()["agent-solver"]["range"] == RANGE + with pytest.raises(ClockError, match="is outside the times clock follower 'agent-solver' holds"): + clock.set_time("3026-01-01T00:00:00Z") + assert asyncio.run(followers.retire("agent-solver")) + assert clock.set_time("3026-01-01T00:00:00Z")["virtual_time"] == "3026-01-01T00:00:00Z" + + +def test_an_agent_whose_range_the_clock_is_outside_now_is_refused_and_one_that_declares_none_is_not(): + clock, followers, _ = _clock() + clock.set_time("3026-01-01T00:00:00Z") + with pytest.raises(ClockError, match="the clock, at 3026-01-01T00:00:00Z, is outside the times clock follower " + "'agent-solver' holds, 1677-09-21T00:12:44Z to 2262-04-11T23:47:16Z"): + followers.declare("agent-solver", "token", HELD) + assert "agent-solver" not in followers.state() + followers.declare("agent-old", "token") + assert "range" not in followers.state()["agent-old"] + assert clock.set_time("9000-01-01T00:00:00Z")["virtual_time"] == "9000-01-01T00:00:00Z" + + +def test_the_gateway_reads_each_computers_range_from_its_start_environment(): + assert parse_clock_follower_ranges( + "desktop=1677-09-21T00:12:44Z/2262-04-11T23:47:16Z, browser=1950-01-01T00:00:00Z/2100-01-01T00:00:00Z") == { + "desktop": HELD, "browser": parse_follower_range({"earliest": "1950-01-01T00:00:00Z", + "latest": "2100-01-01T00:00:00Z"})} + assert parse_clock_follower_ranges("") == {} + for spec in ("desktop", "desktop=1677-09-21T00:12:44Z", "desktop=2262-04-11T23:47:16Z/1677-09-21T00:12:44Z", + "desktop=yesterday/today"): + with pytest.raises(ValueError, match="CLOCK_FOLLOWER_RANGES"): + parse_clock_follower_ranges(spec) diff --git a/tst/unit/env/gateway/get_time_test.py b/tst/unit/env/gateway/get_time_test.py index ad9f734e6..65be7d6c4 100644 --- a/tst/unit/env/gateway/get_time_test.py +++ b/tst/unit/env/gateway/get_time_test.py @@ -20,7 +20,6 @@ from agent_env.env.gateway.constants import DEFAULT_ROLE from agent_env.env.gateway.get_time import GET_TIME_TOOL_DESCRIPTION, GET_TIME_TOOL_NAME from agent_env.env.gateway.gateway import Gateway -from tst.unit.env.gateway.triggers_time_test import FakeNow T = "2019-06-15T12:00:00Z" @@ -275,22 +274,20 @@ def test_local_time_is_the_same_reading_at_second_precision(gw): @pytest.mark.asyncio -@pytest.mark.parametrize("arm, rate, real_s, zone, now", [ - ("2026-01-01T00:00:00Z", 86400, 1e9, "Asia/Tokyo", "2262-04-11T23:47:16Z"), - ("1677-09-21T00:12:44Z", 0, 0, "America/New_York", "1677-09-21T00:12:44Z"), -], ids=["a-gateway-that-outlives-the-range", "the-start-of-the-range"]) -async def test_every_time_the_clock_holds_shows_in_any_zone(gw, arm, rate, real_s, zone, now): - """The clock stays within its range, even on a gateway that outlives it, and every zone's clock shows its ends.""" - real = FakeNow() - gw._clock = Clock(now_fn=real) - gw._clock.set_time(arm, rate) - real.tick(real_s) +@pytest.mark.parametrize("now, zone", [ + ("9999-12-31T20:00:00Z", "Asia/Tokyo"), + ("0001-01-01T02:00:00Z", "America/New_York"), +], ids=["after-the-last-date", "before-the-first-date"]) +async def test_a_time_the_zone_cannot_show_is_a_tool_error_naming_it(gw, now, zone): + gw._clock.set_time(now, 0) gw._register_get_time_tool() + message = f"the current time {now} can't be shown in time zone {zone!r}: its local date is out of range" - payload = await _mcp_call(gw, {"time_zone": zone}) - reading = json.loads(payload["content"][0]["text"]) - assert reading["current_time"] == now and reading["time_zone"] == zone - assert datetime.fromisoformat(reading["local_time"]) == datetime.fromisoformat(now) + assert await _mcp_call(gw, {"time_zone": zone}) == { + "content": [{"type": "text", "text": message}], "isError": True} + status, body = await _step_call(gw, {"time_zone": zone}) + assert (status, json.loads(body)) == ( + 200, {"content": [{"type": "text", "text": message}], "isError": True, "changelog_id": None}) def test_the_description_keeps_tool_dates_in_utc_and_gives_the_users_clock_when_their_zone_is_known(): diff --git a/tst/unit/providers/env_providers/env_gateway_provider_test.py b/tst/unit/providers/env_providers/env_gateway_provider_test.py index 89d08c54a..ae8a096d4 100644 --- a/tst/unit/providers/env_providers/env_gateway_provider_test.py +++ b/tst/unit/providers/env_providers/env_gateway_provider_test.py @@ -2931,6 +2931,24 @@ def test_compose_declares_the_children_that_follow_the_clock_by_their_read_token assert "read-desk" not in redacted and " - CLOCK_FOLLOWER_TOKENS=***" in redacted +def test_compose_hands_the_gateway_the_times_each_follower_that_holds_a_range_holds(): + from agent_env.env.envs.service_db import ServiceDBConfig + from agent_env.env.gateway import ExternalChild + + held = {"earliest": "1677-09-21T00:12:44Z", "latest": "2262-04-11T23:47:16Z"} + rendered = EnvironmentGatewayProvider().create_docker_compose( + mcp_servers=[], gateway_image="agent-gateway", + state_provider=LocalPostgresStateProvider(service_db_config=ServiceDBConfig()), + state_instance=LocalPostgresStateProvider.default_instance(), + external_children=(ExternalChild("desktop", "https://desk.example/mcp", "https://desk.example", "read-desk", held), + ExternalChild("old", "https://old.example/mcp", "https://old.example", "read-old"), + ExternalChild("phone", "https://phone.example/mcp", "https://phone.example", None, held))) + + environment = yaml.safe_load(rendered)["services"][GATEWAY_SERVICE_NAME]["environment"] + assert [item for item in environment if item.startswith("CLOCK_FOLLOWER_RANGES=")] == [ + "CLOCK_FOLLOWER_RANGES=desktop=1677-09-21T00:12:44Z/2262-04-11T23:47:16Z"] + + def test_no_service_depends_on_the_gateway_so_a_vm_deploy_can_start_them_all_before_it(): """A VM deploy with children runs ``compose up --scale gateway=0`` first, which starts a service that depends on the gateway with it, before its children answer.""" diff --git a/tst/unit/task_step/agent_clock_test.py b/tst/unit/task_step/agent_clock_test.py index 1b020bad6..fdc349132 100644 --- a/tst/unit/task_step/agent_clock_test.py +++ b/tst/unit/task_step/agent_clock_test.py @@ -68,6 +68,65 @@ async def test_an_agent_is_declared_a_follower_then_handed_its_config_with_the_s assert (agent["agent"], agent["synced"], agent["follower"]) == ("solver", True, "agent-solver") +HELD = {"earliest": "1677-09-21T00:12:44Z", "latest": "2262-04-11T23:47:16Z"} + + +def _ranged_agent() -> DeployedAgent: + sync = {"uri": EXT_CLOCK_URI, "params": {"endpoint": "/ext/clock", "methods": {"sync_time": SYNC_TIME}, "range": HELD}} + return dataclasses.replace(_agent(), a2a_card={"capabilities": {"extensions": [sync]}}) + + +def _refusing_declarations(monkeypatch, error: str) -> list: + """Record every request, as _mock_http does, the gateway refusing every declare_follower with ``error``.""" + import httpx + + sent, real = [], httpx.AsyncClient + + def handle(request: httpx.Request) -> httpx.Response: + sent.append(request) + if request.url.path.endswith("/clock/followers") and request.method == "PUT": + return httpx.Response(400, json={"ok": False, "error": error}) + return httpx.Response(200, json={"env_get_time_url": CLOCK_URL} if request.url.path.endswith("/clock/state") else {}) + + monkeypatch.setattr(httpx, "AsyncClient", lambda *a, **k: real(transport=httpx.MockTransport(handle))) + return sent + + +@pytest.mark.asyncio +async def test_an_agent_whose_card_declares_the_times_it_holds_brings_that_range_to_the_gateway(monkeypatch): + sent = _mock_http(monkeypatch, state={"env_get_time_url": CLOCK_URL}) + _no_servers(monkeypatch) + context = await _context(_ranged_agent()) + + await _step().execute(context) + + [declared] = [r for r in sent if r.method == "PUT" and r.url.path.endswith("/clock/followers")] + assert json.loads(declared.content)["range"] == HELD + + +@pytest.mark.asyncio +@pytest.mark.parametrize("required", [False, True]) +async def test_an_agent_the_gateway_refuses_for_its_range_is_reported_and_skipped_or_fails_the_step(monkeypatch, + required): + refusal = ("the clock, at 3026-01-01T00:00:00Z, is outside the times clock follower 'agent-solver' holds, " + "1677-09-21T00:12:44Z to 2262-04-11T23:47:16Z") + sent = _refusing_declarations(monkeypatch, refusal) + _no_servers(monkeypatch) + context = await _context(_ranged_agent()) + step = SyncEnvClockTaskStep(id="sync", version=1, env_id="e1", virtual_time="3026-01-01T00:00:00Z", + agent_clock=True, require_agent_clock=required, depends_on=[]) + + if required: + with pytest.raises(StepContextError, match="agent 'solver' can't follow the clock of env 'e1': outside_range: " + "the clock, at 3026"): + await step.execute(context) + else: + await step.execute(context) + [agent] = context.metadata["clock_configurations"][0]["agents"] + assert (agent["synced"], agent["reason"]) == (False, f"outside_range: {refusal}") + assert not [r for r in sent if r.url.path.endswith("/ext/clock/sync-time")] + + @pytest.mark.asyncio async def test_only_the_agents_registered_with_the_env_follow_its_clock(monkeypatch): sent = _mock_http(monkeypatch, state={"env_get_time_url": CLOCK_URL}) diff --git a/tst/unit/task_step/sync_env_clock_test.py b/tst/unit/task_step/sync_env_clock_test.py index 01ce8a924..28bedc2cb 100644 --- a/tst/unit/task_step/sync_env_clock_test.py +++ b/tst/unit/task_step/sync_env_clock_test.py @@ -6,7 +6,6 @@ import pytest from agent_env.env.env import DeployedEnv, DeployedGatewayEnv, DeployedSandboxEnv -from agent_env.env.gateway.clock import outside_range from agent_env.env.gateway.constants import EXT_CLOCK_URI, WELL_KNOWN_PATH from agent_env.task import Task from agent_env.task.lint import lint @@ -16,7 +15,6 @@ T0 = "2026-01-01T00:00:00Z" CLOCK_URL = "http://gateway:9000/clock/time" -RANGE = "the env clock's range, 1677-09-21T00:12:44Z to 2262-04-11T23:47:16Z" def _step(**kw): @@ -348,17 +346,15 @@ def test_a_time_that_disagrees_with_the_zone_is_refused(virtual_time, zone, matc @pytest.mark.parametrize("virtual_time, zone", [("0001-01-01T00:00:00", "Asia/Kolkata"), ("9999-12-31T23:00:00", "America/Chicago")]) -def test_a_wall_time_whose_instant_no_date_holds_is_refused_naming_the_clocks_range(virtual_time, zone): - with pytest.raises(ValueError, match=re.escape(f"virtual_time '{virtual_time}' in {zone} is outside {RANGE}")): +def test_a_wall_time_whose_instant_no_date_holds_is_refused_saying_so(virtual_time, zone): + with pytest.raises(ValueError, match=re.escape(f"virtual_time '{virtual_time}' in {zone} is outside the times a " + "datetime holds")): _zoned(virtual_time, zone) @pytest.mark.parametrize("kwargs, problem", [ - ({"virtual_time": "3026-01-01T00:00:00Z"}, f"virtual_time '3026-01-01T00:00:00Z' is outside {RANGE}"), - ({"virtual_time": "1677-09-21T05:00:00", "timezone": "Asia/Tokyo"}, - f"virtual_time '1677-09-21T05:00:00' in Asia/Tokyo is outside {RANGE}"), - ({"virtual_time": "2262-04-11T23:00:00Z"}, - "virtual_time '2262-04-11T23:00:00Z' at rate 1 would pass 2262-04-11T23:47:16Z, the end of the env clock's range"), + ({"virtual_time": "9999-12-31T12:00:00Z"}, + "virtual_time '9999-12-31T12:00:00Z' at rate 1 would overflow datetime near the max"), ({"virtual_time": "2026-01-01T12:00:00"}, "invalid RFC3339 virtual_time '2026-01-01T12:00:00'"), ({"virtual_time": T0, "virtual_seconds_per_real_second": -1}, "rate must be non-negative"), ]) @@ -368,16 +364,17 @@ def test_a_time_or_rate_the_gateway_would_refuse_is_a_problem_before_anything_de def test_lint_names_the_step_of_a_time_the_gateway_would_refuse_once(): - step = SyncEnvClockTaskStep(id="clock", version=1, env_id="e1", virtual_time="3026-01-01T00:00:00Z", depends_on=[]) + step = SyncEnvClockTaskStep(id="clock", version=1, env_id="e1", virtual_time="2026-01-01T12:00:00", depends_on=[]) found = [finding.text for finding in lint(Task(id="t", version=1, steps=[step])) if finding.rule == "step-config"] - assert found == ["step 'clock': " + outside_range("virtual_time '3026-01-01T00:00:00Z'")] + assert found == ["step 'clock': invalid RFC3339 virtual_time '2026-01-01T12:00:00': expected " + "YYYY-MM-DDThh:mm:ss[.fff](Z|+hh:mm)"] def test_a_time_the_gateway_arms_at_is_no_problem(): assert _step().config_problems() == [] assert _step(virtual_seconds_per_real_second=0).config_problems() == [] - assert SyncEnvClockTaskStep(id="sync", version=1, env_id="e1", virtual_time="2262-04-11T23:47:16Z", - virtual_seconds_per_real_second=0).config_problems() == [] + for far in ("1600-01-01T00:00:00Z", "3026-01-01T00:00:00Z", "9999-06-01T00:00:00Z"): + assert SyncEnvClockTaskStep(id="sync", version=1, env_id="e1", virtual_time=far).config_problems() == [] assert _zoned("1677-09-21T09:31:43", "Asia/Tokyo").config_problems() == [] From ceea964ff42f7f18c03e475564c77a4d06420ada Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Tue, 24 Nov 2026 09:39:01 -0800 Subject: [PATCH 12/16] fix(clock): a follower's range refusals say what they refuse, and a bad range never stops the gateway Fixes from testing the per-follower clock ranges, the design unchanged: - declare_follower refuses a ranged follower the clock would run past the end of from within a real hour, as set_time refuses arming with it, so arming first and declaring the agent after no longer gets around the horizon. - Its range refusals carry error code outside_range, and follow() reports only those as outside_range: any other refusal (a name a start follower holds) raises as it does for an agent with no range. - Core parses a computer's or an agent's card range itself; one that doesn't parse is logged and left out, as a card that declares none, rather than crash-looping the gateway at boot (CLOCK_FOLLOWER_RANGES) or being sent to declare_follower. - A range that doesn't parse is refused naming "range earliest" or "range latest", not virtual_time. - set_time checks an unknown time zone before overflow again, as main does. - ExternalChild holds the parsed FollowerRange, so it stays hashable. set_rate stays unchecked: a horizon check there would refuse always_on starting a clock it froze near the end again. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- src/agent_env/a2a_agent/clock.py | 24 +++++--- .../env/envs/computer/utils/clock.py | 15 ++++- src/agent_env/env/gateway/__init__.py | 7 ++- src/agent_env/env/gateway/clock.py | 57 +++++++++++++------ src/agent_env/env/gateway/clock_followers.py | 13 ++--- src/agent_env/env/gateway/constants.py | 5 +- src/agent_env/env/gateway/gateway.py | 5 +- .../env_providers/env_gateway_provider.py | 2 +- tst/unit/env/envs/test_multi_env_computers.py | 30 ++++++++-- tst/unit/env/gateway/clock_range_test.py | 37 +++++++++++- tst/unit/env/gateway/clock_watch_test.py | 19 +++++++ .../env_gateway_provider_test.py | 3 +- tst/unit/task_step/agent_clock_test.py | 39 +++++++++++-- 14 files changed, 205 insertions(+), 53 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 9b1b2fa3b..cd81057c2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -149,7 +149,7 @@ and deserialized through a registry. | Package | Contents | |---|---| -| `env/` | `Env` base class: a subclass declares `type`, implements `from_dict` and `async deploy(...) -> DeployedEnv`, and may override `reset`, `close` and `load_file_artifact_universe`; teardown closes each env a run deployed before terminating its sandboxes by id. Built-ins in `env/envs/`: `MCPServerEnv` (`mcp_server`), `MultiEnv` (`multi`, MCP servers plus websites and computers; its website browser is the one its `browser_envs` names, none for `[]`, else the run's when it has websites: an MCP server env such as `playwright-mcp` runs among the gateway's MCP servers, and a browser computer such as `chromium` on a sandbox of its own as one more computer child, sized by its `child_envs` entry, its tools under its name and `_`, routing the multi env's synthetic sites unless that entry's `site_routing` says, its network its own env's, as any computer child's; a website env deployed alone refuses a browser computer as the run's browser), `ServiceDBEnv` (`service_db`, PostgreSQL), `WebsiteEnv` (`website`, one site: a server image, `backend_image` in its env.toml, serving the pages and API, ready when its card's `website/v1` `ready` answers a `WebsiteReadiness` that says so, as `agentenv_protocol.website` (`website_readiness`, `env_readiness`) defines a website env's health for the deploy and `DeployedEnv.readiness()` alike, or, for a card without `ready`, when its `health` path answers 200, which is deprecated; its env.toml's `ready_timeout_s`, how long it may take from its server's container starting to ready, is that container's health check `start_period` and what the deploy waits, or its card's `ready` timeout if longer, and its `shm_mb` is the container's `shm_size`, each left to the gateway and Docker without them; the gateway container's `env/gateway/constants.py` mirrors the URI and op, a test keeping them equal; a separate frontend image is deprecated, warned of at put and optional in a bundle, and a stored `backend_docker_image_artifact` reads as the server image; a live one, `live = true`, is a real site whose server serves none of its pages, its `live`, `domains` and `allow_hosts` read at put from its server's `@website(...)` (`utils/card_naming.py` `WebsiteSource`) unless given, its `settings`' secrets only as references the gateway resolves as it writes the site's container (`WEBSITE_SETTINGS_ENV`); the gateway gives it no site route, a computer's site table leaves it out, a computer whose network is an allowlist is let reach its names (`MultiEnv.live_hosts`), a browser alone's forward port takes them straight to the real site (`site_proxy.py` `direct`), as the browser base's stand-in proxy takes any host, refusing nothing, each proxy logging each such connection as a JSON line, and a run that deploys one is marked live, `reproducible: false`), `GatewayEnv` (`gateway_server`), `ComputerDriverEnv` (`computer_driver`, `env/envs/computer/driver_env.py`: a computer driver's files and what its class declares for each platform it supports, read at put in a process of its own, `agentenv_protocol.computer._declare`, where the driver's own dependencies needn't be installed, with the `port` it serves on and its install by OS, `[install.]`, or for one distribution `[install."/"]`, which replaces its OS type's there, as its `known_failures` do (`env/envs/computer/utils/install.py`): files, apt `packages` with extra `sources`, a `python` requirements file for a venv, `downloads` by URL and sha256, `run` scripts, the services the base's init runs, and `ports`; it deploys only as a computer env's driver), `ComputerEnv` (`computer`, in `env/envs/computer/`: a base computer and a driver, matched at put by gate 1 before anything is stored, then composed by `composer.py` into an image for each form and arch on a builder of the put's sandbox provider, by default the env's (`utils/builder.py`; `--sandbox` on `env build`): this machine's Docker for `local`, else a VM of the provider, which fetches the put's stored files by signed URL, takes the rest inline and pushes to the image store itself, so it builds only with stores a remote VM reaches; each arch goes to the first link that runs it natively, else one that emulates it (a VM registers QEMU; `--no-emulate` leaves it `skipped` instead, for a later put), and its pair records the provider that built it (`builder`); a run or register composes only the computer envs its tasks deploy (`materialize._composed_envs`: each env a task's steps name, and each env those hold but a computer env's own apps and driver, which run inside it) and those it pulls in from an installed bundle, whose one write every bundle shares, every one for a plan with no tasks, any other composing at its first deploy; one that reuses a computer env composes what it has left (`pending`), a run, and a register given a `--sandbox`, only the forms its sandbox's deploys boot (`booted_forms`: on each link, the first form it boots natively, by the deploy's own rule, `boot.first_native`; a compose of a disk adds its container), and a deploy composes first what it boots that no compose started, and a container it runs natively that was built but not probed, as one whose probe a setting that didn't resolve stopped, booting it only once ready (`ComputerEnv.compose_unstarted`); tagged `agentenv-computers:` in the image store by a key of the image's Dockerfile, build context and lock so any env with the same inputs reuses it; every layer's packages, requirements and downloads are resolved at put in a container of the base for each arch (`utils/packages.py`, `utils/resolve_in_base.py`), stored in the object store by sha256 under `agentenv-packages/`, and listed in a lock stored by a digest of its inputs, which any env with the same inputs reuses, and builds install only the lock's files, every install step `RUN --network=none`; each pair's status goes into its metadata, `composed`, the arches built are written as its computer, a `computer` artifact over one index, and `agent-env env build` resumes what a put left; gate 3 (`utils/probing.py`) then boots each native build on the put's sandbox provider and probes it at `full`, making it `ready` or `failed`, and a build no provider runs natively stays `unverified`. Its deploy, through the `computer` env provider (`providers/env_providers/env_computer_provider.py`), boots its first `ready` build on a sandbox provider that runs its arch natively (`native_platforms()`), with no gateway in front and the driver's card as the env card, its `/dev/shm` the most its apps' Linux installs ask for (`shm_mb`, in MiB, which its composed computer and the deploy record keep; `--shm-size` on a container, `AGENTENV_SHM_MB` read by a Linux disk's init, passed only to a provider whose `SHARED_MEMORY` says it gives that much, else the sandbox's default, which the deploy logs), then checks its `display`; `deploy_env` `env_params` take a `form`, `computer_settings` (deploy-phase values of the base's settings; a secret one, here or on the env, only as a bare `secret:`/`env:` reference) and `driver_settings` (the driver's `ComputerSettings`, such as its default coordinate space); a `network` that allows nothing runs it on local Docker's internal network behind a relay (`providers/sandbox_providers/local_docker/relay/`); `reset` and `close` have the driver end its recordings first (`computer-recording/v1` `end_all`, each uploading what's left and its manifest under the grant it started with), and `reset` then boots a fresh container in its place (`reset_container`), keeping the computer's address but not an agent's MCP session to the old driver; its `load_file_artifact_universe` writes files under the session user's home through the driver's `data/add`, `Downloads` by default, each file's bytes through a read grant when the store's grants reach it and its network allows everything, else inline (`env/envs/computer/utils/inside.py`)), `ComputerAppEnv` (`computer_app`, `env/envs/computer/app_env.py`: an app on a computer, a `ComputerAppEnvironment` class its env.toml's `module` names, read at put by the same `_declare`, which declares each OS with its own decorator (`@linux(...)`, or `@install(os_type, spec)` for any OS type; `@linux(distribution=...)` or `@install("/", spec)` for one distribution, which replaces its OS type's there) holding its install, its launch and, optionally, a skill and settings and build settings that add to the class's there, and install steps and ready checks for every OS or those their `os=` names; everything that reads its settings, launch or steps asks for the computer's OS type; deployed alone it is a one-app computer env, a `ComputerEnv` of the computer and driver its env.toml names, the composer installing it under `/opt/agentenv/apps//` with its services as supervisord programs beside its own server (`agentenv_protocol.computer.serve_app`, in a venv with the protocol's `app` extra, on `.agentenv/server.sock` in its folder), which adds its launcher, launches a `boot` app once per boot and says through `computer-app/v1` whether it's ready, as the driver's `computer-ready` asks, its card named after it, and `env_params` `app_settings` handing it values of its `Settings` in `AGENTENV_APP_SETTINGS`, a secret one only as a bare reference, over its env.toml's `[settings]` and a computer env's `settings` beside it in `apps`, each by top-level field (`params.app_settings`; checked at put, a required one left to the deploy; the deploy record keeps the merged values as `app_settings`, secrets withheld); its env.toml's `build_settings`, values of its `BuildSettings` checked at put, are written to `.agentenv/build_settings.json` in its folder, so they're part of the image's key, its install steps read them, and a deploy can't change them). An env type whose services take environment data defines `load_environment_artifact` and `load_environment_universe_artifact`; `load_artifact` refuses an environment artifact aimed at a type that doesn't, at save and before it loads. An env built on the protocol SDK can serve agents a skill (`@agent_skill`, `skill/v1`), which `add_skills` `env_ids` installs under its environment name (behind a gateway, each server's under that server's name); a skill with files beside its SKILL.md goes as a bundle stored once per content under `agentenv-env-skills/` in the object store. `env/gateway/gateway.py` is the env-side gateway server, container-only code. Its site route, `/website//`, never forwards a site's data plane or card (`/agentenv/…`, `/.well-known/agent-env.json`), which agentenv reaches through `/svc//`; a site with no frontend image is served by its server image there. A request from a computer's site proxy names its computer (`AgentEnv-Computer`, sent from the proxy's private upstream headers, a page's own copy and any `AgentEnv-Role` it sends dropped) and takes the role driving that computer now (the gateway's computers being those `COMPUTERS` names, a multi env's, with or without a control token): the last to make an input call to its tools, as the call starts, through `/mcp`, `/step` or a trigger action under its `as` (`Gateway._drive`); without one, or from a computer the gateway doesn't front, it is `default`, the role read once per request. `changes/v1` (`ChangeAttribution`) counts no write window for a call to a computer's tools, a trigger action's included, so a write the computer's browser made goes to its request and one another party made during the call to that party. Its CDP route, `/browser//cdp//` (`env/gateway/browser_proxy.py`), reaches the website browser behind the `/svc` child ``, found from that child's card (it, or an app among its children, offering `browser/v1` `cdp` with `/cdp/` in its `computer-app/v1` `agent_routes`): it relays the browser's discovery and WebSocket both ways, each leg pinged every 20 s, and every CDP address the browser hands out, in `json/version`, `json/list` and its `cdp` answer through `/svc//`, comes back at the gateway, everything before `/cdp//` becoming the address the caller reached the gateway at and `/browser/`, keeping the https or wss of an address the browser minted under an origin its caller named, as `browser_connect_cdp` names the agent's, since a tunnel that ends TLS, as Modal's, may send no `X-Forwarded-Proto`; each connection is a `browser_connection` trajectory event, without its token. Its clock (`env/gateway/clock.py`) keeps to the range of times each of its followers holds when that follower's card declares one (clock/v1's `range`; a computer's and a clock-following agent's is 1677-09-21T00:12:44Z to 2262-04-11T23:47:16Z, what 64 bits of nanoseconds since 1970 hold, as their clock page and Python keep time, core passing a computer's as `CLOCK_FOLLOWER_RANGES` and an agent bringing its own to `declare_follower`): `set_time` and `advance` refuse a time outside it, naming the follower, `set_time` one it would run past the end of from within a real hour, and `declare_follower` one the clock is outside now; a follower that declares none, or no follower, leaves the clock what a datetime holds. Its clock has one opaque version, a per-boot id and a count, that every `set_time`, `advance` and `clear` changes; `set_rate` (`/clock/set-rate`) changes an armed clock's rate from its time at the write, keeping its `t0` and generation as `advance` does, so time triggers keep their marks. Every clock change goes through `Gateway._change_clock`, which wakes the triggers when the change kept the clock's generation, answers the held watches and waits for the followers. Its followers, the computers on it (`CLOCK_FOLLOWER_TOKENS`, each child whose card serves `clock/v1` `sync_time`, by its read token, its control token for now), long-poll `/clock/watch` naming the version they show, each watch held up to the card's `hold_s` (`env/gateway/clock_followers.py`), and a write given `wait_followers_s` waits for each, answering 504 naming those behind, but not for one that hasn't watched for longer than a hold and a reconnect (`ClockFollowers.QUIET_S`), which it names at once with when each last watched; a restarted gateway is unarmed. While its clock is armed it serves agents `get_time` (`env/gateway/get_time.py`), which answers in UTC and also in the universe's zone, the one `sync_env_clock`'s `timezone` armed it in, or in an IANA `time_zone` it's given; executors' working `hours` (`env/gateway/triggers.py`) take a fixed `utc_offset` or an IANA `time_zone`. | +| `env/` | `Env` base class: a subclass declares `type`, implements `from_dict` and `async deploy(...) -> DeployedEnv`, and may override `reset`, `close` and `load_file_artifact_universe`; teardown closes each env a run deployed before terminating its sandboxes by id. Built-ins in `env/envs/`: `MCPServerEnv` (`mcp_server`), `MultiEnv` (`multi`, MCP servers plus websites and computers; its website browser is the one its `browser_envs` names, none for `[]`, else the run's when it has websites: an MCP server env such as `playwright-mcp` runs among the gateway's MCP servers, and a browser computer such as `chromium` on a sandbox of its own as one more computer child, sized by its `child_envs` entry, its tools under its name and `_`, routing the multi env's synthetic sites unless that entry's `site_routing` says, its network its own env's, as any computer child's; a website env deployed alone refuses a browser computer as the run's browser), `ServiceDBEnv` (`service_db`, PostgreSQL), `WebsiteEnv` (`website`, one site: a server image, `backend_image` in its env.toml, serving the pages and API, ready when its card's `website/v1` `ready` answers a `WebsiteReadiness` that says so, as `agentenv_protocol.website` (`website_readiness`, `env_readiness`) defines a website env's health for the deploy and `DeployedEnv.readiness()` alike, or, for a card without `ready`, when its `health` path answers 200, which is deprecated; its env.toml's `ready_timeout_s`, how long it may take from its server's container starting to ready, is that container's health check `start_period` and what the deploy waits, or its card's `ready` timeout if longer, and its `shm_mb` is the container's `shm_size`, each left to the gateway and Docker without them; the gateway container's `env/gateway/constants.py` mirrors the URI and op, a test keeping them equal; a separate frontend image is deprecated, warned of at put and optional in a bundle, and a stored `backend_docker_image_artifact` reads as the server image; a live one, `live = true`, is a real site whose server serves none of its pages, its `live`, `domains` and `allow_hosts` read at put from its server's `@website(...)` (`utils/card_naming.py` `WebsiteSource`) unless given, its `settings`' secrets only as references the gateway resolves as it writes the site's container (`WEBSITE_SETTINGS_ENV`); the gateway gives it no site route, a computer's site table leaves it out, a computer whose network is an allowlist is let reach its names (`MultiEnv.live_hosts`), a browser alone's forward port takes them straight to the real site (`site_proxy.py` `direct`), as the browser base's stand-in proxy takes any host, refusing nothing, each proxy logging each such connection as a JSON line, and a run that deploys one is marked live, `reproducible: false`), `GatewayEnv` (`gateway_server`), `ComputerDriverEnv` (`computer_driver`, `env/envs/computer/driver_env.py`: a computer driver's files and what its class declares for each platform it supports, read at put in a process of its own, `agentenv_protocol.computer._declare`, where the driver's own dependencies needn't be installed, with the `port` it serves on and its install by OS, `[install.]`, or for one distribution `[install."/"]`, which replaces its OS type's there, as its `known_failures` do (`env/envs/computer/utils/install.py`): files, apt `packages` with extra `sources`, a `python` requirements file for a venv, `downloads` by URL and sha256, `run` scripts, the services the base's init runs, and `ports`; it deploys only as a computer env's driver), `ComputerEnv` (`computer`, in `env/envs/computer/`: a base computer and a driver, matched at put by gate 1 before anything is stored, then composed by `composer.py` into an image for each form and arch on a builder of the put's sandbox provider, by default the env's (`utils/builder.py`; `--sandbox` on `env build`): this machine's Docker for `local`, else a VM of the provider, which fetches the put's stored files by signed URL, takes the rest inline and pushes to the image store itself, so it builds only with stores a remote VM reaches; each arch goes to the first link that runs it natively, else one that emulates it (a VM registers QEMU; `--no-emulate` leaves it `skipped` instead, for a later put), and its pair records the provider that built it (`builder`); a run or register composes only the computer envs its tasks deploy (`materialize._composed_envs`: each env a task's steps name, and each env those hold but a computer env's own apps and driver, which run inside it) and those it pulls in from an installed bundle, whose one write every bundle shares, every one for a plan with no tasks, any other composing at its first deploy; one that reuses a computer env composes what it has left (`pending`), a run, and a register given a `--sandbox`, only the forms its sandbox's deploys boot (`booted_forms`: on each link, the first form it boots natively, by the deploy's own rule, `boot.first_native`; a compose of a disk adds its container), and a deploy composes first what it boots that no compose started, and a container it runs natively that was built but not probed, as one whose probe a setting that didn't resolve stopped, booting it only once ready (`ComputerEnv.compose_unstarted`); tagged `agentenv-computers:` in the image store by a key of the image's Dockerfile, build context and lock so any env with the same inputs reuses it; every layer's packages, requirements and downloads are resolved at put in a container of the base for each arch (`utils/packages.py`, `utils/resolve_in_base.py`), stored in the object store by sha256 under `agentenv-packages/`, and listed in a lock stored by a digest of its inputs, which any env with the same inputs reuses, and builds install only the lock's files, every install step `RUN --network=none`; each pair's status goes into its metadata, `composed`, the arches built are written as its computer, a `computer` artifact over one index, and `agent-env env build` resumes what a put left; gate 3 (`utils/probing.py`) then boots each native build on the put's sandbox provider and probes it at `full`, making it `ready` or `failed`, and a build no provider runs natively stays `unverified`. Its deploy, through the `computer` env provider (`providers/env_providers/env_computer_provider.py`), boots its first `ready` build on a sandbox provider that runs its arch natively (`native_platforms()`), with no gateway in front and the driver's card as the env card, its `/dev/shm` the most its apps' Linux installs ask for (`shm_mb`, in MiB, which its composed computer and the deploy record keep; `--shm-size` on a container, `AGENTENV_SHM_MB` read by a Linux disk's init, passed only to a provider whose `SHARED_MEMORY` says it gives that much, else the sandbox's default, which the deploy logs), then checks its `display`; `deploy_env` `env_params` take a `form`, `computer_settings` (deploy-phase values of the base's settings; a secret one, here or on the env, only as a bare `secret:`/`env:` reference) and `driver_settings` (the driver's `ComputerSettings`, such as its default coordinate space); a `network` that allows nothing runs it on local Docker's internal network behind a relay (`providers/sandbox_providers/local_docker/relay/`); `reset` and `close` have the driver end its recordings first (`computer-recording/v1` `end_all`, each uploading what's left and its manifest under the grant it started with), and `reset` then boots a fresh container in its place (`reset_container`), keeping the computer's address but not an agent's MCP session to the old driver; its `load_file_artifact_universe` writes files under the session user's home through the driver's `data/add`, `Downloads` by default, each file's bytes through a read grant when the store's grants reach it and its network allows everything, else inline (`env/envs/computer/utils/inside.py`)), `ComputerAppEnv` (`computer_app`, `env/envs/computer/app_env.py`: an app on a computer, a `ComputerAppEnvironment` class its env.toml's `module` names, read at put by the same `_declare`, which declares each OS with its own decorator (`@linux(...)`, or `@install(os_type, spec)` for any OS type; `@linux(distribution=...)` or `@install("/", spec)` for one distribution, which replaces its OS type's there) holding its install, its launch and, optionally, a skill and settings and build settings that add to the class's there, and install steps and ready checks for every OS or those their `os=` names; everything that reads its settings, launch or steps asks for the computer's OS type; deployed alone it is a one-app computer env, a `ComputerEnv` of the computer and driver its env.toml names, the composer installing it under `/opt/agentenv/apps//` with its services as supervisord programs beside its own server (`agentenv_protocol.computer.serve_app`, in a venv with the protocol's `app` extra, on `.agentenv/server.sock` in its folder), which adds its launcher, launches a `boot` app once per boot and says through `computer-app/v1` whether it's ready, as the driver's `computer-ready` asks, its card named after it, and `env_params` `app_settings` handing it values of its `Settings` in `AGENTENV_APP_SETTINGS`, a secret one only as a bare reference, over its env.toml's `[settings]` and a computer env's `settings` beside it in `apps`, each by top-level field (`params.app_settings`; checked at put, a required one left to the deploy; the deploy record keeps the merged values as `app_settings`, secrets withheld); its env.toml's `build_settings`, values of its `BuildSettings` checked at put, are written to `.agentenv/build_settings.json` in its folder, so they're part of the image's key, its install steps read them, and a deploy can't change them). An env type whose services take environment data defines `load_environment_artifact` and `load_environment_universe_artifact`; `load_artifact` refuses an environment artifact aimed at a type that doesn't, at save and before it loads. An env built on the protocol SDK can serve agents a skill (`@agent_skill`, `skill/v1`), which `add_skills` `env_ids` installs under its environment name (behind a gateway, each server's under that server's name); a skill with files beside its SKILL.md goes as a bundle stored once per content under `agentenv-env-skills/` in the object store. `env/gateway/gateway.py` is the env-side gateway server, container-only code. Its site route, `/website//`, never forwards a site's data plane or card (`/agentenv/…`, `/.well-known/agent-env.json`), which agentenv reaches through `/svc//`; a site with no frontend image is served by its server image there. A request from a computer's site proxy names its computer (`AgentEnv-Computer`, sent from the proxy's private upstream headers, a page's own copy and any `AgentEnv-Role` it sends dropped) and takes the role driving that computer now (the gateway's computers being those `COMPUTERS` names, a multi env's, with or without a control token): the last to make an input call to its tools, as the call starts, through `/mcp`, `/step` or a trigger action under its `as` (`Gateway._drive`); without one, or from a computer the gateway doesn't front, it is `default`, the role read once per request. `changes/v1` (`ChangeAttribution`) counts no write window for a call to a computer's tools, a trigger action's included, so a write the computer's browser made goes to its request and one another party made during the call to that party. Its CDP route, `/browser//cdp//` (`env/gateway/browser_proxy.py`), reaches the website browser behind the `/svc` child ``, found from that child's card (it, or an app among its children, offering `browser/v1` `cdp` with `/cdp/` in its `computer-app/v1` `agent_routes`): it relays the browser's discovery and WebSocket both ways, each leg pinged every 20 s, and every CDP address the browser hands out, in `json/version`, `json/list` and its `cdp` answer through `/svc//`, comes back at the gateway, everything before `/cdp//` becoming the address the caller reached the gateway at and `/browser/`, keeping the https or wss of an address the browser minted under an origin its caller named, as `browser_connect_cdp` names the agent's, since a tunnel that ends TLS, as Modal's, may send no `X-Forwarded-Proto`; each connection is a `browser_connection` trajectory event, without its token. Its clock (`env/gateway/clock.py`) keeps to the range of times each of its followers holds when that follower's card declares one (clock/v1's `range`; a computer's and a clock-following agent's is 1677-09-21T00:12:44Z to 2262-04-11T23:47:16Z, what 64 bits of nanoseconds since 1970 hold, as their clock page and Python keep time, core passing a computer's as `CLOCK_FOLLOWER_RANGES` and an agent bringing its own to `declare_follower`): `set_time` and `advance` refuse a time outside it, naming the follower, `set_time` one it would run past the end of from within a real hour, and `declare_follower` one the clock is outside now or would run past the end of from within a real hour (error code `outside_range`); `set_rate` isn't checked, so `always_on` can start a clock it froze near the end again; a range that doesn't parse is left out by core, with a warning; a follower that declares none, or no follower, leaves the clock what a datetime holds. Its clock has one opaque version, a per-boot id and a count, that every `set_time`, `advance` and `clear` changes; `set_rate` (`/clock/set-rate`) changes an armed clock's rate from its time at the write, keeping its `t0` and generation as `advance` does, so time triggers keep their marks. Every clock change goes through `Gateway._change_clock`, which wakes the triggers when the change kept the clock's generation, answers the held watches and waits for the followers. Its followers, the computers on it (`CLOCK_FOLLOWER_TOKENS`, each child whose card serves `clock/v1` `sync_time`, by its read token, its control token for now), long-poll `/clock/watch` naming the version they show, each watch held up to the card's `hold_s` (`env/gateway/clock_followers.py`), and a write given `wait_followers_s` waits for each, answering 504 naming those behind, but not for one that hasn't watched for longer than a hold and a reconnect (`ClockFollowers.QUIET_S`), which it names at once with when each last watched; a restarted gateway is unarmed. While its clock is armed it serves agents `get_time` (`env/gateway/get_time.py`), which answers in UTC and also in the universe's zone, the one `sync_env_clock`'s `timezone` armed it in, or in an IANA `time_zone` it's given; executors' working `hours` (`env/gateway/triggers.py`) take a fixed `utc_offset` or an IANA `time_zone`. | | `artifact/` | Immutable versioned artifacts; every `put()` creates a new version. The document goes to the document store, binary payloads to the object store. Every artifact but an environment universe, whose `metadata` key holds its legacy metadata file ids, carries a `metadata` dict outside its versioned fields, changed by compare-and-swap (`merge_metadata`). Built-ins: `CliArtifact` (`cli`), `ComputerArtifact` (`computer`, a base computer: its architectures, OS, session user, settings and container form, whose image `put` reads from its registry into `metadata.validated_images`), `FileArtifact` (`file`), `FileArtifactUniverse` (`file_artifact_universe`), `DockerImageArtifact` (`docker_image`), `EnvironmentArtifact` (`environment`: its environment's files by path, stored as the one wrapped `file_artifact_ref` every environment artifact had when it has one file at its filename, else as `file_artifact_refs`; `get_file_artifacts()` reads either, and a load hands each file to the env's `data/add` with its path, which a pre-v1 load, taking one file, refuses), `EnvironmentUniverseArtifact` (`environment_universe`), `SkillArtifact` (`skill`); `[artifacts] type_aliases` maps another stored spelling of a type onto one of them. A `DockerImageArtifact` holds a tar.gz of its image, or, written by `put_ref` (`--image-ref` on `env mcp-server put` and `a2a-agent put`), only a registry reference with its tag pinned to a digest, which sandboxes pull, or a published image's tag with its `image_digest` and its build context, which sandboxes pull by the digest and build from the context when they can't (the infra images, and a bundle agent built from a shipped agent's sources, `Plan.published`), or, written by `put_context`, only its build context, which a VM sandbox builds before running it (`VmSandbox.load_docker_images`) and Modal builds before creating its container (`ModalSandboxProvider.prepare_image`, outside a fallback chain's deadline); anything else that runs images by name (a container on the local provider, a lone server on any provider but Modal) refuses such an image. A build context (`utils/docker/context.py`) is what `docker build` would send, `.dockerignore` applied, written so equal files give equal bytes and an equal `source_digest`. | | `task/`, `task_step/` | A `Task` holds its `TaskStep`s inline; `Task.run()` executes them as a DAG. Its `headline_verifiers`, step ids saved only when set, name the grades that are its reward: one is the reward, several a multi-reward over them, none a multi-reward over every grade; it refuses one that names no step of the task, or one named twice. `depends_on` (None means all prior steps) gates a step, independent steps run concurrently, `fail_task_on_error` makes a failure fatal or tolerated, `retry_config` rolls a failed span back through the step journal and re-dispatches it. `task/lint.py` is `agent-env task lint` (a bundle folder, a task file or a stored task): an error is what a task gets wrong before it runs (a field its step doesn't read, a step's own `config_problems`, a headline that grades nothing, an aggregate source no verifier writes) and refuses `agent-env run`, `bundle register`, `task create`, `task validate` and `eval run`, and the bundle plans `openenv`'s `build_app` and the trainers make (`run`, `register`, `build_app`, `prepare_bundle` and the trainers take `--skip-lint`/`skip_lint`, which lifts lint's own rules but not a step's `config_problems`, which refused a bundle before lint; `eval run`'s lifts every error, since it checked none before); a warning is what may be wrong (a step's `config_warnings`, a store entity read with no version, no verifier, several and no headline, a judge that runs in the solver's own agent, which training refuses) and is only printed, each kind once by a run (`task.lint.said`), an eval run's unpinned references as one count (`unpinned_summary`), every one by `task lint`. `aggregate_verifiers` names its sources by step id (`sources`, `gates`) and reads their named grades: `combine` `pooled` (the default) pools their rows, `weighted_mean` weighs their scores, equally unless `weights` gives every source one, and a failing gate scores it 0; a failed or missing source fails it, and its older `verifier_ids` pools legacy entries as it always has. Built-in steps live in `task_step/task_steps/` (`deploy_env`, `deploy_agent`, `prompt_agent`, the verifiers under `verifiers/`, among them `start_computer_recording` (its driver draws each input over the frames in its caller's colour, and a pointer per role where the frames lack one, unless `annotation_settings` says `is_enabled: false`; a driver whose card lists no `annotate` records it plain, with a warning, and the run's recording entry says `annotated`) and `end_computer_recording`, `start_browser_recording` and `end_browser_recording` (`browser-recording/v1`: one recording per context, a lease's or the default one's, with a video of the tab its agent is on, its context's log, the browser's network log as HAR and opt-in frames keyed to the action log, the contexts its agents make recorded with it, one universe per recording, anything missing failing the run), and more). Every built-in verifier is on the `VerifierTaskStep` base (`verifiers/verifier.py`): it implements `verify` and returns a `Verification`, and the base writes the step's named grade to `context.metadata["grades"][]` (score, `min_passing_score`, `passed`, `verifier_status` graded, skipped or failed, criteria rows, type, version, and `verifier_settings`, the values the run graded with, its overrides applied and named in `overridden`, with `scoring_rules`) beside the legacy `verifications` entries every reader still takes; an exception from `verify` or a `Verification` with an `error`, as a timed-out `run_container_unit_tests_verifier`, is a failed grade, and `rubrics_verifier` still writes its `-trajectory-mistakes` entry itself. On an env whose card serves computer-exec/v1 (a computer), `run_code` with `env_id` and `run_container_unit_tests_verifier` with `env_id` run inside it as its session user through the driver: files staged with `data/add` and read with `data/get`, commands run with `run`; `computer_exec` runs one command there through `run` (a program and its arguments, or a string through `sh -c`; in a multi env, the computer it names), recorded under `computer_exec` in the run's metadata, a non-zero exit or a timeout failing it unless `check` is off, or with `background` starts it and leaves it running, as an app launched for the agent, a program that isn't there exiting 127; with `scope: "system"` it runs as root instead, through the computer's sandbox (`RootChannel`, `docker exec -u 0`), in the session user's folder and `HOME`, its output capped in the computer, never with `background` and not on a computer booted from a disk; on a Windows computer, which has no `sh`, a string or `background` command is refused; on a multi env, `load_artifact` with `env_id` puts an environment artifact named after one of its computers, or after an app of one, into that computer, the computer's own as files at their paths under the session user's home; `env_outcome_verifier` hands a `verify` that takes an `env_url` keyword the env's address. A computer's framework-only routes (everything but MCP and the card) take the per-deploy control token its provider boots it with (`DeployedEnv.control_token`, `AGENTENV_CONTROL_TOKEN`), a multi env's computers the multi env's own, which its gateway passes on only on their `/svc` routes and its clock watch (`CONTROL_TOKEN_CHILDREN`); framework calls send `deployed.control_headers`, `Task.run` runs every step under `protocol_v1.authorized` with each deployed env's (a `verify` included), and a `run_code` script inside the computer gets `input["env"]["headers"]`. `teardown_run` and the `teardown_sandboxes` step share one core (`task/teardown.py` `tear_down`): the recordings the run left open end with fresh grants, each env still up closes (`Env.close`; a computer env ends any recording still open), what stayed open is registered from its namespace, then every sandbox is terminated by id. A run whose teardown leaves sandboxes up, stopped by a second signal or failing, keeps on its instance the context it ended with (`record_teardown`), and `agent-env run` and `task run --keep` name `agent-env task teardown --instance `, which tears down what that context still records up, a running one only with `--force`. `task/episode/` runs a task with some of its agents played from outside, as a training loop does (`EpisodeSpec`). | | `store/` | Four store ABCs with local and cloud implementations: `DocumentStore` (SQLite, MongoDB, DynamoDB, Firestore with MongoDB compatibility), `ObjectStore` (filesystem, S3, Cloud Storage), `ImageStore` (local OCI registry, ECR), `SecretStore` (env vars or file, AWS Secrets Manager, Google Cloud Secret Manager). `VersionedEntityStore` implements the shared versioned get/put logic, `QueryBuilder` is the immutable chained query API, `store/base.py` holds the error types. `store/routing.py` is the local namespaces, `@local` and `@hf` (`is_local_id`), each with a documents file of its own: while the CLI or a `build_app` server runs, a local id and what a local task's run records go to local stores beside the configured ones, and that run's writes to the configured stores are refused. A new backend must pass the conformance kits in `tst/store/`. | diff --git a/src/agent_env/a2a_agent/clock.py b/src/agent_env/a2a_agent/clock.py index 4e819e11f..f6d5a8011 100644 --- a/src/agent_env/a2a_agent/clock.py +++ b/src/agent_env/a2a_agent/clock.py @@ -23,7 +23,8 @@ from agent_env.a2a_agent.a2a_agent import A2AAgent from agent_env.env.env import EnvCapabilityUnsupported, gateway_url_of -from agent_env.env.gateway.constants import CLOCK_WATCH_PATH, EXT_CLOCK_URI +from agent_env.env.gateway.clock import ClockError, FollowerRange, parse_follower_range +from agent_env.env.gateway.constants import CLOCK_OUTSIDE_RANGE, CLOCK_WATCH_PATH, EXT_CLOCK_URI from agent_env.providers.sandbox_providers.local_docker.provider import host_url_for from agent_env.providers.sandbox_providers.sandbox_provider import reachable_url, sandbox_request_headers_for_url from agent_env.task_step.context import StepContextError @@ -53,11 +54,18 @@ def follower_name(agent: DeployedAgent) -> str: return f"agent-{agent.agent_name}" -def held_range(agent: DeployedAgent) -> Optional[dict]: +def held_range(agent: DeployedAgent) -> Optional[FollowerRange]: """The times ``agent`` holds, when its card declares it holds only a range of them (clock/v1's ``range``); a card - from before it declares none.""" + from before it declares none, and one that doesn't parse is logged and left out, as if it declared none.""" held = (A2AAgent.find_extension(agent.a2a_card or {}, EXT_CLOCK_URI) or {}).get("params", {}).get("range") - return held if isinstance(held, dict) and held.get("earliest") and held.get("latest") else None + if held is None: + return None + try: + return parse_follower_range(held) + except ClockError as e: + logger.warning(f"agent '{agent.agent_name}': its card's clock/v1 range is left out, so the gateway's clock " + f"doesn't keep to it: {e}") + return None def _sync_time(agent: DeployedAgent) -> tuple[Optional[dict], Optional[str]]: @@ -82,7 +90,8 @@ async def follow(agent: DeployedAgent, env: DeployedEnv, *, env_get_time_url: Op """Have ``agent`` follow ``env``'s gateway clock. ``{"synced": False, "reason": ...}`` for an agent that can't: its card serves no ``sync_time`` (``not_advertised``) or one without the follower's fields (``no_follower_fields``), the gateway takes no followers after it starts (``gateway_takes_no_followers``), or the - clock is outside the range of times the agent's card says it holds (``outside_range: ``); raises + clock is outside the range of times the agent's card says it holds, or would run past its end from within a real + hour (``outside_range: ``); raises for one that serves it and fails, having retired the follower it declared, or can't take the task's zone, as for a server.""" method, path = _sync_time(agent) @@ -98,11 +107,12 @@ async def follow(agent: DeployedAgent, env: DeployedEnv, *, env_get_time_url: Op held = held_range(agent) try: await env.invoke(EXT_CLOCK_URI, "declare_follower", - {"name": name, "read_token": token, **({"range": held} if held else {})}, timeout=timeout) + {"name": name, "read_token": token, **({"range": held.as_dict()} if held else {})}, + timeout=timeout) except EnvCapabilityUnsupported: return {"synced": False, "reason": "gateway_takes_no_followers"} except ExtensionCallError as e: - if held is None or e.response.status_code != 400: + if e.code != CLOCK_OUTSIDE_RANGE: raise return {"synced": False, "reason": f"outside_range: {e.detail}"} body = {"env_get_time_url": env_get_time_url or "", "watch_url": watch_url_for(agent, env), "name": name, diff --git a/src/agent_env/env/envs/computer/utils/clock.py b/src/agent_env/env/envs/computer/utils/clock.py index c43341dc5..7c1b6ce81 100644 --- a/src/agent_env/env/envs/computer/utils/clock.py +++ b/src/agent_env/env/envs/computer/utils/clock.py @@ -23,6 +23,7 @@ from agentenv_protocol.computer.clock import CONFIG, FOLLOWER_USER from agent_env.env.envs.computer.utils.sites import RootChannel +from agent_env.env.gateway.clock import ClockError, FollowerRange, parse_follower_range from agent_env.env.gateway.constants import EXT_CLOCK_URI if TYPE_CHECKING: @@ -40,11 +41,19 @@ def follows(record: DeployedEnv) -> bool: return record.supports(EXT_CLOCK_URI, "sync_time") -def held_range(record: DeployedEnv) -> Optional[dict]: +def held_range(record: DeployedEnv) -> Optional[FollowerRange]: """The times the computer ``record`` deployed holds, when its card declares it holds only a range of them - (clock/v1's ``range``, ``{"earliest": ..., "latest": ...}``); a card from before it declares none.""" + (clock/v1's ``range``, ``{"earliest": ..., "latest": ...}``); a card from before it declares none, and one that + doesn't parse, which would stop the gateway starting, is logged and left out, as if it declared none.""" held = protocol_v1.extension_params(record.environment_card or {}, EXT_CLOCK_URI).get("range") - return held if follows(record) and isinstance(held, dict) and held.get("earliest") and held.get("latest") else None + if not follows(record) or held is None: + return None + try: + return parse_follower_range(held) + except ClockError as e: + logger.warning(f"{record.env_id}: its card's clock/v1 range is left out, so the gateway's clock doesn't keep to " + f"it: {e}") + return None def recorded(record: DeployedEnv) -> Optional[dict]: diff --git a/src/agent_env/env/gateway/__init__.py b/src/agent_env/env/gateway/__init__.py index 46d88c761..344e366ae 100644 --- a/src/agent_env/env/gateway/__init__.py +++ b/src/agent_env/env/gateway/__init__.py @@ -3,6 +3,7 @@ from dataclasses import dataclass +from .clock import FollowerRange from .constants import ( AGENT_ENV_HIDDEN_BY_DEFAULT_META_KEY, AGENT_ENV_ROLE_HEADER, @@ -31,14 +32,14 @@ class InternalMCPServer: class ExternalChild: """A child env on a sandbox of its own, which the gateway fronts as it does an MCP server: its name, and its MCP endpoint and base URL as the process holding it reaches them. A child that is a clock follower has the read token its - clock watch carries, and the gateway's clock writes wait for it; one that holds only a range of times has that range - (``{"earliest": ..., "latest": ...}``), which the gateway's clock keeps to.""" + clock watch carries, and the gateway's clock writes wait for it; one that holds only a range of times has that range, + which the gateway's clock keeps to.""" name: str mcp_url: str base_url: str clock_read_token: str | None = None - clock_range: dict | None = None + clock_range: FollowerRange | None = None __all__ = [ diff --git a/src/agent_env/env/gateway/clock.py b/src/agent_env/env/gateway/clock.py index d6e17e06f..9841b54a7 100644 --- a/src/agent_env/env/gateway/clock.py +++ b/src/agent_env/env/gateway/clock.py @@ -20,6 +20,10 @@ class ClockError(ValueError): """Invalid clock configuration (surfaced as HTTP 400).""" +class OutsideRange(ClockError): + """A time outside the range of times a clock follower holds, or one the clock would run past its end from.""" + + MAX_RATE = 86400.0 # 1 real second = 1 virtual day (the max virtual-time speed) # Fast-fail a t0 that would overflow within a real day of advancement at `rate` (frozen clocks @@ -39,27 +43,43 @@ class FollowerRange: earliest: datetime latest: datetime + def as_dict(self) -> dict[str, str]: + return {"earliest": _iso(self.earliest), "latest": _iso(self.latest)} + def parse_follower_range(value) -> FollowerRange: """A follower's declared range, ``{"earliest": , "latest": }``.""" if not isinstance(value, dict): raise ClockError(f"a follower's range takes earliest and latest RFC3339 times, got {value!r}") - held = FollowerRange(_parse_rfc3339(value.get("earliest")), _parse_rfc3339(value.get("latest"))) + held = FollowerRange(_parse_rfc3339(value.get("earliest"), "range earliest"), + _parse_rfc3339(value.get("latest"), "range latest")) if held.earliest > held.latest: raise ClockError(f"a follower's range ends before it starts: {value!r}") return held -def check_arm(virtual_time: str, rate=1.0) -> tuple[datetime, float]: - """``virtual_time`` and ``rate`` as the clock arms at them, or the ClockError it refuses them with whatever its - followers, as sync_env_clock checks them before anything deploys.""" +def check_arm(virtual_time: str, rate=1.0, time_zone: str | None = None) -> tuple[datetime, float]: + """``virtual_time`` and ``rate`` as the clock arms at them, in ``time_zone`` if one, or the ClockError it refuses + them with whatever its followers, as sync_env_clock checks them before anything deploys.""" t0 = _parse_rfc3339(virtual_time) r = _parse_rate(1.0 if rate is None else rate) + if time_zone is not None and _zone(time_zone) is None: + raise ClockError(f"unknown time zone {time_zone!r}: pass an IANA time zone name such as 'America/New_York'") if t0 > _MAX_T0 - timedelta(seconds=_OVERFLOW_HORIZON_S * r): raise ClockError(f"virtual_time {virtual_time!r} at rate {r:g} would overflow datetime near the max") return t0, r +def _check_range(what: str, name: str, held: FollowerRange, t: datetime, rate: float | None) -> None: + """Refuse ``t`` outside the range follower ``name`` holds, or, run at ``rate``, one it would pass the end of that + range from within a real hour.""" + where = f"clock follower {name!r} holds, {_iso(held.earliest)} to {_iso(held.latest)}" + if not held.earliest <= t <= held.latest: + raise OutsideRange(f"{what} is outside the times {where}") + if rate and (held.latest - t).total_seconds() < _FOLLOWER_HORIZON_S * rate: + raise OutsideRange(f"{what} at rate {rate:g} would pass the end of the times {where}, within a real hour") + + def _parse_rate(rate) -> float: if isinstance(rate, bool) or not isinstance(rate, (int, float)): raise ClockError(f"rate must be a number, got {type(rate).__name__}") @@ -88,23 +108,23 @@ def _parse_rate(rate) -> float: _RFC3339_SHAPE = "YYYY-MM-DDThh:mm:ss[.fff](Z|+hh:mm)" -def _parse_rfc3339(text: str) -> datetime: +def _parse_rfc3339(text: str, what: str = "virtual_time") -> datetime: if not isinstance(text, str): - raise ClockError(f"virtual_time must be an RFC3339 string, got {type(text).__name__}") + raise ClockError(f"{what} must be an RFC3339 string, got {type(text).__name__}") # Don't strip: a whitespace-wrapped value would slip through the anchored grammar (a 200 the contract calls a 400). raw = text if not _RFC3339_RE.match(raw): - raise ClockError(f"invalid RFC3339 virtual_time {text!r}: expected {_RFC3339_SHAPE}") + raise ClockError(f"invalid RFC3339 {what} {text!r}: expected {_RFC3339_SHAPE}") if raw.endswith(("Z", "z")): raw = raw[:-1] + "+00:00" try: dt = datetime.fromisoformat(raw) except ValueError as e: - raise ClockError(f"invalid RFC3339 virtual_time {text!r}: {e}") + raise ClockError(f"invalid RFC3339 {what} {text!r}: {e}") try: return dt.astimezone(timezone.utc) except OverflowError: - raise ClockError(f"invalid RFC3339 virtual_time {text!r}: out of representable range") + raise ClockError(f"invalid RFC3339 {what} {text!r}: out of representable range") def _iso(dt: datetime) -> str: @@ -221,9 +241,7 @@ def t0(self) -> datetime | None: def set_time(self, virtual_time: str, rate=1.0, time_zone: str | None = None) -> dict: """Arm/re-arm: anchor t0=virtual_time to now, advancing at `rate` virtual s per real s, in the universe's `time_zone` (its users' IANA zone), or none.""" - t0, r = check_arm(virtual_time, rate) - if time_zone is not None and _zone(time_zone) is None: - raise ClockError(f"unknown time zone {time_zone!r}: pass an IANA time zone name such as 'America/New_York'") + t0, r = check_arm(virtual_time, rate, time_zone) self._check_followers(f"virtual_time {virtual_time!r}", t0, r) with self._lock: self._bank(t0) @@ -240,11 +258,16 @@ def _check_followers(self, what: str, t: datetime, rate: float | None) -> None: """Refuse ``t``, a time the clock would be set or advanced to, outside the range of a follower it has, or, armed at ``rate``, one it would run past the end of that range from within a real hour.""" for name, held in sorted(self._follower_ranges().items()): - where = f"clock follower {name!r} holds, {_iso(held.earliest)} to {_iso(held.latest)}" - if not held.earliest <= t <= held.latest: - raise ClockError(f"{what} is outside the times {where}") - if rate and (held.latest - t).total_seconds() < _FOLLOWER_HORIZON_S * rate: - raise ClockError(f"{what} at rate {rate:g} would pass the end of the times {where}, within a real hour") + _check_range(what, name, held, t, rate) + + def check_follower(self, name: str, held: FollowerRange) -> None: + """Refuse a follower ``name`` that holds only ``held`` while the clock is outside it now, or, at its rate, would + run past its end from within a real hour, as set_time refuses arming with one; an unarmed clock takes any.""" + with self._lock: + if not self._armed or self._t0 is None: + return + now, rate = _advance(self._t0, (self._now() - self._anchor) * self._rate + self._ahead), self._rate + _check_range(f"the clock, at {_iso(now)},", name, held, now, rate) def set_rate(self, rate) -> dict: """Change an armed clock's rate from its time at the call, keeping t0 and generation as an advance does, so time diff --git a/src/agent_env/env/gateway/clock_followers.py b/src/agent_env/env/gateway/clock_followers.py index 05c3df68a..196659c72 100644 --- a/src/agent_env/env/gateway/clock_followers.py +++ b/src/agent_env/env/gateway/clock_followers.py @@ -10,7 +10,7 @@ import time from collections.abc import Callable, Mapping -from .clock import Clock, ClockError, FollowerRange, _iso +from .clock import Clock, ClockError, FollowerRange from .constants import CLOCK_MAX_WAIT_FOLLOWERS_S, CLOCK_WATCH_HOLD_S @@ -52,14 +52,14 @@ def __init__(self, clock: Callable[[], Clock], tokens: Mapping[str, str], def declare(self, name: str, token: str, held: FollowerRange | None = None) -> None: """Declare ``name`` a follower, with the read token its watch carries and the range of times it holds if it holds only some, after the gateway started: an agent the run deploys. Declared again, as a redeploy does, it takes - the new token and range and is waited for afresh. One whose range the clock is outside now is refused.""" + the new token and range and is waited for afresh. One whose range the clock is outside now, or would run past + the end of from within a real hour, is refused (``OutsideRange``).""" if not name or not token: raise ClockError("a follower takes a name and a read token") if name in self._tokens and name not in self._declared: raise ClockError(f"{name!r} is a follower this gateway started with, which a declaration doesn't replace") - if held is not None and (now := self._clock().now()) is not None and not held.earliest <= now <= held.latest: - raise ClockError(f"the clock, at {_iso(now)}, is outside the times clock follower {name!r} holds, " - f"{_iso(held.earliest)} to {_iso(held.latest)}") + if held is not None: + self._clock().check_follower(name, held) self._tokens[name] = token if held is None: self._held.pop(name, None) @@ -150,6 +150,5 @@ def state(self) -> dict: now, clock = time.monotonic(), self._clock() return {name: {"version": None if shown is None else clock.version_of(shown), "seen_s_ago": round(now - self._seen[name], 3) if name in self._seen else None, - **({"range": {"earliest": _iso(held.earliest), "latest": _iso(held.latest)}} - if (held := self._held.get(name)) else {})} + **({"range": held.as_dict()} if (held := self._held.get(name)) else {})} for name, shown in self._shown.items()} diff --git a/src/agent_env/env/gateway/constants.py b/src/agent_env/env/gateway/constants.py index b932fa9e8..408939d38 100644 --- a/src/agent_env/env/gateway/constants.py +++ b/src/agent_env/env/gateway/constants.py @@ -91,6 +91,9 @@ def data_plane_load_timeout_s(size_bytes: int | None) -> int: # The route a clock follower long-polls, with its read token. CLOCK_WATCH_PATH = "/clock/watch" CLOCK_FOLLOWERS_PATH = "/clock/followers" +# The error code declare_follower refuses a follower with when the clock is outside the range of times it holds, or +# would run past its end from within a real hour. +CLOCK_OUTSIDE_RANGE = "outside_range" # How long /clock/watch holds a watch naming the current version before answering it unchanged; a follower's request # timeout must be longer. The card's watch method advertises it as hold_s. CLOCK_WATCH_HOLD_S = 25.0 @@ -271,7 +274,7 @@ def random_mcp_server_name() -> str: }, { "uri": EXT_CLOCK_URI, - "description": "Virtual clock (urn:agentenv:clock/v1): read the gateway's virtual time (wall-clock-derived, rate-scaled) via get_time; set_time/set_rate/advance/clear are the harness control path, each changing the clock's opaque version and, given wait_followers_s, answering 504 naming the followers that don't show it in time (set_rate keeps t0, as advance does, so time triggers keep their marks; rate 0 freezes the clock); declare_follower adds a follower after the gateway started (an agent the run deploys), with the read token its watches carry and, for one that holds only a range of times (its card's clock/v1 range), that range, refused when the clock is outside it now; set_time and advance refuse a time outside the range of a follower the clock has, naming it, and set_time one it would run past that range's end from within a real hour; retire_follower removes one so writes stop waiting for it (an agent the run tears down); a follower follows it through watch, a long poll naming the version it shows and held up to hold_s; state's followers block is diagnostic, not part of the contract.", + "description": "Virtual clock (urn:agentenv:clock/v1): read the gateway's virtual time (wall-clock-derived, rate-scaled) via get_time; set_time/set_rate/advance/clear are the harness control path, each changing the clock's opaque version and, given wait_followers_s, answering 504 naming the followers that don't show it in time (set_rate keeps t0, as advance does, so time triggers keep their marks; rate 0 freezes the clock); declare_follower adds a follower after the gateway started (an agent the run deploys), with the read token its watches carry and, for one that holds only a range of times (its card's clock/v1 range), that range, refused with error code outside_range when the clock is outside it now or would run past its end from within a real hour; set_time and advance refuse a time outside the range of a follower the clock has, naming it, and set_time one it would run past that range's end from within a real hour; retire_follower removes one so writes stop waiting for it (an agent the run tears down); a follower follows it through watch, a long poll naming the version it shows and held up to hold_s; state's followers block is diagnostic, not part of the contract.", "params": {"endpoint": "/clock/time", "methods": { "get_time": {"method": "GET", "endpoint": "/clock/time"}, "set_time": {"method": "PUT", "endpoint": "/clock/set-time", "request": {"type": "object", "properties": {"virtual_time": {"type": "string"}, "virtual_seconds_per_real_second": {"type": "number"}, "time_zone": {"type": "string"}, **_WAIT_FOLLOWERS}, "required": ["virtual_time"]}}, diff --git a/src/agent_env/env/gateway/gateway.py b/src/agent_env/env/gateway/gateway.py index 6f8ace1d0..97503b9b3 100644 --- a/src/agent_env/env/gateway/gateway.py +++ b/src/agent_env/env/gateway/gateway.py @@ -48,6 +48,7 @@ CARD_FETCH_TIMEOUT_S, CHANGES_PAGE_DEFAULT, CLOCK_FOLLOWERS_PATH, + CLOCK_OUTSIDE_RANGE, CLOCK_WATCH_PATH, CHANGES_PAGE_MAX, CHILD_DISCOVERY_TIMEOUT_S, @@ -80,7 +81,7 @@ from .caller import Caller from .changes import ChangeAttribution from .child_sessions import ChildSessions, is_dead_session -from .clock import Clock, ClockError, FollowerRange, _iso, parse_follower_range +from .clock import Clock, ClockError, FollowerRange, OutsideRange, _iso, parse_follower_range from .clock_followers import ClockFollowers, parse_wait from .console_session import ConsoleSession, LinkRedaction, without_session_cookie from .get_time import GET_TIME_TOOL_NAME, build_get_time_tool @@ -437,6 +438,8 @@ async def clock_declare_follower(request: Request) -> Response: try: held = None if body.get("range") is None else parse_follower_range(body["range"]) self._clock_followers.declare(str(body.get("name") or ""), str(body.get("read_token") or ""), held) + except OutsideRange as e: + return self._json_response({"ok": False, "error": {"code": CLOCK_OUTSIDE_RANGE, "message": str(e)}}, 400) except ClockError as e: return self._json_response({"ok": False, "error": str(e)}, 400) return self._json_response({"ok": True, "followers": self._clock_followers.state()}, 200) diff --git a/src/agent_env/providers/env_providers/env_gateway_provider.py b/src/agent_env/providers/env_providers/env_gateway_provider.py index 17f8c3454..e49e0cde3 100644 --- a/src/agent_env/providers/env_providers/env_gateway_provider.py +++ b/src/agent_env/providers/env_providers/env_gateway_provider.py @@ -1866,7 +1866,7 @@ def clock_followers_environment(children: Iterable[ExternalChild]) -> dict[str, times each that holds only a range of them holds.""" children = [child for child in children if child.clock_read_token] followers = ",".join(f"{child.name}={child.clock_read_token}" for child in children) - held = ",".join(f"{child.name}={child.clock_range['earliest']}/{child.clock_range['latest']}" + held = ",".join("{name}={earliest}/{latest}".format(name=child.name, **child.clock_range.as_dict()) for child in children if child.clock_range) return {**({CLOCK_FOLLOWERS_ENV: followers} if followers else {}), **({CLOCK_FOLLOWER_RANGES_ENV: held} if held else {})} diff --git a/tst/unit/env/envs/test_multi_env_computers.py b/tst/unit/env/envs/test_multi_env_computers.py index ac11a9c94..88f0d2573 100644 --- a/tst/unit/env/envs/test_multi_env_computers.py +++ b/tst/unit/env/envs/test_multi_env_computers.py @@ -331,18 +331,40 @@ async def test_deploy_hands_the_gateway_each_computer_deployed_under_its_name_wi ("gw", "modal_vm"), ("gw", "modal_vm"), ("sb-desktop", "modal_vm"), ("sb-laptop", "modal_vm")] +def _ranged(name: str, held) -> DeployedSandboxEnv: + return dataclasses.replace(_record(name, clock=True), environment_card={"name": name, "capabilities": { + "extensions": [{**CLOCK_CARD["capabilities"]["extensions"][0], "params": { + **CLOCK_CARD["capabilities"]["extensions"][0]["params"], "range": held}}]}}) + + def test_a_computer_whose_card_declares_the_times_it_holds_hands_the_gateway_that_range(): from agent_env.env.envs.computer.utils import clock as computer_clock + from agent_env.env.gateway.clock import parse_follower_range held = {"earliest": "1677-09-21T00:12:44Z", "latest": "2262-04-11T23:47:16Z"} - ranged = dataclasses.replace(_record("desktop", clock=True), environment_card={"name": "desktop", "capabilities": { - "extensions": [{**CLOCK_CARD["capabilities"]["extensions"][0], "params": { - **CLOCK_CARD["capabilities"]["extensions"][0]["params"], "range": held}}]}}) - assert computer_clock.held_range(ranged) == held + assert computer_clock.held_range(_ranged("desktop", held)) == parse_follower_range(held) + child = ExternalChild("desktop", "https://desk.example/mcp", "https://desk.example", "read-desk", + computer_clock.held_range(_ranged("desktop", held))) + assert {child} == {dataclasses.replace(child)} assert computer_clock.held_range(_record("old", clock=True)) is None assert computer_clock.held_range(_record("laptop")) is None +@pytest.mark.parametrize("held", [{"earliest": "1677-09-21", "latest": "2262-04-11"}, {"earliest": 0, "latest": 1}, + {"latest": "2262-04-11T23:47:16Z"}, "1677/2262"]) +def test_a_computer_whose_card_declares_a_range_that_doesnt_parse_starts_the_gateway_as_if_it_declared_none(held, caplog): + from agent_env.env.envs.computer.utils import clock as computer_clock + from agent_env.env.gateway.entrypoint import parse_clock_follower_ranges + + child = ExternalChild("desktop", "https://desk.example/mcp", "https://desk.example", "read-desk", + computer_clock.held_range(_ranged("desktop", held))) + environment = env_gateway_provider.clock_followers_environment([child]) + + assert child.clock_range is None and "CLOCK_FOLLOWER_RANGES" not in environment + assert parse_clock_follower_ranges(environment.get("CLOCK_FOLLOWER_RANGES", "")) == {} + assert "desktop-computer: its card's clock/v1 range is left out" in caplog.text + + def test_a_computer_whose_card_follows_a_clock_hands_the_gateway_its_control_token_as_its_read_token(): from agent_env.env.envs._multi_computers import _clock_read_token diff --git a/tst/unit/env/gateway/clock_range_test.py b/tst/unit/env/gateway/clock_range_test.py index 9e4c2fbc3..540e36c40 100644 --- a/tst/unit/env/gateway/clock_range_test.py +++ b/tst/unit/env/gateway/clock_range_test.py @@ -1,7 +1,8 @@ """The clock's followers that hold only a range of times (a computer's and a clock-following agent's card declare clock/v1's ``range``, what 64 bits of nanoseconds since 1970 hold): while the clock has one, it refuses a set_time or an advance outside that range, naming the follower, and a set_time it would run past the range's end from within a real -hour; a declaration the clock is outside now is refused. Without such a follower the clock is as it always was.""" +hour; a declaration the clock is outside now, or would run past the end of from within a real hour, is refused. Without +such a follower the clock is as it always was.""" from __future__ import annotations import asyncio @@ -9,7 +10,7 @@ import pytest from agentenv_protocol.computer.clock import RANGE -from agent_env.env.gateway.clock import Clock, ClockError, parse_follower_range +from agent_env.env.gateway.clock import Clock, ClockError, OutsideRange, parse_follower_range from agent_env.env.gateway.clock_followers import ClockFollowers from agent_env.env.gateway.entrypoint import parse_clock_follower_ranges from tst.unit.env.gateway.triggers_time_test import FakeNow @@ -42,6 +43,8 @@ def test_without_a_follower_that_holds_a_range_the_clock_arms_anywhere_a_datetim def test_without_one_the_clock_still_refuses_what_it_always_did(): with pytest.raises(ClockError, match="would overflow datetime near the max"): _clock()[0].set_time("9999-12-31T12:00:00Z") + with pytest.raises(ClockError, match="unknown time zone 'Nowhere/Zone'"): + _clock()[0].set_time("9999-12-31T12:00:00Z", 1, "Nowhere/Zone") @pytest.mark.parametrize("virtual_time", ["0001-01-01T00:00:00Z", "1677-09-21T00:12:43Z", "2262-04-11T23:47:17Z", @@ -92,6 +95,22 @@ def test_a_declared_agent_brings_its_range_and_takes_it_away_when_retired(): assert clock.set_time("3026-01-01T00:00:00Z")["virtual_time"] == "3026-01-01T00:00:00Z" +@pytest.mark.parametrize("virtual_time, rate", [("2262-04-11T23:30:00Z", 1), ("2262-04-11T00:00:00Z", 86400)]) +def test_an_agent_the_clock_would_run_past_the_end_of_from_within_a_real_hour_is_refused_as_an_arm_with_it_is( + virtual_time, rate): + clock, followers, _ = _clock() + clock.set_time(virtual_time, rate=rate) + with pytest.raises(OutsideRange, match=f"the clock, at {virtual_time}, at rate {rate:g} would pass the end of the " + "times clock follower 'agent-solver' holds, .*, within a real hour"): + followers.declare("agent-solver", "token", HELD) + assert "agent-solver" not in followers.state() + with pytest.raises(OutsideRange, match="would pass the end"): + _clock({"agent-solver": HELD})[0].set_time(virtual_time, rate=rate) + clock.set_rate(0) + followers.declare("agent-solver", "token", HELD) + assert followers.state()["agent-solver"]["range"] == RANGE + + def test_an_agent_whose_range_the_clock_is_outside_now_is_refused_and_one_that_declares_none_is_not(): clock, followers, _ = _clock() clock.set_time("3026-01-01T00:00:00Z") @@ -114,3 +133,17 @@ def test_the_gateway_reads_each_computers_range_from_its_start_environment(): "desktop=yesterday/today"): with pytest.raises(ValueError, match="CLOCK_FOLLOWER_RANGES"): parse_clock_follower_ranges(spec) + with pytest.raises(ValueError, match="invalid CLOCK_FOLLOWER_RANGES entry for 'desktop': invalid RFC3339 range " + "earliest '1677-09-21'"): + parse_clock_follower_ranges("desktop=1677-09-21/2262-04-11") + + +@pytest.mark.parametrize("held, said", [ + ({"earliest": "x", "latest": "y"}, "invalid RFC3339 range earliest 'x'"), + ({"earliest": "1677-09-21T00:12:44Z", "latest": "2262-04-11"}, "invalid RFC3339 range latest '2262-04-11'"), + ({}, "range earliest must be an RFC3339 string, got NoneType"), + ({"earliest": "1677-09-21T00:12:44Z", "latest": 1}, "range latest must be an RFC3339 string, got int")]) +def test_a_range_that_doesnt_parse_is_refused_naming_the_end_of_it_that_doesnt(held, said): + with pytest.raises(ClockError, match=said) as refused: + parse_follower_range(held) + assert "virtual_time" not in str(refused.value) diff --git a/tst/unit/env/gateway/clock_watch_test.py b/tst/unit/env/gateway/clock_watch_test.py index e18caa897..06cdf2e69 100644 --- a/tst/unit/env/gateway/clock_watch_test.py +++ b/tst/unit/env/gateway/clock_watch_test.py @@ -482,6 +482,25 @@ async def test_declaring_a_follower_takes_a_name_and_a_read_token(gateway, body) assert answer.status_code == 400 and gw._clock_followers.state() == {} +HELD = {"earliest": "1677-09-21T00:12:44Z", "latest": "2262-04-11T23:47:16Z"} + + +@pytest.mark.asyncio +async def test_a_follower_the_clock_is_outside_the_range_of_is_refused_with_its_own_code_and_a_bad_range_without( + gateway): + gw = gateway(followers={}) + async with _client(gw) as client: + await client.put("/clock/set-time", json={"virtual_time": "3026-01-01T00:00:00Z"}) + outside = await client.put("/clock/followers", json={"name": "agent-solver", "read_token": "t", "range": HELD}) + malformed = await client.put("/clock/followers", json={"name": "agent-solver", "read_token": "t", + "range": {"earliest": "x", "latest": "y"}}) + assert outside.status_code == 400 and outside.json()["error"]["code"] == "outside_range" + assert "is outside the times clock follower 'agent-solver' holds" in outside.json()["error"]["message"] + assert malformed.status_code == 400 and malformed.json()["error"] == ( + "invalid RFC3339 range earliest 'x': expected YYYY-MM-DDThh:mm:ss[.fff](Z|+hh:mm)") + assert gw._clock_followers.state() == {} + + @pytest.mark.asyncio async def test_only_the_envs_control_token_declares_or_retires_a_follower(gateway): gw = gateway(followers={}, control_token="control") diff --git a/tst/unit/providers/env_providers/env_gateway_provider_test.py b/tst/unit/providers/env_providers/env_gateway_provider_test.py index ae8a096d4..74c85de90 100644 --- a/tst/unit/providers/env_providers/env_gateway_provider_test.py +++ b/tst/unit/providers/env_providers/env_gateway_provider_test.py @@ -2934,8 +2934,9 @@ def test_compose_declares_the_children_that_follow_the_clock_by_their_read_token def test_compose_hands_the_gateway_the_times_each_follower_that_holds_a_range_holds(): from agent_env.env.envs.service_db import ServiceDBConfig from agent_env.env.gateway import ExternalChild + from agent_env.env.gateway.clock import parse_follower_range - held = {"earliest": "1677-09-21T00:12:44Z", "latest": "2262-04-11T23:47:16Z"} + held = parse_follower_range({"earliest": "1677-09-21T00:12:44Z", "latest": "2262-04-11T23:47:16Z"}) rendered = EnvironmentGatewayProvider().create_docker_compose( mcp_servers=[], gateway_image="agent-gateway", state_provider=LocalPostgresStateProvider(service_db_config=ServiceDBConfig()), diff --git a/tst/unit/task_step/agent_clock_test.py b/tst/unit/task_step/agent_clock_test.py index fdc349132..4b5dbc595 100644 --- a/tst/unit/task_step/agent_clock_test.py +++ b/tst/unit/task_step/agent_clock_test.py @@ -9,6 +9,7 @@ import pytest from agentenv_protocol import CONTROL_TOKEN_HEADER +from agentenv_protocol.client import ExtensionCallError from agent_env.env.gateway.constants import EXT_CLOCK_URI from agent_env.task_step.context import DeployedAgent, StepContextError, TaskStepContext @@ -71,13 +72,14 @@ async def test_an_agent_is_declared_a_follower_then_handed_its_config_with_the_s HELD = {"earliest": "1677-09-21T00:12:44Z", "latest": "2262-04-11T23:47:16Z"} -def _ranged_agent() -> DeployedAgent: - sync = {"uri": EXT_CLOCK_URI, "params": {"endpoint": "/ext/clock", "methods": {"sync_time": SYNC_TIME}, "range": HELD}} +def _ranged_agent(held=HELD) -> DeployedAgent: + sync = {"uri": EXT_CLOCK_URI, "params": {"endpoint": "/ext/clock", "methods": {"sync_time": SYNC_TIME}, "range": held}} return dataclasses.replace(_agent(), a2a_card={"capabilities": {"extensions": [sync]}}) -def _refusing_declarations(monkeypatch, error: str) -> list: - """Record every request, as _mock_http does, the gateway refusing every declare_follower with ``error``.""" +def _refusing_declarations(monkeypatch, error) -> list: + """Record every request, as _mock_http does, the gateway refusing every declare_follower with ``error``: its + message, or its code and message.""" import httpx sent, real = [], httpx.AsyncClient @@ -110,7 +112,7 @@ async def test_an_agent_the_gateway_refuses_for_its_range_is_reported_and_skippe required): refusal = ("the clock, at 3026-01-01T00:00:00Z, is outside the times clock follower 'agent-solver' holds, " "1677-09-21T00:12:44Z to 2262-04-11T23:47:16Z") - sent = _refusing_declarations(monkeypatch, refusal) + sent = _refusing_declarations(monkeypatch, {"code": "outside_range", "message": refusal}) _no_servers(monkeypatch) context = await _context(_ranged_agent()) step = SyncEnvClockTaskStep(id="sync", version=1, env_id="e1", virtual_time="3026-01-01T00:00:00Z", @@ -127,6 +129,33 @@ async def test_an_agent_the_gateway_refuses_for_its_range_is_reported_and_skippe assert not [r for r in sent if r.url.path.endswith("/ext/clock/sync-time")] +@pytest.mark.asyncio +async def test_a_declaration_the_gateway_refuses_for_anything_but_the_range_fails_the_step_as_it_would_without_one( + monkeypatch): + refusal = "'agent-solver' is a follower this gateway started with, which a declaration doesn't replace" + _refusing_declarations(monkeypatch, refusal) + _no_servers(monkeypatch) + + with pytest.raises(ExtensionCallError, match="a follower this gateway started with"): + await _step().execute(await _context(_ranged_agent())) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("held", [{"earliest": "x", "latest": "y"}, {}, {"earliest": "1677-09-21T00:12:44Z"}]) +async def test_an_agent_whose_card_declares_a_range_that_doesnt_parse_follows_as_if_it_declared_none(monkeypatch, held, + caplog): + sent = _mock_http(monkeypatch, state={"env_get_time_url": CLOCK_URL}) + _no_servers(monkeypatch) + context = await _context(_ranged_agent(held)) + + await _step().execute(context) + + [declared] = [r for r in sent if r.method == "PUT" and r.url.path.endswith("/clock/followers")] + assert "range" not in json.loads(declared.content) + assert context.metadata["clock_configurations"][0]["agents"][0]["synced"] is True + assert "agent 'solver': its card's clock/v1 range is left out" in caplog.text + + @pytest.mark.asyncio async def test_only_the_agents_registered_with_the_env_follow_its_clock(monkeypatch): sent = _mock_http(monkeypatch, state={"env_get_time_url": CLOCK_URL}) From eeb111a5e3993e900d1ad5e4ee70979e22e40984 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Tue, 24 Nov 2026 09:53:10 -0800 Subject: [PATCH 13/16] fix(clock): a clock that runs to the end of a follower's range stands there, and sync_env_clock is as on main While the clock has a follower that holds only a range of times, its reads, state and watch stand at the end of the narrowest such range, at rate 0, so the gateway's tools and the computer agree (Greptile). sync_env_clock's up-front check is dropped: it reached steps with no follower range, which run as on main. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- src/agent_env/env/gateway/clock.py | 39 +++++++++---------- src/agent_env/env/gateway/constants.py | 2 +- .../task_step/task_steps/sync_env_clock.py | 32 +++++---------- tst/unit/env/gateway/clock_range_test.py | 17 ++++++++ tst/unit/task_step/sync_env_clock_test.py | 37 ------------------ 6 files changed, 47 insertions(+), 82 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index cd81057c2..9c3898d88 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -149,7 +149,7 @@ and deserialized through a registry. | Package | Contents | |---|---| -| `env/` | `Env` base class: a subclass declares `type`, implements `from_dict` and `async deploy(...) -> DeployedEnv`, and may override `reset`, `close` and `load_file_artifact_universe`; teardown closes each env a run deployed before terminating its sandboxes by id. Built-ins in `env/envs/`: `MCPServerEnv` (`mcp_server`), `MultiEnv` (`multi`, MCP servers plus websites and computers; its website browser is the one its `browser_envs` names, none for `[]`, else the run's when it has websites: an MCP server env such as `playwright-mcp` runs among the gateway's MCP servers, and a browser computer such as `chromium` on a sandbox of its own as one more computer child, sized by its `child_envs` entry, its tools under its name and `_`, routing the multi env's synthetic sites unless that entry's `site_routing` says, its network its own env's, as any computer child's; a website env deployed alone refuses a browser computer as the run's browser), `ServiceDBEnv` (`service_db`, PostgreSQL), `WebsiteEnv` (`website`, one site: a server image, `backend_image` in its env.toml, serving the pages and API, ready when its card's `website/v1` `ready` answers a `WebsiteReadiness` that says so, as `agentenv_protocol.website` (`website_readiness`, `env_readiness`) defines a website env's health for the deploy and `DeployedEnv.readiness()` alike, or, for a card without `ready`, when its `health` path answers 200, which is deprecated; its env.toml's `ready_timeout_s`, how long it may take from its server's container starting to ready, is that container's health check `start_period` and what the deploy waits, or its card's `ready` timeout if longer, and its `shm_mb` is the container's `shm_size`, each left to the gateway and Docker without them; the gateway container's `env/gateway/constants.py` mirrors the URI and op, a test keeping them equal; a separate frontend image is deprecated, warned of at put and optional in a bundle, and a stored `backend_docker_image_artifact` reads as the server image; a live one, `live = true`, is a real site whose server serves none of its pages, its `live`, `domains` and `allow_hosts` read at put from its server's `@website(...)` (`utils/card_naming.py` `WebsiteSource`) unless given, its `settings`' secrets only as references the gateway resolves as it writes the site's container (`WEBSITE_SETTINGS_ENV`); the gateway gives it no site route, a computer's site table leaves it out, a computer whose network is an allowlist is let reach its names (`MultiEnv.live_hosts`), a browser alone's forward port takes them straight to the real site (`site_proxy.py` `direct`), as the browser base's stand-in proxy takes any host, refusing nothing, each proxy logging each such connection as a JSON line, and a run that deploys one is marked live, `reproducible: false`), `GatewayEnv` (`gateway_server`), `ComputerDriverEnv` (`computer_driver`, `env/envs/computer/driver_env.py`: a computer driver's files and what its class declares for each platform it supports, read at put in a process of its own, `agentenv_protocol.computer._declare`, where the driver's own dependencies needn't be installed, with the `port` it serves on and its install by OS, `[install.]`, or for one distribution `[install."/"]`, which replaces its OS type's there, as its `known_failures` do (`env/envs/computer/utils/install.py`): files, apt `packages` with extra `sources`, a `python` requirements file for a venv, `downloads` by URL and sha256, `run` scripts, the services the base's init runs, and `ports`; it deploys only as a computer env's driver), `ComputerEnv` (`computer`, in `env/envs/computer/`: a base computer and a driver, matched at put by gate 1 before anything is stored, then composed by `composer.py` into an image for each form and arch on a builder of the put's sandbox provider, by default the env's (`utils/builder.py`; `--sandbox` on `env build`): this machine's Docker for `local`, else a VM of the provider, which fetches the put's stored files by signed URL, takes the rest inline and pushes to the image store itself, so it builds only with stores a remote VM reaches; each arch goes to the first link that runs it natively, else one that emulates it (a VM registers QEMU; `--no-emulate` leaves it `skipped` instead, for a later put), and its pair records the provider that built it (`builder`); a run or register composes only the computer envs its tasks deploy (`materialize._composed_envs`: each env a task's steps name, and each env those hold but a computer env's own apps and driver, which run inside it) and those it pulls in from an installed bundle, whose one write every bundle shares, every one for a plan with no tasks, any other composing at its first deploy; one that reuses a computer env composes what it has left (`pending`), a run, and a register given a `--sandbox`, only the forms its sandbox's deploys boot (`booted_forms`: on each link, the first form it boots natively, by the deploy's own rule, `boot.first_native`; a compose of a disk adds its container), and a deploy composes first what it boots that no compose started, and a container it runs natively that was built but not probed, as one whose probe a setting that didn't resolve stopped, booting it only once ready (`ComputerEnv.compose_unstarted`); tagged `agentenv-computers:` in the image store by a key of the image's Dockerfile, build context and lock so any env with the same inputs reuses it; every layer's packages, requirements and downloads are resolved at put in a container of the base for each arch (`utils/packages.py`, `utils/resolve_in_base.py`), stored in the object store by sha256 under `agentenv-packages/`, and listed in a lock stored by a digest of its inputs, which any env with the same inputs reuses, and builds install only the lock's files, every install step `RUN --network=none`; each pair's status goes into its metadata, `composed`, the arches built are written as its computer, a `computer` artifact over one index, and `agent-env env build` resumes what a put left; gate 3 (`utils/probing.py`) then boots each native build on the put's sandbox provider and probes it at `full`, making it `ready` or `failed`, and a build no provider runs natively stays `unverified`. Its deploy, through the `computer` env provider (`providers/env_providers/env_computer_provider.py`), boots its first `ready` build on a sandbox provider that runs its arch natively (`native_platforms()`), with no gateway in front and the driver's card as the env card, its `/dev/shm` the most its apps' Linux installs ask for (`shm_mb`, in MiB, which its composed computer and the deploy record keep; `--shm-size` on a container, `AGENTENV_SHM_MB` read by a Linux disk's init, passed only to a provider whose `SHARED_MEMORY` says it gives that much, else the sandbox's default, which the deploy logs), then checks its `display`; `deploy_env` `env_params` take a `form`, `computer_settings` (deploy-phase values of the base's settings; a secret one, here or on the env, only as a bare `secret:`/`env:` reference) and `driver_settings` (the driver's `ComputerSettings`, such as its default coordinate space); a `network` that allows nothing runs it on local Docker's internal network behind a relay (`providers/sandbox_providers/local_docker/relay/`); `reset` and `close` have the driver end its recordings first (`computer-recording/v1` `end_all`, each uploading what's left and its manifest under the grant it started with), and `reset` then boots a fresh container in its place (`reset_container`), keeping the computer's address but not an agent's MCP session to the old driver; its `load_file_artifact_universe` writes files under the session user's home through the driver's `data/add`, `Downloads` by default, each file's bytes through a read grant when the store's grants reach it and its network allows everything, else inline (`env/envs/computer/utils/inside.py`)), `ComputerAppEnv` (`computer_app`, `env/envs/computer/app_env.py`: an app on a computer, a `ComputerAppEnvironment` class its env.toml's `module` names, read at put by the same `_declare`, which declares each OS with its own decorator (`@linux(...)`, or `@install(os_type, spec)` for any OS type; `@linux(distribution=...)` or `@install("/", spec)` for one distribution, which replaces its OS type's there) holding its install, its launch and, optionally, a skill and settings and build settings that add to the class's there, and install steps and ready checks for every OS or those their `os=` names; everything that reads its settings, launch or steps asks for the computer's OS type; deployed alone it is a one-app computer env, a `ComputerEnv` of the computer and driver its env.toml names, the composer installing it under `/opt/agentenv/apps//` with its services as supervisord programs beside its own server (`agentenv_protocol.computer.serve_app`, in a venv with the protocol's `app` extra, on `.agentenv/server.sock` in its folder), which adds its launcher, launches a `boot` app once per boot and says through `computer-app/v1` whether it's ready, as the driver's `computer-ready` asks, its card named after it, and `env_params` `app_settings` handing it values of its `Settings` in `AGENTENV_APP_SETTINGS`, a secret one only as a bare reference, over its env.toml's `[settings]` and a computer env's `settings` beside it in `apps`, each by top-level field (`params.app_settings`; checked at put, a required one left to the deploy; the deploy record keeps the merged values as `app_settings`, secrets withheld); its env.toml's `build_settings`, values of its `BuildSettings` checked at put, are written to `.agentenv/build_settings.json` in its folder, so they're part of the image's key, its install steps read them, and a deploy can't change them). An env type whose services take environment data defines `load_environment_artifact` and `load_environment_universe_artifact`; `load_artifact` refuses an environment artifact aimed at a type that doesn't, at save and before it loads. An env built on the protocol SDK can serve agents a skill (`@agent_skill`, `skill/v1`), which `add_skills` `env_ids` installs under its environment name (behind a gateway, each server's under that server's name); a skill with files beside its SKILL.md goes as a bundle stored once per content under `agentenv-env-skills/` in the object store. `env/gateway/gateway.py` is the env-side gateway server, container-only code. Its site route, `/website//`, never forwards a site's data plane or card (`/agentenv/…`, `/.well-known/agent-env.json`), which agentenv reaches through `/svc//`; a site with no frontend image is served by its server image there. A request from a computer's site proxy names its computer (`AgentEnv-Computer`, sent from the proxy's private upstream headers, a page's own copy and any `AgentEnv-Role` it sends dropped) and takes the role driving that computer now (the gateway's computers being those `COMPUTERS` names, a multi env's, with or without a control token): the last to make an input call to its tools, as the call starts, through `/mcp`, `/step` or a trigger action under its `as` (`Gateway._drive`); without one, or from a computer the gateway doesn't front, it is `default`, the role read once per request. `changes/v1` (`ChangeAttribution`) counts no write window for a call to a computer's tools, a trigger action's included, so a write the computer's browser made goes to its request and one another party made during the call to that party. Its CDP route, `/browser//cdp//` (`env/gateway/browser_proxy.py`), reaches the website browser behind the `/svc` child ``, found from that child's card (it, or an app among its children, offering `browser/v1` `cdp` with `/cdp/` in its `computer-app/v1` `agent_routes`): it relays the browser's discovery and WebSocket both ways, each leg pinged every 20 s, and every CDP address the browser hands out, in `json/version`, `json/list` and its `cdp` answer through `/svc//`, comes back at the gateway, everything before `/cdp//` becoming the address the caller reached the gateway at and `/browser/`, keeping the https or wss of an address the browser minted under an origin its caller named, as `browser_connect_cdp` names the agent's, since a tunnel that ends TLS, as Modal's, may send no `X-Forwarded-Proto`; each connection is a `browser_connection` trajectory event, without its token. Its clock (`env/gateway/clock.py`) keeps to the range of times each of its followers holds when that follower's card declares one (clock/v1's `range`; a computer's and a clock-following agent's is 1677-09-21T00:12:44Z to 2262-04-11T23:47:16Z, what 64 bits of nanoseconds since 1970 hold, as their clock page and Python keep time, core passing a computer's as `CLOCK_FOLLOWER_RANGES` and an agent bringing its own to `declare_follower`): `set_time` and `advance` refuse a time outside it, naming the follower, `set_time` one it would run past the end of from within a real hour, and `declare_follower` one the clock is outside now or would run past the end of from within a real hour (error code `outside_range`); `set_rate` isn't checked, so `always_on` can start a clock it froze near the end again; a range that doesn't parse is left out by core, with a warning; a follower that declares none, or no follower, leaves the clock what a datetime holds. Its clock has one opaque version, a per-boot id and a count, that every `set_time`, `advance` and `clear` changes; `set_rate` (`/clock/set-rate`) changes an armed clock's rate from its time at the write, keeping its `t0` and generation as `advance` does, so time triggers keep their marks. Every clock change goes through `Gateway._change_clock`, which wakes the triggers when the change kept the clock's generation, answers the held watches and waits for the followers. Its followers, the computers on it (`CLOCK_FOLLOWER_TOKENS`, each child whose card serves `clock/v1` `sync_time`, by its read token, its control token for now), long-poll `/clock/watch` naming the version they show, each watch held up to the card's `hold_s` (`env/gateway/clock_followers.py`), and a write given `wait_followers_s` waits for each, answering 504 naming those behind, but not for one that hasn't watched for longer than a hold and a reconnect (`ClockFollowers.QUIET_S`), which it names at once with when each last watched; a restarted gateway is unarmed. While its clock is armed it serves agents `get_time` (`env/gateway/get_time.py`), which answers in UTC and also in the universe's zone, the one `sync_env_clock`'s `timezone` armed it in, or in an IANA `time_zone` it's given; executors' working `hours` (`env/gateway/triggers.py`) take a fixed `utc_offset` or an IANA `time_zone`. | +| `env/` | `Env` base class: a subclass declares `type`, implements `from_dict` and `async deploy(...) -> DeployedEnv`, and may override `reset`, `close` and `load_file_artifact_universe`; teardown closes each env a run deployed before terminating its sandboxes by id. Built-ins in `env/envs/`: `MCPServerEnv` (`mcp_server`), `MultiEnv` (`multi`, MCP servers plus websites and computers; its website browser is the one its `browser_envs` names, none for `[]`, else the run's when it has websites: an MCP server env such as `playwright-mcp` runs among the gateway's MCP servers, and a browser computer such as `chromium` on a sandbox of its own as one more computer child, sized by its `child_envs` entry, its tools under its name and `_`, routing the multi env's synthetic sites unless that entry's `site_routing` says, its network its own env's, as any computer child's; a website env deployed alone refuses a browser computer as the run's browser), `ServiceDBEnv` (`service_db`, PostgreSQL), `WebsiteEnv` (`website`, one site: a server image, `backend_image` in its env.toml, serving the pages and API, ready when its card's `website/v1` `ready` answers a `WebsiteReadiness` that says so, as `agentenv_protocol.website` (`website_readiness`, `env_readiness`) defines a website env's health for the deploy and `DeployedEnv.readiness()` alike, or, for a card without `ready`, when its `health` path answers 200, which is deprecated; its env.toml's `ready_timeout_s`, how long it may take from its server's container starting to ready, is that container's health check `start_period` and what the deploy waits, or its card's `ready` timeout if longer, and its `shm_mb` is the container's `shm_size`, each left to the gateway and Docker without them; the gateway container's `env/gateway/constants.py` mirrors the URI and op, a test keeping them equal; a separate frontend image is deprecated, warned of at put and optional in a bundle, and a stored `backend_docker_image_artifact` reads as the server image; a live one, `live = true`, is a real site whose server serves none of its pages, its `live`, `domains` and `allow_hosts` read at put from its server's `@website(...)` (`utils/card_naming.py` `WebsiteSource`) unless given, its `settings`' secrets only as references the gateway resolves as it writes the site's container (`WEBSITE_SETTINGS_ENV`); the gateway gives it no site route, a computer's site table leaves it out, a computer whose network is an allowlist is let reach its names (`MultiEnv.live_hosts`), a browser alone's forward port takes them straight to the real site (`site_proxy.py` `direct`), as the browser base's stand-in proxy takes any host, refusing nothing, each proxy logging each such connection as a JSON line, and a run that deploys one is marked live, `reproducible: false`), `GatewayEnv` (`gateway_server`), `ComputerDriverEnv` (`computer_driver`, `env/envs/computer/driver_env.py`: a computer driver's files and what its class declares for each platform it supports, read at put in a process of its own, `agentenv_protocol.computer._declare`, where the driver's own dependencies needn't be installed, with the `port` it serves on and its install by OS, `[install.]`, or for one distribution `[install."/"]`, which replaces its OS type's there, as its `known_failures` do (`env/envs/computer/utils/install.py`): files, apt `packages` with extra `sources`, a `python` requirements file for a venv, `downloads` by URL and sha256, `run` scripts, the services the base's init runs, and `ports`; it deploys only as a computer env's driver), `ComputerEnv` (`computer`, in `env/envs/computer/`: a base computer and a driver, matched at put by gate 1 before anything is stored, then composed by `composer.py` into an image for each form and arch on a builder of the put's sandbox provider, by default the env's (`utils/builder.py`; `--sandbox` on `env build`): this machine's Docker for `local`, else a VM of the provider, which fetches the put's stored files by signed URL, takes the rest inline and pushes to the image store itself, so it builds only with stores a remote VM reaches; each arch goes to the first link that runs it natively, else one that emulates it (a VM registers QEMU; `--no-emulate` leaves it `skipped` instead, for a later put), and its pair records the provider that built it (`builder`); a run or register composes only the computer envs its tasks deploy (`materialize._composed_envs`: each env a task's steps name, and each env those hold but a computer env's own apps and driver, which run inside it) and those it pulls in from an installed bundle, whose one write every bundle shares, every one for a plan with no tasks, any other composing at its first deploy; one that reuses a computer env composes what it has left (`pending`), a run, and a register given a `--sandbox`, only the forms its sandbox's deploys boot (`booted_forms`: on each link, the first form it boots natively, by the deploy's own rule, `boot.first_native`; a compose of a disk adds its container), and a deploy composes first what it boots that no compose started, and a container it runs natively that was built but not probed, as one whose probe a setting that didn't resolve stopped, booting it only once ready (`ComputerEnv.compose_unstarted`); tagged `agentenv-computers:` in the image store by a key of the image's Dockerfile, build context and lock so any env with the same inputs reuses it; every layer's packages, requirements and downloads are resolved at put in a container of the base for each arch (`utils/packages.py`, `utils/resolve_in_base.py`), stored in the object store by sha256 under `agentenv-packages/`, and listed in a lock stored by a digest of its inputs, which any env with the same inputs reuses, and builds install only the lock's files, every install step `RUN --network=none`; each pair's status goes into its metadata, `composed`, the arches built are written as its computer, a `computer` artifact over one index, and `agent-env env build` resumes what a put left; gate 3 (`utils/probing.py`) then boots each native build on the put's sandbox provider and probes it at `full`, making it `ready` or `failed`, and a build no provider runs natively stays `unverified`. Its deploy, through the `computer` env provider (`providers/env_providers/env_computer_provider.py`), boots its first `ready` build on a sandbox provider that runs its arch natively (`native_platforms()`), with no gateway in front and the driver's card as the env card, its `/dev/shm` the most its apps' Linux installs ask for (`shm_mb`, in MiB, which its composed computer and the deploy record keep; `--shm-size` on a container, `AGENTENV_SHM_MB` read by a Linux disk's init, passed only to a provider whose `SHARED_MEMORY` says it gives that much, else the sandbox's default, which the deploy logs), then checks its `display`; `deploy_env` `env_params` take a `form`, `computer_settings` (deploy-phase values of the base's settings; a secret one, here or on the env, only as a bare `secret:`/`env:` reference) and `driver_settings` (the driver's `ComputerSettings`, such as its default coordinate space); a `network` that allows nothing runs it on local Docker's internal network behind a relay (`providers/sandbox_providers/local_docker/relay/`); `reset` and `close` have the driver end its recordings first (`computer-recording/v1` `end_all`, each uploading what's left and its manifest under the grant it started with), and `reset` then boots a fresh container in its place (`reset_container`), keeping the computer's address but not an agent's MCP session to the old driver; its `load_file_artifact_universe` writes files under the session user's home through the driver's `data/add`, `Downloads` by default, each file's bytes through a read grant when the store's grants reach it and its network allows everything, else inline (`env/envs/computer/utils/inside.py`)), `ComputerAppEnv` (`computer_app`, `env/envs/computer/app_env.py`: an app on a computer, a `ComputerAppEnvironment` class its env.toml's `module` names, read at put by the same `_declare`, which declares each OS with its own decorator (`@linux(...)`, or `@install(os_type, spec)` for any OS type; `@linux(distribution=...)` or `@install("/", spec)` for one distribution, which replaces its OS type's there) holding its install, its launch and, optionally, a skill and settings and build settings that add to the class's there, and install steps and ready checks for every OS or those their `os=` names; everything that reads its settings, launch or steps asks for the computer's OS type; deployed alone it is a one-app computer env, a `ComputerEnv` of the computer and driver its env.toml names, the composer installing it under `/opt/agentenv/apps//` with its services as supervisord programs beside its own server (`agentenv_protocol.computer.serve_app`, in a venv with the protocol's `app` extra, on `.agentenv/server.sock` in its folder), which adds its launcher, launches a `boot` app once per boot and says through `computer-app/v1` whether it's ready, as the driver's `computer-ready` asks, its card named after it, and `env_params` `app_settings` handing it values of its `Settings` in `AGENTENV_APP_SETTINGS`, a secret one only as a bare reference, over its env.toml's `[settings]` and a computer env's `settings` beside it in `apps`, each by top-level field (`params.app_settings`; checked at put, a required one left to the deploy; the deploy record keeps the merged values as `app_settings`, secrets withheld); its env.toml's `build_settings`, values of its `BuildSettings` checked at put, are written to `.agentenv/build_settings.json` in its folder, so they're part of the image's key, its install steps read them, and a deploy can't change them). An env type whose services take environment data defines `load_environment_artifact` and `load_environment_universe_artifact`; `load_artifact` refuses an environment artifact aimed at a type that doesn't, at save and before it loads. An env built on the protocol SDK can serve agents a skill (`@agent_skill`, `skill/v1`), which `add_skills` `env_ids` installs under its environment name (behind a gateway, each server's under that server's name); a skill with files beside its SKILL.md goes as a bundle stored once per content under `agentenv-env-skills/` in the object store. `env/gateway/gateway.py` is the env-side gateway server, container-only code. Its site route, `/website//`, never forwards a site's data plane or card (`/agentenv/…`, `/.well-known/agent-env.json`), which agentenv reaches through `/svc//`; a site with no frontend image is served by its server image there. A request from a computer's site proxy names its computer (`AgentEnv-Computer`, sent from the proxy's private upstream headers, a page's own copy and any `AgentEnv-Role` it sends dropped) and takes the role driving that computer now (the gateway's computers being those `COMPUTERS` names, a multi env's, with or without a control token): the last to make an input call to its tools, as the call starts, through `/mcp`, `/step` or a trigger action under its `as` (`Gateway._drive`); without one, or from a computer the gateway doesn't front, it is `default`, the role read once per request. `changes/v1` (`ChangeAttribution`) counts no write window for a call to a computer's tools, a trigger action's included, so a write the computer's browser made goes to its request and one another party made during the call to that party. Its CDP route, `/browser//cdp//` (`env/gateway/browser_proxy.py`), reaches the website browser behind the `/svc` child ``, found from that child's card (it, or an app among its children, offering `browser/v1` `cdp` with `/cdp/` in its `computer-app/v1` `agent_routes`): it relays the browser's discovery and WebSocket both ways, each leg pinged every 20 s, and every CDP address the browser hands out, in `json/version`, `json/list` and its `cdp` answer through `/svc//`, comes back at the gateway, everything before `/cdp//` becoming the address the caller reached the gateway at and `/browser/`, keeping the https or wss of an address the browser minted under an origin its caller named, as `browser_connect_cdp` names the agent's, since a tunnel that ends TLS, as Modal's, may send no `X-Forwarded-Proto`; each connection is a `browser_connection` trajectory event, without its token. Its clock (`env/gateway/clock.py`) keeps to the range of times each of its followers holds when that follower's card declares one (clock/v1's `range`; a computer's and a clock-following agent's is 1677-09-21T00:12:44Z to 2262-04-11T23:47:16Z, what 64 bits of nanoseconds since 1970 hold, as their clock page and Python keep time, core passing a computer's as `CLOCK_FOLLOWER_RANGES` and an agent bringing its own to `declare_follower`): `set_time` and `advance` refuse a time outside it, naming the follower, `set_time` one it would run past the end of from within a real hour, and `declare_follower` one the clock is outside now or would run past the end of from within a real hour (error code `outside_range`); `set_rate` isn't checked, so `always_on` can start a clock it froze near the end again, and a clock that runs to the end of a follower's range stands there, reporting rate 0, so the gateway's tools and the follower agree; a range that doesn't parse is left out by core, with a warning; a follower that declares none, or no follower, leaves the clock what a datetime holds. Its clock has one opaque version, a per-boot id and a count, that every `set_time`, `advance` and `clear` changes; `set_rate` (`/clock/set-rate`) changes an armed clock's rate from its time at the write, keeping its `t0` and generation as `advance` does, so time triggers keep their marks. Every clock change goes through `Gateway._change_clock`, which wakes the triggers when the change kept the clock's generation, answers the held watches and waits for the followers. Its followers, the computers on it (`CLOCK_FOLLOWER_TOKENS`, each child whose card serves `clock/v1` `sync_time`, by its read token, its control token for now), long-poll `/clock/watch` naming the version they show, each watch held up to the card's `hold_s` (`env/gateway/clock_followers.py`), and a write given `wait_followers_s` waits for each, answering 504 naming those behind, but not for one that hasn't watched for longer than a hold and a reconnect (`ClockFollowers.QUIET_S`), which it names at once with when each last watched; a restarted gateway is unarmed. While its clock is armed it serves agents `get_time` (`env/gateway/get_time.py`), which answers in UTC and also in the universe's zone, the one `sync_env_clock`'s `timezone` armed it in, or in an IANA `time_zone` it's given; executors' working `hours` (`env/gateway/triggers.py`) take a fixed `utc_offset` or an IANA `time_zone`. | | `artifact/` | Immutable versioned artifacts; every `put()` creates a new version. The document goes to the document store, binary payloads to the object store. Every artifact but an environment universe, whose `metadata` key holds its legacy metadata file ids, carries a `metadata` dict outside its versioned fields, changed by compare-and-swap (`merge_metadata`). Built-ins: `CliArtifact` (`cli`), `ComputerArtifact` (`computer`, a base computer: its architectures, OS, session user, settings and container form, whose image `put` reads from its registry into `metadata.validated_images`), `FileArtifact` (`file`), `FileArtifactUniverse` (`file_artifact_universe`), `DockerImageArtifact` (`docker_image`), `EnvironmentArtifact` (`environment`: its environment's files by path, stored as the one wrapped `file_artifact_ref` every environment artifact had when it has one file at its filename, else as `file_artifact_refs`; `get_file_artifacts()` reads either, and a load hands each file to the env's `data/add` with its path, which a pre-v1 load, taking one file, refuses), `EnvironmentUniverseArtifact` (`environment_universe`), `SkillArtifact` (`skill`); `[artifacts] type_aliases` maps another stored spelling of a type onto one of them. A `DockerImageArtifact` holds a tar.gz of its image, or, written by `put_ref` (`--image-ref` on `env mcp-server put` and `a2a-agent put`), only a registry reference with its tag pinned to a digest, which sandboxes pull, or a published image's tag with its `image_digest` and its build context, which sandboxes pull by the digest and build from the context when they can't (the infra images, and a bundle agent built from a shipped agent's sources, `Plan.published`), or, written by `put_context`, only its build context, which a VM sandbox builds before running it (`VmSandbox.load_docker_images`) and Modal builds before creating its container (`ModalSandboxProvider.prepare_image`, outside a fallback chain's deadline); anything else that runs images by name (a container on the local provider, a lone server on any provider but Modal) refuses such an image. A build context (`utils/docker/context.py`) is what `docker build` would send, `.dockerignore` applied, written so equal files give equal bytes and an equal `source_digest`. | | `task/`, `task_step/` | A `Task` holds its `TaskStep`s inline; `Task.run()` executes them as a DAG. Its `headline_verifiers`, step ids saved only when set, name the grades that are its reward: one is the reward, several a multi-reward over them, none a multi-reward over every grade; it refuses one that names no step of the task, or one named twice. `depends_on` (None means all prior steps) gates a step, independent steps run concurrently, `fail_task_on_error` makes a failure fatal or tolerated, `retry_config` rolls a failed span back through the step journal and re-dispatches it. `task/lint.py` is `agent-env task lint` (a bundle folder, a task file or a stored task): an error is what a task gets wrong before it runs (a field its step doesn't read, a step's own `config_problems`, a headline that grades nothing, an aggregate source no verifier writes) and refuses `agent-env run`, `bundle register`, `task create`, `task validate` and `eval run`, and the bundle plans `openenv`'s `build_app` and the trainers make (`run`, `register`, `build_app`, `prepare_bundle` and the trainers take `--skip-lint`/`skip_lint`, which lifts lint's own rules but not a step's `config_problems`, which refused a bundle before lint; `eval run`'s lifts every error, since it checked none before); a warning is what may be wrong (a step's `config_warnings`, a store entity read with no version, no verifier, several and no headline, a judge that runs in the solver's own agent, which training refuses) and is only printed, each kind once by a run (`task.lint.said`), an eval run's unpinned references as one count (`unpinned_summary`), every one by `task lint`. `aggregate_verifiers` names its sources by step id (`sources`, `gates`) and reads their named grades: `combine` `pooled` (the default) pools their rows, `weighted_mean` weighs their scores, equally unless `weights` gives every source one, and a failing gate scores it 0; a failed or missing source fails it, and its older `verifier_ids` pools legacy entries as it always has. Built-in steps live in `task_step/task_steps/` (`deploy_env`, `deploy_agent`, `prompt_agent`, the verifiers under `verifiers/`, among them `start_computer_recording` (its driver draws each input over the frames in its caller's colour, and a pointer per role where the frames lack one, unless `annotation_settings` says `is_enabled: false`; a driver whose card lists no `annotate` records it plain, with a warning, and the run's recording entry says `annotated`) and `end_computer_recording`, `start_browser_recording` and `end_browser_recording` (`browser-recording/v1`: one recording per context, a lease's or the default one's, with a video of the tab its agent is on, its context's log, the browser's network log as HAR and opt-in frames keyed to the action log, the contexts its agents make recorded with it, one universe per recording, anything missing failing the run), and more). Every built-in verifier is on the `VerifierTaskStep` base (`verifiers/verifier.py`): it implements `verify` and returns a `Verification`, and the base writes the step's named grade to `context.metadata["grades"][]` (score, `min_passing_score`, `passed`, `verifier_status` graded, skipped or failed, criteria rows, type, version, and `verifier_settings`, the values the run graded with, its overrides applied and named in `overridden`, with `scoring_rules`) beside the legacy `verifications` entries every reader still takes; an exception from `verify` or a `Verification` with an `error`, as a timed-out `run_container_unit_tests_verifier`, is a failed grade, and `rubrics_verifier` still writes its `-trajectory-mistakes` entry itself. On an env whose card serves computer-exec/v1 (a computer), `run_code` with `env_id` and `run_container_unit_tests_verifier` with `env_id` run inside it as its session user through the driver: files staged with `data/add` and read with `data/get`, commands run with `run`; `computer_exec` runs one command there through `run` (a program and its arguments, or a string through `sh -c`; in a multi env, the computer it names), recorded under `computer_exec` in the run's metadata, a non-zero exit or a timeout failing it unless `check` is off, or with `background` starts it and leaves it running, as an app launched for the agent, a program that isn't there exiting 127; with `scope: "system"` it runs as root instead, through the computer's sandbox (`RootChannel`, `docker exec -u 0`), in the session user's folder and `HOME`, its output capped in the computer, never with `background` and not on a computer booted from a disk; on a Windows computer, which has no `sh`, a string or `background` command is refused; on a multi env, `load_artifact` with `env_id` puts an environment artifact named after one of its computers, or after an app of one, into that computer, the computer's own as files at their paths under the session user's home; `env_outcome_verifier` hands a `verify` that takes an `env_url` keyword the env's address. A computer's framework-only routes (everything but MCP and the card) take the per-deploy control token its provider boots it with (`DeployedEnv.control_token`, `AGENTENV_CONTROL_TOKEN`), a multi env's computers the multi env's own, which its gateway passes on only on their `/svc` routes and its clock watch (`CONTROL_TOKEN_CHILDREN`); framework calls send `deployed.control_headers`, `Task.run` runs every step under `protocol_v1.authorized` with each deployed env's (a `verify` included), and a `run_code` script inside the computer gets `input["env"]["headers"]`. `teardown_run` and the `teardown_sandboxes` step share one core (`task/teardown.py` `tear_down`): the recordings the run left open end with fresh grants, each env still up closes (`Env.close`; a computer env ends any recording still open), what stayed open is registered from its namespace, then every sandbox is terminated by id. A run whose teardown leaves sandboxes up, stopped by a second signal or failing, keeps on its instance the context it ended with (`record_teardown`), and `agent-env run` and `task run --keep` name `agent-env task teardown --instance `, which tears down what that context still records up, a running one only with `--force`. `task/episode/` runs a task with some of its agents played from outside, as a training loop does (`EpisodeSpec`). | | `store/` | Four store ABCs with local and cloud implementations: `DocumentStore` (SQLite, MongoDB, DynamoDB, Firestore with MongoDB compatibility), `ObjectStore` (filesystem, S3, Cloud Storage), `ImageStore` (local OCI registry, ECR), `SecretStore` (env vars or file, AWS Secrets Manager, Google Cloud Secret Manager). `VersionedEntityStore` implements the shared versioned get/put logic, `QueryBuilder` is the immutable chained query API, `store/base.py` holds the error types. `store/routing.py` is the local namespaces, `@local` and `@hf` (`is_local_id`), each with a documents file of its own: while the CLI or a `build_app` server runs, a local id and what a local task's run records go to local stores beside the configured ones, and that run's writes to the configured stores are refused. A new backend must pass the conformance kits in `tst/store/`. | diff --git a/src/agent_env/env/gateway/clock.py b/src/agent_env/env/gateway/clock.py index 9841b54a7..02a21f6aa 100644 --- a/src/agent_env/env/gateway/clock.py +++ b/src/agent_env/env/gateway/clock.py @@ -58,18 +58,6 @@ def parse_follower_range(value) -> FollowerRange: return held -def check_arm(virtual_time: str, rate=1.0, time_zone: str | None = None) -> tuple[datetime, float]: - """``virtual_time`` and ``rate`` as the clock arms at them, in ``time_zone`` if one, or the ClockError it refuses - them with whatever its followers, as sync_env_clock checks them before anything deploys.""" - t0 = _parse_rfc3339(virtual_time) - r = _parse_rate(1.0 if rate is None else rate) - if time_zone is not None and _zone(time_zone) is None: - raise ClockError(f"unknown time zone {time_zone!r}: pass an IANA time zone name such as 'America/New_York'") - if t0 > _MAX_T0 - timedelta(seconds=_OVERFLOW_HORIZON_S * r): - raise ClockError(f"virtual_time {virtual_time!r} at rate {r:g} would overflow datetime near the max") - return t0, r - - def _check_range(what: str, name: str, held: FollowerRange, t: datetime, rate: float | None) -> None: """Refuse ``t`` outside the range follower ``name`` holds, or, run at ``rate``, one it would pass the end of that range from within a real hour.""" @@ -241,7 +229,12 @@ def t0(self) -> datetime | None: def set_time(self, virtual_time: str, rate=1.0, time_zone: str | None = None) -> dict: """Arm/re-arm: anchor t0=virtual_time to now, advancing at `rate` virtual s per real s, in the universe's `time_zone` (its users' IANA zone), or none.""" - t0, r = check_arm(virtual_time, rate, time_zone) + t0 = _parse_rfc3339(virtual_time) + r = _parse_rate(1.0 if rate is None else rate) + if time_zone is not None and _zone(time_zone) is None: + raise ClockError(f"unknown time zone {time_zone!r}: pass an IANA time zone name such as 'America/New_York'") + if t0 > _MAX_T0 - timedelta(seconds=_OVERFLOW_HORIZON_S * r): + raise ClockError(f"virtual_time {virtual_time!r} at rate {r:g} would overflow datetime near the max") self._check_followers(f"virtual_time {virtual_time!r}", t0, r) with self._lock: self._bank(t0) @@ -266,7 +259,7 @@ def check_follower(self, name: str, held: FollowerRange) -> None: with self._lock: if not self._armed or self._t0 is None: return - now, rate = _advance(self._t0, (self._now() - self._anchor) * self._rate + self._ahead), self._rate + (now, _), rate = self._current(), self._rate _check_range(f"the clock, at {_iso(now)},", name, held, now, rate) def set_rate(self, rate) -> dict: @@ -297,7 +290,7 @@ def advance(self, virtual_time: str) -> dict: if target > _MAX_T0 - timedelta(seconds=_OVERFLOW_HORIZON_S * self._rate): raise ClockError(f"virtual_time {virtual_time!r} at rate {self._rate:g} would overflow datetime near the max") self._check_followers(f"virtual_time {virtual_time!r}", target, None) - current = _advance(self._t0, (self._now() - self._anchor) * self._rate + self._ahead) + current, _ = self._current() jump = (target - current).total_seconds() if jump < 0: raise ClockError(f"advance only moves forward: {virtual_time!r} is before the current {_iso(current)}") @@ -328,8 +321,7 @@ def now(self) -> datetime | None: with self._lock: if not self._armed or self._t0 is None: return None - elapsed = self._now() - self._anchor - return _advance(self._t0, elapsed * self._rate + self._ahead) + return self._current()[0] @property def time_zone(self) -> str | None: @@ -355,11 +347,18 @@ def state(self) -> dict: with self._lock: if not self._armed or self._t0 is None: return {"armed": False, "version": self.version} - elapsed = self._now() - self._anchor - return {"armed": True, "t0": _iso(self._t0), "virtual_seconds_per_real_second": self._rate, - "virtual_time": _iso(_advance(self._t0, elapsed * self._rate + self._ahead)), + current, at_end = self._current() + return {"armed": True, "t0": _iso(self._t0), "virtual_seconds_per_real_second": 0.0 if at_end else self._rate, + "virtual_time": _iso(current), **({"time_zone": self._time_zone} if self._time_zone else {}), "version": self.version} + def _current(self) -> tuple[datetime, bool]: + """The current arm's time now, and whether it stands at the end of the narrowest range a follower holds: a clock + doesn't run past what a follower of it can show, so the gateway's tools and the follower agree. Lock held.""" + current = _advance(self._t0, (self._now() - self._anchor) * self._rate + self._ahead) + end = min((held.latest for held in self._follower_ranges().values()), default=None) + return (end, True) if end is not None and current >= end else (current, False) + def _bank(self, t0: datetime | None = None) -> None: """Fold the stretch since the last arm/clear into `_lived` at its rate, and start the next one now.""" now = self._now() diff --git a/src/agent_env/env/gateway/constants.py b/src/agent_env/env/gateway/constants.py index 408939d38..56e1d72db 100644 --- a/src/agent_env/env/gateway/constants.py +++ b/src/agent_env/env/gateway/constants.py @@ -274,7 +274,7 @@ def random_mcp_server_name() -> str: }, { "uri": EXT_CLOCK_URI, - "description": "Virtual clock (urn:agentenv:clock/v1): read the gateway's virtual time (wall-clock-derived, rate-scaled) via get_time; set_time/set_rate/advance/clear are the harness control path, each changing the clock's opaque version and, given wait_followers_s, answering 504 naming the followers that don't show it in time (set_rate keeps t0, as advance does, so time triggers keep their marks; rate 0 freezes the clock); declare_follower adds a follower after the gateway started (an agent the run deploys), with the read token its watches carry and, for one that holds only a range of times (its card's clock/v1 range), that range, refused with error code outside_range when the clock is outside it now or would run past its end from within a real hour; set_time and advance refuse a time outside the range of a follower the clock has, naming it, and set_time one it would run past that range's end from within a real hour; retire_follower removes one so writes stop waiting for it (an agent the run tears down); a follower follows it through watch, a long poll naming the version it shows and held up to hold_s; state's followers block is diagnostic, not part of the contract.", + "description": "Virtual clock (urn:agentenv:clock/v1): read the gateway's virtual time (wall-clock-derived, rate-scaled) via get_time; set_time/set_rate/advance/clear are the harness control path, each changing the clock's opaque version and, given wait_followers_s, answering 504 naming the followers that don't show it in time (set_rate keeps t0, as advance does, so time triggers keep their marks; rate 0 freezes the clock); declare_follower adds a follower after the gateway started (an agent the run deploys), with the read token its watches carry and, for one that holds only a range of times (its card's clock/v1 range), that range, refused with error code outside_range when the clock is outside it now or would run past its end from within a real hour; set_time and advance refuse a time outside the range of a follower the clock has, naming it, and set_time one it would run past that range's end from within a real hour, and a clock that runs to that end stands there, at rate 0; retire_follower removes one so writes stop waiting for it (an agent the run tears down); a follower follows it through watch, a long poll naming the version it shows and held up to hold_s; state's followers block is diagnostic, not part of the contract.", "params": {"endpoint": "/clock/time", "methods": { "get_time": {"method": "GET", "endpoint": "/clock/time"}, "set_time": {"method": "PUT", "endpoint": "/clock/set-time", "request": {"type": "object", "properties": {"virtual_time": {"type": "string"}, "virtual_seconds_per_real_second": {"type": "number"}, "time_zone": {"type": "string"}, **_WAIT_FOLLOWERS}, "required": ["virtual_time"]}}, diff --git a/src/agent_env/task_step/task_steps/sync_env_clock.py b/src/agent_env/task_step/task_steps/sync_env_clock.py index f0e1e6927..f14876926 100644 --- a/src/agent_env/task_step/task_steps/sync_env_clock.py +++ b/src/agent_env/task_step/task_steps/sync_env_clock.py @@ -28,7 +28,6 @@ from agent_env.a2a_agent.clock import follow_agents, on_deployment, torn_down from agent_env.env.env import Env, EnvCapabilityUnsupported, gateway_url_of -from agent_env.env.gateway.clock import ClockError, check_arm from agent_env.env.gateway.constants import EXT_CLOCK_URI from agent_env.task_step.context import StepContextError, TaskStepContext from agent_env.entity.refs import EntityRef @@ -56,19 +55,15 @@ def resolve_virtual_time(virtual_time: str, timezone: Optional[str]) -> str: parsed = datetime.fromisoformat(virtual_time) except ValueError as e: raise ValueError(f"virtual_time {virtual_time!r} is not an ISO 8601 / RFC3339 timestamp") from e - try: - if parsed.tzinfo is None: - local = parsed.replace(tzinfo=zone) - if local.astimezone(_utc_tz.utc).astimezone(zone).replace(tzinfo=None) != parsed: - raise ValueError(f"virtual_time {virtual_time!r} does not exist in {zone.key} (clock skips it)") - return local.astimezone(_utc_tz.utc).isoformat().replace("+00:00", "Z") - if parsed.astimezone(zone).utcoffset() != parsed.utcoffset(): - raise ValueError(f"virtual_time {virtual_time!r} carries offset {parsed.utcoffset()} but {zone.key} is at " - f"{parsed.astimezone(zone).utcoffset()} at that instant; drop the offset or fix the " - "timezone") - return parsed.astimezone(_utc_tz.utc).isoformat().replace("+00:00", "Z") - except OverflowError as e: - raise ValueError(f"virtual_time {virtual_time!r} in {zone.key} is outside the times a datetime holds") from e + if parsed.tzinfo is None: + local = parsed.replace(tzinfo=zone) + if local.astimezone(_utc_tz.utc).astimezone(zone).replace(tzinfo=None) != parsed: + raise ValueError(f"virtual_time {virtual_time!r} does not exist in {zone.key} (clock skips it)") + return local.astimezone(_utc_tz.utc).isoformat().replace("+00:00", "Z") + if parsed.astimezone(zone).utcoffset() != parsed.utcoffset(): + raise ValueError(f"virtual_time {virtual_time!r} carries offset {parsed.utcoffset()} but {zone.key} is at " + f"{parsed.astimezone(zone).utcoffset()} at that instant; drop the offset or fix the timezone") + return parsed.astimezone(_utc_tz.utc).isoformat().replace("+00:00", "Z") class SyncEnvClockTaskStep(TaskStep): @@ -118,15 +113,6 @@ def __init__( self.timezone = timezone.strip() if isinstance(timezone, str) else timezone self.armed_virtual_time = resolve_virtual_time(virtual_time, self.timezone) - def config_problems(self) -> list[str]: - """A time or rate the gateway's clock would refuse to arm at whatever its followers, said before anything - deploys; a follower that holds only a range of times refuses one outside it when the step runs.""" - try: - check_arm(self.armed_virtual_time, self.virtual_seconds_per_real_second) - except ClockError as e: - return [str(e)] - return [] - def to_dict(self) -> dict: base = super().to_dict() base["env_id"] = self.env_id diff --git a/tst/unit/env/gateway/clock_range_test.py b/tst/unit/env/gateway/clock_range_test.py index 540e36c40..de8632625 100644 --- a/tst/unit/env/gateway/clock_range_test.py +++ b/tst/unit/env/gateway/clock_range_test.py @@ -147,3 +147,20 @@ def test_a_range_that_doesnt_parse_is_refused_naming_the_end_of_it_that_doesnt(h with pytest.raises(ClockError, match=said) as refused: parse_follower_range(held) assert "virtual_time" not in str(refused.value) + + +def test_a_clock_that_runs_into_a_followers_end_stands_there_at_rate_0_and_one_with_none_runs_on(): + """As the computer's page stands at the end of its range, so does the gateway's clock while it has the computer, so + the gateway's tools and the computer's programs agree; with no follower that holds a range it runs on as before.""" + ranged, _, now = _clock({"desktop": HELD}) + ranged.set_time("2262-04-11T22:47:16Z") + now.tick(3601) + assert ranged.read()["virtual_time"] == "2262-04-11T23:47:16Z" + state = ranged.state() + assert (state["virtual_time"], state["virtual_seconds_per_real_second"]) == ("2262-04-11T23:47:16Z", 0.0) + + free, _, now = _clock() + free.set_time("2262-04-11T22:47:16Z") + now.tick(3601) + assert free.read()["virtual_time"] == "2262-04-11T23:47:17Z" + assert free.state()["virtual_seconds_per_real_second"] == 1.0 diff --git a/tst/unit/task_step/sync_env_clock_test.py b/tst/unit/task_step/sync_env_clock_test.py index 28bedc2cb..191247b98 100644 --- a/tst/unit/task_step/sync_env_clock_test.py +++ b/tst/unit/task_step/sync_env_clock_test.py @@ -1,14 +1,11 @@ """Unit tests for SyncEnvClockTaskStep — round-trip + the per-server sync_time fan-out (mocked).""" import json -import re from types import SimpleNamespace import pytest from agent_env.env.env import DeployedEnv, DeployedGatewayEnv, DeployedSandboxEnv from agent_env.env.gateway.constants import EXT_CLOCK_URI, WELL_KNOWN_PATH -from agent_env.task import Task -from agent_env.task.lint import lint from agent_env.task_step.context import StepContextError, TaskStepContext from agent_env.task_step.task_steps import sync_env_clock as mod from agent_env.task_step.task_steps.sync_env_clock import SyncEnvClockTaskStep, resolve_virtual_time @@ -344,40 +341,6 @@ def test_a_time_that_disagrees_with_the_zone_is_refused(virtual_time, zone, matc _zoned(virtual_time, zone) -@pytest.mark.parametrize("virtual_time, zone", [("0001-01-01T00:00:00", "Asia/Kolkata"), - ("9999-12-31T23:00:00", "America/Chicago")]) -def test_a_wall_time_whose_instant_no_date_holds_is_refused_saying_so(virtual_time, zone): - with pytest.raises(ValueError, match=re.escape(f"virtual_time '{virtual_time}' in {zone} is outside the times a " - "datetime holds")): - _zoned(virtual_time, zone) - - -@pytest.mark.parametrize("kwargs, problem", [ - ({"virtual_time": "9999-12-31T12:00:00Z"}, - "virtual_time '9999-12-31T12:00:00Z' at rate 1 would overflow datetime near the max"), - ({"virtual_time": "2026-01-01T12:00:00"}, "invalid RFC3339 virtual_time '2026-01-01T12:00:00'"), - ({"virtual_time": T0, "virtual_seconds_per_real_second": -1}, "rate must be non-negative"), -]) -def test_a_time_or_rate_the_gateway_would_refuse_is_a_problem_before_anything_deploys(kwargs, problem): - problems = SyncEnvClockTaskStep(id="sync", version=1, env_id="e1", depends_on=[], **kwargs).config_problems() - assert len(problems) == 1 and problems[0].startswith(problem), problems - - -def test_lint_names_the_step_of_a_time_the_gateway_would_refuse_once(): - step = SyncEnvClockTaskStep(id="clock", version=1, env_id="e1", virtual_time="2026-01-01T12:00:00", depends_on=[]) - found = [finding.text for finding in lint(Task(id="t", version=1, steps=[step])) if finding.rule == "step-config"] - assert found == ["step 'clock': invalid RFC3339 virtual_time '2026-01-01T12:00:00': expected " - "YYYY-MM-DDThh:mm:ss[.fff](Z|+hh:mm)"] - - -def test_a_time_the_gateway_arms_at_is_no_problem(): - assert _step().config_problems() == [] - assert _step(virtual_seconds_per_real_second=0).config_problems() == [] - for far in ("1600-01-01T00:00:00Z", "3026-01-01T00:00:00Z", "9999-06-01T00:00:00Z"): - assert SyncEnvClockTaskStep(id="sync", version=1, env_id="e1", virtual_time=far).config_problems() == [] - assert _zoned("1677-09-21T09:31:43", "Asia/Tokyo").config_problems() == [] - - def test_without_a_zone_virtual_time_is_passed_through_untouched(): assert _step().armed_virtual_time == T0 assert resolve_virtual_time("2026-01-01T12:00:00", None) == "2026-01-01T12:00:00" From ed0240aecb76f1188d82fba8dab84f8dc03e5698 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Tue, 24 Nov 2026 09:54:24 -0800 Subject: [PATCH 14/16] test(clock): integration tests pin a computer's refusal past its range and an MCP-only gateway arming past 2262 Co-Authored-By: Claude Opus 5.5 --- tst/integration/computer/computer_clock_test.py | 12 +++++++++++- tst/integration/env/gateway/gateway_test.py | 9 +++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/tst/integration/computer/computer_clock_test.py b/tst/integration/computer/computer_clock_test.py index cdda42e51..faa7a2074 100644 --- a/tst/integration/computer/computer_clock_test.py +++ b/tst/integration/computer/computer_clock_test.py @@ -3,7 +3,8 @@ keeps but the token; sync_env_clock arms the clock as a task does, calling the computer's sync_time; through the gateway's jumps of a day and a week on and a month back, a rate of 10, a freeze and a restart, a killed follower and a reset, the session's clock is within 1 s of the gateway's once the follower has acknowledged each change, and runs at -the gateway's rate; a follower killed comes back within 3 s. Each reading is taken inside the computer, between two +the gateway's rate; a follower killed comes back within 3 s. The computer's card declares the times it holds, so the +gateway refuses a time past them, naming it. Each reading is taken inside the computer, between two of real time, so no driver or exec latency is in it. Needs Docker and the local registry on localhost:5000.""" import asyncio @@ -12,6 +13,8 @@ from urllib.parse import urlsplit import pytest +from agentenv_protocol.client import ExtensionCallError +from agentenv_protocol.computer.clock import RANGE from agent_env.env import Env from agent_env.env.env import DeployedEnv @@ -89,6 +92,9 @@ async def test_a_multi_envs_computer_keeps_within_a_second_of_its_gateways_clock await _shown(deployed) skews["after a reset"] = await _skew(deployed, own) state_after_reset = await _shown(deployed) + with pytest.raises(ExtensionCallError) as refusal: + await deployed.invoke(EXT_CLOCK_URI, "set_time", {"virtual_time": "3026-11-23T12:00:00Z"}, timeout=30) + state_after_refusal = await deployed.invoke(EXT_CLOCK_URI, "state", timeout=30) finally: report = await teardown_run(context) @@ -99,6 +105,10 @@ async def test_a_multi_envs_computer_keeps_within_a_second_of_its_gateways_clock assert abs(rates[RATE] / RATE - 1) < 0.05 and abs(rates["frozen"]) < 0.01, rates assert back not in ("-", killed) and came_back < FOLLOWER_BACK_S, came_back assert state_after_reset["followers"]["desktop"]["version"] == state_after_reset["version"], state_after_reset + assert state_after_reset["followers"]["desktop"]["range"] == RANGE, state_after_reset + assert refusal.value.detail == ("virtual_time '3026-11-23T12:00:00Z' is outside the times clock follower 'desktop' " + "holds, 1677-09-21T00:12:44Z to 2262-04-11T23:47:16Z"), refusal.value.detail + assert state_after_refusal["version"] == state_after_reset["version"], state_after_refusal assert not report.failed diff --git a/tst/integration/env/gateway/gateway_test.py b/tst/integration/env/gateway/gateway_test.py index 1132db47d..861c395bd 100644 --- a/tst/integration/env/gateway/gateway_test.py +++ b/tst/integration/env/gateway/gateway_test.py @@ -3366,6 +3366,15 @@ async def _rate_check(client, gw, rate, sleep_s=5.0): assert GET_TIME not in (await _get_time_surfaces(client, gw, result.mcp_url)).mcp assert (await _read(client, gw)).status_code == 404, "rejected arm must not arm the clock" + # With no follower that holds only a range of times (no computer, no clock-following agent), the clock + # arms past 2262-04-11 as it always has. + for far in ("3026-11-23T12:00:00Z", "9999-06-01T12:00:00Z"): + armed_far = await client.put(f"{gw}/clock/set-time", + json={"virtual_time": far, "virtual_seconds_per_real_second": 0}, timeout=30) + assert armed_far.status_code == 200 and armed_far.json()["virtual_time"] == far, armed_far.text + assert (await client.post(f"{gw}/clock/clear", timeout=30)).status_code == 200 + assert (await _read(client, gw)).status_code == 404 + # Without the deploy's control token, every control route refuses; the clock's routes and the reads stay open. async with httpx.AsyncClient() as agent: for method, path in (("POST", "/tools/enable"), ("POST", "/tools/disable"), ("POST", "/triggers/register"), From 3cc0d61ec59226913bca7f08122c51c57172af82 Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Tue, 24 Nov 2026 10:17:52 -0800 Subject: [PATCH 15/16] fix(clock): a clock that runs to the end of a follower's range stops there, rather than only reading there Its run up to the end is folded in and its rate set to 0 the first time anything reads or writes it after, so its delays and marks stop with it (elapsed and at_elapsed agree with the time it shows), retiring the follower leaves it where it stands rather than jumping it to where it would have run, and a follower declared while it stands is taken (Greptile, testers). Co-Authored-By: Claude Opus 5.5 --- src/agent_env/env/gateway/clock.py | 50 +++++++++++++++----- src/agent_env/env/gateway/clock_followers.py | 1 + tst/unit/env/gateway/clock_range_test.py | 22 +++++++++ 3 files changed, 62 insertions(+), 11 deletions(-) diff --git a/src/agent_env/env/gateway/clock.py b/src/agent_env/env/gateway/clock.py index 02a21f6aa..ea3dc37a3 100644 --- a/src/agent_env/env/gateway/clock.py +++ b/src/agent_env/env/gateway/clock.py @@ -237,6 +237,7 @@ def set_time(self, virtual_time: str, rate=1.0, time_zone: str | None = None) -> raise ClockError(f"virtual_time {virtual_time!r} at rate {r:g} would overflow datetime near the max") self._check_followers(f"virtual_time {virtual_time!r}", t0, r) with self._lock: + self._stop_at_end() self._bank(t0) self._t0 = t0 self._rate = r @@ -259,7 +260,8 @@ def check_follower(self, name: str, held: FollowerRange) -> None: with self._lock: if not self._armed or self._t0 is None: return - (now, _), rate = self._current(), self._rate + self._stop_at_end() + now, rate = self._current(), self._rate _check_range(f"the clock, at {_iso(now)},", name, held, now, rate) def set_rate(self, rate) -> dict: @@ -270,6 +272,7 @@ def set_rate(self, rate) -> dict: with self._lock: if not self._armed or self._t0 is None: raise ClockError("clock is not armed") + self._stop_at_end() now = self._now() ran = (now - self._anchor) * self._rate if _advance(self._t0, ran + self._ahead) > _MAX_T0 - timedelta(seconds=_OVERFLOW_HORIZON_S * r): @@ -290,7 +293,8 @@ def advance(self, virtual_time: str) -> dict: if target > _MAX_T0 - timedelta(seconds=_OVERFLOW_HORIZON_S * self._rate): raise ClockError(f"virtual_time {virtual_time!r} at rate {self._rate:g} would overflow datetime near the max") self._check_followers(f"virtual_time {virtual_time!r}", target, None) - current, _ = self._current() + self._stop_at_end() + current = self._current() jump = (target - current).total_seconds() if jump < 0: raise ClockError(f"advance only moves forward: {virtual_time!r} is before the current {_iso(current)}") @@ -302,6 +306,7 @@ def advance(self, virtual_time: str) -> dict: def clear(self) -> dict: """Disarm (idempotent). Afterwards reads 404.""" with self._lock: + self._stop_at_end() self._bank() self._armed = False self._t0 = None @@ -315,13 +320,15 @@ def clear(self) -> dict: def elapsed(self) -> float: """Virtual seconds run so far: real time at each arm's rate (1 unarmed), plus each forward re-arm or advance.""" with self._lock: + self._stop_at_end() return self._lived + (self._now() - self._anchor) * self._rate def now(self) -> datetime | None: with self._lock: if not self._armed or self._t0 is None: return None - return self._current()[0] + self._stop_at_end() + return self._current() @property def time_zone(self) -> str | None: @@ -334,6 +341,7 @@ def at_elapsed(self, elapsed: float) -> datetime | None: with self._lock: if not self._armed or self._t0 is None: return None + self._stop_at_end() return _advance(self._t0, elapsed - self._lived + self._ahead) def read(self) -> dict: @@ -347,17 +355,37 @@ def state(self) -> dict: with self._lock: if not self._armed or self._t0 is None: return {"armed": False, "version": self.version} - current, at_end = self._current() - return {"armed": True, "t0": _iso(self._t0), "virtual_seconds_per_real_second": 0.0 if at_end else self._rate, - "virtual_time": _iso(current), + self._stop_at_end() + return {"armed": True, "t0": _iso(self._t0), "virtual_seconds_per_real_second": self._rate, + "virtual_time": _iso(self._current()), **({"time_zone": self._time_zone} if self._time_zone else {}), "version": self.version} - def _current(self) -> tuple[datetime, bool]: - """The current arm's time now, and whether it stands at the end of the narrowest range a follower holds: a clock - doesn't run past what a follower of it can show, so the gateway's tools and the follower agree. Lock held.""" - current = _advance(self._t0, (self._now() - self._anchor) * self._rate + self._ahead) + def _current(self) -> datetime: + """The current arm's time now. Lock held.""" + return _advance(self._t0, (self._now() - self._anchor) * self._rate + self._ahead) + + def stop_at_end(self) -> None: + """``_stop_at_end``, taking the lock: before a follower's range stops applying, as when it retires.""" + with self._lock: + self._stop_at_end() + + def _stop_at_end(self) -> None: + """Once the clock has run to the end of the narrowest range a follower holds, stop it there, frozen (rate 0) from + the moment it got there, as the follower's page stands there: its reads, delays and marks agree with what the + follower shows, and it stays there until a write moves it. Lock held.""" + if not self._armed or self._t0 is None or self._rate <= 0: + return end = min((held.latest for held in self._follower_ranges().values()), default=None) - return (end, True) if end is not None and current >= end else (current, False) + if end is None: + return + now = self._now() + to_end = max(0.0, (end - _advance(self._t0, self._ahead)).total_seconds()) + if (now - self._anchor) * self._rate < to_end: + return + self._lived += to_end + self._ahead += to_end + self._anchor = now + self._rate = 0.0 def _bank(self, t0: datetime | None = None) -> None: """Fold the stretch since the last arm/clear into `_lived` at its rate, and start the next one now.""" diff --git a/src/agent_env/env/gateway/clock_followers.py b/src/agent_env/env/gateway/clock_followers.py index 196659c72..2a4b69615 100644 --- a/src/agent_env/env/gateway/clock_followers.py +++ b/src/agent_env/env/gateway/clock_followers.py @@ -75,6 +75,7 @@ async def retire(self, name: str) -> bool: one; a follower the gateway started with stays.""" if name not in self._declared: return False + self._clock().stop_at_end() # a clock standing at the end of its range stays there when the range goes async with self._acks: self._declared.discard(name) for followers in (self._tokens, self._shown, self._seen, self._held): diff --git a/tst/unit/env/gateway/clock_range_test.py b/tst/unit/env/gateway/clock_range_test.py index de8632625..39e952131 100644 --- a/tst/unit/env/gateway/clock_range_test.py +++ b/tst/unit/env/gateway/clock_range_test.py @@ -164,3 +164,25 @@ def test_a_clock_that_runs_into_a_followers_end_stands_there_at_rate_0_and_one_w now.tick(3601) assert free.read()["virtual_time"] == "2262-04-11T23:47:17Z" assert free.state()["virtual_seconds_per_real_second"] == 1.0 + + +def test_a_clock_stopped_at_a_followers_end_stops_its_delays_keeps_still_when_the_follower_goes_and_takes_one_more(): + """Stopped there, not only read there: a delay counts no further (elapsed and at_elapsed agree with the time shown), + retiring the follower leaves the clock where it stands rather than jumping it to where it would have run, and a + follower declared while it stands is taken, since the clock runs no further.""" + clock, followers, now = _clock() + clock.set_time("2262-04-11T22:47:16Z") + followers.declare("agent-solver", "token", HELD) + now.tick(3600 * 5) + elapsed = clock.elapsed() + now.tick(600) + assert clock.elapsed() == elapsed and clock.at_elapsed(clock.elapsed()) == HELD.latest + + followers.declare("agent-late", "token", HELD) + assert asyncio.run(followers.retire("agent-solver")) and asyncio.run(followers.retire("agent-late")) + now.tick(600) + state = clock.state() + assert (state["virtual_time"], state["virtual_seconds_per_real_second"]) == ("2262-04-11T23:47:16Z", 0.0) + assert clock.set_rate(1)["virtual_seconds_per_real_second"] == 1.0 + now.tick(1) + assert clock.read()["virtual_time"] == "2262-04-11T23:47:17Z" From 3941a67e5e9d308c33f3fd7d58fb563fb45fcadc Mon Sep 17 00:00:00 2001 From: Edgar Arakelyan Date: Tue, 24 Nov 2026 10:46:43 -0800 Subject: [PATCH 16/16] fix(clock): each clock operation reads real time once, so a reading across a follower's end never passes it Co-Authored-By: Claude Opus 5.5 --- src/agent_env/env/gateway/clock.py | 57 +++++++++++++----------- tst/unit/env/gateway/clock_range_test.py | 16 +++++++ 2 files changed, 48 insertions(+), 25 deletions(-) diff --git a/src/agent_env/env/gateway/clock.py b/src/agent_env/env/gateway/clock.py index ea3dc37a3..70ca7a84c 100644 --- a/src/agent_env/env/gateway/clock.py +++ b/src/agent_env/env/gateway/clock.py @@ -237,8 +237,9 @@ def set_time(self, virtual_time: str, rate=1.0, time_zone: str | None = None) -> raise ClockError(f"virtual_time {virtual_time!r} at rate {r:g} would overflow datetime near the max") self._check_followers(f"virtual_time {virtual_time!r}", t0, r) with self._lock: - self._stop_at_end() - self._bank(t0) + now = self._now() + self._stop_at_end(now) + self._bank(now, t0) self._t0 = t0 self._rate = r self._ahead = 0.0 @@ -260,8 +261,9 @@ def check_follower(self, name: str, held: FollowerRange) -> None: with self._lock: if not self._armed or self._t0 is None: return - self._stop_at_end() - now, rate = self._current(), self._rate + real = self._now() + self._stop_at_end(real) + now, rate = self._current(real), self._rate _check_range(f"the clock, at {_iso(now)},", name, held, now, rate) def set_rate(self, rate) -> dict: @@ -272,8 +274,8 @@ def set_rate(self, rate) -> dict: with self._lock: if not self._armed or self._t0 is None: raise ClockError("clock is not armed") - self._stop_at_end() now = self._now() + self._stop_at_end(now) ran = (now - self._anchor) * self._rate if _advance(self._t0, ran + self._ahead) > _MAX_T0 - timedelta(seconds=_OVERFLOW_HORIZON_S * r): raise ClockError(f"rate {r:g} would overflow datetime near the max") @@ -293,8 +295,9 @@ def advance(self, virtual_time: str) -> dict: if target > _MAX_T0 - timedelta(seconds=_OVERFLOW_HORIZON_S * self._rate): raise ClockError(f"virtual_time {virtual_time!r} at rate {self._rate:g} would overflow datetime near the max") self._check_followers(f"virtual_time {virtual_time!r}", target, None) - self._stop_at_end() - current = self._current() + now = self._now() + self._stop_at_end(now) + current = self._current(now) jump = (target - current).total_seconds() if jump < 0: raise ClockError(f"advance only moves forward: {virtual_time!r} is before the current {_iso(current)}") @@ -306,8 +309,9 @@ def advance(self, virtual_time: str) -> dict: def clear(self) -> dict: """Disarm (idempotent). Afterwards reads 404.""" with self._lock: - self._stop_at_end() - self._bank() + now = self._now() + self._stop_at_end(now) + self._bank(now) self._armed = False self._t0 = None self._time_zone = None @@ -320,15 +324,17 @@ def clear(self) -> dict: def elapsed(self) -> float: """Virtual seconds run so far: real time at each arm's rate (1 unarmed), plus each forward re-arm or advance.""" with self._lock: - self._stop_at_end() - return self._lived + (self._now() - self._anchor) * self._rate + now = self._now() + self._stop_at_end(now) + return self._lived + (now - self._anchor) * self._rate def now(self) -> datetime | None: with self._lock: if not self._armed or self._t0 is None: return None - self._stop_at_end() - return self._current() + now = self._now() + self._stop_at_end(now) + return self._current(now) @property def time_zone(self) -> str | None: @@ -341,7 +347,7 @@ def at_elapsed(self, elapsed: float) -> datetime | None: with self._lock: if not self._armed or self._t0 is None: return None - self._stop_at_end() + self._stop_at_end(self._now()) return _advance(self._t0, elapsed - self._lived + self._ahead) def read(self) -> dict: @@ -355,21 +361,23 @@ def state(self) -> dict: with self._lock: if not self._armed or self._t0 is None: return {"armed": False, "version": self.version} - self._stop_at_end() + now = self._now() + self._stop_at_end(now) return {"armed": True, "t0": _iso(self._t0), "virtual_seconds_per_real_second": self._rate, - "virtual_time": _iso(self._current()), + "virtual_time": _iso(self._current(now)), **({"time_zone": self._time_zone} if self._time_zone else {}), "version": self.version} - def _current(self) -> datetime: - """The current arm's time now. Lock held.""" - return _advance(self._t0, (self._now() - self._anchor) * self._rate + self._ahead) + def _current(self, now: float) -> datetime: + """The current arm's time at real time ``now``, the one time a locked operation reads, so its stop at a + follower's end and its reading agree. Lock held.""" + return _advance(self._t0, (now - self._anchor) * self._rate + self._ahead) def stop_at_end(self) -> None: """``_stop_at_end``, taking the lock: before a follower's range stops applying, as when it retires.""" with self._lock: - self._stop_at_end() + self._stop_at_end(self._now()) - def _stop_at_end(self) -> None: + def _stop_at_end(self, now: float) -> None: """Once the clock has run to the end of the narrowest range a follower holds, stop it there, frozen (rate 0) from the moment it got there, as the follower's page stands there: its reads, delays and marks agree with what the follower shows, and it stays there until a write moves it. Lock held.""" @@ -378,7 +386,6 @@ def _stop_at_end(self) -> None: end = min((held.latest for held in self._follower_ranges().values()), default=None) if end is None: return - now = self._now() to_end = max(0.0, (end - _advance(self._t0, self._ahead)).total_seconds()) if (now - self._anchor) * self._rate < to_end: return @@ -387,9 +394,9 @@ def _stop_at_end(self) -> None: self._anchor = now self._rate = 0.0 - def _bank(self, t0: datetime | None = None) -> None: - """Fold the stretch since the last arm/clear into `_lived` at its rate, and start the next one now.""" - now = self._now() + def _bank(self, now: float, t0: datetime | None = None) -> None: + """Fold the stretch since the last arm/clear, to real time ``now``, into `_lived` at its rate, and start the next + one then.""" ran = (now - self._anchor) * self._rate self._lived += ran if t0 is not None and self._armed: # a re-arm forward is time the world lived through; one back adds nothing diff --git a/tst/unit/env/gateway/clock_range_test.py b/tst/unit/env/gateway/clock_range_test.py index 39e952131..d18a323af 100644 --- a/tst/unit/env/gateway/clock_range_test.py +++ b/tst/unit/env/gateway/clock_range_test.py @@ -6,6 +6,7 @@ from __future__ import annotations import asyncio +from datetime import datetime import pytest from agentenv_protocol.computer.clock import RANGE @@ -186,3 +187,18 @@ def test_a_clock_stopped_at_a_followers_end_stops_its_delays_keeps_still_when_th assert clock.set_rate(1)["virtual_seconds_per_real_second"] == 1.0 now.tick(1) assert clock.read()["virtual_time"] == "2262-04-11T23:47:17Z" + + +def test_a_reading_that_crosses_a_followers_end_mid_operation_never_shows_a_time_past_it_or_steps_back(): + """Each locked operation reads real time once, so its stop at the end and the time it gives agree even when the + clock crosses the end between two of its reads of real time: here every read of real time is 0.3 s later.""" + ticks = iter(range(10**6)) + followers: ClockFollowers | None = None + clock = Clock(now_fn=lambda: 1000.0 + 0.3 * next(ticks), follower_ranges=lambda: followers.held()) + followers = ClockFollowers(lambda: clock, {"desktop": "token"}, {"desktop": HELD}) + clock.set_time("2262-04-11T23:47:14.300000Z", rate=0) + clock.set_rate(1) + readings = [datetime.fromisoformat(clock.state()["virtual_time"].replace("Z", "+00:00")) for _ in range(12)] + readings += [clock.now() for _ in range(4)] + [clock.at_elapsed(clock.elapsed())] + assert all(t <= HELD.latest for t in readings) and readings == sorted(readings), readings + assert readings[-1] == HELD.latest