Skip to content

[Bug]: Tailscale Serve discovery resets a learned route's saved order after a server restart or one probe timeout #35529

Closed as not planned

Description

@coygeek

Before submitting

  • I searched existing issues and did not find a duplicate.
  • I included enough detail to reproduce or investigate the problem.

Area

Not sure

Steps to reproduce

  1. With dependencies installed at the version below, save the following as apps/server/src/environment/zzrepro-leads-endpoint-order.test.ts. It uses the real DirectEndpoints.make, Tailscale status parser, HTTPS descriptor probe, and mergeLearnedRoutes; only the external process and HTTP responses are fixtures. The JSON uses the BackendState, Self.DNSName, Self.TailscaleIPs, and capability-map shapes of Tailscale status. The descriptor names the same environment as the saved routes. No server or Tailscale daemon starts.
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it as effectIt } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Deferred from "effect/Deferred";
import * as Fiber from "effect/Fiber";
import * as Ref from "effect/Ref";
import * as Layer from "effect/Layer";
import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import * as HttpClient from "effect/http/HttpClient";
import type * as HttpClientRequest from "effect/http/HttpClientRequest";
import * as HttpClientResponse from "effect/http/HttpClientResponse";
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
import { expect } from "vite-plus/test";

import * as ServerConfig from "../config.ts";
import * as DirectEndpoints from "./DirectEndpoints.ts";

import * as TestClock from "effect/testing/TestClock";
import { EnvironmentId, type ServerDirectEndpoint } from "@t3tools/contracts";
import * as Option from "effect/Option";
import { RelayConnectionTarget } from "../../../../packages/client-runtime/src/connection/model.ts";
import { type ConnectionCatalogEntry, type ConnectionRoute } from "../../../../packages/client-runtime/src/connection/catalog.ts";
import { connectionRouteId, connectionRoutes, entryWithRoutes, mergeLearnedRoutes } from "../../../../packages/client-runtime/src/connection/routes.ts";

const TAILSCALE_STATUS_JSON = JSON.stringify({
  BackendState: "Running",
  Self: { DNSName: "host-a.tailnet-name.ts.net.", TailscaleIPs: ["100.64.0.1"], CapMap: { https: null } },
});

const layerTailscaleUp = Layer.succeed(
  ChildProcessSpawner.ChildProcessSpawner,
  ChildProcessSpawner.make(() =>
    Effect.succeed(
      ChildProcessSpawner.makeHandle({
        pid: ChildProcessSpawner.ProcessId(1),
        exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
        isRunning: Effect.succeed(false),
        kill: () => Effect.void,
        unref: Effect.succeed(Effect.void),
        stdin: Sink.drain,
        stdout: Stream.make(new TextEncoder().encode(TAILSCALE_STATUS_JSON)),
        stderr: Stream.empty,
        all: Stream.empty,
        getInputFd: () => Sink.drain,
        getOutputFd: () => Stream.empty,
      }),
    ),
  ),
);

const T3_DESCRIPTOR_BODY = JSON.stringify({
  environmentId: "test-environment",
  label: "Serve test",
  platform: { os: "linux", arch: "x64" },
  serverVersion: "0.0.0-test",
  capabilities: { repositoryIdentity: true },
});

const serveProbeResponse = (request: HttpClientRequest.HttpClientRequest, status: number) =>
  HttpClientResponse.fromWeb(
    request,
    new Response(status === 200 ? T3_DESCRIPTOR_BODY : null, { status }),
  );

const layerServeConfig = (host = "127.0.0.1") =>
  Layer.effect(
    ServerConfig.ServerConfig,
    Effect.map(ServerConfig.ServerConfig, (config) => ({
      ...config,
      host,
      privateNetworkOnly: false,
      port: 3773,
      tailscaleServeEnabled: true,
      tailscaleServePort: 443,
    })),
  ).pipe(
    Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-direct-" })),
    Layer.provide(NodeServices.layer),
  );


const environmentId = EnvironmentId.make("test-environment");
const relay: ConnectionRoute = {
  target: new RelayConnectionTarget({ environmentId, label: "Server" }),
  profile: Option.none(),
};
const relayOnly: ConnectionCatalogEntry = { ...relay, enabled: true };
const reported = [{ kind: "tailnet" as const, httpBaseUrl: "https://host-a.tailnet-name.ts.net/" }];
const learned = mergeLearnedRoutes({ entry: relayOnly, activeRoute: relay, reported, allowInsecure: true })!;
// The user drags T3 Connect ahead of the learned Tailscale route.
const customized = entryWithRoutes(relayOnly, [relay, learned[0]!]);
const ids = (entry: ConnectionCatalogEntry) => connectionRoutes(entry).map(r => connectionRouteId(r.target) === "relay" ? "T3 Connect" : "Tailscale HTTPS");
const applyReport = (entry: ConnectionCatalogEntry, endpoints: ReadonlyArray<ServerDirectEndpoint>) => {
  const next = mergeLearnedRoutes({ entry, activeRoute: relay, reported: endpoints, allowInsecure: true });
  return next === null ? entry : entryWithRoutes(entry, next);
};

effectIt.effect("fresh discovery and a timeout each erase the learned route's saved order", () =>
  Effect.gen(function* () {
    const probeStarted = yield* Deferred.make<void>();
    const finishProbe = yield* Deferred.make<void>();
    const service = yield* DirectEndpoints.make.pipe(Effect.provide(Layer.mergeAll(
      layerServeConfig(), layerTailscaleUp,
      Layer.succeed(HttpClient.HttpClient, HttpClient.make(request => Effect.gen(function* () {
        yield* Deferred.succeed(probeStarted, undefined);
        yield* Deferred.await(finishProbe);
        return serveProbeResponse(request, 200);
      }))),
    )));
    console.log("saved order:", JSON.stringify(ids(customized)));
    const firstResolve = yield* Effect.forkScoped(service.resolve());
    yield* Deferred.await(probeStarted);
    const initial = yield* service.resolveAvailable();
    console.log("fresh initial endpoints:", JSON.stringify(initial));
    const dropped = applyReport(customized, initial);
    yield* Deferred.succeed(finishProbe, undefined);
    const completed = yield* Fiber.join(firstResolve);
    console.log("fresh completed endpoints:", JSON.stringify(completed));
    const relearned = applyReport(dropped, completed);
    console.log("order after fresh discovery:", JSON.stringify(ids(relearned)));
    expect(ids(relearned)).toEqual(["Tailscale HTTPS", "T3 Connect"]);

    const pending = yield* Deferred.make<void>();
    const timeoutProbeStarted = yield* Deferred.make<void>();
    const timeout = yield* Ref.make(false);
    const service2 = yield* DirectEndpoints.make.pipe(Effect.provide(Layer.mergeAll(
      layerServeConfig(), layerTailscaleUp,
      Layer.succeed(HttpClient.HttpClient, HttpClient.make(request => Effect.gen(function* () {
        if (yield* Ref.get(timeout)) {
          yield* Deferred.succeed(timeoutProbeStarted, undefined);
          yield* Deferred.await(pending);
        }
        return serveProbeResponse(request, 200);
      }))),
    )));
    console.log("validated endpoints:", JSON.stringify(yield* service2.resolve()));
    yield* Ref.set(timeout, true);
    const revalidate = yield* Effect.forkScoped(service2.resolve());
    yield* Deferred.await(timeoutProbeStarted);
    yield* TestClock.adjust("2500 millis");
    const afterTimeout = yield* Fiber.join(revalidate);
    console.log("endpoints after one probe timeout:", JSON.stringify(afterTimeout));
    expect(afterTimeout).toEqual([]);
    yield* Ref.set(timeout, false);
    const recovered = yield* service2.resolve();
    const reordered = applyReport(applyReport(customized, afterTimeout), recovered);
    console.log("order after timeout and recovery:", JSON.stringify(ids(reordered)));
    expect(ids(reordered)).toEqual(["Tailscale HTTPS", "T3 Connect"]);
  }).pipe(Effect.scoped),
);
  1. From the repository root, run node_modules/.bin/vp test run apps/server/src/environment/zzrepro-leads-endpoint-order.test.ts --silent=false.
  2. Read the printed route order. The test deliberately asserts the observed wrong order, so it passes while demonstrating the bug. Delete the scratch test afterward.

Deterministic: both triggers reproduced on all four focused runs; the exact final inline fixture was run once. The timeout is advanced with the virtual test clock. A full desktop, browser, or mobile session was not run.

Expected behavior

A learned route's custom position should survive pending discovery and a temporary probe failure when the same address returns. docs/user/remote-access.md:118-119 says routes can be reordered, and docs/user/remote-access.md:128-130 explicitly says learned routes can be reordered. Temporarily withdrawing an unusable endpoint can be appropriate, but finding the same URL again should not silently undo that choice. This expectation does not require advertising an unvalidated or failing endpoint. The consequence of ordering is documented at docs/user/remote-access.md:132-136: the client tries routes in order and checks earlier routes while connected over a later one.

Actual behavior

In apps/server/src/environment/DirectEndpoints.ts and packages/client-runtime/src/connection/routes.ts, a user-selected order of T3 Connect followed by a learned Tailscale HTTPS route becomes Tailscale HTTPS followed by T3 Connect after discovery temporarily omits the unchanged Serve URL. Focused runs of the production discovery and route-merging functions reproduced both triggers: a fresh service returns no HTTPS endpoint while its first validation is pending, and a previously validated service clears its endpoint after a single HTTPS probe times out. When the same URL is reported again, it is inserted at its default position ahead of T3 Connect instead of its saved position. This changes which route the client prefers; it is not just a transient endpoint health display.

The supported server/client path is source-only beyond those functions: t3 serve --tailscale-serve or the desktop Tailscale HTTPS setting enables discovery; the config subscription starts validation in a fiber and gets its initial endpoints from resolveAvailable() (apps/server/src/ws.ts:1819-1821, apps/server/src/ws.ts:3270-3282). A fresh service starts with no cached Serve URL (apps/server/src/environment/DirectEndpoints.ts:131), so a validation that outlasts initial config loading produces directEndpoints: []. The later result becomes another config snapshot (apps/server/src/ws.ts:359-393, apps/server/src/ws.ts:3380-3403). The client consumes both snapshots (packages/client-runtime/src/connection/supervisor.ts:348-370) and persists each changed route list (packages/client-runtime/src/connection/registry.ts:935-959). On a warm service, one failed probe similarly emits a withdrawal; a later successful subscription reports the URL again and loses its former position.

Impact and scope: Impact: P2 - a saved connection preference is lost and the client starts preferring a route the user deliberately moved behind T3 Connect; the user can reorder it again after discovery finishes.

Affected: clients with a learned Tailscale HTTPS route in a custom position, reconnecting after the host server restarts or across a transient Serve self-probe failure. The route itself and its credential are not deleted upstream; the changed client route order is persisted. Explicitly paired routes do not take this removal path because mergeLearnedRoutes keeps routes without learned: true (packages/client-runtime/src/connection/routes.ts:281-288, source-only for that workaround). The shared route code is used by web, desktop, and mobile. NOT_ENOUGH_INFO: frequency on real devices; a client trace across a restart would establish it for a particular install.

Impact

Minor bug or occasional failure

Version or commit

main @ 86ff9d0

Environment

Linux x64, Node.js v26.13.1, repository-pinned Vite+ test runner (Vitest 5.0.5). Tailscale status shape checked against tailscale/tailscale@071bf947 (1.105.0); no Tailscale binary was installed or run.

Logs or stack traces

Relevant lines from the focused test output:

saved order: ["T3 Connect","Tailscale HTTPS"]
fresh initial endpoints: []
fresh completed endpoints: [{"kind":"tailnet","httpBaseUrl":"https://host-a.tailnet-name.ts.net/"}]
order after fresh discovery: ["Tailscale HTTPS","T3 Connect"]
validated endpoints: [{"kind":"tailnet","httpBaseUrl":"https://host-a.tailnet-name.ts.net/"}]
endpoints after one probe timeout: []
order after timeout and recovery: ["Tailscale HTTPS","T3 Connect"]
Test Files  1 passed (1)
Tests  1 passed (1)

Source references at the pinned commit: apps/server/src/environment/DirectEndpoints.ts:131-144 returns only bound addresses until a Serve URL has been validated; apps/server/src/environment/DirectEndpoints.ts:158-168 writes the failed or timed-out result over the cached URL; packages/tailscale/src/tailscale.ts:28 and packages/tailscale/src/tailscale.ts:713-728 bound the HTTPS probe to 2.5 seconds within DirectEndpoints' 3-second total budget; packages/client-runtime/src/connection/routes.ts:288 removes unreported learned routes and packages/client-runtime/src/connection/routes.ts:294-328 inserts a reported URL again through the normal default ranking (packages/client-runtime/src/connection/routes.ts:131-138). Tailscale's matching status fields are defined at tailscale/tailscale@071bf947 ipn/ipnstate/ipnstate.go:32-55, ipn/ipnstate/ipnstate.go:244-255; HTTPS certificate acquisition can wait up to one minute in ipn/ipnlocal/serve.go:1532-1559, although certificate provisioning was not exercised in this reproduction.

Screenshots, recordings, or supporting files

No response

Workaround

See Impact and scope under Actual behavior.

Additional details

  • Interface: Library: server DirectEndpoints, config subscription, and shared client route learning; the user setting is route ordering in Settings → Environments.
  • Earliest failure stage: State or storage

Analysis or suspected cause

Source-based: omission means both "not validated yet" and "no longer available" on the config stream, and the client keeps no position for a learned route once it is omitted. Relearning the identical origin therefore applies the default rank instead of the user's earlier ordering.

References

none found in open and closed issues for the lost route-order preference (searched "learned order", "DirectEndpoints", "Tailscale route order", "learned reconnect", and related PRs). #26775 (closed by #29432) concerns slow initial config delivery; its deferred discovery produces the first-snapshot case here. #24516 (open) concerns replacing a live socket before a better route connects; this report concerns the saved order changing before that decision. #5233 (closed) requested ordered routes, which now exist.


Found by reading T3 Code's Tailscale integration against the Tailscale source (tailscale/tailscale@071bf947, v1.105.0); written up with AI assistance (Claude Code).

Activity

  1. added
    vouch:denounced
    on Nov 13, 2026
  2. maria-rcks commented on Nov 15, 2026

    @maria-rcks
    Collaborator

    Note

    Written by claude-fable-5-2 on behalf of Maria

    Closing: this account is denounced in .github/VOUCHED.td for filing automated issues faster than maintainers can triage them. A fix PR that links this issue is not affected by this close.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    vouch:denounced

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions