~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(notifications): render scheme-less refusal diagnostics into the audit message (#6576)
LearningCircuit080edb37f0c8
diff --git a/changelog.d/5619.bugfix.md b/changelog.d/5619.bugfix.mdnew file mode 100644index 0000000000..fb5448f26a--- /dev/null+++ b/changelog.d/5619.bugfix.md@@ -0,0 +1 @@+The notification audit warnings for an unparseable service URL (on the send path, the test-notification path, the egress filter and the Apprise URL partitioner) now render their content-free diagnostics — the fragment's length and the number of parsed entries, plus the user id and event type on the send path — into the log message itself. They were previously passed as loguru keyword arguments with no template placeholder, so no production sink (stderr, log file, in-app log viewer) displayed them, and operators lost the fragment length and entry count needed to locate the malformed entry.diff --git a/src/local_deep_research/notifications/manager.py b/src/local_deep_research/notifications/manager.pyindex 534fcf9e7f..7b8fea6859 100644--- a/src/local_deep_research/notifications/manager.py+++ b/src/local_deep_research/notifications/manager.py@@ -339,14 +339,21 @@ class NotificationManager:# secret (``slack://xoxb-SECRET/T00/B00`` redacts to# ``slack://xoxb-SECRET``), and a fragment can be the# whole entry when the illegal character only trails it.- # The fragment's length and position are enough to- # diagnose the misconfiguration.+ # The fragment's length and the parsed-entry count are+ # enough to diagnose the misconfiguration. They are+ # rendered into the message with positional placeholders:+ # loguru kwargs with no template placeholder reach no+ # production sink (stderr, log file, database) — #5619.+ # The user id and event type are rendered too; this module+ # already renders both in its other warnings.logger.bind(policy_audit=True).warning(- "notification dropped: unparseable service URL fragment",- fragment_length=len(invalid_fragment),- entries_parsed=len(url_entries),- user=self._user_id,- event=event_type.value,+ "notification dropped: unparseable service URL "+ "fragment (fragment_length={}, entries_parsed={}, "+ "user={}, event={})",+ len(invalid_fragment),+ len(url_entries),+ self._user_id,+ event_type.value,)return NotificationResult(sent=False,@@ -591,11 +598,14 @@ class NotificationManager:# Log NOTHING derived from the fragment's content, not even# a redacted form — see the identical branch in# ``send_notification`` for why ``scheme://host`` is still- # the secret for token-in-authority Apprise schemes.+ # the secret for token-in-authority Apprise schemes. The+ # content-free diagnostics are rendered into the message, as+ # there (#5619).logger.bind(policy_audit=True).warning(- "test notification refused: unparseable service URL fragment",- fragment_length=len(invalid_fragment),- entries_parsed=len(url_entries),+ "test notification refused: unparseable service URL "+ "fragment (fragment_length={}, entries_parsed={})",+ len(invalid_fragment),+ len(url_entries),)return {"status": "error",@@ -663,15 +673,22 @@ class NotificationManager:service_urls, separator)if invalid_fragment is not None:- # As in ``send_notification``: never log anything derived- # from the fragment's content. Even the redacted+ # Same rule as the identical branches in+ # ``send_notification`` and ``test_service`` (both parse+ # first and return before calling this method, so this+ # branch only fires for a direct caller): never log anything+ # derived from the fragment's content. Even the redacted# ``scheme://host`` form leaks the secret for token-in-# authority Apprise schemes, and the fragment may be the- # entire entry.+ # entire entry. The content-free diagnostics are rendered+ # into the message with positional placeholders, as at those+ # sites — loguru kwargs with no template placeholder never+ # appear in any production sink's output (#5619).logger.bind(policy_audit=True).warning(- "all notification URLs refused: unparseable URL fragment",- fragment_length=len(invalid_fragment),- entries_parsed=len(url_entries),+ "all notification URLs refused: unparseable URL "+ "fragment (fragment_length={}, entries_parsed={})",+ len(invalid_fragment),+ len(url_entries),)return ""diff --git a/src/local_deep_research/notifications/service.py b/src/local_deep_research/notifications/service.pyindex 0484299c1d..45e5e72023 100644--- a/src/local_deep_research/notifications/service.py+++ b/src/local_deep_research/notifications/service.py@@ -249,11 +249,14 @@ class NotificationService:# for direct callers of this helper. Fail closed rather than# dispatching only the valid subset — the caller must validate# the list themselves before dispatching it.+ # Rendered positionally: loguru kwargs with no template+ # placeholder reach no production sink (#5619).logger.warning("Notification service_url list contains a malformed "- "fragment; refusing the whole list",- fragment_length=len(invalid_fragment),- entries_parsed=len(entries),+ "fragment; refusing the whole list "+ "(fragment_length={}, entries_parsed={})",+ len(invalid_fragment),+ len(entries),)return [], []for entry in entries:diff --git a/tests/notifications/conftest.py b/tests/notifications/conftest.pyindex d24db55510..6e42d19479 100644--- a/tests/notifications/conftest.py+++ b/tests/notifications/conftest.py@@ -46,3 +46,29 @@ def capture_loguru():# ``src/local_deep_research/__init__.py`` and the ``loguru_caplog``# fixtures in the root conftest, which do the same).loguru_logger.disable("local_deep_research")+++def capture_loguru_records():+ """Capture raw loguru records, so a test can assert on+ ``record["message"]`` alone.++ ``record["message"]`` is the only field the production sinks show an+ operator: the stderr/file formats carry no ``{extra}``, and the+ database sink persists only the message. A diagnostic passed as a+ loguru kwarg without a template placeholder lands in ``extra`` and is+ never displayed (#5619) — ``capture_loguru``'s+ ``"{message} | {extra}"`` format would let such a test pass anyway.+ """+ records = []+ sink_id = loguru_logger.add(+ lambda message: records.append(message.record),+ level="DEBUG",+ diagnose=False,+ )+ loguru_logger.enable("local_deep_research")+ try:+ yield records+ finally:+ loguru_logger.remove(sink_id)+ loguru_logger.disable("local_deep_research")diff --git a/tests/notifications/test_manager.py b/tests/notifications/test_manager.pyindex 949901447c..d1841ec46f 100644--- a/tests/notifications/test_manager.py+++ b/tests/notifications/test_manager.py@@ -695,7 +695,7 @@ class TestNotificationResultSemantics:assert "refused" not in result.detaildef test_fragment_drop_log_never_carries_the_fragment(- self, mocker, capture_loguru+ self, mocker, capture_loguru, capture_loguru_records):r"""The ``invalid_url`` drop log must record NOTHING derived fromthe fragment's content — not even a redacted form.@@ -714,11 +714,14 @@ class TestNotificationResultSemantics:Teeth: restore ``fragment=redact_url_for_log(invalid_fragment)``in ``NotificationManager.send_notification`` and the bound extracarries ``slack://xoxb-SECRET-TOKEN`` — the token assertion fails- while the positive control still passes.+ while the positive control still passes. Pass the diagnostics as+ bare loguru kwargs again (no placeholder) and the rendered-message+ assertions fail: no production sink would show them (#5619)."""token = "xoxb-SECRET-TOKEN"+ service_url = f"slack://{token}/T00000/B00000\\"snapshot = {- "notifications.service_url": f"slack://{token}/T00000/B00000\\",+ "notifications.service_url": service_url,"notifications.on_research_completed": True,}manager = NotificationManager(settings_snapshot=snapshot, user_id="u")@@ -738,8 +741,23 @@ class TestNotificationResultSemantics:assert "unparseable service URL fragment" in loggedassert token not in loggedassert "slack://" not in logged- # The diagnostic that replaced it is content-free.- assert "fragment_length" in logged+ # The diagnostic that replaced it is content-free, and it is+ # RENDERED into the message — the only field a production sink+ # shows. (``logged`` above also includes ``{extra}``, so checking+ # it would pass even for an unrendered kwarg.) The trailing+ # backslash makes the whole entry the fragment.+ drops = [+ r+ for r in capture_loguru_records+ if r["message"].startswith(+ "notification dropped: unparseable service URL fragment"+ )+ ]+ assert len(drops) == 1+ assert drops[0]["extra"].get("policy_audit") is True+ rendered = drops[0]["message"]+ assert f"fragment_length={len(service_url)}" in rendered+ assert "entries_parsed=1" in rendered# ...and the user-facing detail is content-free too.assert token not in result.detail@@ -1501,42 +1519,99 @@ class TestEgressPolicyURLFilter:assert mgr._filter_urls_by_egress_policy(service_urls) == ""- def test_scheme_less_refusal_logs_no_fragment_content(self):- """The scheme-less refusal log records the fragment's LENGTH and- the entry count, and nothing derived from its content — not even- a ``redact_url_for_log`` form.-- ``redact_url_for_log`` keeps ``scheme://host``, but for the- token-in-authority Apprise schemes the first authority segment IS- the secret, and when the illegal character only trails an entry- the fragment is the whole entry. Teeth: restore- ``fragment=redact_url_for_log(invalid_fragment)`` in- ``_filter_urls_by_egress_policy`` and the ``"fragment" not in- kwargs`` assertion fails; drop the diagnostics and the- ``fragment_length`` / ``entries_parsed`` assertions fail.+ @pytest.mark.parametrize(+ "path, expected_prefix",+ [+ (+ "send_notification",+ "notification dropped: unparseable service URL fragment",+ ),+ (+ "test_service",+ "test notification refused: unparseable service URL fragment",+ ),+ (+ "_filter_urls_by_egress_policy",+ "all notification URLs refused: unparseable URL fragment",+ ),+ ],+ )+ def test_scheme_less_refusal_renders_content_free_diagnostics(+ self, mocker, capture_loguru_records, path, expected_prefix+ ):+ """The scheme-less refusal warning must RENDER its diagnostics.++ Production sinks (stderr, file, database) format only the+ message: loguru kwargs with no placeholder in the template+ never reach an operator (#5619). The diagnostics are+ content-free (fragment length + entry count); the fragment+ itself must stay out of the message AND the bound ``extra``,+ not even in a ``redact_url_for_log`` form — for+ token-in-authority Apprise schemes the first authority segment+ IS the secret, and when the illegal character only trails an+ entry the fragment is the whole entry.++ ``send_notification`` is the live path; ``test_service`` and+ ``_filter_urls_by_egress_policy`` carry the same branch (the+ latter is reached only by a direct caller, since both callers+ parse first and return early).++ Teeth: revert any of the three sites to bare kwargs and its+ ``fragment_length`` / ``entries_parsed`` assertions fail (the+ rendered message is the bare template); render or bind the+ fragment instead and the ``secret.example.com`` /+ ``/private/token`` assertions fail."""- mgr = self._mgr("unprotected")fragment = "secret.example.com/private/token"service_urls = f"{fragment} slack://t/x/y"-- with patch(- "local_deep_research.notifications.manager.logger"- ) as mock_logger:+ mgr = NotificationManager(+ settings_snapshot={+ "policy.egress_scope": {"value": "unprotected"},+ "search.tool": {"value": "searxng"},+ "notifications.service_url": service_urls,+ "notifications.on_research_completed": True,+ },+ user_id="u",+ )+ mgr._rate_limiter.is_allowed = mocker.MagicMock(return_value=True)+ mgr.service.send_event = mocker.MagicMock(return_value=True)+ mgr.service.test_service = mocker.MagicMock(+ return_value={"status": "ok"}+ )++ if path == "send_notification":+ result = mgr.send_notification(+ event_type=EventType.RESEARCH_COMPLETED,+ context={"query": "q"},+ )+ assert result.reason is NotificationReason.INVALID_URL+ mgr.service.send_event.assert_not_called()+ elif path == "test_service":+ assert mgr.test_service(service_urls)["status"] == "error"+ mgr.service.test_service.assert_not_called()+ else:assert mgr._filter_urls_by_egress_policy(service_urls) == ""- mock_logger.bind.assert_called_once_with(policy_audit=True)- warning = mock_logger.bind.return_value.warning- warning.assert_called_once()- # No content-bearing field at all.- assert "fragment" not in warning.call_args.kwargs- # Only the content-free diagnostics, and they are the real values.- assert warning.call_args.kwargs["fragment_length"] == len(fragment)- assert warning.call_args.kwargs["entries_parsed"] == 2- # Nothing derived from the input reaches the message or any kwarg.- emitted = [str(warning.call_args.args[0])] + [- str(value) for value in warning.call_args.kwargs.values()+ warnings = [+ r+ for r in capture_loguru_records+ if r["message"].startswith(expected_prefix)]- for text in emitted:+ assert len(warnings) == 1+ record = warnings[0]+ # The audit bind still routes the record correctly.+ assert record["extra"].get("policy_audit") is True+ # The content-free diagnostics ARE rendered into the message —+ # the only field production sinks show an operator.+ rendered = record["message"]+ assert f"fragment_length={len(fragment)}" in rendered+ assert "entries_parsed=2" in rendered+ if path == "send_notification":+ assert "user=u" in rendered+ assert f"event={EventType.RESEARCH_COMPLETED.value}" in rendered+ # ...and nothing derived from the fragment's content is, in the+ # message or in any bound field.+ for text in (rendered, str(record["extra"])):assert "secret.example.com" not in textassert "/private/token" not in textdiff --git a/tests/notifications/test_service.py b/tests/notifications/test_service.pyindex 40fc52913e..587729fd57 100644--- a/tests/notifications/test_service.py+++ b/tests/notifications/test_service.py@@ -928,3 +928,34 @@ class TestIntegration:assert "Test research query" in titleassert "Test summary" in bodyassert "http://localhost:5000/research/test-123" in body+++class TestPartitionUrlsMalformedFragmentLog:+ """``_partition_urls`` refuses a list with a malformed fragment and+ logs content-free diagnostics that production sinks can display."""++ def test_malformed_fragment_log_renders_diagnostics(+ self, capture_loguru_records+ ):+ """Teeth: pass ``fragment_length`` / ``entries_parsed`` as bare+ loguru kwargs again and the rendered-message assertions fail —+ no production sink formats ``extra`` (#5619). Log the fragment+ and the ``secret.example.com`` assertions fail."""+ fragment = "secret.example.com/private/token"++ assert NotificationService._partition_urls(+ f"{fragment} slack://t/x/y"+ ) == ([], [])++ warnings = [+ r+ for r in capture_loguru_records+ if "contains a malformed fragment" in r["message"]+ ]+ assert len(warnings) == 1+ rendered = warnings[0]["message"]+ assert f"fragment_length={len(fragment)}" in rendered+ assert "entries_parsed=2" in rendered+ for text in (rendered, str(warnings[0]["extra"])):+ assert "secret.example.com" not in text+ assert "/private/token" not in text