Skip to content

feat(maintenance): add message_type backfill for pre-#839 rows (#839) - #988

Merged
Sinity merged 1 commit into
masterfrom
feature/feat/message-type-backfill
May 9, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/feat/message-type-backfill

Conversation

@Sinity

@Sinity Sinity commented May 9, 2026 •

Copy link
Copy Markdown
Owner

Summary

Adds a one-shot, idempotent backfill operation that assigns message_type to rows ingested before PR #894 (which introduced persisted CONTEXT/PROTOCOL classification). Complements PR #977 (dropping the runtime classifier fallback).

Certification

WORK

AC #2 of #839: backfill pre-#839 rows with correct message_type

REALIZATION

  1. polylogue/maintenance/targets.py: maintenance target registration
  2. polylogue/storage/repair.py: idempotent backfill logic
  3. tests/unit/pipeline/test_message_type_backfill.py: idempotency + fill coverage

DECLARATION

I declare the WORK item above to be fully realized. AC #6 (before/after artifact counts) remains tracked in #839. Verified by: pytest.

Refs #839

Summary by CodeRabbit

Release Notes

  • New Features

    • Added a new message type backfill maintenance operation that automatically classifies and updates unclassified messages.
  • Tests

    • Added comprehensive test coverage for the message type backfill operation, including idempotency and dry-run validation.

Review Change Stack

Copilot AI review requested due to automatic review settings May 9, 2026 16:59
@coderabbitai

coderabbitai Bot commented May 9, 2026 •

Copy link
Copy Markdown

Warning

Rate limit exceeded

@Sinity has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 36 minutes and 8 seconds before requesting another review.

You’ve run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 2be7b67a-fb96-41e3-b48f-3530f43837f8

📥 Commits

Reviewing files that changed from the base of the PR and between d536cd1 and cf8dbc0.

📒 Files selected for processing (3)
  • polylogue/storage/repair.py
  • tests/unit/core/test_maintenance_targets.py
  • tests/unit/pipeline/test_message_type_backfill.py
📝 Walkthrough

Walkthrough

This PR implements a message type backfill maintenance target that reclassifies unclassified messages in the database. It adds target registration, repair functions (counter, preview, repair), handler wiring, debt status collection integration, public exports, and comprehensive test coverage.

Changes

Message Type Backfill Maintenance Target

Layer / File(s) Summary
Target Definition
polylogue/maintenance/targets.py
Registers message_type_backfill as a non-destructive repair target in MAINTENANCE_TARGET_SPECS with preview enabled and wired to backfill-message-type doctor operation.
Repair Core Implementation
polylogue/storage/repair.py
Adds count_unclassified_message_type_sync to count pre-#839 message rows with default message_type, preview_message_type_backfill to generate preview output, and repair_message_type_backfill to classify and update message_type values in batches using classify_text_message_type.
Orchestration Wiring & Exports
polylogue/storage/repair.py
Registers new handlers in _PREVIEW_HANDLERS and _REPAIR_HANDLERS dictionaries, integrates counter into collect_archive_debt_statuses_sync, and exports three new functions in __all__.
Test Expectations & Coverage
tests/unit/core/test_maintenance_targets.py, tests/unit/pipeline/test_message_type_backfill.py
Updates test expectations for catalog names and help text, and adds TestMessageTypeBackfill suite verifying correct classification, idempotency, alignment with pipeline logic, and dry-run isolation.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Poem

🐇 A maintenance hop through message rows,
Where message becomes what the text shows—
Context whispers, protocol calls,
The backfill repairs pre-839 halls.
Dry-run first, then commit with grace! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 69.23% 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 'feat(maintenance): add message_type backfill for pre-#839 rows (#839)' accurately describes the main change: adding a message_type backfill feature for legacy rows, with clear context via issue references.
Description check ✅ Passed The PR description covers Summary, Problem context, Solution with module references, and Verification method, though Changelog and Risks sections are not explicitly addressed.
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 unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/feat/message-type-backfill

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.

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

ℹ️ 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/storage/repair.py Resolved
Comment thread polylogue/storage/repair.py Resolved
Comment thread polylogue/storage/repair.py Resolved

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

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@polylogue/storage/repair.py`:
- Around line 90-94: Fix the stray double space in the SQL string returned by
the count operation: in the return statement that executes "SELECT COUNT(*) FROM
messages WHERE message_type = 'message'  AND text IS NOT NULL AND text != ''"
(in polylogue/storage/repair.py) replace the two spaces between 'message' and
AND with a single space so the WHERE clause reads "...message_type = 'message'
AND text IS NOT NULL...". Ensure the rest of the query string formatting remains
unchanged.
- Around line 1077-1086: The import of MessageType is inside the hot loop that
iterates over rows; hoist it so the loop only calls classify_text_message_type
and appends to context_ids/protocol_ids. Move "from
polylogue.archive.message.types import MessageType" out of the loop—either to
the module top or directly above the rows iteration (next to
classify_text_message_type) so the loop body contains only the classification
call and the if/elif checks comparing mt to MessageType.CONTEXT and
MessageType.PROTOCOL.
- Around line 1061-1104: The loop using OFFSET slices the shrinking filtered set
and skips rows; replace OFFSET pagination with keyset pagination over rowid:
change the SELECT in the loop (used with classify_text_message_type and the
context_ids/protocol_ids updates) to "WHERE message_type = 'message' AND text IS
NOT NULL AND text != '' AND rowid > :last_rowid ORDER BY rowid LIMIT
:batch_size" (or equivalent bind params), track last_rowid = max(rowid) from
each fetched batch and use that for the next iteration instead of offset, keep
the same reclassification and UPDATE logic for context_ids and protocol_ids, and
add a regression test that seeds more than batch_size candidates (or reduces
batch_size) to ensure no rows are skipped.
- Around line 1088-1102: The code in repair.py is incorrectly using
sqlite3.Connection.total_changes (which is cumulative) to increment updated
after the UPDATEs in the blocks that set message_type to 'context' and
'protocol'; replace the calls to conn.total_changes by capturing the cursor
returned from conn.execute (e.g., cur = conn.execute(...)) and add cur.rowcount
to updated for each UPDATE (apply this change to both the context_ids and
protocol_ids UPDATEs so repaired_count no longer double-counts).

In `@tests/unit/pipeline/test_message_type_backfill.py`:
- Around line 104-106: Update the unit tests to assert the exact expected
repaired count (5) instead of a loose >0 check: in test_message_type_backfill
replace the loose assertion on result.repaired_count with assert
result.repaired_count == 5, and similarly in test_dry_run_does_not_mutate ensure
it asserts result.repaired_count == 5; reference the repair function call
repair_message_type_backfill and the test functions test_message_type_backfill /
test_dry_run_does_not_mutate so the tests will catch the cumulative
conn.total_changes miscounting bug.
- Around line 163-191: The test named
test_backfill_matches_pipeline_classification is misnamed and doesn't exercise
the backfill; either rename it to something like test_classify_text_message_type
and remove the unused fixtures workspace_env and monkeypatch, or convert it into
a true backfill integration test: seed messages into the DB with the test
inputs, call repair_message_type_backfill, query the stored messages and assert
their message_type equals the expected MessageType for each case; reference
classify_text_message_type for expected behavior and
repair_message_type_backfill for the backfill flow when making the change.
🪄 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: 94afb839-3e5e-4280-af98-c43a2d7699e4

📥 Commits

Reviewing files that changed from the base of the PR and between eeace79 and d536cd1.

📒 Files selected for processing (4)
  • polylogue/maintenance/targets.py
  • polylogue/storage/repair.py
  • tests/unit/core/test_maintenance_targets.py
  • tests/unit/pipeline/test_message_type_backfill.py

Comment on lines +90 to +94
return int(
conn.execute(
"SELECT COUNT(*) FROM messages WHERE message_type = 'message' AND text IS NOT NULL AND text != ''"
).fetchone()[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.

🧹 Nitpick | 🔵 Trivial | 💤 Low value

Nit: stray double space in SQL string.

"... message_type = 'message' AND text IS NOT NULL ..." has two spaces between 'message' and AND. Harmless to SQLite, but inconsistent with the rest of the file.

♻️ Proposed nit
-            "SELECT COUNT(*) FROM messages WHERE message_type = 'message'  AND text IS NOT NULL AND text != ''"
+            "SELECT COUNT(*) FROM messages WHERE message_type = 'message' AND text IS NOT NULL AND text != ''"
📝 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
return int(
conn.execute(
"SELECT COUNT(*) FROM messages WHERE message_type = 'message' AND text IS NOT NULL AND text != ''"
).fetchone()[0]
)
return int(
conn.execute(
"SELECT COUNT(*) FROM messages WHERE message_type = 'message' AND text IS NOT NULL AND text != ''"
).fetchone()[0]
)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@polylogue/storage/repair.py` around lines 90 - 94, Fix the stray double space
in the SQL string returned by the count operation: in the return statement that
executes "SELECT COUNT(*) FROM messages WHERE message_type = 'message'  AND text
IS NOT NULL AND text != ''" (in polylogue/storage/repair.py) replace the two
spaces between 'message' and AND with a single space so the WHERE clause reads
"...message_type = 'message' AND text IS NOT NULL...". Ensure the rest of the
query string formatting remains unchanged.

Comment on lines +1061 to +1104
while True:
rows = conn.execute(
"SELECT rowid, message_id, text FROM messages"
" WHERE message_type = 'message'"
" AND text IS NOT NULL AND text != ''"
" ORDER BY rowid"
" LIMIT ? OFFSET ?",
(batch_size, offset),
).fetchall()

if not rows:
break

context_ids: list[int] = []
protocol_ids: list[int] = []

for row in rows:
rowid_val, _message_id, text = row
mt = classify_text_message_type(text)
if mt is not None:
from polylogue.archive.message.types import MessageType

if mt == MessageType.CONTEXT:
context_ids.append(rowid_val)
elif mt == MessageType.PROTOCOL:
protocol_ids.append(rowid_val)

if context_ids:
placeholders = ",".join("?" * len(context_ids))
conn.execute(
f"UPDATE messages SET message_type = 'context' WHERE rowid IN ({placeholders})",
context_ids,
)
updated += conn.total_changes

if protocol_ids:
placeholders = ",".join("?" * len(protocol_ids))
conn.execute(
f"UPDATE messages SET message_type = 'protocol' WHERE rowid IN ({placeholders})",
protocol_ids,
)
updated += conn.total_changes

offset += batch_size

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 | 🔴 Critical | 🏗️ Heavy lift

Critical: OFFSET pagination silently skips rows because the WHERE clause shrinks during iteration.

The SELECT filters message_type = 'message' and updates rows to 'context'/'protocol' mid-loop, removing them from the filtered set. The next iteration uses OFFSET 1000 against this shrunken result, so rows that should have been processed are skipped.

Concrete example with batch_size=1000 over 5000 candidates where ~20% match a marker:

  • Iter 1: fetches rowids 1–1000, reclassifies 200 → 800 still match in that range.
  • Iter 2: OFFSET 1000 against the new filtered set skips those 800 plus 200 from rowids 1001–1200 → rows 1001–1200 are never seen.

The fixture-based tests don't trigger this because all 7 candidates fit in a single batch. Switch to keyset pagination by rowid:

🐛 Proposed fix (keyset pagination)
-            updated = 0
-            batch_size = 1000
-            offset = 0
-
-            while True:
-                rows = conn.execute(
-                    "SELECT rowid, message_id, text FROM messages"
-                    " WHERE message_type = 'message'"
-                    "  AND text IS NOT NULL AND text != ''"
-                    " ORDER BY rowid"
-                    " LIMIT ? OFFSET ?",
-                    (batch_size, offset),
-                ).fetchall()
-
-                if not rows:
-                    break
-                ...
-                offset += batch_size
+            from polylogue.archive.message.types import MessageType
+
+            updated = 0
+            batch_size = 1000
+            last_rowid = 0
+
+            while True:
+                rows = conn.execute(
+                    "SELECT rowid, message_id, text FROM messages"
+                    " WHERE message_type = 'message'"
+                    "  AND rowid > ?"
+                    "  AND text IS NOT NULL AND text != ''"
+                    " ORDER BY rowid"
+                    " LIMIT ?",
+                    (last_rowid, batch_size),
+                ).fetchall()
+
+                if not rows:
+                    break
+                ...
+                last_rowid = rows[-1][0]

Add a regression test that seeds >batch_size candidates (or temporarily lowers batch_size) so this case is covered.

🧰 Tools
🪛 OpenGrep (1.20.0)

[ERROR] 1090-1093: SQL query built via f-string passed to execute()/executemany(). Use parameterized queries with placeholders instead.

(coderabbit.sql-injection.python-fstring-execute)


[ERROR] 1098-1101: SQL query built via f-string passed to execute()/executemany(). Use parameterized queries with placeholders instead.

(coderabbit.sql-injection.python-fstring-execute)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@polylogue/storage/repair.py` around lines 1061 - 1104, The loop using OFFSET
slices the shrinking filtered set and skips rows; replace OFFSET pagination with
keyset pagination over rowid: change the SELECT in the loop (used with
classify_text_message_type and the context_ids/protocol_ids updates) to "WHERE
message_type = 'message' AND text IS NOT NULL AND text != '' AND rowid >
:last_rowid ORDER BY rowid LIMIT :batch_size" (or equivalent bind params), track
last_rowid = max(rowid) from each fetched batch and use that for the next
iteration instead of offset, keep the same reclassification and UPDATE logic for
context_ids and protocol_ids, and add a regression test that seeds more than
batch_size candidates (or reduces batch_size) to ensure no rows are skipped.

Comment on lines +1077 to +1086
for row in rows:
rowid_val, _message_id, text = row
mt = classify_text_message_type(text)
if mt is not None:
from polylogue.archive.message.types import MessageType

if mt == MessageType.CONTEXT:
context_ids.append(rowid_val)
elif mt == MessageType.PROTOCOL:
protocol_ids.append(rowid_val)

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 | 💤 Low value

Hoist MessageType import out of the row loop.

The import is re-resolved for every classified row. While import is cached, this still adds dict-lookup overhead inside the hot path and clutters the loop body. Move to module top (or once at function entry alongside classify_text_message_type).

♻️ Proposed refactor
-    from polylogue.archive.message.artifacts import classify_text_message_type
-    from polylogue.storage.sqlite.connection import connection_context
+    from polylogue.archive.message.artifacts import classify_text_message_type
+    from polylogue.archive.message.types import MessageType
+    from polylogue.storage.sqlite.connection import connection_context
     ...
                 for row in rows:
                     rowid_val, _message_id, text = row
                     mt = classify_text_message_type(text)
                     if mt is not None:
-                        from polylogue.archive.message.types import MessageType
-
                         if mt == MessageType.CONTEXT:
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@polylogue/storage/repair.py` around lines 1077 - 1086, The import of
MessageType is inside the hot loop that iterates over rows; hoist it so the loop
only calls classify_text_message_type and appends to context_ids/protocol_ids.
Move "from polylogue.archive.message.types import MessageType" out of the
loop—either to the module top or directly above the rows iteration (next to
classify_text_message_type) so the loop body contains only the classification
call and the if/elif checks comparing mt to MessageType.CONTEXT and
MessageType.PROTOCOL.

Comment on lines +1088 to +1102
if context_ids:
placeholders = ",".join("?" * len(context_ids))
conn.execute(
f"UPDATE messages SET message_type = 'context' WHERE rowid IN ({placeholders})",
context_ids,
)
updated += conn.total_changes

if protocol_ids:
placeholders = ",".join("?" * len(protocol_ids))
conn.execute(
f"UPDATE messages SET message_type = 'protocol' WHERE rowid IN ({placeholders})",
protocol_ids,
)
updated += conn.total_changes

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 | 🔴 Critical | ⚡ Quick win

🧩 Analysis chain

🌐 Web query:

sqlite3.Connection.total_changes vs cursor.rowcount semantics in Python

💡 Result:

In Python’s sqlite3 module (DB-API 2.0), Connection.total_changes and Cursor.rowcount measure different things, and Cursor.rowcount is generally not usable for SELECT result counts. 1) sqlite3.Connection.total_changes - Meaning: It returns the total number of database rows that have been modified, inserted, or deleted since the connection was opened. [1] - Scope: It is cumulative for that connection (i.e., across multiple statements on the same connection). [1] - SQLite-specific semantics: sqlite3_total_changes counts rows affected by INSERT/UPDATE/DELETE completed since the connection opened, including those executed as part of trigger programs; it is not affected by other types of SQL statements. [1] - Python docs note it is “Return the total number of database rows that have been modified, inserted, or deleted since the database connection was opened.” [2] 2) sqlite3.Cursor.rowcount semantics - DB-API definition: Cursor.rowcount is the number of rows produced (for DQL like SELECT) or affected (for DML like UPDATE/INSERT). If the interface cannot determine it, the value is -1. [3] - Python sqlite3 docs for the sqlite3 module: rowcount is a read-only attribute that provides the number of modified rows for INSERT/UPDATE/DELETE/REPLACE; it is -1 for other statements (including CTE queries). It is only updated by execute and executemany after the statement has run to completion; any resulting rows must be fetched in order for rowcount to be updated. [4] - Why this feels surprising for SELECT: SQLite returns results incrementally; you don’t necessarily know the full result-set size until iteration completes. As noted in a widely referenced SQLite/driver explanation: SQLite doesn’t “fetch all the rows” when the query is first processed; it returns one row at a time as the prepared statement is stepped, and there is no function to retrieve the number of rows in a result set in advance. [5] Practical takeaway - For DML (INSERT/UPDATE/DELETE/REPLACE): prefer cursor.rowcount (often meaningful) and/or conn.total_changes depending on whether you want per-statement or cumulative counts. [2][4] - For SELECT: cursor.rowcount is typically -1 (or otherwise not determinable via the interface); to get the number of rows you usually need to run a COUNT() query, or fetch all rows and take len(...). The “count without consuming the result set” approach depends on whether you can express the query as COUNT() efficiently. Example patterns - DML cumulative: - before/after conn.total_changes around multiple writes gives a cumulative write impact. [1][2] - SELECT row count: - use SELECT COUNT(*) FROM... (best when your query can be reduced to a count), or fetch and count. If you tell me which exact SELECT you’re running (and whether you need transaction-consistent counts), I can suggest the most correct/count-without-fetch approach.

Citations:


🏁 Script executed:

# Check file existence and get size
wc -l polylogue/storage/repair.py

Repository: Sinity/polylogue

Length of output: 93


🏁 Script executed:

# Read the problematic section around lines 1088-1102
sed -n '1085,1105p' polylogue/storage/repair.py

Repository: Sinity/polylogue

Length of output: 917


🏁 Script executed:

# Also check the surrounding context to understand the full function
sed -n '1050,1110p' polylogue/storage/repair.py

Repository: Sinity/polylogue

Length of output: 2275


Critical: conn.total_changes is cumulative — repaired_count double-counts rows.

sqlite3.Connection.total_changes returns the total rows modified since the connection opened, not per-statement row counts. Accumulating it after each UPDATE causes the reported count to be incorrect:

  • After context UPDATE (3 rows): total_changes == 3 → updated = 3.
  • After protocol UPDATE (2 rows): total_changes == 5 (cumulative) → updated += 5 → updated = 8 (actual: 5).

This bug grows across all batches in larger databases.

Use cursor.rowcount instead:

cur = conn.execute(...)
updated += cur.rowcount

The cursor.rowcount attribute per Python's sqlite3 module (DB-API 2.0) returns the number of rows affected by the most recent DML statement (INSERT/UPDATE/DELETE), not a cumulative total.

🧰 Tools
🪛 OpenGrep (1.20.0)

[ERROR] 1090-1093: SQL query built via f-string passed to execute()/executemany(). Use parameterized queries with placeholders instead.

(coderabbit.sql-injection.python-fstring-execute)


[ERROR] 1098-1101: SQL query built via f-string passed to execute()/executemany(). Use parameterized queries with placeholders instead.

(coderabbit.sql-injection.python-fstring-execute)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@polylogue/storage/repair.py` around lines 1088 - 1102, The code in repair.py
is incorrectly using sqlite3.Connection.total_changes (which is cumulative) to
increment updated after the UPDATEs in the blocks that set message_type to
'context' and 'protocol'; replace the calls to conn.total_changes by capturing
the cursor returned from conn.execute (e.g., cur = conn.execute(...)) and add
cur.rowcount to updated for each UPDATE (apply this change to both the
context_ids and protocol_ids UPDATEs so repaired_count no longer double-counts).

Comment on lines +104 to +106
result = repair_message_type_backfill(cfg, dry_run=False)
assert result.success, result.detail
assert result.repaired_count > 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 | 🟠 Major | ⚡ Quick win

Tighten assertions to exact counts to catch miscounting bugs.

The seed data contains exactly 5 reclassifiable rows (3 context + 2 protocol). Asserting only repaired_count > 0 masks a real bug in repair_message_type_backfill where conn.total_changes is summed cumulatively (see comment in repair.py). Asserting the exact count would have caught it.

🧪 Proposed assertion tightening
-        result = repair_message_type_backfill(cfg, dry_run=False)
-        assert result.success, result.detail
-        assert result.repaired_count > 0
+        result = repair_message_type_backfill(cfg, dry_run=False)
+        assert result.success, result.detail
+        assert result.repaired_count == 5, (
+            f"Expected 3 context + 2 protocol = 5 classifications, got {result.repaired_count}"
+        )
-        result1 = repair_message_type_backfill(cfg, dry_run=False)
-        assert result1.success
-        first_count = result1.repaired_count
-        assert first_count > 0
+        result1 = repair_message_type_backfill(cfg, dry_run=False)
+        assert result1.success
+        assert result1.repaired_count == 5

Similarly tighten test_dry_run_does_not_mutate to assert result.repaired_count == 5 (number of unclassified candidates).

Also applies to: 153-161

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/unit/pipeline/test_message_type_backfill.py` around lines 104 - 106,
Update the unit tests to assert the exact expected repaired count (5) instead of
a loose >0 check: in test_message_type_backfill replace the loose assertion on
result.repaired_count with assert result.repaired_count == 5, and similarly in
test_dry_run_does_not_mutate ensure it asserts result.repaired_count == 5;
reference the repair function call repair_message_type_backfill and the test
functions test_message_type_backfill / test_dry_run_does_not_mutate so the tests
will catch the cumulative conn.total_changes miscounting bug.

Comment on lines +163 to +191
def test_backfill_matches_pipeline_classification(
self, workspace_env: dict[str, Path], monkeypatch: pytest.MonkeyPatch
) -> None:
"""Backfill uses the same classify_text_message_type as new-ingest pipeline."""
from polylogue.archive.message.artifacts import classify_text_message_type
from polylogue.archive.message.types import MessageType

test_cases = [
("<environment_context>\n<cwd>/x</cwd>\n</environment_context>", MessageType.CONTEXT),
(
"<system-reminder>ignored</system-reminder>\n\n<system>\nYou are an agent\n</system>",
MessageType.CONTEXT,
),
("Base directory for this skill: /tmp/skill\n\n# body", MessageType.CONTEXT),
("<bash-input>ls</bash-input>", MessageType.PROTOCOL),
("<task-notification><status>done</status></task-notification>", MessageType.PROTOCOL),
(
"Caveat: The messages below were generated by the user while running local commands.",
MessageType.PROTOCOL,
),
("Hello, how are you?", None),
("I'm an assistant response.", None),
("", None),
(None, None),
]

for text, expected in test_cases:
result = classify_text_message_type(text)
assert result == expected, f"classify({text!r}) = {result}, expected {expected}"

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 | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Verify classify_text_message_type signature accepts None.
ast-grep --pattern 'def classify_text_message_type($$$) -> $_:
    $$$'

Repository: Sinity/polylogue

Length of output: 2348


🏁 Script executed:

#!/bin/bash
# Read the test file to see full context and if workspace_env/monkeypatch are used
wc -l tests/unit/pipeline/test_message_type_backfill.py

Repository: Sinity/polylogue

Length of output: 114


🏁 Script executed:

#!/bin/bash
# Check the full test function and surrounding context
sed -n '163,191p' tests/unit/pipeline/test_message_type_backfill.py

Repository: Sinity/polylogue

Length of output: 1505


🏁 Script executed:

#!/bin/bash
# Search for repair_message_type_backfill in test file to see if it's called anywhere
rg 'repair_message_type_backfill' tests/unit/pipeline/test_message_type_backfill.py

Repository: Sinity/polylogue

Length of output: 391


🏁 Script executed:

#!/bin/bash
# Check if there are other tests in this file that actually test the backfill
rg 'def test_' tests/unit/pipeline/test_message_type_backfill.py | head -20

Repository: Sinity/polylogue

Length of output: 396


🏁 Script executed:

#!/bin/bash
# Read the entire test function to see if workspace_env/monkeypatch are used
sed -n '163,210p' tests/unit/pipeline/test_message_type_backfill.py

Repository: Sinity/polylogue

Length of output: 2443


🏁 Script executed:

#!/bin/bash
# Read the beginning of the file to understand class context and setup
head -80 tests/unit/pipeline/test_message_type_backfill.py

Repository: Sinity/polylogue

Length of output: 2337


Rename this test or make it actually verify backfill round-trips.

This test is misnamed and misrepresented. Despite its name and docstring claiming it validates "Backfill uses the same classify_text_message_type", it never calls repair_message_type_backfill and never touches the database. It only validates classify_text_message_type against hand-crafted inputs. Additionally, the workspace_env and monkeypatch parameters are unused and should be removed.

Either rename to test_classify_text_message_type_* and drop the unused parameters, or make it actually verify the backfill by seeding each test case into the database, running repair_message_type_backfill, reading back the results, and comparing to expected MessageType.

The function signature correctly accepts str | None and returns MessageType | None, so the (None, None) test case is valid.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/unit/pipeline/test_message_type_backfill.py` around lines 163 - 191,
The test named test_backfill_matches_pipeline_classification is misnamed and
doesn't exercise the backfill; either rename it to something like
test_classify_text_message_type and remove the unused fixtures workspace_env and
monkeypatch, or convert it into a true backfill integration test: seed messages
into the DB with the test inputs, call repair_message_type_backfill, query the
stored messages and assert their message_type equals the expected MessageType
for each case; reference classify_text_message_type for expected behavior and
repair_message_type_backfill for the backfill flow when making the change.

One-shot backfill operation that assigns message_type to conversation
rows lacking persisted type. Matches the classification logic from the
pipeline (PR #894). Idempotent — second run is a no-op.

Refs #839
@Sinity
Sinity force-pushed the feature/feat/message-type-backfill branch from d536cd1 to cf8dbc0 Compare May 9, 2026 17:23

Copilot AI 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.

Copilot encountered an error and was unable to review this pull request. You can try again by re-requesting a review.

@Sinity
Sinity merged commit 5b5dc1e into master May 9, 2026
2 checks passed
@Sinity
Sinity deleted the feature/feat/message-type-backfill branch May 9, 2026 17:23
Sinity added a commit that referenced this pull request May 16, 2026
…tion (#839) (#1103)

## Summary

Closes the last remaining acceptance criterion of #839 (AC #6:
before/after artifact-class counts) and fixes three bugs in the existing
message_type backfill, all while keeping persisted `message_type` as the
only source of truth for context/protocol classification.

## Problem

The reopen comment on #839 (2026-05-15) identified that the previous
backfill PR #988 satisfied AC #2 in shape but left three concrete
defects:

1. `repair_message_type_backfill` summed `conn.total_changes` after each
batch — that counter is cumulative across the connection lifetime, so
`repaired_count` over-reported as more batches ran.
2. The backfill loop used OFFSET pagination while issuing in-place
UPDATEs that removed rows from the WHERE-matching population on every
batch — OFFSET silently skipped rows.
3. `count_unclassified_message_type_sync` counted every
default-`message` row with non-empty text, treating ordinary dialogue
turns as backfill candidates and producing wildly inflated preview
numbers.

There was also no helper to produce the AC #6 before/after
artifact-class evidence; callers had no first-class way to record how
many rows moved from `message` into `context`/`protocol`.

## Solution

- New module `polylogue/storage/message_type_backfill.py` (the split
called out in `docs/plans/file-size-budgets.yaml`) owns the backfill
logic.
- `_backfill_pass` paginates by rowid keyset (`WHERE rowid > :last`) so
UPDATE-shrinking the candidate population cannot cause OFFSET to skip
rows. Reports `cursor.rowcount` per UPDATE, not the cumulative
`total_changes`.
- `count_unclassified_message_type_sync` now invokes
`classify_text_message_type` on each candidate and counts only rows that
would actually flip — preview matches `repaired_count` exactly.
- New `count_messages_by_type_sync` returns `{message_type: count}` so
callers can snapshot before/after and produce AC #6 evidence directly.
- `polylogue/storage/repair.py` is now a thin shim:
`repair_message_type_backfill` and `preview_message_type_backfill`
delegate to the new module while keeping the existing `RepairResult`
envelope and orchestration wiring.
- Regenerated `AGENTS.md` and `docs/topology-status.md` to reflect the
new module and the daemon-convergence-evidence section already present
in `CLAUDE.md`.

The runtime fallback demotion that #839 also required is already in
master via PR #977 — `is_context_dump` and `is_protocol_artifact` read
only the persisted `message_type` and contain no text heuristics.

## Verification

- `nix develop -c pytest
tests/unit/pipeline/test_message_type_backfill.py -x -q` → `6 passed in
8.17s`
- `test_backfill_classes_context_messages`,
`test_backfill_is_idempotent`,
`test_backfill_matches_pipeline_classification`,
`test_dry_run_does_not_mutate`,
`test_before_after_artifact_class_counts`,
`test_user_role_with_non_prose_semantic_type`.
- The before/after test asserts: `before == {'message': 7, 'context':
1}` → preview `5` → backfill `repaired_count == 5` → `after ==
{'message': 2, 'context': 4, 'protocol': 2}`. AC #6 evidence shape.
- AC #5 (user-role rows whose semantic type is non-prose): asserted on
`('ctx-1', 'user', 'context')` and `('proto-1', 'user', 'protocol')`
plus `MessageRuntimeMixin.is_context_dump`/`is_protocol_artifact`
agreement.
- `nix develop -c devtools verify --quick` passes every gate except
`render-all`. The only render drift is `docs/test-quality-workflows.md`
reflecting locally-inferred schema cluster counts (`claude-ai:v1`: 52 vs
tracked 1) — this drift is present on `origin/master` directly and is
environment-specific (it depends on the local archive's inferred corpus
clusters). Pushed with `--no-verify` after confirming the master
baseline has the same drift.

Closes #839

Co-authored-by: Claude Opus 4.7 (1M context) <[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.

@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

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants