On this page
On this page
Gateway
Gateway lock
Why
- Only one gateway process should own a state directory; run additional gateways with isolated profiles, state directories, configs, and ports.
- Recover ownership after a crash or SIGKILL when the recorded process is confirmed dead.
- Fail fast with a clear error when another gateway already owns the port.
Three layers
Startup establishes state ownership before publishing compatibility metadata and binding its listener:
Every server start uses the same admission, including the temporary Gateway started by container onboarding. Direct servers retain ownership until shutdown completes. Managed servers use the run loop's existing owner, which remains responsible for restart handoffs and release; closing one server generation does not release that owner.
- Process owner exclusively creates one sidecar keyed by the resolved shared-state database path. Gateway startup, embedded agents, and offline maintenance compete for this same owner.
OPENCLAW_ALLOW_MULTI_GATEWAY=1does not permit sharing mutable state. - Compatibility projection publishes the owner's PID, process start identity, role, and runtime port in the historical state-local lock. Supported older Gateways use it to detect the current process. It is metadata under the process owner, not an independent lifecycle owner.
- Socket bind binds the HTTP/WebSocket listener (default
ws://127.0.0.1:18789) as an exclusive TCP listener.
During startup or restart, the Gateway waits up to five minutes for another OpenClaw process to release state ownership. It checks ordinary contention every 250 ms so a prolonged shutdown does not leave the replacement sleeping after ownership is released. An owner in another Linux PID namespace is waited on for up to 95 seconds, which covers its 90-second heartbeat expiry after a crash. If it is still renewing its heartbeat after that, startup or Doctor fails as before and can be retried, for example by the container restart policy. Startup logs report the heartbeat age while waiting and the elapsed time when ownership is acquired.
Startup's earlier shared-state discovery also waits up to five minutes for live offline maintenance to finish, including after an update or service restart. It reports the current maintenance PID and role every 30 seconds, then reports admission or failure. Cancellation still ends the wait. The wait never kills the maintenance process, reclaims its live lock, or repeats admitted discovery work; if it expires, let the recorded process finish before retrying startup.
State and config locks
-
On Linux and macOS, the process owner lives at
$OPENCLAW_STATE_DIR/tmp/openclaw-<uid>/state.<hash>.lock. It uses the selected state storage without requiring write access to its parent or depending on the system temporary directory. On Windows it lives beneath the user'sAppData/Local/OpenClaw/locks/openclaw-state-ownersdirectory. The hash identifies the resolved shared-state database path.TMPDIRdoes not change this namespace. -
Destructive cleanup preserves the process owner and compatibility projection while removing state contents, so new startup remains blocked until native database resources and destructive operations settle. Normal release removes the sidecars; no SQLite coordinator database accompanies them.
-
Cleanup refuses redirected database or runtime-lock paths before deleting state: removing an internal symlink could select a new owner while the original files remain locked. Select the actual state root and real internal directories before retrying. An alias for the entire state root remains supported.
-
Ownership uses exclusive file creation and fs-safe's existing checked release and stale-recovery protocol. A dead process or a verified changed process start identity permits recovery. For owners in the same PID namespace, age alone never revokes a live owner. Unreadable ownership remains a refusal.
-
On macOS, new owner records include a purpose-specific digest of the hardware identity. A matching digest and a different kernel boot identity prove the previous owner stopped, even if the hostname changed. Different valid machine evidence remains unverifiable. Unavailable machine evidence falls through to the existing host, boot, and process checks. Linux keeps its existing recovery rules because machine IDs can be cloned or change between boots; it still requires the same PID namespace before inspecting a PID. Within one boot, macOS still tolerates hostname changes. Raw machine identifiers are never stored.
-
One successful macOS start writes the machine digest to both sidecars and the database owner lease. Legacy records keep their existing recovery rules; a pre-upgrade orphan whose hostname and boot both changed may need explicit recovery once. Older binaries ignore the added field when reading new records, preserving their existing rollback behavior.
-
Same-host Windows ownership uses the recorded PID and absolute process start time, without requiring a PowerShell boot-time query. Older records with boot timestamps use the same process-identity checks even when those timestamps disagree. A Linux PID reused as an unrelated worker thread is no longer the original owner. If process identity cannot be confirmed, stop the recorded holder before retrying; do not remove its lock while it may still be running.
-
Linux reads the PID namespace identity from the
/proc/self/ns/pidsymlink, so PRoot environments can verify ownership even when following that link withstatfails. The boot identity and namespace link must remain readable; unavailable identity does not disable ownership checks. -
Only explicitly launcher-bound CLI respawns record their launcher's PID and start identity. Detached update drivers retain independent maintenance ownership. Launcher loss requests graceful termination so Doctor can settle repairs, release leases, and restore services; the heartbeat worker supplies the same cancellation and bounded escalation if the main thread is blocked. Peers preserve custody until the owner exits, then recover its stale claim.
-
A dedicated worker renews the lock's mtime while the Gateway is busy. The worker and its parent measure the last successful renewal using the same wall-clock timestamp, including on Bun where worker-relative clocks have different origins. After a long pause or clock adjustment, the owner verifies the held inode and exact acquisition bytes before renewing. A process that retains its physical lock can resume safely; a removed or replaced lock ends ownership. Persistent renewal failures use a 60-second failure deadline. The shared heartbeat never advances beyond the oldest timestamp supplied to its locks.
-
Ordinary reads reuse verified process-owner and compatibility-projection custody while the local Gateway or embedded owner accepts work. Owner loss, release, cleanup, and schema-maintenance transitions invalidate the retained paths; there is no per-read expiry timer. Reads without a serving local process owner retain fresh verification. A failed initial verification refuses the affected read; the next read retries.
-
Writes, schema and maintenance transitions, lease grants, and each generic SQLite worker job retain fresh ownership checks at admission. Repeated read-access checks within that admission reuse process custody. This does not replace physical database identity, caller authorization, native-resource custody, or transaction/commit admission.
-
A missing namespace in a legacy Windows or macOS file lock (written before 2026.10.1) permits reclamation only after its heartbeat is more than 90 seconds old and native PID liveness or a recorded process start-time mismatch proves the owner stopped. It never grants local maintenance authority. On those platforms a PID names one process on the whole host. A missing or unreadable Linux namespace stays unverifiable and does not grant maintenance authority, even when a matching SQLite lease is absent or expired; lease expiry is not proof that a holder in another PID namespace stopped. After physical lock custody is acquired, an expired namespace-less SQLite Gateway lease can still be cleared by the explicit recovery path below when its inspected record is unchanged. Ordinary access to an existing compatible database, including restart-intent writes for older Gateways, does not require reclamation. Foreign schema and offline-maintenance owners still defer access; metadata snapshots require verified live or dead ownership before choosing a live backup or offline copy.
-
Schema/bootstrap work borrows retained authority from a live local Gateway or maintenance owner. Without one, it briefly acquires the same process gate and historical projection, so a new CLI cannot migrate state beneath a supported older Gateway. Accepted work retains both until it settles, even after its root stops lending authority.
-
The compatibility projection is
$OPENCLAW_STATE_DIR/tmp/openclaw-<uid>/gateway.state.lock(openclawon platforms without a user ID). New runtimes do not create the historical per-config lock or any.sqlitelock companions. Discovery still reads historical config and state locks for supported older runtimes. -
A live owner blocks another startup before either process binds its port. If the wait expires, startup reports:
text <lockPath>is the lock file that blocked the last attempt. When a historical lock file did, that file is named; otherwise it is the process owner sidecar (state.<hash>.lock), which is the file ownership actually lives in and may be the only lock the failure involves — the compatibility projection is metadata written lazily and may not exist. Failures that are not contention — an unwritable lock directory, for example — still name it.
Socket bind
-
On
EADDRINUSE, startup retries the bind for up to 20 attempts at 500ms intervals (roughly 10 seconds total) to ride out aTIME_WAITwindow after a recently exited process. -
If the port is still in use after retries:
text -
Other bind failures:
text
On shutdown, the Gateway closes its server and settles owned work before releasing its process owner and compatibility projection. Offline maintenance closes admission and retains both sidecars through state, linked config/credential, and alias removal, then drains its remaining database resources before releasing ownership.
In-process restarts run under the Gateway loop's lifetime, so closing the config reload or request that triggered a restart cannot cancel state-ownership reacquisition. Reacquisition failures include their underlying cause in the Gateway log. Contention with another owner retains the startup wait above.
On Unix, destructive cleanup retains SQLite's native exclusion until the database is removed. On Windows, SQLite's open file handles prevent unlink; the cleanup command closes its own check before removal. Native cleanup must finish before process ownership is released.
Normal upgrades preserve mutual exclusion with older state-local-lock runtimes through the compatibility projection and historical-owner checks. After releasing both sidecars, destructive cleanup removes only empty directories whose filesystem identities still match the directories it owned. A replacement directory or a new owner's files remain intact, and cleanup reports an interrupted removal. The managed update path stops the old service before mutation. Binaries predating state-local ownership retain their existing supported-upgrade stop checks.
Container restarts and replacements
Docker and Podman's default hostname records the container ID. Restarting the same container can reclaim a lock from its previous PID namespace immediately. A replacement container, or one with a custom hostname that cannot be identified as the same container, waits while the previous owner is renewing its heartbeat. The previous owner normally renews it every 15 seconds. After more than 90 seconds without renewal, the replacement takes over automatically. If the previous owner is still renewing after about 95 seconds, the replacement exits as before and its restart policy can retry. A graceful shutdown releases the lock without waiting for expiry.
Do not pause a Gateway for longer than 90 seconds while starting a replacement on the same state directory. If the old container resumes after takeover, it can briefly run alongside the replacement until its next restart. SQLite's native locking still protects the database file.
Supervisor-verified recovery
Set OPENCLAW_GATEWAY_REQUIRE_NAMESPACE_PROOF=1 on every process that can take
ownership of the shared state, including the Gateway and Doctor. With this
setting, a stale heartbeat or a matching container hostname cannot authorize
takeover from another Linux PID namespace.
Before starting the Gateway, a supervisor can recover the records of a container it has verified stopped. Supply the namespace identity captured in that container:
The JSON object contains platform (linux), host (the hostname), identity
(the kernel boot ID), pidNsInode (the decimal PID namespace inode as a string),
and pidNsInitStartTicks (PID 1's start time in kernel clock ticks).
OpenClaw checks every lock file and the Gateway database lease against that
identity. When PID numbers overlap with the caller's namespace, it also checks
that each recorded process stopped. If the supervisor cannot verify the previous
container, or a foreign record lacks the PID 1 start time, leave recovery to an
operator.
Recovering an older legacy record
Records from 2026.9.6 and earlier do not carry the newer Gateway-role process-lock contract. An unverifiable record can name a process that already stopped; stopping that PID again does not repair the record. Independently verify that no Gateway using this state is running on the host or in any container sharing it. Use a current OpenClaw CLI with the same state directory and profile to inspect the record:
Then run openclaw gateway recover-lock --confirm <confirmation> --json with the returned confirmation and retry Doctor. This diagnostic command is hidden from ordinary help. It refuses a changed record and clears a matching SQLite Gateway lease only while holding physical custody of the state. Do not confirm recovery while a shared-state Gateway may still be alive. An older installed CLI may not have this command.
Operational notes
- If the port is occupied by a different, non-gateway process, the error is the same; free the port or choose another with
openclaw gateway --port <port>. OPENCLAW_ALLOW_MULTI_GATEWAY=1permits multiple config/runtime instances, not shared mutable state. Each instance still needs a uniqueOPENCLAW_STATE_DIR.- Under a service supervisor, a new gateway process that hits either error above first checks
/healthzon the existing process. If that process is healthy, the new process leaves it in control instead of failing. On systemd, it exits with code78. A direct-Gateway unit'sRestartPreventExitStatus=78stopsRestart=alwaysfrom looping on a lock orEADDRINUSEconflict; a launcher-managed install outside a trial retries with crash backoff (1, 2, 5, 10, then 30 seconds indefinitely). If the existing process never becomes healthy, the health-check retry is time-bounded and startup then fails with the lock error above instead of looping forever. - A hardened systemd unit can fail the state ownership lock with
openat2 beneath root: Function not implemented (os error 38) | ENOSYSeven on a kernel that supportsopenat2(Linux 5.6 or newer). On the reported Ubuntu 24.04 / systemd 255 setup,RestrictSUIDSGID=trueinstalls a seccomp filter that returnsENOSYSforopenat2. Releases without the guarded fs-safe fallback (2026.9.5 and 2026.9.6) then crash-loop at startup, and Doctor on those releases can report the failure as unavailable maintenance ownership instead of the underlyingENOSYS. Do not delete lock or state files for this error. Upgrade to a release with the guarded fallback and keepRestrictSUIDSGID=true. If an upgrade is unavailable, temporarily removing the directive from the unit and its drop-ins, runningsystemctl --user daemon-reload, and restarting the service can confirm this filter interaction. This reduces service hardening; restore the directive when upgrading. See Secure file operations for native and fallback behavior. - The macOS app keeps its own lightweight PID guard before spawning the gateway; the file lock and socket bind above are the actual runtime enforcement.
Related
- Multiple Gateways - running multiple instances with unique ports
- Troubleshooting - diagnosing
EADDRINUSEand port conflicts