diff --git a/AGENTS.md b/AGENTS.md index 9da4ced94..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`) 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/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/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/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 d87233c9f..c10ab8b74 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/computer/clock.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/computer/clock.py @@ -27,6 +27,13 @@ #: 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 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. DISK_GUEST = "/etc/agentenv/vm/image.env" @@ -53,7 +60,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..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): @@ -198,6 +199,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/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/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..f6d5a8011 100644 --- a/src/agent_env/a2a_agent/clock.py +++ b/src/agent_env/a2a_agent/clock.py @@ -19,9 +19,12 @@ 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 +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 @@ -51,6 +54,20 @@ def follower_name(agent: DeployedAgent) -> str: return f"agent-{agent.agent_name}" +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, 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") + 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]]: return A2AAgent.operation(A2AAgent.find_extension(agent.a2a_card or {}, EXT_CLOCK_URI), "sync_time") @@ -72,7 +89,9 @@ 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, 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) @@ -85,10 +104,17 @@ 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.as_dict()} if held else {})}, + timeout=timeout) except EnvCapabilityUnsupported: return {"synced": False, "reason": "gateway_takes_no_followers"} + except ExtensionCallError as e: + 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, "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..7c1b6ce81 100644 --- a/src/agent_env/env/envs/computer/utils/clock.py +++ b/src/agent_env/env/envs/computer/utils/clock.py @@ -18,10 +18,12 @@ 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 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: @@ -39,6 +41,21 @@ def follows(record: DeployedEnv) -> bool: return record.supports(EXT_CLOCK_URI, "sync_time") +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, 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") + 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]: """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..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,12 +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.""" + 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: FollowerRange | None = None __all__ = [ diff --git a/src/agent_env/env/gateway/clock.py b/src/agent_env/env/gateway/clock.py index 5f575c86e..70ca7a84c 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 @@ -18,12 +20,52 @@ 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 # 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) +# 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 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"), "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_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: @@ -54,23 +96,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: @@ -129,8 +171,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 @@ -191,8 +235,11 @@ def set_time(self, virtual_time: str, rate=1.0, time_zone: str | None = 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) + now = self._now() + self._stop_at_end(now) + self._bank(now, t0) self._t0 = t0 self._rate = r self._ahead = 0.0 @@ -202,6 +249,23 @@ 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()): + _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 + 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: """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 @@ -211,6 +275,7 @@ def set_rate(self, rate) -> dict: if not self._armed or self._t0 is None: raise ClockError("clock is not armed") 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") @@ -229,7 +294,10 @@ def advance(self, virtual_time: str) -> dict: 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") - current = _advance(self._t0, (self._now() - self._anchor) * self._rate + self._ahead) + self._check_followers(f"virtual_time {virtual_time!r}", target, None) + 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)}") @@ -241,7 +309,9 @@ def advance(self, virtual_time: str) -> dict: def clear(self) -> dict: """Disarm (idempotent). Afterwards reads 404.""" with self._lock: - self._bank() + now = self._now() + self._stop_at_end(now) + self._bank(now) self._armed = False self._t0 = None self._time_zone = None @@ -254,14 +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: - 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 - elapsed = self._now() - self._anchor - return _advance(self._t0, elapsed * self._rate + self._ahead) + now = self._now() + self._stop_at_end(now) + return self._current(now) @property def time_zone(self) -> str | None: @@ -274,6 +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._now()) return _advance(self._t0, elapsed - self._lived + self._ahead) def read(self) -> dict: @@ -287,14 +361,42 @@ 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 + 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(_advance(self._t0, elapsed * self._rate + self._ahead)), + "virtual_time": _iso(self._current(now)), **({"time_zone": self._time_zone} if self._time_zone else {}), "version": self.version} - 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 _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._now()) + + 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.""" + 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) + if end is None: + return + 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, 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/src/agent_env/env/gateway/clock_followers.py b/src/agent_env/env/gateway/clock_followers.py index 190c58b3c..2a4b69615 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 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, 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: + self._clock().check_follower(name, held) 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) @@ -64,13 +75,18 @@ 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): + 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 +150,6 @@ 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": 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 35e4d6957..56e1d72db 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 @@ -88,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 @@ -268,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 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"]}}, @@ -276,7 +282,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..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, _iso +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 @@ -182,6 +183,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 +191,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 +275,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 +436,10 @@ 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 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 922f4d230..e49e0cde3 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("{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 {})} def control_token_children_environment(children: Iterable[ExternalChild], control_token: str | None) -> dict[str, str]: 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..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,45 @@ static void ft_page_open(void) ft_page = map; } +/* 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) +{ + __int128 fake; + if (s->rate == 0 || t <= s->anchor_ns) return s->universe_ns; + 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 + 1970 isn't written "-1.-5". */ +static void ft_spec_time(char *out, size_t size, int64_t 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]; + char spec[160], universe[32], anchor[32]; 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)); + { + 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); __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..83526c683 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) { @@ -166,6 +168,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: 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); +} static inline bool ft_rt_clock(clockid_t c) { return c == CLOCK_REALTIME || c == CLOCK_REALTIME_ALARM; @@ -179,20 +187,17 @@ 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. */ + 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; - r = (double) (due - s->universe_ns) / s->rate; + 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; } @@ -223,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 @@ -279,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. */ @@ -301,13 +307,13 @@ 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) { 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 && 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); @@ -339,8 +345,11 @@ 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; + if (left < 1) left = 1; + out->it_value.tv_sec = (time_t) (left / FT_NS); + out->it_value.tv_nsec = (long) (left % FT_NS); } } @@ -416,16 +425,39 @@ 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. + 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; + 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) @@ -439,12 +471,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); } @@ -577,7 +620,7 @@ static long ft_u_futex_rt(uint32_t *uaddr, int op, uint32_t val, const struct ti struct ft_clock_page s; int64_t due = ft_ns(abs); *handled = false; - if (!ft_snap(&s)) return 0; + if (!ft_snap(&s) || !ft_valid_due(abs, &s)) return 0; *handled = true; for (;;) { @@ -786,7 +829,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; @@ -824,8 +867,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; @@ -1129,8 +1172,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/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/src/agent_env/utils/faketime_clock/libfaketime.patch b/src/agent_env/utils/faketime_clock/libfaketime.patch index 17555d2b8..ae588a173 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_ns(req)); ++ if (ft_snap(&s) && ft_valid_due(req, &s)) return ft_rt_sleep(&s, ft_ns(req)); + } if (real_clock_nanosleep == NULL) { @@ -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 1bd599966..6182b94ad 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 @@ -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 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 + + 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"): @@ -308,6 +315,34 @@ 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 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) + 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 {**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 @@ -326,7 +361,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 +370,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 +401,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 +426,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 +452,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") @@ -452,6 +489,63 @@ def deadwriter(): "read": _classify(after, before, 21 * DAY)} +def end(): + """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 = _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 {"read": read, "from": -9223372036 + (before - anchor) * DAY, "to": -9223372036 + (after - anchor) * DAY} + + def _classify(value: float, before: float, universe_offset: float) -> object: if abs(value - before) < 30: return "real" @@ -525,7 +619,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: @@ -674,8 +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, condstress, semstress, stall, torn, - deadwriter, 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/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/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/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..f7062462e --- /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 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; +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/tfdend.py b/tst/clock/programs/tfdend.py new file mode 100644 index 000000000..e8134bbd3 --- /dev/null +++ b/tst/clock/programs/tfdend.py @@ -0,0 +1,32 @@ +"""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 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 +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 +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()})) diff --git a/tst/clock/programs/tfdfrozen.py b/tst/clock/programs/tfdfrozen.py new file mode 100644 index 000000000..f0834ef69 --- /dev/null +++ b/tst/clock/programs/tfdfrozen.py @@ -0,0 +1,48 @@ +"""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, 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 +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) + + +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/programs/torn.c b/tst/clock/programs/torn.c index 0f80aff0a..2b3e194f6 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 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; } -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..9a0324d69 --- /dev/null +++ b/tst/clock/range_test.py @@ -0,0 +1,132 @@ +"""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 + +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 = { + "1677": datetime(1677, 9, 22, tzinfo=timezone.utc), + "1950": datetime(1950, 1, 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.""" + def run(name: str, *args, timeout: float = 600): + return gate(name, *args, timeout=timeout, docker_args=_base(BASES[request.param])) + + return run + + +@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_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"} + 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_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_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 = [] + 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_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) + assert (r["a2_count"], r["o_fired_early"]) == (1, 0), (how, r) + assert at_jump(r), (how, r) + + +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_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_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 + + +@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 + + +def test_a_clock_that_outlives_its_range_stops_at_the_end_rather_than_wrapping(gate): + 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_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 + + +def test_a_periodic_timer_ticking_into_the_end_stops_there_with_no_page_written(gate): + assert gate("end_periodic") == {"expirations": 4, "now": 9223372036000000000} 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"), diff --git a/tst/unit/env/envs/test_computer_clock_follower.py b/tst/unit/env/envs/test_computer_clock_follower.py index 9f57d3f2d..b07827cd4 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 agentenv_protocol.computer.clock import RANGE from agentenv_protocol.computer import clock as protocol_clock CLOCK = Path(agent_env.__file__).parent / "utils" / "faketime_clock" @@ -146,6 +147,39 @@ 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 _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) == (_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 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 = _range_ns("latest") + + 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] == _range_ns("earliest") + + 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/envs/test_multi_env_computers.py b/tst/unit/env/envs/test_multi_env_computers.py index 817dd1c63..88f0d2573 100644 --- a/tst/unit/env/envs/test_multi_env_computers.py +++ b/tst/unit/env/envs/test_multi_env_computers.py @@ -331,6 +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"} + 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 new file mode 100644 index 000000000..d18a323af --- /dev/null +++ b/tst/unit/env/gateway/clock_range_test.py @@ -0,0 +1,204 @@ +"""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, 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 +from datetime import datetime + +import pytest +from agentenv_protocol.computer.clock import 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 + +HELD = parse_follower_range(RANGE) +DESKTOP = "clock follower 'desktop' holds, 1677-09-21T00:12:44Z to 2262-04-11T23:47:16Z" + + +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_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", ["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 + + +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", + "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"] + + +@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.read()["virtual_time"] >= virtual_time + + +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" + + +@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") + 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) + 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) + + +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 + + +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" + + +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 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 89d08c54a..74c85de90 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,25 @@ 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 + from agent_env.env.gateway.clock import parse_follower_range + + 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()), + 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..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 @@ -68,6 +69,93 @@ 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(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) -> 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 + + 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, {"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", + 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_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})