From b33a61e35af294855a5c09717d77bd699d6d6c4b Mon Sep 17 00:00:00 2001 From: Patty Chow <91703531+patty-chow@users.noreply.github.com> Date: Sun, 18 Oct 2026 21:36:45 -0700 Subject: [PATCH 1/3] Prepare bundled semantic search automatically on Codespaces start --- .azure/deployment-plan.md | 24 +++++ .devcontainer/devcontainer.json | 2 +- .devcontainer/organizer/devcontainer.json | 2 +- README.md | 54 ++++++++++-- compose.search.yaml | 5 +- docs/acceptance.md | 66 ++++++++++++++ docs/instructor.md | 15 +++- docs/lab.md | 6 +- docs/local.md | 11 ++- docs/organizer.md | 17 +++- docs/semantic-search.md | 103 +++++++++++++++++----- package.json | 1 + scripts/codespace-start.mjs | 45 ++++++++++ scripts/search-prepare.mjs | 94 +++++++++++++------- scripts/workspace-lock.mjs | 25 ++++++ test/codespace-start.test.js | 102 +++++++++++++++++++++ test/search-prepare-interruption.test.js | 72 ++++++++++++--- test/search-prepare.test.js | 76 ++++++++++++++-- test/workspace.test.js | 2 +- 19 files changed, 635 insertions(+), 87 deletions(-) create mode 100644 scripts/codespace-start.mjs create mode 100644 scripts/workspace-lock.mjs create mode 100644 test/codespace-start.test.js diff --git a/.azure/deployment-plan.md b/.azure/deployment-plan.md index e6d4a5a..dab7ab9 100644 --- a/.azure/deployment-plan.md +++ b/.azure/deployment-plan.md @@ -82,3 +82,27 @@ Still requiring environment-specific acceptance (not replaced by those receipts) No unattended cleanup worker, cloud IAM grants, Kubernetes dependency, background sync, Azure app hosting or new cloud resources are introduced by this plan. + + +## Automatic local search startup boundary + +Both Codespaces profiles use `npm run codespace:start`: normal two-site startup +and seeding first, then automatic bundled search preparation for local Site A/B. +This does not authenticate, provision or seed Azure, require a paid AI key, or +change any exercise. Attendees can begin at CORE READY while first-use downloads +finish (~274 MB model plus ~455 MB amd64 runtime). Refresh at SEARCH READY. +Verified cached resumes reuse the pinned model/bundle without a model-registry +request or downloader start; a missing runtime Docker image may still be pulled. + +Normal `npm ci`, laptop startup and `npm run workspace:start` stay core-only. +`WORKSHOP_AUTO_SEARCH=0` in the lifecycle environment opts out (selected profile +`containerEnv` for persistence, not private `.env`). Older Codespaces require one +reviewed manual `git pull --ff-only` and `npm run codespace:start`; lifecycle never +runs Git or overwrites attendee edits. No destructive rebuild is needed to run the +new command with existing tools. Search-only failure warns without blocking core; +unsafe downloader cleanup and cancellation stay nonzero. See the +[search lifecycle and recovery guide](../docs/semantic-search.md). + +The prior 17-second cached manual preparation is not a cold/new automatic-start +measurement. Fresh lifecycle/Codespaces proof must be recorded separately from +offline orchestration/cleanup tests and historical model/vector acceptance. diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index 85dac9e..dcf1325 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -28,7 +28,7 @@ }, "onCreateCommand": "npm ci --ignore-scripts --no-audit --no-fund", "postCreateCommand": "npm run setup", - "postStartCommand": "npm run workspace:start", + "postStartCommand": "npm run codespace:start", "customizations": { "vscode": { "extensions": [ diff --git a/.devcontainer/organizer/devcontainer.json b/.devcontainer/organizer/devcontainer.json index 54fe1f5..6c60fbe 100644 --- a/.devcontainer/organizer/devcontainer.json +++ b/.devcontainer/organizer/devcontainer.json @@ -32,7 +32,7 @@ }, "onCreateCommand": "npm ci --ignore-scripts --no-audit --no-fund", "postCreateCommand": "npm run setup && npm run organizer:check", - "postStartCommand": "npm run workspace:start", + "postStartCommand": "npm run codespace:start", "customizations": { "vscode": { "extensions": [ diff --git a/README.md b/README.md index e820125..131df94 100644 --- a/README.md +++ b/README.md @@ -40,12 +40,19 @@ cross-listings, unresolved disagreements, and the excluded invalid break time. 1. [Open the workshop in Codespaces](https://codespaces.new/documentdb/ato-2026-workshop). Choose **ATO 2026 - Attendee** if prompted. -2. Wait for setup to finish. It installs dependencies, generates independent +2. Wait for core setup to finish. It installs dependencies, generates independent private development credentials, starts both databases and the app, waits for each database, and seeds the same catalog in both. It does not copy favorites. + Then it automatically prepares **Search by meaning** for both local sites. + First use downloads a ~274 MB query model plus the pinned runtime (~455 MB on + amd64) and can take minutes; cached resumes verify/reuse the model and bundle. + No Azure connection or paid AI key is needed. 3. When the terminal says **Site A and Site B are ready and both catalogs are seeded**, select **Ports** beside Terminal in the editor's bottom panel. Find row **3000** and use **Open in Browser** (globe). Keep visibility **Private**. + You can begin the core exercises while search preparation finishes. The app + briefly restarts to enable search; when **SEARCH READY** appears, refresh the + planner, then use **Search by meaning** / **Check search readiness**. 4. Run `npm run extension:connections`, then follow the [private connection steps](docs/extension.md#connect-the-two-existing-sites-privately) to save **Workshop — Site A** and **Workshop — Site B** in the DocumentDB @@ -81,7 +88,21 @@ Two databases need more memory/storage than the earlier single-site version; preflight cold creation on the chosen Codespaces machine before class. Helpers should triage at minute 12, not spend the workshop installing Docker on laptops. -Retry a failed setup after reading and resolving the error: +Retry a failed Codespaces setup after reading and resolving the error: + +```sh +npm run codespace:start +``` + +It runs core setup first, then prepares the built-in search showcase. Search-only +failure prints **unavailable** and a retry command without stopping the core app +or databases. Cancellation and an unverifiable downloader cleanup are nonzero +errors; follow the [scoped recovery guide](docs/semantic-search.md#interruptions-and-emergency-downloader-recovery). +To skip automatic search for one run: `WORKSHOP_AUTO_SEARCH=0 npm run codespace:start`. +For a persistent opt-out, set `WORKSHOP_AUTO_SEARCH` to `"0"` in the selected +profile's `containerEnv` and rebuild, or use an equivalent Codespaces environment +setting. This is a **host lifecycle environment variable**, not a private `.env` +setting. The standalone laptop/core-only fallback remains: ```sh npm run workspace:start @@ -95,6 +116,16 @@ if they remain in an older `.env`. No Azure login, provisioning, or seed occurs. ### Existing notebook or older practice version? +Startup **never runs Git operations**: a new Codespace clones the selected branch; +a resumed one keeps its checkout and your exercise edits. It does not automatically +receive this new lifecycle from upstream. For an existing older Codespace, review +and preserve your changes, manually run **`git pull --ff-only` once** on the intended +branch (ask a helper if it refuses; do not reset/stash/overwrite exercises), then +run **`npm run codespace:start`**. Already-running environments with the existing +CLI tools need no destructive/full rebuild to prepare search now. Fresh or rebuilt +configurations use the new `postStartCommand` on future starts; until that config +is applied, run the new command explicitly on resumes. + Keep the same checkout directory and Compose project name to retain the existing `documentdb-data` volume: it is still **Site A**. Site B gets a new, separate `documentdb-site-b-data` volume. Changing directories/project names selects other @@ -131,25 +162,32 @@ API**—over the same public title/track metadata. The catalog has no abstracts, rankings are suggestions, not confidence claims. Keyword search stays separate; missing models or indexes never trigger a hidden keyword/static fallback. -This is **not another lab exercise** and is disabled during ordinary startup. -Outside the 105-minute lab, after both sites are seeded, explicitly enable it: +This is **not another lab exercise**: both Codespaces profiles now prepare it +**automatically after core startup**, without solving or adding TODOs. No manual +search setup is required on a fresh/current-config Codespace. Laptop setup, +`npm ci` and `npm run workspace:start` remain core-only. For a search-only retry, +or to opt in on a laptop after both sites are seeded: ```sh npm run search:prepare -- --local-sites ``` -This downloads a pinned ~274 MB embedding model once for arbitrary live queries, +On a cache miss this downloads a pinned ~274 MB embedding model once for arbitrary live queries, starts an internal-only CPU service, and **imports the same checked-in ~716 KiB session-vector bundle** into both existing local sites before building each real DocumentDB vector index. Attendee preparation makes **zero document-embedding calls**; these are precomputed embeddings, not canned search results. -In the tested two-core Codespace, full optional preparation with the model/image +A **prior manual-preparation revision** in a two-core Codespace with the model/image already cached took **17 seconds**, including about **1.8 seconds per site** for -import/index/verification. First-time model downloads add time; see the +import/index/verification. That is not a measurement of this automatic lifecycle +or first-time setup. Cached preparation now checks the full pinned manifest hash, +bounded size and model availability locally, without contacting the model registry +or starting the downloader. A missing Docker runtime image may still be pulled. +First-time model downloads add time; see the [measured acceptance and limits](docs/semantic-search.md#codespace-and-browser-acceptance-october-18-2026). It does not change catalog documents or favorites, provision Azure, or replace your TODO code. See [optional search setup, limits, model/runtime tradeoffs and -verification](docs/semantic-search.md) before enabling it on a classroom machine. +verification](docs/semantic-search.md) for resource limits, opt-out and recovery. ## Complete reference and recovery diff --git a/compose.search.yaml b/compose.search.yaml index e86d644..6e74e94 100644 --- a/compose.search.yaml +++ b/compose.search.yaml @@ -1,4 +1,5 @@ -# Optional showcase only. Normal workspace:start never loads this overlay/model. +# Built-in showcase: Codespaces prepares it automatically after core startup. +# Normal workspace:start never loads this overlay/model. # This bounded, multi-platform official runtime is deliberately CPU-only at runtime. # See docs/semantic-search.md for the image-size tradeoff and model license. x-search-runtime: &search-runtime @@ -51,7 +52,7 @@ services: profiles: [search-download] networks: - default - # Runs only while the explicit preparation command downloads the model. + # Runs only on a cache miss during automatic or manual preparation. # No query traffic is sent here. Stopped in the preparation command's finally. networks: diff --git a/docs/acceptance.md b/docs/acceptance.md index d2dbeb6..20261d3 100644 --- a/docs/acceptance.md +++ b/docs/acceptance.md @@ -1,5 +1,71 @@ # Acceptance record and remaining gates +## Automatic Codespaces search startup — October 18, 2026 + +This revision adds automatic search preparation after normal core startup to both +Codespaces profiles. It builds on bundled-search main +`1b98ea4d246482b307cd1f59903f8b94ab18ca4c`; it does not change the search UI, vector +store, checked-in bundle, model/runtime pins, exercise files or Azure boundaries. +The older Codespace timings below and the prior **17.07-second cached manual** +search measurement are not measurements of this new lifecycle. + +### Executed on an isolated local stack + +- macOS arm64 host, Docker **2 CPUs / approximately 4 GiB RAM**, new project + `ato-auto-search-verify-20261018`, loopback app **8786** and database extension + ports **10272/10273**. New independent private credentials, database volumes, + model volume and runner volume; no other project's settings/data were adopted. + Existing pinned Docker images were cached. No Codespace or Azure resource was + changed, and no heavyweight replacement runtime was downloaded. +- Actual `npm run codespace:start` with **empty model/runner volumes** completed + in **55.72 seconds**. Core readiness appeared first; optional preparation took + **45.19 seconds**, including bounded cold read-only runner fallback, first + model download and verified downloader shutdown. Site A/B imported all **216** + bundled vectors in **2.290 / 2.269 seconds**, with zero document embeddings and + real hash/index/full-corpus cosine-query verification. This is not a cold Docker + image download or fresh Codespace measurement. +- A repeat of the automatic lifecycle with **host model-registry fetch forbidden** + completed in **13.49 seconds** (search phase **6.70 seconds**). It reported + `cached: true`, **0 external fetch calls**, and reused both real search collections + with full integrity/index/query probes (**157 / 165 ms**). The stopped downloader's + `StartedAt` and `FinishedAt` were exactly unchanged. The cache's actual manifest + passed the full SHA-256 pin and size check, followed by real `ollama show`. +- Actual inference inspection: read-only root filesystem and both model/runner + mounts; **no published ports**; only the Docker network marked `internal: true`. +- Real model/DocumentDB search integration **1/1 passed**; ordinary independent + two-site database/HTTP/aggregation integration **2/2 passed**. These suites use + and remove only their uniquely named test databases, not attendee notebooks. +- With an **injected cache miss plus simulated model-registry failure**, the real + automatic lifecycle returned **0 with `core: ready, search: unavailable`**, not + a search-ready claim. No model-cache files were altered. In command-scoped + complete-reference mode, actual core health/state endpoints remained **200** + with **216 sessions**; exercise source and private configuration were unchanged. + This is failure injection, not an observed internet outage. +- Live `WORKSHOP_AUTO_SEARCH=0 npm run codespace:start` and a subsequent cached + manual `search:prepare -- --local-sites` retry were also checked. No credential + rotation or exercise edits; all owned services are stopped after verification, + with their isolated volumes retained for reviewed retesting. + +### Offline verification and limits + +After `npm ci --ignore-scripts --no-audit --no-fund`, host `npm test` passed +**181 tests, 0 failures, 1 Linux-only skip** (182 total). Tests cover both profile +hooks, core-before-search ordering, opt-out, safe optional failures, hard cleanup +errors, cache digest/size/missing-blob/runner cases, zero external fetch/downloader +startup on a hit, bounded readiness, shared lock exclusion/release and no Git/Azure +lifecycle commands. Real OS subprocess tests deliver SIGINT/SIGTERM to whole +process groups during core startup and model preparation, including a second +signal during cleanup; cancellation stays nonzero and indexing never starts. +Existing search/bundle/UI regression tests remain unchanged. These signal tests +use fake Docker/registry services, not a live-container interruption claim for +this revision. Documentation links are checked offline. + +**Still pending:** actual new/rebuilt Attendee and Organizer Codespace lifecycle +proof on this revision, a cold runtime-image download on representative networks, +and human classroom timing. Local timings and historical GUI/search acceptance +do not replace those gates. See the [automatic startup/recovery guide](semantic-search.md) +for old-checkout updates, environment opt-out, cache receipts and scoped cleanup. + ## Extension-integrated revision — live GUI acceptance **Core fresh attendee GUI acceptance passed October 18, 2026.** A new two-core diff --git a/docs/instructor.md b/docs/instructor.md index 68af809..ef925a1 100644 --- a/docs/instructor.md +++ b/docs/instructor.md @@ -58,7 +58,20 @@ It does not authenticate to or seed Azure. A failed Site B wait/seed is a failed setup, not silent success with one working site. An older Azure URI in `.env` is not passed into the attendee app. Keep secrets out of logs/screenshots. -Both dev-container configurations start this simulation; the Organizer profile's +Both dev-container configurations now run `npm run codespace:start`: core startup +above first, then automatic built-in search preparation for both sites. At **CORE +READY**, begin the existing exercises while first-use model/runtime downloads +finish (~274 MB model plus ~455 MB amd64 runtime; potentially minutes). At **SEARCH +READY**, refresh the planner after its brief app restart. This adds no TODO or +classroom step. A verified cached resume skips registry access/downloader startup; +no first-start timing claim follows from the previous 17-second cached manual run. +Search-only unavailability must not block the core lab; retry +`npm run search:prepare -- --local-sites` or use +`WORKSHOP_AUTO_SEARCH=0 npm run codespace:start`. Persistent `containerEnv` opt-out, +older-checkout manual update and nonzero cleanup-error recovery are in the +[search guide](semantic-search.md). Re-measure cold startup on the delivery revision. + +Both dev-container configurations start only this simulation; the Organizer profile's Azure tooling is optional and does not confer permissions. The browser editor supports the TODOs. The complete-reference override preserves exercises and data. Optional GitHub CLI/SSH diagnostics are helper tools, not attendee prerequisites. diff --git a/docs/lab.md b/docs/lab.md index f455f30..72156c7 100644 --- a/docs/lab.md +++ b/docs/lab.md @@ -35,7 +35,11 @@ hints. Keep the guide and your private planner open in separate tabs. If account policy or quota blocks startup, tell a helper early for pairing or follow-along. Do not share logins, expose public ports, or install Docker during -the timed lab. Retry a diagnosed setup failure with `npm run workspace:start`. +the timed lab. Retry a diagnosed setup failure with `npm run codespace:start`. +At **CORE READY**, begin these exercises while the built-in search showcase +prepares automatically. At **SEARCH READY**, refresh the planner. Search adds no +TODO; if it is unavailable, continue the core lab. `npm run workspace:start` remains +the core-only fallback. See the [search guide](semantic-search.md) for retry/opt-out. Check the active label: **Site A — self-hosted**. The implementation label should say **Exercise implementation (your editable code)**. This labels the selected diff --git a/docs/local.md b/docs/local.md index 8ffe69e..4fb3ac2 100644 --- a/docs/local.md +++ b/docs/local.md @@ -4,7 +4,16 @@ The attendee workshop is browser-first. Use this appendix only if Docker already works on your laptop; do not spend the timed workshop installing/repairing it. You need Docker with Linux containers, Docker Compose, a browser, and VS Code with the official `ms-azuretools.vscode-documentdb` extension (guide: version 1.0.0). -No host Node.js, Azure CLI or Kubernetes installation is required. +No host Node.js, Azure CLI or Kubernetes installation is required for the core lab. + +Unlike the Codespaces lifecycle, the commands below remain **core-only**: no model +or search index is downloaded/prepared. With host Node.js 24.13+ available, you may +opt into the built-in showcase after core startup with +`npm run search:prepare -- --local-sites`; see the [search guide](semantic-search.md). +Its first run downloads ~274 MB of model assets plus the pinned runtime (~455 MB +amd64 / 410 MB arm64); subsequent verified-cache runs do not contact the model +registry or start the downloader. No paid AI key or Azure service is needed. +`npm run workspace:start` likewise remains the Node-based core-only shortcut. Download/extract or clone the repository and open a terminal in its directory. Use a consistent directory and Compose project name to keep the same volumes. diff --git a/docs/organizer.md b/docs/organizer.md index e1e52ea..8b80da7 100644 --- a/docs/organizer.md +++ b/docs/organizer.md @@ -11,7 +11,13 @@ The presenter uses one existing, authorized Azure instance for an optional capst conference connectivity, storage retention and the pairing/follow-along plan. 2. Measure a fresh **ATO 2026 - Attendee** Codespace with both database services. The preceding main source measured 4m47s on a fresh two-core attendee Codespace; - repeat on the delivery revision and representative accounts/network. + repeat on the delivery revision and representative accounts/network. Current + start hooks prepare search automatically **after CORE READY**; first use adds + ~274 MB model assets and ~455 MB amd64 runtime download, potentially minutes. + Cached resumes verify the local pin and reuse bundled vectors without model + registry access/downloader startup. Measure both cold and cached lifecycle, + and verify core remains available when search fails; the prior 17-second cached + manual preparation is not this lifecycle's cold-start measurement. 3. Rehearse TODOs/reference recovery, app restart persistence, both copy directions, duplicate-safe retry, second-site failure/recovery and a real calendar-app import. 4. Follow the [presenter runbook](presenter.md) on the actual presenter laptop, @@ -29,7 +35,14 @@ even if legacy settings remain in `.env`, and starts at Site A. The optional **ATO 2026 - Organizer** dev-container configuration retains Azure CLI/Bicep for separately approved operations. Both configurations start the -attendee simulation only. Selecting Organizer installs tools; it neither signs +attendee simulation only, followed by automatic local-only search preparation via +`npm run codespace:start`. No manual search setup is needed on current-config +Codespaces; search does not change TODOs. Use `WORKSHOP_AUTO_SEARCH=0 npm run +codespace:start` for one-run opt-out, or the selected profile's `containerEnv` for +persistent opt-out (apply with rebuild; not a private `.env` key). Older checkouts +need one reviewed manual `git pull --ff-only` and `npm run codespace:start`; the +hook never pulls over exercise edits. See [startup/recovery details](semantic-search.md). +Selecting Organizer installs tools; it neither signs in nor grants access, and is unnecessary for the existing-instance presenter path. Do not share an authenticated organizer Codespace or Azure login cache. diff --git a/docs/semantic-search.md b/docs/semantic-search.md index 78d2295..ae63ec0 100644 --- a/docs/semantic-search.md +++ b/docs/semantic-search.md @@ -1,9 +1,10 @@ # Optional showcase: Search by meaning -This is a **built-in site feature, not another required lab exercise**. Prepare it -before or after the 105-minute workshop. The required TODOs, extension activities, -copy/return flow and calendar export are unchanged. Normal `npm ci` and -`npm run workspace:start` do **not** download a model or create a vector index. +This is a **built-in site feature, not another required lab exercise**. Both +Codespaces profiles automatically prepare it after core startup via +`npm run codespace:start`. The required TODOs, extension activities, copy/return +flow and calendar export are unchanged. Normal `npm ci`, laptop setup and +`npm run workspace:start` still do **not** download a model or create a vector index. The panel uses an embedding model to turn a query into a vector, then asks the **selected DocumentDB instance** to retrieve similar session metadata. There is @@ -13,10 +14,41 @@ If either the model or selected database is unavailable, semantic search fails explicitly; it never silently uses keywords, static results, Site A, or another model as a substitute. -## Enable explicitly in Codespaces or the local workshop - -First finish ordinary startup so both canonical catalogs are seeded. Run in the -repository terminal (inside Codespaces for the Codespaces workshop): +## Automatic Codespaces preparation; manual retry or laptop opt-in + +The Codespaces `postStartCommand` runs `npm run codespace:start` for both Attendee +and Organizer. It first runs the unchanged core `workspace:start` (setup, app, +Site A/B wait and catalog seed), then prepares search for **both local sites**. +No Azure operation, paid AI key, source-control operation, exercise edit or +credential rotation is added. Organizer remains a local-only simulation. + +At **CORE READY**, start the hands-on workshop on private port 3000 while search +finishes. Cold model/runtime downloads can take minutes; the app briefly restarts +when search is enabled. At **SEARCH READY**, refresh the planner and its request +token, then use **Search by meaning** / **Check search readiness**. A search-only +failure reports `search: unavailable`, leaves the core services alone, and exits +successfully so the core workshop can continue. Core startup failure stops before +search; cancellation or **SEARCH_DOWNLOAD_CLEANUP_FAILED** remains nonzero. + +For a one-run opt-out use `WORKSHOP_AUTO_SEARCH=0 npm run codespace:start`. +For a persistent opt-out add `"WORKSHOP_AUTO_SEARCH": "0"` to `containerEnv` in the +selected `.devcontainer/devcontainer.json` or `.devcontainer/organizer/devcontainer.json` +and apply that config with a rebuild, or set the equivalent Codespaces environment +variable. It is read from the **lifecycle process environment**, not the private +Compose `.env`. `npm run workspace:start` is always a core-only fallback. Opt-out +skips preparation; it does not stop a sidecar from an earlier search-enabled run +(see the explicit stop command below). + +Older existing Codespaces do not auto-update their checkout or lifecycle. Preserve +and review your changes, manually `git pull --ff-only` on the intended branch once, +then `npm run codespace:start`. If Git refuses, ask a helper rather than resetting, +stashing or overwriting exercises. No full rebuild is required to prepare search +in an already-running environment with the existing CLI tools. Fresh/rebuilt +configurations apply the new start hook; until then, invoke it explicitly. Startup +never pulls, checks out, commits or modifies attendee source files. + +To retry **only search**, or opt in on a laptop, first ensure both canonical +catalogs are seeded, then run in the repository terminal: ```sh npm run search:prepare -- --local-sites @@ -24,13 +56,21 @@ npm run search:prepare -- --local-sites This uses the current Compose project and its existing credentials/volumes. It: -1. Checks the pinned public embedding manifest and its download size. -2. Starts an **unpublished, temporary download service**, downloads only the - embedding model, then stops that service on success, failure, **SIGINT or - SIGTERM**. It waits for cancelled subprocesses to close, stops only this - project's downloader, and verifies the container state before continuing. -3. Starts the internal-only CPU embedding service and enables the app's optional - search configuration with `compose.search.yaml`. +1. Starts the read-only, internal-only CPU service and waits with bounded retries + for its process. A cache hit verifies the **full SHA-256 of actual manifest + bytes**, including pinned blob sizes, and checks `ollama show` can read the + model. Filenames and `ollama list`'s shortened hash are not trusted. This uses + **no embedding call, external model-registry fetch/DNS, or downloader start**. + Docker may still pull the fixed runtime image if its local image cache is absent. +2. **Only if the cache/model/runner assets are missing or invalid**, stops the + inference service, checks the pinned public manifest and size, starts an + **unpublished, temporary download service**, initializes runtime assets and + pulls only the embedding model. It stops that service on success, failure, + **SIGINT or SIGTERM**, waits for cancelled subprocesses to close, and verifies + only this project's downloader is stopped before continuing. The registry + manifest must still match the pin; a changed upstream tag is not accepted. +3. Starts the internal-only CPU service and enables the app's optional search + configuration with `compose.search.yaml`, with another bounded readiness probe. 4. Imports the **same checked-in 216-session embedding bundle** into a separate search collection in **both** local sites, builds each native vector index, and live-probes it. There are **zero document-embedding calls during ordinary @@ -69,7 +109,14 @@ favorites. The helper never provisions Azure or prepares a cloud target. ### Restart, stop, or return to the model-free workshop -With cached assets, this restart needs no model registry access: +On a normal Codespaces resume, the start hook repeats core startup and verifies +cached search/model assets without re-pulling the model. Search-store reuse still +checks the bundled vector hashes, real index and full-corpus query; there are no +document embeddings. The terminal emits `search-model-cache` with `verified: true` +and the final search receipt includes `cached: true`. + +To run that lifecycle manually, use `npm run codespace:start`. To restart just +already-prepared search services with cached assets and no model registry access: ```sh docker compose -f compose.yaml -f compose.search.yaml --profile search up -d --wait --wait-timeout 240 app search-model @@ -93,8 +140,9 @@ pruning or `down --volumes` as a troubleshooting step. ### Interruptions and emergency downloader recovery -Use Ctrl+C once to cancel preparation and **wait for the -`search-download-stopped` / `verified: true` receipt**. The helper handles SIGINT +Use Ctrl+C once to cancel preparation and **wait for exit and, if a downloader +was started, the `search-download-stopped` / `verified: true` receipt**. A verified +cache hit never starts the downloader and therefore has no download cleanup receipt. The helper handles SIGINT and SIGTERM during the manifest fetch, readiness and model pull. Cleanup is independent of the cancelled operation; a second SIGINT/SIGTERM does not interrupt it. No later app-start or indexing step begins after cancellation. The helper @@ -122,7 +170,15 @@ If termination happened before the helper printed project/context names, use `docker context show` and `docker compose -f compose.yaml -f compose.search.yaml config --format json` locally to establish the original selection; the latter contains private credentials and must **not** be pasted into chat or a public log. -Do not run concurrent preparation commands for the same Compose project. If your +Automatic startup and manual search preparation share an exclusive +`.workshop-private/startup.lock` in the same checkout. A second invocation fails +with `WORKSHOP_STARTUP_BUSY` rather than racing app changes or downloader cleanup; +it does not wait forever or steal a stale lock. Normal exit and handled signals +release it. After SIGKILL/crash, first ensure the old Node/Docker clients are gone +and complete the scoped downloader recovery above, then remove **only** +`.workshop-private/startup.lock` and retry. Never run two checkouts against the same +Compose project or run a competing core-only startup during preparation. +If your terminal overrides `DOCKER_HOST` without selecting `DOCKER_CONTEXT`, preparation refuses to guess a daemon: select the matching explicit Docker context first. It must be the same daemon that already owns your workshop volumes. @@ -321,7 +377,7 @@ migration—there is no automatic deletion/force-overwrite command. volumes reduce exposure; they do not remove that API or patch runtime defects. The temporary downloader is writable and internet-connected, which is why its verified shutdown matters. The host preparation command contacts the public - model registry; queries do not. + model registry only on a cache miss; cached preparation and queries do not. Reserve roughly **2 GB of extra disk** beyond the normal workshop and enough RAM for the extra 1 GiB-limited sidecar. Codespaces compute/storage usage still applies; @@ -332,8 +388,9 @@ images automatically. ## Failures and ownership -- **Disabled / unseeded / not prepared:** use the explicit target command after - ordinary startup. The search panel is separate from core workshop readiness. +- **Disabled / unseeded / not prepared:** current Codespaces startup prepares both + sites automatically. If it did not finish, retry `npm run search:prepare -- --local-sites` + after core startup. The search panel is separate from core workshop readiness. - **Model missing/digest mismatch:** preparation checks the fixed manifest and repulls the pinned public model; a different model is never substituted. - **Interrupted matching preparation:** rerun it; validated bundle-bound existing @@ -448,7 +505,7 @@ running applications: The bundled source `d4c10d6c7b2f2722e9f672045cd80841d520885c` was tested in an existing owned **two-core / 8 GiB Codespace**, using fresh canonical database names on both sites. Earlier notebooks, solved files, credentials and model cache -were preserved. This final evidence update changes documentation only. +were preserved. These measurements precede the automatic-start/cache-first lifecycle. - Complete `search:prepare -- --local-sites` with cached image/model assets took **17.07 seconds**, including service readiness and verified downloader shutdown. diff --git a/package.json b/package.json index 6a9b4eb..ede5bb7 100644 --- a/package.json +++ b/package.json @@ -13,6 +13,7 @@ "dev": "node --watch src/server.js", "setup": "node scripts/setup.mjs", "workspace:start": "node scripts/workspace-start.mjs", + "codespace:start": "node scripts/codespace-start.mjs", "organizer:check": "node scripts/organizer-check.mjs", "organizer:prepare": "node scripts/organizer-prepare.mjs", "seed": "node scripts/database.mjs seed", diff --git a/scripts/codespace-start.mjs b/scripts/codespace-start.mjs new file mode 100644 index 0000000..45671bb --- /dev/null +++ b/scripts/codespace-start.mjs @@ -0,0 +1,45 @@ +import { pathToFileURL } from "node:url"; +import { prepareSearchUnlocked, runCommand, withPreparationSignals } from "./search-prepare.mjs"; +import { withWorkspaceLock } from "./workspace-lock.mjs"; + +export async function startCodespace({ + run = runCommand, prepare = prepareSearchUnlocked, withLock = withWorkspaceLock, + env = process.env, log = console.log, signal, +} = {}) { + return withLock(async () => { + signal?.throwIfAborted(); + // Run the unchanged core startup first: setup preserves credentials, both + // local catalogs are seeded, and exercise source is never edited. + const core = await run(process.execPath, ["scripts/workspace-start.mjs"], { signal, timeout: 1800000 }); + signal?.throwIfAborted(); + if (core.error || core.cancelled || core.status !== 0) throw new Error("Core workspace startup failed. Search preparation was not started. Diagnose the error and retry npm run codespace:start (or npm run workspace:start for core only)."); + log("CORE READY: Site A/B are seeded. You can begin the hands-on exercises on private port 3000 now."); + if (env.WORKSHOP_AUTO_SEARCH === "0") { + log(JSON.stringify({ event: "codespace-start", core: "ready", search: "disabled" })); + log("Automatic search preparation is disabled by WORKSHOP_AUTO_SEARCH=0. Core workshop remains available."); + return; + } + log("Preparing built-in Search by meaning for both local sites. First use downloads ~274 MB of model assets plus the pinned runtime (~455 MB on amd64) and can take minutes. Continue the core exercises while this finishes; the app will briefly restart. No new TODOs, Azure access or paid AI keys."); + try { + await prepare(["--local-sites"], { run, log, signal }); + signal?.throwIfAborted(); + log(JSON.stringify({ event: "codespace-start", core: "ready", search: "ready" })); + log("SEARCH READY: Refresh the planner (including its request token), then use Search by meaning / Check search readiness. Your exercise files and favorites are unchanged."); + } catch (error) { + log(JSON.stringify({ event: "codespace-start", core: "ready", search: "unavailable" })); + log("Search preparation did not finish; core app/databases were not stopped. Continue the core workshop. Refresh after any app restart. Retry: npm run search:prepare -- --local-sites"); + // Optional failure must not hide cancellation or an unsafe downloader. + if (error?.code === "SEARCH_DOWNLOAD_CLEANUP_FAILED") throw error; + signal?.throwIfAborted(); + if (error?.name === "AbortError") throw error; + log(`WARNING: ${error?.message || "Search unavailable."}`); + } + }); +} + +export async function codespaceStartMain(options = {}) { + return withPreparationSignals((signal) => startCodespace({ ...options, signal }), options); +} +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + process.exitCode = await codespaceStartMain(); +} diff --git a/scripts/search-prepare.mjs b/scripts/search-prepare.mjs index c281051..0aa0086 100644 --- a/scripts/search-prepare.mjs +++ b/scripts/search-prepare.mjs @@ -2,6 +2,7 @@ import { spawn } from "node:child_process"; import { createHash } from "node:crypto"; import { setTimeout as sleep } from "node:timers/promises"; import { pathToFileURL } from "node:url"; +import { withWorkspaceLock } from "./workspace-lock.mjs"; import { SEARCH_MODEL, MODEL_MAX_BYTES } from "../src/search-model.js"; export function preparationTargets(args) { @@ -62,7 +63,13 @@ export function runCommand(command, args, { signal, timeout = 900000, capture = }); } -export async function prepareSearch(args, { run = runCommand, fetchImpl = fetch, log = console.log, signal } = {}) { +export async function prepareSearch(args, { withLock = withWorkspaceLock, ...options } = {}) { + preparationTargets(args); // reject invalid targets even before acquiring a lock + return withLock(() => prepareSearchUnlocked(args, options)); +} + +// Caller must hold the shared startup lock across core startup and preparation. +export async function prepareSearchUnlocked(args, { run = runCommand, fetchImpl = fetch, log = console.log, signal, pause = sleep } = {}) { const targets = preparationTargets(args); if (process.env.DOCKER_HOST && !process.env.DOCKER_CONTEXT) { throw new Error("Search preparation requires an explicit Docker context when DOCKER_HOST is overridden. Select a context for the intended daemon before retrying; no search service was started."); @@ -70,22 +77,6 @@ export async function prepareSearch(args, { run = runCommand, fetchImpl = fetch, const started = performance.now(); const checkCancelled = () => signal?.throwIfAborted(); checkCancelled(); - const response = await fetchImpl("https://registry.ollama.ai/v2/library/nomic-embed-text/manifests/v1.5", { - redirect: "error", signal: AbortSignal.any([...(signal ? [signal] : []), AbortSignal.timeout(30000)]), - }); - if (!response.ok) throw new Error("The pinned public model manifest is unavailable. Preparation did not start; the core workshop is unchanged."); - if (!response.body) throw new Error("The public model registry returned an empty manifest."); - const chunks = []; - let manifestBytes = 0; - for await (const chunk of response.body) { - checkCancelled(); - manifestBytes += chunk.length; - if (manifestBytes > 64_000) throw new Error("The public model manifest exceeded the size bound. Preparation did not start."); - chunks.push(chunk); - } - checkCancelled(); - const bytes = checkManifest(Buffer.concat(chunks).toString("utf8")); - log(`Optional embedding-only showcase: pinned query-model assets ${bytes} bytes (Apache-2.0); document vectors are imported from the checked-in bundle, not generated here. No answer model or paid API. Targets: ${targets.join(", ")}.`); const execute = async (args, options = {}) => { if (!options.cleanup) checkCancelled(); const result = await run("docker", args, { signal: options.cleanup ? undefined : signal, timeout: 900000, ...options }); @@ -105,6 +96,53 @@ export async function prepareSearch(args, { run = runCommand, fetchImpl = fetch, if (typeof project !== "string" || !/^[a-z0-9][a-z0-9_-]{0,127}$/.test(project)) throw new Error("Cannot safely identify this Compose project; no search service was started."); const base = ["--context", context, "compose", "--project-name", project, ...files]; const docker = (args, options) => execute([...base, ...args], options); + const waitReady = async (service) => { + for (let attempt = 0; attempt < 20; attempt++) { + checkCancelled(); + const result = await run("docker", [...base, "exec", "-T", service, "ollama", "list"], { signal, quiet: true, timeout: 5000 }); + checkCancelled(); + if (!result.error && !result.cancelled && result.status === 0) return true; + await pause(1000, undefined, { signal }); + } + return false; + }; + // Start ONLY the read-only, internal inference service first. A cold runner + // volume cannot initialize read-only: bounded readiness falls back to the + // controlled downloader below. Docker may still pull a missing runtime image. + await docker(["--profile", "search", "up", "-d", "search-model"]); + let bytes; + let cached = false; + if (await waitReady("search-model")) { + try { + // Never trust the cache name or ollama list's truncated digest. Hash the + // actual manifest bytes against the full pin, including bounded blob sizes, + // then ask Ollama to parse/show the model (no inference, network or pull). + bytes = checkManifest(await docker(["exec", "-T", "search-model", "cat", "/models/manifests/registry.ollama.ai/library/nomic-embed-text/v1.5"], { capture: true, timeout: 10000 })); + await docker(["exec", "-T", "search-model", "ollama", "show", SEARCH_MODEL.name], { capture: true, timeout: 10000 }); + cached = true; + } catch { checkCancelled(); } + } + log(JSON.stringify({ event: "search-model-cache", project, context, verified: cached })); + if (!cached) { + // No two services may initialize/use the writable runner cache concurrently. + await docker(["stop", "--timeout", "10", "search-model"]); + const response = await fetchImpl("https://registry.ollama.ai/v2/library/nomic-embed-text/manifests/v1.5", { + redirect: "error", signal: AbortSignal.any([...(signal ? [signal] : []), AbortSignal.timeout(30000)]), + }); + if (!response.ok) throw new Error("The pinned public model manifest is unavailable. Preparation did not start; the core workshop is unchanged."); + if (!response.body) throw new Error("The public model registry returned an empty manifest."); + const chunks = []; + let manifestBytes = 0; + for await (const chunk of response.body) { + checkCancelled(); + manifestBytes += chunk.length; + if (manifestBytes > 64_000) throw new Error("The public model manifest exceeded the size bound. Preparation did not start."); + chunks.push(chunk); + } + checkCancelled(); + bytes = checkManifest(Buffer.concat(chunks).toString("utf8")); + } + log(`Optional embedding-only showcase: pinned query-model assets ${bytes} bytes (Apache-2.0); document vectors are imported from the checked-in bundle, not generated here. No answer model or paid API. Targets: ${targets.join(", ")}.`); let attemptedDownload = false; let cleanupPromise; const cleanup = () => cleanupPromise ||= (async () => { @@ -137,34 +175,27 @@ export async function prepareSearch(args, { run = runCommand, fetchImpl = fetch, throw error; } })(); - try { + if (!cached) try { checkCancelled(); attemptedDownload = true; await docker(["--profile", "search-download", "up", "-d", "search-download"]); log(JSON.stringify({ event: "search-download-started", project, context })); - let ready = false; - for (let attempt = 0; attempt < 20; attempt++) { - checkCancelled(); - const result = await run("docker", [...base, "exec", "-T", "search-download", "ollama", "list"], { signal, quiet: true, timeout: 5000 }); - checkCancelled(); - if (!result.error && !result.cancelled && result.status === 0) { ready = true; break; } - await sleep(1000, undefined, { signal }); - } - if (!ready) throw new Error("The model download service did not become ready. Core workshop startup does not depend on it."); + if (!await waitReady("search-download")) throw new Error("The model download service did not become ready. Core workshop startup does not depend on it."); await docker(["exec", "-T", "search-download", "ollama", "pull", SEARCH_MODEL.name]); } finally { await cleanup(); } checkCancelled(); await docker(["--profile", "search", "up", "--build", "-d", "--wait", "--wait-timeout", "240", "app", "search-model"]); + if (!await waitReady("search-model")) throw new Error("The internal model service did not become ready. Core browsing remains available; retry search preparation."); for (const target of targets) { checkCancelled(); await docker(["exec", "-T", "app", "node", "scripts/search-index.mjs", "--target", target]); } checkCancelled(); - log(JSON.stringify({ status: "ready", targets, model: SEARCH_MODEL, modelAssetBytes: bytes, elapsedMs: Math.round(performance.now() - started) })); + log(JSON.stringify({ status: "ready", targets, model: SEARCH_MODEL, modelAssetBytes: bytes, cached, elapsedMs: Math.round(performance.now() - started) })); log("Search by meaning is enabled. Refresh the page/readiness. This is a built-in showcase, not an extra lab exercise. Normal workspace:start remains model-free."); } -export async function searchPrepareMain(args, options = {}) { +export async function withPreparationSignals(operation, options = {}) { const interrupted = new AbortController(); let receivedSignal; const onSignal = (signal) => { @@ -174,7 +205,7 @@ export async function searchPrepareMain(args, options = {}) { process.on("SIGINT", onSignal); process.on("SIGTERM", onSignal); try { - await prepareSearch(args, { ...options, signal: interrupted.signal }); + await operation(interrupted.signal); return receivedSignal === "SIGINT" ? 130 : receivedSignal ? 143 : 0; } catch (error) { const message = error?.code === "SEARCH_DOWNLOAD_CLEANUP_FAILED" ? error.message @@ -188,6 +219,9 @@ export async function searchPrepareMain(args, options = {}) { process.removeListener("SIGTERM", onSignal); } } +export async function searchPrepareMain(args, options = {}) { + return withPreparationSignals((signal) => prepareSearch(args, { ...options, signal }), options); +} if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { process.exitCode = await searchPrepareMain(process.argv.slice(2)); } diff --git a/scripts/workspace-lock.mjs b/scripts/workspace-lock.mjs new file mode 100644 index 0000000..fbf6286 --- /dev/null +++ b/scripts/workspace-lock.mjs @@ -0,0 +1,25 @@ +import { mkdir, open, unlink } from "node:fs/promises"; +import { resolve } from "node:path"; + +// Shared by automatic startup and manual search preparation. Never steal an old +// lock: after SIGKILL a surviving Docker client may still be changing this project. +export async function withWorkspaceLock(operation, directory = process.cwd()) { + const folder = resolve(directory, ".workshop-private"); + await mkdir(folder, { recursive: true, mode: 0o700 }); + const path = resolve(folder, "startup.lock"); + let file; + try { file = await open(path, "wx", 0o600); } + catch (error) { + if (error.code !== "EEXIST") throw error; + const busy = new Error("WORKSHOP_STARTUP_BUSY: another startup/search preparation owns .workshop-private/startup.lock. Wait for it; after an unhandled termination, follow docs/semantic-search.md recovery before removing only that lock."); + busy.code = "WORKSHOP_STARTUP_BUSY"; + throw busy; + } + try { + await file.writeFile(`${JSON.stringify({ pid: process.pid, startedAt: new Date().toISOString() })}\n`); + return await operation(); + } finally { + await file.close(); + await unlink(path); + } +} diff --git a/test/codespace-start.test.js b/test/codespace-start.test.js new file mode 100644 index 0000000..93effa5 --- /dev/null +++ b/test/codespace-start.test.js @@ -0,0 +1,102 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { startCodespace, codespaceStartMain } from "../scripts/codespace-start.mjs"; +import { withWorkspaceLock } from "../scripts/workspace-lock.mjs"; +import { prepareSearch } from "../scripts/search-prepare.mjs"; + +const unlocked = (operation) => operation(); +function fixture() { + const calls = [], logs = []; + return { calls, logs, options: { + withLock: unlocked, env: {}, log: (message) => logs.push(message), + run: async (command, args, options) => { calls.push([command, args, options]); return { status: 0 }; }, + prepare: async (args, options) => { calls.push(["prepare", args]); assert.ok(logs.some((line) => line.startsWith("CORE READY"))); assert.ok(options.signal); }, + } }; +} + +test("Codespaces serially starts unchanged core, then prepares both sites with an honest readiness receipt", async () => { + const { calls, logs, options } = fixture(); + assert.equal(await codespaceStartMain(options), 0); + assert.equal(calls.length, 2); + assert.equal(calls[0][0], process.execPath); + assert.deepEqual(calls[0][1], ["scripts/workspace-start.mjs"]); + assert.deepEqual(calls[1], ["prepare", ["--local-sites"]]); + assert.match(logs.join("\n"), /can take minutes/); + assert.match(logs.join("\n"), /"core":"ready","search":"ready"/); + assert.match(logs.join("\n"), /Refresh the planner/); +}); + +test("core failure aborts search and does not claim core readiness", async () => { + const { calls, logs, options } = fixture(); + options.run = async () => ({ status: 1 }); + assert.equal(await codespaceStartMain({ ...options, errorLog: (message) => logs.push(message) }), 1); + assert.equal(calls.length, 0); + assert.doesNotMatch(logs.join("\n"), /CORE READY|"core":"ready"/); +}); + +test("explicit opt-out keeps core, without invoking preparation", async () => { + const { calls, logs, options } = fixture(); + assert.equal(await codespaceStartMain({ ...options, env: { WORKSHOP_AUTO_SEARCH: "0" } }), 0); + assert.equal(calls.length, 1); + assert.match(logs.join("\n"), /"search":"disabled"/); +}); + +for (const mode of ["unavailable", "SEARCH_DOWNLOAD_CLEANUP_FAILED", "AbortError"]) { + test(`optional failure ${mode}: core remains available, unsafe/cancelled runs are nonzero`, async () => { + const { calls, logs, options } = fixture(); + options.prepare = async () => { const error = new Error(mode); error.code = mode; error.name = mode; throw error; }; + assert.equal(await codespaceStartMain({ ...options, errorLog: (message) => logs.push(message) }), mode === "unavailable" ? 0 : 1); + assert.equal(calls.length, 1, "must not stop core Docker services after search failure"); + assert.match(logs.join("\n"), /"core":"ready","search":"unavailable"/); + assert.doesNotMatch(logs.join("\n"), /SEARCH READY|"search":"ready"/); + assert.match(logs.join("\n"), /npm run search:prepare -- --local-sites/); + if (mode === "SEARCH_DOWNLOAD_CLEANUP_FAILED") assert.match(logs.join("\n"), /SEARCH_DOWNLOAD_CLEANUP_FAILED/); + }); +} + +for (const phase of ["core", "search"]) for (const signal of ["SIGINT", "SIGTERM"]) { + test(`${signal} during ${phase} waits for cleanup and returns the correct exit`, async () => { + const { calls, logs, options } = fixture(); + let cleaned = false; + const interrupt = async (...args) => { + process.emit(signal, signal); + await new Promise((resolve) => setImmediate(resolve)); + cleaned = true; + args.at(-1).signal.throwIfAborted(); + }; + if (phase === "core") options.run = interrupt; + else options.prepare = interrupt; + assert.equal(await codespaceStartMain({ ...options, errorLog: (message) => logs.push(message) }), signal === "SIGINT" ? 130 : 143); + assert.equal(cleaned, true); + assert.ok(calls.every(([command]) => command !== "prepare")); + assert.doesNotMatch(logs.join("\n"), /SEARCH READY/); + }); +} + +test("same checkout lock excludes simultaneous automatic/manual preparation and is released on failure", async (t) => { + const directory = await mkdtemp(join(tmpdir(), "startup-lock-")); + t.after(() => rm(directory, { recursive: true, force: true })); + const lock = (operation) => withWorkspaceLock(operation, directory); + await assert.rejects(lock(async () => { + assert.equal((await stat(join(directory, ".workshop-private/startup.lock"))).mode & 0o077, 0); + await assert.rejects(startCodespace({ withLock: lock, run: () => assert.fail("busy startup") }), { code: "WORKSHOP_STARTUP_BUSY" }); + await assert.rejects(prepareSearch(["--local-sites"], { withLock: lock, run: () => assert.fail("busy preparation") }), { code: "WORKSHOP_STARTUP_BUSY" }); + throw new Error("operation failed"); + }), /operation failed/); + await lock(async () => {}); + const path = join(directory, ".workshop-private/startup.lock"); + await writeFile(path, '{"pid":99999999}'); + await assert.rejects(lock(() => assert.fail("must not steal stale lock")), { code: "WORKSHOP_STARTUP_BUSY" }); + assert.equal(await readFile(path, "utf8"), '{"pid":99999999}'); +}); + +test("lifecycle has no source-control, Azure, exercise writes, scheduler or destructive cleanup commands", async () => { + for (const path of ["scripts/codespace-start.mjs", "scripts/workspace-start.mjs", "scripts/search-prepare.mjs"]) { + const source = await readFile(new URL(`../${path}`, import.meta.url), "utf8"); + assert.doesNotMatch(source, /["'`](?:git|az|azd|crontab|systemctl)["'`]|\b(?:checkout|reset|stash|prune)\b|--volumes/); + assert.doesNotMatch(source, /writeFile|["']\.env["']/); + } +}); diff --git a/test/search-prepare-interruption.test.js b/test/search-prepare-interruption.test.js index 9ce654b..893df81 100644 --- a/test/search-prepare-interruption.test.js +++ b/test/search-prepare-interruption.test.js @@ -3,7 +3,7 @@ import test from "node:test"; import assert from "node:assert/strict"; import { spawn } from "node:child_process"; -import { mkdtemp, writeFile, readFile, rm } from "node:fs/promises"; +import { mkdtemp, mkdir, writeFile, readFile, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { fileURLToPath } from "node:url"; @@ -13,17 +13,28 @@ import { runCommand } from "../scripts/search-prepare.mjs"; const root = fileURLToPath(new URL("../", import.meta.url)); const manifest = '{"schemaVersion":2,"mediaType":"application/vnd.docker.distribution.manifest.v2+json","config":{"mediaType":"application/vnd.docker.container.image.v1+json","digest":"sha256:31df23ea7daa448f9ccdbbcecce6c14689c8552222b80defd3830707c0139d4f","size":420},"layers":[{"mediaType":"application/vnd.ollama.image.model","digest":"sha256:970aa74c0a90ef7482477cf803618e776e173c007bf957f635f1015bfcfef0e6","size":274290656},{"mediaType":"application/vnd.ollama.image.license","digest":"sha256:c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4","size":11357},{"mediaType":"application/vnd.ollama.image.params","digest":"sha256:ce4a164fc04605703b485251fe9f1a181688ba0eb6badb80cc6335c0de17ca0d","size":17}]}'; -async function fixture(t, mode) { +async function fixture(t, mode, automatic = false) { const directory = await mkdtemp(join(tmpdir(), "search-interruption-")); const commands = join(directory, "commands.jsonl"); const stateFile = join(directory, "running"); const reached = join(directory, "reached"); const cleaned = join(directory, "cleaning"); await writeFile(stateFile, "false"); + await mkdir(join(directory, "scripts")); + // The orchestrator really launches a subprocess; core is a local fake here, + // never real setup/credentials/database Docker calls. + await writeFile(join(directory, "scripts/workspace-start.mjs"), ` + import { writeFileSync } from 'node:fs'; + if(process.env.TEST_MODE==='core') { writeFileSync(process.env.TEST_REACHED,'core');setInterval(()=>{},1000); } + else if(process.env.TEST_MODE==='core-failure') process.exitCode=7; + else console.log('FAKE-CORE-COMPLETED'); + `); const bootstrap = join(directory, "registry.mjs"); await writeFile(bootstrap, `import { writeFileSync } from 'node:fs'; const mode=process.env.TEST_MODE; +process.chdir(process.env.TEST_DIRECTORY); globalThis.fetch=async (_url, {signal})=>{ + if(mode==='cached') throw new Error('Unexpected external registry fetch on cache hit'); if(mode==='manifest') { writeFileSync(process.env.TEST_REACHED,'manifest'); return new Promise((_,reject)=>{const timer=setInterval(()=>{},1000); signal.addEventListener('abort',()=>{clearInterval(timer);reject(signal.reason)},{once:true})}); @@ -41,14 +52,15 @@ const fs=require('node:fs');const args=process.argv.slice(2);const mode=process. fs.appendFileSync(process.env.TEST_COMMANDS,JSON.stringify(args)+'\\n'); const has=x=>args.includes(x), output=x=>console.log(x), write=x=>fs.writeFileSync(process.env.TEST_STATE,String(x)); if(args[0]==='context') output('offline-context'); +else if(has('cat')&&mode==='cached') process.stdout.write(${JSON.stringify(manifest)}); else if(has('config')) output(JSON.stringify({name:'offline-project',private:'PRIVATE-CONFIG-CREDENTIAL-DO-NOT-LOG'})); else if(has('up')&&has('search-download')) {write(true);if(mode==='startup'){fs.writeFileSync(process.env.TEST_REACHED,'startup');setInterval(()=>{},1000);}} -else if(has('list')) {if(mode==='readiness'){fs.writeFileSync(process.env.TEST_REACHED,'readiness');setInterval(()=>{},1000);}} +else if(has('list')) {if(mode==='cache-readiness'||(mode==='readiness'&&has('search-download'))){fs.writeFileSync(process.env.TEST_REACHED,'readiness');setInterval(()=>{},1000);}} else if(has('pull')) { if(mode==='pull'||mode==='signal-cleanup-failure'){fs.writeFileSync(process.env.TEST_REACHED,'pull');setInterval(()=>{},1000);} else if(mode==='pull-failure') process.exitCode=7; } -else if(has('stop')) { +else if(has('stop')&&has('search-download')) { fs.writeFileSync(process.env.TEST_CLEANING,'yes'); // Keep cleanup alive long enough to deliver a second signal to the parent. setTimeout(()=>{ @@ -59,9 +71,9 @@ else if(has('stop')) { else if(has('ps')) output('aaaaaaaaaaaa'); else if(has('inspect')) {const running=fs.readFileSync(process.env.TEST_STATE,'utf8')==='true';output(JSON.stringify({Running:running,Status:running?'running':'exited'}));} `, { mode: 0o700 }); - const child = spawn(process.execPath, ["--import", bootstrap, "scripts/search-prepare.mjs", "--local-sites"], { + const child = spawn(process.execPath, ["--import", bootstrap, join(root, automatic ? "scripts/codespace-start.mjs" : "scripts/search-prepare.mjs"), ...(automatic ? [] : ["--local-sites"])], { cwd: root, detached: process.platform !== "win32", stdio: ["ignore", "pipe", "pipe"], - env: { ...process.env, DOCKER_HOST: mode === "host-override" ? "tcp://PRIVATE-DOCKER-HOST:2375" : "", DOCKER_CONTEXT: "", PATH: `${directory}:${process.env.PATH}`, TEST_MODE: mode, TEST_COMMANDS: commands, TEST_STATE: stateFile, TEST_REACHED: reached, TEST_CLEANING: cleaned }, + env: { ...process.env, DOCKER_HOST: mode === "host-override" ? "tcp://PRIVATE-DOCKER-HOST:2375" : "", DOCKER_CONTEXT: "", PATH: `${directory}:${process.env.PATH}`, TEST_MODE: mode, TEST_DIRECTORY: directory, TEST_COMMANDS: commands, TEST_STATE: stateFile, TEST_REACHED: reached, TEST_CLEANING: cleaned }, }); let output = ""; child.stdout.on("data", (chunk) => { output += chunk; }); @@ -99,12 +111,12 @@ else if(has('inspect')) {const running=fs.readFileSync(process.env.TEST_STATE,'u } for (const signal of ["SIGINT", "SIGTERM"]) { - for (const phase of ["manifest", "manifest-body", "startup", "readiness", "pull"]) { + for (const phase of ["manifest", "manifest-body", "cache-readiness", "startup", "readiness", "pull"]) { test(`${signal} during ${phase}: cancel, reconcile downloader, never index; repeated signal cannot interrupt cleanup`, { timeout: 20000 }, async (t) => { const run = await fixture(t, phase); await run.waitFile(run.reached); assert.equal(run.sendGroupSignal(signal), true); - if (!["manifest", "manifest-body"].includes(phase)) { + if (!["manifest", "manifest-body", "cache-readiness"].includes(phase)) { await run.waitFile(run.cleaned); assert.equal(run.sendGroupSignal(signal === "SIGINT" ? "SIGTERM" : "SIGINT"), true); } @@ -113,11 +125,11 @@ for (const signal of ["SIGINT", "SIGTERM"]) { assert.ok(commands.every((args) => !args.includes("scripts/search-index.mjs"))); assert.ok(commands.every((args) => !(args.includes("up") && args.includes("app")))); assert.equal(await run.running(), "false"); - if (["manifest", "manifest-body"].includes(phase)) assert.deepEqual(commands, []); + if (["manifest", "manifest-body", "cache-readiness"].includes(phase)) assert.ok(commands.every((args) => !args.includes("search-download"))); else { assert.match(run.output(), /"event":"search-download-stopped".*"verified":true/); assert.ok(commands.some((args) => args.includes("inspect"))); - for (const args of commands.filter((args) => args.includes("stop") || args.includes("ps") || args.includes("inspect"))) { + for (const args of commands.filter((args) => (args.includes("stop") && args.includes("search-download")) || args.includes("ps") || args.includes("inspect"))) { assert.deepEqual(args.slice(0, 2), ["--context", "offline-context"]); if (args.includes("stop")) assert.ok(args.includes("offline-project") && args.at(-1) === "search-download"); assert.ok(!args.includes("down") && !args.includes("--volumes") && !args.includes("rm")); @@ -181,3 +193,43 @@ test("ambiguous DOCKER_HOST override is rejected before selecting or modifying a assert.match(run.output(), /requires an explicit Docker context/); assert.doesNotMatch(run.output(), /PRIVATE-DOCKER-HOST/); }); + + +for (const [mode, expected] of [["success", 0], ["cached", 0], ["pull-failure", 0], ["cleanup-failure", 1], ["core-failure", 1]]) { + test(`automatic CLI ${mode}: core first, explicit search outcome, no hidden cleanup failure`, { timeout: 20000 }, async (t) => { + const run = await fixture(t, mode, true); + assert.deepEqual(await run.done, { code: expected, signal: null }); + const commands = await run.commandList(); + if (mode === "core-failure") { + assert.deepEqual(commands, []); + assert.doesNotMatch(run.output(), /CORE READY/); + } else { + assert.match(run.output(), /FAKE-CORE-COMPLETED[\s\S]*CORE READY/); + assert.match(run.output(), /"core":"ready"/); + if (["success", "cached"].includes(mode)) assert.match(run.output(), /SEARCH READY/); + else assert.doesNotMatch(run.output(), /SEARCH READY/); + if (mode === "cached") { + assert.match(run.output(), /"cached":true/); + assert.ok(commands.every((args) => !args.includes("search-download") && !args.includes("pull"))); + } + if (mode === "cleanup-failure") assert.match(run.output(), /SEARCH_DOWNLOAD_CLEANUP_FAILED/); + assert.ok(commands.every((args) => !args.includes("down") && !args.includes("--volumes"))); + } + }); +} +for (const phase of ["core", "pull"]) for (const signal of ["SIGINT", "SIGTERM"]) { + test(`automatic CLI real group ${signal} during ${phase} waits for cleanup`, { timeout: 20000 }, async (t) => { + const run = await fixture(t, phase, true); + await run.waitFile(run.reached); + run.sendGroupSignal(signal); + if (phase === "pull") { + await run.waitFile(run.cleaned); + run.sendGroupSignal(signal === "SIGINT" ? "SIGTERM" : "SIGINT"); + } + assert.deepEqual(await run.done, { code: signal === "SIGINT" ? 130 : 143, signal: null }); + assert.equal(await run.running(), "false"); + assert.doesNotMatch(run.output(), /SEARCH READY/); + assert.ok((await run.commandList()).every((args) => !args.includes("scripts/search-index.mjs"))); + if (phase === "pull") assert.match(run.output(), /"event":"search-download-stopped".*"verified":true/); + }); +} diff --git a/test/search-prepare.test.js b/test/search-prepare.test.js index ff7d649..a9d3d27 100644 --- a/test/search-prepare.test.js +++ b/test/search-prepare.test.js @@ -3,7 +3,7 @@ import test from "node:test"; import assert from "node:assert/strict"; import { readFile } from "node:fs/promises"; -import { checkManifest, preparationTargets, prepareSearch } from "../scripts/search-prepare.mjs"; +import { checkManifest, preparationTargets, prepareSearchUnlocked as prepareSearch } from "../scripts/search-prepare.mjs"; import { SEARCH_MODEL } from "../src/search-model.js"; // Public registry manifest, no model weights or private source material. @@ -51,7 +51,7 @@ test("explicit helper downloads only the embedding pin, stops downloader, then i const text = commands.map((args) => args.join(" ")).join("\n"); assert.match(text, new RegExp(`ollama pull ${SEARCH_MODEL.name}`)); assert.doesNotMatch(text, /qwen|generate|chat|cloud|prune|\bdown\b|--volumes|seed|migrate/); - const stop = commands.findIndex((args) => args.includes("stop")); + const stop = commands.findIndex((args) => args.includes("stop") && args.includes("search-download")); const upApp = commands.findIndex((args) => args.includes("app") && args.includes("up")); assert.ok(stop >= 0 && stop < upApp); assert.deepEqual(commands.filter((args) => args.includes("scripts/search-index.mjs")).map((args) => args.at(-1)), ["local", "site-b"]); @@ -68,11 +68,11 @@ test("a failed download still stops its service and never enables/indexes the ap assert.ok(commands.every((args) => !args.includes("scripts/search-index.mjs"))); }); -test("failed, changed or oversized registry responses do not invoke Docker", async () => { +test("failed, changed or oversized registry responses never start downloader, app or index", async () => { for (const response of [new Response("unavailable", { status: 503 }), new Response("{}"), new Response("x".repeat(64001))]) { - let calls = 0; - await assert.rejects(prepareSearch(["--local-sites"], { run() { calls++; }, fetchImpl: async () => response, log() {} })); - assert.equal(calls, 0); + const commands = []; + await assert.rejects(prepareSearch(["--local-sites"], { run: mockRun(commands), fetchImpl: async () => response, log() {} })); + assert.ok(commands.every((args) => !args.includes("search-download") && !args.includes("app") && !args.includes("scripts/search-index.mjs"))); } }); @@ -95,3 +95,67 @@ test("model is optional, private, bounded and absent from core startup; optional assert.match(workflow, /workflow_dispatch:/); assert.doesNotMatch(workflow, /pull_request:|push:/); }); + +for (const cache of ["valid", "wrong-digest", "oversize", "missing", "missing-blob", "cold-runners"]) { + test(`cache-first preparation: ${cache}`, async () => { + const commands = []; + const messages = []; + let fetches = 0; + let downloaded = false; + let coldProbes = 0; + const run = async (command, args, options) => { + const result = await mockRun(commands)(command, args, options); + if (args.includes("pull")) downloaded = true; + if (args.includes("search-model") && args.includes("list") && cache === "cold-runners" && !downloaded) { + coldProbes++; + return { status: 1 }; + } + if (args.includes("cat")) return { status: cache === "missing" ? 1 : 0, stdout: + cache === "wrong-digest" ? manifest + "\n" : cache === "oversize" ? manifest.replace("274290656", "474290656") : manifest }; + if (args.includes("ollama") && args.includes("show") && cache === "missing-blob") return { status: 1 }; + return result; + }; + await prepareSearch(["--local-sites"], { + run, pause: async () => {}, log: (message) => messages.push(message), + fetchImpl: async () => { + fetches++; + assert.notEqual(cache, "valid", "valid cache must work with no external fetch/DNS"); + return new Response(manifest); + }, + }); + const hit = cache === "valid"; + assert.equal(fetches, hit ? 0 : 1); + assert.equal(downloaded, !hit); + if (hit) { + assert.ok(commands.every((args) => !args.includes("search-download") && !args.includes("pull"))); + assert.ok(commands.some((args) => args.includes("cat"))); + assert.ok(commands.some((args) => args.includes("show"))); + } else { + const stop = commands.findIndex((args) => args.includes("stop") && args.includes("search-download")); + const index = commands.findIndex((args) => args.includes("scripts/search-index.mjs")); + assert.ok(stop >= 0 && index > stop); + } + if (cache === "cold-runners") assert.equal(coldProbes, 20); + assert.ok(messages.some((message) => message.includes(`"cached":${hit}`))); + assert.deepEqual(commands.filter((args) => args.includes("scripts/search-index.mjs")).map((args) => args.at(-1)), ["local", "site-b"]); + assert.doesNotMatch(commands.map((args) => args.join(" ")).join("\n"), /embeddings|generate|chat|\bgit\b|\baz\b|--target cloud/); + }); +} + +test("cache service readiness retries, then verifies full manifest rather than trusting an image/name", async () => { + const commands = []; + let probes = 0; + let pauses = 0; + await prepareSearch(["--target", "local"], { + run: async (command, args, options) => { + const result = await mockRun(commands)(command, args, options); + if (args.includes("list") && ++probes < 3) return { status: 1 }; + if (args.includes("cat")) return { status: 0, stdout: manifest }; + return result; + }, + pause: async () => { pauses++; }, + fetchImpl: () => assert.fail("no registry on verified cache"), log() {}, + }); + assert.equal(pauses, 2); + assert.ok(commands.every((args) => !args.includes("search-download"))); +}); diff --git a/test/workspace.test.js b/test/workspace.test.js index 8fc4db6..56700a8 100644 --- a/test/workspace.test.js +++ b/test/workspace.test.js @@ -25,7 +25,7 @@ test("attendee and organizer configurations share startup, not Azure authenticat assert.equal(attendee.containerEnv.WORKSHOP_ROLE, "attendee"); assert.equal(organizer.containerEnv.WORKSHOP_ROLE, "organizer"); assert.equal(attendee.image, organizer.image); - assert.equal(attendee.postStartCommand, "npm run workspace:start"); + assert.equal(attendee.postStartCommand, "npm run codespace:start"); assert.equal(attendee.postStartCommand, organizer.postStartCommand); assert.ok(Object.keys(attendee.features).every((name) => !name.includes("azure-cli"))); const azure = Object.entries(organizer.features).find(([name]) => name.includes("/azure-cli:")); From 92bc4a900deedb3c1e90f682520ecb83a895c59b Mon Sep 17 00:00:00 2001 From: Patty Chow <91703531+patty-chow@users.noreply.github.com> Date: Sun, 18 Oct 2026 22:04:45 -0700 Subject: [PATCH 2/3] Refuse cached search startup when prior downloader cleanup is unsafe --- docs/acceptance.md | 35 +++++++++++ docs/semantic-search.md | 21 +++++-- scripts/search-prepare.mjs | 55 +++++++++++------ src/public/index.html | 4 +- src/search.js | 2 +- test/search-prepare-interruption.test.js | 2 +- test/search-prepare.test.js | 79 +++++++++++++++++++++++- test/search-ui.test.js | 4 ++ 8 files changed, 173 insertions(+), 29 deletions(-) diff --git a/docs/acceptance.md b/docs/acceptance.md index 20261d3..7a009a9 100644 --- a/docs/acceptance.md +++ b/docs/acceptance.md @@ -1,5 +1,40 @@ # Acceptance record and remaining gates +## Downloader preflight follow-up — October 18, 2026 + +Review reproduced a two-invocation safety gap in `b33a61e`: a successful model pull +followed by failed downloader shutdown released the process lock; a subsequent +valid-cache run could report ready while the old writable, outbound-capable +downloader remained running. The follow-up fails closed **before any inference +startup/cache access, registry fetch or indexing**, using the frozen project and +Docker context. Stable owned-container inspection requires explicit stopped, +not-paused, not-restarting states. Uncertain inventory produces the same nonzero +`SEARCH_DOWNLOAD_CLEANUP_FAILED` recovery error. No new automatic stop is added. + +- Offline regression uses a **real filesystem lock and two preparation calls**: + pull succeeds/stop fails; the second cache-valid call refuses before mutations + or fetches. Explicit simulated scoped recovery allows the cached third call. + Additional cases reject running/restarting/paused/missing/unknown/malformed + states and failed/invalid/changing inventories. Existing whole-process-group + signal and cleanup tests remain passing. +- Full host suite: **194 passed, 1 Linux-only skip, 0 failures** (195 total). +- Actual owned local project `ato-auto-search-verify-20261018`: started only its + cached downloader, then preparation refused with zero registry fetches and no + app/database/model startup, execution or stop. Independent before/after state + and timestamps of those four services were unchanged. Scoped manual downloader + stop was verified **exited, Running/Restarting/Paused all false**; a subsequent + cached preparation reached both sites ready with zero fetches and unchanged + downloader timestamps. All owned services were stopped after proof; no volumes + deleted and no unrelated project changed. +- Search panel and disabled-state message now say Codespaces prepares search + automatically, core work can continue while loading, and the manual command is + for retry/laptop setup. This is copy-only: no polling or query/UI behavior change. + +**This follow-up has not been tested in Codespaces.** Earlier `b33a61e` lifecycle +proof does not prove this new preflight guard; the parent review/release run owns +that remaining gate. The live case above used the same local arm64 Docker project +and cached image/model volumes, not a new model download or fresh Codespace. + ## Automatic Codespaces search startup — October 18, 2026 This revision adds automatic search preparation after normal core startup to both diff --git a/docs/semantic-search.md b/docs/semantic-search.md index ae63ec0..f0329bc 100644 --- a/docs/semantic-search.md +++ b/docs/semantic-search.md @@ -56,22 +56,29 @@ npm run search:prepare -- --local-sites This uses the current Compose project and its existing credentials/volumes. It: -1. Starts the read-only, internal-only CPU service and waits with bounded retries +1. **Before any inference startup, cache access, registry request or indexing**, + inventories only this frozen Docker context/project's downloader containers. + Two stable inspections must show none running, restarting or paused. Unknown + states or failed inspection also return **SEARCH_DOWNLOAD_CLEANUP_FAILED**; + a released process lock or valid model cache is not evidence of safe cleanup. + Use the scoped recovery below before retrying. A clean exited downloader is + inspected but never restarted on a cache hit. +2. Starts the read-only, internal-only CPU service and waits with bounded retries for its process. A cache hit verifies the **full SHA-256 of actual manifest bytes**, including pinned blob sizes, and checks `ollama show` can read the model. Filenames and `ollama list`'s shortened hash are not trusted. This uses **no embedding call, external model-registry fetch/DNS, or downloader start**. Docker may still pull the fixed runtime image if its local image cache is absent. -2. **Only if the cache/model/runner assets are missing or invalid**, stops the +3. **Only if the cache/model/runner assets are missing or invalid**, stops the inference service, checks the pinned public manifest and size, starts an **unpublished, temporary download service**, initializes runtime assets and pulls only the embedding model. It stops that service on success, failure, **SIGINT or SIGTERM**, waits for cancelled subprocesses to close, and verifies only this project's downloader is stopped before continuing. The registry manifest must still match the pin; a changed upstream tag is not accepted. -3. Starts the internal-only CPU service and enables the app's optional search +4. Starts the internal-only CPU service and enables the app's optional search configuration with `compose.search.yaml`, with another bounded readiness probe. -4. Imports the **same checked-in 216-session embedding bundle** into a separate +5. Imports the **same checked-in 216-session embedding bundle** into a separate search collection in **both** local sites, builds each native vector index, and live-probes it. There are **zero document-embedding calls during ordinary preparation**. A target is only marked ready after the reviewed bundle, stored @@ -163,7 +170,11 @@ docker --context YOUR_CONTEXT compose --project-name YOUR_PROJECT -f compose.yam docker --context YOUR_CONTEXT compose --project-name YOUR_PROJECT -f compose.yaml -f compose.search.yaml ps --all search-download ``` -The downloader must show **Exited**, or no container. If it is still running, +The downloader must show **Exited**, or no container. Every subsequent preparation +performs its own bounded, fail-closed inventory before enabling inference—even +when a preceding pull succeeded and the model cache is valid. The preflight receipt +is `search-download-preflight` / `verified: true`, not a claim that a new download +ran. If the downloader is still running, restore Docker access and repeat the scoped stop before retrying preparation. Never substitute a different project, delete volumes, or run a system-wide prune. If termination happened before the helper printed project/context names, use diff --git a/scripts/search-prepare.mjs b/scripts/search-prepare.mjs index 0aa0086..54933bd 100644 --- a/scripts/search-prepare.mjs +++ b/scripts/search-prepare.mjs @@ -96,6 +96,40 @@ export async function prepareSearchUnlocked(args, { run = runCommand, fetchImpl if (typeof project !== "string" || !/^[a-z0-9][a-z0-9_-]{0,127}$/.test(project)) throw new Error("Cannot safely identify this Compose project; no search service was started."); const base = ["--context", context, "compose", "--project-name", project, ...files]; const docker = (args, options) => execute([...base, ...args], options); + const cleanupError = () => { + const error = new Error(`SEARCH_DOWNLOAD_CLEANUP_FAILED: could not verify search-download stopped in project ${project}, Docker context ${context}. Run the scoped recovery command in docs/semantic-search.md before retrying. No data or volumes were deleted.`); + error.code = "SEARCH_DOWNLOAD_CLEANUP_FAILED"; + return error; + }; + const verifyDownloaderStopped = async (options = {}) => { + const inventory = async () => { + const output = await execute(["--context", context, "ps", "-aq", "--filter", `label=com.docker.compose.project=${project}`, "--filter", "label=com.docker.compose.service=search-download"], { ...options, timeout: 10000, capture: true }); + const ids = output.trim() ? output.trim().split(/\s+/) : []; + if (ids.length > 4 || ids.some((id) => !/^[a-f0-9]{12,64}$/.test(id))) throw new Error("Invalid owned container inventory"); + for (const id of ids) { + const text = await execute(["--context", context, "inspect", "--format", "{{json .State}}", id], { ...options, timeout: 5000, capture: true }); + const state = JSON.parse(text); + if (state.Running !== false || state.Restarting !== false || state.Paused !== false || !["exited", "created", "dead"].includes(state.Status)) throw new Error("Owned downloader is still running"); + } + return ids; + }; + const ids = await inventory(); + // Require a stable inventory; cleanup also waits for the cancelled client to close. + await sleep(250, undefined, { signal: options.cleanup ? undefined : signal }); + const finalIds = await inventory(); + if (JSON.stringify(ids.sort()) !== JSON.stringify(finalIds.sort())) throw new Error("Owned downloader inventory changed during cleanup"); + return finalIds; + }; + // A previous invocation can finish its pull but fail cleanup. A released + // process lock or valid model cache does NOT prove its writable downloader is + // stopped. Refuse before any inference/cache access, fetch or indexing. + try { + const ids = await verifyDownloaderStopped(); + log(JSON.stringify({ event: "search-download-preflight", project, context, verified: true, containers: ids.length })); + } catch { + checkCancelled(); + throw cleanupError(); + } const waitReady = async (service) => { for (let attempt = 0; attempt < 20; attempt++) { checkCancelled(); @@ -152,27 +186,10 @@ export async function prepareSearchUnlocked(args, { run = runCommand, fetchImpl // Every command remains independently time-bounded; no deletion or pruning. try { await docker(["stop", "--timeout", "10", "search-download"], { cleanup: true, timeout: 45000, capture: true }); - const inventory = async () => { - const output = await execute(["--context", context, "ps", "-aq", "--filter", `label=com.docker.compose.project=${project}`, "--filter", "label=com.docker.compose.service=search-download"], { cleanup: true, timeout: 10000, capture: true }); - const ids = output.trim() ? output.trim().split(/\s+/) : []; - if (ids.length > 4 || ids.some((id) => !/^[a-f0-9]{12,64}$/.test(id))) throw new Error("Invalid owned container inventory"); - for (const id of ids) { - const text = await execute(["--context", context, "inspect", "--format", "{{json .State}}", id], { cleanup: true, timeout: 5000, capture: true }); - const state = JSON.parse(text); - if (state.Running !== false || !["exited", "created", "dead"].includes(state.Status)) throw new Error("Owned downloader is still running"); - } - return ids; - }; - const ids = await inventory(); - // Recheck after the cancelled startup client has closed and Docker settled. - await sleep(250); - const finalIds = await inventory(); - if (JSON.stringify(ids.sort()) !== JSON.stringify(finalIds.sort())) throw new Error("Owned downloader inventory changed during cleanup"); + const finalIds = await verifyDownloaderStopped({ cleanup: true }); log(JSON.stringify({ event: "search-download-stopped", project, context, verified: true, containers: finalIds.length })); } catch { - const error = new Error(`SEARCH_DOWNLOAD_CLEANUP_FAILED: could not verify search-download stopped in project ${project}, Docker context ${context}. Run the scoped recovery command in docs/semantic-search.md before retrying. No data or volumes were deleted.`); - error.code = "SEARCH_DOWNLOAD_CLEANUP_FAILED"; - throw error; + throw cleanupError(); } })(); if (!cached) try { diff --git a/src/public/index.html b/src/public/index.html index 24efcf1..c4ef0c9 100644 --- a/src/public/index.html +++ b/src/public/index.html @@ -198,7 +198,7 @@

Search by meaning

- Optional setup: npm run search:prepare -- --local-sites. Core keyword browsing does not require a model. + Codespaces prepares search automatically on startup; the core workshop stays usable while it loads. Retry or laptop-local setup: npm run search:prepare -- --local-sites. Refresh after SEARCH READY.