← Offstack All Offstack Docs Topic & How-To Guides v15.0.0 · ~14 KB

Startup, Health & Readiness Contract

Startup guarantees covering default loopback binding, selective boots, API Gateway startup, connection handling, health/metrics endpoints, and edition guards.

Two changes to start.py, both made on 2026-11-10. This note records what changed, why, and what the old behaviour cost — the "why" is the part that does not survive in a diff.


1. Readiness failure now exits non-zero

Before

The launcher started every service, then ran a readiness loop:

for name, port in services_info.items():
    if _wait_for_port(port):
        logger.debug(f"{name} ready on port {port}")
    else:
        logger.warning(f"{name} did not become ready on port {port}")

_print_banner(services_info, args)      # unconditional
stop_event.wait()                       # then blocks forever

A service that never came up printed a WARNING and execution continued to the banner. The banner is the signal every consumer keys on — AIH's gateway/simulator_helper.py, the installer payload scripts, and the smoke probe — so a half-boot and a healthy boot were the same bytes on stdout.

Why that mattered

It did not merely weaken a test. It made the failure invisible at the moment it mattered: a supervisor that adopts a running simulator by waiting for the banner would adopt a process whose DynamoDB was dead and then hang on the first request. The only evidence was a log line nobody was reading, indistinguishable from ordinary startup noise.

After

_check_readiness() returns the failing (name, port) pairs; if any exist, main() logs each and returns 1 before printing the banner. __main__ now does sys.exit(main()) — previously it called main() and threw the status away, so the return value would have been cosmetic.

Verified two ways:

not block;

Correction (2026-11-10). This section first claimed the second proof was --dynamodb-port 99999. It was not. An out-of-range port dies inside socket.bind with OverflowError: bind(): port must be 0-65535 before any _start_* handler runs, so the process still exited 1 with no banner — the right outcome via a mechanism the readiness path never touched. Citing it as evidence for fail-closed readiness was wrong. The real proof is the port-ownership case in §4; the out-of-range case now has its own behaviour (§5), which is also why the exit code moved from 1 to 2.

2. The banner and the readiness probe use the BOUND port

Before

services_info was built from the argparse values. With --dynamodb-port 0 the server binds an ephemeral port, but the launcher probed port 0 and printed http://localhost:0.

socket.create_connection(("127.0.0.1", 0)) can never succeed, so port 0 produced a permanent did not become ready warning on every run, and the banner advertised an endpoint nothing listens on. Measured: 23.2 s to banner, two permanent warnings, no usable address.

After

Every entry goes through _bound_port(server, requested), which reads server.server_address[1] and falls back to the requested value only when the server reports nothing usable. The readiness loop and the banner both consume that resolved value.

Measured after the change: banner at 2.0 s, zero warnings, real port 59842.

Why it had to be BOTH

Fixing only the banner leaves readiness probing port 0, and with change #1 that turns every --port 0 run into a non-zero exit — trading a false green for an unusable mode. Fixing only the readiness probe leaves the banner printing 0. The two changes are one change; the tests pin them together (TestEphemeralPortIsProbedAsBound) rather than separately, because the bug was in the composition.

3. Services that were never started are not failures

API Gateway starts only when --lambda-config names a file. Its port is None when it does not start, and None entries are dropped from services_info before the readiness check — otherwise every run without a Lambda config would report a failure for a service the operator never asked for.

What this unblocks

The smoke probe no longer needs fixed free ports or a fail_patterns entry to detect a half-boot: the banner now means what a probe wants it to mean. See SMOKE_PROBE_SPEC.md. Configs that do pin fail_patterns keep working — the string is still emitted by the error path, so it matches harmlessly on a healthy new binary.

It also makes "run two simulators side by side" practical: with every service able to take port 0 and report the port it got, two processes can coexist without pre-arranging a port map. See REPLACING_V1.md for that recipe.

4. The simulator owns its ports (Windows)

The readiness check answers "does something respond on this port". It cannot answer "is that something *us". Those differ on Windows because ThreadingHTTPServer.allow_reuse_address is True, which on Windows permits a second live bind to an already-listening port. Measured 2026-11-10: two ThreadingHTTPServer instances bound the same port and both accepted connections.

Consequence, measured end to end: with a real simulator holding 13160, python start.py --dynamodb-port 13160 printed the banner, logged zero readiness warnings, and blocked — while a different process owned the port. The bind succeeded, the readiness probe answered, and the operator connected to something that was not the simulator.

After

server_base.ExclusiveThreadingHTTPServer sets allow_reuse_address = False on Windows and leaves it True on POSIX, where the flag only means "bind a port held by a peer in TIME_WAIT". Every one of the sixteen servers derives from it.

caught by _start_* → exit 1, no banner.

verified, so the fix does not make a fixed dev port unusable.

out the TIME_WAIT linger.

The same test suite failed immediately after the change for an unrelated and useful reason: one test mocked every _start_* except _start_lambda, and it had been passing only because co-bind let the real server steal port 13000. That is the second time this hazard has hidden a defect.

Migration note: a second simulator on an overlapping default now fails

Anyone who has been running two simulators with overlapping defaults has been relying on co-bind without knowing it — the second process bound the same ports and both answered, so "it worked" only meant requests were split between two processes unpredictably. That is now a startup failure: exit 1, no banner, ERROR Port <n> is already in use.

This is the intended change, but it is a behaviour change, and it surfaces in a place that looks unrelated: a smoke probe or launcher that pins a few ports and leaves the rest on defaults will now fail on whichever default a stale simulator happens to hold. Measured on the machine this was written on, fifteen of the sixteen defaults were occupied by leftover processes.

Two ways to be correct:

SMOKE_PROBE_SPEC.md carries the all-zero form; REPLACING_V1.md §2.6 carries the explicit-offset form.

5. An out-of-range port is a usage error

--dynamodb-port 99999 used to reach socket.bind and die with OverflowError. The exit code was 1 and looked handled, but a supervisor saw a Python traceback rather than the argument it got wrong.

Ports are now validated in argparse (_port()), so the same command prints error: argument --dynamodb-port: port must be 0-65535 (0 = any free port), got 99999 and exits 2 (argparse's usage-error code) before any socket is created. 0 remains valid and means "any free port".

The exit code changed from 1 to 2 deliberately: 2 is "you invoked me wrongly", 1 is "I tried and failed". A supervisor can now tell them apart.

6. Optional services and the two cwd-dependence bugs

Two defects sharing one shape: something assumed a fixed key set or a fixed working directory. Neither is exotic — both fire on the default invocation of a packaged binary.

The banner indexed keys that may legitimately be absent

services_info drops entries for services that never started — API Gateway is optional, started only when a lambda config file exists — and _print_banner indexed services['lambda_port'] unconditionally. Running from a directory without lambda_routes.json therefore printed a traceback instead of a banner:

KeyError: 'lambda_port'   at start.py:366 in _print_banner

The banner now renders from the dict it is given (_BANNER_SERVICES for order, .get() for lookup) and shows (not started) for an absent service. Its output for a full run is byte-identical to before, so a consumer matching the marker or a service line sees no change.

DEFAULT_LAMBDA_CONFIG was resolved against the caller's directory

"./lambda_routes.json" is relative, and start.py does os.path.isfile(args.lambda_config). The same command therefore started API Gateway from a checkout and silently skipped it from anywhere else — which is what made the KeyError above reachable for every user running the packaged exe from its install directory.

The defaults are now anchored through config._sim_home(): the executable's directory when frozen, this module's directory from source. sys.frozen is not the right frozen test for Nuitka — it does not set it; __compiled__ is set instead, so both are checked. This is the same fix, for the same reason, as the .mjs worker resolution in lambda_api/invoker.py.

Updated 2026-11-11 — "the executable's directory" is wrong for PyInstaller onedir. PyInstaller sets sys.frozen but writes its datas to _internal/ beside the exe, so dirname(sys.executable) found none of lambda_routes.json, env.json or table_schemas/. The exe bound all eighteen ports, printed the banner, exited 0 — and API Gateway never started, with No lambda config at ...\dist\offstack\lambda_routes.json as the only trace. _sim_home() now prefers sys._MEIPASS (PyInstaller's pointer to its data directory) for frozen builds, keeping Nuitka's __compiled__.containing_dir first. Order matters: containing_dir, then _MEIPASS, then dirname(executable), then this module's directory.

Behaviour change: a run outside the checkout now starts API Gateway from the checkout's lambda_routes.json where it previously started nothing. To get the old "API Gateway absent" state deliberately, pass an explicit path that does not exist (--lambda-config /nonexistent/routes.json).

Second behaviour change, easy to miss: DEFAULT_ENV_FILE got the same anchoring, so a run from an arbitrary directory now picks up the checkout's env.json instead of silently having none. That file is not inert — the API Gateway's EnvManager loads it and layers it into every handler invocation, re-reading it when its mtime changes. A previous run outside the checkout injected no env.json variables at all; such a run now injects whatever the checkout's file declares.

This is the correct default for the same reason as above, but it is the kind of difference that presents as "works from my shell, not from the installer": two launch directories, two different sets of handler environment variables, no error either way. Pass --env-file explicitly, or an empty path, if a launch must not inherit the checkout's file.

What this does not change

handler, before the banner. That path is unchanged and still distinct from the readiness path.

on it).


7. Current v15.0.0 Contract Updates

While the fail-closed guarantees in §§1–6 remain in force, several startup defaults and runtime behaviors evolved through v15.0.0:


Want a live walkthrough or evaluation setup for Offstack? Message George Vranjesevic or reach out at george@developmentsnapshot.com.