﻿# clock — the controllable platform clock (a test feature)

**Test feature, not for production.** The clock is instance-wide: one setting applies to every tenant. While a move runs, the clock lands on the due times…

<em>cyoda-go version <a href="https://github.com/Cyoda/cyoda-go/releases/tag/v0.9.0">0.9.0</a></em>

# clock

## NAME

clock — set, move and speed up the platform's clock for tests and demonstrations.

## SYNOPSIS

```
GET  /api/platform/clock
POST /api/platform/clock      {"time": "2024-01-02T09:00:00Z"}
POST /api/platform/clock      {"advanceByMs": 86400000}
POST /api/platform/clock      {"rate": 1}
```

`POST` needs a platform operator and `CYODA_CLOCK_CONTROL_ENABLED=true` (see `cyoda help config clock`); without it the answer is `403 CLOCK_CONTROL_DISABLED`. `GET` answers any authenticated caller, and over gRPC there is `PlatformClockGetRequest`. A change takes `time` or `advanceByMs` (not both), and optionally `rate`. A successful `POST` answers `200` with `now`, `rate`, `controllable` and `nodes`, the ids of the nodes that hold the new setting (`["local"]` without clustering, `CYODA_CLUSTER_ENABLED=false`). A `time` later than now is a move (see below), not only a set in the past.

## DESCRIPTION

**Test feature, not for production.** The clock is instance-wide: one setting applies to every tenant. While a move runs, the clock lands on the due times of scheduled tasks in every tenant, so any caller reading the clock then sees those times (not which tenant they belong to).

**What it affects.** Business times: entity and revision dates, audit event times, consistency times, model update dates, search-job times, scheduled-transition due times, the point-in-time "now", and the `time` attribute of callout requests (the owner's platform time when it took the callout up, kept across retries; see `cyoda help cloudevents`), so a schedule function can compute an absolute fire time on the platform's clock. **What stays on real time:** token and key validity, timeouts and deadlines, leases, heartbeats and keep-alives.

**Starting in the past.** Set the start first, on a fresh store. A time earlier than the latest time the store has recorded is refused with `409 CLOCK_BEFORE_RECORDED_TIME`, naming the latest recorded time. Any earlier activity (a write, a point-in-time read, a search) raises the earliest allowed start. Model import does not, but it records its date, so set the start before importing models. The check records the time it is made at, so setting the same time again can be refused.

**Range.** `time` lies in the years 1970 to 9000, and `advanceByMs` may not move the clock past the end of 9000.

**Moving forward.** A move does not jump. It steps through the scheduled transitions that come due on the way, and each fires at its own due time, within about one scan interval (`CYODA_SCHEDULER_SCAN_INTERVAL`) times the rate. Due order holds for due times further apart than that; closer ones run together. The cost is one step per distinct due time, including retries and schedules that re-arm themselves. A move waits while a due task is pending (for example when no node runs a scheduler), so allow for that when you wait for the answer. A move that is interrupted leaves the clock where it got to. To continue, repeat it with the same `time`; `advanceByMs` counts from the clock's current time, so read `GET /platform/clock` first.

**Rate.** From 0.1 to 100; 1 is recommended. A rate other than 1 makes retries and time limits pass faster or slower in platform time, and multiplies any difference between node clocks. Retention follows platform time as well: after a move, async search jobs past their `expirationDate` at the new time are refused at once and deleted by the next reap, and later commits drop recorded submit times past their retention, and a rate above 1 shortens retention in real time. A `rate` sent with a later `time` or with `advanceByMs` takes effect when the move finishes.

**Restrictions.**
- Keep the system idle while the clock changes; nothing guards activity during a change. See `TESTING WITH THE PLATFORM CLOCK`.
- Cluster nodes need synchronised real clocks, and all use the same value of `CYODA_CLOCK_CONTROL_ENABLED`.
- A node that restarts while other nodes run takes their setting. Only a full restart (no node left running, or a single-node deployment) returns the clock to real time, and that startup fails if the store holds times more than 1 s later than real time: start over with a fresh store.
- Mock IAM lets any admin act as platform operator.

## TESTING WITH THE PLATFORM CLOCK

The clock is for tests on a cluster you control. A change is only correct under three preconditions, which nothing enforces:

- The cluster is static during a change: no node starts, stops or joins.
- The system is idle.
- One change at a time: send the next only after the previous call has returned.

Every change, and every step of a move, is pushed to every node of the cluster, and each node must echo exactly that setting. A `200` therefore means every node holds the setting, and the answer lists the nodes in `nodes`. If a node does not confirm within `CYODA_PROXY_TIMEOUT`, the answer is `503 CLOCK_NOT_CONFIRMED`, which names the nodes. Nothing is rolled back, so the cluster may hold different clocks; start over by restarting the cluster with a fresh store (see `cyoda help errors CLOCK_NOT_CONFIRMED`).

Advice for a test run:

- Set a start in the past first, before you write any data or import any model: see **Starting in the past**.
- Allow for retention after a move and at a rate above 1: see **Rate**.
- A move needs a running scheduler and the compute nodes that its scheduled tasks call; without them it waits.
- A node that starts or shuts down while a change runs can make the change fail, or the change can miss it: a node that joins after the change has read the list of nodes is not pushed the setting and is not in `nodes`. Check `nodes` against the nodes you run.
- Synchronise the real clocks of the cluster nodes and give every node the same `CYODA_CLOCK_CONTROL_ENABLED`: see **Restrictions**.

## SEE ALSO

- config.clock
- config.cluster
- errors.CLOCK_NOT_CONFIRMED
- scheduled-tasks
- workflows
- crud
- openapi

## See also

- [`cyoda help config clock`](/help/config/clock/) — The platform clock is the time cyoda records as business time: entity and audit dates, transition times and scheduled due times. By default it is the real clock and cannot be changed.
- [`cyoda help config cluster`](/help/config/cluster/) — - `CYODA_CLUSTER_ENABLED` (bool, default: `false`) — enable multi-node clustering.
- `CYODA_NODE_ID` (string, default: unset) — unique node identifier; required when `CYODA_CLUSTER_ENABLED=true`; any non-empty string is accepted. It must be distinct on every node: a hand-over between nodes is sealed for the node it is sent to, by this id, so two nodes sharing one id can open each other's (see the `cluster` help topic, `DISPATCH REPLAY PROTECTION`). A node that finds its id already held by a live node of the cluster keeps trying for the whole of `CYODA_STARTUP_TIMEOUT` and refuses to start if the id is still held when that budget runs out, naming this setting, the address the id was found at and the seed it was learned from; the node already holding it keeps serving. The retrying is what a crash needs: a node that did not leave gracefully and comes back at another address finds its peers still holding the record of its previous life, and nothing distinguishes that record from another node's — so the first attempts are refused, and the node starts on the attempt made after its peers have reaped the record, usually a few seconds later. The check runs only while a node is starting, and it runs there twice over: on the join exchange with a seed, and on the membership gossip that follows it, which is what two nodes starting at the same instant have instead of an exchange. It does **not** run afterwards. Once a node is serving, an id claimed from a second address is logged at ERROR, once per address, and nothing else happens: both nodes keep serving under the one id, and each can open the other's hand-overs. Two clusters that each started healthily under overlapping ids and only later meet — a network policy opened, a namespace split joined up, a partition healed — are exactly that case, and so is a node started with no seeds that is later given some. Watch for the ERROR line, fix the id and restart the node that has the wrong one. Together with `CYODA_NODE_ADDR` and `CYODA_GRPC_NODE_ADDR` it must fit the 512-byte gossip metadata (406 bytes for the three values together; 106 bytes are framing, the longest list version and the longest node state); a node whose identity does not fit refuses to start.
- `CYODA_NODE_ADDR` (string, default: `http://localhost:8080`) — this node's HTTP base URL; must include scheme (`http://` or `https://`). Peers proxy requests to it, so `CYODA_HTTP_BIND_ADDRESS` must be an address they can reach (`0.0.0.0` on a multi-host cluster; the default `127.0.0.1` serves only nodes on the same host).
- `CYODA_GRPC_NODE_ADDR` (string, default: unset) — this node's gRPC endpoint advertised to peers (`host:port`, no scheme). When set, peers dial this address for cross-node gRPC callback forwarding. When unset, peers derive the gRPC address from this node's HTTP host plus their own `CYODA_GRPC_PORT` (uniform-deployment default). Either way, `CYODA_GRPC_BIND_ADDRESS` must be an address peers can reach.
- `CYODA_GOSSIP_ADDR` (string, default: `:7946`) — gossip protocol listen address; format `[host]:port` — parsed via `net.SplitHostPort`; invalid format causes startup failure.
- `CYODA_GOSSIP_STABILITY_WINDOW` (duration, default: `2s`) — gossip stability window.
- `CYODA_SEED_NODES` (string, default: empty) — comma-separated list of seed node addresses (e.g., `node1.example.com:7946,node2.example.com:7946`); empty means single-node or seed-discovery handled externally.
- `CYODA_HMAC_SECRET` (string, default: unset) — hex-encoded HMAC secret for inter-node dispatch authentication; required when `CYODA_CLUSTER_ENABLED=true`. Supports `_FILE` suffix. Single root secret for gossip encryption, dispatch AEAD, and tx-token signing; no versioned-key rotation — changing it requires a full-cluster stop/start (see the `cluster` help topic, `SECRET ROTATION`).
- `CYODA_PROXY_TIMEOUT` (duration, default: `30s`) — the bound on the wait for a transaction's owner to begin answering a request forwarded to it (HTTP: its response headers; gRPC: a unary call's response, or a streamed call's first message), past which the request answers `503 TRANSACTION_NODE_UNAVAILABLE`, not retryable once the request was sent, because the owner may have run it; also the bound on one platform clock confirmation round (every peer contacted in parallel), and the bound on each status ask of `GET /platform/cluster`; half of it bounds the database check of the node that answers the ask (see the `cluster` help topic, `CLUSTER STATUS`). Must be `> 0`; startup fails otherwise.
- `CYODA_DISPATCH_WAIT_TIMEOUT` (duration, default: `5s`) — the patience: how long one callout waits, in total, for a compute member with matching tags to exist. It applies on a single node as in a cluster and whatever the callout's `retryPolicy` — waiting for a member to exist is not a retry and costs no try. The wait ends the moment a member attaches or a peer announces one. `0` disables waiting: a callout with no member fails at once with `NO_COMPUTE_MEMBER_FOR_TAG`. Must not be negative; startup fails otherwise.
- `CYODA_DISPATCH_CONNECT_TIMEOUT` (duration, default: `2s`) — time allowed to open the connection when a callout is handed over to another node. A node that cannot be connected to costs no try; the next one is asked. Behind a sidecar or an ingress the connection always opens and a dead peer shows as a 502–504, which counts as one try. Must be `> 0`; startup fails otherwise.
- `CYODA_CALLOUT_HANDOVER_ALLOWANCE` (duration, default: `30s`) — what the owning node allows a hand-over on top of `tries left × answer limit`, and the last term of a callout's overall deadline (`tries × answer limit + CYODA_DISPATCH_WAIT_TIMEOUT + this`; 155 s at the defaults). Must be `> 0`; startup fails otherwise.
- `CYODA_CALLOUT_PASS_ALLOWANCE` (duration, default: `30s`) — how long the transaction token given to a compute member outlives its try's answer limit: the margin for routing a callback between nodes and for clocks that differ between them. Must be `> 0`; startup fails otherwise.
- [`cyoda help errors CLOCK_NOT_CONFIRMED`](/help/errors/clock_not_confirmed/) — `POST /api/platform/clock` pushes every new clock setting to all other nodes of the cluster and answers only when each of them has echoed exactly that setting back. A node is reported when, within `CYODA_PROXY_TIMEOUT`:
- [`cyoda help scheduled-tasks`](/help/scheduled-tasks/) — A scheduled workflow transition arms a task each time the entity enters the transition's source state. `GET /scheduled-tasks` lists the caller's tenant's scheduled-transition tasks that still exist: `WAITING`, `RUNNING` or `FAILED`. A task that fired, was declined, expired or was cancelled is removed; its outcome is in the entity's audit trail (see the `audit` topic), not here.
- [`cyoda help workflows`](/help/workflows/) — A workflow definition is a named finite state machine attached to an entity model. Workflows are stored per model reference `(entityName, modelVersion)`. A model may have multiple workflow definitions; the engine selects the matching one per entity using the workflow-level `criterion` field, on every operation that runs the entity's workflow (see *Workflow-level selection*). When no `criterion` matches, the engine uses the default built-in workflow.
- [`cyoda help crud`](/help/crud/) — Entities are instances of models. Each entity has a UUID, a model reference (`entityName`, `modelVersion`), and a lifecycle state managed by the workflow engine. Creating an entity requires the referenced model to be in `LOCKED` state. All write operations run within a Cyoda transaction and return a `transactionId` alongside the affected entity IDs.
- [`cyoda help openapi`](/help/openapi/) — cyoda-go generates its OpenAPI 3.1 specification from the embedded `api/openapi.yaml` file compiled into the binary at build time. The spec is served at `/openapi.json` with runtime-patched server URLs. The Scalar API Reference UI is served at `/docs` and loads the spec from `/openapi.json`.

## Raw formats

- [`/help/clock.json`](/help/clock.json) — full descriptor (matches `GET /help/{topic}` envelope)
- [`/help/clock.md`](/help/clock.md) — body only