Skip to content

refactor: split derived status metrics - #301

Merged
Sinity merged 5 commits into
masterfrom
feature/refactor/derived-status-builders
Apr 21, 2026
Merged

Sinity merged 5 commits into
masterfrom
feature/refactor/derived-status-builders

Conversation

@Sinity

@Sinity Sinity commented Apr 21, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • Split derived-status metric collection into message FTS, action-event, session-product, embedding, and retrieval metric builders.
  • Reworked action-event status collection around typed source/materialized count snapshots shared by sync and async surfaces.
  • Shared derived-status product builders for FTS, timeline, and aggregate readiness statuses.
  • Factored embedding-stat readers into shared base-stat snapshots and snapshot construction for sync and async callers.

Problem

collect_derived_model_statuses_sync flattened every derived-model metric into one large inline dict, obscuring which upstream status object owned each metric and making retrieval readiness coupling harder to audit. The adjacent action-event status and embedding-stat modules duplicated sync and async table probing, source-alignment counts, retrieval-band assembly, and public status construction. The product-status builder repeated the same metric coercion and DerivedModelStatus scaffolding across profile, timeline, FTS, and aggregate read models.

Solution

  • Added typed metric aliases and helper builders for each derived-status source.
  • Added private action-event source/count snapshots and shared status builders for sync and async APIs.
  • Added shared metric accessors, FTS status builders, timeline status builders, and aggregate status builders for archive-product readiness.
  • Added private embedding-stat parts and shared snapshot/retrieval-band assembly for sync and async readers.
  • Kept the existing build_archive_product_statuses, build_retrieval_statuses, public action-event status APIs, and public embedding-stat APIs unchanged.

Verification

  • pytest -q tests/unit/storage/test_action_event_artifacts.py tests/unit/storage/test_fts5.py
  • pytest -q tests/unit/storage/test_action_event_artifacts.py tests/unit/storage/test_derived_status.py tests/unit/cli/test_products.py tests/unit/core/test_health_core.py
  • pytest -q tests/unit/storage/test_embedding_stats.py tests/unit/storage/test_derived_status.py tests/unit/cli/test_embed.py
  • pytest -q tests/unit/storage/test_embedding_stats.py tests/unit/storage/test_action_event_artifacts.py tests/unit/storage/test_fts5.py tests/unit/storage/test_derived_status.py tests/unit/cli/test_products.py tests/unit/cli/test_embed.py tests/unit/core/test_health_core.py
  • mypy polylogue/storage/action_event_status.py tests/unit/storage/test_action_event_artifacts.py tests/unit/storage/test_fts5.py
  • mypy polylogue/storage/derived_status_products.py polylogue/storage/derived_status.py tests/unit/storage/test_action_event_artifacts.py tests/unit/storage/test_derived_status.py
  • mypy polylogue/storage/embedding_stats.py tests/unit/storage/test_embedding_stats.py tests/unit/storage/test_derived_status.py
  • mypy polylogue tests
  • devtools verify --quick

Ref #270

@coderabbitai

coderabbitai Bot commented Apr 21, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

Refactored storage modules across the codebase to introduce type aliases for metrics and status values, extract counting and metric construction logic into centralized helper functions, and consolidate sync/async database operations. Updated public function signatures to use typed dataclasses and aliases instead of untyped dictionaries.

Changes

Cohort / File(s) Summary
Storage Status Refactoring
polylogue/storage/action_event_status.py, polylogue/storage/derived_status.py, polylogue/storage/derived_status_products.py, polylogue/storage/embedding_stats.py
Introduced type aliases (SqlRow, StatusValue, ReadModelStatus, Metrics, MetricValue) and extracted database counting/metric computation into internal helpers (_counts_sync/_counts_async, _materialized_counts_*, _source_counts_*, etc.). Refactored public builders to use typed parameters and centralized helper functions for status construction. Return type signatures updated to use new type aliases (e.g., dict[str, int | bool] → ReadModelStatus/Metrics). Logic remains functionally equivalent but now modular and type-safe.
Test Exception Handling
tests/unit/pipeline/test_concurrency_guards.py
Updated concurrency test filtering to distinguish locked SQLite errors from other exceptions. Added _is_locked_error helper and revised assertions to track unexpected write exceptions and validate row counts against successful writes instead of a fixed constant.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 Hop hop, types now flow,
Helpers tidy up the show,
Dataclasses, aliases bright,
Database logic shining right,
Refactored storage, safe and sound! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 4.62% 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 'refactor: split derived status metrics' clearly and concisely describes the main refactoring work—splitting metric collection logic across the derived status modules.
Description check ✅ Passed The PR description comprehensively covers all template sections: a clear summary of changes, problem statement explaining the refactoring motivation, detailed solution approach across multiple modules, extensive verification steps with specific test commands and mypy checks, and no follow-up risks identified.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ 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/refactor/derived-status-builders

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.

Base automatically changed from feature/refactor/session-product-status-runtime to master April 21, 2026 13:50
@Sinity
Sinity force-pushed the feature/refactor/derived-status-builders branch from f180727 to a869790 Compare April 21, 2026 13:51

@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: 3

🤖 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/storage/action_event_status.py`:
- Around line 106-120: The async helpers leak cursors because they await
conn.execute(...) without using async context managers; update _count_async and
_table_exists_async to use "async with conn.execute(sql, params) as cur" (or
similar) and then call await cur.fetchone(), casting the result as before, so
cursors are explicitly closed; keep _table_exists_sync unchanged but ensure
_count_async uses the same pattern when executing its SQL and
_table_exists_async uses "async with conn.execute(_ACTION_EVENTS_EXISTS_SQL) as
cur" and returns bool(await cur.fetchone()).

In `@polylogue/storage/embedding_stats.py`:
- Around line 137-139: The function _total_conversations_async uses nested await
conn.execute(...).fetchone() which doesn't explicitly close the cursor; change
it to use an async context manager: open the cursor with "async with
conn.execute(... ) as cursor", await cursor.fetchone(), cast to StatsRow | None,
then return _row_count(row) so the cursor is closed promptly; update the
implementation in _total_conversations_async accordingly (no changes needed to
_row_count).

In `@tests/unit/pipeline/test_concurrency_guards.py`:
- Around line 363-378: The test currently allows all writes to be transiently
locked out and still pass; update the assertions in test_concurrency_guards.py
to require at least one successful write so the test fails if every write raises
a locked OperationalError: after computing successful_writes (from
write_results) add an assertion like assert successful_writes >= 1 (or a higher
floor you prefer) and keep the existing check that final_count ==
successful_writes by awaiting _read(); also update the test docstring (the one
describing reads during concurrent writes) to reflect that transient "database
locked" errors are tolerated for writes (but non-locked exceptions are still
failures). Ensure references use write_results, read_results, _is_locked_error,
successful_writes and _read to locate the relevant code.
🪄 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: bc016a92-e594-41ca-8f6f-8e44049920a9

📥 Commits

Reviewing files that changed from the base of the PR and between a2a3e7b and 8ff1fd5.

📒 Files selected for processing (5)
  • polylogue/storage/action_event_status.py
  • polylogue/storage/derived_status.py
  • polylogue/storage/derived_status_products.py
  • polylogue/storage/embedding_stats.py
  • tests/unit/pipeline/test_concurrency_guards.py

Comment on lines +106 to +120
async def _count_async(
conn: aiosqlite.Connection,
sql: str,
params: Sequence[object] = (),
) -> int:
row = cast(SqlRow | None, await (await conn.execute(sql, params)).fetchone())
return _row_int(row, 0)


def _table_exists_sync(conn: sqlite3.Connection) -> bool:
return conn.execute(_ACTION_EVENTS_EXISTS_SQL).fetchone() is not None


async def _table_exists_async(conn: aiosqlite.Connection) -> bool:
return bool(await (await conn.execute(_ACTION_EVENTS_EXISTS_SQL)).fetchone())

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick | 🔵 Trivial

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Find remaining nested aiosqlite execute/fetch patterns.
# Expectation: No matches after cursor handling is made explicit.
rg -nP 'await\s*\(\s*await\s+\w+\.execute\([^)]*\)\s*\)\.fetch(one|all)\s*\(' --type py

Repository: Sinity/polylogue

Length of output: 1889


🏁 Script executed:

#!/bin/bash
# Check aiosqlite imports and library usage in the codebase
rg -n "import aiosqlite|from aiosqlite" --type py | head -5

Repository: Sinity/polylogue

Length of output: 350


🌐 Web query:

aiosqlite cursor async context manager support

💡 Result:

Yes, aiosqlite cursors support async context managers. The Cursor class implements async aenter and async aexit(exc_type, exc_val, exc_tb) methods, enabling usage like: async with db.execute("SELECT * FROM some_table") as cursor: async for row in cursor: ... This automatically closes the cursor upon exit. Both Connection and Cursor are designed as async context managers for safe resource management in asyncio code. Example from official docs: async with aiosqlite.connect(...) as db: async with db.execute("SELECT * FROM some_table") as cursor: async for row in cursor: ...

Citations:


🏁 Script executed:

#!/bin/bash
# Find all usages of _count_async and _table_exists_async
rg -n "_count_async|_table_exists_async" --type py

Repository: Sinity/polylogue

Length of output: 7653


🏁 Script executed:

#!/bin/bash
# Check the full context of the functions and their return type annotations
cat -n polylogue/storage/action_event_status.py | sed -n '106,125p'

Repository: Sinity/polylogue

Length of output: 845


🏁 Script executed:

#!/bin/bash
# Verify operator precedence in Python: await vs comparison operators
python3 << 'EOF'
import ast
import inspect

# Test: await cursor.fetchone() is not None
# Python parses this as: await (cursor.fetchone() is not None) due to precedence
# which is incorrect

code1 = "await cursor.fetchone() is not None"
code2 = "(await cursor.fetchone()) is not None"

tree1 = ast.parse(code1, mode='eval')
tree2 = ast.parse(code2, mode='eval')

print("Without parentheses:")
print(ast.dump(tree1.body, indent=2))
print("\nWith parentheses:")
print(ast.dump(tree2.body, indent=2))
EOF

Repository: Sinity/polylogue

Length of output: 605


Use async context managers for explicit cursor cleanup in the shared async helpers.

These helpers are on the public async status path, so cursor cleanup should be explicit rather than relying on implicit garbage collection. aiosqlite supports async context managers for this purpose.

♻️ Proposed fix
 async def _count_async(
     conn: aiosqlite.Connection,
     sql: str,
     params: Sequence[object] = (),
 ) -> int:
-    row = cast(SqlRow | None, await (await conn.execute(sql, params)).fetchone())
+    async with conn.execute(sql, params) as cursor:
+        row = cast(SqlRow | None, await cursor.fetchone())
     return _row_int(row, 0)
@@
 async def _table_exists_async(conn: aiosqlite.Connection) -> bool:
-    return bool(await (await conn.execute(_ACTION_EVENTS_EXISTS_SQL)).fetchone())
+    async with conn.execute(_ACTION_EVENTS_EXISTS_SQL) as cursor:
+        return await cursor.fetchone() is not None
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/storage/action_event_status.py` around lines 106 - 120, The async
helpers leak cursors because they await conn.execute(...) without using async
context managers; update _count_async and _table_exists_async to use "async with
conn.execute(sql, params) as cur" (or similar) and then call await
cur.fetchone(), casting the result as before, so cursors are explicitly closed;
keep _table_exists_sync unchanged but ensure _count_async uses the same pattern
when executing its SQL and _table_exists_async uses "async with
conn.execute(_ACTION_EVENTS_EXISTS_SQL) as cur" and returns bool(await
cur.fetchone()).

Comment on lines +137 to +139
async def _total_conversations_async(conn: aiosqlite.Connection) -> int:
row = cast(StatsRow | None, await (await conn.execute("SELECT COUNT(*) FROM conversations")).fetchone())
return _row_count(row)

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Find remaining nested aiosqlite execute/fetch patterns.
# Expectation: No matches after cursor handling is made explicit.
rg -nP 'await\s*\(\s*await\s+\w+\.execute\([^)]*\)\s*\)\.fetch(one|all)\s*\(' --type py

Repository: Sinity/polylogue

Length of output: 1889


🏁 Script executed:

#!/bin/bash
# Check if there are existing examples of async context manager usage with aiosqlite
rg -n 'async with.*\.execute\(' --type py polylogue/storage/

Repository: Sinity/polylogue

Length of output: 42


🌐 Web query:

aiosqlite cursor cleanup fetchone async context manager

💡 Result:

In aiosqlite, Cursor objects support async context managers for automatic cleanup and are async iterators. Use async with db.execute("SELECT ...") as cursor: to safely execute queries, fetch data with await cursor.fetchone, and ensure the cursor closes automatically on exit, preventing resource leaks. Key practices: - Always use async with for cursors obtained via db.execute or db.cursor to handle aenter/aexit. - fetchone is async: row = await cursor.fetchone returns a single Row or None. - Context manager calls await cursor.close implicitly. - For manual handling (less recommended): cursor = await db.execute(sql); row = await cursor.fetchone; await cursor.close. - Connection async close handles queued cursors, but explicit cursor cleanup avoids queue buildup. Example: async with aiosqlite.connect('example.db') as db: async with db.execute('SELECT * FROM table LIMIT 1') as cursor: row = await cursor.fetchone # Use row; cursor auto-closes here This pattern ensures proper cleanup without explicit close calls in most cases.

Citations:


🏁 Script executed:

#!/bin/bash
# Verify the actual code in embedding_stats.py matches the snippet
sed -n '137,139p' polylogue/storage/embedding_stats.py

Repository: Sinity/polylogue

Length of output: 268


🏁 Script executed:

#!/bin/bash
# Check how often _total_conversations_async is called
rg -n '_total_conversations_async' --type py polylogue/

Repository: Sinity/polylogue

Length of output: 303


Use async context manager to explicitly close the cursor.

The nested await conn.execute(...).fetchone() pattern doesn't explicitly close cursors, relying on implicit cleanup when the connection closes. Per aiosqlite documentation, use the async context manager pattern to ensure cursors are properly closed, avoiding resource queue buildup during repeated calls.

♻️ Proposed fix
 async def _total_conversations_async(conn: aiosqlite.Connection) -> int:
-    row = cast(StatsRow | None, await (await conn.execute("SELECT COUNT(*) FROM conversations")).fetchone())
+    async with conn.execute("SELECT COUNT(*) FROM conversations") as cursor:
+        row = cast(StatsRow | None, await cursor.fetchone())
     return _row_count(row)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/storage/embedding_stats.py` around lines 137 - 139, The function
_total_conversations_async uses nested await conn.execute(...).fetchone() which
doesn't explicitly close the cursor; change it to use an async context manager:
open the cursor with "async with conn.execute(... ) as cursor", await
cursor.fetchone(), cast to StatsRow | None, then return _row_count(row) so the
cursor is closed promptly; update the implementation in
_total_conversations_async accordingly (no changes needed to _row_count).

Comment on lines +363 to +378
# Transient OperationalError("database is locked") is acceptable under
# heavy contention. SQLite WAL mode does not guarantee zero-wait access
# on all platforms. Non-locked exceptions are real failures.
unexpected_writes = [
result for result in write_results if isinstance(result, Exception) and not _is_locked_error(result)
]
assert unexpected_writes == [], (
f"Got unexpected write exceptions during concurrent read/write: {unexpected_writes}"
)

unexpected = [r for r in read_results if isinstance(r, Exception) and not _is_locked_error(r)]
assert unexpected == [], f"Got unexpected exceptions during concurrent read/write: {unexpected}"

# All 10 conversations should exist
successful_writes = sum(1 for result in write_results if not isinstance(result, Exception))
final_count = await _read()
assert final_count == 10
assert final_count == successful_writes

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

Test can pass vacuously if every write is locked out.

With the new tolerance, if all 10 writes happen to raise OperationalError("... locked ..."), unexpected_writes is empty, successful_writes is 0, and final_count == 0 — the test passes while actually demonstrating total write failure under contention. Consider asserting a minimum number of successful writes (e.g. assert successful_writes >= 1, or a higher floor) so the guard still proves that concurrent reads don't block writes entirely.

🛡️ Suggested floor
     successful_writes = sum(1 for result in write_results if not isinstance(result, Exception))
+    assert successful_writes > 0, (
+        f"All writes were locked out; test provides no real guarantee. write_results={write_results}"
+    )
     final_count = await _read()
     assert final_count == successful_writes

Also, the docstring on line 326 ("Reads during concurrent writes must not error or return garbage") is now inconsistent with the new tolerance — worth updating to reflect that transient lock errors are accepted.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/unit/pipeline/test_concurrency_guards.py` around lines 363 - 378, The
test currently allows all writes to be transiently locked out and still pass;
update the assertions in test_concurrency_guards.py to require at least one
successful write so the test fails if every write raises a locked
OperationalError: after computing successful_writes (from write_results) add an
assertion like assert successful_writes >= 1 (or a higher floor you prefer) and
keep the existing check that final_count == successful_writes by awaiting
_read(); also update the test docstring (the one describing reads during
concurrent writes) to reflect that transient "database locked" errors are
tolerated for writes (but non-locked exceptions are still failures). Ensure
references use write_results, read_results, _is_locked_error, successful_writes
and _read to locate the relevant code.

@Sinity
Sinity merged commit 60e0ca5 into master Apr 21, 2026
14 checks passed
@Sinity
Sinity deleted the feature/refactor/derived-status-builders branch April 21, 2026 14:17
Sinity added a commit that referenced this pull request Apr 22, 2026
## Summary
- Split derived-status metric collection into message FTS, action-event, session-product, embedding, and retrieval metric builders.
- Reworked action-event status collection around typed source/materialized count snapshots shared by sync and async surfaces.
- Shared derived-status product builders for FTS, timeline, and aggregate readiness statuses.
- Factored embedding-stat readers into shared base-stat snapshots and snapshot construction for sync and async callers.

## Problem
`collect_derived_model_statuses_sync` flattened every derived-model metric into one large inline dict, obscuring which upstream status object owned each metric and making retrieval readiness coupling harder to audit. The adjacent action-event status and embedding-stat modules duplicated sync and async table probing, source-alignment counts, retrieval-band assembly, and public status construction. The product-status builder repeated the same metric coercion and `DerivedModelStatus` scaffolding across profile, timeline, FTS, and aggregate read models.

## Solution
- Added typed metric aliases and helper builders for each derived-status source.
- Added private action-event source/count snapshots and shared status builders for sync and async APIs.
- Added shared metric accessors, FTS status builders, timeline status builders, and aggregate status builders for archive-product readiness.
- Added private embedding-stat parts and shared snapshot/retrieval-band assembly for sync and async readers.
- Kept the existing `build_archive_product_statuses`, `build_retrieval_statuses`, public action-event status APIs, and public embedding-stat APIs unchanged.

## Verification
- `pytest -q tests/unit/storage/test_action_event_artifacts.py tests/unit/storage/test_fts5.py`
- `pytest -q tests/unit/storage/test_action_event_artifacts.py tests/unit/storage/test_derived_status.py tests/unit/cli/test_products.py tests/unit/core/test_health_core.py`
- `pytest -q tests/unit/storage/test_embedding_stats.py tests/unit/storage/test_derived_status.py tests/unit/cli/test_embed.py`
- `pytest -q tests/unit/storage/test_embedding_stats.py tests/unit/storage/test_action_event_artifacts.py tests/unit/storage/test_fts5.py tests/unit/storage/test_derived_status.py tests/unit/cli/test_products.py tests/unit/cli/test_embed.py tests/unit/core/test_health_core.py`
- `mypy polylogue/storage/action_event_status.py tests/unit/storage/test_action_event_artifacts.py tests/unit/storage/test_fts5.py`
- `mypy polylogue/storage/derived_status_products.py polylogue/storage/derived_status.py tests/unit/storage/test_action_event_artifacts.py tests/unit/storage/test_derived_status.py`
- `mypy polylogue/storage/embedding_stats.py tests/unit/storage/test_embedding_stats.py tests/unit/storage/test_derived_status.py`
- `mypy polylogue tests`
- `devtools verify --quick`

Ref #270
@Sinity Sinity added tool:claude Claude type:refactor Code restructuring labels Apr 22, 2026
Sinity added a commit that referenced this pull request Apr 22, 2026
`collect_derived_model_statuses_sync` flattened every derived-
model metric into one large inline dict, obscuring which upstream
status object owned each metric and making retrieval readiness
coupling hard to audit. Adjacent action-event status and embedding-
stat modules duplicated sync/async table probing, source-alignment
counts, retrieval-band assembly, and public status construction.
The product-status builder repeated the same metric coercion and
`DerivedModelStatus` scaffolding across profile, timeline, FTS, and
aggregate read models.

Splits derived-status metric collection into message-FTS, action-
event, session-product, embedding, and retrieval metric builders.
Reworks action-event status collection around typed source /
materialized count snapshots shared by sync and async surfaces.
Shares derived-status product builders for FTS, timeline, and
aggregate readiness statuses. Factors embedding-stat readers into
shared base-stat snapshots and snapshot construction for sync and
async callers.

Keeps existing `build_archive_product_statuses`,
`build_retrieval_statuses`, public action-event status APIs, and
public embedding-stat APIs unchanged.

Verification: pytest + mypy over action-event-artifacts /
derived-status / embedding-stats / products / health-core / fts5
suites; devtools verify --quick green.

Ref #270
Sinity added a commit that referenced this pull request Apr 22, 2026
`cli/embed_stats.py` mixed database reads, status derivation,
freshness decisions, JSON payload construction, and terminal
rendering in a single flow. Hard to audit after the embedding-stat
reader cleanup in #301.

Splits embedding CLI payload derivation into focused status,
coverage, freshness, and readiness helpers. Splits terminal
rendering into named sections for timestamp windows, model/
dimension counts, and retrieval bands. Preserves the existing
`embedding_status_payload`, `render_embedding_stats`, and
`show_embedding_stats` public helpers; output labels and payload
keys stay stable.

Verification: pytest + mypy over embed-stats tests; devtools
verify --quick green.

Ref #270
Sinity added a commit that referenced this pull request Apr 22, 2026
`collect_derived_model_statuses_sync` flattened every derived-
model metric into one large inline dict, obscuring which upstream
status object owned each metric and making retrieval readiness
coupling hard to audit. Adjacent action-event status and embedding-
stat modules duplicated sync/async table probing, source-alignment
counts, retrieval-band assembly, and public status construction.
The product-status builder repeated the same metric coercion and
`DerivedModelStatus` scaffolding across profile, timeline, FTS, and
aggregate read models.

Splits derived-status metric collection into message-FTS, action-
event, session-product, embedding, and retrieval metric builders.
Reworks action-event status collection around typed source /
materialized count snapshots shared by sync and async surfaces.
Shares derived-status product builders for FTS, timeline, and
aggregate readiness statuses. Factors embedding-stat readers into
shared base-stat snapshots and snapshot construction for sync and
async callers.

Keeps existing `build_archive_product_statuses`,
`build_retrieval_statuses`, public action-event status APIs, and
public embedding-stat APIs unchanged.

Verification: pytest + mypy over action-event-artifacts /
derived-status / embedding-stats / products / health-core / fts5
suites; devtools verify --quick green.

Ref #270
Sinity added a commit that referenced this pull request Apr 22, 2026
`cli/embed_stats.py` mixed database reads, status derivation,
freshness decisions, JSON payload construction, and terminal
rendering in a single flow. Hard to audit after the embedding-stat
reader cleanup in #301.

Splits embedding CLI payload derivation into focused status,
coverage, freshness, and readiness helpers. Splits terminal
rendering into named sections for timestamp windows, model/
dimension counts, and retrieval bands. Preserves the existing
`embedding_status_payload`, `render_embedding_stats`, and
`show_embedding_stats` public helpers; output labels and payload
keys stay stable.

Verification: pytest + mypy over embed-stats tests; devtools
verify --quick green.

Ref #270
Sinity added a commit that referenced this pull request Apr 22, 2026
`collect_derived_model_statuses_sync` flattened every derived-
model metric into one large inline dict, obscuring which upstream
status object owned each metric and making retrieval readiness
coupling hard to audit. Adjacent action-event status and embedding-
stat modules duplicated sync/async table probing, source-alignment
counts, retrieval-band assembly, and public status construction.
The product-status builder repeated the same metric coercion and
`DerivedModelStatus` scaffolding across profile, timeline, FTS, and
aggregate read models.

Splits derived-status metric collection into message-FTS, action-
event, session-product, embedding, and retrieval metric builders.
Reworks action-event status collection around typed source /
materialized count snapshots shared by sync and async surfaces.
Shares derived-status product builders for FTS, timeline, and
aggregate readiness statuses. Factors embedding-stat readers into
shared base-stat snapshots and snapshot construction for sync and
async callers.

Keeps existing `build_archive_product_statuses`,
`build_retrieval_statuses`, public action-event status APIs, and
public embedding-stat APIs unchanged.

Verification: pytest + mypy over action-event-artifacts /
derived-status / embedding-stats / products / health-core / fts5
suites; devtools verify --quick green.

Ref #270
Sinity added a commit that referenced this pull request Apr 22, 2026
`cli/embed_stats.py` mixed database reads, status derivation,
freshness decisions, JSON payload construction, and terminal
rendering in a single flow. Hard to audit after the embedding-stat
reader cleanup in #301.

Splits embedding CLI payload derivation into focused status,
coverage, freshness, and readiness helpers. Splits terminal
rendering into named sections for timestamp windows, model/
dimension counts, and retrieval bands. Preserves the existing
`embedding_status_payload`, `render_embedding_stats`, and
`show_embedding_stats` public helpers; output labels and payload
keys stay stable.

Verification: pytest + mypy over embed-stats tests; devtools
verify --quick green.

Ref #270
@Sinity

Sinity commented Apr 28, 2026

Copy link
Copy Markdown
Owner Author

🤖 Post-hoc audit note: this PR received bot review feedback verified against current HEAD as part of #544. 1 finding(s) confirmed still present → tracked in #550.

@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:43
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🚀

ℹ️ 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".

@Sinity
Sinity removed the request for review from Copilot May 1, 2026 01:05
@Sinity

Sinity commented May 1, 2026

Copy link
Copy Markdown
Owner Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🎉

ℹ️ 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".

@Sinity
Sinity removed the request for review from Copilot May 1, 2026 02:15
Sinity pushed a commit that referenced this pull request Sep 2, 2026
Bumps [pytest-benchmark](https://github.com/ionelmc/pytest-benchmark)
from 5.2.3 to 5.3.0.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/ionelmc/pytest-benchmark/releases">pytest-benchmark's
releases</a>.</em></p>
<blockquote>
<h2>v5.3.0</h2>
<ul>
<li>Added --benchmark-precision and --benchmark-confidence: instead of a
fixed number of rounds, stop once the mean's relative margin of error
falls below the given fraction. Contributed by Aarni Koskela in <a
href="https://redirect.github.com/ionelmc/pytest-benchmark/pull/318">ionelmc/pytest-benchmark#318</a>.</li>
<li>Added compare --between mode. Example: pytest-benchmark compare
--between=min 0001 0002. Contributed by Aarni Koskela in <a
href="https://redirect.github.com/ionelmc/pytest-benchmark/pull/302">ionelmc/pytest-benchmark#302</a>.</li>
<li>Modernized the CI/linting and added spellchecking. Contributed by
Aarni Koskela in <a
href="https://redirect.github.com/ionelmc/pytest-benchmark/pull/304">ionelmc/pytest-benchmark#304</a>,
<a
href="https://redirect.github.com/ionelmc/pytest-benchmark/pull/306">ionelmc/pytest-benchmark#306</a>
and <a
href="https://redirect.github.com/ionelmc/pytest-benchmark/pull/319">ionelmc/pytest-benchmark#319</a>.</li>
<li>Defer the xdist auto-disable warning until a benchmark fixture is
collected. Contributed by xlyyddy in <a
href="https://redirect.github.com/ionelmc/pytest-benchmark/pull/317">ionelmc/pytest-benchmark#317</a>
(fixes <a
href="https://redirect.github.com/ionelmc/pytest-benchmark/issues/65">ionelmc/pytest-benchmark#65</a>).</li>
<li>Replaced deprecated argparse.FileType. Contributed by Sophia
Castellarin in <a
href="https://redirect.github.com/ionelmc/pytest-benchmark/pull/310">ionelmc/pytest-benchmark#310</a>.</li>
<li>Fixed various spelling/typos. Contributed by Daniel Holth and Hugo
van Kemenade in <a
href="https://redirect.github.com/ionelmc/pytest-benchmark/pull/297">ionelmc/pytest-benchmark#297</a>
and <a
href="https://redirect.github.com/ionelmc/pytest-benchmark/pull/299">ionelmc/pytest-benchmark#299</a>.</li>
<li>Cleaned up various dead code. Contributed by Hugo van Kemenade in <a
href="https://redirect.github.com/ionelmc/pytest-benchmark/pull/300">ionelmc/pytest-benchmark#300</a>
and <a
href="https://redirect.github.com/ionelmc/pytest-benchmark/pull/301">ionelmc/pytest-benchmark#301</a>.</li>
<li>CI now tests only with latest Pytest (now 9.1.1), Python 3.10-3.14
and PyPy 3.11.</li>
</ul>
</blockquote>
</details>
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/ionelmc/pytest-benchmark/blob/master/CHANGELOG.rst">pytest-benchmark's
changelog</a>.</em></p>
<blockquote>
<h2>v5.3.0 (2026-08-23)</h2>
<ul>
<li>Added <code>--benchmark-precision</code> and
<code>--benchmark-confidence</code>:
instead of a fixed number of rounds, stop once the mean's relative
margin of error falls below the given fraction.
Contributed by Aarni Koskela in
<code>[#318](ionelmc/pytest-benchmark#318)
&lt;https://github.com/ionelmc/pytest-benchmark/pull/318&gt;</code>_.</li>
<li>Added <code>compare --between</code> mode. Example:
<code>pytest-benchmark compare --between=min 0001 0002</code>.
Contributed by Aarni Koskela in
<code>[#302](ionelmc/pytest-benchmark#302)
&lt;https://github.com/ionelmc/pytest-benchmark/pull/302&gt;</code>_.</li>
<li>Modernized the CI/linting and added spellchecking.
Contributed by Aarni Koskela in
<code>[#304](ionelmc/pytest-benchmark#304)
&lt;https://github.com/ionelmc/pytest-benchmark/pull/304&gt;</code><em>,
<code>[#306](ionelmc/pytest-benchmark#306)
&lt;https://github.com/ionelmc/pytest-benchmark/pull/306&gt;</code></em>
and
<code>[#319](ionelmc/pytest-benchmark#319)
&lt;https://github.com/ionelmc/pytest-benchmark/pull/319&gt;</code>_.</li>
<li>Defer the xdist auto-disable warning until a benchmark fixture is
collected.
Contributed by xlyyddy in
<code>[#317](ionelmc/pytest-benchmark#317)
&lt;https://github.com/ionelmc/pytest-benchmark/pull/317&gt;</code>_
(fixes
<code>[#65](ionelmc/pytest-benchmark#65)
&lt;https://github.com/ionelmc/pytest-benchmark/issues/65&gt;</code>_).</li>
<li>Replaced deprecated argparse.FileType.
Contributed by Sophia Castellarin in
<code>[#310](ionelmc/pytest-benchmark#310)
&lt;https://github.com/ionelmc/pytest-benchmark/pull/310&gt;</code>_.</li>
<li>Fixed various spelling/typos.
Contributed by Daniel Holth and Hugo van Kemenade in
<code>[#297](ionelmc/pytest-benchmark#297)
&lt;https://github.com/ionelmc/pytest-benchmark/pull/297&gt;</code>_ and
<code>[#299](ionelmc/pytest-benchmark#299)
&lt;https://github.com/ionelmc/pytest-benchmark/pull/299&gt;</code>_.</li>
<li>Cleaned up various dead code.
Contributed by Hugo van Kemenade in
<code>[#300](ionelmc/pytest-benchmark#300)
&lt;https://github.com/ionelmc/pytest-benchmark/pull/300&gt;</code>_ and
<code>[#301](ionelmc/pytest-benchmark#301)
&lt;https://github.com/ionelmc/pytest-benchmark/pull/301&gt;</code>_.</li>
<li>CI now tests only with latest Pytest (now 9.1.1), Python 3.10-3.14
and PyPy 3.11.</li>
</ul>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="https://github.com/ionelmc/pytest-benchmark/commit/07d519672687402e6c3fac1a543fbefd810d1e5b"><code>07d5196</code></a>
Bump version: 5.2.3 → 5.3.0</li>
<li><a
href="https://github.com/ionelmc/pytest-benchmark/commit/accf7331e22c0ede38ffa72081c38f3469e0c9b5"><code>accf733</code></a>
Add some details on <a
href="https://redirect.github.com/ionelmc/pytest-benchmark/issues/304">#304</a>.</li>
<li><a
href="https://github.com/ionelmc/pytest-benchmark/commit/417dd9fa275e8b9d62c469e676cdb7546d2c4b8f"><code>417dd9f</code></a>
Really update the changelog.</li>
<li><a
href="https://github.com/ionelmc/pytest-benchmark/commit/898acb34430c99ad877e94c52c8b90256a3bb4a8"><code>898acb3</code></a>
Update changelog and plan release.</li>
<li><a
href="https://github.com/ionelmc/pytest-benchmark/commit/9cc7ef0bb1ad3785a46834b24660562dd48e4a0b"><code>9cc7ef0</code></a>
Defer xdist warning until benchmark collection (<a
href="https://redirect.github.com/ionelmc/pytest-benchmark/issues/65">#65</a>)</li>
<li><a
href="https://github.com/ionelmc/pytest-benchmark/commit/ef485506f04d5510831fdbdee5be7014f4726a93"><code>ef48550</code></a>
Some minor skel updates: test only against latest pytest; bump
linting/format...</li>
<li><a
href="https://github.com/ionelmc/pytest-benchmark/commit/88eaea957d1685f604a5835555d2ce5dbec1ac29"><code>88eaea9</code></a>
Add --benchmark-precision for adaptive rounds (opt-in)</li>
<li><a
href="https://github.com/ionelmc/pytest-benchmark/commit/3b83d127127de74d9f71a3a78e5f661fac044950"><code>3b83d12</code></a>
Update and freeze GHA actions</li>
<li><a
href="https://github.com/ionelmc/pytest-benchmark/commit/4b7662fbfba046eb92dd183e005e8708ac81e6cd"><code>4b7662f</code></a>
Fix ruff complaints</li>
<li><a
href="https://github.com/ionelmc/pytest-benchmark/commit/26b011361d2c41f529a73833e1be8d3a565600fa"><code>26b0113</code></a>
Remove Taplo lint (unmaintained)</li>
<li>Additional commits viewable in <a
href="https://github.com/ionelmc/pytest-benchmark/compare/v5.2.3...v5.3.0">compare
view</a></li>
</ul>
</details>
<br />


[![Dependabot compatibility
score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=pytest-benchmark&package-manager=uv&previous-version=5.2.3&new-version=5.3.0)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)

Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)


</details>

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

tool:claude Claude type:refactor Code restructuring

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant