Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions docs/specs/account-vpn.md
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,60 @@ public exit addresses through that child. Opening a new tunnel always reads
the current account-wide session count under the reservation lock. Restarting
the child discards its session metadata.

### A device after its tunnel stopped

AirVPN keeps listing the session of a tunnel for a few minutes after the
tunnel is gone. Until 30 Nov 2026 every start in that window was refused with
`airvpn_device_in_use`, so no VPN-routed account worked for minutes after each
Core restart, and after any retired tunnel.

Core records who last started each device. After a verified start, and still
under `airvpn.lock`, it replaces `holder-<device>.json` in the coordinator
directory with its instance (`prod` or `dev`, the identity that also scopes
managed machines), its process id and the start time of that process from
`/proc/<pid>/stat`. A start that cannot write the record stops its tunnel and
fails with `vpn_coordinator_unavailable`: an older record must never go on
naming someone else.

When AirVPN lists a session on the device being started, the start may
replace it only if the record names this same instance and either:

- the recorded process no longer exists (missing, a zombie, or its process id
now belongs to a process with another start time). This is decided on Linux
only, where the parent-death signal ends a tunnel with its Core process; or
- the record names this very process, with a known start time. A process
starts a device only while it runs no tunnel on it, so the listed session is
the one it stopped itself.

A replaced session does not count against the session limit, since the
handshake takes its place. Every other session still counts and still needs
readable evidence.

No record, an unreadable record, a record of the other instance, or a
recorded process that still runs or cannot be observed keeps the old answer,
`airvpn_device_in_use`. Dev never takes over a device last started by prod,
and the reverse. The record says nothing about a consumer outside Orb that
uses the same device key: device profiles imported into Orb are for Orb only.
`AirVpnTunnel.ownStaleSession` is the rule, `checkStart` the reservation.

### When a route is only waiting

Three refusals clear without an operator: `vpn_coordinator_busy` (another
start holds the lock), `airvpn_device_in_use` (the case above, when the
takeover is not allowed) and `vpn_exit_in_use` (another account of the
category occupies the exit). `AccountVpnPool.transientRetrySecs?` lists them
with the time after which a retry is worth it.

When Core chooses the Antigravity account for an admin turn
(`adminDirectAntigravityStaticTarget?`), an account whose route is waiting is
passed over for the next usable account, VPN-routed or Direct, in priority
order. The route is checked only for accounts that are otherwise usable, and
only up to the chosen one, because the check starts the tunnel. A waiting
account never runs without its route. If no other account can take the turn,
the waiting account is kept, so the refusal names its route: the answer is
`409` with the `error` code, a `message` in plain words and
`retry_after_secs`. See [refused-launch.md](refused-launch.md).

The WireGuard test changes the actual source address using SNAT inside the
test namespace. Each tunnel has IPv4 and IPv6 addresses. An IPv6-only
collision forces one ChatGPT account onto a verified third peer even though
Expand Down
67 changes: 67 additions & 0 deletions docs/specs/refused-launch.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
# Refused launches

A launch that Core refuses leaves nothing behind: no mission, no row in any
client, and no second attempt made by a transport on the user's behalf.

## Incident (30 Nov 2026)

One click on an Antigravity launch answered
`antigravity_vpn_unavailable:airvpn_device_in_use` and left three missions in
the sidebar. None of them existed in Core.

1. Core writes the mission row and appends its first `user_message` before it
asks the node to run the turn. Both reach live clients at once: the event
through the mission stream, the row through the list refresh that every
`mission_presentation` hint triggers.
2. The dispatch was refused (the VPN route, see
[account-vpn.md](account-vpn.md)). Core deleted the row without telling
anyone. The desktop list is reconciled, never replaced, so a row that a
later answer omits stays.
3. The refusal was answered `502`. `orb-locald` forwards a write that carries
an `Idempotency-Key` to the next of its three origins on `429` and any
`5xx` (`lean/OrbLocald/OrbLocald/CliMain.lean`). All three origins reach
the same Core, and the refusal had released the key, so each forward
created, announced and deleted another mission.

## Rules

**One rollback.** Every path that removes a mission whose creation did not
commit (create, fork, `/btw`, MCP `start_mission` / `consult_model`) calls
`discardUnbornMission` (`lean/OrbCore/OrbCore/Store.lean`). It deletes the
mission with its events and runs, then emits the same
`mission_presentation` / `mission_deleted` notice as an explicit delete, with
the owner so the frame is authorized after the row is gone.

**Removal is an event.** A client removes the row when it receives
`mission_deleted`, and keeps it out of a list answer that was requested
earlier. Desktop: `removedMissionId` in `orb/src/missionHierarchy.ts`, applied
in `App.tsx` and the sidebar tree. iOS and Android refresh their roster on the
same hint and do not yet remove the row on the event itself.

**A refusal keeps its answer.** A create that is refused after real work
(placement, track lease, auto-managed machine, dispatch) records the refusal
on its idempotency key (`refuseIdempotencySlot`, phase `refused`) instead of
releasing it. A repeat of the key within `idempotencyRefusalReplaySecs`
(10 s) gets the same status and body and does no work. After that the key
reserves a fresh attempt, so a person who retries the same draft later is not
stuck with an old refusal. Refusals do not survive a Core restart. Validation
errors (`400`) still release the key at once.

**A status that says who refused.** A launch refused by Core itself for an
account or VPN-route reason (`antigravity_*`, `native_*`) answers `409`, not a
gateway status. A node that rejects the job still answers `502`, and the
replay window above covers the forwards that follow. When the cause clears by
itself the body carries `message` in plain words and `retry_after_secs` next
to the `error` code, and the composer shows the message.

## Tests

- `TurnOutcomeTests.lean`: a create whose dispatch the node rejects leaves no
mission and no event, a repeat with the same key returns the same answer
without reaching the node, and listeners receive `mission_deleted` after the
`user_message`.
- `SelfTest.lean`: a refusal replays inside the window, the key reserves again
after it, and a refusal without a reservation writes nothing.
- `orb/tests/mission-hierarchy.test.ts`, `orb/tests/launch.test.ts`: a partial
list keeps the row, only `mission_deleted` names it for removal, and the
composer shows Core's explanation.
3 changes: 2 additions & 1 deletion lean/OrbCore/OrbCore/AccountVpnApi.lean
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ private def reasonMessage : String → String
| "vpn_coordinator_unconfigured" => "The Core VPN coordinator needs configuration."
| "vpn_coordinator_unavailable" => "Check Core’s access to the shared AirVPN coordinator directory."
| "vpn_coordinator_busy" => "Another VPN connection is starting. Retry shortly."
| "airvpn_device_in_use" => "This WireGuard device already has an active session."
| "airvpn_device_in_use" =>
"AirVPN lists a session for this WireGuard device. One left by a stopped tunnel clears within a few minutes."
| "vpn_route_changed" => "The account connection changed during verification. Reload its settings."
| "vpn_profile_changed" | "vpn_profile_unavailable" => "Check the saved WireGuard profile for this server in AirVPN Settings."
| "vpn_process_unavailable" | "vpn_start_failed" | "vpn_config_transfer_failed" =>
Expand Down
10 changes: 10 additions & 0 deletions lean/OrbCore/OrbCore/AccountVpnPool.lean
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,16 @@ structure PoolState where

abbrev Pool := Std.Mutex PoolState

/-- Refusals that clear without an operator, with the seconds after which a
retry is worth it: another start holds the coordinator lock, AirVPN still
lists a closed session of the device, or another account occupies the exit.
Meanwhile a request can be served by another account. -/
def transientRetrySecs? : String → Option Nat
| "vpn_coordinator_busy" => some 15
| "airvpn_device_in_use" => some 180
| "vpn_exit_in_use" => some 60
| _ => none

private def unlock (locks : List UInt32) : IO Unit :=
locks.forM fun fd => closeFdRaw fd.toInt32

Expand Down
32 changes: 32 additions & 0 deletions lean/OrbCore/OrbCore/AirVpnSettingsTests.lean
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,38 @@ def run (root : String) : IO Unit := do
"reservation preserves other consumers of the same device"
check ((checkSlot (Array.replicate 5 other)).isOk == false &&
!(checkSlot #[JVal.null]).isOk) "full budget and unknown devices block startup"
-- After a Core restart AirVPN lists the previous process's session for a few minutes.
let thisCore : AirVpnTunnel.Holder := ⟨"prod", 4242, 99⟩
let predecessor : AirVpnTunnel.Holder := ⟨"prod", 4000, 7⟩
let otherInstance : AirVpnTunnel.Holder := ⟨"dev", 4000, 7⟩
let untimed : AirVpnTunnel.Holder := ⟨"prod", 4242, 0⟩
let unnamed : AirVpnTunnel.Holder := ⟨"", 4242, 99⟩
let stale := AirVpnTunnel.ownStaleSession thisCore
check (stale (some predecessor) true && stale (some thisCore) false)
"the leftover of this instance's dead predecessor, or of this process's stopped tunnel, may be replaced"
check (!stale none true && !stale (some otherInstance) true && !stale (some predecessor) false &&
!AirVpnTunnel.ownStaleSession untimed (some untimed) false &&
!AirVpnTunnel.ownStaleSession unnamed (some unnamed) true)
"an unknown holder, another instance or a process that may still run keeps the device"
let checkStart := fun (sessions : Array JVal) (staleOwn : Bool) => AirVpnTunnel.checkStart [v4] sessions staleOwn
check ((checkStart #[used] true).isOk && !(checkStart #[used] false).isOk &&
(checkStart ((Array.replicate 4 other).push used) true).isOk &&
!(checkStart (Array.replicate 5 other) true).isOk && !(checkStart #[JVal.null, used] true).isOk)
"a replaced session frees only its own slot; other consumers and unknown sessions still count"
let holderDir := root ++ "/airvpn-holder-test"
IO.FS.createDirAll holderDir
let noRecord ← AirVpnTunnel.readHolder holderDir "device"
check noRecord.isNone "no record means an unknown holder"
let wroteFirst ← AirVpnTunnel.recordHolder holderDir "device" predecessor
let readFirst ← AirVpnTunnel.readHolder holderDir "device"
check (wroteFirst && readFirst == some predecessor) "holder record written and read back"
let wroteNext ← AirVpnTunnel.recordHolder holderDir "device" thisCore
let readNext ← AirVpnTunnel.readHolder holderDir "device"
check (wroteNext && readNext == some thisCore) "a later start replaces the record"
let wroteOutside ← AirVpnTunnel.recordHolder holderDir "../device" thisCore
let readOutside ← AirVpnTunnel.readHolder holderDir "../device"
check (!wroteOutside && readOutside.isNone)
"a device name cannot address a file outside the coordinator directory"
let dir := root ++ "/airvpn-settings-test"
check ((sessionRecords? (.obj #[("result", .str "ok")])).isNone)
"missing session list cannot admit a new tunnel"
Expand Down
90 changes: 87 additions & 3 deletions lean/OrbCore/OrbCore/AirVpnTunnel.lean
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import OrbCore.AirVpnObservation
import OrbCore.AirVpnSettings
import OrbCore.HarnessSessionRegistry

namespace OrbCore.AirVpnTunnel

Expand Down Expand Up @@ -105,9 +106,83 @@ def checkReservation (addresses : List ExitAddress) (sessions : Array JVal) : Ex
throw "airvpn_session_evidence_unavailable"
if sessions.any (ownsSession addresses) then throw "airvpn_device_in_use"

/-- The Core process that last started a tunnel on a device: which instance
(`prod` or `dev`) and which process. A tunnel dies with its Core process, but
AirVPN keeps listing its session for a few minutes. -/
structure Holder where
service : String
pid : UInt32
startTicks : UInt64
deriving DecidableEq, Repr

/-- Whether the session AirVPN still lists for a device is a leftover of this
instance's own tunnel, which a new handshake may replace. `recordedGone` says
the recorded process no longer exists. The record of this very process also
qualifies when its start time is known: it starts a device only when it runs
no tunnel on it. A missing record, another instance, or a process that may
still run keeps the device reserved for its holder. -/
def ownStaleSession (self : Holder) (recorded? : Option Holder) (recordedGone : Bool) : Bool :=
match recorded? with
| none => false
| some h =>
!self.service.isEmpty && h.service == self.service &&
(recordedGone || (self.startTicks != 0 && h == self))

/-- Reservation for starting a device. A stale session of this instance is
replaced by the new handshake, so it neither blocks the start nor counts
against the session limit. -/
def checkStart (addresses : List ExitAddress) (sessions : Array JVal) (staleOwn : Bool) :
Except String Unit :=
checkReservation addresses (if staleOwn then sessions.filter (fun s => !ownsSession addresses s) else sessions)

private def holderPath? (sharedDir device : String) : Option System.FilePath :=
if device.isEmpty || device.length > 128 || !device.all (fun c => c.isAlphanum || c == '-' || c == '_') then none
else some ((System.FilePath.mk sharedDir) / s!"holder-{device}.json")

/-- The caller holds the coordinator lock. An unreadable record is no record. -/
def readHolder (sharedDir device : String) : IO (Option Holder) := do
let some path := holderPath? sharedDir device | return none
let raw ← try IO.FS.readFile path catch _ => return none
let .ok value := OrbBin.Json.parse raw | return none
let some service := value.fieldStr? "service" | return none
let some pid := value.fieldNat? "pid" | return none
let some ticks := value.fieldNat? "start_ticks" | return none
return some ⟨service, pid.toUInt32, ticks.toUInt64⟩

/-- The caller holds the coordinator lock. The file is replaced, so an
instance running as another user can take the record over. A record that
cannot be written must not leave an older one naming someone else. -/
def recordHolder (sharedDir device : String) (holder : Holder) : IO Bool := do
let some path := holderPath? sharedDir device | return false
try IO.FS.removeFile path catch _ => pure ()
try
IO.FS.writeFile path (renderCompact (.obj #[
("service", .str holder.service),
("pid", .num (toString holder.pid)),
("start_ticks", .num (toString holder.startTicks))]))
return true
catch _ => return false

/-- This Core process as a holder. Without a readable start time (no Linux
`/proc`) the identity cannot be told from a later process with the same id. -/
def currentHolder : IO Holder := do
let pid ← IO.Process.getPID
let ticks ← OrbCore.HarnessSessionRegistry.readLiveProcStartTicks? pid
return ⟨← currentManagedInstance, pid, ticks.getD 0⟩

/-- Only Linux ends a tunnel with its Core process (parent-death signal), and
only there the start time distinguishes a reused process id. A process that
cannot be observed counts as still running. -/
private def holderGone (h : Holder) : IO Bool := do
if !System.Platform.isLinux || h.pid == 0 || h.startTicks == 0 then return false
let obs ← OrbCore.HarnessSessionRegistry.observeProcStat h.pid
return Orb.Kernel.procLivenessStep obs.procMissing obs.procReadError obs.isZombieOrDeadState 1
obs.fieldsAfterComm h.startTicks obs.actualStartTicks == 0

/-- Dev and production use the same operator-owned directory. Hold the lock
through the handshake until AirVPN lists the session, so the next reservation
sees it. A device already in use cannot replace another consumer's session. -/
sees it. A device already in use cannot replace another consumer's session;
the leftover session of this instance's own stopped tunnel can be replaced. -/
def startVerified (root sharedDir device server country : String) (port : UInt16) :
IO (Except String (Tunnel × VerifiedTunnel)) := do
if sharedDir.isEmpty then return .error "vpn_coordinator_unconfigured"
Expand All @@ -118,7 +193,13 @@ def startVerified (root sharedDir device server country : String) (port : UInt16
let some (endpoint, profile) ← readEndpoint root device | return .error "vpn_profile_unavailable"
if endpoint.country != country || endpoint.server != server then return .error "vpn_profile_changed"
let .ok sessions ← activeSessions root | return .error "airvpn_session_evidence_unavailable"
if let .error e := checkReservation profile.addresses sessions then return .error e
let self ← currentHolder
let recorded? ← readHolder sharedDir device
let recordedGone ← match recorded? with
| some h => holderGone h
| none => pure false
if let .error e := checkStart profile.addresses sessions (ownStaleSession self recorded? recordedGone) then
return .error e
let t ← match ← start profile port with
| .ok t => pure t
| .error e => return .error e
Expand All @@ -131,7 +212,10 @@ def startVerified (root sharedDir device server country : String) (port : UInt16
if evidence.isSome then break
pure evidence
catch _ => pure none
if let some verified := checked then return .ok (t, verified)
if let some verified := checked then
if ← recordHolder sharedDir device self then return .ok (t, verified)
t.stop
return .error "vpn_coordinator_unavailable"
t.stop
return .error "vpn_exit_unverified"
finally closeFdRaw lock.toInt32
Expand Down
Loading
Loading