Skip to content

perf: report slow query progress - #359

Merged
Sinity merged 1 commit into
masterfrom
feature/perf/slow-query-transparency
Apr 22, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/perf/slow-query-transparency

Conversation

@Sinity

@Sinity Sinity commented Apr 22, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • Add a slow-query observer around CLI search/query execution paths.
  • Emit one human-only stderr progress note after a configurable threshold.
  • Include route, retrieval lane, and degraded action-read-model context when available.
  • Keep JSON, YAML, and CSV output streams clean.

Closes #219

Problem

Long CLI searches can appear hung, especially when execution falls back to a slower retrieval path or an action-event read model is not materialized. Before this change, human users received no progress signal while machine-readable output contracts could not tolerate extra status text.

Solution

  • Added polylogue/cli/query_progress.py with the slow-query notice model, machine-output suppression, threshold handling, and action read-model context probing.
  • Wrapped the main query retrieval operations in polylogue/cli/query.py so slow searches, counts, stats, open, modify, and delete paths report progress consistently.
  • Added CLI law tests proving human progress notes are emitted, JSON output stays silent, and degraded action read-model context is included.

Verification

  • ruff check polylogue/cli/query_progress.py polylogue/cli/query.py tests/unit/cli/test_query_exec_laws.py tests/unit/cli/test_query_exec.py
  • mypy polylogue/cli/query_progress.py polylogue/cli/query.py tests/unit/cli/test_query_exec_laws.py tests/unit/cli/test_query_exec.py
  • pytest -q tests/unit/cli/test_query_exec_laws.py tests/unit/cli/test_query_exec.py tests/unit/cli/test_json_envelope_contract.py
  • pytest -q tests/unit/security/test_attachment_security.py::test_path_traversal_creates_valid_attachment
  • devtools verify
  • push hook: devtools verify --quick

Summary by CodeRabbit

Release Notes

  • New Features

    • CLI queries now display progress notices when queries run longer than a configurable threshold.
    • Progress notices are suppressed for machine-readable output formats.
    • Notices include elapsed time, operation route, and retrieval lane information.
  • Tests

    • Added test coverage for slow-query progress notification behavior.

@coderabbitai

coderabbitai Bot commented Apr 22, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

A new slow-query transparency system was added to CLI query execution. It introduces a query_progress module providing notice generation and slow-query observation capabilities, integrates slow-query monitoring into the main query handler, and includes test coverage for progress signaling behavior across different output formats.

Changes

Cohort / File(s) Summary
Query Operation Wrapper
polylogue/cli/query.py
Added _observe_query_operation helper to wrap async query operations with slow-query observation. Updated async_execute_query_request to route COUNT, SUMMARY_LIST, SUMMARY_STATS, STATS_BY, OPEN, MODIFY, DELETE, and other operations through the observation wrapper instead of direct invocation.
Slow-Query Transparency Helpers
polylogue/cli/query_progress.py
New module implementing slow-query signaling infrastructure: QuerySlowNotice dataclass for formatting user-facing messages, slow_query_notice_threshold() for threshold computation via environment variable, should_emit_slow_query_notes() to suppress notices for machine-readable output formats, build_query_slow_notice() to construct notices with retrieval context and optional action-event artifact state, and observe_slow_query() to execute operations with concurrent timing and conditional notice emission.
Slow-Query Progress Tests
tests/unit/cli/test_query_exec_laws.py
Added three unit tests: one validating that delayed query execution emits a progress notice with elapsed time to stderr, another verifying that JSON output format suppresses progress notices, and a third confirming that build_query_slow_notice() correctly surfaces action-event artifact state in the notice message.

Sequence Diagram

sequenceDiagram
    participant CLI as CLI Handler
    participant OSQ as observe_slow_query
    participant OP as Query Operation
    participant NF as Notice Factory
    participant Emit as Emit (stderr)
    participant Result as Result

    CLI->>OSQ: operation, enabled, notice_factory, threshold
    activate OSQ
    OSQ->>OP: spawn async task
    activate OP
    OSQ->>OSQ: wait up to threshold_seconds
    alt Operation completes before threshold
        OP-->>OSQ: result
        OSQ->>Result: return result
    else Threshold exceeded
        OSQ->>NF: invoke notice_factory()
        activate NF
        NF-->>OSQ: QuerySlowNotice
        deactivate NF
        OSQ->>Emit: emit(notice.message())
        Emit->>Emit: click.echo(..., err=True)
        OSQ->>OP: await completion
        OP-->>OSQ: result
        OSQ->>Result: return result
    end
    deactivate OSQ
    deactivate OP
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

Poem

🐰 Hark! No more silent waits in the dark,
Our queries now whisper when running their arc,
A note in the night when the path stretches long,
Progress made plain—no more wondering wrong!
Silent for scripts, but transparent and true. ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 26.32% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'perf: report slow query progress' directly summarizes the main change: adding slow-query progress reporting to CLI query execution.
Description check ✅ Passed The description follows the template structure with all required sections (Summary, Problem, Solution, Verification) completed and detailed.
Linked Issues check ✅ Passed The PR implementation aligns with issue #219 objectives: emits progress notes when query execution exceeds a threshold [#219], suppresses progress for machine-readable outputs [#219], surfaces retrieval degradation and action-read-model context [#219], includes tests for slow-query behavior [#219], and verifies via devtools [#219].
Out of Scope Changes check ✅ Passed All changes directly support the slow-query transparency objective: query_progress.py provides the notice model and threshold handling, query.py integrates observation into query paths, and test_query_exec_laws.py validates the behavior.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/perf/slow-query-transparency

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@Sinity
Sinity merged commit 6693d0d into master Apr 22, 2026
13 of 14 checks passed

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
polylogue/cli/query.py (1)

472-499: ⚠️ Potential issue | 🟠 Major

Observe the full async semantic/profile stats path, not just summary lookup.

These branches stop observation before output_stats_by_semantic_summaries(...) / output_stats_by_profile_summaries(...), but those helpers can perform additional batched repository reads. If that phase is the slow part, no progress note is emitted.

🐛 Proposed restructuring
     if route == QueryRoute.STATS_BY and plan.stats_dimension in {"action", "tool"}:
-        semantic_summaries = await _observe_query_operation(
-            repo,
-            plan,
-            route,
-            _semantic_stats_summaries(repo, filter_chain),
-        )
-        if semantic_summaries is not None:
+        async def emit_semantic_stats() -> bool:
+            semantic_summaries = await _semantic_stats_summaries(repo, filter_chain)
+            if semantic_summaries is None:
+                return False
             await _query_output.output_stats_by_semantic_summaries(
                 env,
                 semantic_summaries,
                 repo,
                 _stats_dimension(plan),
                 selection=plan.selection,
                 output_format=plan.output.output_format,
             )
+            return True
+
+        if await _observe_query_operation(repo, plan, route, emit_semantic_stats()):
             return
 
     if route == QueryRoute.STATS_BY and plan.stats_dimension in {"repo", "work-kind"}:
-        summaries = await _observe_query_operation(repo, plan, route, _profile_stats_summaries(repo, filter_chain))
-        await _query_output.output_stats_by_profile_summaries(
-            env,
-            summaries,
-            repo,
-            _stats_dimension(plan),
-            selection=plan.selection,
-            output_format=plan.output.output_format,
-        )
+        async def emit_profile_stats() -> None:
+            summaries = await _profile_stats_summaries(repo, filter_chain)
+            await _query_output.output_stats_by_profile_summaries(
+                env,
+                summaries,
+                repo,
+                _stats_dimension(plan),
+                selection=plan.selection,
+                output_format=plan.output.output_format,
+            )
+
+        await _observe_query_operation(repo, plan, route, emit_profile_stats())
         return
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/cli/query.py` around lines 472 - 499, The observation currently
wraps only the summary-generation calls (_semantic_stats_summaries and
_profile_stats_summaries) via _observe_query_operation, which stops before the
subsequent output helpers and misses any batched repo reads inside
output_stats_by_semantic_summaries or output_stats_by_profile_summaries; change
the code so that _observe_query_operation wraps the entire async flow including
the calls to _query_output.output_stats_by_semantic_summaries and
_query_output.output_stats_by_profile_summaries (i.e., call
_observe_query_operation with a coroutine that runs the summary generator and
then invokes the corresponding output_* helper), or alternatively extend
_observe_query_operation to accept a post-processing callback so the observation
encompasses both summary creation and the output_* call for functions
_semantic_stats_summaries, _profile_stats_summaries,
output_stats_by_semantic_summaries, and output_stats_by_profile_summaries.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@polylogue/cli/query_progress.py`:
- Around line 45-54: The slow_query_notice_threshold function currently accepts
non-finite floats (NaN/inf) from POLYLOGUE_SLOW_QUERY_NOTICE_SECONDS; update it
to reject non-finite values by using math.isfinite(value) after parsing and
falling back to SLOW_QUERY_NOTICE_SECONDS when isfinite is False, and add the
necessary import for math; keep the existing ValueError handling and the
max(value, 0.0) clamp for valid finite values.
- Around line 134-142: The code spawns a detached task via task =
asyncio.ensure_future(operation) and doesn’t cancel it if the caller cancels
while waiting or building the notice; wrap the wait/notice logic in a try/except
asyncio.CancelledError block, and in the except call task.cancel() and await the
task (catching and ignoring its CancelledError) before re-raising the original
cancellation so task.cancelled() becomes True and its cleanup runs; apply this
change around the asyncio.wait call and the notice_factory/emit handling for the
symbols task, operation, notice_factory, emit and sink.

---

Outside diff comments:
In `@polylogue/cli/query.py`:
- Around line 472-499: The observation currently wraps only the
summary-generation calls (_semantic_stats_summaries and
_profile_stats_summaries) via _observe_query_operation, which stops before the
subsequent output helpers and misses any batched repo reads inside
output_stats_by_semantic_summaries or output_stats_by_profile_summaries; change
the code so that _observe_query_operation wraps the entire async flow including
the calls to _query_output.output_stats_by_semantic_summaries and
_query_output.output_stats_by_profile_summaries (i.e., call
_observe_query_operation with a coroutine that runs the summary generator and
then invokes the corresponding output_* helper), or alternatively extend
_observe_query_operation to accept a post-processing callback so the observation
encompasses both summary creation and the output_* call for functions
_semantic_stats_summaries, _profile_stats_summaries,
output_stats_by_semantic_summaries, and output_stats_by_profile_summaries.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: e70422b1-2564-45f7-b8ea-26dd2427b954

📥 Commits

Reviewing files that changed from the base of the PR and between c18be53 and bd7a83b.

📒 Files selected for processing (3)
  • polylogue/cli/query.py
  • polylogue/cli/query_progress.py
  • tests/unit/cli/test_query_exec_laws.py

Comment on lines +45 to +54
def slow_query_notice_threshold() -> float:
"""Return the slow-query notice threshold, allowing local override."""
raw_value = os.environ.get("POLYLOGUE_SLOW_QUERY_NOTICE_SECONDS")
if raw_value is None:
return SLOW_QUERY_NOTICE_SECONDS
try:
value = float(raw_value)
except ValueError:
return SLOW_QUERY_NOTICE_SECONDS
return max(value, 0.0)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Reject non-finite threshold overrides.

float("nan") and float("inf") parse successfully, but they are not safe timeout values and can also break elapsed formatting. Fall back to the default for non-finite values.

🛡️ Proposed fix
 import asyncio
+import math
 import os
@@
     try:
         value = float(raw_value)
     except ValueError:
         return SLOW_QUERY_NOTICE_SECONDS
+    if not math.isfinite(value):
+        return SLOW_QUERY_NOTICE_SECONDS
     return max(value, 0.0)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/cli/query_progress.py` around lines 45 - 54, The
slow_query_notice_threshold function currently accepts non-finite floats
(NaN/inf) from POLYLOGUE_SLOW_QUERY_NOTICE_SECONDS; update it to reject
non-finite values by using math.isfinite(value) after parsing and falling back
to SLOW_QUERY_NOTICE_SECONDS when isfinite is False, and add the necessary
import for math; keep the existing ValueError handling and the max(value, 0.0)
clamp for valid finite values.

Comment on lines +134 to +142
task = asyncio.ensure_future(operation)
done, _pending = await asyncio.wait({task}, timeout=threshold)
if done:
return task.result()

notice = await notice_factory()
sink = emit or (lambda message: click.echo(message, err=True))
sink(notice.message(elapsed_seconds=threshold))
return await task

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
python - <<'PY'
import asyncio

async def operation(flag):
    try:
        await asyncio.sleep(10)
    finally:
        flag["cancelled"] = True

async def current_pattern():
    flag = {"cancelled": False}
    task = asyncio.ensure_future(operation(flag))
    waiter = asyncio.create_task(asyncio.wait({task}, timeout=10))
    await asyncio.sleep(0)
    waiter.cancel()
    try:
        await waiter
    except asyncio.CancelledError:
        pass
    await asyncio.sleep(0)
    print("underlying task cancelled:", task.cancelled(), "cleanup ran:", flag["cancelled"])
    task.cancel()

asyncio.run(current_pattern())
PY

Repository: Sinity/polylogue

Length of output: 111


🏁 Script executed:

find . -name "query_progress.py" -type f

Repository: Sinity/polylogue

Length of output: 93


🏁 Script executed:

cat -n polylogue/cli/query_progress.py | sed -n '130,150p'

Repository: Sinity/polylogue

Length of output: 854


🏁 Script executed:

python - <<'PY'
import asyncio
from contextlib import suppress

async def operation(flag):
    try:
        await asyncio.sleep(10)
    finally:
        flag["cancelled"] = True

async def proposed_fix():
    flag = {"cancelled": False}
    task = asyncio.ensure_future(operation(flag))
    waiter = asyncio.create_task(asyncio.wait({task}, timeout=10))
    await asyncio.sleep(0)
    waiter.cancel()
    try:
        await waiter
    except asyncio.CancelledError:
        task.cancel()
        with suppress(asyncio.CancelledError):
            await task
        raise
    except BaseException:
        pass
    await asyncio.sleep(0)
    print("underlying task cancelled:", task.cancelled(), "cleanup ran:", flag["cancelled"])

asyncio.run(proposed_fix())
PY

Repository: Sinity/polylogue

Length of output: 889


🏁 Script executed:

python - <<'PY'
import asyncio
from contextlib import suppress

async def operation(flag):
    try:
        await asyncio.sleep(10)
    finally:
        flag["cancelled"] = True

async def proposed_fix_with_cancellation():
    flag = {"cancelled": False}
    task = asyncio.ensure_future(operation(flag))
    
    # Simulate cancellation during the wait
    async def wait_with_timeout():
        done, _pending = await asyncio.wait({task}, timeout=0.1)
        if done:
            return task.result()
        # Simulate something cancelling us here (like CLI cancellation)
        raise asyncio.CancelledError()
    
    try:
        result = await wait_with_timeout()
        return result
    except asyncio.CancelledError:
        task.cancel()
        with suppress(asyncio.CancelledError):
            await task
        raise
    
async def main():
    try:
        await proposed_fix_with_cancellation()
    except asyncio.CancelledError:
        pass
    await asyncio.sleep(0.1)
    print("Task cleanup works as expected")

asyncio.run(main())
PY

Repository: Sinity/polylogue

Length of output: 90


🏁 Script executed:

python - <<'PY'
import asyncio
from contextlib import suppress

async def operation(flag):
    try:
        await asyncio.sleep(10)
    finally:
        flag["cancelled"] = True

async def current_pattern_cancellation():
    """Simulates current pattern where cancellation happens during the wait"""
    flag = {"cancelled": False}
    task = asyncio.ensure_future(operation(flag))
    
    # Simulate timeout + cancellation during wait
    try:
        done, _pending = await asyncio.wait({task}, timeout=0.05)
        if done:
            return task.result()
        # Simulate external cancellation (e.g., CLI/request cancelled)
        raise asyncio.CancelledError("External cancellation")
    except asyncio.CancelledError:
        pass  # Current pattern doesn't handle this
    
    return flag

async def proposed_pattern_cancellation():
    """Simulates proposed fix with explicit task cancellation"""
    flag = {"cancelled": False}
    task = asyncio.ensure_future(operation(flag))
    
    try:
        done, _pending = await asyncio.wait({task}, timeout=0.05)
        if done:
            return task.result()
        # Simulate external cancellation
        raise asyncio.CancelledError("External cancellation")
    except asyncio.CancelledError:
        task.cancel()
        with suppress(asyncio.CancelledError):
            await task
        raise
    
    return flag

async def main():
    print("=== Current Pattern (without fix) ===")
    flag1 = await current_pattern_cancellation()
    await asyncio.sleep(0.2)
    print(f"Current pattern - Task cancelled: {flag1['cancelled']}")
    
    print("\n=== Proposed Pattern (with fix) ===")
    try:
        await proposed_pattern_cancellation()
    except asyncio.CancelledError:
        pass
    flag2 = {}  # The flag from proposed pattern is local, but let's track it differently
    
    # Better approach: track the actual task state
    flag = {"cancelled": False}
    task = asyncio.ensure_future(operation(flag))
    try:
        done, _pending = await asyncio.wait({task}, timeout=0.05)
        if not done:
            raise asyncio.CancelledError("External cancellation")
    except asyncio.CancelledError:
        task.cancel()
        with suppress(asyncio.CancelledError):
            await task
    
    await asyncio.sleep(0.1)
    print(f"Proposed pattern - Task cancelled: {task.cancelled()}, Cleanup ran: {flag['cancelled']}")

asyncio.run(main())
PY

Repository: Sinity/polylogue

Length of output: 233


🏁 Script executed:

head -20 polylogue/cli/query_progress.py

Repository: Sinity/polylogue

Length of output: 643


🏁 Script executed:

grep -n "^import\|^from" polylogue/cli/query_progress.py | head -15

Repository: Sinity/polylogue

Length of output: 479


🏁 Script executed:

grep -n "observe_slow_query" polylogue/cli/query_progress.py | head -5

Repository: Sinity/polylogue

Length of output: 123


🏁 Script executed:

grep -r "observe_slow_query" --include="*.py" | head -10

Repository: Sinity/polylogue

Length of output: 290


Cancel the spawned operation when observation is cancelled.

ensure_future(operation) detaches the query from the caller's cancellation path. If the CLI/request is cancelled while waiting or building the notice, the underlying repository operation continues running in the background.

The issue is demonstrated by the current pattern leaving the task unscheduled for cancellation:

  • Current behavior: when cancellation occurs, task.cancelled() returns False and cleanup code doesn't run
  • Proposed fix ensures: when cancellation occurs, task.cancelled() returns True and cleanup code runs
🔧 Proposed fix
 import asyncio
 import os
 from collections.abc import Awaitable, Callable
+from contextlib import suppress
     threshold = slow_query_notice_threshold() if threshold_seconds is None else max(threshold_seconds, 0.0)
     task = asyncio.ensure_future(operation)
-    done, _pending = await asyncio.wait({task}, timeout=threshold)
-    if done:
-        return task.result()
-
-    notice = await notice_factory()
-    sink = emit or (lambda message: click.echo(message, err=True))
-    sink(notice.message(elapsed_seconds=threshold))
-    return await task
+    try:
+        done, _pending = await asyncio.wait({task}, timeout=threshold)
+        if done:
+            return task.result()
+
+        notice = await notice_factory()
+        sink = emit or (lambda message: click.echo(message, err=True))
+        sink(notice.message(elapsed_seconds=threshold))
+        return await task
+    except asyncio.CancelledError:
+        task.cancel()
+        with suppress(asyncio.CancelledError):
+            await task
+        raise
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
task = asyncio.ensure_future(operation)
done, _pending = await asyncio.wait({task}, timeout=threshold)
if done:
return task.result()
notice = await notice_factory()
sink = emit or (lambda message: click.echo(message, err=True))
sink(notice.message(elapsed_seconds=threshold))
return await task
import asyncio
import os
from collections.abc import Awaitable, Callable
from contextlib import suppress
Suggested change
task = asyncio.ensure_future(operation)
done, _pending = await asyncio.wait({task}, timeout=threshold)
if done:
return task.result()
notice = await notice_factory()
sink = emit or (lambda message: click.echo(message, err=True))
sink(notice.message(elapsed_seconds=threshold))
return await task
task = asyncio.ensure_future(operation)
try:
done, _pending = await asyncio.wait({task}, timeout=threshold)
if done:
return task.result()
notice = await notice_factory()
sink = emit or (lambda message: click.echo(message, err=True))
sink(notice.message(elapsed_seconds=threshold))
return await task
except asyncio.CancelledError:
task.cancel()
with suppress(asyncio.CancelledError):
await task
raise
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/cli/query_progress.py` around lines 134 - 142, The code spawns a
detached task via task = asyncio.ensure_future(operation) and doesn’t cancel it
if the caller cancels while waiting or building the notice; wrap the wait/notice
logic in a try/except asyncio.CancelledError block, and in the except call
task.cancel() and await the task (catching and ignoring its CancelledError)
before re-raising the original cancellation so task.cancelled() becomes True and
its cleanup runs; apply this change around the asyncio.wait call and the
notice_factory/emit handling for the symbols task, operation, notice_factory,
emit and sink.

@Sinity
Sinity deleted the feature/perf/slow-query-transparency branch April 22, 2026 12:13
Sinity added a commit that referenced this pull request Apr 22, 2026
## Summary
- Add a slow-query observer around CLI search/query execution paths.
- Emit one human-only stderr progress note after a configurable threshold.
- Include route, retrieval lane, and degraded action-read-model context when available.
- Keep JSON, YAML, and CSV output streams clean.

Closes #219

## Problem
Long CLI searches can appear hung, especially when execution falls back to a slower retrieval path or an action-event read model is not materialized. Before this change, human users received no progress signal while machine-readable output contracts could not tolerate extra status text.

## Solution
- Added `polylogue/cli/query_progress.py` with the slow-query notice model, machine-output suppression, threshold handling, and action read-model context probing.
- Wrapped the main query retrieval operations in `polylogue/cli/query.py` so slow searches, counts, stats, open, modify, and delete paths report progress consistently.
- Added CLI law tests proving human progress notes are emitted, JSON output stays silent, and degraded action read-model context is included.

## Verification
- `ruff check polylogue/cli/query_progress.py polylogue/cli/query.py tests/unit/cli/test_query_exec_laws.py tests/unit/cli/test_query_exec.py`
- `mypy polylogue/cli/query_progress.py polylogue/cli/query.py tests/unit/cli/test_query_exec_laws.py tests/unit/cli/test_query_exec.py`
- `pytest -q tests/unit/cli/test_query_exec_laws.py tests/unit/cli/test_query_exec.py tests/unit/cli/test_json_envelope_contract.py`
- `pytest -q tests/unit/security/test_attachment_security.py::test_path_traversal_creates_valid_attachment`
- `devtools verify`
- push hook: `devtools verify --quick`

<!-- This is an auto-generated comment: release notes by coderabbit.ai -->

## Summary by CodeRabbit

## Release Notes

* **New Features**
  * CLI queries now display progress notices when queries run longer than a configurable threshold.
  * Progress notices are suppressed for machine-readable output formats.
  * Notices include elapsed time, operation route, and retrieval lane information.

* **Tests**
  * Added test coverage for slow-query progress notification behavior.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
@Sinity Sinity added area:cli CLI tool:claude Claude type:perf Performance labels Apr 22, 2026
Sinity added a commit that referenced this pull request Apr 22, 2026
Long CLI searches can appear hung, especially when execution falls
back to a slower retrieval path or an action-event read model
isn't materialized. Before this change, human users received no
progress signal while machine-readable output contracts couldn't
tolerate extra status text.

Adds `cli/query_progress.py` with the slow-query notice model,
machine-output suppression, threshold handling, and action
read-model context probing. One human-only stderr progress note
fires after a configurable threshold, including route, retrieval
lane, and degraded action-read-model context when available. JSON,
YAML, and CSV output streams stay clean.

Wraps the main query retrieval operations in `cli/query.py` so
slow searches, counts, stats, open, modify, and delete paths
report progress consistently. Adds CLI law tests proving human
progress notes are emitted, JSON output stays silent, and degraded
action read-model context is included.

Verification: ruff + mypy + pytest over query-exec-laws / query-exec
/ json-envelope / attachment-security suites; devtools verify and
--quick green.

Closes #219
Sinity added a commit that referenced this pull request Apr 22, 2026
Long CLI searches can appear hung, especially when execution falls
back to a slower retrieval path or an action-event read model
isn't materialized. Before this change, human users received no
progress signal while machine-readable output contracts couldn't
tolerate extra status text.

Adds `cli/query_progress.py` with the slow-query notice model,
machine-output suppression, threshold handling, and action
read-model context probing. One human-only stderr progress note
fires after a configurable threshold, including route, retrieval
lane, and degraded action-read-model context when available. JSON,
YAML, and CSV output streams stay clean.

Wraps the main query retrieval operations in `cli/query.py` so
slow searches, counts, stats, open, modify, and delete paths
report progress consistently. Adds CLI law tests proving human
progress notes are emitted, JSON output stays silent, and degraded
action read-model context is included.

Verification: ruff + mypy + pytest over query-exec-laws / query-exec
/ json-envelope / attachment-security suites; devtools verify and
--quick green.

Closes #219
Sinity added a commit that referenced this pull request Apr 22, 2026
Long CLI searches can appear hung, especially when execution falls
back to a slower retrieval path or an action-event read model
isn't materialized. Before this change, human users received no
progress signal while machine-readable output contracts couldn't
tolerate extra status text.

Adds `cli/query_progress.py` with the slow-query notice model,
machine-output suppression, threshold handling, and action
read-model context probing. One human-only stderr progress note
fires after a configurable threshold, including route, retrieval
lane, and degraded action-read-model context when available. JSON,
YAML, and CSV output streams stay clean.

Wraps the main query retrieval operations in `cli/query.py` so
slow searches, counts, stats, open, modify, and delete paths
report progress consistently. Adds CLI law tests proving human
progress notes are emitted, JSON output stays silent, and degraded
action read-model context is included.

Verification: ruff + mypy + pytest over query-exec-laws / query-exec
/ json-envelope / attachment-security suites; devtools verify and
--quick green.

Closes #219
@Sinity

Sinity commented May 1, 2026

Copy link
Copy Markdown
Owner Author

@codex review

@Sinity
Sinity requested a review from Copilot May 1, 2026 00:44

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 6693d0dcd7

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread polylogue/cli/query_progress.py Resolved
Comment thread polylogue/cli/query_progress.py Resolved
@Sinity
Sinity requested review from Copilot and removed request for Copilot May 1, 2026 01:05
Sinity added a commit that referenced this pull request Jul 31, 2026
…ch (#3455)

## Summary

Knob-excision sweep (operator's standing complaint: flags and
conditionals that are not pointless but harmful). Deletes three config
knobs where one branch strictly dominates or no branch exists at all:
two documented-but-inert config keys (`log_level`,
`slow_query_notice_seconds`) and one default-on off-switch whose off
branch reintroduces the policy bug its feature exists to close
(`daemon_whale_raw_materialization`). Net: **-103 lines**, 3 config
keys, 2 env-var mappings, 1 runtime conditional; the whale escalation
pass is now unconditional.

## Problem

Bead polylogue-8249 established the pattern: a documented knob nothing
reads is worse than no knob — it costs operator trust, test matrix, and
mental model. Sweeping every `PolylogueConfig` property for production
readers (rg two ways, excluding config.py itself) found:

- **`log_level`**: property + default + inventory entry
(`logging.level`), read by nothing. `polylogue/logging.py` derives its
level exclusively from the `--verbose` flag. Its only trace elsewhere
was a docs-coverage baseline entry recording that it was never even
documented.
- **`slow_query_notice_seconds`**: property + default + inventory +
`POLYLOGUE_SLOW_QUERY_NOTICE_SECONDS` env mapping + commented example in
`docs/configuration.md`. Zero reads in `polylogue/`, `devtools/`, or
`tests/`. Pickaxe traces the last real consumer to the pre-split-archive
era (#359 introduced it; the reporter was deleted generations ago, the
key survived).
- **`daemon_whale_raw_materialization`**: default `True` since
introduction (polylogue-t93b, #3256), never set to any other value in
the live config, any deployment, or git history (pickaxe shows only the
introducing commit). The flag's own docstring described the off branch
as "the pre-polylogue-t93b behavior" — i.e. holding whale components
permanently offline-manual, the exact policy bug t93b closed. A
default-on flag whose off branch is a known bug is pure cost: the on
branch strictly dominates.

## Solution

- `polylogue/config.py`: three properties, three defaults, three
inventory entries, and the `_FLOAT_CONFIG_KEYS`/`_BOOL_CONFIG_KEYS`
memberships deleted (-64 lines).
- `polylogue/daemon/cli.py`: `_maybe_run_raw_materialization_whale_pass`
no longer consults config; docstring states the pass is unconditional
and why.
- `docs/configuration.md`, `docs/plans/docs-coverage-baseline.yaml`,
`polylogue/sources/revision_backfill.py`: stale rows/example/comment
references removed in the same change (surgical renewal, no deprecation
theater).
- `tests/unit/daemon/test_daemon_cli.py`: the off-switch existence test
deleted with the flag; the two behavior tests (candidate found / no
candidate) are unchanged. Per CLAUDE.md, no tests were added that merely
assert the flags are gone.

Deliberately **not** cut (real losing axis exists):
`browser_capture_allow_remote`/`allow_no_auth` (security valves),
`embedding_enabled`/`judgment_automation_enabled` (cost opt-ins),
`mcp_*_enabled` (role-gate contract), parse-stage worker/byte knobs
(measured tuning surface), `sinex_mode` (permanent product mode).
Judgement call recorded as bead polylogue-v6xh instead of cut: the 16
`notification_*`/`health_*` typed properties are dead accessors
(consumers read `cfg.raw`), but the keys themselves are live — that is
accessor drift, not an inert knob.

## Verification

- `devtools verify --quick` — exit 0 (format, lint, mypy --strict,
render all --check, 18 steps).
- `devtools test tests/unit/core/test_config.py` — 95 passed.
- `devtools test tests/unit/daemon/test_daemon_cli.py` — 111 passed, 2
failed; the same 2 tests fail identically with pristine `origin/master`
code restored into the same worktree (`2 failed, 112 passed`), so they
are pre-existing and environment-dependent, not introduced here —
mechanism (autouse env scrub defeats the tests' `load_polylogue_config`
monkeypatch via the `archive_root()` fallback) filed as bead
polylogue-010x.
- Not run: full suite (behavior-preserving deletion; testmon unseeded in
this fresh worktree).

Ref polylogue-8249, polylogue-t93b.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01KAAzxpu1wNZLmuAb8Wgyso

---------

Co-authored-by: Claude Opus 5 <[email protected]>
@Sinity

Sinity commented Oct 1, 2026

Copy link
Copy Markdown
Owner Author

Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.

Only the rows listed above are dispositioned. Held findings remain open.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

perf: add slow-query transparency to CLI search

1 participant