Repository navigation
fix(platform): repair boot and serving-shell dead-ends - #3132
Merged
Merged
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes the boot/serving-shell dead-end class from the deep review: five verified findings, each with a regression test that fails on main (or a structural guard where the artifact is a Dockerfile).
1. SCIM per-resource ops broken on the advertised /http_api tenant URL (critical)
extractPathPartsslicedprefix.lengthchars without checking the path starts with the prefix. On the advertised alias mount (/http_api/scim/v2, whichapp.ts:171mounts and the proxy forwards path-preserved)/http_api/scim/is exactly as long as/scim/v2/Users/, so every per-resource op parsedid: 'v2'— an IdP configured with the tenant URL the admin UI advertises (getPublicHttpApiUrl()+/scim/v2, alsometa.location) could create/list users but never update, deactivate, or delete them.extractPathPartsnow locates the prefix in the pathname (every prefix starts with/, so a match always sits on a segment boundary) and answers an empty id when absent (backend/core/lib/rest/helpers.ts).rgshows exactly two callers — the SCIM Users/Groups dispatchers. No other module uses the helper.helpers.test.ts); dispatcher-level tests pinning that GET/DELETE on/http_api/scim/v2/Users/:idand/Groups/:idresolve the real id (backend/core/scim/http_actions.test.ts). Verified failing on main: the three alias-mount cases fail, the bare-mount ones pass — exactly the reported asymmetry.2. Backend roles never receive WEBDAV_APP_PASSWORD_HMAC_KEY in containers (high)
The entrypoint's
api|worker|allbranchexecs node (line ~145) before the web lane sourcesenv.shand derives the key fromINSTANCE_SECRET(line ~265) — and the web-tier process (server.ts) doesn't even read the key, while the backend process that needs it (webdav hash/verify, hostcall tokens, sandbox stage tokens — all reading rawprocess.env) never got it.loadEnv()(backend boot) now calls the existingensureWebdavHmacKeyfromlib/webdav/hmac-key.ts— the single derivation, already pinned by test to be byte-identical to the entrypoint's shell sha256. It caches the key onto the boot env so all four lazy readers pick it up; an explicitWEBDAV_APP_PASSWORD_HMAC_KEYstill wins, and noINSTANCE_SECRETleaves behavior exactly as before. No shell duplication; single source of truth kept.web: entrypoint web flow →env.sh→ensure_instance_secret→ shell derivation →bun server.ts(unchanged).api/worker/allcontainers: composeenv_file: .env(the CLI'sensure-env.ts:647writesINSTANCE_SECRET=<64-hex>there) →exec node main.ts→ new:loadEnv()derives the key.scripts/dev-engine.ts/dev-secrets.tsalready callensureWebdavHmacKey(unchanged; the boot call is idempotent).bash -n docker-entrypoint.shclean (script untouched); the compose/env_file wiring was traced by reading, not by running a container.3. Squash stage drops KNOWLEDGE_MIGRATIONS_DIR (high)
The
FROM scratchsquash re-declares the runner's ENV by hand and dropped exactly one var:KNOWLEDGE_MIGRATIONS_DIR.findMigrationsDir's fallback walks for a repo checkout a flat image doesn't have, so BYO-corpus preparation degraded to "apply the migrations yourself" in every shipped image — the exact production bugbackend/MIGRATION.md:127records as fixed "with a guard test" that did not exist.tests/guards/dockerfile-env-parity.guard.test.ts, the promised one): parses the Dockerfile's runner + squash stages and pins the ENV blocks equal name-and-value (any future squash drop fails with the variable named), pins the DDL COPY + both pointer lines, and (follow-up commit) the builder/dev-stage copy + workspace-layout pointer — completing the MIGRATION.md promise. Verified failing on main's Dockerfile.COPY --from=runner / /, so the ENV pointer is the only missing piece.4. Graceful shutdown hangs on open /events streams → SIGKILL (high)
shutdown()awaited a bareserver.close(), which waits for every open connection; SSE responses never end on their own (15s heartbeats, loop exits only on client abort). One connected browser parked shutdown past the orchestrator's grace (compose default 10s,backend-apisets none) → SIGKILL withboss.stop({graceful}),sql.end, and the error flush unreached — in-flight jobs (includingretryLimit-0 sends) died mid-write.realtime/sse.tskeeps a registry of live streams;endAllEventStreams()aborts them (hono'sabort()cancels the response readable, so the connection goes idle immediately and the loop exits on its next tick).backend/http-shutdown.tscloseServerGracefully(): ends the streams, then closes with a periodiccloseIdleConnections()sweep and a 5scloseAllConnections()backstop for connections the registry cannot see (long streaming responses) — well under the 10s SIGKILL so the graceful job stop still runs. The sweep matters:close()reaps idle connections only at the moment it is called, and a connection that goes idle a tick later otherwise lingers until the client's keep-alive timer (observed: undici's 4s) — found empirically while writing the test.main.tsuses the helper.backend/http-shutdown.test.ts, realserve()socket + the real events handler over stubbed sql): (a) the premise — a bareserver.close()does NOT fire within 500ms while one SSE client is connected; (b)closeServerGracefullyresolves well before the force deadline with an open SSE client, and the client observes its stream end; (c) the force backstop closes an unregistered never-ending response at the deadline. (a) pins main's behavior directly; the helper/registry don't exist on main, so the file as a whole also fails there.5. Email-attachment URLs mint the retired /http_api/storage route (high)
buildBlobServeUrl/buildDownloadUrlminted${SITE_URL}${BASE_PATH}/http_api/storage?.... The 0.5 backend mounts no such route and the proxy injects only four/http_apilanes (sso, scim, trusted-headers, cloud-import oauth) — the URL fell through to the SPA catch-all. Every mail-connector attachment stored a dead link (sole live caller:materialize_email_attachments.ts, viasyncMailbox).<img>es; outbound connector sends re-presign fresh per send and never read the stored field — swept every consumer). The live serving contract is a presigned S3 GET minted at open time, which cannot be stored (it expires). So the builder now mints a stable, session + org-membership-gated redirect:GET /api/app/files/serve?orgId&ref&filename→ 302 to a fresh presigned GET (attachment disposition when a filename is given). Reviving the retired unauthenticated/http_api/storagedoor would have required a new proxy lane AND reintroduced a capability-URL surface that outlives conversation access — the gated lane matches how every other/api/appsurface authorizes, and the proxy's existing/api/app/*lane forwards it./serveroute indomains/files/routes.ts(declared before/:fileId);getFileUrlgains an optionalfilename(presign disposition — object keys are nameless<org>/<uuid>by design);buildBlobServeUrlre-pointed (+getPublicAppApiUrl);buildDownloadUrldeleted — its branch was unreachable (0.5'sputOrgBlobBytesalways answerss3:refs) and it had no other importer; the ingest caller now has one lane.public_storage_url.test.tsasserts the minted URL against the REAL router (createAppwith stub deps): the path must reach the mounted lane (the session gate's 401, not Hono's 404), the retired path must stay unmounted, plus param/BASE_PATH shape;materialize_email_attachments.test.tspins the stored URL. Verified failing on main — the route-existence test fails there withexpected 404 to be 401, i.e. the minted URL literally 404s against main's router.reuse_stored_attachmentscarries pointers forward); re-pointing them would be a data backfill over conversation metadata — deliberately out of this PR. New syncs mint working links.Refuted findings
None — all five verified in code before changing anything.
Gates run
bun run --filter @tale/platform typecheck— exit 0.bun run --filter @tale/platform lint(oxlint --type-aware) — exit 0.bash -n services/platform/docker-entrypoint.sh— clean.backend:integration(throwaway tale-db + MinIO perbackend/README.md,ITEST_S3_ENDPOINTon :59001 to leave the dev stack's store untouched) — run becausemain.ts+ app routing were touched: 279/279 checks passed, exit 0 (includes the live/eventsstream +Last-Event-IDreplay checks against the patched handler, and the suite's ownserver.close()teardown).backend/realtime): 10 files / 135 tests passed; lint + typecheck re-run green after the last merge.Verified by reading only (no execution)
env_file/CLI.envpath that deliversINSTANCE_SECRETto backend containers (finding 2).COPY --from=runner / /inheritance argument, finding 3).