Skip to content

Incorrect handling of skip policy with JPA infrastructure #5377

Closed

Description

@fmbenhassine

As of 6.0.3, it is impossible to skip invalid records with a JPA setup. The issue does not happen with a JDBC setup. This was initially discussed in #5303 and seems to be a bug in Spring Batch (to be confirmed). Here is a minimal example:

demo-gh5303.zip

The sample is expected to insert some items in a table using a JpaItemWriter. When all items are valid, they are inserted correctly. If an item violates a database constraint and I try to skip it, the job fails with the following exception:

[main] ERROR org.springframework.batch.core.step.AbstractStep -  COMMONS-LOGGING Encountered an error executing step myJobStep in job job
org.springframework.transaction.UnexpectedRollbackException: Transaction silently rolled back because it has been marked as rollback-only
	at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:803)
	at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:757)
	at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:149)
	at org.springframework.transaction.support.TransactionOperations.executeWithoutResult(TransactionOperations.java:67)
	at org.springframework.batch.core.step.item.ChunkOrientedStep.doExecute(ChunkOrientedStep.java:369)
	at org.springframework.batch.core.step.AbstractStep.execute(AbstractStep.java:251)
	at org.springframework.batch.core.job.SimpleStepHandler.handleStep(SimpleStepHandler.java:128)
	at org.springframework.batch.core.job.AbstractJob.handleStep(AbstractJob.java:397)
	at org.springframework.batch.core.job.SimpleJob.doExecute(SimpleJob.java:129)
	at org.springframework.batch.core.job.AbstractJob.execute(AbstractJob.java:293)
	at org.springframework.batch.core.launch.support.TaskExecutorJobLauncher$1.run(TaskExecutorJobLauncher.java:220)
	at org.springframework.core.task.SyncTaskExecutor.execute(SyncTaskExecutor.java:88)
	at org.springframework.batch.core.launch.support.TaskExecutorJobLauncher.launchJobExecution(TaskExecutorJobLauncher.java:211)
	at org.springframework.batch.core.launch.support.TaskExecutorJobLauncher.run(TaskExecutorJobLauncher.java:109)
	at org.springframework.batch.core.launch.support.SimpleJobOperator.start(SimpleJobOperator.java:201)
	at org.springframework.batch.core.launch.support.TaskExecutorJobOperator.start(TaskExecutorJobOperator.java:117)
	at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104)
	at java.base/java.lang.reflect.Method.invoke(Method.java:565)
	at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:359)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:158)
	at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:133)
	at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:371)
	at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:130)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
	at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:222)
	at jdk.proxy2/jdk.proxy2.$Proxy60.start(Unknown Source)
	at com.example.demo.DemoApplication.main(DemoApplication.java:47)

In this case, it is expected that the job succeeds and only the invalid item is skipped (this works as expected with JDBC).

Activity

  1. added this to the 6.0.4 milestone on Apr 10, 2026
  2. quaff commented on Apr 13, 2026

    @quaff
    Contributor

    I think it's caused by JPA perform all inserts/updates at end of chunk which triggered by entityManager.flush(), JDBC setup execute every insert/update on item write.

  3. MinChul-Son commented on Apr 14, 2026

    @MinChul-Son
    Contributor

    @fmbenhassine Hi,

    I've analyzed this issue and would like to contribute a fix. Here's my proposed approach:

    Root Cause

    The scan() method in ChunkOrientedStep processes multiple items within a single transaction in scan mode. With JPA (Hibernate), when entityManager.flush() fails for item A, Hibernate marks the entire transaction as rollback-only. When the next item B is subsequently
    written in that same transaction, JPA immediately throws "Transaction silently rolled back because it has been marked as rollback-only" — which is not in the skip list, causing a NonSkippableWriteException and ultimately failing the step. JDBC does not have this
    problem because a failed SQL statement does not poison the entire transaction.

    Proposed Fix

    Change scan mode to process one item per transaction instead of all items in a single transaction:

    1. Refactor ChunkTracker<O> — replace pendingChunk: Chunk<O> with a LinkedList<O> queue, and add pollNextScanItem() / hasPendingScanItems() methods.
     @Nullable O pollNextScanItem() {
         return (this.pendingScanItems != null) ? this.pendingScanItems.poll() : null;
     }
    
     boolean hasPendingScanItems() {
         return this.pendingScanItems != null && !this.pendingScanItems.isEmpty();
     }
    1. Modify processChunkSequentially() and processChunkConcurrently() scan mode blocks — call tracker.pollNextScanItem() to pull a single item per transaction, instead of passing the entire pending chunk to scan() at once.
     if (tracker.isScanMode()) {
         logger.info("Executing scan in new transaction after rollback");
         O item = tracker.pollNextScanItem();   // change here
         if (item != null) {
             Chunk<O> singleItemChunk = new Chunk<>(item);
             ChunkScanEvent chunkScanEvent = new ChunkScanEvent(stepExecution.getStepName(), stepExecution.getId());
             chunkScanEvent.begin();
             compositeChunkListener.beforeChunk(singleItemChunk);
             scan(singleItemChunk, contribution, status);   // change here
             
             // change here
             if (!status.isRollbackOnly()) {
                 compositeChunkListener.afterChunk(singleItemChunk);
             }
             chunkScanEvent.skipCount = contribution.getSkipCount();
             chunkScanEvent.commit();
         }
         
         // change here
         if (!tracker.hasPendingScanItems()) {
             logger.info("Chunk scan completed");
             tracker.exitScanMode();
             if (!status.isRollbackOnly()) {
                 stepExecution.incrementCommitCount();
             }
         }
         return;
     }
    1. Add TransactionStatus parameter to scan() — explicitly call status.setRollbackOnly() when a skip occurs, ensuring consistent rollback behavior for both JDBC and JPA.This ensures JPA's rollback-only marking is isolated to a single item's transaction and does not affect subsequent items.
     private void scan(Chunk<O> chunk, StepContribution contribution, TransactionStatus status) {
         for (O item : chunk) {
             Chunk<O> singleItemChunk = new Chunk<>(item);
             try {
                 this.compositeItemWriteListener.beforeWrite(singleItemChunk);
                 this.itemWriter.write(singleItemChunk);
                 contribution.incrementWriteCount(singleItemChunk.size());
                 this.compositeItemWriteListener.afterWrite(singleItemChunk);
             }
             catch (Exception exception) {
                 if (this.skipPolicy.shouldSkip(exception, contribution.getStepSkipCount())) {
                     this.compositeSkipListener.onSkipInWrite(item, exception);
                     contribution.incrementWriteSkipCount();
                     contribution.getStepExecution().incrementRollbackCount();
                     status.setRollbackOnly();  // change here
                 }
                 else {
                     logger.error("Failed to write item: " + item, exception);
                     this.compositeItemWriteListener.onWriteError(exception, singleItemChunk);
                     throw new NonSkippableWriteException("Skip policy rejected skipping item", exception);
                 }
             }
         }
     }

    I would love to be assigned to this issue and submit a PR. Would this approach be acceptable to the team?

  4. fxpaquette commented on Apr 14, 2026

    @fxpaquette

    I believe @MinChul-Son is correct and that the root cause (chunk scanning being done in a single transaction) may lead to non-JPA related issues.
    I provided jdbc examples in #5361.

  5. sjoerd-vogel commented on Apr 14, 2026

    @sjoerd-vogel

    I am not familiar enough to really comment on internal workings of spring batch. But @fxpaquette comment rings true to me as I have had complicated setups (interacting with multiple tables) attempting to migrate from jpa to jdbc as a proof of concept fail on me as well.

  6. added 2 commits that reference this issue on Apr 15, 2026
    84a60fb
    1d23215
  7. MinChul-Son commented on Apr 15, 2026

    @MinChul-Son
    Contributor

    #5379 is my purpose. Feel free to reviewing my stuff

  8. added a commit that references this issue on May 5, 2026
  9. added a commit that references this issue on May 5, 2026
    05b2484
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions