Skip to content

fix(platform): route legacy knowledge purges through the live pool and prune dead script paths - #3235

Merged
larryro merged 10 commits into
mainfrom
fix/platform-scripts-shared-cleanup
Sep 6, 2026
Merged

larryro merged 10 commits into
mainfrom
fix/platform-scripts-shared-cleanup

Conversation

@larryro

@larryro larryro commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fix campaign, theme platform-scripts-shared: the legacy knowledge purge/reconcile now routes through the live per-org pool (the second resolver honoured a RAG_DATABASE_URL alias the pool never read, so in the shipped container env purges deleted from an empty twin of the corpus); the phantom legacy.knowledge_delete.deleteDocument handler name and the single-document delete it backed are gone; two dead script paths are deleted (the OpenAI-compat probe with its committed key literal, five @tale/shared export subpaths nothing imports, plus the ai dependency only the probe used); dev-engine registers its signal handlers before any child spawns and tree-kills children on a boot failure; /events/file writes a heartbeat and the session-oracle fetch has a timeout; the integration harness defaults the gateway admin password before the lanes that mint keys and reads JSON with the HTTP status in hand.

Findings fixed

  • platform-scripts-shared-1 — SANDBOX_LLM_GATEWAY_ADMIN_PASSWORD ??= hoisted into main()'s env bootstrap; the reclaim lane keeps only its save/restore (e2bf6b6).
  • platform-scripts-shared-2 — readJson(res, label) next to runLanes; checkReviewArc's happy-path GET/POST chains use it (the deliberate refusal read stays) (e2bf6b6).
  • platform-scripts-shared-3 — scripts/test-openai-compat.ts + README bullet + @ai-sdk/openai-compatible deleted (1446e20); the ai dependency it alone imported dropped with its lock closure (cfa095b).
  • platform-scripts-shared-4 — config/base, config/org-slug, logging/setup, errors, reporter sources, tests, exports and README entries deleted (c2597db).
  • platform-scripts-shared-5 — knowledge_delete.ts takes its Sql from getKnowledgePoolForOrg(orgSlug); own resolver + RAG_DATABASE_URL alias retired in env.sh, docker-entrypoint.sh, dev-secrets.ts; regression test core/legacy/knowledge_delete.test.ts pins that purge and reconcile hit the pool the indexer wrote to, never the alias (df04cc1). The purge-honesty lane now forgets the cached org resolution via invalidateOrgUrl the way domains/knowledge/admin.ts does, since the purge shares the pool's 15 s cache (b3900d3).
  • platform-scripts-shared-6 — legacy block removed from handler_names.ts; deleteKnowledgeDocument, deleteOneDocument and their types deleted (df04cc1).
  • platform-scripts-shared-7 — shutdown defined and SIGINT/SIGTERM registered before docker/backend/Vite bring-up (a7661b9). Observing it with a real SIGTERM 3 s into bring-up showed the backend child dying as intended but the bunx wait-on tcp:127.0.0.1:3005 --timeout 180000 helper from waitForBackend surviving the exit and polling for its full three minutes — runCommand now records its live step child and shutdown() tree-kills it with the backend and Vite (6510a28).
  • platform-scripts-shared-v1 — boot-failure catch routes through shutdown(1), tree-killing both children (a7661b9); with the step helpers killed on a signal, the catch returns when a shutdown is already in flight instead of reporting the killed step's wait-on timeout wording as a boot failure (6510a28).
  • platform-scripts-shared-8 — : ping comment frame every 30 s per SSE client, cleared through one dropSseClient door; /api/sse/auth fetch carries AbortSignal.timeout(5_000); tests pin the cadence, the timer teardown on cancel, and the signal (e26cf29).

Skipped

  • none

Review polish (approve round)

  • knowledge_delete.ts header now says why the 'use node' directive stays (the core/ marker for Node-side I/O, here the postgres pool) (0a12aa2).
  • MIGRATION.md inc 43 line keeps the historical deleteKnowledgeDocument mention and says it was folded into deleteKnowledgeDocumentsBatch in core/legacy/knowledge_delete.ts (0a12aa2).
  • dev-engine SIGTERM/boot-failure behaviour observed (see -7/-v1 above and the probe below); the wait-on orphan it exposed is fixed (6510a28).
  • Not done: sweeping the ~550 other bare .json() sites in integration-check.ts onto readJson — a harness-wide refactor beyond finding -2's scope; the helper is there to adopt as lanes are touched.

Tests & gates observed

  • services/platform: bunx tsc --noEmit exit 0; bunx oxlint --type-aware exit 0 (re-run at 0a12aa2).
  • bunx vitest --run --project server (at 0a12aa2): Test Files 494 passed (494) / Tests 5983 passed (5983).
  • bun run check (worktree root, at 0a12aa2 uncommitted state = same tree): Tasks: 39 successful, 40 total, the one red being @tale/platform#test:ui with two Timed out in waitFor in chat-surface.test.tsx and data-residency-settings.test.tsx (files this PR does not touch); rerun alone with vitest.ui.config.ts: Test Files 2 passed (2) / Tests 64 passed (64) — CPU-load flake. bun run knip:check exit 0 (same pre-existing cron-parser hint).
  • dev-engine probe (script outside the repo: bun scripts/dev.ts with TALE_DEV_SKIP_DOCKER=1 TALE_E2E=1 PORT=3100 BACKEND_PORT=3105, a non-routable DATABASE_URL, TALE_CONFIG_DIR under /tmp): SIGTERM at 3 s with node backend/main.ts and bunx wait-on tcp:127.0.0.1:3105 as live children → before 6510a28 orphansAfter: [wait-on], after it orphansAfter: [], exit: {code: 0, signal: null}, shutdown ≈ 700 ms; boot failure (app port held) → exit: {code: 1}, childrenLeft: [], 616 ms.
  • packages/shared: bun run test → Test Files 22 passed (22) / Tests 205 passed (205).
  • bun run check (worktree root, at cfa095b): exit 0, Tasks: 40 successful, 40 total (platform test 500/500 files, test:ui 455/455, shared 22, ui 124, docs 30, web 22). A first run alongside knip hit one Hook timed out in 10000ms under CPU load; alone it is green.
  • bun run knip:check: exit 0 — one pre-existing configuration hint (cron-parser … Remove from ignoreDependencies, root knip.config.ts l.167), unrelated.
  • Integration proof (run-itest.sh copy WITHOUT SANDBOX_LLM_GATEWAY_ADMIN_PASSWORD exported, with aa3d1d7a9 cherry-picked temporarily and dropped afterwards): [itest] 464/466 checks passed across 133/133 lanes, no truncation. PASS automation agent node … vk=1/1, PASS automation-run tool lane, PASS sandbox teardown revokes the session gateway key — the -1 proof; PASS corpus purge: failed purge keeps the row (honest), retry heals — brokenDelete → 500 (want !ok) … retry → 200. The two reds: webdav re-home (red on main before the campaign) and knowledge: corpus scope drift is corrected and reported — drifted=null (knowledge theme's lane: it picks LIMIT 1 of active docs without an ORDER BY and got one with no corpus row; its path is domains/knowledge/service.ts + pool.ts, untouched here; on main the lane truncates earlier on the jsonb error fix(platform): pass the corpus scope rows as one jsonb parameter #3222 fixes).

Notes for the reviewer

  • The heartbeat lives in server.ts's /events/file handler and keeps the route's shape; if the shared-lib PR retires that SSE door, the heartbeat drops out on rebase with it.
  • integration-check.ts changes are confined to: one ??= line in main(), the readJson helper next to runLanes + checkReviewArc call sites, and two invalidateOrgUrl calls in the purge-honesty step. No lanes moved.
  • RAG_DATABASE_URL was dropped, not renamed: exporting KNOWLEDGE_DATABASE_URL=${POSTGRES_URL}/tale_knowledge in its place would have re-routed the live pool onto the operational db host.
  • bun.lock was regenerated with bun install --lockfile-only (node_modules untouched); the diff is exactly the @ai-sdk/openai-compatible and ai closures.
  • dev-engine's ordering change has no unit test (the orchestrator is side-effect driven); it was exercised with the live SIGTERM probe above. Cosmetic: a Ctrl-C during Starting backend now prints that step's [ x ] Starting backend mark after Shutting down (the killed wait-on rejects the step) — honest "step aborted", exit code stays 0. StepWarning was not used there because it would resolve the step and let the bring-up continue into the Vite spawn during a shutdown.

core/legacy/knowledge_delete.ts carried its own copy of the per-org
knowledge-DB resolver, and that copy honoured a RAG_DATABASE_URL alias the
live pool (core/knowledge/pool.ts) never read. The shipped container env
(env.sh + docker-entrypoint.sh) exported RAG_DATABASE_URL as
${POSTGRES_URL}/tale_knowledge — the operational host — while the indexer
wrote to knowledge-db, so the ref-release purge and the daily reconcile
walked an empty twin of the corpus and reported success with nothing
deleted.

- deleteKnowledgeDocumentsBatch / listKnowledgeDocumentRefs now take their
  Sql from getKnowledgePoolForOrg(orgSlug), the single tenant-routing entry
  point; the private resolver, its SOPS/config readers and the per-call
  postgres()/end() are gone.
- The phantom `legacy.knowledge_delete.deleteDocument` handler name (no shim
  handler, no caller) and the single-document deleteKnowledgeDocument it
  backed are removed; the header now describes the two live release.ts
  callers instead of the Convex calling convention.
- RAG_DATABASE_URL is retired everywhere it was set or read: env.sh,
  docker-entrypoint.sh, dev-secrets.ts (an explicit alias no longer
  suppresses the host-side KNOWLEDGE_DATABASE_URL derivation).

Regression tests: knowledge_delete.test.ts stubs the pool factory and
asserts both the purge and the reconcile walk hit the pool resolved for the
org (default and BYO) and never the alias; dev-secrets.test.ts pins
ensureKnowledgeDatabaseUrl.

Findings: platform-scripts-shared-5, platform-scripts-shared-6.
scripts/test-openai-compat.ts probed /api/v1/models and
/api/v1/chat/completions, routes no 0.5 door serves (rest/, app.ts,
server.ts and every domain routes.ts were searched) — every request it
made could only 404 — and it embedded a credential-shaped API-key literal,
against the secrets-live-in-env boundary. The script was the only importer
of @ai-sdk/openai-compatible, so the dependency goes with it (lockfile
regenerated with `bun install --lockfile-only`), as does the scripts/README
bullet that advertised it as a live utility.

Finding: platform-scripts-shared-3.
@tale/shared exported config/base, config/org-slug, logging/setup, errors
and reporter, but a repo-wide search (every workspace, docs, scripts,
configs — string forms included) finds no importer of any of them; the only
mention was a comment in scripts/dev-output.ts naming the reporter shim.
reporter/index.ts was the `@deprecated … kept for one release` re-export of
tux and had outlived that lifetime. knip cannot flag these because a
package.json exports entry counts as an entry point.

The modules, their exports entries and their README sections are removed;
config/base.ts was the package's only zod importer, so the dependency goes
too (lockfile regenerated with `bun install --lockfile-only`). The README
also still listed config/providers and utils/sops, which had already left
the package — those stale bullets and the intro's RAG/crawler wording are
brought in line with the surviving exports.

Finding: platform-scripts-shared-4.
The SIGINT/SIGTERM handlers were registered only after Vite had spawned,
so a SIGTERM (supervisor or IDE stop) landing during the docker/backend
bring-up killed the orchestrator by default action and left the
`node backend/main.ts` grandchild holding :3005; the next `bun run dev`
then failed at waitForBackend blaming another instance. The outer catch
had the same hole without any signal: a backend still waiting on its
database when waitForBackend gave up outlived the `process.exit(1)`.

Define `shutdown` and register both handlers right after the supervisor
state is set up, before any child spawns (`killProcessTree` already
tolerates a null child), give it an exit code, and route the boot-failure
catch through it so both children are tree-killed before exiting 1.

Findings: platform-scripts-shared-7, platform-scripts-shared-v1.
`/events/file` wrote only the initial connected frame plus watcher events,
although the Bun.serve comment relied on "the stream's own heartbeats" to
keep a client inside `idleTimeout: 255`. Config changes are rare, so a
quiet client was cut every ~255 s; EventSource reconnects, but each cycle
costs a backend auth lookup and drops any change event in the gap. The
session-oracle fetch to `/api/sse/auth` had no timeout, so a hung backend
left every `/events/file` and `/canvas-preview` request pending forever.

Write a `: ping` comment frame every 30 s per client, cleared through one
`dropSseClient` door on cancel and on a failed enqueue; give the oracle
fetch a 5 s `AbortSignal.timeout` (the existing catch turns it into 401).
Tests pin the frame cadence, the timer teardown on cancel, and the signal.

Finding: platform-scripts-shared-8.
`SANDBOX_LLM_GATEWAY_ADMIN_PASSWORD` was defaulted only inside
checkSandboxGatewayKeyReclaim, but checkAutomationAgentNode and
checkAutomationRunToolLane mint gateway keys earlier in the lane order and
`requireGatewayAdminPassword` throws before any network call, so the
documented run recipe failed both lanes' `minted === 1` assertions on a
machine that never exported the variable. Hoist the `??=` into main()'s
env bootstrap; the reclaim lane keeps its save/restore only.

checkReviewArc parsed every response with `.json()` regardless of status,
so a non-JSON error body truncated the run as a bare SyntaxError that hid
the HTTP status and body. Add `readJson(res, label)` next to runLanes —
throws `<label>: HTTP <status> <body excerpt>` on a non-2xx status and
wraps a parse failure with the same context — and route the lane's
happy-path GET/POST chains through it (the deliberate refusal read stays).

Findings: platform-scripts-shared-1, platform-scripts-shared-2.
`scripts/test-openai-compat.ts` was the sole importer of `ai`; deleting
the probe left the dependency declared but unused, which knip flags.
Remove it from services/platform/package.json and let the lockfile drop
its private closure (@ai-sdk/gateway, @ai-sdk/provider-utils,
@vercel/oidc, the nested @opentelemetry/api).

Finding: platform-scripts-shared-3 (follow-through).
The purge-honesty step of checkCorpusPurgeConsistency points the org at a
dead `connection.json` and expects the delete to fail. The legacy purge
re-read that file on every call; now that it routes through
`getKnowledgePoolForOrg` — the same per-org pool the indexer uses, with a
15 s resolution cache — the write alone no longer reaches it, and the
purge succeeded against the real corpus (200, want !ok).

Forget the cached resolution after writing and after removing the file,
the way `domains/knowledge/admin.ts` does when a connection is saved
(`invalidateOrgUrl`). The lane's `corpusPool` handle was captured before
the break and keeps reading the real corpus for its kept/gone assertions.

Finding: platform-scripts-shared-5 (proof follow-through).
Observing the finding-7 fix with a real SIGTERM 3 s into bring-up (backend
spawned, still connecting) showed the backend child dying as intended but
the `bunx wait-on tcp:127.0.0.1:3005 --timeout 180000` helper that
waitForBackend spawns through runCommand surviving the orchestrator and
polling the port for its full three minutes. The same shape applies to the
other step helpers (`docker compose up`, `vite build`) when a signal lands
mid-step.

runCommand now records its live child in a module-level set and drops it
on exit/error; shutdown() tree-kills every recorded step child alongside
the backend and Vite. Because the killed helper rejects its step, the
outer boot-failure catch returns when a shutdown is already in flight
instead of reporting the wait-on timeout wording as a boot failure.

Probe (SIGTERM at 3 s, TALE_DEV_SKIP_DOCKER, isolated ports, non-routable
DATABASE_URL): before, the wait-on pair outlived the exit; after, zero
orphans, exit code 0, shutdown in ~700 ms. Boot failure (port taken)
exits 1 with no children.

Refs platform-scripts-shared-7, platform-scripts-shared-v1.
Review polish on #3235: knowledge_delete.ts kept its `'use node'`
directive after the rewrite but the new header no longer said why — one
line now names it as the core/ marker for Node-side I/O (the postgres
pool here). The inc 43 changelog line in MIGRATION.md still pointed at
`deleteKnowledgeDocument`, which that PR deleted; the historical line
stays and now says where the symbol was folded.
@larryro
larryro merged commit b2945b0 into main Sep 6, 2026
50 checks passed
@larryro
larryro deleted the fix/platform-scripts-shared-cleanup branch September 6, 2026 01:35
larryro added a commit that referenced this pull request Sep 6, 2026
…ession

#3235 gave the purge its pool through getKnowledgePoolForOrg with a double
that answers unsafe/begin; this branch's corpus bootstrap now takes its
advisory lock on sql.reserve(), so the double answers that too — the same
shape pool.test.ts already uses.
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