Skip to content

fix(ci): make linked computers, desktop runtime and tests reliable - #44

Merged
nixuuu merged 9 commits into
devfrom
fix/flaky-ci-tests
Nov 4, 2026
Merged

nixuuu merged 9 commits into
devfrom
fix/flaky-ci-tests

Conversation

@nixuuu

@nixuuu nixuuu commented Nov 4, 2026

Copy link
Copy Markdown
Member

Makes CI reliable again; one item is a real desktop regression.

  • Desktop gateway crashed on every start since feat(gateway): link computers with pinned mutual tls #13 (tsyringe requires a reflect polyfill): the desktop sidecar loads the gateway lazily, so @peculiar/x509's tsyringe ran before reflect-metadata. The desktop release jobs failed on it (no broken installer was published). Fix: load reflect-metadata first in the sidecar.
  • Linked computers closed live links under a slow database: heartbeats were handled after two DB round trips inside the per-link reader (300–430 ms against a 400 ms dead-link limit). A heartbeat now marks the link alive immediately and writes last_seen at most every 5 s; a late-firing timer no longer declares the peer dead. 37 → 0 failures under identical load.
  • Desktop sidecars ignored a stop during startup (kept running, or orphaned forever if the app died). They now exit at once.
  • Moves: shutdown stops move work before announcing; the roll-forward test really stops the source and waits for the target's own record.
  • Test harness/fixtures: unique scripted provider thread ids (collisions closed the worker link and cascaded 5 s timeouts); Postgres test containers without fsync and a non-blocking readiness wait (45 s, psql error in the message); the registry fixture counts only package downloads; the orphan test waits for the killed guardian's sidecars.

Verification: seven linked/queue/move files ×20 (final 360/360 + 180/180 after the last fix), desktop integration ×20 with no leftover dirs, restart loops 50/50, three full check:tmp runs green (833 pass / 0 fail); install, gen:check, typecheck, format:check, builds clean.

Follow-ups (not in this PR): one failing worker message stops event processing for that worker until it reconnects; the fixed 100 ms wait for the shutdown announcement could drop it under load.

The desktop sidecar imports the gateway dynamically, so Bun wraps it
lazily and runs its ESM dependencies before the CJS ones. tsyringe
(through @peculiar/x509, since the linked computers stage 1) then ran
before x509's own `import "reflect-metadata"` and threw, so the bundled
gateway exited on every start and the desktop never became ready.
The scripted worker reported `codex-` plus the last 4 hex digits of the
thread id. Two threads of one worker collided now and then on
threads_provider_thread: the gateway could not store the threadReady,
drained and closed the link, and every later test of the file waited
for a worker that was gone (queue-manage: the race and whileHead tests).
The moved thread shows on the target before the target records the move
as done (redirects first, then its own record), so a repeated decision
could still answer `committed`. Wait for the target's record instead.
Links died under load although both computers were up. Each heartbeat
was read only after two database round trips (the peer lookup and the
last_seen update), in the reader that handles a link's frames one after
another, so a slow database held up every frame behind it until the
link looked silent and was closed. Heartbeats were also sent from the
tick, which skips a beat while a slow tick is still running.

A heartbeat now marks the link alive at once and writes last_seen at
most every 5 s. Heartbeats and the dead-link check run on every
interval without the database, and a late interval (this process
stalled, the peer's frames may wait unread) gives no verdict.
Under load the throwaway PostgreSQL containers did not become ready in
the ~15 s the harness allowed: initdb synced every file (one sync step
alone took 17 s), and each readiness probe was a spawnSync that froze
the whole test process, other gateways' links included.

Test databases now skip fsync at init and at run time, the probe runs
asynchronously, and the wait is 45 s (before the suites' 60 s hook
limit) with psql's last error in the message.
The restart check failed now and then with one request too many. The
app had downloaded once; the extra requests were `GET /` probes that
local tools send to newly opened loopback ports (two test processes got
them in the same millisecond). The fixture now counts and serves only
the package tarball and answers anything else 404.
The worker sidecar listened for SIGTERM to close stdin, so the signal
no longer ended the process; until the worker installed its own stop
(after loading config, journal and recovery) a stop was swallowed and
it ran on until the supervisor's SIGKILL, or forever when its guardian
had died. The gateway sidecar's stdin-EOF stop went nowhere before the
gateway's handler existed. Both now exit right away while starting:
there is nothing to stop gracefully yet.

Seen as a test that left a worker writing into its removed directory.
close() announced the shutdown (and waited for it to go out) before it
closed the moves, so a heartbeat in between could still settle a move.
Moves now close first; what already runs finishes as before.

The roll-forward test simulated a crashed source by failing its commit
step while it kept running, and its heartbeat sometimes told the target
anyway. The source now stops there, like the target does in the same
test.
The orphan test checked only the postmaster. The killed guardian's
other sidecars stop on their own after stdin EOF; one still stopping
when the run removed its directory wrote into it again, and check:tmp
found a leftover. The test now requires all of them to be gone.
@nixuuu
nixuuu merged commit 9afe1ad into dev Nov 4, 2026
2 of 3 checks passed
@nixuuu
nixuuu deleted the fix/flaky-ci-tests branch November 4, 2026 09:56
nixuuu added a commit that referenced this pull request Nov 4, 2026
…46)

Code-quality phase 2, area A (docs/code-quality.md): `apps/gateway`
except store/bots/connectors — core, api, computers, updates,
worker-link, attachments, gateway root and tests. 321 non-size lint
findings → 0 (318 fixes; 3 justified disables in `core/worker-ssh.ts`:
the ambient `*.sh` reference and two terminal-control sanitizers). Typed
core values and error causes; linked-computer values decoded at the link
boundary; `GatewayCore` bot-thread actions and `linkedAgents.botTool`
now return JSON-compatible results, so six casts in `bots/platform.ts`
are gone. Rebased on #44/#45, keeping #44's heartbeat behaviour exactly.
No behaviour, proto or API changes. Size findings (22) are phase 3.

Checks: every linked-computer/queue integration file ×20 (1 900 passes,
0 failures), two full check:tmp runs 830 pass / 0 fail, install,
gen:check, typecheck, format:check, web build.
nixuuu added a commit that referenced this pull request Nov 6, 2026
Nightly releases were cancelled by assertions that observed an earlier
asynchronous event, plus three product lifecycle bugs. This change waits
for the state each assertion actually needs and fixes the product bugs
in separate commits. It adds no test retries, skips, blanket timeout
increases or workflow cancellation changes.

### Product fixes

- Bot shutdown releases the turn lease without replying “interrupted” to
a worker's pending tool call. Old handlers reject instead of continuing
to poll; the worker resends the same call after reconnect, preserving
the pending approval and running inference once. The restart test now
asserts these shutdown outcomes explicitly.
- LAN discovery shutdown drains outstanding certificate checks and route
writes. A handshake that finishes after discovery is disabled or
shutdown starts cannot add a route. The silence test drains old
discovery before deleting routes and observes actual query cycles
instead of sleeping.
- CLI discovery discards results captured before an overlapping install
completed. A successful install can no longer be published alongside the
previous executable/version. A controlled overlap reproduces the
original stale-version report deterministically using the real discovery
and installer code.

### Reproduction and results

Rates below are **failed executions / attempted executions**, not
historical workflow frequency. Gateway suites ran one file at a time,
pinned to one CPU (`taskset -c 10`); process tests used `--rerun-each
100`. Skill-source checks also ran with two bounded CPU burners on that
CPU. Temp data stayed on disk outside the repository. All repetitions
execute the assertions normally; no retry wrapper is committed.

| Test / suite | Cause and fix | Before | After |
| --- | --- | --- | --- |
| Governor: timeout kills an owned descendant | `/proc` exists/read
races with reaping (including `ESRCH`); parent completion also precedes
descendant signal delivery. Read once, catch only process disappearance,
wait until the owned process cannot execute, retain the no-delayed-write
assertion. | 9/100 | 0/100 |
| Bots harness: restart preserves pending approval | Product shutdown
returned an interruption or kept polling a released lease. Reject the
old handler and preserve the unanswered call for replay. | 4/30 | 0/30 |
| Composer: timeout and Stop kill the process group | Stop competed with
a global 1.5 s fixture timeout; a local PID marker can precede gateway
`turnStarted`; file creation can precede PID contents; immediate PID
existence counts zombies as running. Give only the timeout case its
short deadline, await gateway running state for Stop, publish PID
atomically and await process termination. | 1/1 full suite | 0/10 full
suites |
| Composer: Stop during shell steer | Same PID publication and
termination races. Keep interrupted-result and failed-delivery
assertions. | Empty PID reproduced during verification | 0/10 full
suites |
| Linked-home unreachable/read-only | Re-enabling sharing reconnects
before worker-record bootstrap arrives. Await the expected replicated
settings before disconnecting. | 1/10 | 0/10 |
| Remote thread creation/live stream | UI creation response precedes
worker command delivery. Await delivery and explicitly verify the echo;
settle its turn before enabling the next test's held-turn fixture. |
0/10 locally; 2 historical runs | 0/10 |
| Remote attached file | Earlier shared-turn state can cascade into
attachment waits. Finish held turns and restore fixture state in
`finally`; preserve byte/content checks. No independent message-loss bug
reproduced. | 0/10 locally; 2 historical runs | 0/10 |
| Remote inline file / older peer | Same shared-turn sequencing;
explicitly assert the received input exists before inspecting it.
Preserve placement and old-peer fallback assertions. | 0/10 locally; 2
historical runs | 0/10 |
| Relay: reciprocal sharing | Route withdrawal precedes asynchronous
mirror purge. Await purge and retain the late-subscription rejection
assertion. | 0/5 locally; 2 historical runs | 0/10 |
| LAN: discovery disabled | Pending handshakes/writes survived socket
closure and could recreate deleted routes. Drain discovery and recheck
enablement after TLS. | 1/5 | 0/10 |
| CLI: native update / discovery overlap | Product report combined a
pre-install version with a post-install success status. Discard
discovery across an install revision. | Controlled overlap 1/1; original
suite 0/1 | Controlled overlap 0/100; original suite 0/10 |
| Grok process cleanup (disposal and ignored cancellation) | Immediate
PID check assumes signal delivery/reaping is synchronous. Use the shared
bounded process-state condition; a zombie cannot execute. The reported
flake did not reproduce locally. | 0/600 tests (100 complete runs) |
0/600 tests (100 complete runs) |
| Agent skill sources | No verified current cause found; left assertions
and product code unchanged. | 0/5 full suites plus 0/1 with two CPU
burners | Passed in the full gate |

The new process wait retains a five-second failure bound and accepts
only a missing or non-executable process. Unexpected OS errors still
fail the test. Stop still has to terminate its child and persist a user
interruption; the timeout case still has to fail without launching a
harness.

### Historical inventory

Audit snapshot: **189 `dev` Release runs**, 2026-11-03 08:39 UTC through
2026-11-06 08:52 UTC, and **9 failed CI runs**. Read failed job logs,
including first-attempt logs for the successful rerun of Release
`42072916585`. Counts are distinct failed workflow runs per test,
deduplicating run IDs across both listings and Bun's repeated summary
lines. They are not a failure percentage: cancelled jobs did not all
execute every test. Superseded cancellations with no failed job are
excluded from test counts.

| Full test name | Failed runs | Disposition |
| --- | ---: | --- |
| bots, schedules and worker settings at their linked home > an
unreachable home fails immediately, keeps records read-only and queues
nothing | 7 | Bootstrap barrier in this PR |
| bot platform tools through the UI core > discover a worker without
roots, add any absolute workspace, validate paths, start a thread and
search its title | 5 | Already fixed by #107: wait for the returned
initial turn to finish |
| bots through official worker harnesses > gateway restart preserves a
pending approval and never reruns inference | 4 | Product fix in this PR
|
| process governor with owned subprocesses > a timeout kills an owned
descendant that would otherwise survive its parent | 3 | Process-state
condition in this PR |
| Share onward: three real gateways and independent databases > explicit
reciprocal sharing permits both directions without a routing loop | 2 |
Mirror-purge barrier in this PR |
| bundled stack: local enrollment, gRPC online, remote enrollment,
restart durability and complete shutdown | 2 | Already fixed by #44
(missing desktop reflect polyfill/startup) and #103 (initial pairing
racing secure-route migration; preserves identity/data and separately
verifies unchanged saves) |
| migration 0077: connector configuration bootstrap > (unnamed) | 2 |
Deterministic historical schema/fixture failure, not classified as a
flake |
| moving things between linked computers > interrupted after the
decision: the move rolls forward through restarts and link drops,
idempotently | 2 | Already fixed by #44: stop source work and await
target's own record |
| remote threads across two linked gateways > a file attached on A
travels with the message to B | 2 | Shared-turn sequencing in this PR;
no independent message loss reproduced |
| remote threads across two linked gateways > a file placed in the text
on A keeps its place on B; an older B gets the text without the badge |
2 | Shared-turn sequencing in this PR; no independent message loss
reproduced |
| remote threads across two linked gateways > a thread created from A on
B's worker lives on B and streams back live | 2 | Worker-delivery /
turn-completion barriers in this PR |
| Bun worker -> grpc-js (Node) gateway over TLS > handshake, command,
100 events, ack, worker half-close | 1 | Already fixed by #107: await
the client-end output event |
| a postmaster orphaned by a killed guardian is stopped on the next
start, so only one runs | 1 | Already fixed by #44: await orphaned
sidecars during recovery |
| actionable errors across gateway APIs > Grok bot with native id and
Proxy connection uses the gateway API without a reasoning-starving cap |
1 | Obsolete API expectation; Grok execution now uses worker harnesses |
| attachments > access to bytes > a preview the worker uploaded is
readable through its thread (and its tree), nothing else | 1 |
Historical 5 s timeout; current reproduction not established; #44 fixed
scripted provider-ID collisions that could close links, but attribution
of this timeout is unproven |
| automation worktrees over gRPC > settled scheduled threads can be
cleaned up and linked worktree schedules are refused | 1 | Deterministic
historical expectation/refusal mismatch |
| durable read-only thread mirrors across two gateways > a stale cursor
or a journal gap fully resynchronizes, removing deleted threads and
preserving archivals | 1 | Historical 60 s timeout; current cause not
established; no speculative change |
| guardian closes its owned process groups when the Electron pipe
disappears | 1 | Already fixed by #44: stop during startup / desktop
sidecar initialization |
| managing the queue (gateway + scripted worker) > races with the head
starting: the scheduler starts the head as it stands, with its current
text | 1 | Historical closed worker link; #44 fixed colliding scripted
provider thread IDs, but the log does not prove this particular link's
closure cause |
| managing the queue (gateway + scripted worker) > the scheduler starts
a head only as it read it (whileHead) | 1 | Same historical closed
worker link; exact attribution unproven |
| owner-scoped SSH enrollment trust boundary > (unnamed) | 1 |
Deterministic malformed OpenSSH fixture failure in `beforeAll` |
| provider CLIs (gateway + real worker + fake CLIs and registry) >
native Claude updates with `claude install`; output is redacted and
secrets never reach the installer | 1 | Product report-consistency fix
in this PR; regression forces the overlap |
| remote threads across two linked gateways > only thread actions cross
the link; requests that point elsewhere are refused | 1 | Deterministic
historical allowed-method expectation |
| routes and local network discovery between two linked gateways > with
discovery off a computer announces nothing, answers nothing and forgets
LAN routes | 1 | Product discovery-lifecycle fix in this PR |
| worker enrollment and credential lifecycle over gRPC > CLI spends a
token once, writes a private config, connects; rotation and revoke
invalidate the live link | 1 | Already fixed by #45: enrollment token
beginning with a dash was parsed as a CLI option |

An additional failed CI run (`41914149735`) failed migration-ID/lint
checks without a test failure; it is not a per-test row. Composer, Grok
cleanup and skill sources were also investigated because they were
reported in the task, although those names did not appear in this
audit's failed-job inventory.

### Validation and limits

- `bun install`, `bun run gen:check`, `bun run typecheck`, `bun run
lint`, `bun run format:check` and `bun scripts/build-web.ts` passed
after rebasing onto current `origin/dev`.
- Full `bun run check:tmp`: **1,448 passed, 159 existing skips, 0
failed**, 258 files / 1,607 tests, 462.49 s. No test temp directories
left behind; tool-owned runtime caches were removed by the runner's
private-directory cleanup.
- Additional unchanged suites: thread mirrors, attachments and queue
management each passed **5/5 complete runs** pinned to one CPU.
- The exact historical attachment-preview, mirror-resync and queue-link
failures have no proven current root cause. The reported skill-source
and Grok flakes did not reproduce in the bounded local runs. Passing
repetitions reduce uncertainty; they do not prove every historical
failure has been eliminated.
- No live-provider tests, packaged macOS runtime tests or browser/E2E
tests were enabled. Existing opt-in skips remain unchanged. No UI copy
changed; the new gateway shutdown rejection is an internal worker replay
signal.

Fixes: #97
Fixes: #35
Fixes: #26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant