Skip to content

Refactor: separate the UNVERSIONED write path from the CAS branch in JdbcAgentStateStore - #3273

Merged
xzxiaoshan merged 3 commits into
agentscope-ai:mainfrom
aiyili:refactor/jdbc-write-path
Sep 26, 2026
Merged

xzxiaoshan merged 3 commits into
agentscope-ai:mainfrom
aiyili:refactor/jdbc-write-path

Conversation

@aiyili

@aiyili aiyili commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Orthogonal refactor of the JDBC single-state write path, extracted from the work on #3216 / #3244 so the migration PR stays focused.

  • Lift the UNVERSIONED case out of the CAS transaction in saveIfVersion - the unconditional write path no longer mixes with CAS logic. The write+version-read still happens in a single transaction (version captured before the write lock is released); an inline comment now documents that invariant.
  • Rename executeUpsert -> upsertSingleState and call it from both save() and the UNVERSIONED branch, so the unconditional single-state write keeps a single definition.
  • Add javadoc on save() noting that subclasses intercepting writes should override both save and saveIfVersion.

No behavioral change to any public API. All existing tests pass.

@oss-maintainer oss-maintainer left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔍 Automated Code Review — PR #3273

Review generation encountered an error. Manual review recommended.


🤖 Generated by github-manager | 2026-09-24T05:32:03Z

@aiyili
aiyili force-pushed the refactor/jdbc-write-path branch 3 times, most recently from 75cbc85 to 1055e72 Compare September 24, 2026 06:40

@oss-maintainer oss-maintainer left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Summary

Inlines executeUpsert into the two write paths and splits readVersion into a connection-bound variant plus a new standalone variant in JdbcAgentStateStore. The core semantics do hold up: both upsert paths issue the same dialect.sessionStateUpsert SQL with the same binding, the UNVERSIONED branch still reads the version on the transaction-bound connection (line 282), so optimistic-locking behaviour is preserved — my earlier automated review on 41e01e44 failed to generate and never actually covered this code, so consider this the real first review.

I am not approving yet for three reasons below: the new 3-arg readVersion overload is unreachable dead code, removing the helper duplicated a 9-line JDBC block, and the javadoc that carried the "why not delegate to save()" rationale was deleted rather than moved. All three are small, so a quick revision should get this to approved.

Findings

  • [Warning] JdbcAgentStateStore.java:232 — new private readVersion(userId, sessionId, key) has no callers, and it reads the version on its own connection outside the write transaction.
  • [Warning] JdbcAgentStateStore.java:135 — the upsert block is now duplicated verbatim with the UNVERSIONED branch at line 276; the removed executeUpsert was the single place dialect/SQL changes had to be applied.
  • [Info] JdbcAgentStateStore.java:276 — the deleted javadoc documented why saveIfVersion must not delegate to save() (capture the version before the write lock is released); that reasoning is now implicit exactly where it matters.

Suggestions

Keep the helper, or extract the shared block:

private void upsertIn(Connection conn, String slotId, String key, String json) throws SQLException {
    BoundSql boundSql = dialect.sessionStateUpsert(slotId, key, SINGLE_STATE_INDEX, json);
    try (PreparedStatement stmt = conn.prepareStatement(boundSql.sql())) {
        bindParams(stmt, boundSql.params());
        stmt.executeUpdate();
    }
}

which restores one write path, keeps the UNVERSIONED and save() branches structurally identical, and lets you delete the unused 3-arg readVersion overload without touching the transaction-bound one.


Automated review by github-manager-bot

}

private long readVersion(Connection conn, String slotId, String key) throws SQLException {
private long readVersion(String userId, String sessionId, String key) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[Warning] This new private readVersion(userId, sessionId, key) overload has no callers anywhere in the file (the only call site, line 282, resolves to the readVersion(Connection, slotId, key) overload). Dead private code also risks a -Werror/lint break and invites future misuse: unlike the Connection-bound version, it opens its own connection outside any write transaction, so a caller would get a version that can change before it is used — exactly the race the transaction-bound variant exists to avoid. Please drop it, or wire it in only where a non-transactional read is genuinely intended.

() -> {
executeUpsert(conn, slotId, key, JsonUtils.getJsonCodec().toJson(value));
BoundSql boundSql =
dialect.sessionStateUpsert(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[Warning] Inlining executeUpsert leaves this sessionStateUpsert + bindParams + executeUpdate() block duplicated verbatim here and in the UNVERSIONED branch of saveIfVersion (line ~276). The helper was the single place a dialect/SQL change had to be applied; with two copies, a future fix (e.g. a new upsert column or conflict clause) can silently land in one path only. If the goal was to remove an indirection used twice, consider keeping a small private upsertIn(conn, slotId, key, json) helper — or extracting a shared lambda — instead of duplicating the body.

conn,
() -> {
BoundSql boundSql =
dialect.sessionStateUpsert(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[Info] The removed javadoc on saveIfVersion documented a non-obvious invariant: it deliberately does not delegate to save(...) — even for unconditional writes — "so the version is captured before the write lock is released". That reasoning is now implicit exactly at this line, and it is also the branch where a subtle semantic change lives (a dedicated UNVERSIONED fast path that always re-reads the version). Please keep a one-line comment here stating why the upsert and the version read must stay in the same transaction.

@codecov

codecov Bot commented Sep 24, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 77.77778% with 16 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
...ope/extensions/jdbc/state/JdbcAgentStateStore.java 77.77% 10 Missing and 6 partials ⚠️

📢 Thoughts on this report? Let us know!

@aiyili aiyili changed the title Refactor: inline executeUpsert and simplify readVersion in JdbcAgentStateStore Refactor: inline executeUpsert and simplify saveIfVersion in JdbcAgentStateStore Sep 24, 2026
@aiyili
aiyili force-pushed the refactor/jdbc-write-path branch from 1055e72 to 48759ca Compare September 24, 2026 07:09

@oss-maintainer oss-maintainer left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Summary

Wiring the raw execution channel so ExecutionConfig retries actually apply to tool exceptions is the right fix, and the new test matrix (sync / Mono / CompletableFuture / MCP transport vs protocol / suspend / retryOn / parallel isolation / direct-path contract) is thorough. The useExecutionPath split correctly keeps Toolkit.callTool semantics intact, which was the risky part.

My main concern is upstream of the code: this turns a previously inert setting into a live one. Anyone who already set maxAttempts > 1 on a tool path (with the default permissive retryOn) will start re-executing side-effecting tools after a transient failure once they upgrade, and the worst-case latency of a single tool call becomes maxAttempts x timeout. That deserves an explicit decision on the default retry predicate plus a changelog note before merge.

Findings

  • [Critical] ToolExecutor.java:506 - retryOn defaults to error -> true, so maxAttempts>1 now retries non-idempotent tools; previously this was a no-op for tool exceptions.
  • [Warning] ToolExecutor.java:303 - one DefaultToolEmitter is reused across retry attempts, so chunks emitted by the discarded attempt are already delivered before the retry re-emits.
  • [Warning] ToolExecutor.java:483 - timeout is applied per attempt, not cumulatively; document it or bound total elapsed time.
  • [Info] McpTool.java:206 - eager Objects.requireNonNull escapes the onErrorResume compat contract; wrap in Mono.defer.
  • [Info] ExceptionUtils.java:117 - whole-cause-chain suspension lookup can permanently suspend a genuine failure; consider bounding the walk. Also note core.util now depends on core.tool.

Suggestions

  • Default the tool retry predicate to ExecutionConfig.RETRYABLE_ERRORS (already available), or gate implicit retries on AgentTool.isReadOnly(), keeping an opt-in for callers that need the current behavior.
  • Build executionParam / toolEmitter inside the Mono.defer so each attempt is isolated.
  • Add a test asserting chunk callbacks are not duplicated across a retry - that gap is exactly what makes the emitter finding invisible to CI.

Overall: solid fix and excellent test coverage; I would only settle the default-retry-policy question so the upgrade path is safe for existing configurations.


Automated review by github-manager-bot

validateSlotId(slotId);
validateStateKey(key);
String json = JsonUtils.getJsonCodec().toJson(value);
try (Connection conn = dataSource.getConnection()) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[Warning] The UNVERSIONED early return duplicates save()'s body, and the two copies will drift.

This branch now re-implements slotId() + validateSlotId + validateStateKey + toJson + executeInWriteTransaction + the same sessionStateUpsert PreparedStatement block that save() has. The deleted executeUpsert(Connection, slotId, key, json) helper existed precisely to keep those two call sites in sync; removing it re-couples them by copy instead of by call.

The duplication also has a real cost for subclasses: save() is a documented override point, and a subclass that overrides save() to intercept writes used to have that contract stated in the javadoc. Because saveIfVersion deliberately does not delegate to save(), a subclass interceptor still has to override both methods — but nothing here says so any more.

Suggested fix: restore a private helper that both paths call, e.g.

private void upsertSingleState(Connection conn, String slotId, String key, String json)
        throws SQLException {
    BoundSql boundSql = dialect.sessionStateUpsert(slotId, key, SINGLE_STATE_INDEX, json);
    try (PreparedStatement stmt = conn.prepareStatement(boundSql.sql())) {
        bindParams(stmt, boundSql.params());
        stmt.executeUpdate();
    }
}

That keeps the inlining win (no method whose only job was to forward one call) while preserving a single definition of "the unconditional write", and restores the javadoc note about overriding both save and saveIfVersion.

result[0] = readVersion(conn, slotId, key);
});
return result[0];
} catch (Exception e) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[Warning] Two different messages now wrap the same failure, and the CAS branch lost its guard context.

The new branch throws RuntimeException("Failed to save state if version: " + key, e) before the shared tail, so an UNVERSIONED write failure and a CAS write failure produce the same message from two independent catch blocks. That is fine for users but it means the two blocks must be kept identical by hand forever.

More important: the pre-existing tail branch also catches Exception and rethrows. If a future edit adds behaviour to the tail (e.g. retry-on-deadlock, or verifyTableExists() handling), the UNVERSIONED path will silently not get it. Keeping one transaction body with an if (expectedVersion == UNVERSIONED) inside it avoided that class of bug, which is what the original comment ("Writes and obtains the assigned version in one database transaction") was documenting.

If the split is intentional, please say so in a short comment here so the next reader does not "helpfully" re-merge them, and keep the two catch blocks consistent.

bindParams(stmt, boundSql.params());
stmt.executeUpdate();
}
result[0] = readVersion(conn, slotId, key);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[Info] readVersion inside the transaction is the subtle part of this refactor — worth a comment.

The atomicity argument in the PR description is correct: the version must be read before the write lock is released, so saveIfVersion(UNVERSIONED) cannot simply delegate to save(). That constraint is invisible at this line, and the javadoc that used to explain it here was deleted in this same hunk.

Please keep a one-line comment on the branch, e.g. // Read the version inside the same transaction: the write lock must not be released before we observe it. This is the kind of invariant that gets optimized away by the next well-meaning refactor into save().

@oss-maintainer

Copy link
Copy Markdown
Collaborator

Correction — review summary for this re-review

The review body attached to pullrequestreview-5301441002 was pasted from the wrong workspace and describes another PR. The three inline comments on JdbcAgentStateStore.java (lines 253 / 268 / 265) are correct and are the substance of this re-review. The intended summary is below. Apologies for the noise.

Summary

Pure refactor of the JDBC single-state write path: the one-line executeUpsert helper is inlined and the UNVERSIONED case is lifted out of the CAS branch. No public API or wire behavior changes, and the atomicity argument holds — the version is still read inside the same write transaction, so a caller can never observe a released lock with a stale version.

My only reservation is that the refactor trades one indirection for two copies of the same statement. Both save() and the new early-return branch now own a private definition of "the unconditional write".

Note on overlap: this repeats part of my own earlier findings on this PR (the deleted saveIfVersion javadoc and the inlining at line 135). Those earlier comments still apply; the new comments add the drift risk from the duplicated catch block and the now-undocumented version-read-inside-transaction invariant.

Findings

  • [Warning] JdbcAgentStateStore.java:253 — UNVERSIONED branch duplicates save()'s validation + upsert block; the deleted helper was what kept them in sync.
  • [Warning] JdbcAgentStateStore.java:268 — two independent catch blocks now produce the same message; future changes to the transaction tail will silently skip the UNVERSIONED path.
  • [Info] JdbcAgentStateStore.java:265 — "read the version before the write lock is released" is the non-obvious invariant here and is now undocumented; worth a one-line comment.

Suggestions

Keep a private upsertSingleState(Connection, slotId, key, json) that both paths call. That preserves the stated win (no method whose only job is to forward one call) while keeping a single definition of the unconditional write, and restore the subclasses intercepting writes should override both save and saveIfVersion note, which is still true and is easy to lose.

Not blocking — the change is correct as written. Flagging before the duplication spreads to the other store implementations.


Automated review by github-manager-bot

@aiyili aiyili changed the title Refactor: inline executeUpsert and simplify saveIfVersion in JdbcAgentStateStore Refactor: separate the UNVERSIONED write path from the CAS branch in JdbcAgentStateStore Sep 24, 2026
@aiyili
aiyili force-pushed the refactor/jdbc-write-path branch from 48759ca to a994975 Compare September 24, 2026 08:07
@aiyili

aiyili commented Sep 24, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the careful re-review - all three findings addressed in a994975:

  1. Duplication (L253): the unconditional write is back behind a shared helper, renamed to upsertSingleState(Connection, slotId, key, json). Both save() and the UNVERSIONED branch call it, so the definition lives in exactly one place again.
  2. Duplicated catch (L268): the two catch blocks remain separate by construction (each path opens its own connection), but with the statement body unified the drift surface is reduced to the transaction tail only.
  3. Undocumented invariant (L265): added an inline comment at the version read - it is captured inside the same write transaction, before the write lock is released.

Also restored the subclassing javadoc note on save(). Thanks for catching the duplication before it spread to the other store implementations.

@oss-maintainer oss-maintainer left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Summary

Separates the UNVERSIONED write path from the CAS branch in saveIfVersion and funnels both unconditional writes through one upsertSingleState(...) helper, so the write itself can no longer drift between save() and saveIfVersion(). Verified behavior-preserving: slotId derivation, validateSlotId/validateStateKey ordering, the toJson call and the readVersion inside the same write transaction are all identical to the previous single-flow version, and the CAS branches (expectedVersion == 0 / > 0) are untouched.

LGTM — approving. The three inline notes are maintainability follow-ups, none of them blocking:

  • JdbcAgentStateStore.java:245 — the shared helper covers the write, but the preamble (slotId + validations + toJson) and the teardown (connection, transaction, catch/wrap) are now written twice; a small "run this body inside a write transaction" helper would finish what this commit started.
  • JdbcAgentStateStore.java:313 — the contract javadoc was deleted from saveIfVersion and the new one documents upsertSingleState, which does not own the "version read inside the same write transaction" invariant.
  • JdbcAgentStateStore.java:259 — no test change accompanies the split; if nothing asserts the version returned by the UNVERSIONED path yet, that is the claim worth pinning.

Findings

  • [Warning] JdbcAgentStateStore.java:245 — duplicated transaction scaffolding around the shared write.
  • [Warning] JdbcAgentStateStore.java:313 — method-level contract doc removed from the public override.
  • [Info] JdbcAgentStateStore.java:259 — invariant documented but not pinned by a test in this commit.

Automated review by github-manager-bot

@Override
public long saveIfVersion(
String userId, String sessionId, String key, State value, long expectedVersion) {
if (expectedVersion == UNVERSIONED) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[Warning] Sharing upsertSingleState(...) removes the duplicated write, but this branch now carries a second copy of everything around it: slotId(...) + validateSlotId + validateStateKey + toJson + try (Connection ...) + long[] result + executeInWriteTransaction + the identical catch (Exception e) → RuntimeException("Failed to save state if version: " + key, e). That is the same drift risk this refactor was set up to remove, just relocated one level out — any change to validation order, error wrapping or transaction setup now has to be made twice, and the compiler will not notice when it isn't.

Passing the body through one helper keeps the split readable and the scaffolding single-sourced, e.g.:

private long writeInTransaction(String userId, String sessionId, String key, State value,
        ThrowingBiFunction<Connection, String, Void> body) { /* slotId + validate + json + try/catch */ }

so the UNVERSIONED and CAS branches differ only in what they do inside the transaction. Not blocking.

}

private void executeUpsert(Connection conn, String slotId, String key, String json)
/**

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[Warning] The javadoc that carried the real contract was deleted from saveIfVersion and the replacement text landed on upsertSingleState, which does not actually own the invariant: the guarantee is "the version is read inside the same write transaction, before the lock is released", and that belongs to the method that opens the transaction. saveIfVersion is a public override whose CAS/UNVERSIONED semantics are subtle (special values of expectedVersion, the version returned, why it must not delegate to save()), so losing its method-level doc is a net readability regression even though the file now has more comments than before.

Could the contract go back on saveIfVersion (covering both branches) with a short pointer from the helper?

// Read the version inside the same write transaction: capturing it
// before the write lock is released guarantees the returned version
// belongs to the row this call just wrote, not a concurrent writer's.
result[0] = readVersion(conn, slotId, key);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[Info] This commit only touches the main source, so the claim in the new comment — the returned version belongs to this call's write and not to a concurrent writer's — is documented but not pinned by a test in the same change. If JdbcAgentStateStoreTest already asserts the UNVERSIONED return value we're fine; otherwise a small test that writes twice with UNVERSIONED and asserts strictly increasing returned versions (ideally with two threads on the same slotId/key) would keep the next refactor of this method honest. Same reasoning applies to the wrapped-exception message, which is now duplicated in two places.

- Move the expectedVersion == UNVERSIONED early-return out of the CAS
  transaction in saveIfVersion: the unconditional write+version-read runs
  in its own single transaction (version still captured before the write
  lock is released)
- Rename executeUpsert -> upsertSingleState and call it from both save()
  and the UNVERSIONED branch, so the unconditional write keeps a single
  definition
- Add javadoc on save() noting that subclasses intercepting writes should
  override both save and saveIfVersion

Orthogonal to the version-column migration (agentscope-ai#3216 / PR agentscope-ai#3244).
@xzxiaoshan

Copy link
Copy Markdown
Collaborator

Would this structure be better? Same two-branch separation as this PR, but the scaffolding (connection + transaction + catch) also collapses into one definition, and the prologue lives once above the dispatch:

    // -------------------------------------------------------------------------
    //  AgentStateStore implementation
    // -------------------------------------------------------------------------

    /**
     * Saves a single value unconditionally. Versioned writes use the same SQL helper but
     * do not invoke this public method; subclasses intercepting writes should override
     * both this method and {@link #saveIfVersion}.
     */
    @Override
    public void save(String userId, String sessionId, String key, State value) {
        String slotId = slotId(userId, sessionId);
        validateSlotId(slotId);
        validateStateKey(key);
        String json = JsonUtils.getJsonCodec().toJson(value);
        executeInWriteTransaction(
                "Failed to save state: " + key,
                conn -> {
                    upsertSingleState(conn, slotId, key, json);
                    return null;
                });
    }

    @Override
    public void save(String userId, String sessionId, String key, List<? extends State> values) {
        String slotId = slotId(userId, sessionId);
        validateSlotId(slotId);
        validateStateKey(key);

        if (values.isEmpty()) {
            return;
        }

        String hashKey = key + HASH_KEY_SUFFIX;

        executeInWriteTransaction(
                "Failed to save list: " + key,
                conn -> {
                    String currentHash = ListHashUtil.computeHash(values);
                    String storedHash = getStoredHash(conn, slotId, hashKey);
                    int existingCount = getListCount(conn, slotId, key);
                    boolean needsFullRewrite =
                            ListHashUtil.needsFullRewrite(values, storedHash, existingCount);

                    if (needsFullRewrite) {
                        LOG.debug(
                                "List rewrite for key '{}': existing={}, incoming={}",
                                key, existingCount, values.size());
                        deleteListItems(conn, slotId, key);
                        insertItems(conn, slotId, key, values, 0);
                        saveHash(conn, slotId, hashKey, currentHash);
                    } else if (values.size() > existingCount) {
                        LOG.debug(
                                "Incremental append for key '{}': appending {} items after"
                                        + " existing {}",
                                key, values.size() - existingCount, existingCount);
                        List<? extends State> newItems =
                                values.subList(existingCount, values.size());
                        insertItems(conn, slotId, key, newItems, existingCount);
                        saveHash(conn, slotId, hashKey, currentHash);
                    }
                    return null;
                });
    }

    /**
     * Writes and obtains the assigned version in one database transaction. The version is
     * always captured before the write lock is released, so it belongs to the row this
     * call just wrote. {@code UNVERSIONED} is an unconditional write — not a CAS — but it
     * still returns the assigned version.
     */
    @Override
    public long saveIfVersion(
            String userId, String sessionId, String key, State value, long expectedVersion) {
        String slotId = slotId(userId, sessionId);
        validateSlotId(slotId);
        validateStateKey(key);
        String json = JsonUtils.getJsonCodec().toJson(value);

        if (expectedVersion == UNVERSIONED) {
            return executeInWriteTransaction(
                    "Failed to save state if version: " + key,
                    conn -> {
                        upsertSingleState(conn, slotId, key, json);
                        return readVersion(conn, slotId, key);
                    });
        }
        return executeInWriteTransaction(
                "Failed to save state if version: " + key,
                conn -> executeCasWrite(conn, slotId, key, json, expectedVersion));
    }

    /**
     * CAS write body: {@code expectedVersion == 0} inserts if absent (savepoint-guarded,
     * with the 0 -> 1 backfill bump), any higher version takes the versioned UPDATE.
     * Returns the new version, or {@link #UNVERSIONED} when the compare fails and
     * nothing was written.
     */
    private long executeCasWrite(
            Connection conn, String slotId, String key, String json, long expectedVersion)
            throws Exception {
        if (expectedVersion > 0L) {
            return executeUpdateIfVersion(conn, slotId, key, json, expectedVersion);
        }
        BoundSql insertSql =
                dialect.sessionStateInsertIfAbsent(slotId, key, SINGLE_STATE_INDEX, json);
        // Guard the INSERT with a savepoint: on vendors like Postgres a failed statement
        // aborts the whole transaction, which would poison the fallback UPDATE below.
        Savepoint savepoint = conn.setSavepoint("cas_insert_if_absent");
        try (PreparedStatement stmt = conn.prepareStatement(insertSql.sql())) {
            bindParams(stmt, insertSql.params());
            if (stmt.executeUpdate() == 1) {
                return 1L;
            }
        } catch (SQLException e) {
            if (!isDuplicateKey(e)) {
                throw e;
            }
            conn.rollback(savepoint);
        }
        // The row already exists. If its stored version is still 0 (e.g. backfilled by an
        // ALTER TABLE migration), that satisfies the CAS — bump 0 -> 1. If a concurrent
        // writer already moved it past 0 this matches nothing and correctly reports
        // UNVERSIONED.
        return executeUpdateIfVersion(conn, slotId, key, json, 0L);
    }

    /** The single definition of an unconditional single-state write, shared by save() and
     *  the UNVERSIONED branch of saveIfVersion(). Keeping it in one place prevents the two
     *  paths from drifting apart. */
    private void upsertSingleState(Connection conn, String slotId, String key, String json)
            throws SQLException {
        // body unchanged
    }

    // readVersion / executeUpdateIfVersion / getStoredHash / ... — unchanged

    @Override
    public void delete(String userId, String sessionId) {
        String slotId = slotId(userId, sessionId);
        validateSlotId(slotId);
        executeInWriteTransaction(
                "Failed to delete session: " + slotId,
                conn -> {
                    BoundSql boundSql = dialect.sessionStateDeleteSession(slotId);
                    try (PreparedStatement stmt = conn.prepareStatement(boundSql.sql())) {
                        bindParams(stmt, boundSql.params());
                        stmt.executeUpdate();
                    }
                    return null;
                });
    }

What this buys, with no behavior change:

  • The two catch blocks from the earlier review round are structurally gone — one definition of connection + transaction + error wrapping serves all four write paths (save, save-list, both saveIfVersion branches, delete).
  • The prologue lives once, above the dispatch; the CAS body returns directly (no long[] capture), and SqlOperation/SqlCall merge into one interface.
  • All the invariants this PR documents are preserved: the UNVERSIONED branch still reads the version inside the same write transaction, upsertSingleState stays the single SQL definition, and every error message is byte-identical.

@xzxiaoshan xzxiaoshan self-assigned this Sep 25, 2026
按 PR agentscope-ai#3273 评审建议,连接获取+事务+异常包装收敛为一个定义,五处写路径
(save/save-list/两个 saveIfVersion 分支/delete)只保留 SQL 本体:

- SqlOperation 并入泛型 SqlCall<T>(接收 Connection、返回 T,可抛异常);
  executeInWriteTransaction(errorMessage, call) 统一负责开连接、事务
  (失败回滚、回滚失败挂 suppressed、恢复 autoCommit)与
  RuntimeException(errorMessage, e) 包装
- 各写路径 prologue(slotId/stateKey 校验、json 序列化)上提到分派之前,
  只写一次;CAS 分支体提取为 executeCasWrite 直接返回 long,去掉 long[] 捕获
  (expectedVersion>0 走版本化 UPDATE;==0 走 savepoint 保护的
  insert-if-absent 与 0->1 回填)
- 行为不变:错误消息逐字节一致(含读路径);UNVERSIONED 仍在同一写事务内
  读取版本;upsertSingleState 仍是唯一无条件单状态写 SQL 定义;
  模块 92/92 测试通过

@oss-maintainer oss-maintainer left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Summary

Re-review of 42537c2d (refactor(jdbc): 写路径脚手架收敛为单一 executeInWriteTransaction), which landed after my approval on a9949756. The consolidation is the right shape and I verified the write paths are otherwise behaviour-preserving: the CAS insert-if-absent + savepoint + 0 -> 1 bump logic moved into executeCasWrite unchanged, save()/delete()/save(list) keep their original RuntimeException prefixes, the rollback-adds-suppressed handling is intact, and auto-commit is still restored only when this method changed it. CI is green on this head (build (ubuntu-latest), build (windows-latest), Check License, Check Module Sync, codecov/patch all success).

Findings

  • [Warning] JdbcAgentStateStore.java:274 — expectedVersion > 0L folds every negative version into the insert-if-absent branch; previously a negative non-sentinel value matched nothing and returned UNVERSIONED without writing.
  • [Info] JdbcAgentStateStore.java:135 — JSON serialization moved outside the wrapped region, so codec failures lose the "Failed to save state: " + key wrapper (same at line 247).
  • [Info] JdbcAgentStateStore.java:537 — the scaffolding collapse itself is a clear improvement.

Suggestions

Only the first item needs a decision before merge. If you can rule out any caller that passes a negative version other than UNVERSIONED — getVersioned reports 0 for an absent key on versioning backends, so -2 should not appear in normal traffic — then the guard is defensive rather than urgent, and an IllegalArgumentException at the top of executeCasWrite is the cheapest way to keep that assumption enforced instead of implied.


Automated review by github-manager-bot

private long executeCasWrite(
Connection conn, String slotId, String key, String json, long expectedVersion)
throws SQLException {
if (expectedVersion > 0L) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[Warning] This > 0L test silently re-classifies every negative expectedVersion as the insert-if-absent case. Before this commit the dispatch was == UNVERSIONED / == 0L / else, so a negative value other than the sentinel (e.g. a corrupted or -2 from a persisted version field) went to executeUpdateIfVersion(..., -2), matched no row, and correctly returned UNVERSIONED without writing. Now it takes the INSERT IF ABSENT branch below, so the same input can create the row and return version 1 — a write where the caller asked for a conditional one. Please keep the two cases distinct:

if (expectedVersion == 0L) {
    // insert-if-absent + savepoint-guarded 0 -> 1 bump
} else if (expectedVersion > 0L) {
    return executeUpdateIfVersion(conn, slotId, key, json, expectedVersion);
}
throw new IllegalArgumentException(
        "expectedVersion must be UNVERSIONED, 0, or a positive version; got " + expectedVersion);

The existing UNVERSIONED short-circuit in saveIfVersion stays as-is; this only closes the remaining negative space.

} catch (Exception e) {
throw new RuntimeException("Failed to save state: " + key, e);
}
String json = JsonUtils.getJsonCodec().toJson(value);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[Info] Small error-reporting scope change worth confirming as intentional: toJson(value) is now computed before executeInWriteTransaction, while previously it ran inside the caller's try { ... } catch (Exception e) { throw new RuntimeException("Failed to save state: " + key, e); }. A codec failure therefore propagates raw from save() / saveIfVersion() instead of being wrapped with the "Failed to save state: " + key prefix that every other failure on this path still carries. Same shape at line 247. Either hoist the serialization inside the lambda, or accept the narrower contract and say so in the save() javadoc — callers that pattern-match on the wrapper message are the ones affected.

* carrying {@code errorMessage}. Callers contribute only the SQL work and the
* user-facing error prefix, so no write path repeats connection/transaction/catch.
*/
private <T> T executeInWriteTransaction(String errorMessage, SqlCall<T> operation) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[Info] Positive: folding connection acquisition, the auto-commit save/restore, rollback-with-suppressed and the RuntimeException wrapping into one generic executeInWriteTransaction(String, SqlCall<T>) removes five duplicated try (Connection ...) { ... } catch (Exception e) { ... } blocks, and passing the message in as a parameter keeps every user-facing prefix identical to before. executeCasWrite as a named method is also a readability win. The return null; in the three void-shaped call sites is the only wart the generic signature buys — a SqlRunnable overload delegating here would remove it if you care; not worth churn on its own.

- 脚手架收敛前 CAS 分派为 ==UNVERSIONED / ==0 / else:负数(如 -2)走
  executeUpdateIfVersion 匹配不到任何行,安全返回 UNVERSIONED 不写;
  收敛后 executeCasWrite 的 expectedVersion > 0L 判断把负数折叠进
  insert-if-absent 分支,同一输入会建行并返回 version 1——调用方请求
  条件写却发生了无条件写
- 修复:saveIfVersion prologue 校验,非 UNVERSIONED 的负数直接抛
  IllegalArgumentException(与 validateSlotId/validateStateKey 同风格,
  建连接前快速失败,异常不被事务包装);executeCasWrite javadoc 注明
  只有 0 与正数会到达
- 采纳评审 Info:javadoc 注明 json 序列化在事务外执行,codec 失败不带
  "Failed to save state" 前缀直接传播
- 回归测试:-2 拒绝且未写入;模块 93/93 通过

自动化评审 oss-maintainer Warning 项

@oss-maintainer oss-maintainer left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Summary

Re-review of the new commit: the expectedVersion guard sits at the only version-accepting entry point (saveIfVersion), fires before any database work as documented, and the sentinel / 0 / positive paths route exactly as before — no semantic change for versioned rows. The new H2 test is meaningful (it fails against the previous > 0L dispatch), and every item from the previous round is resolved: the dead readVersion overload is gone, upsertSingleState is the single definition used by both paths, failure wrapping is consistent, and the version-capture invariant is documented and pinned by a test. Approving with one non-blocking consistency note.

Previous-round follow-up

All prior inline findings are addressed at this head.


Automated review by github-manager-bot

validateSlotId(slotId);
validateStateKey(key);

if (expectedVersion != UNVERSIONED && expectedVersion < 0L) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

The new rejection is JDBC-only and is not part of the shared contract: InMemoryAgentStateStore.casSingleState, MysqlAgentStateStore, PostgresAgentStateStore and MongoAgentStateStore all treat a negative non-sentinel expectedVersion as an ordinary CAS miss and return UNVERSIONED, while AgentStateStore#saveIfVersion in agentscope-core documents no such validation. Since no in-repo caller passes a non-sentinel negative today (ReActAgent only passes UNVERSIONED or a stored version), this is defensive; consider documenting the rejection on the core interface or aligning the sibling stores so one input cannot mean "conflict" on one backend and a thrown exception on another.

@xzxiaoshan
xzxiaoshan merged commit 6a05680 into agentscope-ai:main Sep 26, 2026
6 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants