Skip to content

Support record-level shadow routing for batch INSERT - #40550

Open
Drifter-yh wants to merge 3 commits into
apache:masterfrom
Drifter-yh:fix/shadow-batch-insert-31448
Open

Drifter-yh wants to merge 3 commits into
apache:masterfrom
Drifter-yh:fix/shadow-batch-insert-31448

Conversation

@Drifter-yh

Copy link
Copy Markdown

Fixes #31448.

Changes proposed in this pull request:

  • Decide shadow routing per insert value for a multi-row INSERT ... VALUES (...), (...), and split the statement between the shadow and production data sources when the configured column shadow algorithms match only part of the values.
  • Record the insert value indexes of each route unit in RouteContext, build the per-unit SQL with a shadow insert values token, and distribute grouped insert parameters by the same indexes.
  • Accumulate the update counts of the split statement in JDBC and Proxy.
  • Keep the previous statement-level behavior when all values match, no value matches, the table is sharded, or another rule owns the route units.
  • Document the ## Batch INSERT behavior in the shadow limitations pages and add the Release Notes entry.

Compatibility:

  • No configuration change. A mixed batch executes on both data sources, so atomicity follows the transaction rule configured for the database.

Verification:

  • ./mvnw -pl features/shadow/core test
  • ./mvnw -pl infra/rewrite/core,infra/route/core test
  • ./mvnw -pl test/e2e/driver -Dit.test=ShadowStatementTest,ShadowPreparedStatementTest verify (H2 e2e: mixed batch rows land in the expected data source and the update count is 3)
  • ./mvnw -pl jdbc,proxy/backend/core -Dtest=DriverExecuteUpdateExecutorTest,StandardDatabaseProxyConnectorTest test
  • ./mvnw -pl features/shadow/core,infra/route/core,infra/rewrite/core,jdbc,proxy/backend/core,test/e2e/driver -Pcheck spotless:check checkstyle:check
  • ./mvnw -pl features/shadow/core -Pcheck apache-rat:check

Before submitting this PR, I confirm that:

  • My code follows the code of conduct of this project.
  • I have reviewed my changes.
  • I have (or in comment I request) added corresponding labels for the pull request. Not added; a committer can apply the feature: shadow label.
  • I have passed the required local checks: the scoped Maven commands listed above pass. The full-repository clean install -Pcheck was not run locally.
  • I have updated the relevant documentation.
  • I have added or updated unit tests for my changes.
  • I have updated the Release Notes of the current development version.
  • I have disclosed the AI assistance below.

AI assistance: DeepSeek Harness was used to draft the implementation, tests, and documentation in features/shadow/core, infra/route/core, infra/rewrite/core, jdbc, proxy/backend/core, and test/e2e/driver. I reviewed and verified every line and the commands above.

Route multi-row INSERT values per record when the configured column shadow
algorithms match only part of them, so matching values go to the shadow data
source and the remaining values go to the production data source.

Split the statement into production and shadow route units, filter insert
values and grouped parameters per route unit, and accumulate the update
counts in JDBC and Proxy.

Fixes apache#31448.

@terrymanu terrymanu left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Summary

This PR addresses #31448 by splitting mixed batch INSERTs between production and shadow data sources. It adds row-index metadata, SQL/parameter filtering, and update-count aggregation. Routing, literal preservation, and result handling still require changes.

Result

Review Result: Not Mergeable
Feedback Mode: Change Request
Review Status: Not Converged
Confirmed Blocking Issues: 12

These are confirmed findings. Native review-ledger initialization and session validation could not complete, so this is a qualified subset.

Blocking Issues

[P1] Prevent splitting when SQL rewriting is disabled

  • Evidence: ShadowSQLRouter.java:87 splits routes while SKIP_SQL_REWRITE=true prevents generating the filtering token.
  • Impact: Literal INSERTs execute the complete batch on both data sources, including shadow rows in production. Prepared INSERTs retain all placeholders but receive partial parameters.
  • Required Change: Prevent splitting when its required rewrite cannot run; cover both execution forms.

[P1] Preserve SQL literal semantics

  • Evidence: ShadowInsertValuesTokenGenerator.java:58 reconstructs every expression through InsertValue.
  • Impact: The focused probe confirms PostgreSQL E'line\nbreak' becomes ordinary 'line\nbreak', changing stored characters under the default configuration. MySQL "O'Reilly" also becomes invalid 'O'Reilly'. See PostgreSQL escape semantics and MySQL string quoting.
  • Required Change: Preserve original expression spelling or use dialect-correct rendering, with regression coverage.

[P2] Honor all-shadow decisions across multiple algorithms

  • Evidence: ShadowSQLRouter.java:88 rejects [true, true] when no single algorithm matched the complete statement.
  • Impact: With algorithms matching values 1 and 2 respectively, [1,2,3] sends 1 and 2 to shadow, but removing 3 sends both matching rows to production. This remains an unresolved part of the accepted record-level routing requirement.
  • Required Change: Apply all-true row decisions even when different algorithms matched the rows.

[P2] Complete JDBC update-count aggregation

  • Evidence: DriverJDBCPushDownExecuteUpdateExecutor.java:120 changes only the direct executeUpdate() result.
  • Impact: JDBC getUpdateCount() and prepared executeBatch() still select the first fragment. A 2+1 split reports 2 or [2] instead of 3 or [3].
  • Required Change: Propagate split aggregation to these APIs, including batch entries with different route participation.

[P2] Preserve split INSERT RETURNING results

  • Evidence: ShadowSQLRouter.java:107 creates two executions; MergeEngine.java:82 exposes only the first result without a merger.
  • Impact: PostgreSQL Proxy INSERT … RETURNING silently omits the other data source’s returned rows.
  • Required Change: Merge those results or exclude result-producing INSERTs from splitting until supported.

[P2] Remove quadratic linked-list traversal

  • Evidence: ShadowSQLRouter.java:105 and ShadowInsertValuesToken.java:48 repeatedly index actual LinkedList instances.
  • Impact: Routing and rendering perform quadratic traversal as batch size grows; the router also violates the explicit high-frequency coding rule.
  • Required Change: Use sequential traversal or an appropriate indexed representation.

[P2] Document the actual splitting limitations

  • Evidence: The new English limitation paragraph and corresponding Chinese paragraph promise splitting without the router’s topology restrictions.
  • Impact: Sharded or otherwise excluded routes still send mixed batches wholly to production.
  • Required Change: Document the supported scope and statement-level fallback in both languages.

[P2] Extract the nested algorithm loop

  • Evidence: ShadowInsertValueRouteDecider.java:66.
  • Impact: The new nested loop violates the repository’s extraction rule; its algorithm variable also violates enhanced-loop naming.
  • Required Change: Extract the inner decision and follow the required element naming.

[P2] Use the required type assertion

  • Evidence: ShadowSQLRewriteContextDecoratorTest.java:58.
  • Impact: assertTrue(value instanceof …) violates the explicit type-assertion standard.
  • Required Change: Use assertThat(value, isA(ShadowInsertValuesToken.class)).

[P2] Name the returned map accumulator result

  • Evidence: RouteSQLRewriteEngineTest.java:281.
  • Impact: The newly accumulated and returned storageUnits map violates the returned-value naming rule.
  • Required Change: Name the map result and give the setup mock a distinct name.

[P2] Remove unnecessary statement wrapping

[P2] Use Collection for the iteration-only predicate

  • Evidence: ShadowSQLRouter.java:115.
  • Impact: The private helper requires no List operations or contract, contrary to the collection-declaration rule.
  • Required Change: Accept Collection<Boolean>.

Coverage

Public head b670d37dbb5c14c07f77693aa5f5b9097e256625, base 00f96061f9398347976abccb26e7e510a71c68ea; all 24 changed files inspected through two independent assessments and coordinator reconciliation.

Local Spotless and Checkstyle passed, exit 0, covering all 20 applicable Java files. Focused probes reproduced literal/count failures; an optional boundary harness later exited 1 in mock setup. Full unit/E2E suites were not rerun. Code correctness only; CI was not reviewed.

Native ledger initialization failed because the PR commit object is absent locally; manual-record session validation also failed. No successful formal-session validation is claimed. The checkout remains unchanged.

- Skip splitting when SQL rewrite is skipped and exclude INSERT ... RETURNING
- Preserve original SQL fragments for insert values
- Route all-shadow insert values matched by different algorithms to shadow
- Accumulate update counts for getUpdateCount and executeBatch
- Remove quadratic traversal and apply repository coding rules
@Drifter-yh

Copy link
Copy Markdown
Author

Pushed an update addressing all 12 findings.

  1. [P1] Skip rewrite: ShadowSQLRouter now refuses to split when QueryContext.getHintValueContext().isSkipSQLRewrite() is true. E2E covers Statement and PreparedStatement with SKIP_SQL_REWRITE=true; both keep the whole batch on production and report count 3.
  2. [P1] Literal semantics: ShadowInsertValuesTokenGenerator now substitutes every insert value with the original SQL fragment (startIndex/stopIndex) instead of re-rendering through InsertValue. Regression test uses E'line\nbreak' and 'O''Reilly' fragments and asserts they survive verbatim.
  3. [P2] All-shadow decisions: the router derives allShadow/mixed from the per-value decisions and moves the route unit to the shadow data source when every value matches, even when different algorithms matched different rows. Unit test uses two algorithms covering values 1 and 2.
  4. [P2] updateCount: the JDBC executors record whether the generated RouteContext contains split insert value indexes and expose it through DriverExecutorFacade; getUpdateCount() accumulates for execute() and executeUpdate(), and PreparedStatement.executeBatch() accumulates when any batch entry was split (including entries with different route participation). E2E asserts getUpdateCount() == 3 for both execution forms and executeBatch() returning [2, 2] for two entries (1,2 split; 3,4 production only).
  5. [P2] INSERT RETURNING: splitting is skipped when InsertStatement.getReturning() is present, so the statement keeps one execution and the complete result. Merging two result sets is intentionally out of this change; a unit test covers the routing decision and the limitations pages document the fallback.
  6. [P2] Quadratic traversal: route index construction and token rendering now traverse sequentially; token rendering uses an index set instead of LinkedList.get(int).
  7. [P2] Docs: both limitations pages state the supported scope (non-sharded single-table route) and the statement-level fallback for sharding, other route owners, and RETURNING.
  8. [P2] Coding rules: extracted the per-column algorithm decision, renamed enhanced-for variables to each, used isA(...), named the returned map result, collapsed the 194/170-char statements to one line, and the predicate takes Collection<Boolean>.

Verification on the new head:

  • ./mvnw -pl features/shadow/core,infra/rewrite/core,infra/route/core test - pass (125 shadow tests).
  • ./mvnw -pl jdbc -Dtest=BatchPreparedStatementExecutorTest,DriverExecuteBatchExecutorTest,DriverJDBCPushDownExecuteExecutorTest,DriverExecuteUpdateExecutorTest,DriverExecuteExecutorTest test - pass.
  • ./mvnw -pl test/e2e/driver -Dit.test=ShadowStatementTest,ShadowPreparedStatementTest verify - pass (23 tests).
  • ./mvnw -pl proxy/backend/core -Dtest=StandardDatabaseProxyConnectorTest test - pass (48 tests).
  • ./mvnw -pl <changed modules> -Pcheck spotless:check checkstyle:check - pass.
  • ./mvnw -pl features/shadow/core -Pcheck apache-rat:check - pass.

Ready for another review.

@Drifter-yh

Copy link
Copy Markdown
Author

@terrymanu The review findings are addressed in 65bd6c7; verification is listed in the previous comment. Could you take another look when you have time?

Pass the split INSERT flag of the multi-statement execution contexts to
the shared batch executor, so MySQL Proxy accumulates update counts from
the production and shadow data sources.
@Drifter-yh

Copy link
Copy Markdown
Author

Pushed 3cc6ec0 to fix the MySQL multi-statements compile regression. MySQLMultiStatementsProxyBackendHandler now derives the split flag from its execution contexts and passes it to BatchPreparedStatementExecutor.executeBatch; a regression test covers a split multi-row INSERT ... ON DUPLICATE KEY UPDATE and asserts the summed counts (3, 4, 5) in statement order.

Local verification: the reported compile command succeeds, the MySQL multi-statements test class passes (5 tests), JDBC batch executor tests pass (12), and the JDBC shadow e2e tests pass (23). The new CI / E2E workflows are in action_required and need approval before they can run.

This branch has not been deployed

No deployments
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.

Shadowing with batch insert does not have effect.

2 participants