Skip to content

armgit / nota

Public Imported from GitHub
0

Nota — a free DAW for macOS, Windows and Linux. No subscription, no account — just open it and make music.

(fix) Let hosted plug-in tracks render on the render pool (#532) (#534)

ret_xed1a152dbac5ea
diff --git a/.specify/bugs/kontakt-cpu-dropouts/fix.md b/.specify/bugs/kontakt-cpu-dropouts/fix.md
index 0ca443a5..d1195fbf 100644
--- a/.specify/bugs/kontakt-cpu-dropouts/fix.md
+++ b/.specify/bugs/kontakt-cpu-dropouts/fix.md
@@ -1,9 +1,9 @@
# Bug Fix: high CPU and dropouts with four Kontakt instances
- **Slug**: kontakt-cpu-dropouts
-- **Fixed**: 2026-11-02
+- **Fixed**: 2026-11-02 (round 3 — step 2 — completed 2026-11-06, see below)
- **Assessment**: ./assessment.md
-- **Status**: partial (steps 1 and 2 applied — step 2 as workgroup join for pool workers and AUs, plug-ins still serial; step 3 follow-up; built-in Consort storm in demo21 still open)
+- **Status**: step 1 + step 2 complete; step 3 follow-up; built-in Consort storm in demo21 still open
## Summary
@@ -110,10 +110,70 @@ that is not a fair test of this.
## Follow-ups
-- Step 2: let plug-in tracks render on the pool (one thread per instance per block), with the
- pool workers joined to the device's `os_workgroup` / RT policy. Measure with the same bench.
- Step 3: check `NOTA_DEBUG_PLUGIN_BUSES=1` for Kontakt's enabled outputs; enable only the main
bus unless something routes another.
- Racks: a `PluginInstrument` inside an Instrument Rack chain is still driven by the rack in
segments — the rack could pass timed events through too.
- Pre-existing flaky `RenderPoolTests` overload checks on this Mac.
+
+## Round 3: hosted tracks render on the pool (2026-11-06)
+
+Remediation step 2, filed as [nota-daw/nota#532](https://github.com/nota-daw/nota/issues/532)
+(the same bug class reproduced on Windows: DSP usage reaching 100 % with several SWAM/Kontakt
+instances, dropouts on a Ryzen 9 7900X). Independent audited adapters opt in per instance:
+`Device::supportsParallelRender()` / `Instrument::supportsParallelRender()` → hosted
+instrument/effect leaves dispatch on the render pool with exclusive per-instance/per-block
+ownership (instance-local MIDI, channel storage and playhead state; the engine joins the pool
+before the next block; lifecycle and editor work stay on the message thread). Only VST3 opts
+in by format decision made once in each adapter's constructor; unknown hosted formats and
+rack-nested chains keep the serial fallback. Helpers sizing reserves `kRtSizeLoad` 0.50 of the
+period (was 0.85) and adds a list-scheduling bound on the largest indivisible track job
+(`leafPeakNs_`, EMA 1/16), so indivisible heavy jobs cannot under-size the wake count.
+
+Changes: `src/devices/{Device,Instrument}.h` (contract, default `!hostsPlugin()`),
+`pluginhost/hosting/PluginInstrument.{h,cpp}` and `PluginEffect.{h,cpp}` (`parallelRender_`),
+`src/engine/Engine.h` (`leafPeakNs_`, `kRtSizeLoad = 0.50`), `src/engine/Engine_Render.cpp`
+(eligibility comment + checks, helper sizing, peak EMA), `CMakeLists.txt`
+(`NOTA_BUILD_RENDER_PROBE`, deterministic `nota-render-probe` VST3),
+`pluginhost/tests/RenderProbe.cpp` (new), `tests/Nota.SmokeTest/HostedRenderPoolTests.cs` and
+`HostedPluginProfile.cs` (new guards + profile; wired into `RenderPoolTests.Run()` and
+`Program.cs` via `--hosted-render-pool`, `--profile-hosted`, `--profile-project`).
+
+Guards (`--hosted-render-pool`, deterministic probe, 128 frames / 48 kHz):
+
+- four heavy VST3 instrument tracks, device path: median 5.847 → 1.810 ms, late blocks
+ 100/100 → 0/100; offline: 2.912 → 0.749 ms;
+- new independent VST3 sessions render sample-identically with helpers on/off, on instrument
+ and insert/sidechain paths, through bypass / removal / replacement / undo edits;
+- light per-instance load keeps helpers parked (0.0 ms worker CPU); rack-nested chains stay
+ serial and audible.
+
+Bench (`--profile-hosted`, same probe with per-instance load ≈ 1.47 ms, paced like a device,
+200-block rounds, alternating builds, Windows 11, Ryzen 9 7900X 12c/24t):
+
+| round | build | 4 instances median | p95 | late (of 200) |
+|---|---|---|---|---|
+| 1 | develop | 5.823 ms | 5.909 | 200 |
+| 1 | fix | 1.658 ms | 1.850 | 0 |
+| 2 | develop | 5.815 ms | 5.844 | 200 |
+| 2 | fix | 1.686 ms | 1.888 | 0 |
+| 3 | develop | 5.823 ms | 5.855 | 200 |
+| 3 | fix | 1.576 ms | 1.882 | 0 |
+
+One instance ≈ 1.47 ms on both builds (unchanged); helpers forced off reads 5.82 ms on both
+builds (the serial path is untouched). Worker CPU on the fix build ≈ 0.9–1.0 s per round: the
+same work spread over the pool instead of piling on the audio thread. The probe is a
+deterministic synthetic (no commercial dependency); its per-instance cost was matched to the
+reported overloading shape, and the machine is the same model as the reporter's (7900X).
+
+## Follow-ups (round 3)
+- Real Kontakt/SWAM were not installed on the bench machine; measured with the deterministic
+ probe through the same mechanism the guards use.
+- macOS `os_workgroup` join of pool workers landed in #436 (round 2) and is unchanged here.
+- Review fixes (Greptile, PR #534): pool sizing uses every available worker when the largest
+ indivisible job alone overflows the target (no bound is reachable there; extra workers still
+ lower the list-scheduling bound); `HostedRenderPoolTests.RunIsolated()` times the child out
+ at 10 minutes and kills its tree instead of stalling the smoke suite on a native hang; the
+ four-instance deadline gate calibrates one probe instance's cost first and skips the
+ late-block comparison on machines where a single instance cannot meet the period.
+
diff --git a/CHANGELOG.md b/CHANGELOG.md
index bfa3685f..86a6805d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -66,6 +66,22 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.
and not applied. Nota Remote follows. Orange looks exactly as before.
### Fixed
+- **Four plug-in instruments no longer saturate the audio thread** (#532): hosting several
+ Kontakt/SWAM instances — one per instrument track — put every instance's process call on the
+ audio callback, so playback climbed to a 100 % DSP load and dropped out. An audited VST3
+ adapter keeps all its state inside the instance, so independent hosted instrument/effect
+ tracks may now render their work exclusively on a render-pool worker per block; the engine
+ joins the pool before the next block, and lifecycle/editor work stays on the message thread.
+ Unknown hosted formats, rack-nested chains and record-armed/capture-routed tracks keep the
+ serial fallback, and a light load leaves helpers parked. Measured with a deterministic VST3
+ probe: four heavy instances went from 5.82 ms median (218 % of a 2.67 ms callback period,
+ every block late) to 1.58–1.69 ms with zero late blocks on the same machine.
+- **The render pool reserves playback headroom** (#532): when the pool joins the callback, its
+ helper count now keeps half the buffer free for voice attacks and scheduler jitter (the
+ previous boundary left only 15 %), and the sizing accounts for the largest indivisible track
+ job (list scheduling's bound) — heavy plug-in jobs no longer schedule into serial waves while
+ cores idle. Pools under a 512-frame four-instance load keep the per-callback cost at ~93 % of
+ one such instance instead of four.
- **Default Projects/Samples folders follow the OS locations** (#522): the browser and
save dialogs no longer default to hardcoded `~/Documents/Nota Projects` and
`~/Music/Nota Samples`. On Linux they read `user-dirs.dirs` (`XDG_DOCUMENTS_DIR`,
diff --git a/src/native/nota.engine/CMakeLists.txt b/src/native/nota.engine/CMakeLists.txt
index 83abdc91..99a44653 100644
--- a/src/native/nota.engine/CMakeLists.txt
+++ b/src/native/nota.engine/CMakeLists.txt
@@ -449,6 +449,27 @@ if(APPLE)
target_link_libraries(nota-scanworker PRIVATE "-framework CoreAudioKit")
endif()
+# A real, deterministic VST3 for hosted render-pool regression tests. It stays in
+# the build tree: never copied into a user's plugin directory or app package.
+option(NOTA_BUILD_RENDER_PROBE "Build the hosted render-pool test VST3" ON)
+if(NOTA_BUILD_RENDER_PROBE)
+ juce_add_plugin(nota-render-probe
+ COMPANY_NAME Nota
+ PLUGIN_MANUFACTURER_CODE Nota
+ PLUGIN_CODE Nrpr
+ PRODUCT_NAME "Nota Render Probe"
+ FORMATS VST3
+ IS_SYNTH TRUE
+ NEEDS_MIDI_INPUT TRUE
+ COPY_PLUGIN_AFTER_BUILD FALSE
+ VST3_AUTO_MANIFEST FALSE)
+ target_sources(nota-render-probe PRIVATE pluginhost/tests/RenderProbe.cpp)
+ target_link_libraries(nota-render-probe PRIVATE juce::juce_audio_processors
+ juce::juce_recommended_config_flags)
+ target_compile_definitions(nota-render-probe PRIVATE JUCE_USE_CURL=0
+ JUCE_WEB_BROWSER=0 JUCE_VST3_CAN_REPLACE_VST2=0)
+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`.
diff --git a/src/native/nota.engine/pluginhost/hosting/PluginEffect.cpp b/src/native/nota.engine/pluginhost/hosting/PluginEffect.cpp
index f17b1dbe..39605cf7 100644
--- a/src/native/nota.engine/pluginhost/hosting/PluginEffect.cpp
+++ b/src/native/nota.engine/pluginhost/hosting/PluginEffect.cpp
@@ -17,6 +17,9 @@ namespace hosting {
PluginEffect::PluginEffect(std::unique_ptr<juce::AudioPluginInstance> p, double sr, int maxBlock)
: plugin_(std::move(p)) {
if (plugin_) name_ = plugin_->getName().toStdString();
+ // Per-instance VST3 buffers/playhead/sidechain data permit an exclusive worker
+ // process call. Initialization, state and editors remain on the message thread.
+ parallelRender_ = plugin_ && plugin_->getPluginDescription().pluginFormatName == "VST3";
empty_.ensureSize(256);
setSampleRate(sr, maxBlock);
if (plugin_) plugin_->addListener(this); // "Learn" (M9-B3)
diff --git a/src/native/nota.engine/pluginhost/hosting/PluginEffect.h b/src/native/nota.engine/pluginhost/hosting/PluginEffect.h
index 911c1095..b2fb80bc 100644
--- a/src/native/nota.engine/pluginhost/hosting/PluginEffect.h
+++ b/src/native/nota.engine/pluginhost/hosting/PluginEffect.h
@@ -30,6 +30,7 @@ class PluginEffect : public nota::Device, private juce::AudioProcessorListener {
~PluginEffect() override;
const char* displayName() const override { return name_.empty() ? "Plugin" : name_.c_str(); }
+ bool supportsParallelRender() const override { return parallelRender_; }
void setSampleRate(double sr, int32_t maxBlock) override;
int32_t latencySamples() const override;
@@ -98,6 +99,7 @@ class PluginEffect : public nota::Device, private juce::AudioProcessorListener {
juce::MidiBuffer empty_;
WorkgroupLink workgroup_; // the device workgroup for the plug-in's own threads (#436)
int maxBlock_ = 0; // what the plug-in was prepared for: at most kPluginMaxBlock (#447)
+ bool parallelRender_ = false; // immutable format decision, made on the message thread
bool stereoIn_ = true, stereoOut_ = true; // main buses have a channel 1 (see setSampleRate)
EditorHost editor_; // declared last: destroyed before plugin_
};
diff --git a/src/native/nota.engine/pluginhost/hosting/PluginInstrument.cpp b/src/native/nota.engine/pluginhost/hosting/PluginInstrument.cpp
index abed0c4a..abd6a7f5 100644
--- a/src/native/nota.engine/pluginhost/hosting/PluginInstrument.cpp
+++ b/src/native/nota.engine/pluginhost/hosting/PluginInstrument.cpp
@@ -18,6 +18,11 @@ PluginInstrument::PluginInstrument(std::unique_ptr<juce::AudioPluginInstance> p,
pending_.ensureSize(8192);
piece_.ensureSize(8192);
if (plugin_) name_ = plugin_->getName().toStdString(); // cache for displayName()
+ // VST3 process calls may run on audio workers. All MIDI, channel storage and
+ // playhead state belong to this instance; the engine joins before the next
+ // block and never processes an instance concurrently. Lifecycle/editor work
+ // stays on the message thread. Other formats retain the serial fallback.
+ parallelRender_ = plugin_ && plugin_->getPluginDescription().pluginFormatName == "VST3";
prepare(sr);
if (plugin_) plugin_->addListener(this); // "Learn" (M9-B3)
// Editor-window computer keyboard -> this plugin (drained on the audio thread).
diff --git a/src/native/nota.engine/pluginhost/hosting/PluginInstrument.h b/src/native/nota.engine/pluginhost/hosting/PluginInstrument.h
index 60a0cf91..060daefa 100644
--- a/src/native/nota.engine/pluginhost/hosting/PluginInstrument.h
+++ b/src/native/nota.engine/pluginhost/hosting/PluginInstrument.h
@@ -32,6 +32,7 @@ class PluginInstrument : public nota::Instrument, private juce::AudioProcessorLi
const char* displayName() const override { return name_.empty() ? "Plugin" : name_.c_str(); }
bool handlesSustain() const override { return true; } // the plug-in gets CC64 itself
+ bool supportsParallelRender() const override { return parallelRender_; }
bool takesTimedEvents() const override { return true; } // one processBlock per block (#436)
void setSampleRate(double sr) override;
@@ -99,6 +100,7 @@ class PluginInstrument : public nota::Instrument, private juce::AudioProcessorLi
int maxBlock_; // what the plug-in was prepared for: at most kPluginMaxBlock (#447)
bool stereoOut_ = true; // main output bus has a channel 1 (see prepare)
std::string name_; // cached plugin name for displayName()
+ bool parallelRender_ = false; // immutable format decision, made on the message thread
std::atomic<int32_t> lastTouched_{-1}; // "Learn" (M9-B3)
std::atomic<int32_t> gestureBegin_{-1}, gestureEnd_{-1}; // write gestures (M9-C)
GuiNoteQueue guiNotes_; // editor-window computer keyboard -> render() (message->audio)
diff --git a/src/native/nota.engine/pluginhost/tests/RenderProbe.cpp b/src/native/nota.engine/pluginhost/tests/RenderProbe.cpp
new file mode 100644
index 00000000..4c37ba31
--- /dev/null
+++ b/src/native/nota.engine/pluginhost/tests/RenderProbe.cpp
@@ -0,0 +1,103 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Deterministic real VST3 fixture for the hosted render pool. Independent instances
+// own all DSP state. Expensive, bounded DSP makes missed scheduling measurable;
+// a reentrant process call poisons the output instead of silently passing a test.
+
+#include <juce_audio_processors/juce_audio_processors.h>
+#include <array>
+#include <algorithm>
+#include <atomic>
+#include <cmath>
+#include <cstring>
+#include <limits>
+
+class RenderProbe final : public juce::AudioProcessor {
+ public:
+ RenderProbe() : AudioProcessor(probeBuses()) {
+ addParameter(work_ = new juce::AudioParameterInt({"work", 1}, "Work", 0, 4096, 0));
+ addParameter(gain_ = new juce::AudioParameterFloat({"gain", 1}, "Gain", 0.0f, 1.0f, 0.5f));
+ }
+ const juce::String getName() const override { return "Nota Render Probe"; }
+ void prepareToPlay(double rate, int) override {
+ rate_ = rate; phase_ = 0; state_ = 0.1; notes_.fill(false);
+ }
+ void releaseResources() override {}
+ bool acceptsMidi() const override { return true; }
+ bool producesMidi() const override { return false; }
+ bool isMidiEffect() const override { return false; }
+ double getTailLengthSeconds() const override { return 0; }
+ bool hasEditor() const override { return false; }
+ juce::AudioProcessorEditor* createEditor() override { return nullptr; }
+ int getNumPrograms() override { return 1; }
+ int getCurrentProgram() override { return 0; }
+ void setCurrentProgram(int) override {}
+ const juce::String getProgramName(int) override { return {}; }
+ void changeProgramName(int, const juce::String&) override {}
+ void getStateInformation(juce::MemoryBlock& out) override {
+ const float values[]{float(work_->get()), gain_->get()};
+ out.replaceAll(values, sizeof values);
+ }
+ void setStateInformation(const void* data, int size) override {
+ if (size != 2 * sizeof(float)) return;
+ float values[2]; std::memcpy(values, data, sizeof values);
+ *work_ = juce::roundToInt(values[0]); *gain_ = values[1];
+ }
+ void processBlock(juce::AudioBuffer<float>& buffer, juce::MidiBuffer& midi) override {
+ if (processing_.test_and_set(std::memory_order_acquire)) {
+ for (int c = 0; c < buffer.getNumChannels(); ++c)
+ juce::FloatVectorOperations::fill(buffer.getWritePointer(c),
+ std::numeric_limits<float>::quiet_NaN(), buffer.getNumSamples());
+ return;
+ }
+ const int work = work_->get();
+ const float gain = gain_->get();
+ auto event = midi.cbegin();
+ for (int i = 0; i < buffer.getNumSamples(); ++i) {
+ while (event != midi.cend() && (*event).samplePosition <= i) {
+ const auto msg = (*event).getMessage();
+ if (msg.isNoteOn()) { notes_[(size_t)msg.getNoteNumber()] = true; pitch_ = msg.getNoteNumber(); }
+ if (msg.isNoteOff()) notes_[(size_t)msg.getNoteNumber()] = false;
+ if (msg.isAllNotesOff() || msg.isAllSoundOff()) notes_.fill(false);
+ ++event;
+ }
+ // Depend on the result so Release optimizers must retain the DSP work.
+ for (int k = 0; k < work; ++k) state_ = std::sin(state_ + 0.01);
+ const bool sounding = std::any_of(notes_.begin(), notes_.end(), [](bool n) { return n; });
+ const float tone = sounding ? float(0.04 * std::sin(phase_)) : 0.0f;
+ phase_ += 6.283185307179586 * juce::MidiMessage::getMidiNoteInHertz(pitch_) / rate_;
+ if (phase_ >= 6.283185307179586) phase_ -= 6.283185307179586;
+ const float side = buffer.getNumChannels() > 2 ? buffer.getReadPointer(2)[i] * 0.1f : 0.0f;
+ for (int c = 0; c < std::min(2, buffer.getNumChannels()); ++c)
+ buffer.getWritePointer(c)[i] = buffer.getReadPointer(c)[i] * gain
+ + tone * gain + side + float(state_ * 1e-9);
+ }
+ // The input-sidechain channels share these output slots. Leave finite
+ // data behind: a later callback must initialize its active input range,
+ // including after a larger block. Leakage is audible on the main output.
+ for (int c = 2; c < buffer.getNumChannels(); ++c)
+ juce::FloatVectorOperations::fill(buffer.getWritePointer(c), 0.125f, buffer.getNumSamples());
+ processing_.clear(std::memory_order_release);
+ }
+ private:
+ static BusesProperties probeBuses() {
+ auto buses = BusesProperties()
+ .withInput("Input", juce::AudioChannelSet::stereo(), true)
+ .withInput("Sidechain", juce::AudioChannelSet::stereo(), false)
+ .withOutput("Output", juce::AudioChannelSet::stereo(), true);
+ // A typical large sampler's 28 stereo outputs exercise the host's
+ // reserved-vs-active clearing cost without a commercial dependency.
+ for (int i = 1; i < 28; ++i)
+ buses = buses.withOutput("Aux " + juce::String(i), juce::AudioChannelSet::stereo(), true);
+ return buses;
+ }
+ juce::AudioParameterInt* work_ = nullptr;
+ juce::AudioParameterFloat* gain_ = nullptr;
+ std::atomic_flag processing_ = ATOMIC_FLAG_INIT;
+ std::array<bool, 128> notes_{};
+ double rate_ = 48000, phase_ = 0, state_ = 0.1;
+ int pitch_ = 60;
+};
+
+juce::AudioProcessor* JUCE_CALLTYPE createPluginFilter() { return new RenderProbe(); }
diff --git a/src/native/nota.engine/src/devices/Device.h b/src/native/nota.engine/src/devices/Device.h
index 84df7b35..1226ac16 100644
--- a/src/native/nota.engine/src/devices/Device.h
+++ b/src/native/nota.engine/src/devices/Device.h
@@ -75,11 +75,16 @@ class Device {
// 4=Utility, 6=Amp), or -1 for a hosted plugin. Message thread only.
virtual int32_t builtinKind() const { return -1; }
- // True when processing this device runs a hosted plugin instance — the device itself,
- // or one nested in it (a rack's chains). Such a device stays on the audio thread:
- // plugin instances aren't safe to process from a pool worker. Audio thread safe.
+ // True when processing this device runs a hosted plugin instance - the device itself,
+ // or one nested in it (a rack's chains). Identity is separate from the render
+ // scheduling contract below. Audio thread safe.
virtual bool hostsPlugin() const { return builtinKind() < 0; }
+ // May process on a pool worker, with exclusive ownership of this instance for
+ // the whole block. Hosted adapters must explicitly opt in after auditing their
+ // format/buffers; unknown hosted types and hosted-containing racks stay serial.
+ virtual bool supportsParallelRender() const { return !hostsPlugin(); }
+
// Stable plugin identifier for project save (M7-6c); empty for built-ins.
// Message thread only.
virtual std::string pluginIdentifier() const { return {}; }
diff --git a/src/native/nota.engine/src/devices/Instrument.h b/src/native/nota.engine/src/devices/Instrument.h
index 481c8cfa..a6a2f97c 100644
--- a/src/native/nota.engine/src/devices/Instrument.h
+++ b/src/native/nota.engine/src/devices/Instrument.h
@@ -230,11 +230,14 @@ class Instrument {
// -1 = hosted plugin / unknown. Message thread only.
virtual int32_t kind() const { return -1; }
- // True when rendering this instrument runs a hosted plugin instance — the instrument
- // itself, or one nested in it (a rack's chains). Keeps the track off the render pool
- // (see Device::hostsPlugin). Audio thread safe.
+ // True when rendering this instrument runs a hosted plugin instance - the instrument
+ // itself, or one nested in it (a rack's chains). Audio thread safe.
virtual bool hostsPlugin() const { return kind() < 0; }
+ // Same exclusive-per-block worker contract as Device::supportsParallelRender.
+ // Unknown hosted instruments and hosted-containing racks remain serial.
+ virtual bool supportsParallelRender() const { return !hostsPlugin(); }
+
// Human-readable name (built-in "Synth"/"Sampler", or the hosted plugin's name).
// Used to label the track. Message thread only.
virtual const char* displayName() const { return "Instrument"; }
diff --git a/src/native/nota.engine/src/engine/Engine.h b/src/native/nota.engine/src/engine/Engine.h
index daaab7d6..40d8bd9e 100644
--- a/src/native/nota.engine/src/engine/Engine.h
+++ b/src/native/nota.engine/src/engine/Engine.h
@@ -2325,7 +2325,7 @@ class Engine {
bool audible = false, capturing = false, feeding = false, toMix = false;
bool monitoring = false, frozenActive = false, sessionActive = false;
bool postTapMuted = false; // sidechain tap muted with its source leaf (vocoder key)
- bool eligible = false; // parallel DSP (built-ins only, no shared writers)
+ bool eligible = false; // worker-capable DSP, no shared writers
LeafPath path = LeafPath::Skip;
int wid = -1; // pool worker that rendered this track (diagnostic)
int64_t workNs = 0; // time its parallel DSP took (sizes the next block's helpers)
@@ -2380,11 +2380,15 @@ class Engine {
// kRtMaxHoldSeconds), so a wrong guess costs one late block, rarely.
int64_t leafWorkNs_ = 0;
int64_t parWorkNs_ = 0;
+ int64_t leafPeakNs_ = 0; // largest indivisible task: total work alone can under-size helpers
bool deviceBlock_ = false; // render() (a device callback) vs renderOffline()
bool rtParallel_ = false;
double rtParallelLeftNs_ = 0;
double rtProbeLeftNs_ = 0;
- static constexpr double kRtSizeLoad = 0.85; // helpers: finish within this much of the buffer
+ // Once parallel rendering is needed, reserve half the callback for voice
+ // attacks and scheduler jitter. Near-deadline sizing leaves four large
+ // plug-in jobs in two serial waves despite useful cores being available.
+ static constexpr double kRtSizeLoad = 0.50;
static constexpr double kRtHoldSeconds = 2.0;
static constexpr double kRtMaxHoldSeconds = 32.0;
static constexpr double kRtProbeSeconds = 0.5;
diff --git a/src/native/nota.engine/src/engine/Engine_Render.cpp b/src/native/nota.engine/src/engine/Engine_Render.cpp
index 8aa8bb42..76d8acb4 100644
--- a/src/native/nota.engine/src/engine/Engine_Render.cpp
+++ b/src/native/nota.engine/src/engine/Engine_Render.cpp
@@ -2484,19 +2484,20 @@ void Engine::mixGraph(Graph* g, float* out, int32_t frames, double blockStart, b
}
w.tapRec = (recSrc > 0 && t.id() == recSrc); // internal resampling source
- // Parallel eligibility: built-in DSP only (hosted plugin instances
- // are not thread-safe across threads — also when nested in a rack),
- // no shared-queue writers (record queues are SPSC), no hardware
- // monitoring.
+ // Parallel eligibility is an instance's processing contract, not its
+ // hosted identity: independent audited VST3 adapters own their state
+ // just like built-ins. Unknown formats and hosted-containing racks
+ // remain serial. Shared-queue writers (record queues are SPSC) must
+ // stay on the caller regardless of processor capability.
bool eligible = parallelOk;
const int32_t srcId = t.midiFromTrackId();
if (srcId >= 0 && t.id() == recordTrackId_ && (playing || countInActive_) && recArmed && spb > 0.0)
eligible = false; // captureRouted destination prints into shared takes
if (srcId >= 0 && t.armed()) eligible = false; // routed source prints while armed
- if (eligible && t.instrument && t.instrument->hostsPlugin()) eligible = false;
+ if (eligible && t.instrument && !t.instrument->supportsParallelRender()) eligible = false;
if (eligible)
for (auto& d : t.devices)
- if (d && !d->bypassed() && d->hostsPlugin()) {
+ if (d && !d->bypassed() && !d->supportsParallelRender()) {
eligible = false;
break;
}
@@ -2535,7 +2536,29 @@ void Engine::mixGraph(Graph* g, float* out, int32_t frames, double blockStart, b
}
if (rtParallel_) {
const double work = (double)std::max(leafWorkNs_, parWorkNs_);
- const int threads = (int)std::ceil(work / (kRtSizeLoad * periodNs));
+ const double target = kRtSizeLoad * periodNs;
+ int threads = (int)std::ceil(work / target);
+ // Track jobs are indivisible: four 1.4 ms jobs cannot meet a
+ // 2.67 ms deadline on three threads even though their total
+ // divided by three fits. List scheduling's upper bound is
+ // work / threads + (1 - 1 / threads) * largestJob. Use it to
+ // size helpers without sorting jobs or allocating in the callback.
+ const double peak = std::min(work, (double)leafPeakNs_);
+ if (peak > 0) {
+ const int available = std::min(m, pool_->workerCount() + 1);
+ if (peak < target) {
+ // T >= (work - peak) / (target - peak): the smallest count
+ // whose list-scheduling bound still fits the target.
+ const double needed = std::ceil((work - peak) / (target - peak));
+ threads = std::max(threads, (int)std::min((double)available, needed));
+ } else {
+ // The largest job alone overflows the target: no count meets
+ // the bound. Every extra worker still lowers it (the small
+ // jobs run beside the heavy one instead of queueing in front),
+ // so take the whole pool rather than park on the average.
+ threads = std::max(threads, available);
+ }
+ }
helpers = std::clamp(threads - 1, 1, std::max(1, m - 1));
}
}
@@ -2558,12 +2581,15 @@ void Engine::mixGraph(Graph* g, float* out, int32_t frames, double blockStart, b
// pool's summed task time while it runs (see leafWorkNs_).
if (!offline && m > 0) {
int64_t work = 0;
+ int64_t peak = 0;
bool alone = true;
for (int j = 0; j < m; ++j) {
const LeafWork& w = rs_->leafWork[(size_t)rs_->parIdx[(size_t)j]];
work += w.workNs;
+ peak = std::max(peak, w.workNs);
alone = alone && w.wid == pool_->workerCount();
}
+ leafPeakNs_ += (peak - leafPeakNs_) / 16;
if (rtParallel_) {
parWorkNs_ += (work - parWorkNs_) / 16;
} else {
diff --git a/tests/Nota.SmokeTest/HostedPluginProfile.cs b/tests/Nota.SmokeTest/HostedPluginProfile.cs
new file mode 100644
index 00000000..717f11ee
--- /dev/null
+++ b/tests/Nota.SmokeTest/HostedPluginProfile.cs
@@ -0,0 +1,167 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Opt-in profile of an installed, licensed VST3. Offline device-path calls produce
+// no hardware audio and use an isolated catalog; never part of the normal smoke run.
+
+using System.Diagnostics;
+using System.Runtime.InteropServices;
+using System.Text.Json;
+using Nota.Infrastructure;
+
+namespace Nota.SmokeTest;
+
+internal static class HostedPluginProfile
+{
+ [StructLayout(LayoutKind.Sequential)]
+ private struct WindowMessage
+ {
+ public IntPtr Window;
+ public uint Message;
+ public UIntPtr WParam;
+ public IntPtr LParam;
+ public uint Time;
+ public int X, Y;
+ public uint Private;
+ }
+ [DllImport("user32.dll", EntryPoint = "PeekMessageW")]
+ private static extern bool PeekMessage(out WindowMessage message, IntPtr window, uint first, uint last, uint flags);
+ [DllImport("user32.dll")]
+ private static extern bool TranslateMessage(in WindowMessage message);
+ [DllImport("user32.dll", EntryPoint = "DispatchMessageW")]
+ private static extern IntPtr DispatchMessage(in WindowMessage message);
+
+ private static void Pump()
+ {
+ if (OperatingSystem.IsWindows())
+ while (PeekMessage(out var message, IntPtr.Zero, 0, 0, 1))
+ { TranslateMessage(in message); DispatchMessage(in message); }
+ else NotaEngine.PumpPluginHost();
+ }
+
+ public static void Run(string pluginPath, int frames = 128, int rate = 48000)
+ {
+ string scratch = Directory.CreateTempSubdirectory("nota-plugin-profile-").FullName;
+ NotaEngine.SetDataDir(scratch);
+ string native = Path.GetFullPath("src/native/nota.engine/build");
+ string worker = Path.Combine(native, OperatingSystem.IsWindows() ? "nota-scanworker.exe" : "nota-scanworker");
+ NotaEngine.ScanPlugins(worker, Path.GetDirectoryName(pluginPath)!, false);
+ string name = Path.GetFileNameWithoutExtension(pluginPath);
+ int catalog = Enumerable.Range(0, NotaEngine.PluginCount)
+ .First(i => NotaEngine.PluginDescription(i)?.Contains(name, StringComparison.OrdinalIgnoreCase) == true);
+ foreach (var (instances, helpers) in new[] { (1, 4), (4, 0), (4, 4) })
+ {
+ Console.WriteLine($"PROFILE loading {instances} {name}, helpers={helpers}; {rate} Hz / {frames} frames");
+ using var engine = new NotaEngine { RenderThreads = helpers };
+ var buffer = new float[frames * 2];
+ engine.RenderOffline(buffer, frames, rate);
+ for (int i = 0; i < instances; i++)
+ {
+ int track = engine.AddPluginInstrumentTrack(catalog);
+ engine.SetTrackVolume(track, 0.1f);
+ int clip = engine.AddMidiClip(track, 0, 128);
+ engine.SetClipNotes(track, clip, [new NotaNote(60 + i * 3, 0, 120, 0.8f)]);
+ engine.SetMidiClipController(track, clip, 11, [new AutomationPoint(0, 0.8f)]);
+ engine.SetMidiClipController(track, clip, 1, [new AutomationPoint(0, 0.8f)]);
+ // Probe-only per-instance render load, the same knob the HostedRenderPoolTests
+ // guard uses (Work reads 0..4096 / 4096). 0.5 ≈ 1.4 ms per instance at a
+ // 128-frame block: four instances ≈ 220 % of the period, the load of #532.
+ int workParam = Enumerable.Range(0, engine.PluginParamCount(track, -1))
+ .FirstOrDefault(j => engine.PluginParamName(track, -1, j) == "Work");
+ if (engine.PluginParamName(track, -1, workParam) == "Work")
+ engine.PluginParamSet(track, -1, workParam, 0.5f);
+ }
+ // Commercial instruments may defer model/license initialization to
+ // their message thread. Give it a real pump before sending the notes.
+ var initialize = Stopwatch.StartNew();
+ while (initialize.ElapsedMilliseconds < 1000)
+ { engine.RenderDeviceBlock(buffer, frames); Pump(); Thread.Sleep(2); }
+ engine.Seek(0); engine.Play();
+ const int warmup = 120, count = 200;
+ double period = frames * 1000.0 / rate;
+ var samples = new double[count]; double sum = 0;
+ for (int i = 0; i < warmup; i++) { engine.RenderDeviceBlock(buffer, frames); Pump(); }
+ double workerCpu = engine.RenderThreadsCpuSeconds;
+ var wall = Stopwatch.StartNew();
+ for (int i = 0; i < count; i++)
+ {
+ long start = Stopwatch.GetTimestamp();
+ engine.RenderDeviceBlock(buffer, frames);
+ samples[i] = Stopwatch.GetElapsedTime(start).TotalMilliseconds;
+ foreach (float value in buffer) sum += value * (double)value;
+ Pump();
+ double due = (i + 1) * period;
+ double ahead = due - wall.Elapsed.TotalMilliseconds;
+ if (ahead > 1) Thread.Sleep(TimeSpan.FromMilliseconds(ahead - 0.5));
+ while (wall.Elapsed.TotalMilliseconds < due) Thread.SpinWait(25);
+ }
+ workerCpu = (engine.RenderThreadsCpuSeconds - workerCpu) * 1000;
+ int late = samples.Count(t => t > period); double mean = samples.Average();
+ Array.Sort(samples);
+ Console.WriteLine("PLUGIN_PROFILE " + JsonSerializer.Serialize(new { name, instances, helpers, rate, frames,
+ medianMs = samples[count / 2], p95Ms = samples[(int)(count * 0.95)], meanMs = mean,
+ deadlinePercent = mean / period * 100, late, count, workerCpuMs = workerCpu,
+ rms = Math.Sqrt(sum / (count * frames * 2)) }));
+ }
+ }
+
+ public static void RunProject(string bundle, int frames = 128, int rate = 48000, string? onlyMode = null)
+ {
+ // Seed a scratch catalog from installed identifiers, never scan/save into
+ // the user's catalog or write a project. Apply reads state blobs in place.
+ string scratch = Directory.CreateTempSubdirectory("nota-project-profile-").FullName;
+ File.Copy(Path.Combine(NotaPaths.DataDir, "plugins.xml"), Path.Combine(scratch, "plugins.xml"));
+ NotaEngine.SetDataDir(scratch);
+ foreach (string mode in new[] { "one-swam", "four-swam", "complete-project", "four-swam-all-workers" })
+ {
+ if (onlyMode is not null && mode != onlyMode) continue;
+ bool allWorkers = mode == "four-swam-all-workers";
+ var doc = ProjectService.Load(bundle);
+ var swam = doc.Tracks.Where(t => t.Instrument?.PluginId?.Contains("SWAM") == true).ToArray();
+ if (swam.Length == 0) throw new InvalidOperationException("Project contains no SWAM instrument");
+ double startBeat = swam.SelectMany(t => t.MidiClips)
+ .Where(c => c.Active && c.Notes.Length > 0)
+ .Select(c => c.StartBeat + c.Notes.Min(n => n.Start)).DefaultIfEmpty(0).Min();
+ if (mode != "complete-project")
+ foreach (var track in doc.Tracks)
+ track.Mute = mode == "one-swam" ? track != swam[0] : !swam.Contains(track);
+ Console.WriteLine($"PROJECT_PROFILE loading {mode}; {rate} Hz / {frames} frames; start beat {startBeat:0.###}");
+ using var engine = new NotaEngine();
+ var buffer = new float[frames * 2];
+ engine.RenderOffline(buffer, frames, rate);
+ var warnings = ProjectService.Apply(doc, engine, bundle);
+ if (warnings.Count > 0) throw new InvalidOperationException("Project profile restore warnings: " + string.Join("; ", warnings));
+ engine.SetMetronome(false); engine.SetLoop(false, 0, 4);
+ var initialize = Stopwatch.StartNew();
+ while (initialize.ElapsedMilliseconds < 1200)
+ { engine.RenderDeviceBlock(buffer, frames); Pump(); Thread.Sleep(2); }
+ engine.Seek(startBeat); engine.Play();
+ for (int i = 0; i < 120; i++)
+ { if (allWorkers) engine.RenderOffline(buffer, frames); else engine.RenderDeviceBlock(buffer, frames); Pump(); }
+ const int count = 400;
+ var samples = new double[count]; double squares = 0;
+ double workerCpu = engine.RenderThreadsCpuSeconds;
+ double period = frames * 1000.0 / rate;
+ var wall = Stopwatch.StartNew();
+ for (int i = 0; i < count; i++)
+ {
+ long before = Stopwatch.GetTimestamp();
+ if (allWorkers) engine.RenderOffline(buffer, frames); else engine.RenderDeviceBlock(buffer, frames);
+ samples[i] = Stopwatch.GetElapsedTime(before).TotalMilliseconds;
+ foreach (float value in buffer) squares += value * (double)value;
+ Pump();
+ double due = (i + 1) * period;
+ double ahead = due - wall.Elapsed.TotalMilliseconds;
+ if (ahead > 1) Thread.Sleep(TimeSpan.FromMilliseconds(ahead - 0.5));
+ while (wall.Elapsed.TotalMilliseconds < due) Thread.SpinWait(25);
+ }
+ workerCpu = (engine.RenderThreadsCpuSeconds - workerCpu) * 1000;
+ double mean = samples.Average(); int late = samples.Count(t => t > period);
+ Array.Sort(samples);
+ Console.WriteLine("SAVED_PROJECT_PROFILE " + JsonSerializer.Serialize(new { mode, rate, frames,
+ helpers = engine.RenderThreads, startBeat, medianMs = samples[count / 2], p95Ms = samples[(int)(count * 0.95)],
+ meanMs = mean, deadlinePercent = mean / period * 100, late, count, workerCpuMs = workerCpu,
+ rms = Math.Sqrt(squares / (count * frames * 2)) }));
+ }
+ }
+}
diff --git a/tests/Nota.SmokeTest/HostedRenderPoolTests.cs b/tests/Nota.SmokeTest/HostedRenderPoolTests.cs
new file mode 100644
index 00000000..5fc28798
--- /dev/null
+++ b/tests/Nota.SmokeTest/HostedRenderPoolTests.cs
@@ -0,0 +1,318 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Real VST3 instances through the shipped JUCE adapters and engine C ABI. Run in a
+// child process with its own catalog, so the fixture never enters the user's library.
+
+using System.Diagnostics;
+using System.Text.Json;
+using Nota.Infrastructure;
+
+namespace Nota.SmokeTest;
+
+internal static class HostedRenderPoolTests
+{
+ private const int Rate = 48000, Block = 128;
+ private static string NativeDir
+ {
+ get
+ {
+ if (Environment.GetEnvironmentVariable("NOTA_RENDER_NATIVE_DIR") is { Length: > 0 } path) return path;
+ for (var dir = new DirectoryInfo(Environment.CurrentDirectory); dir is not null; dir = dir.Parent)
+ {
+ path = Path.Combine(dir.FullName, "src", "native", "nota.engine", "build");
+ if (Directory.Exists(path)) return path;
+ }
+ throw new DirectoryNotFoundException("Native build directory unavailable for hosted render tests.");
+ }
+ }
+
+ public static IEnumerable<(bool Ok, string Label)> RunIsolated()
+ {
+ var start = new ProcessStartInfo("dotnet") { RedirectStandardOutput = true,
+ RedirectStandardError = true, UseShellExecute = false, CreateNoWindow = true };
+ start.ArgumentList.Add(typeof(HostedRenderPoolTests).Assembly.Location);
+ start.ArgumentList.Add("--hosted-render-pool");
+ using var child = Process.Start(start)!;
+ // A native hang in the child must fail this module, not stall the whole
+ // smoke suite: drain both streams while a timeout runs (ReadToEnd blocks,
+ // so a timeout after it would never fire), then kill the child's tree.
+ var stdout = child.StandardOutput.ReadToEndAsync();
+ var stderr = child.StandardError.ReadToEndAsync();
+ if (!child.WaitForExit(TimeSpan.FromMinutes(10)))
+ {
+ try { child.Kill(entireProcessTree: true); }
+ catch (InvalidOperationException) { } // already exited between the timeout and the kill
+ stdout.GetAwaiter().GetResult();
+ stderr.GetAwaiter().GetResult();
+ yield return (false, "isolated real VST3 render-pool regressions (did not finish within 10 minutes, killed)");
+ yield break;
+ }
+ Console.Write(stdout.GetAwaiter().GetResult());
+ if (child.ExitCode != 0) Console.Write(stderr.GetAwaiter().GetResult());
+ yield return (child.ExitCode == 0, "isolated real VST3 render-pool regressions");
+ }
+
+ private static int Param(NotaEngine e, int track, int device, string name)
+ {
+ for (int i = 0; i < e.PluginParamCount(track, device); i++)
+ if (e.PluginParamName(track, device, i) == name) return i;
+ throw new InvalidOperationException($"Render probe parameter missing: {name}");
+ }
+
+ private static NotaEngine Session(int catalog, int helpers, int work, bool inserts = false, bool routing = false, int tracks = 4)
+ {
+ var e = new NotaEngine { RenderThreads = helpers };
+ e.RenderOffline(new float[Block * 2], Block, Rate);
+ e.SetBpm(120);
+ int group = routing ? e.AddGroupTrack() : -1;
+ if (routing) e.AddReturnTrack();
+ int previousTrack = -1;
+ for (int i = 0; i < tracks; i++)
+ {
+ int t = inserts ? e.AddInstrumentTrack() : e.AddPluginInstrumentTrack(catalog);
+ int device = inserts ? e.AddTrackEffectPlugin(t, catalog) : -1;
+ e.SetTrackVolume(t, 0.2f);
+ e.SetTrackPan(t, (i - 1.5f) / 4);
+ int clip = e.AddMidiClip(t, 0, 16);
+ e.SetClipNotes(t, clip, [new NotaNote(48 + i * 3, 0, 0.15, 0.8f),
+ new NotaNote(60 + i, 0.2, 8, 0.7f)]);
+ e.PluginParamSet(t, device, Param(e, t, device, "Work"), work / 4096f);
+ if (routing)
+ {
+ e.SetTrackGroup(t, group); e.SetTrackSend(t, 0, 0.1f);
+ int lane = e.AddPluginAutomationLane(t, device, e.PluginParamId(t, device, Param(e, t, device, "Gain")));
+ e.SetAutomationPoints(t, lane, [new AutomationPoint(0, 0.3f), new AutomationPoint(1, 0.8f)]);
+ if (inserts && previousTrack >= 0) e.SetDeviceSidechainSource(t, device, previousTrack);
+ }
+ previousTrack = t;
+ }
+ e.Seek(0); e.Play(); return e;
+ }
+
+ private static float[] Render(NotaEngine e, int blocks = 128, Action<int>? edit = null)
+ {
+ var all = new float[blocks * Block * 2]; var block = new float[Block * 2];
+ for (int i = 0; i < blocks; i++)
+ {
+ edit?.Invoke(i);
+ e.RenderOffline(block, Block);
+ block.CopyTo(all, i * Block * 2);
+ }
+ return all;
+ }
+
+ private sealed record Measurement(double MedianMs, double P95Ms, double CallerMs,
+ double WorkerMs, double DeadlinePercent, int Late, int Blocks);
+
+ private static Measurement Measure(NotaEngine e, bool device, int blocks = 100, int block = Block, int warmup = 80)
+ {
+ var buffer = new float[block * 2];
+ // Adaptive device scheduling must settle before measuring participation/latency.
+ for (int i = 0; i < warmup; i++)
+ if (device) e.RenderDeviceBlock(buffer, block); else e.RenderOffline(buffer, block);
+ var samples = new double[blocks];
+ double workerStart = e.RenderThreadsCpuSeconds;
+ var wall = Stopwatch.StartNew();
+ for (int i = 0; i < blocks; i++)
+ {
+ long before = Stopwatch.GetTimestamp();
+ if (device) e.RenderDeviceBlock(buffer, block); else e.RenderOffline(buffer, block);
+ samples[i] = Stopwatch.GetElapsedTime(before).TotalMilliseconds;
+ if (buffer.Any(v => !float.IsFinite(v))) throw new InvalidOperationException("Reentrant/non-finite plugin render");
+ if (device)
+ {
+ double due = (i + 1) * block * 1000.0 / Rate;
+ double ahead = due - wall.Elapsed.TotalMilliseconds;
+ if (ahead > 1) Thread.Sleep(TimeSpan.FromMilliseconds(ahead - 0.5));
+ while (wall.Elapsed.TotalMilliseconds < due) Thread.SpinWait(25);
+ }
+ }
+ double workerMs = (e.RenderThreadsCpuSeconds - workerStart) * 1000;
+ double callerMs = samples.Sum(); int late = samples.Count(t => t > block * 1000.0 / Rate);
+ Array.Sort(samples);
+ return new(samples[blocks / 2], samples[(int)(blocks * 0.95)], callerMs, workerMs,
+ callerMs / blocks / (block * 1000.0 / Rate) * 100, late, blocks);
+ }
+
+ public static IEnumerable<(bool Ok, string Label)> Run()
+ {
+ string scratch = Directory.CreateTempSubdirectory("nota-hosted-render-").FullName;
+ NotaEngine.SetDataDir(scratch);
+ try
+ {
+ string fixture = Path.Combine(NativeDir, "nota-render-probe_artefacts", "Release", "VST3");
+ string worker = Path.Combine(NativeDir, OperatingSystem.IsWindows() ? "nota-scanworker.exe" : "nota-scanworker");
+ if (!Directory.Exists(fixture)) throw new DirectoryNotFoundException("Build nota-render-probe_VST3 before hosted render tests.");
+ NotaEngine.ScanPlugins(worker, fixture, true);
+ int catalog = Enumerable.Range(0, NotaEngine.PluginCount)
+ .First(i => NotaEngine.PluginDescription(i)?.StartsWith("Nota Render Probe |") == true);
+ yield return (catalog >= 0, "real VST3 fixture scanned into isolated temporary catalog");
+
+ foreach (var result in BufferChecks(catalog)) yield return result;
+
+ foreach (bool inserts in new[] { false, true })
+ {
+ using var one = Session(catalog, 0, 32, inserts, routing: true);
+ using var many = Session(catalog, 4, 32, inserts, routing: true);
+ var a = Render(one); var b = Render(many);
+ yield return (a.Any(v => Math.Abs(v) > 0.001) && a.All(float.IsFinite) && a.SequenceEqual(b),
+ $"VST3 {(inserts ? "inserts/sidechains" : "instruments")}: MIDI, automation, group/return output is sample-identical with helpers");
+ }
+
+ float[] Edited(int helpers)
+ {
+ using var e = Session(catalog, helpers, 32);
+ var ids = Enumerable.Range(0, e.TrackCount).Select(i =>
+ e.TryGetTrackInfo(i, out var track) ? track.Id : -1).ToArray();
+ int effect = e.AddTrackEffectPlugin(ids[0], catalog);
+ return Render(e, 80, i =>
+ {
+ if (i == 8) e.SetDeviceBypassed(ids[0], effect, true);
+ if (i == 16) e.SetDeviceBypassed(ids[0], effect, false);
+ if (i == 24) e.RemoveDevice(ids[0], effect);
+ if (i == 32) e.SetTrackInstrumentPlugin(ids[1], catalog);
+ if (i == 48) e.RemoveTrack(ids[2]);
+ if (i == 56 && !e.Undo()) throw new InvalidOperationException("Hosted remove undo failed");
+ });
+ }
+ yield return (Edited(0).SequenceEqual(Edited(4)),
+ "VST3 bypass, insert removal, instrument replacement and track undo preserve serial output");
+
+ using (var effects = Session(catalog, 4, 1024, inserts: true))
+ {
+ var measured = Measure(effects, false, 40);
+ yield return (measured.WorkerMs > 1, $"real VST3 insert adapters use helpers ({measured.WorkerMs:0.0} ms CPU)");
+ }
+
+ using (var inline = Session(catalog, 0, 1024))
+ using (var parallel = Session(catalog, 4, 1024))
+ {
+ var serial = Measure(inline, false); var many = Measure(parallel, false);
+ yield return (many.WorkerMs > 1, $"VST3 offline helpers participate ({many.WorkerMs:0.0} ms worker CPU)");
+ yield return TimingBudget.Check(true, many.MedianMs < serial.MedianMs * 0.9,
+ $"four VST3 tracks: offline median {many.MedianMs:0.000} ms vs serial {serial.MedianMs:0.000} ms");
+ yield return TimingBudget.Check(true, many.CallerMs + many.WorkerMs < serial.CallerMs * 3,
+ "VST3 parallel processing keeps total render CPU work bounded");
+ Console.WriteLine("HOSTED_OFFLINE " + JsonSerializer.Serialize(new { serial, parallel = many }));
+ }
+
+ using (var inline = Session(catalog, 0, 2048))
+ using (var parallel = Session(catalog, 4, 2048))
+ {
+ var serial = Measure(inline, true); var many = Measure(parallel, true);
+ yield return (many.WorkerMs > 1, $"VST3 overloaded device helpers participate ({many.WorkerMs:0.0} ms worker CPU)");
+ yield return TimingBudget.Check(true, many.MedianMs < serial.MedianMs * 0.9,
+ $"four VST3 tracks: device median {many.MedianMs:0.000} ms vs serial {serial.MedianMs:0.000} ms");
+ // The Work=2048 probe is fixed, not machine-scaled: a single instance
+ // may cost more than the callback period on a slower machine, where no
+ // helper count can save the deadline. Calibrate like RenderPoolTests'
+ // overload check and enforce the late-block gate only when one instance
+ // could meet the period at all.
+ double devicePeriodMs = Block * 1000.0 / Rate;
+ bool oneInstanceFits;
+ using (var cal = Session(catalog, 0, 2048, tracks: 1))
+ oneInstanceFits = Measure(cal, true, 40).MedianMs <= devicePeriodMs;
+ yield return TimingBudget.Check(true, !oneInstanceFits || many.Late <= 1,
+ !oneInstanceFits
+ ? $"one VST3 probe render does not fit a {devicePeriodMs:0.00} ms period on this machine; the late-block gate is skipped ({many.Late}/{many.Blocks} late with helpers)"
+ : $"four indivisible VST3 jobs: {many.Late}/{many.Blocks} device deadlines missed after warm-up (<= 1)");
+ Console.WriteLine("HOSTED_DEVICE " + JsonSerializer.Serialize(new { serial, parallel = many }));
+ if (Environment.GetEnvironmentVariable("NOTA_RENDER_REPORT") is { Length: > 0 } report)
+ File.WriteAllText(report, JsonSerializer.Serialize(new { serial, parallel = many }, new JsonSerializerOptions { WriteIndented = true }));
+ }
+
+ using (var light = Session(catalog, 4, 0))
+ {
+ var measured = Measure(light, true, 150);
+ yield return (measured.WorkerMs < 15, $"light VST3 device workload leaves helpers parked ({measured.WorkerMs:0.0} ms CPU)");
+ }
+
+ using (var oneHeavy = Session(catalog, 0, 1024, tracks: 1))
+ using (var fourHeavy = Session(catalog, 4, 1024))
+ {
+ var one = Measure(oneHeavy, true, block: 512);
+ var four = Measure(fourHeavy, true, block: 512);
+ yield return TimingBudget.Check(true, four.MedianMs <= one.MedianMs * 1.6,
+ $"512-frame large VST3 jobs reserve headroom: four {four.MedianMs:0.000} ms vs one {one.MedianMs:0.000} ms (<= 1.6x)");
+ yield return TimingBudget.Check(true, four.CallerMs + four.WorkerMs <= one.CallerMs * 4 * 2,
+ "512-frame VST3 headroom keeps caller/worker work proxy bounded (<= 2x four serial tracks)");
+ Console.WriteLine("HOSTED_HEADROOM " + JsonSerializer.Serialize(new { frames = 512, one, four }));
+ }
+
+ using (var rack = new NotaEngine { RenderThreads = 4 })
+ {
+ rack.RenderOffline(new float[Block * 2], Block, Rate);
+ int t = rack.AddInstrumentRackTrack();
+ rack.RackAddPluginInstrumentChain(t, catalog);
+ int clip = rack.AddMidiClip(t, 0, 16);
+ rack.SetClipNotes(t, clip, [new NotaNote(60, 0, 8, 0.8f)]); rack.Play();
+ double cpu = rack.RenderThreadsCpuSeconds;
+ var samples = Render(rack, 64);
+ yield return (samples.Any(v => Math.Abs(v) > 0.001) && rack.RenderThreadsCpuSeconds - cpu < 0.01,
+ "hosted instrument rack retains serial fallback and audible output");
+ }
+
+ using (var live = Session(catalog, 4, 32))
+ {
+ bool stop = false, finite = true;
+ int rendered = 0;
+ Exception? renderFailure = null;
+ var render = new Thread(() =>
+ {
+ try
+ {
+ var block = new float[Block * 2];
+ while (!Volatile.Read(ref stop))
+ {
+ live.RenderOffline(block, Block);
+ finite &= block.All(float.IsFinite);
+ Interlocked.Increment(ref rendered);
+ }
+ }
+ catch (Exception ex) { renderFailure = ex; }
+ });
+ render.Start();
+ try
+ {
+ for (int i = 0; i < 8; i++)
+ {
+ int added = live.AddPluginInstrumentTrack(catalog);
+ int clip = live.AddMidiClip(added, 0, 16);
+ live.SetClipNotes(added, clip, [new NotaNote(60, 0, 8, 0.8f)]);
+ Thread.Sleep(2);
+ live.RemoveTrack(added);
+ }
+ }
+ finally { Volatile.Write(ref stop, true); render.Join(); }
+ yield return (rendered > 0 && finite && renderFailure is null,
+ $"VST3 graph additions/removals during worker renders stay finite and complete ({rendered} blocks)");
+ }
+ }
+ finally { NotaEngine.SetDataDir(null); }
+ }
+
+ private static IEnumerable<(bool Ok, string Label)> BufferChecks(int catalog)
+ {
+ foreach (bool inserts in new[] { false, true })
+ {
+ using var smallEngine = Session(catalog, 0, 0, inserts);
+ using var largeEngine = Session(catalog, 0, 0, inserts);
+ smallEngine.StopTransport(); largeEngine.StopTransport();
+ bool clean = true;
+ foreach (int frames in new[] { 128, 16, 8192, 64, 1024, 16384, 128 })
+ {
+ var samples = new float[frames * 2];
+ smallEngine.RenderOffline(samples, frames);
+ clean &= samples.All(v => float.IsFinite(v) && Math.Abs(v) < 1e-7);
+ }
+ string adapter = inserts ? "insert" : "instrument";
+ yield return (clean, $"VST3 {adapter}: changing callback sizes leave no stale main/sidechain input");
+ var small = Measure(smallEngine, false, 400);
+ var large = Measure(largeEngine, false, 40, block: 8192, warmup: 8);
+ yield return TimingBudget.Check(true, small.MedianMs * 32 < large.MedianMs,
+ $"56-channel VST3 {adapter}: 128-frame cost {small.MedianMs:0.0000} ms scales below 1/32 of 8192-frame cost {large.MedianMs:0.0000} ms");
+ Console.WriteLine("HOSTED_BUFFER " + JsonSerializer.Serialize(new { adapter, channels = 56, small, large }));
+ }
+ }
+}
diff --git a/tests/Nota.SmokeTest/PluginStoreTests.cs b/tests/Nota.SmokeTest/PluginStoreTests.cs
index 422eabf5..78c23504 100644
--- a/tests/Nota.SmokeTest/PluginStoreTests.cs
+++ b/tests/Nota.SmokeTest/PluginStoreTests.cs
@@ -259,7 +259,14 @@ internal static class PluginStoreTests
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)");
+ var probed = Probed();
+ // The skip-scan must probe nothing (functional) and run fast (budget).
+ // The timing half is wall-clock, like every other budget: a shared runner
+ // can run the first scan unusually fast and the second slowly, failing a
+ // check that skipped all its work. Under CI the budget prints and does
+ // not fail (TimingBudget).
+ yield return TimingBudget.Check(probed == 0, 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);
diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.cs
index 7518df88..c3a6990c 100644
--- a/tests/Nota.SmokeTest/Program.cs
+++ b/tests/Nota.SmokeTest/Program.cs
@@ -31,6 +31,24 @@ static float MonoRms(float[] buf)
Console.WriteLine($"engine v{NotaEngine.Version}");
+if (args.Length >= 2 && args[0] == "--profile-project")
+{
+ HostedPluginProfile.RunProject(args[1], args.Length > 2 ? int.Parse(args[2]) : 128,
+ args.Length > 3 ? int.Parse(args[3]) : 48000, args.Length > 4 ? args[4] : null);
+ return 0;
+}
+if (args.Length >= 2 && args[0] == "--profile-hosted")
+{
+ HostedPluginProfile.Run(args[1], args.Length > 2 ? int.Parse(args[2]) : 128,
+ args.Length > 3 ? int.Parse(args[3]) : 48000);
+ return 0;
+}
+if (args.Contains("--hosted-render-pool"))
+{
+ foreach (var (ok, label) in HostedRenderPoolTests.Run()) Check(ok, label);
+ return failures == 0 ? 0 : 1;
+}
+
// --- architecture boundary checks (Phase 0.7) --------------------------------
// Enforce the DDD dependency direction at test time: the compiler drops unused
// references, so a forbidden name appearing in an assembly's referenced set means
diff --git a/tests/Nota.SmokeTest/RenderPoolTests.cs b/tests/Nota.SmokeTest/RenderPoolTests.cs
index b1b94ad3..1aa81637 100644
--- a/tests/Nota.SmokeTest/RenderPoolTests.cs
+++ b/tests/Nota.SmokeTest/RenderPoolTests.cs
@@ -123,6 +123,7 @@ internal static class RenderPoolTests
public static IEnumerable<(bool Ok, string Label)> Run()
{
+ foreach (var result in HostedRenderPoolTests.RunIsolated()) yield return result;
int par = ParallelThreads();
// 1. Idle: render threads park. A spinning pool costs ~1 s of CPU per thread per second.