# Docs

Lookup for `jetlag`: the command line, the HTTP API, Targets, privileges and Kubernetes. A first shifted process is on https://jetlag.slopkit.dev/start/. Product source is https://gitlab.techtailors.net/slopkit/jetlag.

Jetlag shifts the time that running processes see, without restarting them. It wraps [epochd](https://github.com/bkaznowski/epochd), which patches the vDSO of a running process, so static Go and Rust binaries and Postgres are covered. It is used to test date-dependent behavior such as trials, expiry and scheduled jobs on a deployed environment.

Linux x86-64 only, which is epochd's limit. Jetlag is for Controlled Environments: it can change the time of any process it can reach.

`jetlag help` prints the usage. `jetlag <command> -h` prints the flags of one command. `jetlag version` prints the version.

## Install

There is no published release yet. Build from source in the dev shell of the product repo:

```
devenv shell
go build -o bin/jetlag ./cmd/jetlag
```

Jetlag builds against epochd v0.8.1 plus three patches kept in `patches/epochd/`: Monotonic Shift, a Reset that uninstalls, and following child processes. `scripts/epochd.sh` applies them into `third_party/epochd`, which `go.mod` uses in place of epochd. The dev shell runs that script on entry. The first run needs network.

## Terms

A Clock Shift applies to a Target and lasts until it is reset. These are the words the commands and the API use.

Clock Shift
: A change to the time a set of processes sees: a forward jump by an Offset, a Freeze, or both. It applies to every process in its Target at once and lasts until it is Reset.

Target
: The set of processes a Clock Shift applies to. A Target includes processes that start inside it while the shift is active. Forms are listed under Targets.

Offset
: How far a Target's wall clock is ahead of real time.

Freeze
: Stopping a Target's wall clock at one instant until it is advanced, unfrozen or Reset.

Wall Clock
: The calendar time a process reads, which day and hour it is. A Clock Shift always moves it.

Monotonic Shift
: An opt-in extension of a Clock Shift that also moves the monotonic clocks. Off by default.

Injection
: Preparing one process so that its clock can be shifted. It happens once per process. Later changes to the shift do not stop the process.

Follow
: Shifting a command and every process it starts, from that process's first instruction. `jetlag run` follows by default.

Reset
: Returning a Target to real time and undoing every Injection, including any Monotonic Shift, so the processes behave as if Jetlag had never touched them.

Node Agent
: Jetlag running on a Kubernetes node with access to all the node's processes. It shifts the processes of matching pods on its own node.

## Targets

A Target is one of:

| Form | Selects |
|---|---|
| `pid:<pid>` | One process. Its children are not followed. |
| `tree:<pid>` | The process and everything descended from it now. |
| `cgroup:<path>` | The cgroup and its descendants. The path is absolute under `/sys/fs/cgroup`, or relative to it, such as `/app.slice`. |
| `k8s:<namespace>/<label-selector>` | The processes in the containers of matching pods. See Kubernetes. |
| `child` | Only under `jetlag run --listen`. The command `jetlag run` started and what it started, which is `tree:<pid>` of the command. |

Kernel threads, zombies and Jetlag itself are skipped. They are listed under `skipped` in a result and never touched.

## Offsets and times

An Offset is a duration such as `30d`, `-2h`, `1d12h` or `90m`. A negative Offset moves the clock back. Jetlag accepts everything Go's duration syntax accepts, plus `d` (24 hours) and `w` (7 days). A day is always 24 hours, so there are no calendar days and no time zones.

A time (`--at`) is RFC 3339, such as `2030-01-01T00:00:00Z`.

## Commands

Every command that takes `--target` also takes these flags:

| Flag | Meaning |
|---|---|
| `--target T` | Target. Required. |
| `--server URL` | Run the operation against a Jetlag server. Without it the operation runs in this process. Env `JETLAG_URL`. |
| `--token-file FILE` | File holding the server's bearer token. Env `JETLAG_TOKEN_FILE`, or `JETLAG_TOKEN`. There is no `--token` flag, because arguments are visible in `ps`. |
| `--json` | Print the JSON response. |

Flags and the one positional argument can come in any order.

Exit codes: `0` ok, `1` the operation failed for some or all processes (details on stderr), `2` wrong usage. `jetlag run` exits with the command's own code, or `128+n` if a signal killed it.

### jetlag resolve

Dry run. Lists the processes a Target selects and changes nothing. It never needs a privilege.

```
jetlag resolve --target cgroup:/app.slice
```

### jetlag shift

Set the Offset. Injects each process first if needed.

```
jetlag shift --target pid:4242 --offset 30d
jetlag shift --target pid:4242 --at 2030-01-01T00:00:00Z --freeze
jetlag shift --target tree:4242 --offset 30d --monotonic
```

| Flag | Meaning |
|---|---|
| `--offset D` | How far ahead of real time. |
| `--at TIME` | The time the clock should show now. Use this instead of `--offset`. |
| `--freeze` | Stop the clock at the shifted instant. |
| `--monotonic` | Also shift the monotonic clocks. See Monotonic Shift. |

Give exactly one of `--offset` and `--at`.

### jetlag freeze

Stop the Wall Clock.

```
jetlag freeze --target pid:4242
jetlag freeze --target pid:4242 --at 2030-01-01T00:00:00Z
```

Without `--at` the clock stops at what the Target's lowest pid shows now.

### jetlag unfreeze

A frozen clock runs again from the instant it stopped at. Processes that are not frozen are left alone.

```
jetlag unfreeze --target pid:4242
```

### jetlag advance

Move each clock by an amount. A negative amount moves it back. The mode is kept, so a frozen clock stays frozen.

```
jetlag advance --target pid:4242 1h
```

### jetlag status

Show each process's mode, Offset and Wall Clock.

```
jetlag status --target pid:458848
```

Example output:

```
pid:458848: 1 process
  PID     COMM   MODE       OFFSET  WALL CLOCK
  458848  sleep  advancing  +30d    2026-12-31T10:02:19Z
```

`MODE` is `real`, `advancing` or `frozen`. With a Monotonic Shift it shows `advancing+mono`.

### jetlag reset

Back to real time. Removes every Injection. Works on a process that was never injected.

```
jetlag reset --target pid:4242
```

### jetlag run

Start a program already shifted. The program's clock is set before it runs any of its own code, and it runs as Jetlag's child. This is the way that needs no privilege.

```
jetlag run --offset 30d -- ./my-server --port 8080
jetlag run --offset 30d --listen 127.0.0.1:7420 -- ./my-server
```

| Flag | Meaning |
|---|---|
| `--offset D` | Start the command this far ahead of real time. |
| `--at TIME` | Start the command with this time on its clock. Use this instead of `--offset`. |
| `--freeze` | Start the clock frozen. Needs `--offset` or `--at`. |
| `--monotonic` | Also shift the monotonic clocks. Needs `--offset` or `--at`, unless `--listen` is set. |
| `--no-follow` | Shift only the command itself, not the processes it starts. |
| `--listen ADDR` | Also serve the API for this command. Takes `--token-file`, `--allow-unauthenticated`, `--reconcile-interval` and the Kubernetes flags as `jetlag serve` does. |

Flags end at the first argument that is not one, so write the command after `--`.

`jetlag run` follows by default. A fork copies the shift. A program that execs, such as a shell script, `cargo run` or `make`, is shifted again from its first instruction. So `jetlag run --offset 30d -- cargo run` shifts the program cargo starts.

With `--listen`, the API serves the command as the Target `child`, or with no Target at all, so callers do not need its pid. `reset` on `child` ends the following and takes the Injection out of every process. A later shift covers the processes that exist then.

```
curl -s -X POST http://127.0.0.1:7420/v1/shift -H 'Content-Type: application/json' -d '{"target":"child","offset":"30d"}'
jetlag status --server http://127.0.0.1:7420 --target child
```

If the API stops on its own, `jetlag run` kills the command rather than leave it running with nobody able to reset its clock. Signals TERM, HUP, QUIT, USR1 and USR2 are passed on to the command.

### jetlag serve

Serve the API. See HTTP API.

```
jetlag serve --listen 127.0.0.1:7420
```

| Flag | Default | Meaning |
|---|---|---|
| `--listen ADDR` | `127.0.0.1:7420` | Address for the API. Port `0` picks a free port. |
| `--token-file FILE` | env `JETLAG_TOKEN_FILE` | File holding the bearer token clients must present. Env `JETLAG_TOKEN` also works. |
| `--allow-unauthenticated` | off | Allow a non-loopback `--listen` without a token. |
| `--reconcile-interval D` | `500ms` | How often to look for processes that joined a cgroup Target. Must be positive. |

The Kubernetes flags are under Kubernetes.

## Privileges

Injection uses `ptrace`. Jetlag never uses `sudo` and never changes `ptrace_scope`.

| Situation | Needs |
|---|---|
| Jetlag started it (`jetlag run -- CMD`) | Nothing. Works with `ptrace_scope=1`, the usual default. |
| Any other process of the same user, such as a service started by systemd or process-compose | `CAP_SYS_PTRACE` on the `jetlag` binary, or run as root. |
| Any process, any user | root, or the capability, and the process must not be setuid or non-dumpable. |

To give the binary the capability once:

```
sudo setcap cap_sys_ptrace+ep /path/to/jetlag
```

The path cannot be in the Nix store. `kernel.yama.ptrace_scope=0` also works but weakens every process on the machine, so it is not recommended. With `ptrace_scope=3` nothing works. `resolve` never needs a privilege.

When an operation is refused, Jetlag reports `permission_denied` for that process and prints a hint.

## HTTP API

`jetlag serve` serves the same operations as the CLI as JSON over HTTP. The CLI is a client of it too, through `--server` or `JETLAG_URL`. The server needs the same privilege as the CLI.

There is no state to keep. Each process holds its own shift, so any `jetlag` can `status`, `advance` or `reset` what another one shifted.

### Access

- **Loopback, no token (default).** The server answers only when the `Host` header is a loopback name: `127.0.0.1`, `[::1]` or `localhost`. This stops a web page from reaching it through DNS rebinding.
- **Token.** With `--token-file`, `JETLAG_TOKEN_FILE` or `JETLAG_TOKEN`, every request except `GET /healthz` needs `Authorization: Bearer <token>`.
- **Non-loopback `--listen`** is refused unless a token is set or `--allow-unauthenticated` is given.
- `POST` bodies must be `application/json`, at most 64 KiB, with no unknown fields.
- The API is plain HTTP. Put TLS in a proxy if you want it.

Any local user can call a server that has no token. On shared machines, use a token.

### Endpoints

| Method and path | Body or query | Does |
|---|---|---|
| `GET /healthz` | | `{"status":"ok","version":"..."}`. No auth. |
| `GET /v1/resolve` | `?target=T` | Dry run: lists the processes the Target selects. |
| `GET /v1/status` | `?target=T` | Reads each process's Wall Clock. |
| `POST /v1/shift` | `{"target":"T","offset":"30d"}` or `{"target":"T","at":"2030-01-01T00:00:00Z"}`, optional `"freeze":true`, `"monotonic":true` | Sets the Offset. Exactly one of `offset` and `at`. |
| `POST /v1/freeze` | `{"target":"T"}`, optional `"at":"<time>"` | Stops the clock. |
| `POST /v1/unfreeze` | `{"target":"T"}` | A frozen clock runs again. |
| `POST /v1/advance` | `{"target":"T","by":"1h"}` | Moves each clock by `by`. |
| `POST /v1/reset` | `{"target":"T"}` | Back to real time. |

Example:

```
curl -s -X POST http://127.0.0.1:7420/v1/advance \
  -H 'Content-Type: application/json' \
  -d '{"target":"cgroup:/app.slice","by":"1h"}'
```

### Result

`status`, `shift`, `freeze`, `unfreeze`, `advance` and `reset` return a Result:

```
{
  "target": "pid:458848",
  "ok": true,
  "now": "2026-12-01T11:02:19.292604512+01:00",
  "processes": [
    {
      "pid": 458848,
      "comm": "sleep",
      "cmdline": "sleep 20",
      "mode": "advancing",
      "time": "2026-12-31T11:02:19.29260357Z",
      "offset": "+30d1h",
      "offset_seconds": 2595600,
      "injected": true,
      "generation": 1
    }
  ],
  "skipped": [{"pid": 7, "comm": "kworker", "reason": "kernel thread"}],
  "warnings": ["one-shot: processes that start in this Target later are not shifted; run jetlag serve to cover them"]
}
```

| Field | Meaning |
|---|---|
| `ok` | `true` when no process reported an error. |
| `now` | Real time the operation ran at. |
| `mode` | `real`, `advancing` or `frozen`. |
| `time` | The Wall Clock the process sees now. |
| `offset`, `offset_seconds` | `time` minus real time. For a frozen clock this shrinks as real time passes. |
| `monotonic` | `true` when the process has a Monotonic Shift. |
| `injected` | Whether epochd's hooks are in the process. `false` after `reset`. |
| `generation` | How many times epochd wrote the clock. |
| `error` | Present instead of the clock fields when the operation failed for that process: `{"code","message"}`. |
| `skipped` | Processes the Target matched that Jetlag never touches. |
| `warnings` | Notes, such as a cgroup shift from a one-shot CLI call that does not cover later processes. |

Error codes per process: `permission_denied`, `process_gone`, `injection_lost` (the process exec'd) and `failed`.

One stuck process never hides the others, so a failure on some processes is a Result and not an HTTP error. The status code summarizes it:

| Status | When |
|---|---|
| `200` | Every process succeeded, or the Target selects nothing. |
| `207` | Some processes failed and some succeeded. |
| `403` | Every process failed with `permission_denied`. |
| `500` | Every process failed, for other reasons. |

`GET /v1/resolve` returns `{"target","processes":[{"pid","comm","cmdline"}],"skipped":[...]}` with `200`. An empty cgroup is not an error.

### Request errors

A body with an `error` object means the request itself was wrong:

```
{"error": {"code": "invalid_request", "message": "exactly one of offset and at is required"}}
```

| Status | `code` | When |
|---|---|---|
| `400` | `invalid_request` | Bad Target, offset or time, bad JSON, both or neither of `offset` and `at`, or an attempt to shift Jetlag itself. |
| `401` | `unauthorized` | Missing or wrong bearer token. |
| `403` | `forbidden` | No token configured and the `Host` header is not loopback. |
| `404` | `not_found` | The process or cgroup does not exist, or the endpoint does not. |
| `415` | `invalid_request` | A `POST` without `Content-Type: application/json`. |
| `501` | `unsupported` | Reserved for options a backend cannot do. None today. |
| `500` | `internal` | Anything unexpected. |

## Cgroup Targets and new processes

A process that starts in a cgroup Target after a shift gets the shift too, but only while a server is running. `jetlag serve` runs a reconciler, every `--reconcile-interval`, that injects new members of every cgroup Target that is shifted. The record of those Targets lives in the server's memory. Restarting the server forgets them, although the processes stay shifted.

A one-shot CLI call (`jetlag shift --target cgroup:...` with no `--server`) shifts only the processes there now and prints a warning.

A process that execs loses its Injection and reads real time until the next reconcile pass, or for good if no server watches its cgroup.

A `pid:` Target is only that process. Use `tree:`, a cgroup Target, or start the program with `jetlag run` to cover the processes it starts.

## Monotonic Shift

A Clock Shift moves the Wall Clock. Many programs time things with a monotonic clock instead, such as `CLOCK_MONOTONIC`, Go's `time.Since`, Rust's `Instant` or Node's `performance.now`. A trial that is "30 days" by `Instant` does not end when the Wall Clock moves 30 days. A Monotonic Shift moves those clocks by the same Offset.

```
jetlag shift --target tree:4242 --offset 30d --monotonic
jetlag run --offset 30d --monotonic -- ./my-server
```

`advance`, `freeze` and `unfreeze` keep the option. A later `shift` without `--monotonic` ends it. `reset` ends it with everything else.

What moves: `CLOCK_MONOTONIC`, `CLOCK_MONOTONIC_RAW`, `CLOCK_MONOTONIC_COARSE` and `CLOCK_BOOTTIME`, read through the vDSO, which is what the Go, Rust and C runtimes do. `CLOCK_TAI` and the process and thread CPU clocks do not move. A Freeze stops the Wall Clock only. The monotonic clocks keep running at the real rate, because freezing them would hang every timeout in the program.

It is off by default for these reasons:

- A timer set before a forward shift fires at once. A timer set while shifted waits for the whole shift if the shift is taken away. A Go process that had a Monotonic Shift and is then reset can sleep for 30 days. Restart such a process after a Reset.
- Code comparing `CLOCK_MONOTONIC` with `CLOCK_REALTIME` sees a stable difference only while both are shifted by the same amount.
- Runtimes that cache a start instant, such as `uptime` or `process.hrtime`, report the shift as elapsed time.

Use it when the behavior under test is measured with a monotonic clock, in programs you can restart. Leave it off for databases and anything with long-lived timers.

## Kubernetes

A `k8s:<namespace>/<label-selector>` Target selects the pods of a namespace that match a label selector, and so every process in their containers. The selector is whatever `kubectl -l` takes and may contain slashes. The namespace ends at the first one.

```
jetlag shift --server $JETLAG_URL --target k8s:shop/app=api --offset 30d
jetlag status --server $JETLAG_URL --target 'k8s:shop/app.kubernetes.io/name=api,tier in (web,worker)'
```

A process that starts later in a matching pod, such as a restarted container or a new replica, is shifted too while a server runs. The reconciler resolves the Target again every `--reconcile-interval`.

Following, as in `jetlag run`, does not exist for Kubernetes Targets.

### Node agents and the gateway

A pod runs on one node, and Jetlag can only change processes it can see and ptrace. So each node runs a node agent, and a gateway sits in front of them.

```
Hunt / jetlag CLI -> gateway (Deployment) -> agent on node 1 -> ptrace its pods' processes
                                          -> agent on node 2 -> ...
```

- The **node agent** is `jetlag serve --node $NODE_NAME` as a DaemonSet with `hostPID: true` and `CAP_SYS_PTRACE` and no other privilege. For a `k8s:` Target it asks the Kubernetes API for the matching pods on its own node, takes each container's ID from the pod status, and finds the processes whose `/proc/<pid>/cgroup` contains that ID. It needs no runtime socket. The pause container is never touched.
- The **gateway** is `jetlag serve --gateway`. It finds the agents, sends the same request to all of them and merges the answers. Each process in a result carries its `pod` and `node`, because pids repeat across nodes. An agent it cannot reach is a warning and makes the result not OK. It serves `k8s:` Targets only.
- Both read pods through the API server with their service account. Nothing is written to the cluster.

Flags on `serve` and `run`:

| Flag | Env | Meaning |
|---|---|---|
| `--node NAME` | `NODE_NAME` | This node's name. `k8s:` Targets resolve pods scheduled here. |
| `--kube-api URL` | `JETLAG_KUBE_API` | Kubernetes API URL. Default is the in-cluster service account when in a pod. `http://127.0.0.1:8001` works with `kubectl proxy`. |
| `--kube-token-file FILE` | | Bearer token file for `--kube-api`. |
| `--gateway` | `JETLAG_GATEWAY=1` | Serve `k8s:` Targets for the whole cluster by sending each request to every node agent. |
| `--agents-namespace NS` | `POD_NAMESPACE` | Gateway: namespace of the agent pods. |
| `--agents-selector SEL` | | Gateway: label selector of the agent pods. Default `app.kubernetes.io/name=jetlag-agent`. |

The agents and the gateway refuse to listen beyond loopback without a token. The same token covers client to gateway and gateway to agent. The API is plain HTTP inside the cluster, so use a NetworkPolicy or a mesh if pod traffic is not trusted.

### Deploy

The repo has manifests under `deploy/kubernetes`:

```
kubectl apply -f deploy/kubernetes/namespace.yaml
kubectl -n jetlag-system create secret generic jetlag-token --from-literal=token="$(openssl rand -hex 32)"
kubectl apply -k deploy/kubernetes
```

Build the image from the repo root with `docker build -f deploy/Dockerfile`. It needs network, because it downloads epochd and applies the patches.

| File | What |
|---|---|
| `namespace.yaml` | The namespace `jetlag-system`. |
| `rbac/rbac.yaml` | Service accounts. The agent may `get` and `list` pods cluster-wide. The gateway may do so only in its own namespace. |
| `agent/daemonset.yaml` | The node agent: `hostPID`, `CAP_SYS_PTRACE` only, not privileged, runtime-default seccomp, read-only root. |
| `agent/networkpolicy.yaml` | Optional: only the gateway reaches the agents. |
| `gateway/gateway.yaml` | A Deployment with no privilege, and the Service `jetlag.jetlag-system:7420`. |

Reach it:

```
kubectl -n jetlag-system port-forward svc/jetlag 7420 &
export JETLAG_URL=http://127.0.0.1:7420 JETLAG_TOKEN=$(kubectl -n jetlag-system get secret jetlag-token -o jsonpath='{.data.token}' | base64 -d)
jetlag resolve --target k8s:shop/app=api
```

`resolve` lists the pod, node and pid of each process.

### Kubernetes limits

- **Close to root on the node.** `hostPID` with `CAP_SYS_PTRACE` can change any process on the node. Deploy it to Controlled Environments only. Some clusters need an AppArmor or SELinux exception for ptrace, and `kernel.yama.ptrace_scope=3` makes it impossible.
- x86-64 nodes only. On arm64 nodes the DaemonSet pods start and every injection fails.
- Processes of a container that is not in the pod's `containerStatuses` yet are found on the next reconcile pass.
- The product docs state that Kubernetes Targets and the node agent have not been run on a real cluster.

### SlopKit Push

SlopKit Push can deploy the gateway from `deploy/push/deploy.nix` as a `dockerfile` app. It cannot express the DaemonSet, `hostPID` or the RBAC, so the node agents are applied separately with `kubectl apply -k deploy/push/agent`. The steps are in `docs/push.md` in the product repo.

## In a stack

`scripts/serve-for-stack.sh` builds Jetlag and serves the API for a dev stack. It sets `JETLAG_URL` for the stack shell, and Hunt then calls the API. Processes the stack did not start through `jetlag run` need the `setcap` command from Privileges.

## Limits

- Linux x86-64 only.
- Absolute-deadline waits in the kernel, such as `futex`, `timerfd`, `clock_nanosleep(TIMER_ABSTIME)` and `epoll_wait` timeouts, run on real time, with or without a Monotonic Shift.
- setuid and non-dumpable processes cannot be shifted without root.
- Two Jetlags changing the same process at once is not protected against.
- Jetlag depends on epochd, which has one maintainer. Our changes are carried as patches against v0.8.1 and have not been sent upstream.

## Decisions

Architecture decision records are in `docs/adr/` in the product repo:

- Wrap epochd and contribute upstream.
- Keep no state: ask the process, and reconcile cgroup Targets.
- Jetlag works on its own descendants, or with `CAP_SYS_PTRACE`.
- The Jetlag API is loopback-only unless it has a token.
- Carry our epochd changes as patches against the pinned version.

Source: https://gitlab.techtailors.net/slopkit/jetlag
