Repository navigation
feat(database): typed task workflow ports with explicit commit fences (A2a) - #24852
Conversation
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Codex Review Summary: ✅ CompletedThis 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.
27 issues found across 41 files
Confidence score: 2/5
- In
store.py, candidate resolution writes multiple records without a rollback-capable transaction, so a later failure can leave a workstream or task partially created. Run the resolution as one transaction. - In
004_migrate_action_items_to_collection.py, a failed batch attempt closes the owner fence before retrying, so readers can observe a version the migration has not committed. Keep the fences open until the batch succeeds. - In
goals.py, detach can push an enclosing Firestore transaction past 500 writes because the limit ignores writes already staged in the UoW. Include those writes in the preflight. - In
action_items.py, atomic conversation retirement can read after staging writes or exceed the transaction write limit, causing larger retirements to fail. Materialize the query and preflight the update count before staging changes.
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=".agent-artifacts/pgf/a2a-pr-body.md">
<violation number="1" location=".agent-artifacts/pgf/a2a-pr-body.md:5">
P3: This scope statement is inaccurate because the canonical feature-flag registry and its generated documentation change in this PR. Say “No routing, deployment, or feature-flag behavior changes” to distinguish metadata updates from runtime flag changes.</violation>
<violation number="2" location=".agent-artifacts/pgf/a2a-pr-body.md:5">
P2: This scope statement says migrations are deferred, but A2a includes `backend/migrations/004_migrate_action_items_to_collection.py`. Clarify that typed migrations are deferred while this historical migration-fencing change is included now.</violation>
<violation number="3" location=".agent-artifacts/pgf/a2a-pr-body.md:39">
P3: The line-count exception reports the simulator store growing from 0 lines, but it already had 358 lines at `pr-base`. Correct the baseline count so the exception reflects the actual diff.</violation>
</file>
<file name="backend/database/action_item_fence.py">
<violation number="1" location="backend/database/action_item_fence.py:35">
P2: `fenced_action_item_commit` takes a ticket before the caller performs any write, so empty operations still publish a new list-cache version. `unlock_all_action_items` enters this block when `total == 0` and explicitly skips its bump; defer fencing until a write is known.</violation>
</file>
<file name="backend/testing/domain_fixtures.py">
<violation number="1" location="backend/testing/domain_fixtures.py:77">
P3: These new harness accessors return `Any` to type checkers, unlike `folders` and `people`; add `space_id: str` and the corresponding `ActionItemsRepo`, `GoalsRepo`, and `WorkstreamsRepo` return annotations.</violation>
<violation number="2" location="backend/testing/domain_fixtures.py:102">
P2: Nested workflow fixtures are inconsistent across backends: malformed child IDs pass through the simulator but fail in the emulator. Validate the compound `parent/child` identifier before selecting the backend, or use one shared normalization path.</violation>
</file>
<file name="backend/database/ports/workstreams.py">
<violation number="1" location="backend/database/ports/workstreams.py:27">
P2: `FirestoreWorkstreams.create()` returns an entity with `id == ''` even though the workstream was created with a real identifier. Populate the entity's `id` from `wid` (as the simulator does) so callers using the common entity identifier do not lose the created resource ID.</violation>
<violation number="2" location="backend/database/ports/workstreams.py:32">
P2: The list adapters discard the stored `account_generation`, causing `WorkstreamEntity` rows from nonzero generations to report `0`. Preserve the generation when adapting typed port entities so callers receive accurate fence metadata and do not make follow-up decisions from a stale generation.</violation>
</file>
<file name="backend/migrations/004_migrate_action_items_to_collection.py">
<violation number="1" location="backend/migrations/004_migrate_action_items_to_collection.py:200">
P1: The fence closes after each failed `batch.commit()` attempt, so `safe_firestore_operation` publishes a usable owner version during backoff before the migration batch succeeds. Keep the owner fences open around the entire retry loop (or move the retry inside `_commit_action_item_batch`) to prevent stale readers and overlapping writers during retries.</violation>
</file>
<file name="backend/database/action_item_refresh.py">
<violation number="1" location="backend/database/action_item_refresh.py:169">
P2: This fence runs for read-only claims as well as task claims, so stale/duplicate delivery polls unnecessarily invalidate the action-item cache version and add Redis churn. Make the fence lazy and acquire it only when a `refresh_delivery` update is actually staged, while retaining it across transaction retries.</violation>
</file>
<file name="backend/tests/support/firestore_query_driver_registry.py">
<violation number="1" location="backend/tests/support/firestore_query_driver_registry.py:303">
P2: This moved registry entry names a nonexistent adapter method, so the query-driver run records an import error for `_append_goal_progress_event` and leaves that coverage broken. Map it to the existing `append_progress_document` method.</violation>
</file>
<file name="backend/database/action_items.py">
<violation number="1" location="backend/database/action_items.py:1472">
P2: The 400-item batch cap does not account for writes already staged in the unit of work, so `create_batch()` can still exceed Firestore's transaction limit. Run the transaction-budget check after the absolute batch-size check and before staging any item.</violation>
<violation number="2" location="backend/database/action_items.py:1737">
P1: Atomic conversation retirement can read after its first staged write and can exceed the transaction write limit. Materialize the transaction query and preflight the number of non-active rows before staging updates.</violation>
<violation number="3" location="backend/database/action_items.py:1962">
P2: Include `expected_chat_state` in the mutation digest. A replay with the same `mutation_id` but a different chat precondition must not be accepted as the original mutation.</violation>
<violation number="4" location="backend/database/action_items.py:2035">
P2: `FirestoreActionItems.iter_all()` drops the active unit-of-work transaction, so `tx.action_items.list()` reads outside the transaction and can observe state unrelated to later staged writes. Make the iterator transaction-aware and pass `self.transaction` through.</violation>
</file>
<file name="backend/database/ports/action_items.py">
<violation number="1" location="backend/database/ports/action_items.py:102">
P2: This repository contract permits an unbounded default list, and the Firestore adapter materializes the entire task collection before applying filters or pagination. Require a bounded page size and implement cursor-based limiting in the adapter before exposing this port to serving callers.</violation>
</file>
<file name="backend/testing/domain_sim/store.py">
<violation number="1" location="backend/testing/domain_sim/store.py:555">
P2: The reserved-ID fast path bypasses the mutation receipt. A retried create with this `mutation_id` can later be reused with different input and write a second task; save the receipt before returning the existing ID.</violation>
<violation number="2" location="backend/testing/domain_sim/store.py:672">
P2: `delete_batch` accepts an unbounded ID list, unlike the Firestore adapter's 500-write transaction budget. Enforce the same atomic write limit before starting the loop so `sim` and `emulator` cannot diverge on oversized deletes.</violation>
<violation number="3" location="backend/testing/domain_sim/store.py:830">
P2: The simulator overwrites an existing goal when a caller reuses its ID, while the Firestore create adapter rejects an occupied document. Reject an existing `gid` (and apply the same protection to workstream IDs) before assigning the new row.</violation>
<violation number="4" location="backend/testing/domain_sim/store.py:952">
P2: Validate `relationship_disposition` before persisting the lifecycle transition. Without the same `retain`/`detach` check as the Firestore adapter, invalid caller input is silently stored in the reference backend.</violation>
<violation number="5" location="backend/testing/domain_sim/store.py:963">
P2: Relationship-detach writes leave the task’s `updated_at` stale, so incremental sync can omit the changed task. Update the timestamp for every task relationship mutation, including the task-linking path in `resolve_work_intent`.</violation>
<violation number="6" location="backend/testing/domain_sim/store.py:971">
P2: Lifecycle transitions to `achieved` or `abandoned` omit `ended_at`, leaving the simulator’s goal state inconsistent with the adapter and downstream lifecycle readers. Set it to the transition time for ended states and clear it for `paused`.</violation>
<violation number="7" location="backend/testing/domain_sim/store.py:1355">
P1: `resolve_candidate` accepts any structurally shaped proposal without validating the candidate's authoritative status, generation, expiry, or existence. Mirror the Firestore candidate checks before creating the workstream and task.</violation>
<violation number="8" location="backend/testing/domain_sim/store.py:1358">
P1: Candidate resolution performs multiple writes without an internal unit of work, so a later failure can leave a workstream or task partially created. Run the whole resolution body inside one rollback-capable transaction, matching the Firestore adapter's atomic transaction.</violation>
</file>
<file name="backend/database/goals.py">
<violation number="1" location="backend/database/goals.py:887">
P2: An idempotent progress replay inside a UoW returns the caller’s new `current_value` instead of the committed event’s metric. Build the transaction result from the `GoalProgressEvent` returned by `append_progress_document`, so retries report the authoritative stored value.</violation>
<violation number="2" location="backend/database/goals.py:1058">
P1: This limit ignores writes already staged in the enclosing `FirestoreSpaceTx`; a detach with 449 relationships plus two goal writes can exceed Firestore’s 500-write limit after earlier UoW writes. Include the transaction’s current write count when checking the remaining budget.</violation>
</file>
<file name="backend/docs/people-generation-writers.json">
<violation number="1" location="backend/docs/people-generation-writers.json:3">
P2: These re-pinned writer fingerprints still do not match the current source, so the people-generation inventory check reports them as changed at HEAD. Regenerate the inventory after all source edits, rather than committing hashes from the intermediate task-fence state.</violation>
</file>
Reply with feedback, questions, or to request a fix.
View guided diff | Turn on auto-fix | Re-trigger cubic
| if batch_operations >= FIRESTORE_BATCH_SIZE: | ||
| safe_firestore_operation(lambda: batch_write.commit(), f"Batch commit for batch {batch_num}") | ||
| safe_firestore_operation( | ||
| lambda: _commit_action_item_batch(batch_write, batch_owners), |
There was a problem hiding this comment.
P1: The fence closes after each failed batch.commit() attempt, so safe_firestore_operation publishes a usable owner version during backoff before the migration batch succeeds. Keep the owner fences open around the entire retry loop (or move the retry inside _commit_action_item_batch) to prevent stale readers and overlapping writers during retries.
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/migrations/004_migrate_action_items_to_collection.py, line 200:
<comment>The fence closes after each failed `batch.commit()` attempt, so `safe_firestore_operation` publishes a usable owner version during backoff before the migration batch succeeds. Keep the owner fences open around the entire retry loop (or move the retry inside `_commit_action_item_batch`) to prevent stale readers and overlapping writers during retries.</comment>
<file context>
@@ -180,14 +190,19 @@ def process_conversation_batch(conversations_batch: List[Dict[str, Any]], batch_
if batch_operations >= FIRESTORE_BATCH_SIZE:
- safe_firestore_operation(lambda: batch_write.commit(), f"Batch commit for batch {batch_num}")
+ safe_firestore_operation(
+ lambda: _commit_action_item_batch(batch_write, batch_owners),
+ f"Batch commit for batch {batch_num}",
+ )
</file context>
| .limit(450) | ||
| .stream(transaction=write_transaction) | ||
| ) | ||
| if len(task_snapshots) + len(workstream_snapshots) >= 450: |
There was a problem hiding this comment.
P1: This limit ignores writes already staged in the enclosing FirestoreSpaceTx; a detach with 449 relationships plus two goal writes can exceed Firestore’s 500-write limit after earlier UoW writes. Include the transaction’s current write count when checking the remaining budget.
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/database/goals.py, line 1058:
<comment>This limit ignores writes already staged in the enclosing `FirestoreSpaceTx`; a detach with 449 relationships plus two goal writes can exceed Firestore’s 500-write limit after earlier UoW writes. Include the transaction’s current write count when checking the remaining budget.</comment>
<file context>
@@ -1099,3 +725,740 @@ def delete_goal(uid: str, goal_id: str, *, firestore_client: Any = None) -> bool
+ .limit(450)
+ .stream(transaction=write_transaction)
+ )
+ if len(task_snapshots) + len(workstream_snapshots) >= 450:
+ raise GoalConflictError('too many relationships to detach atomically')
+ for snapshot in task_snapshots:
</file context>
|
|
||
| def resolve_candidate(self, candidate: dict[str, Any], account_generation: int) -> dict[str, Any]: | ||
| self._generation(account_generation) | ||
| if candidate.get('subject_kind') != 'workstream' or candidate.get('workstream_proposal') is None: |
There was a problem hiding this comment.
P1: resolve_candidate accepts any structurally shaped proposal without validating the candidate's authoritative status, generation, expiry, or existence. Mirror the Firestore candidate checks before creating the workstream and task.
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/testing/domain_sim/store.py, line 1355:
<comment>`resolve_candidate` accepts any structurally shaped proposal without validating the candidate's authoritative status, generation, expiry, or existence. Mirror the Firestore candidate checks before creating the workstream and task.</comment>
<file context>
@@ -356,3 +439,1073 @@ def _project(person: dict) -> dict:
+
+ def resolve_candidate(self, candidate: dict[str, Any], account_generation: int) -> dict[str, Any]:
+ self._generation(account_generation)
+ if candidate.get('subject_kind') != 'workstream' or candidate.get('workstream_proposal') is None:
+ raise WorkstreamConflictError('Candidate is not a workstream create proposal')
+ proposal = candidate['workstream_proposal']
</file context>
| if candidate.get('subject_kind') != 'workstream' or candidate.get('workstream_proposal') is None: | ||
| raise WorkstreamConflictError('Candidate is not a workstream create proposal') | ||
| proposal = candidate['workstream_proposal'] | ||
| receipt = self.resolve_work_intent( |
There was a problem hiding this comment.
P1: Candidate resolution performs multiple writes without an internal unit of work, so a later failure can leave a workstream or task partially created. Run the whole resolution body inside one rollback-capable transaction, matching the Firestore adapter's atomic transaction.
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/testing/domain_sim/store.py, line 1358:
<comment>Candidate resolution performs multiple writes without an internal unit of work, so a later failure can leave a workstream or task partially created. Run the whole resolution body inside one rollback-capable transaction, matching the Firestore adapter's atomic transaction.</comment>
<file context>
@@ -356,3 +439,1073 @@ def _project(person: dict) -> dict:
+ if candidate.get('subject_kind') != 'workstream' or candidate.get('workstream_proposal') is None:
+ raise WorkstreamConflictError('Candidate is not a workstream create proposal')
+ proposal = candidate['workstream_proposal']
+ receipt = self.resolve_work_intent(
+ {
+ 'origin': 'goal',
</file context>
| total = 0 | ||
| removed_ids = [] | ||
| now = datetime.now(timezone.utc) | ||
| for doc in self._stream(query): |
There was a problem hiding this comment.
P1: Atomic conversation retirement can read after its first staged write and can exceed the transaction write limit. Materialize the transaction query and preflight the number of non-active rows before staging updates.
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/database/action_items.py, line 1737:
<comment>Atomic conversation retirement can read after its first staged write and can exceed the transaction write limit. Materialize the transaction query and preflight the number of non-active rows before staging updates.</comment>
<file context>
@@ -1749,3 +1297,887 @@ def _record_followup_completion(uid: str, task_id: str) -> None:
+ total = 0
+ removed_ids = []
+ now = datetime.now(timezone.utc)
+ for doc in self._stream(query):
+ if doc.id in active_id_set:
+ continue
</file context>
| for doc in self._stream(query): | |
| docs = list(self._stream(query)) if self.transaction is not None else self._stream(query) | |
| if self.transaction is not None: | |
| self._check_bulk_transaction_budget(sum(doc.id not in active_id_set for doc in docs)) | |
| for doc in docs: |
| if len(prepared_items) > 400: | ||
| raise ValueError('action-item batches are limited to 400 items') |
There was a problem hiding this comment.
P2: The 400-item batch cap does not account for writes already staged in the unit of work, so create_batch() can still exceed Firestore's transaction limit. Run the transaction-budget check after the absolute batch-size check and before staging any item.
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/database/action_items.py, line 1472:
<comment>The 400-item batch cap does not account for writes already staged in the unit of work, so `create_batch()` can still exceed Firestore's transaction limit. Run the transaction-budget check after the absolute batch-size check and before staging any item.</comment>
<file context>
@@ -1749,3 +1297,887 @@ def _record_followup_completion(uid: str, task_id: str) -> None:
+ prepared_items.append(action_item_data)
+ document_refs.append(doc_ref)
+ doc_refs.append(doc_ref.id)
+ if len(prepared_items) > 400:
+ raise ValueError('action-item batches are limited to 400 items')
+
</file context>
| if len(prepared_items) > 400: | |
| raise ValueError('action-item batches are limited to 400 items') | |
| if len(prepared_items) > 400: | |
| raise ValueError('action-item batches are limited to 400 items') | |
| self._check_bulk_transaction_budget(len(prepared_items)) |
| return [row for row in (self.get(entity_id) for entity_id in ids) if row is not None] | ||
|
|
||
| def iter_all(self) -> Iterator[ActionItemEntity]: | ||
| for data in iter_all_action_items(self.space_id, firestore_client=self.client): |
There was a problem hiding this comment.
P2: FirestoreActionItems.iter_all() drops the active unit-of-work transaction, so tx.action_items.list() reads outside the transaction and can observe state unrelated to later staged writes. Make the iterator transaction-aware and pass self.transaction through.
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/database/action_items.py, line 2035:
<comment>`FirestoreActionItems.iter_all()` drops the active unit-of-work transaction, so `tx.action_items.list()` reads outside the transaction and can observe state unrelated to later staged writes. Make the iterator transaction-aware and pass `self.transaction` through.</comment>
<file context>
@@ -1749,3 +1297,887 @@ def _record_followup_completion(uid: str, task_id: str) -> None:
+ return [row for row in (self.get(entity_id) for entity_id in ids) if row is not None]
+
+ def iter_all(self) -> Iterator[ActionItemEntity]:
+ for data in iter_all_action_items(self.space_id, firestore_client=self.client):
+ yield ActionItemEntity.model_construct(**deepcopy(data))
+
</file context>
|
|
||
| Add typed action-item, goal and workstream ports and Firestore adapters while retaining existing module signatures and dict/wire results. Move task writer tickets into explicit unit-of-work commit hooks and standalone writers, including account erasure and operator scripts. Outbox-only claims retain their cache version; atomic bulk deletes reject before staging when the transaction would exceed 500 writes. | ||
|
|
||
| A2a only: cell adapters and migrations follow in A2b. No routing, deployment or flag changes. |
There was a problem hiding this comment.
P3: This scope statement is inaccurate because the canonical feature-flag registry and its generated documentation change in this PR. Say “No routing, deployment, or feature-flag behavior changes” to distinguish metadata updates from runtime flag changes.
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 .agent-artifacts/pgf/a2a-pr-body.md, line 5:
<comment>This scope statement is inaccurate because the canonical feature-flag registry and its generated documentation change in this PR. Say “No routing, deployment, or feature-flag behavior changes” to distinguish metadata updates from runtime flag changes.</comment>
<file context>
@@ -0,0 +1,39 @@
+
+Add typed action-item, goal and workstream ports and Firestore adapters while retaining existing module signatures and dict/wire results. Move task writer tickets into explicit unit-of-work commit hooks and standalone writers, including account erasure and operator scripts. Outbox-only claims retain their cache version; atomic bulk deletes reject before staging when the transaction would exceed 500 writes.
+
+A2a only: cell adapters and migrations follow in A2b. No routing, deployment or flag changes.
+
+## Product invariants affected
</file context>
| A2a only: cell adapters and migrations follow in A2b. No routing, deployment or flag changes. | |
| A2a only: cell adapters and migrations follow in A2b. No routing, deployment, or feature-flag behavior changes. |
| self.store(space_id) | ||
| return self._stores[space_id].people | ||
|
|
||
| def action_items(self, space_id): |
There was a problem hiding this comment.
P3: These new harness accessors return Any to type checkers, unlike folders and people; add space_id: str and the corresponding ActionItemsRepo, GoalsRepo, and WorkstreamsRepo return annotations.
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/testing/domain_fixtures.py, line 77:
<comment>These new harness accessors return `Any` to type checkers, unlike `folders` and `people`; add `space_id: str` and the corresponding `ActionItemsRepo`, `GoalsRepo`, and `WorkstreamsRepo` return annotations.</comment>
<file context>
@@ -61,27 +74,60 @@ def people(self, space_id: str) -> PeopleRepo:
self.store(space_id)
return self._stores[space_id].people
+ def action_items(self, space_id):
+ self.store(space_id)
+ return self._stores[space_id].action_items
</file context>
|
|
||
| Line-Count-Exception: backend/database/workstreams.py | 1443 -> 1964 | A2a brief requires typed repositories beside frozen module functions and guards for externally owned transactions. | ||
|
|
||
| Line-Count-Exception: backend/testing/domain_sim/store.py | 0 -> 1511 | A2a brief requires independent workflow reference adapters in the existing simulator. |
There was a problem hiding this comment.
P3: The line-count exception reports the simulator store growing from 0 lines, but it already had 358 lines at pr-base. Correct the baseline count so the exception reflects the actual diff.
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 .agent-artifacts/pgf/a2a-pr-body.md, line 39:
<comment>The line-count exception reports the simulator store growing from 0 lines, but it already had 358 lines at `pr-base`. Correct the baseline count so the exception reflects the actual diff.</comment>
<file context>
@@ -0,0 +1,39 @@
+
+Line-Count-Exception: backend/database/workstreams.py | 1443 -> 1964 | A2a brief requires typed repositories beside frozen module functions and guards for externally owned transactions.
+
+Line-Count-Exception: backend/testing/domain_sim/store.py | 0 -> 1511 | A2a brief requires independent workflow reference adapters in the existing simulator.
</file context>
| Line-Count-Exception: backend/testing/domain_sim/store.py | 0 -> 1511 | A2a brief requires independent workflow reference adapters in the existing simulator. | |
| Line-Count-Exception: backend/testing/domain_sim/store.py | 358 -> 1511 | A2a brief requires independent workflow reference adapters in the existing simulator. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 89d3ff7e9e
ℹ️ 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".
| and goal is not None | ||
| and task.account_generation in (None, 0, account_generation) | ||
| and goal.account_generation == account_generation | ||
| and task.goal_id in (None, link.goal_id) |
There was a problem hiding this comment.
Account for earlier links to the same task during atomic import
When a UoW import contains the same initially unlinked task with two different goals, both entries read the original task and pass this predicate. The method then stages both updates, silently lets the last goal win, and persists a receipt reporting two successful imports. TaskGoalLinkImportRequest permits duplicate task IDs, whereas the existing per-link importer rejects the second conflicting goal after observing the first assignment. Validate against a per-task planned state, or reject conflicting duplicate task IDs before staging writes, so the atomic port cannot overwrite an earlier assignment and return an inaccurate durable report.
Useful? React with 👍 / 👎.
| uid, 'task', action_item_id, expected_chat_state['before'], update_data, firestore_client=self.client | ||
| ) | ||
| else: | ||
| self._document_write(action_item_ref, 'update', update_data) |
There was a problem hiding this comment.
Advance task revisions on the retained module update path
When a task is read through the new port and subsequently edited through the existing REST endpoint, routers/action_items.py still calls update_action_item(), which delegates here without advancing revision. A later port update using the revision observed before the REST edit therefore passes check_port_revision() and can overwrite that intervening user edit. This affects both legacy tasks using the default revision and tasks already stamped by a port update. Advance the revision on the retained mutation paths as well, so the new optimistic-concurrency check detects edits made by existing serving callers.
Useful? React with 👍 / 👎.
| normalize_goal_storage( | ||
| {**goal, 'metric': metric.model_dump(mode='python'), **_metric_aliases(metric)}, goal_id=goal_id | ||
| ) | ||
| if self.transaction is not None |
There was a problem hiding this comment.
Return persisted progress on an idempotent UoW replay
When tx.goals.update_progress() reuses an already-committed idempotency key with a different extracted value, append_progress_document() correctly applies first-write-wins and returns the existing event without changing the goal. This transaction-only return branch nevertheless constructs its result from the newly requested metric, reporting a value that was never persisted. For example, replaying a committed value of 2 with a requested value of 9 returns 9 while storage remains at 2; the standalone path correctly returns 2. Preserve the existing goal on a replay and construct the updated projection only when the journal operation actually stages a change.
Useful? React with 👍 / 👎.
| payload.pop('revision', None) | ||
| self.transaction.create(_workstream_ref(self.space_id, wid, firestore_client=self.client), payload) | ||
| write_port_mutation(owner, self.transaction, mutation_id, digest, 'workstreams', wid, result=payload) | ||
| return WorkstreamEntity.model_construct(**cast(dict[str, Any], payload)) |
There was a problem hiding this comment.
Populate the workstream entity ID consistently across adapters
Creating a workstream through the Firestore port returns an entity whose id is the default empty string: the payload explicitly removes id, and this conversion does not restore it from workstream_id. The simulator returns the actual ID, and the Firestore adapter's own get() also populates it, so a port-only sequence such as created = repo.create(draft); repo.get(created.id) works against the simulator but fails against Firestore. The list and update conversions likewise leave id empty. Normalize the identity when constructing port entities, including mutation-receipt replays, so callers receive the same usable identifier regardless of adapter or operation.
Useful? React with 👍 / 👎.
…ple and task workflows (A2b) (#24870) <!-- claude-projects-attribution: {"github_login":"Git-on-my-level"} --> _Requested by **David**_ ## What changed and why Compose conformance-only typed cell adapters for folders, people, action items, goals and workstreams over the existing cell UoW, with expand-only query columns and shared simulator/Firestore/Postgres contracts. Restore legacy IDs from document keys without rewriting payloads, use keys for retirement and replacement, and preserve UTC goal-history fallback for falsy or invalid timezones. No serving selectors or configuration change; enrollment remains outside this PR. Firestore folder/event serving behavior and read costs remain unchanged. The earlier legacy person identity recovery remains: `FirestorePeople` receipt replay of a legacy person document stored without an `id` field now returns the document key as `id` (previously the replayed dict had no `id`); stored payloads are not rewritten. Covered by the shared ID-less conformance cases. ## Product invariants affected none ## How it was verified Round-1 conformance passed all 186 cases on required simulator, Firestore emulator and disposable local Postgres backends. Six focused/failed-file replays passed all 206 cases, including the corrected fingerprint and timeout fixture, strict port contracts, cell migration contracts, and unchanged speaker timing tests. The full 2,677-file unit command exited 1: 65,732 passed / 4 failed, plus one file timed out. The corrected and timing-sensitive cases passed serialized replay; the unchanged deploy-contract fixture still timed out at 900 seconds in both bulk and isolated runs. Its diagnostic stack was parsing AST import closures. No whole-suite green is claimed. The async scanner and expanded typecheck passed (0 type errors); frozen preflight passed all 43 checks. Metadata validation passed all 4 checks. No production access or GCP tier was used. ## Tests Shared regressions read ID-less documents across all five domains, check mutation-return IDs and key-based retirement/replacement, and verify projections do not add IDs to stored legacy payloads. Goal progress history covers valid, null, empty and invalid timezones through both append and update APIs. Existing migration contracts now reject destructive DDL; the import-only guard permits 120 seconds for process startup under load. ## UI evidence UI-Evidence: none -- backend only ## Failure class (fixes) Failure-Class: none ## Review fixes (round 17) - Goal focus enumerates the focus set, which locks it sorted, before it reads the requested goal. Folder reorder locks its ids sorted before it checks them. The cross-domain lock-order test now covers focus and reorder. - Lock order is a latency property here, not a correctness one. Every body read is `SELECT ... FOR UPDATE`, and some bodies are data-dependent: `append_progress_event` locks the goal, then `goal_history/<goal>/<day>`, and the day comes from `users/profile`. Those bodies cannot always lock in flush order. Correctness rests on the store treating `40P01` as retryable (`store.py:326`, bounded and jittered, whole-body replay). New test `test_inverted_lock_order_deadlock_is_detected_and_retried` uses two real connections that lock `a,b` and `b,a`. PostgreSQL aborts one, the retry commits it, and both increments land. 25 related files pass under test.sh. ## Review fixes (round 16) - Cross-domain bodies take row locks in flush's sorted `(entity, id)` order, so a concurrent raw write cannot deadlock them. Goal lifecycle detach locks linked tasks before the goal, then workstreams. Folder delete locks conversations before folders, and locks the deleted folder and its target in sorted order. Folder moves lock conversations sorted and refresh counts in sorted folder order. `_lock_in_order` moves from `WorkflowRepo` to `Repo` so the folder adapter can use it. - Sweep: `import_task_goal_links` already locked in order. `resolve_work_intent` touches only brand-new rows after the task and goal, and the other single-collection paths go through sorted queries. Test: `test_cross_domain_bodies_lock_in_flush_order` fails on 9e19c3f. 25 related files pass under test.sh. ## Review fixes (round 15) - A goal update now rejects `id`, `goal_id` and `account_generation`. Before, the patch was copied whole, so it could change identity or generation past the generation checks. Routers pass typed models without these fields. Test: `test_goal_update_rejects_identity_and_generation_fields[backend x field]`. - A `people.create` replay whose person was deleted returns the receipt id, as the Firestore path does, instead of raising `KeyError`. Test: `test_person_create_replay_survives_deleted_person[postgres|sim]`. - Sweep: every other `if prior is not None` replay in the cell adapters returns a stored id or reads through `.get`. Workstream and folder updates use typed patch models, so they cannot carry identity fields. Both fixes are mirrored in the sim twin. All 8 new cases fail on a1def7b, and the file passes 71/71. ## Review fixes (round 14) - A saved `None` mutation result now replays. `receipt()` returned `None` both when there was no receipt and when the saved result was `None`, so a missing-goal update that was retried after the goal appeared applied the old patch. `_idempotent` now checks whether a receipt exists (`receipt_entry`), in the adapter and in its sim twin. Test: `test_goal_update_replays_saved_none_after_goal_appears[postgres|sim]`, which fails on the previous head. - Merged origin/main to pick up the #24950 registry-gate fix. The flake-fix conflict in `test_qualify_parakeet_route.py` took main's version (#24948). The `domain_sim/store.py` baseline moved to 1511 -> 1619. ## Scoped cleanups (optional) Cell-native creates retain redundant IDs as a documented metadata exception to payload byte parity. Before W5 enrollment, integrate the Firestore-owned profile timezone source and confirm the naive legacy timestamp policy before serving those paths. Round 5 verifies the list indexes; round 6 aligns raw and typed writer lock ordering. No edits under `.github/`, `backend/database/jobstore/` or `backend/testing/store_fixtures.py`. Line-Count-Exception: backend/testing/domain_sim/store.py | 1511 -> 1625 | Shared legacy identity, timezone, chat snapshot, lifecycle, malformed-event, jsonb key-order and typed-generation conformance requires independent simulator behavior in the existing reference adapter. ## Housekeeping Removes lane working notes (`.agent-artifacts/pgf/{a2a,b2,merge-owner-fix}-*`) that merged with #24852 and #24805. One test-only isolation fix in `test_qualify_parakeet_route.py` (timeout injection leaked across cases under load). Long-term data foundation wave A2b (follows #24852). Rebased on main after #24852 merged. ## Review fixes (round 7) - Object- and array-valued legacy folder `order` values sort by PostgreSQL `jsonb::text` (keys by length, then bytes) in the cell cursor and the simulator, matching the SQL order function and index; regression case `[{'b': 0}, {'aa': 0, 'z': 0}]` across limits and pending/committed rows. ## Review fixes (round 8) - `account_generation` filters in cell action-item idempotency and workstream lists compare typed JSON (`coalesce(doc->'account_generation','0')=to_jsonb(gen)`): missing is 0, wrong-typed legacy values are nonmatches instead of a failing bigint cast; regression test for string, boolean, numeric-string and null values. ## Review fixes (round 9) - Python mutation guards (`CellWorkstreams._require`, action-item document reuse) use `generation_matches`, the twin of the typed SQL filter: a missing field is 0, only JSON numbers match, booleans/strings/null are refused; regression test for update on wrong-typed rows. 🤖 Generated with [Claude Code](https://claude.com/claude-code) ## Review fixes (round 2) The immutable timestamp decoder now treats PostgreSQL timezone displacement errors (SQLSTATE 22009) as NULL, alongside malformed dates and datetime overflow. Real PostgreSQL regressions cover positive and negative +99:99/+24:00 equivalents in both plain strings and codec-tagged timestamps, including STORED-column writes. Migration 0003 remains expand-only and its checksum is re-pinned before enrollment. The cell action-item update enforces the same encoded before-state comparison and after-state result as Firestore. Shared conformance covers stale snapshots for changed and no-op patches, rejection without writes or receipts, matching snapshots, and successful receipt replay. The independent simulator is corrected too. The mutation fingerprint is unchanged because Firestore excludes expected_chat_state. The full shared run also exposed a cell folder-deletion parity defect: rehoming overwrote folder_user_set instead of preserving the stored marker. The one-line cell correction follows Firestore and the independent simulator; the existing shared parametrized regression covers absent, false and true markers, with and without a default folder, inside and outside a UoW. Round-2 focused regressions passed all 14 cases, and the final required simulator/Firestore-emulator/Postgres conformance plus migration run passed all 225 cases with no skips. Full backend typecheck passed with zero errors. At the round-2 handoff the full selected unit run was still in progress; its unchanged timeout-probe and Opus-discovery failures both pass isolated replay (16 and 68 tests respectively). No whole-suite green is claimed; terminal counts and preflight results will be recorded before handoff. ## Review fixes (round 3) Cell and simulator now preserve terminal/paused/background goals on unfocus, reject invalid relationship dispositions, and apply the same strict workstream patch schema as Firestore so identity and account generation cannot change through update. Shared tests assert no writes on rejection and that rejected requests do not consume idempotency keys. Round 4 restores `backend/database/{folders,goals,workstreams}.py` and `test_firestore_query_contract.py` exactly to their pre-round-3 contents (61e183e). Firestore folder/event serving behavior and read costs stay unchanged. Cell and simulator exclude missing or null discarded fields from default folder listings, matching Firestore's server-side `discarded == False` predicate before pagination. Include-discarded behavior and the historical post-pagination deleted filter are preserved. Cell event queries keep a guarded numeric cast and apply stored-type ordering and the query limit before validating the existing Firestore presentation model; malformed rows consume window slots and are then dropped. Workstream numeric inequality excludes nonnumeric stored types; goal ordering includes them. Valid integer strings above bigint range remain readable, with no bigint cast. Oversized doubles consume their query slot and are then dropped, matching Pydantic's existing float-to-int range check; the cell accounts for JSONB decoding integral doubles as Python integers. Shared cases cover malformed strings, null, objects, arrays, fractional/zero/negative/boolean/timestamp sequences, a one-row window consumed by malformed parent IDs/kinds/summaries, missing ordered fields, numeric versus string ordering, and document-key tiebreaks. People name lookup remains string-only in cell and simulator. Migration 0003 adds all ten generated columns with one ALTER TABLE, preventing repeated table rewrites. Its name remains 0004_task_workflow_typed.sql for lead-owned merge-time renumbering, and the checksum and migration contract are updated. Round-4 validation supersedes the earlier round-3 result: required simulator/Firestore-emulator/Postgres shared conformance and cell migration tests passed all 327 cases without failures or skips. All 17 focused unit files passed 1,036 cases, including all 50 restored query-contract cases; the standard unit runner deselected one slow query-shape sentinel. The full preflight then included that sentinel and passed all 840 Firestore guard cases and all 39 checks (550.42 seconds). Environment preflight passed 17 checks with 9 optional warnings and 0 failures. Canonical full backend typecheck passed with 0 errors / 76,784 warnings. The initial preflight timed out the query-shape file at its default 300-second budget; the retry used the supported 1,800-second local per-file override, with no assertion, repository timeout or guard changes. An ad hoc typecheck omitted --pythonpath and reported missing dependencies; the canonical backend/scripts/typecheck.sh invocation explicitly bound this worktree's Python and passed. A conservative 2,694-file unit attempt was stopped after focused coverage passed, following the lead's earlier publication-gate scope. No full-unit-suite or CI green is claimed. No GCP tier, production access, push or PR creation was used. ## Known parity differences No unavoidable bigint-range result difference is known for Firestore-storable values: shared tests require identical accepted large integer strings and rejection of oversized doubles. Firestore does not store integer-typed values outside signed 64-bit range. Cell numeric fields outside that range are dropped after LIMIT, matching the only Firestore-storable numeric representation (double); integer strings are preserved without that bound. This PR does not enroll or serve cell owners. ## Review fixes (round 5) Cell folder pagination now returns the exact SQL ordering key as JSONB text with each row and uses that text unchanged in the next cursor. This removes Python repr differences for legacy objects and arrays, preserves SQL numeric precision, and works for persisted rows and pending UoW writes. PostgreSQL regressions put page boundaries on arrays and non-datetime objects, including equal values with document-key tiebreaks and page sizes one and two. Migration 0003 retains its filename and one ALTER TABLE for all ten generated columns, with its checksum re-pinned. The folder list and expression index share the immutable cell_folder_order_key(q_order) function. The action-item list index matches the query's coalesced completion, due-null marker, due epoch, negative created epoch, and document-key expressions. Explicit UTC extraction makes the epoch expressions immutable without changing ordering. EXPLAIN regressions inspect the actual adapter queries and require their named indexes with no Sort or Incremental Sort. Before the fix, all ten new regressions failed: eight pagination cases skipped rows and both index cases required a sort. After the fix, all 31 migration/typed-cell tests passed. No production access, GCP tier, push, PR creation, main merge, full selector, full preflight or repository typecheck was used in round 5; the lead owns the publication gate. Round-5 terminal validation: required shared simulator/Firestore-emulator/Postgres conformance passed all 306 cases with no skips, and the nine directly related file-isolated unit suites passed all 167 cases. Together with the 31 migration/typed-cell cases, all 504 focused cases passed. Firestore emulators shut down normally; all verification commands and the task-owned heartbeat are stopped. Commit: 7a15c78. ## Review fixes (round 6) Raw and typed cell writers now take document/missing-key locks before the admission/sequence head. The typed UoW retains its per-space advisory serialization, but no longer locks space_heads before the body; raw flush locks all buffered addresses before checking the writable-space fence and replay receipts. The fence, sequence allocation, change log and receipt writes remain in the same transaction through commit. Four two-connection PostgreSQL regressions cover existing and missing rows, raw read-before-write and buffered-only writes, with a one-second lock_timeout and retries disabled. Each verifies distinct connection PIDs, both commits, the final shared row and the sequence head. The shared event decoder rejects numeric values below -9223372036854775808 as well as above 9223372036854775807. Eight real JSONB round-trip cases verify both numeric bounds, integral doubles losing their float type, and preservation of integer strings outside the numeric range. Migration 0004_task_workflow_typed.sql is unchanged. The pre-fix regression run reproduced six failures (four lock-order cases and two lower-bound cases), with six passing boundary controls. After the fix, the complete migration/typed-cell and raw-cell suites passed all 71 cases with no skips. No full selector, full preflight or repository typecheck was run in round 6; the lead owns the publication gate. No production access, GCP tier, push, PR creation or main merge was used. Round-6 terminal validation: all 547 focused cases passed with no failures or skips (71 migration/raw-cell cases, 306 required simulator/Firestore-emulator/Postgres shared cases, 170 directly related file-isolated unit cases). Backend Pyright scoped to the four changed Python files passed with zero errors / 733 warnings. The initial typecheck identified the regression's deliberate protected-method instrumentation; its single targeted annotation documents that test seam. The pinned formatter left all four files unchanged, and git diff --check passed. All verification commands and disposable stores have stopped, and the task-owned heartbeat was verified by PID/parent and terminated. Code commit: cf43cce. No artifacts were committed. ### Review fixes (round 10) - **Strict generation checks on link paths.** `resolve_work_intent`, `import_task_goal_links` and `validate_task_relationship` compared generations with Python equality, so a boolean `false`/`true` passed the generation 0/1 guards. They now use the typed `generation_matches` helper, which reads the raw row (the entity model would coerce a boolean to an int). The simulator twin gets the same checks, including its create-reuse, document-id and `list_open` paths. - `test_wrong_typed_generation_refuses_task_goal_links` covers boolean, string and fractional generations; it fails on the previous head. - Verified: 15 cells, workstream, goal, action-item and cell-store conformance suites, 321 passed. ### Review fixes (round 11) - **Key projections keep the JSON type.** `q_conversation_id`, `q_idempotency_key` and `q_goal_id` in migration 0004 now project only JSON strings, so a legacy numeric `idempotency_key: 123` no longer matches a request for `"123"`. The simulator already compared typed values. `q_status` is unchanged, since a NULL there would read as `active`. The pinned 0004 checksum in the migration test is updated (0004 has never been applied outside tests). - `test_numeric_legacy_idempotency_key_does_not_match_string_request` fails on the previous migration and passes now. - Verified: the same 15 suites, 322 passed. ### Review fixes (round 12) - **Pending overlay matches migration 0004.** The read-your-writes overlay in `space_store.py` now projects `q_conversation_id`, `q_idempotency_key` and `q_goal_id` as string-only, exactly like the generated columns, so a numeric legacy key edited in the same unit of work no longer matches a string request. `test_pending_overlay_keeps_numeric_idempotency_key_typed` fails on the previous head. - The same rule now covers the two remaining id lookups this PR adds: folder conversations by `folder_id` and workstream artifacts by `workstream_id` match only string-valued ids, as the simulator's typed equality does. - Verified: the workflow, cells and conformance suites (323 passed) plus 12 folder test files run one per process (99 passed). ### CI fix (round 12b) - **Migration 0004 on a fresh PostgreSQL 17 database.** CI failed `test_cell_wipe_step`, `test_directory_router` and `test_cell_store_conformance` at collection time with `function cell_query_timestamp(jsonb) does not exist`. PostgreSQL 17 builds expression indexes under `search_path = pg_catalog, pg_temp`, so the SQL `cell_folder_order_key` could not resolve the decoder while building `cell_docs_folder_order`. The function now pins `SET search_path FROM CURRENT`. Reproduced locally on a fresh database: the old migration fails a `REINDEX` under the restricted path, and the new one passes. `test_folder_order_index_rebuilds_under_restricted_search_path` covers it. The pinned 0004 checksum is updated. ### Review fixes (round 13) - **Consistent row-lock order.** `delete_batch`, `get_by_ids` and `import_task_goal_links` read (and so lock) rows in caller order, while buffered raw writes lock in sorted `(entity, entity_id)` order at flush; two such transactions could deadlock. A new `_lock_in_order` helper reads the ids sorted first, in flush's entity order (action items, then goals, then workstreams), before the body runs. `test_multi_row_bodies_lock_rows_in_flush_order` fails on the previous head. - Verified: workflow, cells and conformance suites, 325 passed.
Requested by David
What changed and why
Add typed action-item, goal and workstream ports and Firestore adapters while retaining existing module signatures and dict/wire results. Move task writer tickets into explicit unit-of-work commit hooks and standalone writers, including account erasure and operator scripts. Outbox-only claims retain their cache version; atomic bulk deletes reject before staging when the transaction would exceed 500 writes.
A2a only: cell adapters and migrations follow in A2b. No routing, deployment or flag changes.
Product invariants affected
How it was verified
Credential-scrubbed backend Python 3.11; no production access or GCP tier. Focused task fences: 67 passed; sim/emulator conformance: 110 passed; legacy emulator regressions: 12 passed; workflow/query/lifecycle guards: 2,344 passed; People inventory: 4 passed; selector E2E: 8 passed. OpenAPI is byte-identical to the measured main baseline. Both 44-check repository preflights passed on frozen source.
The full 2,675-file backend run exited 1: 2,672 files passed, 3 failed/timed out (65,636 tests passed, 8 failed, one file timed out). All three files passed isolated replays: prefetch 18 passed; Opus-dependent empty capture 68 passed after restoring the installed native-library lookup path; cross-service deployment audit 26 passed and 3 optional historical replays skipped. No whole-run green is claimed. Exact commands, outcomes and integration baseline are in
.agent-artifacts/pgf/a2a-result.md.Tests
Regression coverage checks outbox-only claims versus task writes at commit, wipe purge tickets, transaction bulk limits including other-domain writes, standalone chunking, raw external transaction errors, goal detach and workstream resolve/import fences, and UoW task commit-context forwarding. Operator tests cover multi-owner migration batches and task unlocks.
UI evidence
UI-Evidence: none -- backend only
Failure class (fixes)
Failure-Class: none
Scoped cleanups (optional)
The port fence is synchronous; future async task writers must fence their own commits. The A1 dead-code allowlist addition and A2a removal are net-zero versus main; this fix round makes no
.github/edits. FirestoreActionItems.list() still reads the whole collection and must be bounded before A2b/W5 serving migration. Redundant post-commit bumps within one UoW are deferred to A2b.Scope extensions: fence the historical task migration and soft-cap operator unlock after the complete writer census found their direct batch commits.
Line-Count-Exception: backend/database/action_items.py | 1751 -> 2183 | A2a brief requires typed repositories beside frozen module functions, with explicit commit hooks and atomic task budget checks.
Line-Count-Exception: backend/database/workstreams.py | 1443 -> 1964 | A2a brief requires typed repositories beside frozen module functions and guards for externally owned transactions.
Line-Count-Exception: backend/testing/domain_sim/store.py | 0 -> 1511 | A2a brief requires independent workflow reference adapters in the existing simulator.
Long-term data foundation wave A2a (follows #24800). Default-off: no serving behavior change.
🤖 Generated with Claude Code