@teamscala/service-boot 0.23.300 → 0.23.302

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -6,7 +6,7 @@
6
6
  },
7
7
  "name": "@teamscala/service-boot",
8
8
  "type": "module",
9
- "version": "0.23.300",
9
+ "version": "0.23.302",
10
10
  "sideEffects": false,
11
11
  "files": [
12
12
  "src"
@@ -882,6 +882,14 @@
882
882
  "types": "./src/resolve-service-context.d.ts",
883
883
  "default": "./src/resolve-service-context.ts"
884
884
  },
885
+ "./resolve-service-port": {
886
+ "types": "./src/resolve-service-port.d.ts",
887
+ "default": "./src/resolve-service-port.ts"
888
+ },
889
+ "./resolve-service-port.ts": {
890
+ "types": "./src/resolve-service-port.d.ts",
891
+ "default": "./src/resolve-service-port.ts"
892
+ },
885
893
  "./resolve-theme-mode": {
886
894
  "types": "./src/resolve-theme-mode.d.ts",
887
895
  "default": "./src/resolve-theme-mode.ts"
@@ -0,0 +1,66 @@
1
+ /**
2
+ * @system service-runtime
3
+ * @status handwritten
4
+ * @edit edit directly
5
+ *
6
+ * Decides which port a service binds, from the two sources that can claim one:
7
+ * the PORT environment variable and the port the registry declares for that
8
+ * service (`service_routing.local_port` for a backend, `service_install.port`
9
+ * for a UI service).
10
+ *
11
+ * This is the resolver for BOTH kinds. It lives in service-boot rather than
12
+ * service-runtime because the UI branch boots from here and may not import
13
+ * upward; keeping one copy is the point, since the second copy is exactly what
14
+ * went wrong (below).
15
+ *
16
+ * The rule, and why it is not "env always wins":
17
+ *
18
+ * Railway injects PORT and healthchecks that exact port, reporting the service
19
+ * unavailable if it listens elsewhere — so where there is NO routing row (a
20
+ * Railway-only backend), the env is the only truth and must win.
21
+ *
22
+ * But a `service_routing` row means this service has a DECLARED port on this
23
+ * host. There, a PORT that disagrees is a polluted launcher environment, never
24
+ * an intention, and obeying it binds someone else's port. That is not a
25
+ * hypothetical: mcp-ai-chat-system booted onto 3021 — session-picker's port —
26
+ * while its own MCP_SERVER_URL still pointed at 8080. Both processes bound 3021,
27
+ * SO_REUSEPORT load-balanced between them, and every symptom appeared somewhere
28
+ * else: a chat loopback that resolved to nothing, tool-description curation
29
+ * failing for every tool and disabling itself via its circuit breaker, RPC calls
30
+ * landing in the wrong service, and 59 restarts. Nothing failed loudly because
31
+ * nothing ever compared the two numbers.
32
+ *
33
+ * So the registry wins wherever it has an opinion, and the disagreement is
34
+ * REPORTED rather than silently resolved — a wrong port that boots cleanly is
35
+ * the expensive shape, because the damage surfaces far from the cause.
36
+ *
37
+ * That reasoning was written for the backend branch and wired only there, so
38
+ * the UI branch kept taking `process.env.PORT` unconditionally — and on
39
+ * 2026-07-31 reproduced the identical incident in the other direction:
40
+ * scala-quiz (kind:ui, declared 5203) inherited a leaked PORT=3021 from the
41
+ * tmux server environment and bound session-picker's port. Half of every RPC
42
+ * to the session daemon was answered by a quiz service with no /rpc routes.
43
+ *
44
+ * A rule enforced on one of two branches is not enforced. Both branches now
45
+ * call this function, and `port-resolution-is-registry-authoritative` fails
46
+ * the push if either stops.
47
+ */
48
+ export interface PortResolution {
49
+ /** The port to bind. */
50
+ port: number;
51
+ /** Which source decided it — for the boot log, so the choice is auditable. */
52
+ source: "env" | "service_routing";
53
+ /** Set when PORT disagreed with the row; the caller logs it. */
54
+ conflict?: {
55
+ envPort: number;
56
+ declaredPort: number;
57
+ };
58
+ }
59
+ /**
60
+ * @param envPort parsed PORT env, or undefined when unset/unparseable
61
+ * @param declaredPort `service_routing.local_port`, or undefined when the
62
+ * service has no routing row (the Railway-only case)
63
+ */
64
+ export declare function resolveServicePort(envPort: number | undefined, declaredPort: number | undefined): PortResolution | {
65
+ error: "no-port-source";
66
+ };
@@ -0,0 +1,98 @@
1
+ /**
2
+ * @system service-boot
3
+ * @status handwritten
4
+ * @edit edit directly
5
+ *
6
+ * The load-bearing case is the contradiction one: a PORT env that disagrees
7
+ * with the service's own declared port must NOT be obeyed. Obeying it put
8
+ * mcp-ai-chat-system on session-picker's port with a loopback pointing at a
9
+ * port nothing was listening on, and the failure surfaced as broken tool
10
+ * curation rather than as a port problem. It then did it again on 2026-07-31
11
+ * to scala-quiz — see the kind:ui block below.
12
+ */
13
+
14
+ import { describe, expect, test } from "bun:test";
15
+ import { resolveServicePort } from "./resolve-service-port.ts";
16
+
17
+ /** Narrow off the error arm so a resolution's port can be asserted directly. */
18
+ function resolvedPort(envPort: number | undefined, declaredPort: number | undefined): number {
19
+ const r = resolveServicePort(envPort, declaredPort);
20
+ if ("error" in r) throw new Error(`expected a resolution, got ${r.error}`);
21
+ return r.port;
22
+ }
23
+
24
+ describe("resolveServicePort", () => {
25
+ test("no routing row: Railway's injected PORT wins", () => {
26
+ // A Railway-only backend legitimately has no dev routing row, and Railway
27
+ // healthchecks the exact port it injected.
28
+ expect(resolveServicePort(8080, undefined)).toEqual({ port: 8080, source: "env" });
29
+ });
30
+
31
+ test("no routing row and no usable PORT is an error, not a guess", () => {
32
+ expect(resolveServicePort(undefined, undefined)).toEqual({ error: "no-port-source" });
33
+ });
34
+
35
+ test("routing row with no PORT env: the row wins", () => {
36
+ expect(resolveServicePort(undefined, 3021)).toEqual({ port: 3021, source: "service_routing" });
37
+ });
38
+
39
+ test("routing row and an agreeing PORT: no conflict reported", () => {
40
+ const r = resolveServicePort(3021, 3021);
41
+ expect(r).toEqual({ port: 3021, source: "service_routing" });
42
+ expect("conflict" in r).toBe(false);
43
+ });
44
+
45
+ test("a PORT contradicting the routing row is REFUSED and reported", () => {
46
+ // The exact incident: env said 3021 (session-picker's port), the row said
47
+ // 8080. Obeying the env bound another service's port.
48
+ expect(resolveServicePort(3021, 8080)).toEqual({
49
+ port: 8080,
50
+ source: "service_routing",
51
+ conflict: { envPort: 3021, declaredPort: 8080 },
52
+ });
53
+ });
54
+
55
+ test("an unparseable or out-of-range PORT never displaces a valid row", () => {
56
+ expect(resolvedPort(Number.NaN, 3021)).toBe(3021);
57
+ expect(resolvedPort(0, 3021)).toBe(3021);
58
+ expect(resolvedPort(70_000, 3021)).toBe(3021);
59
+ });
60
+
61
+ test("an out-of-range PORT with no row is an error rather than a bad bind", () => {
62
+ expect(resolveServicePort(70_000, undefined)).toEqual({ error: "no-port-source" });
63
+ });
64
+
65
+ // The UI branch reaches this same function via `service_install.port`. These
66
+ // cases are the 2026-07-31 incident, which the backend-only wiring missed.
67
+ describe("kind:ui services (declared port from service_install)", () => {
68
+ test("the live bug: a leaked PORT cannot move a UI service off its declared port", () => {
69
+ // scala-quiz declares 5203; PORT=3021 leaked in from the tmux server
70
+ // env and it bound session-picker's port, splitting that daemon's
71
+ // traffic via SO_REUSEPORT.
72
+ expect(resolveServicePort(3021, 5203)).toEqual({
73
+ port: 5203,
74
+ source: "service_routing",
75
+ conflict: { envPort: 3021, declaredPort: 5203 },
76
+ });
77
+ });
78
+
79
+ test("the conflict is reported, not swallowed — the boot log must be able to say so", () => {
80
+ const r = resolveServicePort(3021, 5203);
81
+ expect("error" in r).toBe(false);
82
+ if ("error" in r) return;
83
+ expect(r.conflict).toBeDefined();
84
+ expect(r.conflict?.envPort).toBe(3021);
85
+ });
86
+
87
+ test("Railway is unaffected: no declared port means the injected PORT still wins", () => {
88
+ expect(resolveServicePort(8080, undefined)).toEqual({ port: 8080, source: "env" });
89
+ });
90
+
91
+ test("an agreeing PORT reports no conflict", () => {
92
+ expect(resolveServicePort(5203, 5203)).toEqual({
93
+ port: 5203,
94
+ source: "service_routing",
95
+ });
96
+ });
97
+ });
98
+ });
@@ -0,0 +1,90 @@
1
+ /**
2
+ * @system service-runtime
3
+ * @status handwritten
4
+ * @edit edit directly
5
+ *
6
+ * Decides which port a service binds, from the two sources that can claim one:
7
+ * the PORT environment variable and the port the registry declares for that
8
+ * service (`service_routing.local_port` for a backend, `service_install.port`
9
+ * for a UI service).
10
+ *
11
+ * This is the resolver for BOTH kinds. It lives in service-boot rather than
12
+ * service-runtime because the UI branch boots from here and may not import
13
+ * upward; keeping one copy is the point, since the second copy is exactly what
14
+ * went wrong (below).
15
+ *
16
+ * The rule, and why it is not "env always wins":
17
+ *
18
+ * Railway injects PORT and healthchecks that exact port, reporting the service
19
+ * unavailable if it listens elsewhere — so where there is NO routing row (a
20
+ * Railway-only backend), the env is the only truth and must win.
21
+ *
22
+ * But a `service_routing` row means this service has a DECLARED port on this
23
+ * host. There, a PORT that disagrees is a polluted launcher environment, never
24
+ * an intention, and obeying it binds someone else's port. That is not a
25
+ * hypothetical: mcp-ai-chat-system booted onto 3021 — session-picker's port —
26
+ * while its own MCP_SERVER_URL still pointed at 8080. Both processes bound 3021,
27
+ * SO_REUSEPORT load-balanced between them, and every symptom appeared somewhere
28
+ * else: a chat loopback that resolved to nothing, tool-description curation
29
+ * failing for every tool and disabling itself via its circuit breaker, RPC calls
30
+ * landing in the wrong service, and 59 restarts. Nothing failed loudly because
31
+ * nothing ever compared the two numbers.
32
+ *
33
+ * So the registry wins wherever it has an opinion, and the disagreement is
34
+ * REPORTED rather than silently resolved — a wrong port that boots cleanly is
35
+ * the expensive shape, because the damage surfaces far from the cause.
36
+ *
37
+ * That reasoning was written for the backend branch and wired only there, so
38
+ * the UI branch kept taking `process.env.PORT` unconditionally — and on
39
+ * 2026-07-31 reproduced the identical incident in the other direction:
40
+ * scala-quiz (kind:ui, declared 5203) inherited a leaked PORT=3021 from the
41
+ * tmux server environment and bound session-picker's port. Half of every RPC
42
+ * to the session daemon was answered by a quiz service with no /rpc routes.
43
+ *
44
+ * A rule enforced on one of two branches is not enforced. Both branches now
45
+ * call this function, and `port-resolution-is-registry-authoritative` fails
46
+ * the push if either stops.
47
+ */
48
+
49
+ export interface PortResolution {
50
+ /** The port to bind. */
51
+ port: number;
52
+ /** Which source decided it — for the boot log, so the choice is auditable. */
53
+ source: "env" | "service_routing";
54
+ /** Set when PORT disagreed with the row; the caller logs it. */
55
+ conflict?: { envPort: number; declaredPort: number };
56
+ }
57
+
58
+ function isBindablePort(value: number | undefined): value is number {
59
+ return value !== undefined && Number.isFinite(value) && value > 0 && value <= 65535;
60
+ }
61
+
62
+ /**
63
+ * @param envPort parsed PORT env, or undefined when unset/unparseable
64
+ * @param declaredPort `service_routing.local_port`, or undefined when the
65
+ * service has no routing row (the Railway-only case)
66
+ */
67
+ export function resolveServicePort(
68
+ envPort: number | undefined,
69
+ declaredPort: number | undefined,
70
+ ): PortResolution | { error: "no-port-source" } {
71
+ const envUsable = isBindablePort(envPort);
72
+ const declaredUsable = isBindablePort(declaredPort);
73
+
74
+ // No routing row: Railway's injected PORT is the only truth available.
75
+ if (!declaredUsable) {
76
+ return envUsable ? { port: envPort, source: "env" } : { error: "no-port-source" };
77
+ }
78
+
79
+ // Routing row present and the env agrees (or is absent) — nothing to resolve.
80
+ if (!envUsable || envPort === declaredPort) {
81
+ return { port: declaredPort, source: "service_routing" };
82
+ }
83
+
84
+ // Routing row present and the env contradicts it: the row wins, loudly.
85
+ return {
86
+ port: declaredPort,
87
+ source: "service_routing",
88
+ conflict: { envPort, declaredPort },
89
+ };
90
+ }
@@ -66,7 +66,24 @@ function serveStartInternal(
66
66
  ): ServeHandle {
67
67
  const server = Bun.serve({
68
68
  port: options.port,
69
- reusePort: true,
69
+ // reusePort is deliberately NOT set. SO_REUSEPORT lets a second process
70
+ // bind a port this service already owns; the kernel then load-balances
71
+ // between them and BOTH look healthy while each receives a fraction of
72
+ // the traffic. That is the worst available failure mode — it presents as
73
+ // intermittent, unattributable errors in whichever service is unlucky,
74
+ // far from the process that actually took the port.
75
+ //
76
+ // It has now cost two incidents. mcp-ai-chat-system bound session-picker's
77
+ // 3021 and broke tool curation; scala-quiz did the same on 2026-07-31 and
78
+ // answered ~half of every session-daemon RPC with a 404. Neither failed at
79
+ // bind, because reusePort made a collision legal.
80
+ //
81
+ // Nothing here needs it: PM2 fork mode stops before it starts, dev runs one
82
+ // process per service (`readiness-gated-boot` — the boot window is handled
83
+ // by the in-process readiness gate, explicitly not blue/green), and each
84
+ // Railway container is alone. So the only thing reusePort can express on
85
+ // this platform is a mistake, and without it that mistake is an immediate,
86
+ // legible EADDRINUSE naming the port.
70
87
  // Bun's default idleTimeout (~10s, swept on a coarse timer wheel)
71
88
  // FIN-closes every pending connection in one ~2ms sweep once their
72
89
  // handlers exceed it — packet-captured 2026-06-06: concurrent SSR
package/src/ui-service.ts CHANGED
@@ -14,6 +14,7 @@ import { BootFatalError } from "@teamscala/os/errors/boot-error";
14
14
  import { Hono } from "hono";
15
15
  import type { ServiceInstallConfig } from "./load-service-install-row.ts";
16
16
  import { setReady } from "./readiness-gate.ts";
17
+ import { resolveServicePort } from "./resolve-service-port.ts";
17
18
  import { serveStart } from "./serve/serve";
18
19
  import { buildMinimalApp, buildFullApp, swapToFullApp } from "./two-phase-boot.ts";
19
20
 
@@ -66,12 +67,43 @@ export async function bootUiService(
66
67
  // Phase 1: Build minimal tool-only app
67
68
  const minimalAppResult = await buildMinimalApp(config, serviceSlug, databaseUrl);
68
69
 
69
- // Get port from config
70
+ // Resolve the listen port through the SHARED resolver (`resolveServicePort`),
71
+ // the same one the backend branch uses. The registry wins wherever it has an
72
+ // opinion and a contradicting PORT env is reported, never silently obeyed —
73
+ // full reasoning in that file.
74
+ //
75
+ // This branch previously took `process.env.PORT` unconditionally, which is
76
+ // how scala-quiz (declared 5203) booted onto session-picker's 3021 from a
77
+ // leaked env and silently split that daemon's traffic (2026-07-31). Railway
78
+ // is unaffected by construction: it injects PORT and a Railway-only service
79
+ // has no declared port, so the env still wins there.
70
80
  const envPort = process.env.PORT ? Number(process.env.PORT) : undefined;
71
- const port = requireValidPort(
72
- envPort && Number.isFinite(envPort) && envPort > 0 ? envPort : config.port,
73
- serviceSlug,
74
- );
81
+ // The APP binds its PRIVATE port (app_port) when present — for scale-to-zero
82
+ // services `port` is the ACTIVATOR's ingress (what callers resolve), not the
83
+ // app's bind. Falling back to `port` keeps RESIDENT + unmigrated services
84
+ // unchanged. Without this, a migrated row (port=activator) would make the app
85
+ // bind the activator's port → SO_REUSEPORT silent load-balancing (the
86
+ // service-ports-from-registry trap: clean boot, two owners in ss -ltnp).
87
+ const declaredAppPort = config.app_port ?? config.port;
88
+ const resolution = resolveServicePort(envPort, declaredAppPort);
89
+ if ("error" in resolution) {
90
+ throw new BootFatalError(
91
+ "ui-service.port-resolution",
92
+ serviceSlug,
93
+ `No port source: service_install declares no port and no valid PORT env is set. ` +
94
+ `Every UI service requires a port in its service_install row (or a PORT env when Railway-deployed).`,
95
+ );
96
+ }
97
+ if (resolution.conflict) {
98
+ log.warn(
99
+ `[ui-service-boot:${serviceSlug}] PORT env (${resolution.conflict.envPort}) contradicts its ` +
100
+ `service_install row (${resolution.conflict.declaredPort}) — using ` +
101
+ `${resolution.conflict.declaredPort}. A stale PORT in this service's launcher ` +
102
+ `environment is a polluted launcher env, never an intention; binding the env port ` +
103
+ `would take another service's port.`,
104
+ );
105
+ }
106
+ const port = requireValidPort(resolution.port, serviceSlug);
75
107
 
76
108
  // Start serving with the minimal app (useMutableRef=true)
77
109
  try {