~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix(logpanel): harden pruneToCap against missing/unknown logType (#5004)
LearningCircuitf7773b7d4679
diff --git a/changelog.d/5004.bugfix.md b/changelog.d/5004.bugfix.mdnew file mode 100644index 0000000000..ff212f55b9--- /dev/null+++ b/changelog.d/5004.bugfix.md@@ -0,0 +1 @@+Log pruning now handles missing and Loguru-specific severity levels safely, preserves critical diagnostics, and keeps filter counters accurate at the rendered-entry cap.diff --git a/src/local_deep_research/web/routes/research_routes.py b/src/local_deep_research/web/routes/research_routes.pyindex 37e57c1395..3726aa4c87 100644--- a/src/local_deep_research/web/routes/research_routes.py+++ b/src/local_deep_research/web/routes/research_routes.py@@ -1682,10 +1682,11 @@ def get_research_logs(research_id):``None``) the historical contract is preserved: every row is returned. Thefrontend log panel always sends a valid limit and``priority=diagnostic``. That mode does a best-effort newest-first- selection prioritizing errors, then warnings, then milestones, before- filling the remaining window with routine rows. If the number of higher-- priority rows exceeds the limit, the oldest diagnostics in those categories- and all lower-priority/routine rows are dropped.+ selection prioritizing errors/CRITICAL/FATAL, then warnings, then+ milestones/SUCCESS, before filling the remaining window with routine rows.+ If the number of higher-priority rows exceeds the limit, the oldest+ diagnostics in those categories and all lower-priority/routine rows are+ dropped.Direct API callers retain newest-N behavior unless they opt in."""username = session["username"]@@ -1715,10 +1716,17 @@ def get_research_logs(research_id):ResearchLog.timestamp, ResearchLog.id).all()elif prioritize_diagnostics:+ normalized_level = func.lower(ResearchLog.level)diagnostic_priority = case(- (func.lower(ResearchLog.level) == "error", 0),- (func.lower(ResearchLog.level) == "warning", 1),- (func.lower(ResearchLog.level) == "milestone", 2),+ (+ normalized_level.in_(("error", "critical", "fatal")),+ 0,+ ),+ (normalized_level == "warning", 1),+ (+ normalized_level.in_(("milestone", "success")),+ 2,+ ),else_=3,)log_results = (diff --git a/src/local_deep_research/web/static/js/components/logpanel.js b/src/local_deep_research/web/static/js/components/logpanel.jsindex ed5d68b86a..829159afdb 100644--- a/src/local_deep_research/web/static/js/components/logpanel.js+++ b/src/local_deep_research/web/static/js/components/logpanel.js@@ -613,69 +613,108 @@return null;}+ const PRUNE_REMOVABLE_ORDER = Object.freeze(['info', 'milestone', 'warning', 'error']);++ /**+ * Map a rendered log type to its pruning priority without changing the+ * type stored in the DOM. Loguru's standard levels are normalized+ * explicitly so CRITICAL/FATAL remain as diagnostic as ERROR. SUCCESS is+ * treated like a milestone: it represents a completed operation and+ * should outlive routine TRACE/DEBUG/INFO noise, but not warnings/errors.+ * Future types fall into the routine tier so they cannot bypass the cap.+ *+ * @param {string} type - Lowercase rendered log type.+ * @returns {'info'|'milestone'|'warning'|'error'} Pruning priority.+ */+ function getPruneTier(type) {+ switch (type) {+ case 'trace':+ case 'debug':+ case 'info':+ return 'info';+ case 'success':+ case 'milestone':+ return 'milestone';+ case 'warning':+ return 'warning';+ case 'error':+ case 'critical':+ case 'fatal':+ return 'error';+ default:+ return 'info';+ }+ }++ /**+ * Read the normalized type stored on a rendered log row.+ *+ * @param {Element} entry - Rendered log entry.+ * @returns {string} Lowercase DOM type, defaulting to "info".+ */+ function getRenderedLogType(entry) {+ const rawType = entry.dataset?.logType;+ const normalizedType = typeof rawType === 'string'+ ? rawType.toLowerCase()+ : '';+ return normalizedType || 'info';+ }+/*** Trim log entries from the container down to `cap`, preferring to drop* the least-actionable categories first.*- * The plain "remove from head" prune loses the panel's most diagnostic- * entries — old warnings and errors get flushed even when the cap was- * blown by a flood of routine info entries. Walk the DOM and, for each- * excess slot, drop the oldest entry whose type is in the currently-- * removable category (info, then milestone). Once those are exhausted,- * fall back to dropping warnings, then errors, in age order.- *- * Trade-off: ordered pruning means surviving entries are no longer- * strictly the newest N — an early error can sit among hundreds of- * newer info entries. That is intentional: warnings/errors are the- * most diagnostic categories and should outlive routine info spam- * during a long research run.+ * A single static NodeList is scanned once per priority tier, making the+ * prune O(N) rather than re-querying and re-scanning the DOM after every+ * removal. Within each tier entries are removed in DOM (chronological)+ * order. Surviving warnings/errors may therefore be older than routine+ * entries, which is intentional.*- * Only `.ldr-console-log-entry` children are pruned; transient- * placeholders such as `.ldr-empty-log-message`,- * `.ldr-loading-spinner`, and `.ldr-error-message` (which can- * briefly co-exist with log entries during async loads) are left- * alone.+ * Only `.ldr-console-log-entry` descendants are considered; transient+ * placeholders such as `.ldr-empty-log-message`, `.ldr-loading-spinner`,+ * and `.ldr-error-message` are left alone.** @param {Element} container - The log container element.* @param {number} cap - The maximum allowed entry count after pruning.- * @returns {string[]} The categories of removed entries, in removal- * order. Each element corresponds to one DOM removal. Callers can- * consume the return value to keep an external per-category counter- * in sync without re-querying the DOM.+ * @returns {string[]} Normalized DOM types of removed entries, in removal+ * order. A missing type is normalized to "info", matching the rest of+ * the panel. Explicit unknown types retain their real lowercase value so+ * callers never decrement Info for an untracked DEBUG/NOTICE row.*/- const PRUNE_REMOVABLE_ORDER = Object.freeze(['info', 'milestone', 'warning', 'error']);function pruneToCap(container, cap) {+ const entries = container.querySelectorAll('.ldr-console-log-entry');+ // A fractional cap still means no more than floor(cap) entries.+ // Keep the removal quota integral so the exact-zero stop condition+ // cannot be skipped (e.g. 3 entries at cap=2.5 needs one removal).+ const excess = Math.ceil(entries.length - cap);+ if (excess <= 0) return [];+const removed = [];- while (true) {- // Re-query every iteration: each remove() mutates the live- // NodeList, so a cached handle would go stale.- const entries = container.querySelectorAll('.ldr-console-log-entry');- if (entries.length <= cap) break;- let dropped = null;- for (const targetType of PRUNE_REMOVABLE_ORDER) {- for (const entry of entries) {- const type = (entry.dataset.logType || 'info').toLowerCase();- if (type === targetType) {- dropped = entry;- break;- }+ let stillNeeded = excess;+ for (const targetTier of PRUNE_REMOVABLE_ORDER) {+ if (stillNeeded <= 0) break;+ for (const entry of entries) {+ // querySelectorAll() is static. Removed nodes remain in it, so+ // skip nodes no longer contained after an earlier tier scan.+ // contains() also works when the container itself is detached.+ if (!container.contains(entry)) continue;+ const type = getRenderedLogType(entry);+ if (getPruneTier(type) !== targetTier) continue;++ // Removing an entry also detaches any nested log rows. Include+ // every one in both the quota and returned types so callers'+ // counters stay aligned with the actual DOM mutation.+ const removalGroup = [+ entry,+ ...entry.querySelectorAll('.ldr-console-log-entry'),+ ].filter((row) => container.contains(row));+ entry.remove();+ for (const removedEntry of removalGroup) {+ removed.push(getRenderedLogType(removedEntry));}- if (dropped) break;+ stillNeeded -= removalGroup.length;+ if (stillNeeded <= 0) break;}- // Defensive fallback — should be unreachable because every log- // entry is created via createLogEntryElement which sets- // dataset.logType, but if some non-log child slipped through- // somehow, drop the oldest of those to guarantee forward- // progress.- if (!dropped) {- const fallback = entries[0];- if (!fallback) break;- removed.push((fallback.dataset.logType || 'info').toLowerCase());- fallback.remove();- continue;- }- removed.push(dropped.dataset.logType.toLowerCase());- dropped.remove();}return removed;}@@ -1335,35 +1374,45 @@consoleLogContainer.insertBefore(element, nextNewerEntry || null);}- // Prune oldest entries if over limit to prevent unbounded DOM growth.- // Prefer to drop the least-actionable categories first (info, then- // milestones, then warnings, then errors) so a long research run- // doesn't flush the panel's diagnostic tail. Mirrors the batch-load- // prune above.+ // Account for the inserted row before pruning. If the new row itself+ // is the least-actionable entry and is immediately pruned, this order+ // lets the matching decrement return the counter to zero without a+ // transient negative value.+ let countersChanged = false;+ if (incrementCounter && element) {+ const logType = (element.dataset.logType || 'info').toLowerCase();+ if (Object.prototype.hasOwnProperty.call(+ window._logPanelState.counts,+ logType+ )) {+ window._logPanelState.counts[logType]++;+ }+ countersChanged = true;+ }++ // Prune oldest entries if over the current rendered limit; see+ // pruneToCap for the severity ordering. Keeping renderedLimit here+ // preserves an expanded "Load older" window up to the 5000-row cap.const renderCap =window._logPanelState.renderedLimit ?? MAX_LOG_ENTRIES;const removed = pruneToCap(consoleLogContainer, renderCap);if (removed.length > 0) {- // Keep the per-category counter for the filter badges in sync- // with what was actually removed. pruneToCap returns the- // categories in removal order, so we can decrement directly- // without re-querying the DOM for each entry's type.for (const prunedType of removed) {- if (window._logPanelState.counts[prunedType] !== undefined) {- window._logPanelState.counts[prunedType]--;+ if (Object.prototype.hasOwnProperty.call(+ window._logPanelState.counts,+ prunedType+ )) {+ window._logPanelState.counts[prunedType] = Math.max(+ 0,+ window._logPanelState.counts[prunedType] - 1+ );}}- updateLogCounter(-removed.length);- updateFilterCounters();+ countersChanged = true;}- // Update log count using helper function if needed- if (incrementCounter && element) {- const logType = (element.dataset.logType || 'info').toLowerCase();- if (window._logPanelState.counts[logType] !== undefined) {- window._logPanelState.counts[logType]++;- }- updateLogCounter(1);+ if (countersChanged) {+ updateLogCounter(0);updateFilterCounters();}diff --git a/tests/js/components/logpanel.test.js b/tests/js/components/logpanel.test.jsindex 521220afb3..68656359d1 100644--- a/tests/js/components/logpanel.test.js+++ b/tests/js/components/logpanel.test.js@@ -2175,10 +2175,15 @@ describe('pruneToCap — per-category ordered prune', () => {// cap=200. We need to drop 1002 - 200 = 802 entries. The two// diagnostic entries are the oldest, but the ordered prune must// protect them: all 802 drops must be info entries.+ const querySpy = vi.spyOn(container, 'querySelectorAll');const removed = logPanel._pruneToCap(container, 200);expect(removed.length).toBe(802);expect(removed.every((r) => r === 'info')).toBe(true);+ // The pruning implementation must query once, rather than re-querying+ // and scanning the shrinking DOM for every one of the 802 removals.+ expect(querySpy).toHaveBeenCalledTimes(1);+ querySpy.mockRestore();expect(container.children.length).toBe(200);const survivingMessages = Array.from(container.querySelectorAll('.ldr-log-message')@@ -2255,7 +2260,290 @@ describe('pruneToCap — per-category ordered prune', () => {expect(container.children[0]).toBe(spinner);});- // The "no-op when already under the cap" case is covered by- // `it('is a no-op when already under the cap', ...)` above; no- // need to duplicate it here.+ it('accounts for nested log rows detached with a pruned ancestor', () => {+ const container = document.getElementById('console-log-container');+ const outerInfo = seedEntry(container, 'outer-info', 'info', 0);+ const nestedWarning = seedEntry(+ container,+ 'nested-warning',+ 'warning',+ 1+ );+ const siblingInfo = seedEntry(+ container,+ 'sibling-info-survivor',+ 'info',+ 2+ );+ const milestone = seedEntry(+ container,+ 'milestone-survivor',+ 'milestone',+ 3+ );+ const error = seedEntry(container, 'error-survivor', 'error', 4);+ outerInfo.appendChild(nestedWarning);++ const querySpy = vi.spyOn(container, 'querySelectorAll');+ // Five queried rows at cap=4 means the quota is one, but removing+ // outerInfo atomically detaches its nested warning too. The resulting+ // negative quota must stop both loops before siblingInfo or a later+ // priority tier is touched.+ const removed = logPanel._pruneToCap(container, 4);++ expect(removed).toEqual(['info', 'warning']);+ expect(querySpy).toHaveBeenCalledTimes(1);+ querySpy.mockRestore();+ expect(+ Array.from(+ container.querySelectorAll('.ldr-console-log-entry')+ )+ ).toEqual([siblingInfo, milestone, error]);+ });++ it('drops every entry when cap=0', () => {+ const container = document.getElementById('console-log-container');+ seedEntry(container, 'info-0', 'info', 0);+ seedEntry(container, 'warn-0', 'warning', 1);+ seedEntry(container, 'err-0', 'error', 2);++ expect(logPanel._pruneToCap(container, 0)).toEqual([+ 'info',+ 'warning',+ 'error',+ ]);+ expect(container.querySelectorAll('.ldr-console-log-entry')).toHaveLength(0);+ });++ it("handles a missing dataset.logType using the panel's info fallback", () => {+ const container = document.getElementById('console-log-container');+ const untyped = seedEntry(container, 'untyped', 'info', 0);+ delete untyped.dataset.logType;+ seedEntry(container, 'warn-0', 'warning', 1);+ seedEntry(container, 'err-0', 'error', 2);++ const removed = logPanel._pruneToCap(container, 2);++ expect(removed).toEqual(['info']);+ expect(Array.from(container.children).map((entry) => entry.dataset.logType))+ .toEqual(['warning', 'error']);+ });++ it('returns an unknown row real type instead of its info priority tier', () => {+ const container = document.getElementById('console-log-container');+ seedEntry(container, 'notice-0', 'NOTICE', 0);+ seedEntry(container, 'warn-0', 'warning', 1);+ seedEntry(container, 'err-0', 'error', 2);++ expect(logPanel._pruneToCap(container, 2)).toEqual(['notice']);+ expect(Array.from(container.children).map((entry) => entry.dataset.logType))+ .toEqual(['warning', 'error']);+ });++ it('normalizes Loguru severities into explicit pruning tiers', () => {+ const container = document.getElementById('console-log-container');+ seedEntry(container, 'critical-0', 'CRITICAL', 0);+ seedEntry(container, 'trace-0', 'TRACE', 1);+ seedEntry(container, 'success-0', 'SUCCESS', 2);+ seedEntry(container, 'warn-0', 'WARNING', 3);+ seedEntry(container, 'fatal-0', 'FATAL', 4);+ seedEntry(container, 'debug-0', 'DEBUG', 5);+ seedEntry(container, 'milestone-0', 'milestone', 6);+ seedEntry(container, 'info-0', 'INFO', 7);+ seedEntry(container, 'error-0', 'ERROR', 8);++ // TRACE/DEBUG/INFO go first, SUCCESS deliberately shares milestone's+ // tier, then WARNING. CRITICAL/FATAL/ERROR are the three survivors.+ expect(logPanel._pruneToCap(container, 3)).toEqual([+ 'trace',+ 'debug',+ 'info',+ 'success',+ 'milestone',+ 'warning',+ ]);+ expect(Array.from(container.children).map((entry) => entry.dataset.logType))+ .toEqual(['CRITICAL', 'FATAL', 'ERROR']);+ });+});++describe('addLog — live pruning integration', () => {+ function setupLivePanel(renderedLimit) {+ setupPanelDom({ page: 'progress', researchId: null });+ window._logPanelState.expanded = true;+ window._logPanelState.renderedLimit = renderedLimit;++ const indicator = document.createElement('span');+ indicator.className = 'ldr-log-indicator';+ indicator.textContent = '0';+ document.getElementById('log-panel-toggle').appendChild(indicator);+ return document.getElementById('console-log-container');+ }++ function getBadge(type) {+ return Number(document.querySelector(+ `.ldr-filter-count[data-filter-count="${type}"]`+ ).textContent);+ }++ it('prunes DEBUG without decrementing Info or drifting live counters', () => {+ const container = setupLivePanel(2);++ logPanel.addLog('debug-first', 'DEBUG');+ logPanel.addLog('warning-second', 'WARNING');+ logPanel.addLog('error-third', 'ERROR');++ expect(Array.from(container.children).map((entry) => entry.dataset.logType))+ .toEqual(['warning', 'error']);+ expect(window._logPanelState.counts).toEqual({+ info: 0,+ milestone: 0,+ warning: 1,+ error: 1,+ });+ expect(getBadge('info')).toBe(0);+ expect(getBadge('warning')).toBe(1);+ expect(getBadge('error')).toBe(1);+ expect(getBadge('all')).toBe(2);+ expect(document.querySelector('.ldr-log-indicator').textContent).toBe('2');+ });++ it('does not create an inherited-key counter on live insert', () => {+ const container = setupLivePanel(1);++ logPanel.addLog('live-constructor', 'CONSTRUCTOR');++ expect(Array.from(container.children).map((entry) => entry.dataset.logType))+ .toEqual(['constructor']);+ expect(window._logPanelState.counts).toEqual({+ info: 0,+ milestone: 0,+ warning: 0,+ error: 0,+ });+ expect(+ Object.prototype.hasOwnProperty.call(+ window._logPanelState.counts,+ 'constructor'+ )+ ).toBe(false);+ expect(getBadge('all')).toBe(1);+ expect(document.querySelector('.ldr-log-indicator').textContent).toBe('1');+ });++ it('does not create counters for a prototype-named custom level', async () => {+ const container = setupLivePanel(1);+ globalThis.fetch = vi.fn()+ .mockResolvedValueOnce({+ json: () => Promise.resolve({ total_logs: 1 }),+ })+ .mockResolvedValueOnce({+ json: () => Promise.resolve({+ logs: [{+ timestamp: '2026-07-26T00:00:00Z',+ message: 'custom-level-row',+ log_type: 'CONSTRUCTOR',+ }],+ }),+ });++ try {+ await logPanel.loadLogs('prototype-level-research', 1);++ expect(+ Array.from(container.children).map(+ (entry) => entry.dataset.logType+ )+ ).toEqual(['constructor']);+ expect(window._logPanelState.counts).toEqual({+ info: 0,+ milestone: 0,+ warning: 0,+ error: 0,+ });++ logPanel.addLog('newer-error', 'ERROR');++ expect(+ Array.from(container.children).map(+ (entry) => entry.dataset.logType+ )+ ).toEqual(['error']);+ expect(window._logPanelState.counts).toEqual({+ info: 0,+ milestone: 0,+ warning: 0,+ error: 1,+ });+ expect(+ Object.prototype.hasOwnProperty.call(+ window._logPanelState.counts,+ 'constructor'+ )+ ).toBe(false);+ expect(getBadge('error')).toBe(1);+ expect(getBadge('all')).toBe(1);+ expect(+ document.querySelector('.ldr-log-indicator').textContent+ ).toBe('1');+ } finally {+ delete globalThis.fetch;+ }+ });++ it('prunes older CRITICAL before newer ERROR in their shared tier', () => {+ const container = setupLivePanel(1);++ logPanel.addLog('critical-first', 'CRITICAL');+ logPanel.addLog('error-second', 'ERROR');++ expect(Array.from(container.children).map((entry) => entry.dataset.logType))+ .toEqual(['error']);+ expect(window._logPanelState.counts).toEqual({+ info: 0,+ milestone: 0,+ warning: 0,+ error: 1,+ });+ expect(getBadge('error')).toBe(1);+ expect(getBadge('all')).toBe(1);+ expect(document.querySelector('.ldr-log-indicator').textContent).toBe('1');+ });++ it('floors a fractional renderedLimit without draining the panel', () => {+ const container = setupLivePanel(2.5);++ logPanel.addLog('warning-first', 'WARNING');+ logPanel.addLog('error-second', 'ERROR');+ logPanel.addLog('info-third', 'INFO');++ expect(Array.from(container.children).map((entry) => entry.dataset.logType))+ .toEqual(['warning', 'error']);+ expect(window._logPanelState.counts).toEqual({+ info: 0,+ milestone: 0,+ warning: 1,+ error: 1,+ });+ expect(getBadge('all')).toBe(2);+ expect(document.querySelector('.ldr-log-indicator').textContent).toBe('2');+ });++ it('does not collapse an expanded renderedLimit back to the default 500', () => {+ const container = setupLivePanel(501);+ for (let i = 0; i < MAX_LOG_ENTRIES; i++) {+ const entry = makeLiveEntry(`seed-${i}`, 'info');+ entry.dataset.logTimeMs = String(i);+ container.appendChild(entry);+ }+ window._logPanelState.counts.info = MAX_LOG_ENTRIES;+ document.querySelector('.ldr-log-indicator').textContent = String(MAX_LOG_ENTRIES);++ logPanel.addLog('live-after-load-older', 'error');++ expect(container.querySelectorAll('.ldr-console-log-entry')).toHaveLength(501);+ expect(window._logPanelState.counts.info).toBe(500);+ expect(window._logPanelState.counts.error).toBe(1);+ expect(getBadge('all')).toBe(501);+ });});diff --git a/tests/web/routes/test_research_routes.py b/tests/web/routes/test_research_routes.pyindex acb922f2a4..b843c9bd72 100644--- a/tests/web/routes/test_research_routes.py+++ b/tests/web/routes/test_research_routes.py@@ -562,6 +562,46 @@ class TestGetResearchLogsApi:finally:self._close_session(session)+ def test_diagnostic_priority_loguru_tiers(self, authenticated_client):+ """Loguru aliases share the frontend's diagnostic priority tiers."""+ from local_deep_research.database.models import ResearchLog++ session = self._seed_real_session(10)+ try:+ rows = session.query(ResearchLog).order_by(ResearchLog.id).all()+ rows[0].level = "CRITICAL"+ rows[1].level = "FATAL"+ rows[2].level = "ERROR"+ rows[3].level = "CRITICAL"+ rows[4].level = "WARNING"+ rows[5].level = "SUCCESS"+ rows[6].level = "MILESTONE"+ session.commit()++ overflow_resp = self._get_logs(+ authenticated_client,+ session,+ "?limit=3&priority=diagnostic",+ )+ assert overflow_resp.status_code == 200, overflow_resp.status_code+ assert [r["message"] for r in overflow_resp.get_json()] == [+ "Log 1",+ "Log 2",+ "Log 3",+ ]++ all_tiers_resp = self._get_logs(+ authenticated_client,+ session,+ "?limit=7&priority=diagnostic",+ )+ assert all_tiers_resp.status_code == 200, all_tiers_resp.status_code+ assert [r["message"] for r in all_tiers_resp.get_json()] == [+ f"Log {i}" for i in range(7)+ ]+ finally:+ self._close_session(session)+def test_diagnostic_priority_overflow(self, authenticated_client):"""When a single tier (e.g. errors) alone exceeds limit, the oldesterrors and all other lower-priority categories are dropped."""