Nota — a free DAW for macOS, Windows and Linux. No subscription, no account — just open it and make music.
C# audioaudio-unitavaloniacpp20cross-platformdawdigital-audio-workstationdspjucelinux-audiomcp-servermidimusicmusic-productionpiano-rollplugin-hostsequencersynthesizervstvst3
(fix) Plugin scans finish, and large plugin folders scan in minutes (#256)
Egor Khindikaynen724b363b5765
diff --git a/.specify/bugs/plugin-scan-hang-windows/assessment.md b/.specify/bugs/plugin-scan-hang-windows/assessment.mdnew file mode 100644index 00000000..4efa4874--- /dev/null+++ b/.specify/bugs/plugin-scan-hang-windows/assessment.md@@ -0,0 +1,155 @@+# Bug Assessment: Plugin scan hangs forever on Windows ("Scanning Analytiks…")++- **Slug**: plugin-scan-hang-windows+- **Created**: 2026-10-21+- **Source**: https://github.com/nota-daw/nota/issues/220 (host: github.com — allowlisted, read via `gh issue view`) + follow-up details from the reporter relayed by the maintainer+- **Verdict**: valid (scan-never-finishes mechanism confirmed in code; the specific plugin that wedges the worker is not yet identified)+- **Severity**: high++## Report (verbatim or summarized)++Issue #220, "Plug-in scan doesn't work on Windows 11 (0.56.1)": the plug-in scan does+not pick up installed plug-ins, so none show up in the browser. Windows 11 x64, Intel+Core i5, 24 GB RAM. No log attached.++Follow-up from the reporter (relayed in chat, with two screenshots):++- Preferences scan path: `C:\Users\tuned\AppData\Roaming\Nota\plugins\VST3` (the+ Get Plug-ins store folder).+- App installed at `C:\Program Files\Nota\Nota.App.exe`. No antivirus.+- After downloading a plug-in from Get Plug-ins, the job hangs indefinitely on+ "Scanning Analytiks…" (the progress bar never finishes).++## Symptom++On Windows, after a Get Plug-ins install (and likewise on Rescan) the plug-in scan+never returns: the job stays on "Scanning <name>…" forever, the catalog is never saved+and the browser is never rebuilt, so installed plug-ins never show up. Expected: each+plug-in is probed within a bounded time (a hanging one is killed and skipped after+30 s), the scan finishes and the browser lists what was found.++## Reproduction++1. Windows 11 x64, Nota 0.56.1, installed under `C:\Program Files\Nota`.+2. Preferences → Get Plug-ins → install a plug-in (reported: Analytiks).+3. The job shows "Scanning Analytiks…" and never completes.++The label is misleading: `RescanAfterStoreChange` runs a **full** rescan of every scan+path plus the default VST3 location (`C:\Program Files\Common Files\VST3`), so the+plug-in that wedges the worker may be any not-yet-catalogued one on that machine,+not necessarily Analytiks.++[NEEDS CLARIFICATION: which plug-ins are in `C:\Program Files\Common Files\VST3`; is a+`nota-scanworker.exe` process left running in Task Manager while the job hangs, and+does it carry the path of a specific `.vst3` on its command line?]++## Suspected Code Paths++- `src/native/nota.engine/pluginhost/scanner/OutOfProcessScanner.cpp:scanDescriptions()`+ — the per-plug-in timeout is checked only *between* `proc.readProcessOutput(buf, 8192)`+ calls. That call does not return early:+ - Windows (`juce_core/native/juce_Threads_windows.cpp`, `ActiveProcess::read`): loops+ with `PeekNamedPipe` + `Sleep(1)` until **all 8192 bytes** are read or the child+ stops running.+ - POSIX (`juce_SharedCode_posix.h`, `ActiveProcess::read`): `fread(…, 8192)` on the+ pipe, which likewise blocks until 8192 bytes or EOF.+ The worker's whole output is far below 8 KB, so the first read blocks until the+ worker exits. If the worker never exits, the `deadline` check is never reached and+ `proc.kill()` never runs — the 30 s timeout is dead code on every platform.+- `src/native/nota.engine/pluginhost/scanner/abi_pluginscanner.cpp:nota_pluginhost_scan()`+ — scans plug-ins serially and only calls `catalog.save()` at the end, so one stuck+ worker blocks the whole scan and nothing found earlier is persisted.+- `src/native/nota.engine/pluginhost/scanner/worker/PluginScannerWorker.cpp` — prints the+ sentinel block and returns from `main`; the process then runs plug-in unload / static+ teardown (`ScopedJuceInitialiser_GUI` destructor, `FreeLibrary` of the `.vst3`). A+ plug-in that deadlocks during unload, waits on a hidden dialog (activation, licence,+ first-run), or blocks inside `findAllTypesForFile` keeps the worker alive forever.+ The worker is started with `CREATE_NO_WINDOW` and the parent shows nothing about it.+- `src/managed/Nota.App/PluginScan.cs:RescanAsync()` and+ `src/managed/Nota.App/PreferencesWindow.Store.cs:InstallFromStore()` — `await+ Task.Run(() => catalog.Scan(worker))` with no cancellation or timeout, so the store job+ waits on the native call indefinitely.+- `src/native/nota.engine/pluginhost/scanner/PluginCatalog.cpp:unknownIds()` — a plug-in+ whose probe failed or timed out is not remembered, so it is re-probed (and costs the+ full timeout) on every scan.++## Root Cause Hypothesis++`OutOfProcessScanner::scanDescriptions` relies on `juce::ChildProcess::readProcessOutput`+returning promptly, but both JUCE implementations block until the requested 8 KB are+read or the child exits. Any `nota-scanworker.exe` that does not exit — a plug-in that+hangs during probing, waits on an invisible modal, or deadlocks on unload after the+sentinel was already printed — therefore hangs the whole scan forever instead of being+killed after 30 s. Confidence: **high** that this is why the scan never ends (the timeout+cannot fire); **medium** on which plug-in, and in which phase, keeps the worker alive on+the reporter's machine (Windows VST3 plug-ins hanging in `DllMain`/static teardown on+process exit is a well-known pattern, and the bug is long-standing: the same loop existed+in the former `PluginHost.cpp`).++## Proposed Remediation++**Preferred**: make the per-plug-in timeout real and stop waiting once the answer is in.++1. In `scanDescriptions`, move the pipe draining off the waiting thread: a reader+ (`std::thread` or `juce::Thread`) loops `readProcessOutput` into a buffer guarded by+ a mutex and signals when the buffer contains `<<<NOTA_PLUGINS_END>>>` or the read+ returns 0. The caller waits on that signal with the deadline. On the END sentinel →+ parse the result, `proc.kill()` if still running (the answer is in; a hang at exit no+ longer matters). On deadline → `proc.kill()` (which unblocks the read on both+ platforms: `TerminateProcess` stops `isRunning()`, SIGKILL gives EOF), join the reader,+ return empty.+2. In the worker, after printing and flushing the sentinel block, terminate immediately+ (`std::_Exit(0)` / `TerminateProcess(GetCurrentProcess(), 0)` on Windows) instead of+ returning through plug-in unload and static destructors.+3. Log one line per probe (format, path, ms, outcome: ok / no types / timeout / crash) to+ the engine log, so the next report names the plug-in that misbehaves.++**Alternatives**:+- Read 1 byte at a time in the existing loop — does not help: a 1-byte read still blocks+ while the pipe is empty and the child is alive.+- Windows-only `PeekNamedPipe` before each read via our own process wrapper — fixes+ Windows, but POSIX keeps the same latent hang; the reader-thread approach covers both.+- Remember timed-out / crashed plug-ins in a "failed" list in the catalog (JUCE's+ `KnownPluginList::addToBlacklist` / dead-man's-pedal style) so later scans skip them+ until the file changes, and show them in Preferences — worthwhile follow-up, not+ required to stop the hang.+- Make the managed scan cancellable and report "Scanning <plug-in>…" per plug-in (needs a+ progress callback across the C ABI) — better UX, larger change.++**Files likely to change**:+- `src/native/nota.engine/pluginhost/scanner/OutOfProcessScanner.cpp`+- `src/native/nota.engine/pluginhost/scanner/OutOfProcessScanner.h` (if the timeout+ becomes injectable for tests)+- `src/native/nota.engine/pluginhost/scanner/worker/PluginScannerWorker.cpp`+- `src/native/nota.engine/pluginhost/scanner/abi_pluginscanner.cpp` (per-probe logging)++**Tests to add or update**:+- Native test: point `OutOfProcessScanner` (short timeout, e.g. 500 ms) at a stub+ "worker" that prints nothing and sleeps forever → `scanDescriptions` returns empty+ within ~timeout and the child is gone.+- Native test: stub that prints a valid sentinel block and then sleeps forever →+ returns the parsed descriptions promptly, child killed.+- Native test: stub that prints > 8 KB of noise before the sentinel → still parsed.+- Smoke: existing scan path keeps finding the bundled/test plug-ins.++## Risks & Considerations++- Killing the worker right after the END sentinel is safe: the result is already in the+ pipe buffer and fully read before the kill.+- Reader thread lifetime: always join after kill; on Windows the read loop exits once+ `isRunning()` is false, on POSIX once EOF is seen.+- `std::_Exit` in the worker skips flushing — flush `std::cout` explicitly first (the+ current `std::endl` already does).+- No ABI change; managed side untouched for the preferred fix.+- Performance: one extra thread per probe, negligible next to process spawn.+- This does not explain *why* the worker hangs on the reporter's machine; logging (step 3)+ is what will name the plug-in if the scan still reports a timeout.++## Open Questions++- [NEEDS CLARIFICATION: logs from `%APPDATA%\Nota\logs\` and the list of VST3 plug-ins on+ the reporter's machine — is Analytiks itself the hanging plug-in, or one in+ `C:\Program Files\Common Files\VST3`?]+- [NEEDS CLARIFICATION: is `nota-scanworker.exe` still running in Task Manager during the+ hang, and does ending it let the scan continue? This would confirm the hypothesis on the+ user's machine without a new build.]diff --git a/.specify/bugs/plugin-scan-hang-windows/fix.md b/.specify/bugs/plugin-scan-hang-windows/fix.mdnew file mode 100644index 00000000..179d2867--- /dev/null+++ b/.specify/bugs/plugin-scan-hang-windows/fix.md@@ -0,0 +1,113 @@+# Bug Fix: Plugin scan hangs forever on Windows ("Scanning Analytiks…")++- **Slug**: plugin-scan-hang-windows+- **Fixed**: 2026-10-22+- **Assessment**: ./assessment.md+- **Status**: applied (Windows run not verified locally — covered by CI's `build-win.ps1`)++## Summary++The per-plugin scan timeout now actually fires, and a worker that has already answered is+not waited for. After the reporter said they have **about 1000 plugins**, the scope grew+(agreed with the maintainer) to make a large first scan finish in reasonable time and+visibly. The scan now:++- runs four probes in parallel, and retries the timeouts on its own afterwards;+- saves as it goes;+- remembers failed plugins;+- reports progress;+- after a store install, scans only the store folder;+- writes one log line per probe to `logs/plugin-scan.log`.++While load-testing the parallel scan we found a JUCE POSIX bug (an fd closed twice).+Because of it, the macOS/Linux scanner now spawns workers itself instead of through+`juce::ChildProcess`.++## Changes++| File | Change | Notes |+|------|--------|-------|+| `src/native/nota.engine/pluginhost/scanner/OutOfProcessScanner.cpp` | rewritten | **POSIX**: `posix_spawn`; pipe is `FD_CLOEXEC` (plus `POSIX_SPAWN_CLOEXEC_DEFAULT` on macOS); stdin/stderr go to `/dev/null`; SIGPIPE/SIGCHLD reset to default; `poll()` loop with the deadline; stops at the end sentinel; `waitpid` only on its own pid; SIGKILL only while unreaped; always reaped (no zombies); exit code or signal goes to the log. **Windows**: `juce::ChildProcess`; the pipe is drained 1 byte at a time on a reader thread; the caller waits with the deadline, then kills the worker; spawns are serialised |+| `src/native/nota.engine/pluginhost/scanner/OutOfProcessScanner.h` | modified | `Outcome` enum (`Ok` / `Timeout` / `NoAnswer` / `StartFailed`); optional `outcome` / `detail` out-params |+| `src/native/nota.engine/pluginhost/scanner/worker/PluginScannerWorker.cpp` | modified | `exitNow(0)` right after printing: `TerminateProcess` on Windows (skips DLL detach), `_Exit` elsewhere |+| `src/native/nota.engine/pluginhost/scanner/abi_pluginscanner.cpp` | rewritten scan | <ul><li>Discovery builds a single probe list; up to 4 workers (`hw/2`, at least 1) pull from it.</li><li>Timeouts and missing answers in the parallel pass are retried one at a time with the full timeout before they count as failures.</li><li>Catalog and failed list are saved every 5 s and at the end.</li><li>Progress counters and the current name are kept in atomics behind a scan mutex (one scan at a time).</li><li>`only_dir` scans only VST3 in that folder.</li><li>`NOTA_SCAN_RETRY_FAILED` clears the failed list.</li><li>`ScanLog` is thread-safe.</li></ul> |+| `src/native/nota.engine/pluginhost/scanner/PluginCatalog.{h,cpp}` | modified | `scan-failed.txt`: id → file mtime. `unknownIds` skips a failed id while its mtime is unchanged. `markFailed` / `forgetFailed` / `clearFailed` / `failedCount`. Entries for deleted bundles are pruned. `scanLogPath()` |+| `src/native/nota.engine/include/nota/nota_engine.h` | modified | New `nota_pluginhost_scan_ex(worker, only_dir, flags)`, `nota_pluginhost_scan_progress(&done, &total)`, `nota_pluginhost_scan_current()`, `nota_pluginhost_scan_failed_count()`, `NOTA_SCAN_RETRY_FAILED`. `nota_pluginhost_scan` is unchanged and wraps `_ex` |+| `src/managed/Nota.Infrastructure/Interop/{NativeMethods,NotaEngine}.PluginHost.cs`, `PluginCatalog.cs` | modified | P/Invoke for the new calls; `ScanPlugins(worker, onlyDir, retryFailed)`, `ScanProgress`, `ScanFailedCount` |+| `src/managed/Nota.Application/Ports/IPluginCatalog.cs` | modified | New members are default-implemented, so the test fakes are unchanged; `PluginScanProgress` record |+| `src/managed/Nota.App/PluginScan.cs` | modified | `RescanAsync(main, progress, onlyDir, retryFailed)` polls progress every 250 ms; `Describe` / `Fraction` |+| `src/managed/Nota.App/PreferencesWindow.cs` | modified | **Rescan plugins** retries failed plugins and shows "Scanning plugins · 312 of 1,000 · Name". Final line: "Found N plugins. K couldn't be loaded — see plugin-scan.log…" |+| `src/managed/Nota.App/PreferencesWindow.Store.cs` | modified | Install/remove scans only `PluginsDir`, with a determinate fraction in the Downloads job |+| `src/managed/Nota.App/MainWindow.MissingPlugins.cs` | modified | Same scoped scan and progress |+| `src/native/nota.engine/pluginhost/scanner/tests/ScannerSelfTest.cpp`, `CMakeLists.txt` | added test | `nota-scanner-selftest` |+| `tests/Nota.SmokeTest/PluginStoreTests.cs`, `Program.cs` | added test | `--scan-scale <worker>` (needs a scratch `NOTA_DATA_DIR`) |+| `scripts/build.sh`, `build-linux.sh`, `build-win.ps1` | modified | Run the self-test after the native build, and `--scan-scale` in a scratch data dir after the smoke test, on all three CI OSes |+| `CHANGELOG.md` | modified | `[Unreleased] → Fixed` entry, kept beside #245's entry (conflict resolved) |++## Tests Added or Updated++**`nota-scanner-selftest`** (1.5 s timeout, the binary acts as its own stub worker):+- `ok`, `hang` (→ Timeout), `answer-then-hang` (→ Ok, fast), `noisy` (20 KB before the answer), `die` (→ NoAnswer, fast), missing worker.+- **8 probes in parallel** with mixed modes: each gets the right outcome, all within timeout + slack.+- **No unreaped children** (POSIX `waitpid(-1)` → ECHILD).++**`Nota.SmokeTest --scan-scale`**, against the real worker and 40 empty `.vst3` bundles:+- A folder-only scan probes exactly those 40 (no AU).+- The probes run in parallel.+- Progress counts up while the scan runs and clears afterwards.+- All 40 are remembered as failed.+- The next scan probes 0.+- A touched bundle is probed again.+- Retry probes all 40.+- Deleted bundles are forgotten.++## Local Verification (macOS, Release)++- `nota-scanner-selftest` → PASSED, 6 runs in a row; the parallel case takes about 1.56 s.+- `--scan-scale` → SCAN SCALE PASSED.+- Real full scan of this Mac (57 AU + 14 VST3), scratch data dir:+ - all 72 plugins found;+ - **about 10 s**, versus 49 s for the serial scan before.+- Headless Avalonia harness (`/tmp/scanharness`): Preferences → Plug-ins → **Rescan plugins**, with 300 fake bundles added to the real plugins (371 candidates).+ - Progress line: "Scanning plugins · 111 of 371 · Synth 124".+ - Final line: "Found 72 plugins. 300 couldn't be loaded — see plugin-scan.log in Nota's logs folder."+ - About 9 s per run.+ - Screenshots: `/tmp/scanharness/shots/rescan-{progress,done}.png`.+- **Harness runs before the POSIX spawn rewrite**:+ - 5–16 of 371 probes per run came back "no answer" (0 bytes, pipe closed while the worker was alive; once even exit code 0 with 0 bytes);+ - in one run Kontakt AU (`NiK8`) timed out.+- **After the rewrite**: 4 runs in a row, 0 retries, 0 failures among real plugins.+- `dotnet build Nota.sln -c Release` → succeeded.+- **Full smoke test**: everything passes except two `RenderPoolTests` "overloaded" timing checks (new in #245, pulled during this work).+ - A/B with `--perf`, alternating the base `develop` engine and this branch's engine under the same load (load average about 7: Rider, a Debug Nota.App and GitKraken running):+ - base: pass, pass, **fail** (32 late blocks);+ - new: pass, **fail** (43), pass.+ - Same flakiness on both, so not caused by this change. Re-check on an idle machine or in CI.+- **Scan timing, develop vs this branch** (371 candidates: 57 AU + 14 VST3 + 300 empty bundles; details in `pr-assets/issue-220/summary.md`):+ - Kontakt loading fast: 46.4 s → 13.3 s; both find 72.+ - Kontakt slow (~32 s per load), 3 interleaved runs: about 103 s vs 100 s; develop finds 70 (loses both Kontakt 8), the branch finds 72.+- `scripts/build.sh` on the final tree:+ - scanner self-test PASSED;+ - smoke: 3839 passed, 2 failed (the RenderPoolTests "overloaded" flake above; load average up to 12.8);+ - the script stops there, so `--scan-scale` was run by hand → PASSED.+- **Not verified locally**: the Windows code paths (`TerminateProcess` in the worker, the reader-thread probe, the build). CI's `build-win.ps1` now builds them and runs the self-test and `--scan-scale`.+- **Not verified on Linux**: the worker under a headless CI runner (JUCE GUI init without a display) for `--scan-scale`. If it fails there, that step needs `xvfb-run` or a Linux skip.++## Deviations from Assessment++- **Scope extended** after the "1000 plugins" follow-up (maintainer's decision): parallel probes, incremental save, a remembered-failures list, a progress ABI with UI, and store-folder-only scans. Some of these were listed in the assessment as alternatives or follow-ups. This adds new C ABI functions; the existing ones are unchanged.+- **POSIX no longer uses `juce::ChildProcess`.** JUCE 8.0.14's POSIX `ActiveProcess::~ActiveProcess` calls `fclose(readHandle)` and then `close(pipeHandle)` on the same fd. Under concurrency that second close hits another thread's newly opened fd, which corrupts sibling probes. It could also, in principle, close an unrelated file or socket of the app; that risk existed at lower odds with the old serial scan too. Not found in the assessment.+- **The final attempt gets 2 minutes.** Kontakt 8 took 32 s alone on a bad day (3 s otherwise); with 30 s it would have been remembered as failed. The parallel pass keeps 30 s; the one-at-a-time retry, and a single-plugin scan such as a store install, get 120 s.+- **Progress shows no name for an AU.** Its id (`Synths/aumu,Ni$D,-NI-`) means nothing to a user before it loads; a VST3 shows its bundle name.+- **Serial retry** of timeouts and missing answers. Without it, parallel load made heavy plugins (NI Kontakt AU) miss the 30 s deadline, and the failed list would have hidden them for good.+- **Fallback parse of output without the sentinel dropped.** The worker always prints the sentinel.+- **Log location**: `<data dir>/logs/plugin-scan.log`, written by the engine itself, rather than the app's daily log. This avoids a logging callback across the ABI.+- **A native test executable** instead of a test framework; the project has no native unit-test harness.++## Follow-ups++- Docs: `../nota-docs` pages `plugins/scanning.mdx`, `preferences/plugins.mdx` and `reference/troubleshooting.mdx` (EN + RU) should describe the progress line, the skipped-failures behaviour, Rescan retrying them, and where `plugin-scan.log` lives (nota-docs skill).+- Ask the reporter (issue #220) to try a build with this fix and attach `%APPDATA%\Nota\logs\plugin-scan.log`.+- Consider a Preferences list of the plugins that failed, with a per-plugin retry.+- Consider reporting the JUCE double close upstream.+- Drop `stash@{0}` ("Auto stash before merge of develop and origin/develop", GitKraken's backup from 09:19) once the branch is reviewed. Its content is an older snapshot of this same work.diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 81678401..5a45e13f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -96,6 +96,17 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.on one thread, up to 4x slower. On macOS the engine also no longer wakes every renderthread when a block needs only a few, and a session that overloads one core no longerdrops out every two seconds while it plays.+- **Plug-in scans finish, and large plug-in folders scan in minutes** (nota-daw/nota#220): the+ 30-second limit per plug-in never took effect, so one plug-in that froze while being probed —+ or on unload, after it had already answered — left "Scanning…" up for good, and nothing found+ was saved. Now a stuck plug-in is stopped after 30 seconds and retried once on its own, with+ two minutes to load; plug-ins are probed four at a time; the scan shows how far it is+ ("Scanning plugins · 312 of 1,000"); what it found is saved as it goes, so a scan cut short+ resumes; plug-ins that fail to load are remembered and skipped until they change (Rescan+ plugins retries them); a Get Plug-ins install scans only its own folder; and each scan writes+ `logs/plugin-scan.log` in Nota's data folder, naming every plug-in probed and how it went.+ macOS and Linux: parallel scans no longer lose a plug-in's answer to a file descriptor closed+ twice by the process helper.- **⌘D in the piano roll no longer piles copies at the clip's end** when the selection islonger than the room left after it: copies continue into the next open clip of the track,and those with no clip to land in are left out.diff --git a/FEATURES.md b/FEATURES.mdindex 61774d58..af156300 100644--- a/FEATURES.md+++ b/FEATURES.md@@ -901,7 +901,10 @@ audio effects after it keep running and keep their settings; saved with the proj- **AU** (macOS) and **VST3** (all platforms) — instruments and effects.- **Scanning** and a catalogue of installed plugins (a separate `nota-scanworker`), scan- paths in Preferences, and Rescan.+ paths in Preferences, and Rescan. Four plugins load at a time, each with a time limit+ (a stuck one is retried alone, then skipped); progress shows as "312 of 1,000"; results+ are saved as the scan goes; plugins that failed are skipped until they change or a Rescan;+ each scan writes `logs/plugin-scan.log`.- **Downloads** (Settings → Downloads, formerly Get Plug-ins) — open-source VST3 pluginsfrom the [Nota plugin registry](https://github.com/nota-daw/nota-plugins-registry)(Surge XT, Dexed, Dragonfly Reverb, CHOW Tape Model, Stochas …), installed, updated anddiff --git a/scripts/build-linux.sh b/scripts/build-linux.shindex f4cbd82d..d756e8bf 100755--- a/scripts/build-linux.sh+++ b/scripts/build-linux.sh@@ -41,10 +41,17 @@ cmake -G Ninja -S src/native/nota.engine -B "${NATIVE}" \-DCMAKE_BUILD_TYPE=Releasecmake --build "${NATIVE}"+echo "==> Scanner self-test"+"${NATIVE}/nota-scanner-selftest"+echo "==> Building managed (.NET)"dotnet build Nota.sln -c Release --nologoecho "==> Smoke test"dotnet run --project tests/Nota.SmokeTest -c Release --nologo+echo "==> Plugin scan check (large folders, scratch data dir)"+NOTA_DATA_DIR="$(mktemp -d /tmp/nota-scan-scale-XXXX)" dotnet tests/Nota.SmokeTest/bin/Release/net10.0/Nota.SmokeTest.dll \+ --scan-scale "$PWD/${NATIVE}/nota-scanworker"+echo "==> Done. Run the app with: dotnet run --project src/managed/Nota.App"diff --git a/scripts/build-win.ps1 b/scripts/build-win.ps1index 290868ac..bb5cad45 100644--- a/scripts/build-win.ps1+++ b/scripts/build-win.ps1@@ -17,10 +17,18 @@ Write-Host "==> Building native engine (x64/WASAPI)"cmake -G Ninja -S src/native/nota.engine -B $Native "-DCMAKE_BUILD_TYPE=Release"cmake --build $Native+Write-Host "==> Scanner self-test"+& "$Native/nota-scanner-selftest.exe"+Write-Host "==> Building managed (.NET)"dotnet build Nota.sln -c Release --nologoWrite-Host "==> Smoke test"dotnet run --project tests/Nota.SmokeTest -c Release --nologo+Write-Host "==> Plugin scan check (large folders, scratch data dir)"+$env:NOTA_DATA_DIR = Join-Path ([System.IO.Path]::GetTempPath()) ("nota-scan-scale-" + [guid]::NewGuid().ToString('N'))+dotnet tests/Nota.SmokeTest/bin/Release/net10.0/Nota.SmokeTest.dll --scan-scale (Resolve-Path "$Native/nota-scanworker.exe").Path+Remove-Item Env:NOTA_DATA_DIR+Write-Host "==> Done. Run the app with: dotnet run --project src/managed/Nota.App"diff --git a/scripts/build.sh b/scripts/build.shindex cd554aaa..35c00415 100755--- a/scripts/build.sh+++ b/scripts/build.sh@@ -13,6 +13,9 @@ echo "==> Building native engine (universal arm64+x86_64)"cmake -G Ninja -S src/native/nota.engine -B src/native/nota.engine/build \-DCMAKE_BUILD_TYPE=Releasecmake --build src/native/nota.engine/build++echo "==> Scanner self-test"+src/native/nota.engine/build/nota-scanner-selftestlipo -info src/native/nota.engine/build/libnota_engine.dylibecho "==> Building managed (.NET)"@@ -21,4 +24,8 @@ dotnet build Nota.sln -c Release --nologoecho "==> Smoke test"dotnet run --project tests/Nota.SmokeTest -c Release --nologo+echo "==> Plugin scan check (large folders, scratch data dir)"+NOTA_DATA_DIR="$(mktemp -d /tmp/nota-scan-scale-XXXX)" dotnet tests/Nota.SmokeTest/bin/Release/net10.0/Nota.SmokeTest.dll \+ --scan-scale "$PWD/src/native/nota.engine/build/nota-scanworker"+echo "==> Done. Run the app with: dotnet run --project src/managed/Nota.App"diff --git a/src/managed/Nota.App/MainWindow.MissingPlugins.cs b/src/managed/Nota.App/MainWindow.MissingPlugins.csindex 844a29b9..61ab94a6 100644--- a/src/managed/Nota.App/MainWindow.MissingPlugins.cs+++ b/src/managed/Nota.App/MainWindow.MissingPlugins.cs@@ -53,7 +53,8 @@ public partial class MainWindowcatch (StoreException e) { error ??= e.Message; }}prog.Report(ProgressReport.Indeterminate("Scanning plugins…"));- await PluginScan.RescanAsync(_vm);+ await PluginScan.RescanAsync(_vm, new Progress<PluginScanProgress>(s =>+ prog.Report(new ProgressReport(PluginScan.Fraction(s), PluginScan.Describe(s)))), onlyDir: store.PluginsDir);});if (error is not null) { _vm.StatusText = error; return; }diff --git a/src/managed/Nota.App/PluginScan.cs b/src/managed/Nota.App/PluginScan.csindex a6a2d278..aab4ee98 100644--- a/src/managed/Nota.App/PluginScan.cs+++ b/src/managed/Nota.App/PluginScan.cs@@ -36,13 +36,38 @@ internal static class PluginScan}/// <summary>Rescans off the UI thread, then rebuilds the browser lists. Returns the number- /// of known plugins, or null when the scan worker is missing.</summary>- public static async Task<int?> RescanAsync(MainWindowViewModel main)+ /// of known plugins, or null when the scan worker is missing. <paramref name="onlyDir"/>+ /// limits the search to one folder (a store install); <paramref name="retryFailed"/>+ /// probes plugins that failed before again (an explicit Rescan). While the scan runs,+ /// <paramref name="progress"/> gets its state a few times a second on the calling thread.</summary>+ public static async Task<int?> RescanAsync(MainWindowViewModel main, IProgress<PluginScanProgress>? progress = null,+ string? onlyDir = null, bool retryFailed = false){if (WorkerPath is not { } worker) return null;var catalog = App.Services.GetRequiredService<IPluginCatalog>();- int n = await Task.Run(() => catalog.Scan(worker));+ var scan = Task.Run(() => catalog.Scan(worker, onlyDir, retryFailed));+ if (progress is not null)+ {+ // A first scan of a large plugin folder takes minutes: keep showing that it moves.+ while (!scan.IsCompleted)+ {+ await Task.WhenAny(scan, Task.Delay(250));+ if (catalog.ScanProgress is { } p) progress.Report(p);+ }+ }+ int n = await scan;main.Browser.Rebuild();return n;}++ /// <summary>Status line for a running scan, e.g. "Scanning plugins · 312 of 1,000 · Analytiks".</summary>+ public static string Describe(PluginScanProgress p)+ {+ if (p.Total == 0) return "Looking for plugins…";+ var line = $"Scanning plugins · {p.Done:N0} of {p.Total:N0}";+ return p.Current.Length > 0 ? $"{line} · {p.Current}" : line;+ }++ /// <summary>Share of the scan done, or -1 while the total isn't known yet.</summary>+ public static double Fraction(PluginScanProgress p) => p.Total > 0 ? (double)p.Done / p.Total : -1;}diff --git a/src/managed/Nota.App/PreferencesWindow.Store.cs b/src/managed/Nota.App/PreferencesWindow.Store.csindex 49e94932..244d16ba 100644--- a/src/managed/Nota.App/PreferencesWindow.Store.cs+++ b/src/managed/Nota.App/PreferencesWindow.Store.cs@@ -516,12 +516,13 @@ public sealed partial class PreferencesWindowprivate void InstallFromStore(StorePlugin p){var main = _main;+ var dir = _store.PluginsDir;Jobs.Install(p.Id, source: 0, p.Name, p.Asset?.Size ?? 0, new StoreProgress(0, $"Downloading {p.Name}…"),(progress, ct) => _store.InstallAsync(p, progress, ct),async () =>{Jobs.Report(new StoreProgress(-1, $"Scanning {p.Name}…"));- return await RescanAfterStoreChange(main)+ return await RescanAfterStoreChange(main, dir, $"Scanning {p.Name}…")? $"{p.Name} {p.Version} is installed — find it in the browser.": $"{p.Name} is installed. Rescan plugins to use it.";});@@ -535,18 +536,22 @@ public sealed partial class PreferencesWindow"Remove", "Cancel").ShowDialog<bool>(this);if (!ok) return;var main = _main;+ var dir = _store.PluginsDir;Jobs.Remove(p.Id, source: 0, $"Removing {p.Name}…", async () =>{_store.Uninstall(p.Id);- await RescanAfterStoreChange(main);+ await RescanAfterStoreChange(main, dir, $"Removing {p.Name}…");return $"{p.Name} was removed.";});}- // Static: the job can outlive this window.- private static async Task<bool> RescanAfterStoreChange(MainWindowViewModel? main)+ // Static: the job can outlive this window. Only the store's folder is searched — a store+ // install must not set off a scan of every plugin on the machine (nota-daw/nota#220).+ private static async Task<bool> RescanAfterStoreChange(MainWindowViewModel? main, string storeDir, string label){if (main is null) return false;- return await PluginScan.RescanAsync(main) is not null;+ var progress = new Progress<PluginScanProgress>(s =>+ Jobs.Report(new StoreProgress(PluginScan.Fraction(s), s.Total > 1 ? $"{label} {s.Done} of {s.Total}" : label)));+ return await PluginScan.RescanAsync(main, progress, onlyDir: storeDir) is not null;}}diff --git a/src/managed/Nota.App/PreferencesWindow.cs b/src/managed/Nota.App/PreferencesWindow.csindex d92ddaaa..93d6c37b 100644--- a/src/managed/Nota.App/PreferencesWindow.cs+++ b/src/managed/Nota.App/PreferencesWindow.cs@@ -708,8 +708,13 @@ public sealed partial class PreferencesWindow : NotaWindowrescanStatus.Text = $"Searching {folders} folder{(folders == 1 ? "" : "s")}";try{- int? n = await PluginScan.RescanAsync(_main);- rescanStatus.Text = n is { } c ? $"Found {c} plugin{(c == 1 ? "" : "s")}." : "Scanner worker not found.";+ // An explicit Rescan also retries plugins that failed before.+ var progress = new Progress<PluginScanProgress>(p => rescanStatus.Text = PluginScan.Describe(p));+ int? n = await PluginScan.RescanAsync(_main, progress, retryFailed: true);+ int failed = _catalog.FailedCount;+ rescanStatus.Text = n is not { } c ? "Scanner worker not found."+ : $"Found {c:N0} plugin{(c == 1 ? "" : "s")}." ++ (failed > 0 ? $" {failed:N0} couldn't be loaded — see plugin-scan.log in Nota's logs folder." : "");}finally { rescan.IsEnabled = true; rescan.Content = "Rescan plugins"; }};diff --git a/src/managed/Nota.Application/Ports/IPluginCatalog.cs b/src/managed/Nota.Application/Ports/IPluginCatalog.csindex 8e0eec53..f109d2c9 100644--- a/src/managed/Nota.Application/Ports/IPluginCatalog.cs+++ b/src/managed/Nota.Application/Ports/IPluginCatalog.cs@@ -9,6 +9,13 @@ public interface IPluginCatalog{/// <summary>Rescans installed plugins out-of-process. Returns the known count.</summary>int Scan(string workerPath);+ /// <summary>Rescan with options: <paramref name="onlyDir"/> searches just that folder (a store+ /// install); <paramref name="retryFailed"/> probes plugins that failed before again.</summary>+ int Scan(string workerPath, string? onlyDir, bool retryFailed) => Scan(workerPath);+ /// <summary>Progress of the running scan, readable from any thread; null when none runs.</summary>+ PluginScanProgress? ScanProgress => null;+ /// <summary>Plugins that failed to load (crash, hang, nothing inside), skipped until they change.</summary>+ int FailedCount => 0;/// <summary>Number of plugins currently in the catalog.</summary>int Count { get; }/// <summary>Human-readable entry ("Name | Format | inst|fx | Manufacturer | Category"; the category@@ -24,3 +31,7 @@ public interface IPluginCatalogint ScanPathCount { get; }string? ScanPath(int index);}++/// <summary>A running plugin scan: probes finished of <see cref="Total"/> (0 while still+/// searching folders), and a plugin being probed now.</summary>+public readonly record struct PluginScanProgress(int Done, int Total, string Current);diff --git a/src/managed/Nota.Infrastructure/Interop/NativeMethods.PluginHost.cs b/src/managed/Nota.Infrastructure/Interop/NativeMethods.PluginHost.csindex 15d6acbd..e78fceab 100644--- a/src/managed/Nota.Infrastructure/Interop/NativeMethods.PluginHost.cs+++ b/src/managed/Nota.Infrastructure/Interop/NativeMethods.PluginHost.cs@@ -18,6 +18,18 @@ internal static partial class NativeMethods[LibraryImport(Lib, EntryPoint = "nota_pluginhost_scan", StringMarshalling = StringMarshalling.Utf8)]internal static partial int PluginHostScan(string workerPath);+ [LibraryImport(Lib, EntryPoint = "nota_pluginhost_scan_ex", StringMarshalling = StringMarshalling.Utf8)]+ internal static partial int PluginHostScanEx(string workerPath, string? onlyDir, int flags);++ [LibraryImport(Lib, EntryPoint = "nota_pluginhost_scan_progress")]+ internal static partial int PluginHostScanProgress(out int done, out int total);++ [LibraryImport(Lib, EntryPoint = "nota_pluginhost_scan_current")]+ internal static partial IntPtr PluginHostScanCurrent();++ [LibraryImport(Lib, EntryPoint = "nota_pluginhost_scan_failed_count")]+ internal static partial int PluginHostScanFailedCount();+[LibraryImport(Lib, EntryPoint = "nota_pluginhost_plugin_count")]internal static partial int PluginHostPluginCount();diff --git a/src/managed/Nota.Infrastructure/Interop/NotaEngine.PluginHost.cs b/src/managed/Nota.Infrastructure/Interop/NotaEngine.PluginHost.csindex 7482f1cb..feacfc2b 100644--- a/src/managed/Nota.Infrastructure/Interop/NotaEngine.PluginHost.cs+++ b/src/managed/Nota.Infrastructure/Interop/NotaEngine.PluginHost.cs@@ -36,6 +36,31 @@ public sealed partial class NotaEnginereturn n;}+ /// <summary>+ /// <see cref="ScanPlugins(string)"/> with options: <paramref name="onlyDir"/> searches just+ /// that folder for VST3 bundles; <paramref name="retryFailed"/> probes the remembered+ /// failures again. Blocking.+ /// </summary>+ public static int ScanPlugins(string workerPath, string? onlyDir, bool retryFailed)+ {+ int n = NativeMethods.PluginHostScanEx(workerPath, onlyDir, retryFailed ? 1 : 0);+ if (n < 0) throw new NotaEngineException($"Plugin scan failed (code {n}).");+ return n;+ }++ /// <summary>Progress of the running scan (any thread), or null when none runs.</summary>+ public static PluginScanProgress? ScanProgress+ {+ get+ {+ if (NativeMethods.PluginHostScanProgress(out int done, out int total) == 0) return null;+ return new PluginScanProgress(done, total, Marshal.PtrToStringUTF8(NativeMethods.PluginHostScanCurrent()) ?? "");+ }+ }++ /// <summary>Remembered failed candidates, skipped until their file changes.</summary>+ public static int ScanFailedCount => NativeMethods.PluginHostScanFailedCount();+/// <summary>Number of plugins currently in the catalog.</summary>public static int PluginCount => NativeMethods.PluginHostPluginCount();diff --git a/src/managed/Nota.Infrastructure/Interop/PluginCatalog.cs b/src/managed/Nota.Infrastructure/Interop/PluginCatalog.csindex f75b517f..57f198e8 100644--- a/src/managed/Nota.Infrastructure/Interop/PluginCatalog.cs+++ b/src/managed/Nota.Infrastructure/Interop/PluginCatalog.cs@@ -7,6 +7,9 @@ namespace Nota.Infrastructure;public sealed class PluginCatalog : IPluginCatalog{public int Scan(string workerPath) => NotaEngine.ScanPlugins(workerPath);+ public int Scan(string workerPath, string? onlyDir, bool retryFailed) => NotaEngine.ScanPlugins(workerPath, onlyDir, retryFailed);+ public PluginScanProgress? ScanProgress => NotaEngine.ScanProgress;+ public int FailedCount => NotaEngine.ScanFailedCount;public int Count => NotaEngine.PluginCount;public string? Description(int index) => NotaEngine.PluginDescription(index);public string? Id(int index) => NotaEngine.PluginId(index);diff --git a/src/native/nota.engine/CMakeLists.txt b/src/native/nota.engine/CMakeLists.txtindex dcff1c35..bed2833c 100644--- a/src/native/nota.engine/CMakeLists.txt+++ b/src/native/nota.engine/CMakeLists.txt@@ -421,6 +421,23 @@ if(APPLE)target_link_libraries(nota-scanworker PRIVATE "-framework CoreAudioKit")endif()+# --- Scanner self-test (bug plugin-scan-hang-windows) -------------------------+# OutOfProcessScanner against stub workers that hang, die or spam stdout; the+# binary is its own stub. Run by scripts/build*.sh: `nota-scanner-selftest`.+add_executable(nota-scanner-selftest+ pluginhost/scanner/tests/ScannerSelfTest.cpp+ pluginhost/scanner/OutOfProcessScanner.cpp+)+target_include_directories(nota-scanner-selftest PRIVATE pluginhost/scanner)+target_link_libraries(nota-scanner-selftest+ PRIVATE juce::juce_audio_processors+ PUBLIC juce::juce_recommended_config_flags+)+target_compile_definitions(nota-scanner-selftest PRIVATE ${NOTA_JUCE_DEFS})+if(APPLE)+ target_link_libraries(nota-scanner-selftest PRIVATE "-framework CoreAudioKit")+endif()+# --- Nota Pentad as a standalone VST3 (debugging in third-party hosts) -------# Off by default: the app runs Pentad in-process; this wraps the same DSP# (devices/instruments/Pentad.h/.cpp) in a JUCE plugin with the generic editor. Configure withdiff --git a/src/native/nota.engine/include/nota/nota_engine.h b/src/native/nota.engine/include/nota/nota_engine.hindex ffccec02..197d1cce 100644--- a/src/native/nota.engine/include/nota/nota_engine.h+++ b/src/native/nota.engine/include/nota/nota_engine.h@@ -1827,13 +1827,34 @@ NOTA_API int32_t nota_pluginhost_pump(void);/* ---- Plugin scanning & catalog (M3-1, FR-33/NFR-5) ----------------------- *//* Scans installed plugins out-of-process, AudioUnit first then VST3. Each- * candidate is probed in a separate `worker_path` child process with a timeout,- * so a crashing/hanging plugin cannot take down the host. Results are merged- * into the in-memory catalog and persisted to app-support. Blocking; call from- * the message thread. Returns the number of known plugins, or <0 on error.- * `worker_path` is the absolute path to the nota-scanworker executable. */+ * candidate is probed in a separate `worker_path` child process with a timeout+ * (30 s; a candidate that times out or dies is retried alone with 2 min), a few+ * in parallel, so a crashing/hanging plugin cannot take down the+ * host or stall the scan. Results are merged into the in-memory catalog and+ * persisted to app-support as the scan goes. A candidate that yields nothing+ * (crash, timeout, no plugins) is remembered and skipped by later scans until+ * its file changes. One scan runs at a time; a second call waits. Blocking;+ * call off the UI thread. Returns the number of known plugins, or <0 on error.+ * `worker_path` is the absolute path to the nota-scanworker executable.+ * Each scan rewrites <data dir>/logs/plugin-scan.log (one line per probe). */NOTA_API int32_t nota_pluginhost_scan(const char* worker_path);+/* nota_pluginhost_scan with options. `only_dir` (UTF-8, may be NULL): search just+ * this folder for VST3 bundles instead of every location — e.g. after a store+ * install. `flags`: NOTA_SCAN_RETRY_FAILED probes the remembered failures again. */+#define NOTA_SCAN_RETRY_FAILED 1+NOTA_API int32_t nota_pluginhost_scan_ex(const char* worker_path, const char* only_dir, int32_t flags);++/* Progress of the running scan, callable from any thread while it runs: probes+ * finished and probes planned (0 until discovery is done). Returns 1 while a scan+ * runs, 0 otherwise. */+NOTA_API int32_t nota_pluginhost_scan_progress(int32_t* done, int32_t* total);+/* Name of a plugin being probed now (VST3 file name; "" for an AU or when none), UTF-8.+ * Owned by the engine, valid until the next call on the same thread. */+NOTA_API const char* nota_pluginhost_scan_current(void);+/* Number of remembered failed candidates (skipped until their file changes). */+NOTA_API int32_t nota_pluginhost_scan_failed_count(void);+/* Number of plugins in the catalog (after a scan or a load of the saved list). */NOTA_API int32_t nota_pluginhost_plugin_count(void);diff --git a/src/native/nota.engine/pluginhost/scanner/OutOfProcessScanner.cpp b/src/native/nota.engine/pluginhost/scanner/OutOfProcessScanner.cppindex 5556a974..a2606839 100644--- a/src/native/nota.engine/pluginhost/scanner/OutOfProcessScanner.cpp+++ b/src/native/nota.engine/pluginhost/scanner/OutOfProcessScanner.cpp@@ -2,15 +2,273 @@// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.//// OutOfProcessScanner implementation. Mirrors scanOne() in the former-// PluginHost.cpp so the ABI move is behavior-preserving; adds workerAvailable().+// PluginHost.cpp; adds workerAvailable() and a timeout that actually fires.+//+// juce::ChildProcess::readProcessOutput blocks until the requested byte count is+// read or the child exits (Windows: a PeekNamedPipe/Sleep loop; POSIX: fread), so+// a deadline checked between reads never ran while a worker hung — one stuck+// plugin hung the whole scan (bug plugin-scan-hang-windows). Now:+// - POSIX: our own posix_spawn + poll(). JUCE's POSIX ActiveProcess is unusable+// with probes in parallel: its destructor fclose()s the pipe and then close()s+// the same fd number again, closing whatever another thread opened meanwhile+// (a sibling probe's pipe, or any file of the app). Close-on-exec everywhere,+// so a worker never holds another probe's pipe open.+// - Windows: juce::ChildProcess (its handles are closed once each), with the pipe+// drained on a reader thread one byte at a time — so the end sentinel is seen as+// soon as it is written — while this thread waits with the deadline.+// Either way a worker that answered is not waited for: a plugin that deadlocks+// on unload after answering costs nothing.#include "OutOfProcessScanner.h"#include <juce_audio_processors/juce_audio_processors.h>+#include <chrono>+#include <cstring>+#include <mutex>+#include <string>++#if JUCE_WINDOWS+#include <condition_variable>+#include <thread>+#else+#include <cerrno>+#include <csignal>+#include <fcntl.h>+#include <poll.h>+#include <spawn.h>+#include <sys/wait.h>+#include <unistd.h>+#if JUCE_MAC+#include <crt_externs.h>+#endif+#endif++#if !JUCE_WINDOWS && !JUCE_MAC+// Global scope on purpose: declared inside the namespaces below it would name+// nota::scanner::(anonymous)::environ, which nothing defines (the .so fails to link).+extern char** environ;+#endif+namespace nota {namespace scanner {+namespace {++constexpr const char* kBegin = "<<<NOTA_PLUGINS_BEGIN>>>";+constexpr const char* kEnd = "<<<NOTA_PLUGINS_END>>>";+using Outcome = OutOfProcessScanner::Outcome;+using clock = std::chrono::steady_clock;++// What one worker run produced, before parsing.+struct Run {+ Outcome outcome = Outcome::StartFailed;+ std::string output;+ std::string detail;+};++bool endsWithSentinel(const std::string& s, size_t from) {+ const size_t len = std::char_traits<char>::length(kEnd);+ return s.find(kEnd, from > len ? from - len : 0) != std::string::npos;+}++#if JUCE_WINDOWS++// Shared with the reader thread; outlives the call if the reader must be detached.+struct Probe {+ juce::ChildProcess proc;+ std::mutex m;+ std::condition_variable cv;+ std::string output;+ bool answered = false; // end sentinel seen+ bool drained = false; // pipe closed / child gone — reader finished+};++void drain(std::shared_ptr<Probe> p) {+ char c = 0;+ for (;;) {+ const int n = p->proc.readProcessOutput(&c, 1);+ std::lock_guard lock(p->m);+ if (n <= 0) {+ p->drained = true;+ p->cv.notify_all();+ return;+ }+ p->output.push_back(c);+ if (!p->answered && c == '>' && endsWithSentinel(p->output, p->output.size() - 1)) {+ p->answered = true;+ p->cv.notify_all();+ }+ }+}++Run runWorker(const std::string& worker, const std::string& format, const std::string& id, int timeoutMs) {+ Run run;+ auto probe = std::make_shared<Probe>();+ const juce::StringArray cmd{juce::String::fromUTF8(worker.c_str()), juce::String::fromUTF8(format.c_str()),+ juce::String::fromUTF8(id.c_str())};+ {+ // Probes run in parallel; one CreateProcess at a time keeps a child from+ // inheriting another probe's pipe mid-start.+ static std::mutex startMutex;+ std::lock_guard startLock(startMutex);+ if (!probe->proc.start(cmd, juce::ChildProcess::wantStdOut)) return run;+ }++ std::thread reader(drain, probe);+ {+ const auto deadline = clock::now() + std::chrono::milliseconds(timeoutMs);+ std::unique_lock lock(probe->m);+ probe->cv.wait_until(lock, deadline, [&] { return probe->answered || probe->drained; });+ run.outcome = probe->answered ? Outcome::Ok : probe->drained ? Outcome::NoAnswer : Outcome::Timeout;+ run.output = probe->output;+ }+ const bool killed = probe->proc.isRunning();+ if (killed) probe->proc.kill();+ bool drained = false;+ {+ std::unique_lock lock(probe->m);+ drained = probe->cv.wait_for(lock, std::chrono::seconds(2), [&] { return probe->drained; });+ }+ // Pipe still open (a grandchild inherited it): leave the reader blocked on its+ // own copy of the probe rather than hang here.+ if (drained) reader.join();+ else reader.detach();+ if (!killed) run.detail = "exit code " + std::to_string((int)probe->proc.getExitCode());+ return run;+}++#else++char** currentEnvironment() {+#if JUCE_MAC+ return *_NSGetEnviron(); // `environ` isn't reachable from a dylib on macOS+#else+ return ::environ;+#endif+}++// waitpid without blocking. True once the child is gone; `status` is valid when+// `known`. ECHILD (someone else reaped it) counts as gone, status unknown.+bool reaped(pid_t pid, int& status, bool& known) {+ for (;;) {+ const pid_t r = ::waitpid(pid, &status, WNOHANG);+ if (r == pid) {+ known = true;+ return true;+ }+ if (r == 0) return false;+ if (errno == EINTR) continue;+ known = false;+ return true;+ }+}++Run runWorker(const std::string& worker, const std::string& format, const std::string& id, int timeoutMs) {+ Run run;+ int fds[2] = {-1, -1};+ pid_t pid = 0;+ {+ // One spawn at a time: between pipe() and FD_CLOEXEC no sibling may fork.+ static std::mutex startMutex;+ std::lock_guard startLock(startMutex);+ if (::pipe(fds) != 0) return run;+ for (int fd : fds) ::fcntl(fd, F_SETFD, FD_CLOEXEC);++ posix_spawn_file_actions_t actions;+ posix_spawn_file_actions_init(&actions);+ posix_spawn_file_actions_addopen(&actions, 0, "/dev/null", O_RDONLY, 0);+ posix_spawn_file_actions_adddup2(&actions, fds[1], 1);+ posix_spawn_file_actions_addopen(&actions, 2, "/dev/null", O_WRONLY, 0);++ posix_spawnattr_t attr;+ posix_spawnattr_init(&attr);+ short flags = POSIX_SPAWN_SETSIGMASK | POSIX_SPAWN_SETSIGDEF;+#if JUCE_MAC+ flags |= POSIX_SPAWN_CLOEXEC_DEFAULT; // the worker gets stdin/out/err and nothing else+#endif+ posix_spawnattr_setflags(&attr, flags);+ sigset_t none, defaults;+ sigemptyset(&none);+ posix_spawnattr_setsigmask(&attr, &none);+ sigemptyset(&defaults); // the host may ignore these; the worker shouldn't inherit that+ sigaddset(&defaults, SIGPIPE);+ sigaddset(&defaults, SIGCHLD);+ posix_spawnattr_setsigdefault(&attr, &defaults);++ std::string a0 = worker, a1 = format, a2 = id;+ char* argv[] = {a0.data(), a1.data(), a2.data(), nullptr};+ const int err = ::posix_spawn(&pid, worker.c_str(), &actions, &attr, argv, currentEnvironment());+ posix_spawn_file_actions_destroy(&actions);+ posix_spawnattr_destroy(&attr);+ ::close(fds[1]);+ if (err != 0) {+ ::close(fds[0]);+ run.detail = std::string("spawn failed: ") + std::strerror(err);+ return run;+ }+ }++ const auto deadline = clock::now() + std::chrono::milliseconds(timeoutMs);+ int status = 0;+ bool known = false, gone = false, eof = false;+ char buf[4096];+ for (;;) {+ const auto left = std::chrono::duration_cast<std::chrono::milliseconds>(deadline - clock::now()).count();+ if (left <= 0) {+ run.outcome = Outcome::Timeout;+ break;+ }+ if (eof) {+ // stdout closed without the answer: wait for the worker to exit (a crash).+ if ((gone = reaped(pid, status, known))) {+ run.outcome = Outcome::NoAnswer;+ break;+ }+ ::usleep(10000);+ continue;+ }+ pollfd p{fds[0], POLLIN, 0};+ const int r = ::poll(&p, 1, (int)std::min<long long>(left, 100));+ if (r < 0 && errno != EINTR) {+ eof = true;+ continue;+ }+ if (r <= 0) continue;+ const ssize_t n = ::read(fds[0], buf, sizeof buf);+ if (n > 0) {+ const size_t before = run.output.size();+ run.output.append(buf, (size_t)n);+ if (endsWithSentinel(run.output, before)) {+ run.outcome = Outcome::Ok;+ break;+ }+ } else if (n == 0 || (errno != EINTR && errno != EAGAIN)) {+ eof = true;+ }+ }+ ::close(fds[0]);++ // Answered or hung: not waited for. Kill only while it is provably ours and+ // unreaped (a reaped pid may already belong to another process).+ bool killed = false;+ if (!gone && !(gone = reaped(pid, status, known))) {+ ::kill(pid, SIGKILL);+ killed = true;+ // Reap it: a thousand probes must not leave a thousand zombies behind.+ for (int i = 0; i < 200 && !(gone = reaped(pid, status, known)); ++i) ::usleep(10000);+ }+ if (!killed && known) {+ if (WIFEXITED(status)) run.detail = "exit code " + std::to_string(WEXITSTATUS(status));+ else if (WIFSIGNALED(status)) run.detail = "crashed, signal " + std::to_string(WTERMSIG(status));+ }+ return run;+}++#endif++} // namespace+OutOfProcessScanner::OutOfProcessScanner(std::string workerPath, int timeoutMs) noexcept: workerPath_(std::move(workerPath)), timeoutMs_(timeoutMs > 0 ? timeoutMs : kDefaultTimeoutMs) {}@@ -20,54 +278,36 @@ bool OutOfProcessScanner::workerAvailable() const noexcept {}std::vector<std::unique_ptr<juce::PluginDescription>> OutOfProcessScanner::scanDescriptions(- const std::string& formatName, const std::string& fileOrId) const noexcept {+ const std::string& formatName, const std::string& fileOrId, Outcome* outcome, std::string* detail) const noexcept {std::vector<std::unique_ptr<juce::PluginDescription>> out;+ Run run;try {- juce::ChildProcess proc;- juce::StringArray cmd{juce::String::fromUTF8(workerPath_.c_str()), juce::String::fromUTF8(formatName.c_str()),- juce::String::fromUTF8(fileOrId.c_str())};- if (!proc.start(cmd, juce::ChildProcess::wantStdOut)) return out;-- juce::MemoryOutputStream captured;- char buf[8192];- const auto deadline = juce::Time::getMillisecondCounter() + (juce::uint32)timeoutMs_;- while (proc.isRunning()) {- const auto n = proc.readProcessOutput(buf, (int)sizeof(buf));- if (n > 0) captured.write(buf, (size_t)n);- if (juce::Time::getMillisecondCounter() > deadline) {- proc.kill();- return out;+ run = runWorker(workerPath_, formatName, fileOrId, timeoutMs_);+ if (run.outcome == Outcome::Ok) {+ const juce::String text = juce::String::fromUTF8(run.output.data(), (int)run.output.size());+ const int b = text.indexOf(kBegin);+ const int e = text.lastIndexOf(kEnd);+ if (b >= 0 && e > b) {+ if (auto xml = juce::parseXML(text.substring(b + (int)juce::String(kBegin).length(), e))) {+ for (auto* child : xml->getChildIterator()) {+ auto desc = std::make_unique<juce::PluginDescription>();+ if (desc->loadFromXml(*child)) out.push_back(std::move(desc));+ }+ }}- if (n <= 0) juce::Thread::sleep(5);- }- for (;;) {- const auto n = proc.readProcessOutput(buf, (int)sizeof(buf));- if (n <= 0) break;- captured.write(buf, (size_t)n);- }-- const juce::String output = captured.toString();- juce::String xmlText;- const int b = output.indexOf("<<<NOTA_PLUGINS_BEGIN>>>");- const int e = output.lastIndexOf("<<<NOTA_PLUGINS_END>>>");- if (b >= 0 && e > b) {- xmlText = output.substring(b + (int)juce::String("<<<NOTA_PLUGINS_BEGIN>>>").length(), e);} else {- int x = output.indexOf("<?xml");- if (x < 0) x = output.indexOf("<plugins");- if (x >= 0) xmlText = output.substring(x);- }- auto xml = juce::parseXML(xmlText);- if (xml == nullptr) return out;- for (auto* child : xml->getChildIterator()) {- auto desc = std::make_unique<juce::PluginDescription>();- if (desc->loadFromXml(*child)) out.push_back(std::move(desc));+ run.detail = std::to_string(run.output.size()) + " bytes of output" ++ (run.detail.empty() ? "" : ", " + run.detail);}} catch (...) {// A crashing/hanging plugin must never unwind into the caller (AR-7:// no exceptions cross the C ABI; abi_pluginscanner is noexcept).out.clear();+ run.outcome = Outcome::NoAnswer;+ run.detail = "exception in the scanner";}+ if (outcome != nullptr) *outcome = run.outcome;+ if (detail != nullptr) *detail = run.outcome == Outcome::Ok ? std::string() : run.detail;return out;}diff --git a/src/native/nota.engine/pluginhost/scanner/OutOfProcessScanner.h b/src/native/nota.engine/pluginhost/scanner/OutOfProcessScanner.hindex 5e78b373..05687992 100644--- a/src/native/nota.engine/pluginhost/scanner/OutOfProcessScanner.h+++ b/src/native/nota.engine/pluginhost/scanner/OutOfProcessScanner.h@@ -3,7 +3,8 @@//// OutOfProcessScanner — child-process scan coordinator.// Spawns nota-scanworker per undiscovered plugin id, enforces a per-plugin-// timeout, slices the <<<NOTA_PLUGINS_BEGIN>>>..<<<NOTA_PLUGINS_END>>> sentinel+// timeout (the pipe is drained on a reader thread, so a worker that never exits+// is killed on time; once the end sentinel is in, the worker is not waited for), slices the <<<NOTA_PLUGINS_BEGIN>>>..<<<NOTA_PLUGINS_END>>> sentinel// (noisy plugins print to stdout), and parses PluginDescriptions. A crashing or// hanging plugin never takes down the DAW: kill, skip, continue.// No Engine/Track dependency.@@ -26,13 +27,22 @@ class OutOfProcessScanner {public:static constexpr int kDefaultTimeoutMs = 30000;+ // How a probe ended, for the scan log.+ enum class Outcome {+ Ok, // worker answered (possibly with zero types)+ Timeout, // no answer within the timeout — worker killed+ NoAnswer, // worker exited (or crashed) without the sentinel block+ StartFailed, // worker could not be started+ };+explicit OutOfProcessScanner(std::string workerPath, int timeoutMs = kDefaultTimeoutMs) noexcept;// Scan one plugin id (format + fileOrIdentifier) via the worker: full JUCE// descriptions (uid, path hash) for catalog storage. Never throws; returns- // empty on any failure.- std::vector<std::unique_ptr<juce::PluginDescription>> scanDescriptions(- const std::string& formatName, const std::string& fileOrId) const noexcept;+ // empty on any failure; *outcome (optional) says why, *detail (optional) adds+ // what the log needs to tell a crash from a cut-off pipe.+ std::vector<std::unique_ptr<juce::PluginDescription>> scanDescriptions(const std::string& formatName,+ const std::string& fileOrId, Outcome* outcome = nullptr, std::string* detail = nullptr) const noexcept;// Returns false when the worker binary is missing.bool workerAvailable() const noexcept;diff --git a/src/native/nota.engine/pluginhost/scanner/PluginCatalog.cpp b/src/native/nota.engine/pluginhost/scanner/PluginCatalog.cppindex b80c644c..d0e983ad 100644--- a/src/native/nota.engine/pluginhost/scanner/PluginCatalog.cpp+++ b/src/native/nota.engine/pluginhost/scanner/PluginCatalog.cpp@@ -8,6 +8,7 @@#include "PluginCatalog.h"#include <cstdlib>+#include <map>#include "audio_io/NotaConfigFile.h"@@ -22,6 +23,7 @@ struct PluginCatalog::Impl {// (getTypes()), so reads index this instead; sync() after every mutation.std::vector<juce::PluginDescription> types;std::vector<std::string> scanPaths;+ std::map<std::string, int64_t> failed; // id -> file stamp when it failedvoid sync() {const auto all = list.getTypes();types.assign(all.begin(), all.end());@@ -58,6 +60,17 @@ juce::File catalogFile() {juce::File scanPathsFile() {return supportDir().getChildFile("scanpaths.txt");}+juce::File failedFile() {+ return supportDir().getChildFile("scan-failed.txt");+}++// Modification time of a file-based plugin (VST3 path), 0 for registry ids (AU).+int64_t fileStamp(const std::string& id) {+ const juce::String path{juce::CharPointer_UTF8(id.c_str())};+ if (!juce::File::isAbsolutePath(path)) return 0;+ const juce::File f{path};+ return f.exists() ? f.getLastModificationTime().toMilliseconds() : 0;+}} // namespace@@ -177,6 +190,12 @@ void PluginCatalog::removeMissingVst3OnDisk() {if (t.pluginFormatName == "VST3" && !juce::File(t.fileOrIdentifier).exists()) gone.add(t);for (const auto& t : gone) impl_->list.removeType(t);if (!gone.isEmpty()) impl_->sync();+ // Failed bundles that were deleted are no longer worth remembering.+ for (auto it = impl_->failed.begin(); it != impl_->failed.end();) {+ const juce::String path{juce::CharPointer_UTF8(it->first.c_str())};+ if (juce::File::isAbsolutePath(path) && !juce::File(path).exists()) it = impl_->failed.erase(it);+ else ++it;+ }}std::vector<std::string> PluginCatalog::unknownIds(const std::vector<std::string>& discovered) const {@@ -190,11 +209,34 @@ std::vector<std::string> PluginCatalog::unknownIds(const std::vector<std::stringknown = true;break;}- if (!known) out.push_back(id);+ if (known) continue;+ if (auto f = impl_->failed.find(id); f != impl_->failed.end() && f->second == fileStamp(id)) continue;+ out.push_back(id);}return out;}+void PluginCatalog::markFailed(const std::string& id) {+ const auto stamp = fileStamp(id);+ std::unique_lock lock(mutex_);+ impl_->failed[id] = stamp;+}++void PluginCatalog::forgetFailed(const std::string& id) {+ std::unique_lock lock(mutex_);+ impl_->failed.erase(id);+}++void PluginCatalog::clearFailed() {+ std::unique_lock lock(mutex_);+ impl_->failed.clear();+}++int32_t PluginCatalog::failedCount() const {+ std::shared_lock lock(mutex_);+ return static_cast<int32_t>(impl_->failed.size());+}+bool PluginCatalog::typeAt(int32_t index, juce::PluginDescription& out) const {std::shared_lock lock(mutex_);const auto& types = impl_->types;@@ -216,6 +258,37 @@ void PluginCatalog::save() const {if (auto xml = impl_->list.createXml()) xml->writeTo(catalogFile());}+void PluginCatalog::loadFailedOnce() {+ std::unique_lock lock(mutex_);+ if (failedLoaded_) return;+ failedLoaded_ = true;+ const auto f = failedFile();+ if (!f.existsAsFile()) return;+ juce::StringArray lines;+ lines.addLines(f.loadFileAsString());+ for (const auto& l : lines) {+ const int tab = l.indexOfChar('\t');+ if (tab <= 0) continue;+ impl_->failed[l.substring(tab + 1).toStdString()] = l.substring(0, tab).getLargeIntValue();+ }+}++void PluginCatalog::saveFailed() const {+ juce::StringArray lines;+ {+ std::shared_lock lock(mutex_);+ for (const auto& [id, stamp] : impl_->failed)+ lines.add(juce::String(stamp) + "\t" + juce::String::fromUTF8(id.c_str()));+ }+ failedFile().replaceWithText(lines.joinIntoString("\n"));+}++std::string PluginCatalog::scanLogPath() {+ const auto dir = supportDir();+ if (dir.getFullPathName().isEmpty()) return {};+ return dir.getChildFile("logs").getChildFile("plugin-scan.log").getFullPathName().toStdString();+}+void PluginCatalog::loadScanPathsOnce() {std::unique_lock lock(mutex_);if (scanPathsLoaded_) return;diff --git a/src/native/nota.engine/pluginhost/scanner/PluginCatalog.h b/src/native/nota.engine/pluginhost/scanner/PluginCatalog.hindex 99cb8159..c41ae00e 100644--- a/src/native/nota.engine/pluginhost/scanner/PluginCatalog.h+++ b/src/native/nota.engine/pluginhost/scanner/PluginCatalog.h@@ -2,7 +2,7 @@// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.//// PluginCatalog — thread-safe plugin registry.-// Owns plugins.xml + scanpaths.txt in the per-user data dir. Background scans+// Owns plugins.xml + scanpaths.txt + scan-failed.txt in the per-user data dir. Background scans// (C# Task.Run -> nota_pluginhost_scan) take the unique lock; UI reads// (count/desc/index_of_id) take the shared lock — no data races, no iterator// invalidation. Internally keeps full JUCE PluginDescriptions (uid, path hash,@@ -56,8 +56,18 @@ class PluginCatalog {// Mutation from the scan coordinator (unique lock).void addType(const juce::PluginDescription& desc);void removeMissingVst3OnDisk();+ // Discovered ids not in the catalog and not failed before (an id that failed is+ // skipped until its file changes — see markFailed).std::vector<std::string> unknownIds(const std::vector<std::string>& discovered) const;+ // Probes that found nothing usable (no answer, timeout, zero types), keyed by id+ // with the file's modification time: a plugin that hung once costs its timeout on+ // one scan, not on every scan. clearFailed() makes the next scan retry them all.+ void markFailed(const std::string& id);+ void forgetFailed(const std::string& id);+ void clearFailed();+ int32_t failedCount() const;+// Full JUCE description of entry `index` for in-process instantiation, copied// under one lock so the index and the entry can't drift apart mid-scan. False// when `index` is out of range.@@ -68,6 +78,12 @@ class PluginCatalog {void save() const;void loadScanPathsOnce();void saveScanPaths() const;+ void loadFailedOnce();+ void saveFailed() const;++ // <data dir>/logs/plugin-scan.log — one line per probe, rewritten each scan.+ // Empty when there is no data dir (persistence off).+ static std::string scanLogPath();private:PluginCatalog();@@ -77,6 +93,7 @@ class PluginCatalog {mutable std::shared_mutex mutex_;bool catalogLoaded_ = false;bool scanPathsLoaded_ = false;+ bool failedLoaded_ = false;};} // namespace scannerdiff --git a/src/native/nota.engine/pluginhost/scanner/abi_pluginscanner.cpp b/src/native/nota.engine/pluginhost/scanner/abi_pluginscanner.cppindex ab6f17d7..2c611cbe 100644--- a/src/native/nota.engine/pluginhost/scanner/abi_pluginscanner.cpp+++ b/src/native/nota.engine/pluginhost/scanner/abi_pluginscanner.cpp@@ -17,7 +17,14 @@#include <juce_audio_processors/juce_audio_processors.h>+#include <algorithm>+#include <atomic>+#include <chrono>+#include <memory>+#include <mutex>#include <string>+#include <thread>+#include <vector>namespace {@@ -30,9 +37,82 @@ juce::AudioPluginFormat* findFormat(const juce::String& name) {return nullptr;}-} // namespace+using Outcome = nota::scanner::OutOfProcessScanner::Outcome;-extern "C" NOTA_API int32_t nota_pluginhost_scan(const char* worker_path) {+const char* outcomeLabel(Outcome o) {+ switch (o) {+ case Outcome::Ok: return "ok";+ case Outcome::Timeout: return "timed out, worker killed";+ case Outcome::NoAnswer: return "no answer (worker crashed or exited)";+ case Outcome::StartFailed: return "worker failed to start";+ }+ return "?";+}++// plugin-scan.log: each line is flushed as it is written, so a scan that stalls+// still names the plugins it is on. Best-effort — never fails the scan. Probes run+// in parallel, so every line carries its plugin id.+class ScanLog {+ public:+ ScanLog() {+ const auto path = nota::scanner::PluginCatalog::scanLogPath();+ if (path.empty()) return;+ const juce::File file{juce::CharPointer_UTF8(path.c_str())};+ file.getParentDirectory().createDirectory();+ file.deleteFile();+ auto s = std::make_unique<juce::FileOutputStream>(file);+ if (s->openedOk()) stream_ = std::move(s);+ }++ void line(const juce::String& text) {+ std::lock_guard lock(mutex_);+ if (stream_ == nullptr) return;+ stream_->writeText(juce::Time::getCurrentTime().toISO8601(true) + " " + text + "\n", false, false, nullptr);+ stream_->flush();+ }++ private:+ std::mutex mutex_;+ std::unique_ptr<juce::FileOutputStream> stream_;+};++// One scan at a time (Rescan, a store install and the missing-plugins offer can+// overlap); progress belongs to the running one.+std::mutex g_scanMutex;+std::atomic<bool> g_scanning{false};+std::atomic<int32_t> g_done{0};+std::atomic<int32_t> g_total{0};+std::mutex g_currentMutex;+std::string g_current;++void setCurrent(std::string name) {+ std::lock_guard lock(g_currentMutex);+ g_current = std::move(name);+}++// What the UI shows while probing: a VST3 bundle's file name. An AU has no readable+// name until it is loaded (its id is "Synths/aumu,Ni$D,-NI-"), so nothing.+std::string displayName(const std::string& id) {+ const juce::String s{juce::CharPointer_UTF8(id.c_str())};+ if (juce::File::isAbsolutePath(s)) return juce::File(s).getFileNameWithoutExtension().toStdString();+ return {};+}++// Each probe is a separate process, so they parallelise well; a few at a time keeps+// a thousand-plugin first scan in minutes without starving the audio thread.+size_t probeThreads(size_t jobs) {+ const unsigned hw = std::max(2u, std::thread::hardware_concurrency());+ return std::min<size_t>(jobs, std::clamp(hw / 2, 1u, 4u));+}++constexpr int kFinalTimeoutMs = 120000;++struct Probe {+ const char* format;+ std::string id;+};++int32_t runScan(const char* worker_path, const char* only_dir, int32_t flags) {// No JUCE GUI init here on purpose: scanning (format enumeration + child// processes + XML) needs no MessageManager, and this may run off the main// thread. The MessageManager stays owned by the UI thread (editor windows).@@ -40,36 +120,162 @@ extern "C" NOTA_API int32_t nota_pluginhost_scan(const char* worker_path) {auto& catalog = nota::scanner::PluginCatalog::instance();catalog.loadOnce();catalog.loadScanPathsOnce();+ catalog.loadFailedOnce();nota::scanner::OutOfProcessScanner worker(worker_path);if (!worker.workerAvailable()) return -2;+ // The final, one-at-a-time attempt gets longer: big instruments (Kontakt) can take+ // over 30 s to load on a bad day, and a timeout here hides the plugin until a Rescan.+ nota::scanner::OutOfProcessScanner patient(worker_path, kFinalTimeoutMs);++ std::lock_guard scanLock(g_scanMutex);+ g_done = 0;+ g_total = 0;+ setCurrent({});+ g_scanning = true;+ struct Idle {+ ~Idle() { g_scanning = false; }+ } idle;++ ScanLog log;+ log.line("scan start, worker " + juce::String::fromUTF8(worker_path) ++ (only_dir != nullptr ? ", only " + juce::String::fromUTF8(only_dir) : juce::String()));++ if ((flags & NOTA_SCAN_RETRY_FAILED) != 0) catalog.clearFailed();// Forget VST3 bundles that are gone from disk (uninstalled, e.g. via Get Plug-ins),// so the browser stops listing them. AU lives in the system registry — left alone.catalog.removeMissingVst3OnDisk();+ std::vector<Probe> probes;for (const char* formatName : kFormatOrder) {auto* format = findFormat(formatName);if (format == nullptr) continue;- // Default OS locations plus any user-added dirs (file-based formats).- juce::FileSearchPath search = format->getDefaultLocationsToSearch();- for (const auto& p : catalog.scanPaths())- search.addIfNotAlreadyThere(juce::File(juce::CharPointer_UTF8(p.c_str())));+ juce::FileSearchPath search;+ if (only_dir != nullptr) {+ // One folder (a store install): file-based formats only — AU has no folders.+ if (juce::String(formatName) != "VST3") continue;+ search.add(juce::File(juce::CharPointer_UTF8(only_dir)));+ } else {+ // Default OS locations plus any user-added dirs (file-based formats).+ search = format->getDefaultLocationsToSearch();+ for (const auto& p : catalog.scanPaths())+ search.addIfNotAlreadyThere(juce::File(juce::CharPointer_UTF8(p.c_str())));+ }const auto ids = format->searchPathsForPlugins(search, /*recursive*/ true, /*allowAsync*/ false);std::vector<std::string> discovered;for (const auto& id : ids) discovered.push_back(id.toStdString());- for (const auto& id : catalog.unknownIds(discovered)) {- for (auto& desc : worker.scanDescriptions(formatName, id)) catalog.addType(*desc);- }+ const auto unknown = catalog.unknownIds(discovered);+ log.line(juce::String(formatName) + ": " + juce::String((int)discovered.size()) + " found, " ++ juce::String((int)unknown.size()) + " to probe");+ for (const auto& id : unknown) probes.push_back({formatName, id});+ }+ g_total = (int32_t)probes.size();++ // Saved as the scan goes: a scan cut short (the app quit) resumes where it was.+ using clock = std::chrono::steady_clock;+ std::mutex saveMutex;+ auto lastSave = clock::now();+ auto saveNow = [&] {+ catalog.save();+ catalog.saveFailed();+ lastSave = clock::now();+ };++ // One probe. `final`: a timeout or a missing answer counts as the plugin's failure.+ // In the parallel pass it doesn't — heavy plugins (licence daemons, big sample+ // libraries) can miss the deadline only because of their neighbours — so those+ // come back for a serial retry instead. Returns false when it needs one.+ auto probeOne = [&](const Probe& probe, bool final) {+ const auto id = juce::String::fromUTF8(probe.id.c_str());+ setCurrent(displayName(probe.id));+ log.line("probe " + juce::String(probe.format) + " " + id + (final ? " (alone)" : ""));+ const auto t0 = clock::now();+ Outcome outcome = Outcome::StartFailed;+ std::string detail;+ auto descs = (final ? patient : worker).scanDescriptions(probe.format, probe.id, &outcome, &detail);+ for (auto& desc : descs) catalog.addType(*desc);+ const auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(clock::now() - t0);+ log.line(" " + id + ": " + outcomeLabel(outcome) + ", " + juce::String((int)descs.size()) + " types, " ++ juce::String((int)ms.count()) + " ms" ++ (detail.empty() ? juce::String() : " (" + juce::String::fromUTF8(detail.c_str()) + ")"));+ const bool retry = !final && (outcome == Outcome::Timeout || outcome == Outcome::NoAnswer);+ // StartFailed is ours (no worker), not the plugin's — don't hold it against it.+ if (!descs.empty()) catalog.forgetFailed(probe.id);+ else if (!retry && outcome != Outcome::StartFailed) catalog.markFailed(probe.id);+ ++g_done;+ std::lock_guard lock(saveMutex);+ if (clock::now() - lastSave > std::chrono::seconds(5)) saveNow();+ return !retry;+ };++ std::vector<Probe> retries;+ std::mutex retriesMutex;+ std::atomic<size_t> next{0};+ auto work = [&] {+ for (size_t i; (i = next++) < probes.size();)+ if (!probeOne(probes[i], probes.size() == 1)) {+ std::lock_guard lock(retriesMutex);+ retries.push_back(probes[i]);+ }+ };+ const size_t threads = probeThreads(probes.size());+ log.line("probing " + juce::String((int)probes.size()) + " with " + juce::String((int)threads) + " workers");+ std::vector<std::thread> pool;+ for (size_t t = 1; t < threads; ++t) pool.emplace_back(work);+ work();+ for (auto& t : pool) t.join();++ if (!retries.empty()) {+ log.line("retrying " + juce::String((int)retries.size()) + " one at a time");+ g_total += (int32_t)retries.size();+ for (const auto& probe : retries) probeOne(probe, true);}catalog.save();+ catalog.saveFailed();+ log.line("scan done, " + juce::String(catalog.count()) + " plugins known, " + juce::String(catalog.failedCount()) ++ " failed");return catalog.count();}+} // namespace++extern "C" NOTA_API int32_t nota_pluginhost_scan(const char* worker_path) {+ return nota_pluginhost_scan_ex(worker_path, nullptr, 0);+}++extern "C" NOTA_API int32_t nota_pluginhost_scan_ex(const char* worker_path, const char* only_dir, int32_t flags) {+ try {+ return runScan(worker_path, only_dir, flags);+ } catch (...) {+ g_scanning = false; // AR-7: nothing unwinds across the C ABI+ return -3;+ }+}++extern "C" NOTA_API int32_t nota_pluginhost_scan_progress(int32_t* done, int32_t* total) {+ if (done != nullptr) *done = g_done.load();+ if (total != nullptr) *total = g_total.load();+ return g_scanning.load() ? 1 : 0;+}++extern "C" NOTA_API const char* nota_pluginhost_scan_current(void) {+ thread_local std::string name;+ std::lock_guard lock(g_currentMutex);+ name = g_current;+ return name.c_str();+}++extern "C" NOTA_API int32_t nota_pluginhost_scan_failed_count(void) {+ auto& catalog = nota::scanner::PluginCatalog::instance();+ catalog.loadFailedOnce();+ return catalog.failedCount();+}+extern "C" NOTA_API int32_t nota_pluginhost_plugin_count(void) {auto& catalog = nota::scanner::PluginCatalog::instance();catalog.loadOnce();diff --git a/src/native/nota.engine/pluginhost/scanner/tests/ScannerSelfTest.cpp b/src/native/nota.engine/pluginhost/scanner/tests/ScannerSelfTest.cppnew file mode 100644index 00000000..553e68cf--- /dev/null+++ b/src/native/nota.engine/pluginhost/scanner/tests/ScannerSelfTest.cpp@@ -0,0 +1,139 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// nota-scanner-selftest — OutOfProcessScanner against misbehaving workers.+// The binary is its own stub worker: run as `<self> STUB <mode>` (the worker's+// <format> <id> argument shape) it plays a plugin that hangs, answers then hangs+// at exit, prints noise, or dies without answering. Run with no arguments it drives the scanner+// at those stubs and checks every probe ends on time. Exit code 0 = all passed.++#include "../OutOfProcessScanner.h"++#include <juce_audio_processors/juce_audio_processors.h>++#include <chrono>+#include <cstdio>+#include <cstdlib>+#include <cstring>+#include <iostream>+#include <string>+#include <thread>+#include <vector>++#if !JUCE_WINDOWS+#include <cerrno>+#include <sys/wait.h>+#endif++namespace {++using nota::scanner::OutOfProcessScanner;+using Outcome = OutOfProcessScanner::Outcome;++void printAnswer() {+ juce::PluginDescription d;+ d.name = "Stub";+ d.pluginFormatName = "VST3";+ d.fileOrIdentifier = "stub.vst3";+ d.uniqueId = 42;+ juce::XmlElement root("plugins");+ root.addChildElement(d.createXml().release());+ std::cout << "<<<NOTA_PLUGINS_BEGIN>>>\n" << root.toString() << "\n<<<NOTA_PLUGINS_END>>>" << std::endl;+}++[[noreturn]] void hang() {+ for (;;) std::this_thread::sleep_for(std::chrono::hours(1));+}++int runStub(const std::string& mode) {+ if (mode == "hang") hang(); // stuck probing, never answers+ if (mode == "answer-then-hang") { printAnswer(); hang(); } // deadlocks on unload+ if (mode == "noisy") { // chatty plugin, > the old 8 KB read+ for (int i = 0; i < 400; ++i) std::cout << "plugin log line " << i << " ........................\n";+ printAnswer();+ return 0;+ }+ if (mode == "die") std::_Exit(7); // crash stand-in (no WER/ReportCrash dialog)+ if (mode == "ok") { printAnswer(); return 0; }+ return 3;+}++int failures = 0;++void check(bool ok, const std::string& label) {+ std::cout << " [" << (ok ? "PASS" : "FAIL") << "] " << label << "\n";+ if (!ok) ++failures;+}++void probe(const OutOfProcessScanner& scanner, const char* mode, Outcome want, size_t wantTypes, int maxMs) {+ const auto t0 = std::chrono::steady_clock::now();+ Outcome got = Outcome::StartFailed;+ const auto descs = scanner.scanDescriptions("STUB", mode, &got);+ const auto ms =+ (int)std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - t0).count();+ check(got == want && descs.size() == wantTypes && ms <= maxMs,+ std::string(mode) + ": outcome " + std::to_string((int)got) + " (want " + std::to_string((int)want) + "), " ++ std::to_string(descs.size()) + " types (want " + std::to_string(wantTypes) + "), " + std::to_string(ms) ++ " ms (max " + std::to_string(maxMs) + ")");+}++} // namespace++int main(int argc, char** argv) {+ if (argc >= 3 && std::strcmp(argv[1], "STUB") == 0) return runStub(argv[2]);++ const auto self = juce::File::getSpecialLocation(juce::File::currentExecutableFile).getFullPathName().toStdString();+ constexpr int kTimeoutMs = 1500;+ const OutOfProcessScanner scanner(self, kTimeoutMs);+ // Allowance over the timeout: process start-up plus the post-kill join (<= 2 s).+ constexpr int kSlack = 3000;++ std::cout << "-- out-of-process scanner --\n";+ probe(scanner, "ok", Outcome::Ok, 1, kTimeoutMs);+ probe(scanner, "hang", Outcome::Timeout, 0, kTimeoutMs + kSlack);+ probe(scanner, "answer-then-hang", Outcome::Ok, 1, kTimeoutMs);+ probe(scanner, "noisy", Outcome::Ok, 1, kTimeoutMs);+ probe(scanner, "die", Outcome::NoAnswer, 0, kTimeoutMs);++ // A missing worker: Windows fails CreateProcess; POSIX forks and the exec fails.+ const OutOfProcessScanner missing("/nonexistent/nota-scanworker", kTimeoutMs);+ Outcome got = Outcome::Ok;+ const auto descs = missing.scanDescriptions("STUB", "ok", &got);+ check(descs.empty() && (got == Outcome::StartFailed || got == Outcome::NoAnswer), "missing worker: no types, no hang");++ // Parallel probes, as the scan runs them: a dying or hung sibling must not+ // delay or confuse the others (inherited pipe ends), and all finish on time.+ {+ const char* modes[] = {"ok", "die", "hang", "answer-then-hang", "noisy", "die", "ok", "hang"};+ std::vector<std::thread> pool;+ std::vector<std::string> bad(8);+ const auto t0 = std::chrono::steady_clock::now();+ for (int i = 0; i < 8; ++i)+ pool.emplace_back([&, i] {+ Outcome got = Outcome::StartFailed;+ const auto d = scanner.scanDescriptions("STUB", modes[i], &got);+ const std::string m = modes[i];+ const Outcome want = m == "hang" ? Outcome::Timeout : m == "die" ? Outcome::NoAnswer : Outcome::Ok;+ if (got != want || d.size() != (want == Outcome::Ok ? 1u : 0u)) bad[(size_t)i] = m;+ });+ for (auto& t : pool) t.join();+ const auto ms =+ (int)std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - t0).count();+ std::string wrong;+ for (const auto& b : bad)+ if (!b.empty()) wrong += " " + b;+ check(wrong.empty() && ms <= kTimeoutMs + kSlack,+ "8 parallel probes end right and on time (" + std::to_string(ms) + " ms)" ++ (wrong.empty() ? "" : ", wrong:" + wrong));+ }++#if !JUCE_WINDOWS+ // Every worker was reaped: no zombies piling up over a thousand-plugin scan.+ int status = 0;+ const pid_t left = ::waitpid(-1, &status, WNOHANG);+ check(left == -1 && errno == ECHILD, "no unreaped worker processes left");+#endif++ std::cout << (failures == 0 ? "SCANNER SELFTEST PASSED" : "SCANNER SELFTEST FAILED") << "\n";+ return failures == 0 ? 0 : 1;+}diff --git a/src/native/nota.engine/pluginhost/scanner/worker/PluginScannerWorker.cpp b/src/native/nota.engine/pluginhost/scanner/worker/PluginScannerWorker.cppindex 4fbff770..5c581ea7 100644--- a/src/native/nota.engine/pluginhost/scanner/worker/PluginScannerWorker.cpp+++ b/src/native/nota.engine/pluginhost/scanner/worker/PluginScannerWorker.cpp@@ -8,11 +8,36 @@#include <juce_audio_processors/juce_audio_processors.h>+#include <cstdio>+#include <cstdlib>#include <iostream>+#if JUCE_WINDOWS+#ifndef NOMINMAX+#define NOMINMAX+#endif+#include <windows.h>+#endif+namespace nota {namespace scanner {+namespace {++// Ends the process now, skipping plugin unload and static teardown: some plugins+// deadlock there (DllMain / static destructors), and the answer is already out.+// TerminateProcess rather than _Exit on Windows — ExitProcess still runs DLL detach.+[[noreturn]] void exitNow(int code) {+ std::fflush(stdout);+ std::fflush(stderr);+#if JUCE_WINDOWS+ ::TerminateProcess(::GetCurrentProcess(), (UINT)code);+#endif+ std::_Exit(code);+}++} // namespace+int runScannerWorker(int argc, char** argv) {if (argc < 3) {std::cerr << "usage: nota-scanworker <formatName> <fileOrIdentifier>\n";@@ -38,7 +63,7 @@ int runScannerWorker(int argc, char** argv) {for (auto* desc : found) root.addChildElement(desc->createXml().release());std::cout << "<<<NOTA_PLUGINS_BEGIN>>>\n" << root.toString() << "\n<<<NOTA_PLUGINS_END>>>" << std::endl;- return 0;+ exitNow(0);}std::cerr << "unknown format: " << formatName << "\n";diff --git a/tests/Nota.SmokeTest/PluginStoreTests.cs b/tests/Nota.SmokeTest/PluginStoreTests.csindex 0766d8f1..422eabf5 100644--- a/tests/Nota.SmokeTest/PluginStoreTests.cs+++ b/tests/Nota.SmokeTest/PluginStoreTests.cs@@ -214,6 +214,65 @@ internal static class PluginStoreTestsConsole.WriteLine($" (installed under {root})");}+ /// <summary>Scan behaviour for large plugin folders (nota-daw/nota#220), against the real+ /// worker and empty fake .vst3 bundles (each probes to zero types, i.e. fails): a folder-only+ /// scan, progress while it runs, failures remembered and skipped, re-probed once the file+ /// changes or on retry, forgotten once deleted. Needs NOTA_DATA_DIR under /tmp like+ /// <see cref="RunCatalog"/>.</summary>+ public static IEnumerable<(bool Ok, string Label)> RunScanScale(string worker)+ {+ var home = Environment.GetEnvironmentVariable("NOTA_DATA_DIR") ?? "";+ if (home.Length == 0 || !Path.GetFullPath(home).StartsWith(Path.GetFullPath(Path.GetTempPath()), StringComparison.Ordinal)+ && !home.StartsWith("/tmp/", StringComparison.Ordinal))+ {+ yield return (false, "run with NOTA_DATA_DIR=<scratch dir under /tmp> — this rescans the plugin catalog");+ yield break;+ }+ const int N = 40;+ var dir = Path.Combine(home, "fake-vst3");+ for (int i = 0; i < N; i++) Directory.CreateDirectory(Path.Combine(dir, $"Fake {i:00}.vst3"));+ var log = Path.Combine(home, "logs", "plugin-scan.log");+ // "probing 40 with 4 workers" — how many probes the last scan ran.+ int Probed() => File.ReadLines(log).Select(l => System.Text.RegularExpressions.Regex.Match(l, @"probing (\d+) with"))+ .Where(m => m.Success).Select(m => int.Parse(m.Groups[1].Value)).LastOrDefault(-1);++ // Progress, polled the way the app does while the scan runs.+ var seen = new List<PluginScanProgress>();+ var sw = System.Diagnostics.Stopwatch.StartNew();+ var scan = Task.Run(() => NotaEngine.ScanPlugins(worker, dir, retryFailed: false));+ while (!scan.IsCompleted)+ {+ if (NotaEngine.ScanProgress is { } p) seen.Add(p);+ Thread.Sleep(20);+ }+ scan.GetAwaiter().GetResult();+ var first = sw.Elapsed;+ var lines = File.ReadAllLines(log);+ yield return (Probed() == N && !lines.Any(l => l.Contains("AudioUnit:", StringComparison.Ordinal)),+ $"a folder-only scan probes just that folder's {N} bundles ({Probed()} probed)");+ yield return (lines.Any(l => System.Text.RegularExpressions.Regex.IsMatch(l, @"with [2-9] workers")) || Environment.ProcessorCount < 4,+ "probes run in parallel");+ yield return (seen.Any(p => p.Total == N) && seen.Any(p => p.Done > 0 && p.Done < N) && NotaEngine.ScanProgress is null,+ $"progress counts up while it runs ({seen.Count} samples) and clears after");+ yield return (NotaEngine.ScanFailedCount == N && File.Exists(Path.Combine(home, "scan-failed.txt")),+ $"bundles that load nothing are remembered as failed ({NotaEngine.ScanFailedCount})");++ sw.Restart();+ NotaEngine.ScanPlugins(worker, dir, retryFailed: false);+ yield return (Probed() == 0 && sw.Elapsed < first / 2, $"the next scan skips them ({Probed()} probed, {sw.Elapsed.TotalSeconds:0.0} s vs {first.TotalSeconds:0.0} s)");++ Directory.SetLastWriteTimeUtc(Path.Combine(dir, "Fake 07.vst3"), DateTime.UtcNow.AddMinutes(1));+ NotaEngine.ScanPlugins(worker, dir, retryFailed: false);+ yield return (Probed() == 1, $"a bundle that changed on disk is probed again ({Probed()} probed)");++ NotaEngine.ScanPlugins(worker, dir, retryFailed: true);+ yield return (Probed() == N, $"Rescan's retry probes every failed bundle again ({Probed()} probed)");++ Directory.Delete(dir, recursive: true);+ NotaEngine.ScanPlugins(worker, Path.Combine(home, "logs"), retryFailed: false);+ yield return (NotaEngine.ScanFailedCount == 0, $"deleted bundles are forgotten ({NotaEngine.ScanFailedCount} left)");+ }+/// <summary>Catalog behaviour the store relies on, against a real VST3 bundle: a plugin found at a/// new path still resolves by its old identifier (path hash ignored), and a bundle deleted from/// disk drops out of the catalog on the next scan. Rescans the catalog, so it refuses to rundiff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.csindex 87df61c0..925ecf38 100644--- a/tests/Nota.SmokeTest/Program.cs+++ b/tests/Nota.SmokeTest/Program.cs@@ -215,6 +215,13 @@ if (args.Length >= 3 && args[0] == "--store-catalog")Console.WriteLine(failures == 0 ? "STORE CATALOG PASSED" : $"STORE CATALOG FAILED ({failures})");return failures == 0 ? 0 : 1;}+if (args.Length >= 2 && args[0] == "--scan-scale")+{+ Console.WriteLine("-- plugin scan: large folders --");+ foreach (var (ok, label) in PluginStoreTests.RunScanScale(args[1])) Check(ok, label);+ Console.WriteLine(failures == 0 ? "SCAN SCALE PASSED" : $"SCAN SCALE FAILED ({failures})");+ return failures == 0 ? 0 : 1;+}if (args.Length >= 3 && args[0] == "--store-live"){Console.WriteLine("-- get plug-ins: live installs --");