Repository navigation
fix(agent): save draft version on agent update - #16691
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (2)
📝 WalkthroughWalkthroughAdds nickname lookup, transactional canvas version save/replace and cleanup logic, wires ChangesCanvas Version Save/Replace
Estimated code review effort: 4 (Complex) | ~60 minutes Possibly related PRs
Suggested labels: Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/dao/user_canvas_version.go`:
- Around line 151-160: The SaveOrReplaceLatest flow in the UserCanvasVersion
transaction still has a read-then-write race because the latest lookup can be
observed concurrently by multiple writers. Fix this by serializing the
latest-row read in the SaveOrReplaceLatest path, preferably by adding a locking
read on the tx.Where(...).Order(...).First(&latest) lookup in
user_canvas_version.go, or by enforcing the same invariant at the database level
so concurrent requests for the same UserCanvasID cannot both insert a new draft.
Keep the logic around sameDSL/latest unchanged, but ensure the “latest” fetch
cannot race with another transaction.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 47ed5632-ab84-4078-9043-b9457047b223
📒 Files selected for processing (5)
internal/dao/user.gointernal/dao/user_canvas_version.gointernal/dao/user_canvas_version_test.gointernal/service/agent.gointernal/service/agent_test.go
wangq8
left a comment
There was a problem hiding this comment.
Review Summary
This PR adds version-saving on agent updates — when UpdateAgent receives a DSL, it now saves/replaces a draft version row, preserving released snapshots and cleaning up old unpublished drafts. The approach is sound and the tests cover the key scenarios. A few things to address:
🔴 Missing Release field on UserCanvasVersion entity
The internal/entity/canvas.go entity UserCanvasVersion (line 59) does not define a Release field, yet the DAO code writes to release as a column in user_canvas_version:
SaveOrReplaceLatestcallsUpdate("release", opts.Release)getReleaseByIDTxselects the backtick-quotedreleasecolumndeleteAllUnpublishedExcessTxfilters by the backtick-quotedreleasecolumn
Without the entity field, GORM AutoMigrate will not create this column, and the test has to work around it with a raw ALTER TABLE. Either:
- Add a
Release boolfield (with gorm tagcolumn:release;not null;default:false;index) toUserCanvasVersion, or - If the column already exists via a separate migration, document it clearly.
🟡 Redundant DSL normalization
In UpdateAgent, the DSL is already normalized before being stored in updates["dsl"]:
updates["dsl"] = entity.JSONMap(dslpkg.NormalizeForCanvas(entity.JSONMap(dslMap)))Then saveOrReplaceVersion normalizes it again:
normalizedDSL := entity.JSONMap(dslpkg.NormalizeForCanvas(dsl))And then again in the SameDSL callback on line ~625. The result is 3x normalization of the input DSL + 1x for the latest. While NormalizeForCanvas is presumably idempotent, this is unnecessary work on every UpdateAgent call. Consider normalizing once and passing the result through.
🟡 Minor: release column is a SQL reserved word
The backtick quoting is applied in getReleaseByIDTx and deleteAllUnpublishedExcessTx, but Update("release", opts.Release) relies on GORM's internal quoting. On most MySQL configs this works fine, but adding the entity field (which addresses the red issue above) allows GORM to handle quoting uniformly.
✅ What looks good
- Transaction safety: The parent canvas row is locked (
SELECT ... FOR UPDATE) before any version logic, preventing races. - Cleanup inside the transaction:
deleteAllUnpublishedExcessTxruns in the same txn, so partial failures don't leave garbage. - Tests cover both paths: draft replacement (same DSL -> update in place) and released-version preservation (latest is released -> new draft row created).
- Type assertion guard: The
dsltype assertion at ~line 473 returns a proper error instead of panicking. - Good
SetMaxOpenConns(1)in test: Avoids SQLitedatabase is lockederrors during the transaction. - No regression on existing behavior: The version saving is gated on
updates["dsl"]being present, so settings-only patches skip it.
Summary
| Severity | Count | Items |
|---|---|---|
| 🔴 Must fix | 1 | Missing Release field on UserCanvasVersion entity |
| 🟡 Should fix | 2 | Redundant normalization, inconsistent reserved-word quoting |
The logic and test quality are solid. Once the entity definition is updated, this LGTM.
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
internal/dao/user_canvas_version.go (1)
165-181: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick winUpdate
titlewhen replacing an existing version.The create path stores
opts.Title, but the replacement path only refreshes DSL/release/description. Same-DSL draft updates can leave stale version titles after nickname/title changes.Proposed fix
updates := map[string]interface{}{ "dsl": opts.DSL, "release": opts.Release, } + if opts.Title != nil { + updates["title"] = opts.Title + } if opts.Description != nil { updates["description"] = opts.Description } @@ latest.DSL = opts.DSL latest.Release = opts.Release + if opts.Title != nil { + latest.Title = opts.Title + } if opts.Description != nil { latest.Description = opts.Description }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/dao/user_canvas_version.go` around lines 165 - 181, The replacement update path in user canvas version handling is not refreshing the version title, so it can remain stale when an existing draft is replaced. In the logic that builds the updates map and applies it through tx.Model(&entity.UserCanvasVersion{}).Updates, include opts.Title alongside DSL, release, and description, and also mirror that change onto the latest.UserCanvasVersion object so the in-memory record stays consistent.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Outside diff comments:
In `@internal/dao/user_canvas_version.go`:
- Around line 165-181: The replacement update path in user canvas version
handling is not refreshing the version title, so it can remain stale when an
existing draft is replaced. In the logic that builds the updates map and applies
it through tx.Model(&entity.UserCanvasVersion{}).Updates, include opts.Title
alongside DSL, release, and description, and also mirror that change onto the
latest.UserCanvasVersion object so the in-memory record stays consistent.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: c5bf9af6-aea8-41c8-8980-9d74da9d8ca7
📒 Files selected for processing (4)
internal/dao/user_canvas_version.gointernal/entity/canvas.gointernal/service/agent.gointernal/service/agent_test.go
💤 Files with no reviewable changes (1)
- internal/service/agent_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
- internal/service/agent.go
@wangq8 Fixed, could u review my code again? ? |
wangq8
left a comment
There was a problem hiding this comment.
Re-review: fix(agent): save draft version on agent update (#16691)
Good PR overall — the logic is sound, test quality is solid, and the two prior review findings that mattered most (entity Release field + redundant normalization) have already been addressed in commit 8c8f35e. A couple things still need attention.
🔴 Stale version title in replacement path (still open)
In SaveOrReplaceLatest, when the same-DSL replacement path is taken:
updates := map[string]interface{}{
"dsl": opts.DSL,
"release": opts.Release,
}title is not included. The caller builds a fresh buildVersionTitle(nickname, title, time.Now()) every time and passes it as opts.Title, but this fresh title is silently ignored during an in-place update. The consequence: the version title timestamp stays frozen at the first save time, even if the user clicks "save" again hours later.
Fix: add title to the updates map (mirroring the existing description handling), and update the in-memory latest.Title accordingly.
🟡 Backtick quoting in deleteAllUnpublishedExcessTx
.Where("user_canvas_id = ? AND (release = ? OR release IS NULL)", canvasID, false)With the Release bool entity field now properly defined (gorm tag: not null;default:false), the raw backtick quoting is fragile — it works in MySQL but is non-portable, and since Release is NOT NULL DEFAULT false, the IS NULL clause is dead code. This can be simplified to:
.Where("user_canvas_id = ? AND release = ?", canvasID, false)GORM will handle dialect-appropriate quoting automatically.
🟡 Missing user seed in TestUpdateAgentDSLDoesNotOverwriteLatestReleasedVersion
The test creates a UserCanvas with UserID: "user-1" but does not seed a corresponding User row. saveOrReplaceVersion calls GetNicknameByID("user-1") — gets a not-found error — falls back to "user-1" as the nickname. The resulting version title becomes user-1_Released Agent_... instead of a proper nickname. Minor, and the test still validates the correct behavior, but inconsistent with TestUpdateAgentDSLCreatesAndReplacesDraftVersion which does seed a user.
✅ What still looks good
- Transaction safety: Parent canvas row locked with FOR UPDATE, all version/cleanup ops inside one transaction.
- Race mitigation: The FOR UPDATE lock on the canvas row serializes per-canvas access, making the version read-then-write safe in practice.
- Cleanup in same txn: Partial failures roll back version rows too.
- Settings-only patches skip versioning: Gated on
updates["dsl"]— correct. - Tests cover both paths: Draft replacement + released-preservation.
- Type assertion guard: Proper error return instead of panic.
- Default 20 unpublished versions: Sensible cap.
Summary
| Severity | Count | Items |
|---|---|---|
| 🔴 Fix | 1 | Stale version title on replacement |
| 🟡 Improve | 2 | Backtick quoting, missing user seed in 2nd test |
Once the title-update fix lands, LGTM.
@wangq8, Fixed, could u review again plz ? |
wangq8
left a comment
There was a problem hiding this comment.
Review: fix(agent): save draft version on agent update (#16691)
Author: Hz-186 | Base: main | +332 / -14 | 6 files
What the PR Does
When UpdateAgent receives updated DSL, it now automatically saves/replaces a draft user_canvas_version row. If the latest matching version is already released, a new draft row is created to preserve the released snapshot. Old unpublished drafts exceeding the cap (20) are cleaned up.
Previous Reviews Status ✅
All issues from wangq8's two review rounds have been resolved in the current diff:
| Issue | Round | Status |
|---|---|---|
Missing Release field on entity |
R1 | ✅ Added to UserCanvasVersion |
| Redundant DSL normalization | R1 | ✅ Normalized once in UpdateAgent |
Backtick quoting on release |
R1 | ✅ Replaced with GORM map syntax |
| Stale version title on replacement | R2 | ✅ title added to updates map |
| Missing user seed in 2nd test | R2 | ✅ User row seeded |
| Backtick quoting in cleanup query | R2 | ✅ Using map[string]interface{} |
✅ What Looks Good
- Transaction safety: Parent canvas row locked with
FOR UPDATE, serializing per-canvas access - Atomic cleanup:
deleteAllUnpublishedExcessTxruns in the same txn as save/replace - Comment accuracy:
ResetAgentdocstring updated to reflect new behavior - Settings-only patches unaffected: Version save gated on
updates["dsl"]being present - Type safety: Proper error return instead of panic on type assertion
- Test coverage: Two solid tests covering draft-in-place replacement and released-version preservation
- CI all green: preflight, tests (infinity + ES), CodeRabbit all pass
🟡 Minor Suggestion (future consideration)
The canvas update (UpdateFields) and version save are two separate DB operations. If the version save fails after the canvas update succeeds, the canvas has new DSL but no version row. Wrapping both in a single transaction would be ideal but is scope creep for this PR.
Summary
Well-structured PR. All prior review feedback has been addressed, tests are meaningful, and CI is green. I have no blocking findings.
Verdict: LGTM 🟢
What
user_canvas_versionwhenUpdateAgentreceives updated DSL.Testing
bash build.sh --test ./internal/service ./internal/dao