Repository navigation
fix(platform): route legacy knowledge purges through the live pool and prune dead script paths - #3235
Merged
Merged
Conversation
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.
This was referenced Sep 5, 2026
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.
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.
Summary
Fix campaign, theme
platform-scripts-shared: the legacy knowledge purge/reconcile now routes through the live per-org pool (the second resolver honoured aRAG_DATABASE_URLalias the pool never read, so in the shipped container env purges deleted from an empty twin of the corpus); the phantomlegacy.knowledge_delete.deleteDocumenthandler 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/sharedexport subpaths nothing imports, plus theaidependency only the probe used);dev-engineregisters its signal handlers before any child spawns and tree-kills children on a boot failure;/events/filewrites 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
SANDBOX_LLM_GATEWAY_ADMIN_PASSWORD ??=hoisted intomain()'s env bootstrap; the reclaim lane keeps only its save/restore (e2bf6b6).readJson(res, label)next torunLanes;checkReviewArc's happy-path GET/POST chains use it (the deliberate refusal read stays) (e2bf6b6).scripts/test-openai-compat.ts+ README bullet +@ai-sdk/openai-compatibledeleted (1446e20); theaidependency it alone imported dropped with its lock closure (cfa095b).config/base,config/org-slug,logging/setup,errors,reportersources, tests, exports and README entries deleted (c2597db).knowledge_delete.tstakes itsSqlfromgetKnowledgePoolForOrg(orgSlug); own resolver +RAG_DATABASE_URLalias retired inenv.sh,docker-entrypoint.sh,dev-secrets.ts; regression testcore/legacy/knowledge_delete.test.tspins 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 viainvalidateOrgUrlthe waydomains/knowledge/admin.tsdoes, since the purge shares the pool's 15 s cache (b3900d3).legacyblock removed fromhandler_names.ts;deleteKnowledgeDocument,deleteOneDocumentand their types deleted (df04cc1).shutdowndefined andSIGINT/SIGTERMregistered 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 thebunx wait-on tcp:127.0.0.1:3005 --timeout 180000helper fromwaitForBackendsurviving the exit and polling for its full three minutes —runCommandnow records its live step child andshutdown()tree-kills it with the backend and Vite (6510a28).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).: pingcomment frame every 30 s per SSE client, cleared through onedropSseClientdoor;/api/sse/authfetch carriesAbortSignal.timeout(5_000); tests pin the cadence, the timer teardown on cancel, and the signal (e26cf29).Skipped
Review polish (approve round)
knowledge_delete.tsheader now says why the'use node'directive stays (the core/ marker for Node-side I/O, here the postgres pool) (0a12aa2).MIGRATION.mdinc 43 line keeps the historicaldeleteKnowledgeDocumentmention and says it was folded intodeleteKnowledgeDocumentsBatchincore/legacy/knowledge_delete.ts(0a12aa2)..json()sites inintegration-check.tsontoreadJson— 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 --noEmitexit 0;bunx oxlint --type-awareexit 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:uiwith twoTimed out in waitForinchat-surface.test.tsxanddata-residency-settings.test.tsx(files this PR does not touch); rerun alone withvitest.ui.config.ts:Test Files 2 passed (2)/Tests 64 passed (64)— CPU-load flake.bun run knip:checkexit 0 (same pre-existingcron-parserhint).bun scripts/dev.tswithTALE_DEV_SKIP_DOCKER=1 TALE_E2E=1 PORT=3100 BACKEND_PORT=3105, a non-routableDATABASE_URL,TALE_CONFIG_DIRunder /tmp): SIGTERM at 3 s withnode backend/main.tsandbunx wait-on tcp:127.0.0.1:3105as live children → before 6510a28orphansAfter: [wait-on], after itorphansAfter: [],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 oneHook timed out in 10000msunder CPU load; alone it is green.bun run knip:check: exit 0 — one pre-existing configuration hint (cron-parser … Remove from ignoreDependencies, rootknip.config.tsl.167), unrelated.run-itest.shcopy WITHOUTSANDBOX_LLM_GATEWAY_ADMIN_PASSWORDexported, withaa3d1d7a9cherry-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) andknowledge: corpus scope drift is corrected and reported — drifted=null(knowledge theme's lane: it picksLIMIT 1of active docs without an ORDER BY and got one with no corpus row; its path isdomains/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
server.ts's/events/filehandler 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.tschanges are confined to: one??=line inmain(), thereadJsonhelper next torunLanes+checkReviewArccall sites, and twoinvalidateOrgUrlcalls in the purge-honesty step. No lanes moved.RAG_DATABASE_URLwas dropped, not renamed: exportingKNOWLEDGE_DATABASE_URL=${POSTGRES_URL}/tale_knowledgein its place would have re-routed the live pool onto the operationaldbhost.bun.lockwas regenerated withbun install --lockfile-only(node_modules untouched); the diff is exactly the@ai-sdk/openai-compatibleandaiclosures.Starting backendnow prints that step's[ x ] Starting backendmark afterShutting down(the killed wait-on rejects the step) — honest "step aborted", exit code stays 0.StepWarningwas not used there because it would resolve the step and let the bring-up continue into the Vite spawn during a shutdown.