Skip to content

test(lifecycle): ratchet terminal-status writers to the owner module - #24726

Merged
Git-on-my-level merged 4 commits into
mainfrom
lane/lcphase3
Nov 5, 2026
Merged

Git-on-my-level merged 4 commits into
mainfrom
lane/lcphase3

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Nov 5, 2026 •

Copy link
Copy Markdown
Member

Adds a strict AST inventory of terminal conversation statuses (completed, failed) and terminal finalization-job statuses (completed, dead_letter). TERMINAL-WRITER-OWNER rejects new (file, function) sites and stale exceptions. The intended owners are utils/conversations/lifecycle.py plus database/conversations.py:claim_conversation_status, and database/conversation_finalization_jobs.py for jobs.

Test-only phase 3, approved by lead2 decision 923dd2. No runtime, .github, GCP, merge, or deploy changes. The existing lifecycle writer test is selected for every backend Python change. The scanner runs offline, excludes test trees, follows local aliases/payload mutation and patch builders, and inventories dynamic CAS/full-conversation persistence conservatively. It is a static tripwire, not proof of runtime lifecycle behavior or arbitrary whole-program dataflow.

Baseline: freshly fetched origin/main at 148bf4c1c57073dba4ec9a750415f2c72f5adb87; the November 5 sweep was verified against current source. Builders and storage callbacks are separate sites. The finalization inventory includes conversation-merge jobs because they use the same conversation_finalization_jobs collection. record_partial.py reopens the audio barrier but does not write a terminal conversation status, so it adds no terminal exception.

Allowlist: conversation 37, finalization 13. Includes conservative opaque whole-document/dynamic-key candidates whose status cannot be resolved locally.

Unclassified current sites (no reason guessed):

  • conversation: database/conversation_finalization_jobs.py:_apply_snapshot_bound_projection
  • conversation: database/conversation_recorded_time.py:create_if_absent.create
  • conversation: database/conversations.py:release_share_email_recipients
  • conversation: database/review_transcript_changes.py:record_change.build.write
  • conversation: database/review_transcript_changes.py:set_undone.build.write
  • conversation: database/screen_frames.py:bump_conversation_screen_frames_revision
  • conversation: database/screen_frames.py:mark_conversation_screen_frames_adjudicated
  • conversation: database/stuck_backfill.py:_restore_txn
  • conversation: utils/sync/assignment.py:assign_in_transaction
  • conversation: database/conversation_finalization_jobs.py:_complete_server_batch_capture_txn
  • conversation: database/conversation_merge_jobs.py:finish_recovery.commit
  • conversation: database/conversation_terminal_title.py:recover_deferred_processing_failure_txn
  • conversation: database/conversations.py:persist_processing_result_with_lifecycle._persist
  • conversation: database/conversations.py:transition_conversation_status
  • conversation: database/conversations.py:upsert_conversation_with_lifecycle._write_processing_result
  • conversation: database/stuck_backfill.py:_close_txn
  • conversation: utils/conversations/late_meeting_notes.py:refresh_notes_after_evidence
  • conversation: utils/conversations/process_conversation.py:_store_budget_waiting
  • conversation: utils/conversations/process_conversation.py:process_conversation
  • conversation: scripts/staging/replay.py:StagingFirestoreSeeder.seed_capture
  • conversation: utils/dream_canary.py:seed
  • conversation: utils/imports/limitless.py:process_limitless_import
  • conversation: utils/imports/transcript_files.py:build_imported_conversation
  • conversation: utils/sync/late_audio.py:ingest_late_transcript
  • conversation: utils/sync/minimal_redrive.py:_title_new_conversation
  • finalization: database/conversation_merge_jobs.py:begin_recovery.commit
  • finalization: database/conversation_merge_jobs.py:finish.commit
  • finalization: database/conversation_merge_jobs.py:finish_recovery.commit

Why isn't this a shared primitive instead? Runtime convergence is phase 2 of the one-writer redesign and is outside this approved test-only scope. This extends the existing lifecycle AST/state-table gate while that migration proceeds; it does not add a competing mutation API. Concrete precedent: merged #24602 includes the oversized terminal escape now inventoried outside the lifecycle owner; the ratchet requires that kind of additional terminal writer to be reviewed explicitly rather than silently growing the writer set. The existing module allowlist in check_conversation_lifecycle_writes.py does not constrain new terminal functions inside already allowed modules.

Product invariants affected

none

Validation

  • Canonical backend/test.sh via omi-heavy, writer/invariant/selector file list, cloud credential/project vars unset: 1,896 passed, 71 strict xfailed, normal CPU timing guard enabled.
  • 203 alias/string regression cases exercise update/set/merge/claim payloads, imported class aliases, qualified modules, indexed enum members, .value, non-terminal statuses, and reads/comparisons. Discovery is exercised through synthetic source files, without a conversation collection literal.
  • Full scan: 2.645 s wall / 2.620 s CPU, with the same 37 conversation candidates / 13 finalization-job sites. No allowlist relaxation, serving imports, network, or Firestore.
  • make preflight: 36 checks passed in 83.58 s.
  • Full scripts/pr-preflight --pr-body-file: 36 checks passed in 88.93 s.
  • Original normal push passed after parameterizing source modules to fit the unchanged one-second per-test CPU guard; no timing exception, bypass, cap override, or slow marker was added. Alias-fix push through the normal hook passed in 116.95 s, without bypasses, cap overrides, or a Firestore timeout.
  • Grok reviewed the original scanner and per-module scheduling change, finding no remaining blockers. Luna r1 identified an enum-alias false negative; this follow-up fixes it inline with the regression cases above. The candidate prefilter now selects status-write syntax without depending on terminal enum spelling, and the AST resolves imported/qualified ConversationStatus members.

Head: 1b82c1d62089c2df2d8b5ee4b3d3e261c6b3a040. CI status is tracked in the PR checks; no merge or deploy is authorized by this lane.

View guided diff Turn on auto-fix

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 5, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-05T19:39:02.138110Z 1b82c1d New commits
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@cubic-dev-ai cubic-dev-ai 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.

1 issue found across 4 files

Confidence score: 5/5

  • select_backend_unit_tests.py hardcodes the writer-inventory test path a second time, so a rename could leave the references out of sync. Move the path into a named constant and use it here.
Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="backend/scripts/select_backend_unit_tests.py">

<violation number="1" location="backend/scripts/select_backend_unit_tests.py:694">
P3: This hardcodes the writer-inventory test path in a second place. Move it into a named constant (for example `LIFECYCLE_WRITER_INVENTORY_TESTS`) and reference that constant here, so a rename cannot silently drop this gate.</violation>
</file>

Reply with feedback, questions, or to request a fix.

View guided diff | Turn on auto-fix | Re-trigger cubic

# module. Keep the source fallback unchanged while always running its guard.
if any(path.startswith(('backend/database/', 'backend/utils/')) and path.endswith('.py') for path in changed_paths):
selected.update(test for test in LIFECYCLE_INVARIANT_TESTS if test in all_tests)
if any(path.startswith('backend/') and path.endswith('.py') for path in changed_paths):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3: This hardcodes the writer-inventory test path in a second place. Move it into a named constant (for example LIFECYCLE_WRITER_INVENTORY_TESTS) and reference that constant here, so a rename cannot silently drop this gate.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/scripts/select_backend_unit_tests.py, line 694:

<comment>This hardcodes the writer-inventory test path in a second place. Move it into a named constant (for example `LIFECYCLE_WRITER_INVENTORY_TESTS`) and reference that constant here, so a rename cannot silently drop this gate.</comment>

<file context>
@@ -691,6 +691,8 @@ def tests_for_changed_paths(changed_paths: list[str], all_tests: list[str]) -> t
     # module. Keep the source fallback unchanged while always running its guard.
     if any(path.startswith(('backend/database/', 'backend/utils/')) and path.endswith('.py') for path in changed_paths):
         selected.update(test for test in LIFECYCLE_INVARIANT_TESTS if test in all_tests)
+    if any(path.startswith('backend/') and path.endswith('.py') for path in changed_paths):
+        selected.update(test for test in ('tests/unit/test_lifecycle_state_table_writers.py',) if test in all_tests)
     for path in changed_paths:
</file context>

@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: 8a7ff29d7b

ℹ️ 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 on lines +379 to +383
if not conversation_storage and not re.search(
r'''(?:['"](?:completed|failed|dead_letter)['"]|ConversationStatus\.(?:completed|failed)|claim_conversation_status|conversation_data)''',
source,
):
continue

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve dynamic-status writers in the source prefilter

For a new module containing def finish(conversation_ref, target_status): conversation_ref.update({'status': target_status}), terminal_writer_sites correctly inventories an opaque conversation-status writer, but this prefilter excludes the module because it contains no terminal-status literal, claim call, or conversation_data. I reproduced that direct analysis finds the writer while scan_terminal_writers returns empty sets. Since the parametrized CI test uses this same prefilter, such a writer can persist a terminal status outside the owner without triggering the ratchet. Include potentially dynamic conversation-status writes in candidate discovery.

Useful? React with 👍 / 👎.

),
)
def test_terminal_status_writers_match_strict_owner_allowlist(module):
from tests.support.terminal_writer_inventory import assert_terminal_writers, terminal_writer_sites

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Move the new test imports to module scope

The new tests repeatedly import inventory helpers inside test functions, contrary to backend/AGENTS.md, which explicitly requires all imports at module top level and prohibits function-local imports. Move these helper imports, including the selector import in the later test, into the existing module-level import block.

AGENTS.md reference: backend/AGENTS.md:L166-L168

Useful? React with 👍 / 👎.

@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: 1b82c1d620

ℹ️ 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 on lines +112 to +114
item.func.attr in {'update', 'setdefault'}
and len(item.args) <= 1
and isinstance(item.func.value, ast.Name)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Follow two-argument setdefault mutations into persisted payloads

When a writer builds a patch with patch = {}; patch.setdefault('status', 'completed'); conversation_ref.update(patch), the inventory returns no conversation writer. The argument-count restriction excludes the two-argument setdefault call from the patch's bindings, so the existing pairs() handling never sees it when expanding the storage payload. This lets a new terminal-status writer pass the strict allowlist check. Apply the one-argument limit only to update, and retain two-argument setdefault mutations.

Useful? React with 👍 / 👎.

Comment on lines +348 to +351
if len(node.args) >= 2:
target, payload = node.args[:2]
elif len(node.args) == 1 and isinstance(node.func, ast.Attribute):
target, payload = node.func.value, node.args[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.

P2 Badge Distinguish positional document options from transaction targets

For a document write such as conversation_ref.set({'status': 'completed'}, True), where the second positional argument is Firestore's merge option, this branch treats the payload dictionary as the document target and True as the payload. Consequently, machine_for() returns None and the inventory reports no writer, allowing this terminal write outside the owner to pass CI. Distinguish document-reference calls from transaction/batch calls rather than assuming every call with two positional arguments has the latter signature.

Useful? React with 👍 / 👎.

Comment on lines +95 to +97
# Include enclosing bindings for nested transaction callbacks.
if root is not tree:
result.update({name: list(values) for name, values in bindings(root).items()})

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Remove shadowed parameter names from inherited bindings

When a function parameter shadows an enclosing nonterminal-status binding, the scanner incorrectly resolves the parameter to that outer value. For example, with module-level status = 'processing', def finish(conversation_ref, status): conversation_ref.update({'status': status}) produces an empty inventory, and the full scan passes the strict ratchet even though callers can supply 'completed' or 'failed'. Inherited bindings must exclude names bound by the current function's parameters so this write remains opaque and is conservatively inventoried.

Useful? React with 👍 / 👎.

@Git-on-my-level
Git-on-my-level merged commit ee4691b into main Nov 5, 2026
66 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/lcphase3 branch November 5, 2026 20:37
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.

1 participant