Repository navigation
test(backend): harden lifecycle source guards - #24600
Conversation
Preserve existing changed-file coverage and explicitly include scheduler regressions. Inventory lifecycle payload values, aliases, sibling keys and duplicates across database/utils. Probe deadline stamps independently for each persisted entry and reject late, conditional, null or cleared stamps. Correct stale plan gaps against main 1ee787b: proof repair exits, successful terminal alert semantics and finalization completed stock. Add the pure synthetic ordering contracts requested by ruling f1e35a. This is the local WP-B B1 fix delta. Publication is held by ruling c09a2a while the owner of the folded PR #24591 resolves the shared branch.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
1 issue found across 6 files
Confidence score: 5/5
- In
backend/tests/unit/test_lifecycle_invariants.py, selecting the rule by position ties the tests to table ordering and could make them inspect the wrong rule if that order changes. Select it byname, like theORDERING_COUNTEREXAMPLESlookup.
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/tests/unit/test_lifecycle_invariants.py">
<violation number="1" location="backend/tests/unit/test_lifecycle_invariants.py:568">
P3: Select the rule by `name` instead of by position. Index access ties these tests to the table's ordering, unlike the name-keyed `ORDERING_COUNTEREXAMPLES` lookup.</violation>
</file>
Reply with feedback, questions, or to request a fix.
View guided diff | Turn on auto-fix | Re-trigger cubic
| @pytest.mark.parametrize('results,rearm', [(1, False), (0, True), (1, True)]) | ||
| def test_finalization_ordering_accepts_committed_results_or_durable_rearm(results, rearm): | ||
| row = {'record_lane_owner': 'batch_live_v1', 'finalization_status': 'completed'} | ||
| assert ordering_holds(ORDERING_RULES[0], row, batch_result_count=results, rearm_on_result_commit=rearm) |
There was a problem hiding this comment.
P3: Select the rule by name instead of by position. Index access ties these tests to the table's ordering, unlike the name-keyed ORDERING_COUNTEREXAMPLES lookup.
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/tests/unit/test_lifecycle_invariants.py, line 568:
<comment>Select the rule by `name` instead of by position. Index access ties these tests to the table's ordering, unlike the name-keyed `ORDERING_COUNTEREXAMPLES` lookup.</comment>
<file context>
@@ -0,0 +1,595 @@
[email protected]('results,rearm', [(1, False), (0, True), (1, True)])
+def test_finalization_ordering_accepts_committed_results_or_durable_rearm(results, rearm):
+ row = {'record_lane_owner': 'batch_live_v1', 'finalization_status': 'completed'}
+ assert ordering_holds(ORDERING_RULES[0], row, batch_result_count=results, rearm_on_result_commit=rearm)
+
+
</file context>
| assert ordering_holds(ORDERING_RULES[0], row, batch_result_count=results, rearm_on_result_commit=rearm) | |
| rule = next(rule for rule in ORDERING_RULES if rule.name == 'finalization_after_batch_result_or_durable_rearm') | |
| assert ordering_holds(rule, row, batch_result_count=results, rearm_on_result_commit=rearm) |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: e67059b353
ℹ️ 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".
| 'backend/utils/batch_pipeline/', | ||
| 'backend/database/record_audio.py', | ||
| 'backend/database/record_partial.py', | ||
| 'backend/database/conversation_finalization_jobs.py', |
There was a problem hiding this comment.
Select lifecycle guards for finalization service changes
When a PR changes only backend/services/conversation_finalization.py, the selector currently returns 25 tests but neither lifecycle guard. This module supplies reconcile_listen_finalization_jobs, the automatic exit cited by several rows in the new state table and checked by test_lifecycle_invariants.py. Because its existing selection contract prevents full-suite fallback, changes to that declared exit skip the new invariant checks in changed-file CI. Add this service to the lifecycle source mapping and cover it in the selector regression test.
AGENTS.md reference: backend/AGENTS.md:L222-L222
Useful? React with 👍 / 👎.
| def nonempty_fields(pairs, site): | ||
| return { | ||
| field for key, item in pairs for field in literal_key(key, constants) if resolved(item, site) is not None | ||
| } |
There was a problem hiding this comment.
Reject nullable conditional expressions as deadline proof
When a deadline expression has an unresolved conditional with a None branch, resolved() returns UNKNOWN, which this check incorrectly accepts as a non-null stamp. I verified that changing the scheduler's deadline expression to lease_until=now + LEASE_SECONDS if shared_gpu_id else None leaves payload_sites() unchanged and still makes entry_deadline_sites() return [(595, True)], despite omitting the deadline whenever shared_gpu_id is absent. Thus both new guards accept this deadline regression. Inspect the possible conditional branches and reject a stamp when any reachable branch is null rather than treating UNKNOWN as proof.
Useful? React with 👍 / 👎.
| 'result_ready', | ||
| 'vendor_held', |
There was a problem hiding this comment.
Include provider-STT job states in the lifecycle matrix
Provider-routed batch jobs persist three additional states that this matrix omits: provider_stt_admission.enqueue_in_transaction writes provider_pending to jobs, and utils/batch_pipeline/provider_stt.py writes provider_running and terminal provider_superseded to the same job store. Consequently, none of those states receives the four lifecycle clause checks. The batch vocabulary test also misses this omission because it scans only scheduler, live, retry-policy and record-partial modules. Add the provider states to the reviewed table and include their writer modules in the vocabulary completeness check so the provider-STT path is not exempt from the lifecycle contract.
Useful? React with 👍 / 👎.
Use the recent-cohort metric queried by the merged BYOK dwell page. Expand actual PhaseMetrics instances from source-declared Gauge suffixes, and reject invented prefixes and suffixes without weakening assertions. Scoped B1 integration authorized by rulings 6cac95 and cf1a59.
Reject cleared or mutated alias deadline evidence and independently census persisted entries for every deadline-bearing machine. Check positional setdefault state values and literal aliases. Preserve the bounded span patch through a pinned returned-key proof with portable AST fingerprints. The 12 review reproductions and the extra source-alias case failed before the fixes. Valid stamped-entry, rebuilt-payload, null-debt exit and contract mutation controls prevent blanket rejection or unverified exemptions. Refresh the source snapshot at main 563e6c2. Remove two stale record_pending metric/page xfails supplied by #24595; #24587 admission leases still do not stamp an overall pending-dwell deadline. Local backend/test.sh: 926 passed, 68 strict xfails. Unmasked audit: exactly 68 AssertionErrors, no unexpected or CPU guard failures. Main integration is separate (bd6cdcb); compatibility commit372ccb1a61e0 is the inspected cherry-pick of peer6201ba0. Lead acceptance under0d2137 and exact-head green CI are required before merge. No third review.
The merged lifecycle table still binds the BYOK dwell page to the legacy all-age gauge. #24595 correctly changed that page to the recent-cohort gauge so importing it does not page on known backlog. Their combination leaves main's lifecycle invariant checks red. This test-only correction points the table at `omi_finalization_byok_new_oldest_age_seconds`. The AST inventory now derives gauge names from literal `PhaseMetrics` instances and the real factory's `Gauge` suffixes. A negative test rejects a prefix not instantiated as PhaseMetrics and a suffix absent from the factory. Every existing assertion and strict expected-failure declaration stays in place. Only two B1 test/support files change. No runtime code, alert threshold, workflow, production access or deployment changes. Coordinated with B1 owner lcinv for #24600. uicleanup requested this standalone priority fix in ruling4d1372 and explicitly waived Luna review for this test-only delta; lead2 owns merge on green. Validation: in a fresh worktree based on current main `563e6c240944`, canonical `backend/test.sh` with the explicit two-file list passed 429 tests with 79 inherited strict expected failures at head `eaa1316e1624`. The same patch also passed 430 tests in the PR2 tree (one additional source-inventory case there). Guarded push passed full preflight and its selected backend unit gate (143 passed,79 inherited strict expected failures). All local checks/push used `omi-heavy run -- nice -n 19` with the five GCP credential/project variables unset. Current-head CI is pending. No runtime validation is claimed. Initiative: capture/transcription/speakers Failure-Class: none <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/BasedHardware/omi/pull/24605?utm_source=github" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img alt="View guided diff" src="https://www.cubic.dev/buttons/review-in-cubic-light.svg"></picture></a> <a href="https://www.cubic.dev/action/auto-fix/pr/BasedHardware/omi/24605?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F24605&source=description" target="_blank" rel="noopener noreferrer" data-no-image-dialog="true"><picture><source media="(prefers-color-scheme: dark)" srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"><img alt="Turn on auto-fix" src="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"></picture></a> <!-- End of auto-generated description by cubic. -->
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 41ddd85b33
ℹ️ 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".
| def visit_Assign(self, node): | ||
| for target in node.targets: | ||
| if isinstance(target, ast.Subscript): | ||
| self.add(target.slice, node.value, literal_key(target.slice, constants)) |
There was a problem hiding this comment.
Preserve detection of augmented subscript writes
Replacing the previous visit_Subscript store-context scanner with visit_Assign drops augmented assignments from the writer inventory. For example, row['record_upload_sessions'] |= {'new-producer': True} registered a lifecycle writer before this change, but now payload_sites() returns an empty list. Consequently, a new producer-token writer using this valid dictionary-merge form passes test_no_undeclared_or_stale_lifecycle_field_builder without being declared. Handle AugAssign targets as well and add a regression test so the hardened inventory retains the previous scanner's coverage.
Useful? React with 👍 / 👎.
| if isinstance(parent, (ast.Assign, ast.AnnAssign)): | ||
| targets = parent.targets if isinstance(parent, ast.Assign) else [parent.target] | ||
| mapping = targets[0].id if len(targets) == 1 and isinstance(targets[0], ast.Name) else None | ||
| elif isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute): |
There was a problem hiding this comment.
Include dict constructors in the deadline entry census
When a persisted entry uses dict(state='leased') instead of a dictionary literal, this probe never creates a candidate: constructor calls have an ast.Name callee, which this branch excludes. I verified that adding undeclared_entry to the scheduler with tx.update(ref, dict(state='leased')), then refreshing its payload inventory, leaves the batch:leased entry-deadline clause passing despite the new undeclared, unstamped entry. The payload scanner already recognizes this constructor, so the independent entry census must recognize it too rather than silently exempting it from the declaration and deadline checks.
Useful? React with 👍 / 👎.
Preserve the reviewed B1 model while registering the upstream delayed budget requeue and terminalization payload sites. Declare the new queued entry so the independent deadline census verifies its bounded deadline. Validation: six-file canonical backend unit gate, 926 passed / 68 strict xfails. No authored product code or workflow changes.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ad1aadcb7d
ℹ️ 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".
| elif node.func.attr == 'setdefault' and len(node.args) >= 2: | ||
| pairs = [(node.args[0], node.args[1])] | ||
| mapping = node.func.value.id if isinstance(node.func.value, ast.Name) else None |
There was a problem hiding this comment.
Treat setdefault as a conditional deadline write
When a payload already contains a null deadline, setdefault leaves it unchanged, but this branch treats its default argument as an unconditional stamp. For example, initializing job = {'state': 'leased', 'lease_until': None}, calling job.setdefault('lease_until', now + 10), and persisting job makes entry_deadline_sites() report a stamped entry despite storing None. I also verified that replacing the scheduler's deadline assignment with setdefault leaves its entry-deadline clause passing after refreshing the inventory, even though admitted jobs already have lease_until=0.0. Only count this as deadline evidence when the key is proven absent; otherwise preserve the existing value or conservatively reject the proof.
Useful? React with 👍 / 👎.
| if isinstance(node, ast.Dict): | ||
| pairs = list(zip(node.keys, node.values)) |
There was a problem hiding this comment.
Account for dictionary unpacking that overwrites a deadline
When a dictionary contains a deadline followed by an unpacked patch, the unpack has a None AST key and is ignored instead of invalidating the earlier stamp. Consequently, {'state': 'leased', 'lease_until': now + 10, **{'lease_until': None}} is accepted as stamped although its final deadline is null. I verified that using this payload in the scheduler and refreshing its writer inventory still passes the batch:leased entry-deadline clause. Resolve unpacked mappings in overwrite order, or conservatively invalidate deadline evidence when an unverified unpack can overwrite it.
Useful? React with 👍 / 👎.
| while node in parents: | ||
| parent = parents[node] | ||
| if isinstance(parent, ast.If): | ||
| result.append((parent, node in parent.body)) |
There was a problem hiding this comment.
Reject deadline proofs from loops that may not execute
When a deadline mutation is inside a loop but the entry payload is outside it, guards() records no additional condition because it recognizes only ast.If, so guaranteed() incorrectly treats the mutation as unconditional. For example, an unstamped leased payload followed by for attempt in attempts: containing the deadline assignment is reported as stamped even when attempts is empty. I verified that moving the scheduler's lease stamp into a zero-iteration loop and refreshing the inventory still passes the full batch:leased entry-deadline clause. Treat entry into a different loop body as unproven unless execution of that body is established.
Useful? React with 👍 / 👎.
The CI merge tree included #24544 after the preceding local gate. Its Home projection changes a status expression to an aliased processing/failed value. The stale inventory fails exactly that module before refresh. Preserve the source guard and update the one reviewed snapshot value. Validation: canonical six-file backend unit gate passes with 926 passes and 68 strict xfails; the stale-snapshot reproduction has one failure.
#24600 converted the declared field builders to a site inventory; the fold's writer moves (recover_deferred_processing_failure_txn and the dead-letter title helpers into conversation_terminal_title, the home-read member visibility override, and the chat-first fixture capture module) are declared there now.
What changed and why
Harden the lifecycle guards so an inventory refresh cannot hide a new unstamped entry or an unmodeled state. Clearing a job and rebuilding it from an alias now invalidates old deadline evidence; mutated aliases and opaque patches cannot restore it. A separate census compares persisted entries with the declarations for every deadline-bearing machine. Positional setdefault values and literal aliases enter the state-vocabulary check.
Valid stamped rebuilds, declared entries and debt-clearing exits remain accepted. The existing span-only patch has a checked four-field return contract with portable AST fingerprints; source changes, overlapping keys and shadowed names fail the proof. This remains bounded source analysis, not whole-program execution or runtime liveness acceptance.
Preserve the existing changed-file test coverage and select scheduler regressions. Recognize actual PhaseMetrics instances using Gauge suffixes declared by the real factory. Use the fresh-cohort BYOK gauge queried by its page. The source audit at main563e6c240944 also removes the two stale record_pending metric/page xfails supplied by #24595; #24587's admission lease still leaves an overall pending-dwell deadline gap.
The table has 54 rows and 66 remaining clause-specific gaps, plus 2 pure synthetic ordering counterexamples (68 strict xfails). Expected failures allow AssertionError only. The report tracks each remaining dependency; simulator-backed transition/shadow/property rows remain B2 after merged WP-A and rollout-owner go.
Product invariants affected
none
How it was verified
From the product checkout, use the durable file list in the workspace evidence record:
TASK_WORKSPACE_ROOTis the verified omi-workspace checkout. Dated evidence:data/run-2026-11-04-lifecycle-invariants/README.md. The six-file gate was rerun after integrating main throughc8304ee6e8cd; its two new finalization writers and bounded queued entry are registered. A later main integration adds #24544's reviewed Home status projection to the inventory. Before that one-value snapshot refresh, the local writer suite reproduced exactly one failure forhome_read.py; afterward the unchanged six-file gate passes again.With five cloud credential/project variables unset and one worker, backend/test.sh passed 926 tests with 68 strict xfails across the two lifecycle files and four existing selector/ratchet controls. The 23 targeted regression/control cases passed. The unmasked invariant run produced exactly 68 AssertionErrors and 201 passes; the exact case set matches 66 KNOWN_GAPS + 2 ordering cases, with no unexpected or CPU guard failures. Timing and slot limits were unchanged.
Before the fixes, 12 review reproductions failed (3 setdefault cases, clear+alias, 8 deadline-bearing states). An additional mutated source-alias case also failed. Canonical patch-proof fingerprints match under Python 3.11.15 and 3.14.6.
These are source/unit checks without network or GCP. Exact-head fullCI and rollout-owner acceptance are required before merge.
Tests
Payload writer/value/key/alias/duplicate inventory; state vocabulary; all-class entry census; deadline mutation lifetime; verified patch boundary; positive entry/rebuild/exit controls; selector coverage preservation; source-defined metrics; clause-specific strict xfails; pure synthetic ordering controls.
UI evidence
UI-Evidence: none -- test infrastructure only
Failure class (fixes)
Failure-Class: none
New guards
Lifecycle source changes cannot silently add the covered payload forms, persisted entries or literal state values without revisiting the declared contract. Source-derived metrics stay tied to their committed alert expressions.
Tracking
Owner: lcinv. ANX card:lcinv-lifecycle-invariants under capture/transcription. No product/.github/firmware/account-data changes and no deploy needed.