From 4efe67eab942d0502427174646fb97891041b358 Mon Sep 17 00:00:00 2001 From: salman Date: Thu, 3 Sep 2026 19:54:25 +0200 Subject: [PATCH] Cache decoded ROOT objects for fast clean/original/reset toggling Toggling clean/original and reset re-fetched the ROOT file over the network on every redraw, which is slow and flaky on mobile. Each spectrum render now reuses a per-window cached decode: the cache holds the pristine canvas, and every render draws its own JSON deep clone so the clean-view mutation never corrupts the cached original or the 'original' view. The cache key ignores the cache-busting query string so repeated renders hit the same entry, and FFT renders still always decode their freshly fetched file. This removes the per-toggle network round-trip on the hot path. --- muSRFitRoot.js | 74 +++++++++++++++++++++++++++++------ tests/root-plot-clean.test.js | 45 +++++++++++++++++++++ 2 files changed, 108 insertions(+), 11 deletions(-) diff --git a/muSRFitRoot.js b/muSRFitRoot.js index 6ec8975..72584ff 100644 --- a/muSRFitRoot.js +++ b/muSRFitRoot.js @@ -571,6 +571,30 @@ function musrfitRootRenderIsStale(container, generation, canvas) { return !canvas || !canvas.isConnected; } +// A decoded musrview canvas is a plain tree of ROOT field objects. Reusing the +// decoded object across clean/original/reset redraws avoids a network round-trip +// per toggle, which is the slow, flaky path on mobile. A JSON round-trip is a +// JSROOT-version-independent deep clone; JSROOT draws by field name, so the copy +// paints identically. Each clone is mutated in place by the clean view pipeline, +// leaving the cached pristine copy untouched for the "original" view. +function musrfitRootCloneCanvas(canvasObject) { + if (canvasObject && typeof canvasObject !== "object") { + return canvasObject; + } + try { + return JSON.parse(JSON.stringify(canvasObject)); + } catch (error) { + return canvasObject; + } +} + +// Stable per-plot cache key independent of the cache-busting query string, so a +// clean/original/reset redraw hits the same entry across render versions. +function musrfitRootCacheKey(plotSpec) { + let url = String(plotSpec && plotSpec.url || "").split("?")[0]; + return url + "|" + String(plotSpec && plotSpec.item || ""); +} + // JSROOT does not automatically know that our floating dialog was resized by // CSS or by the user, so explicitly notify it when the canvas has real geometry. function resizeMusrfitRootCanvas(jsroot, canvas) { @@ -610,7 +634,7 @@ function installMusrfitRootResizeObserver(jsroot, canvas) { // Draw all ROOT canvases returned by musrview. Each PLOT block becomes one pane; // errors are shown beside the affected pane rather than failing the whole window. -async function renderMusrfitRootPlots(container, plotSpecs, renderVersion, viewMode = "clean") { +async function renderMusrfitRootPlots(container, plotSpecs, renderVersion, viewMode = "clean", decodeCache = null) { let renderToken = beginMusrfitRootRender(container); disconnectMusrfitRootResizeObservers(container); container.replaceChildren(); @@ -662,17 +686,42 @@ async function renderMusrfitRootPlots(container, plotSpecs, renderVersion, viewM if (musrfitRootRenderIsStale(container, renderToken, canvas)) { return; } - let object = await withMusrfitRootTimeout( - file.readObject(plotSpec.item), - "Decoding object " + plotSpec.item, plotSpec.url); - if (musrfitRootRenderIsStale(container, renderToken, canvas)) { - return; + + // Reuse a previously decoded canvas for clean/original/reset redraws + // instead of re-fetching the ROOT file over the network on every toggle. + // The cached copy is always pristine; each render draws its own clone so + // clean-view mutation never leaks back into the cache (or the original). + let cacheKey = decodeCache ? musrfitRootCacheKey(plotSpec) : ""; + let drawObject; + if (decodeCache) { + let cached = decodeCache.get(cacheKey); + if (cached) { + drawObject = musrfitRootCloneCanvas(cached); + } else { + let fileObject = await withMusrfitRootTimeout( + file.readObject(plotSpec.item), + "Decoding object " + plotSpec.item, plotSpec.url); + if (musrfitRootRenderIsStale(container, renderToken, canvas)) { + return; + } + drawObject = musrfitRootCloneCanvas(fileObject); + decodeCache.set(cacheKey, fileObject); + } + } else { + drawObject = await withMusrfitRootTimeout( + file.readObject(plotSpec.item), + "Decoding object " + plotSpec.item, plotSpec.url); + if (musrfitRootRenderIsStale(container, renderToken, canvas)) { + return; + } + drawObject = musrfitRootCloneCanvas(drawObject); } + if (viewMode === "clean") { - cleanMusrfitRootCanvas(object); + cleanMusrfitRootCanvas(drawObject); } let painter = await withMusrfitRootTimeout( - jsroot.draw(canvasId, object, ""), + jsroot.draw(canvasId, drawObject, ""), "Drawing ROOT canvas", plotSpec.url); if (musrfitRootRenderIsStale(container, renderToken, canvas)) { return; @@ -779,6 +828,9 @@ function showWebRootPlotWindow(rootUrls, jobName = "", plotContext = {}) { let fftInProgress = false; let rootViewMode = "clean"; plotWindow.dataset.plotView = rootViewMode; + // Reused across spectrum redraws so clean/original/reset never re-fetch the + // ROOT file; FFT renders pass no cache and always decode their fresh file. + let rootDecodeCache = new Map(); // Redrawing the same ROOT object is the most robust unzoom/reset operation: // it avoids depending on JSROOT painter internals while preserving the file. @@ -787,7 +839,7 @@ function showWebRootPlotWindow(rootUrls, jobName = "", plotContext = {}) { return; } let resetVersion = Date.now().toString(36) + "-reset-" + webRootPlotWindowSequence; - renderMusrfitRootPlots(plotContainer, currentSpecs, resetVersion, rootViewMode); + renderMusrfitRootPlots(plotContainer, currentSpecs, resetVersion, rootViewMode, rootDecodeCache); if (statusMessage && typeof updateJobStatus === "function") { updateJobStatus({ message: statusMessage }); } @@ -803,7 +855,7 @@ function showWebRootPlotWindow(rootUrls, jobName = "", plotContext = {}) { if (plotWindow.dataset.plotMode === "fft") { let restoreVersion = Date.now().toString(36) + "-restore-" + webRootPlotWindowSequence; currentSpecs = spectrumSpecs.slice(); - renderMusrfitRootPlots(plotContainer, currentSpecs, restoreVersion, rootViewMode); + renderMusrfitRootPlots(plotContainer, currentSpecs, restoreVersion, rootViewMode, rootDecodeCache); plotWindow.dataset.plotMode = "spectrum"; if (typeof updateJobStatus === "function") { updateJobStatus({ @@ -875,7 +927,7 @@ function showWebRootPlotWindow(rootUrls, jobName = "", plotContext = {}) { fftInProgress = false; } - renderMusrfitRootPlots(plotContainer, spectrumSpecs, renderVersion, rootViewMode); + renderMusrfitRootPlots(plotContainer, spectrumSpecs, renderVersion, rootViewMode, rootDecodeCache); // Build one action, e.g. a menu button, for a plot action. Toggle/stateful // actions report their current result through updateJobStatus. diff --git a/tests/root-plot-clean.test.js b/tests/root-plot-clean.test.js index 10872f4..9cad7d5 100644 --- a/tests/root-plot-clean.test.js +++ b/tests/root-plot-clean.test.js @@ -352,6 +352,50 @@ function testRenderGenerationGuard() { assert.match(code, /musrfitRootRenderIsStale\(container, renderToken, container\)/); } +// Clean/original/reset redraws reuse a decoded ROOT object instead of re-fetching +// the file each toggle, which is the slow, flaky path on mobile. +function testDecodeCache() { + const lib = loadRootLibrary(); + + // The cache key is stable despite the cache-busting query string on the URL. + assert.strictEqual( + lib.musrfitRootCacheKey({ url: "/tmp/job/run_0.root?musrflow_root=abc", item: "fMainCanvas0;1" }), + "/tmp/job/run_0.root|fMainCanvas0;1" + ); + + // The deep clone paints identically but is fully independent, so mutating the + // drawn copy never corrupts the cached pristine original. + const original = { + _typename: "TCanvas", + fName: "c" , + fTitle: "run", + fPrimitives: { + arr: [ { _typename: "TPad", fName: "p", fX: [1, 2, 3] } ], + opt: [ "p" ] + } + }; + const clone = lib.musrfitRootCloneCanvas(original); + assert.notStrictEqual(clone, original, "clone is a distinct object"); + // Structural equality (JSON round-trip) avoids cross-realm prototype noise, + // since the vm sandbox builds its own Object.prototype. + assert.strictEqual(JSON.stringify(clone), JSON.stringify(original), + "clone matches the source tree"); + clone.fPrimitives.arr[0].fName = "mutated"; + assert.strictEqual(original.fPrimitives.arr[0].fName, "p", + "mutating the clone does not affect the source"); + + const code = fs.readFileSync(path.join(repoRoot, "muSRFitRoot.js"), "utf8"); + // renderMusrfitRootPlots accepts a decode cache; clean view draws a clone of + // the cached pristine copy. + assert.match(code, /viewMode = "clean", decodeCache = null/); + assert.match(code, /drawObject = musrfitRootCloneCanvas\(cached\)/); + assert.match(code, /decodeCache\.set\(cacheKey, fileObject\)/); + // Spectrum renders reuse the window cache; FFT renders never do. + assert.match(code, /renderMusrfitRootPlots\(plotContainer, currentSpecs, resetVersion, rootViewMode, rootDecodeCache\)/); + assert.match(code, /renderMusrfitRootPlots\(plotContainer, currentSpecs, fftVersion, rootViewMode\)/); + assert.match(code, /let rootDecodeCache = new Map\(\)/); +} + function runTests() { testCleanLegendLabels(); testCleanCanvasLayout(); @@ -360,6 +404,7 @@ function runTests() { testTouchActionMenu(); testLoadTimeoutSource(); testRenderGenerationGuard(); + testDecodeCache(); testLoadTimeout(); console.log("ROOT clean-view tests passed."); }