feat: implement phase 2 causal event graph - #2
Conversation
- add PostgreSQL snapshots table and graph indexes - implement explicit cross-agent causal parent assignment - add PostgreSQL-backed ancestors(event_id) traversal - add real three-agent Phase 2 integration coverage - validate planner and worker branches against the fixture - update CI, setup, contribution, and Neon verification docs
🤖 CodeAnt AI — Review Status
|
Thanks for using CodeAnt! 🎉We're free for open-source projects. if you're enjoying it, help us grow by sharing. Share on X · |
| ) -> Event: | ||
| """Append an event whose explicit parents were used by the caller.""" | ||
| parent_ids = list(causal_parents) | ||
| logical_seq = assign_causal_parents(agent_id, clock, parent_ids, log) |
There was a problem hiding this comment.
Suggestion: Sequence allocation occurs before log.append(event). With PostgresEventStore, allocation commits the agent's lamport_offset in a separate transaction, so a failed append permanently consumes a sequence, and retrying an idempotent event allocates another sequence even though the append returns the previously stored event. This leaves durable Lamport state ahead of persisted events and creates unnecessary gaps; allocation and idempotent append need to share one transaction or the existing idempotent event must be checked before allocation. [logic error]
Severity Level: Major ⚠️
- ⚠️ Durable Lamport offsets can exceed persisted event sequences.
- ⚠️ Failed writes and idempotent retries create unnecessary sequence gaps.
- ⚠️ Sequence-based event inspection sees unexplained missing positions.Prompt for AI Agent 🤖
This is a comment left during a code review.
**Path:** core/graph.py
**Line:** 47:47
**Comment:**
*Logic Error: Sequence allocation occurs before `log.append(event)`. With `PostgresEventStore`, allocation commits the agent's `lamport_offset` in a separate transaction, so a failed append permanently consumes a sequence, and retrying an idempotent event allocates another sequence even though the append returns the previously stored event. This leaves durable Lamport state ahead of persisted events and creates unnecessary gaps; allocation and idempotent append need to share one transaction or the existing idempotent event must be checked before allocation.
Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix| SELECT e.id, e.causal_parent_ids | ||
| FROM events e | ||
| JOIN ancestors a ON e.id = ANY(a.causal_parent_ids) |
There was a problem hiding this comment.
Suggestion: The recursive traversal follows every referenced UUID globally and does not constrain the joined event to the target event's run_id. Because record_causal_event only verifies that each parent exists, an event in one run can reference an event from another run, causing ancestors() to merge unrelated run histories. Validate parent run ownership before insertion and/or carry the root run ID through the recursive query. [api mismatch]
Severity Level: Major ⚠️
- ❌ Run-specific causal graphs include unrelated history.
- ⚠️ Phase 2 planner and worker provenance can be misattributed.
- ⚠️ Ancestor-based debugging returns cross-run events.Prompt for AI Agent 🤖
This is a comment left during a code review.
**Path:** storage/postgres.py
**Line:** 218:220
**Comment:**
*Api Mismatch: The recursive traversal follows every referenced UUID globally and does not constrain the joined event to the target event's `run_id`. Because `record_causal_event` only verifies that each parent exists, an event in one run can reference an event from another run, causing `ancestors()` to merge unrelated run histories. Validate parent run ownership before insertion and/or carry the root run ID through the recursive query.
Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix|
@CodeAnt-AI does my new push fix those changes? |
|
Question: does my new push fix those changes? Answer: Remaining issue: rollback can invalidate the fetched rowIn row = cursor.fetchone()
if row is None and event.idempotency_key is not None:
cursor.execute(...)
row = cursor.fetchone()
if row is not None:
self.connection.rollback()
if row is not None:
self.connection.commit()After return self._row_to_event(row)Depending on the psycopg behavior and transaction state, this is fragile and also unnecessarily commits after a rollback. More importantly, the rollback may undo unrelated work in the same transaction, including the sequence allocation—which is intentional for this operation—but it can also discard other caller changes if the store is used inside a larger transaction. A safer approach is to distinguish the conflict case and return immediately after rollback: if row is None and event.idempotency_key is not None:
cursor.execute(...)
row = cursor.fetchone()
if row is not None:
self.connection.rollback()
return self._row_to_event(row)Then commit only for a newly inserted event: self.connection.commit()
return self._row_to_event(row)Alternatively, use a savepoint around the insert/idempotency lookup so a retry does not roll back the caller’s entire transaction. Also worth fixingThe new owned_parent_ids != set(parent_ids)This validates that every parent exists in the same run, but it does not reject duplicate causal parent IDs. If duplicate edges are invalid by contract, validate that explicitly: if len(parent_ids) != len(set(parent_ids)):
raise ValueError("causal parent IDs must be unique")ConclusionThe push appears to address the graph traversal, explicit cross-agent parents, shared ancestor deduplication, schema/indexes, and integration coverage. However, I would not consider it fully fixed until the idempotent PostgreSQL retry transaction handling is changed, preferably using an immediate return after rollback or a savepoint. |
Thanks for using CodeAnt! 🎉We're free for open-source projects. if you're enjoying it, help us grow by sharing. Share on X · |
|
@CodeAnt-AI what do you think now? |
|
Question: what do you think now? Answer: I do see one important idempotency edge case:
|
User description
CodeAnt-AI Description
Add cross-agent causal graph tracking and reliable event retries
What Changed
Impact
✅ Traceable planner-to-worker merges✅ Complete deduplicated ancestry queries✅ Safe idempotent event retries💡 Usage Guide
Checking Your Pull Request
Every time you make a pull request, our system automatically looks through it. We check for security issues, mistakes in how you're setting up your infrastructure, and common code problems. We do this to make sure your changes are solid and won't cause any trouble later.
Talking to CodeAnt AI
Got a question or need a hand with something in your pull request? You can easily get in touch with CodeAnt AI right here. Just type the following in a comment on your pull request, and replace "Your question here" with whatever you want to ask:
This lets you have a chat with CodeAnt AI about your pull request, making it easier to understand and improve your code.
Example
Preserve Org Learnings with CodeAnt
You can record team preferences so CodeAnt AI applies them in future reviews. Reply directly to the specific CodeAnt AI suggestion (in the same thread) and replace "Your feedback here" with your input:
This helps CodeAnt AI learn and adapt to your team's coding style and standards.
Example
Retrigger review
Ask CodeAnt AI to review the PR again, by typing:
Check Your Repository Health
To analyze the health of your code repository, visit our dashboard at https://app.codeant.ai. This tool helps you identify potential issues and areas for improvement in your codebase, ensuring your repository maintains high standards of code health.