nus-yam/ex-repair huggingface dataset:
Program: 13059
Project: 13059
Buggy source:
@Override public void run(){
  JobHolder nextJob;
  try {
    do {
      nextJob=running ? getNextJob() : null;
      if (nextJob != null) {
        if (nextJob.safeRun(nextJob.getRunCount())) {
          removeJob(nextJob);
        }
 else         if (nextJob.getBaseJob().shouldPersist()) {
          persistentJobQueue.insertOrReplace(nextJob);
        }
 else {
          nonPersistentJobQueue.insertOrReplace(nextJob);
        }
      }
    }
 while (nextJob != null);
  }
  finally {
    if (runningConsumerCount.decrementAndGet() == 0 && running) {
      ensureConsumerWhenNeeded();
    }
  }
}

Fixed version (ground truth):
@Override public void run(){
  JobHolder nextJob;
  try {
    do {
      nextJob=running ? getNextJob() : null;
      if (nextJob != null) {
        if (nextJob.safeRun(nextJob.getRunCount())) {
          removeJob(nextJob);
        }
 else         if (nextJob.getBaseJob().shouldPersist()) {
          persistentJobQueue.insertOrReplace(nextJob);
        }
 else {
          nonPersistentJobQueue.insertOrReplace(nextJob);
        }
      }
    }
 while (nextJob != null);
  }
  finally {
    if (runningConsumerCount.decrementAndGet() == 0 && running) {
      ensureConsumerWhenNeeded(null);
    }
  }
}
Program: 13060
Project: 13060
Buggy source:
/** 
 * @param context application context
 * @param id an id that is unique to this JobManager
 * @param queueFactory custom queue factory that can provide any implementation of {@link JobQueue}
 */
public JobManager(Context context,String id,QueueFactory queueFactory){
  running=true;
  sessionId=System.nanoTime();
  executor=new ThreadPoolExecutor(0,maxConsumerCount,15,TimeUnit.SECONDS,new SynchronousQueue<Runnable>(true));
  this.persistentJobQueue=queueFactory.createPersistentQueue(context,sessionId,id);
  this.nonPersistentJobQueue=queueFactory.createNonPersistent(context,sessionId,id);
  networkUtil=new NetworkUtilImpl();
  start();
}

Fixed version (ground truth):
/** 
 * @param context application context
 * @param id an id that is unique to this JobManager
 * @param queueFactory custom queue factory that can provide any implementation of {@link JobQueue}
 */
public JobManager(Context context,String id,QueueFactory queueFactory){
  appContext=context.getApplicationContext();
  running=true;
  sessionId=System.nanoTime();
  executor=new ThreadPoolExecutor(0,maxConsumerCount,15,TimeUnit.SECONDS,new SynchronousQueue<Runnable>(true));
  this.persistentJobQueue=queueFactory.createPersistentQueue(context,sessionId,id);
  this.nonPersistentJobQueue=queueFactory.createNonPersistent(context,sessionId,id);
  networkUtil=new NetworkUtilImpl();
  start();
}
Program: 13061
Project: 13061
Buggy source:
private synchronized JobHolder getNextJob(boolean nonPersistentOnly){
  JobHolder jobHolder=nonPersistentJobQueue.nextJobAndIncRunCount(true);
  if (jobHolder == null && nonPersistentOnly == false) {
    jobHolder=persistentJobQueue.nextJobAndIncRunCount(true);
  }
  return jobHolder;
}

Fixed version (ground truth):
private synchronized JobHolder getNextJob(boolean nonPersistentOnly){
  boolean haveNetwork=hasNetwork();
  JobHolder jobHolder=nonPersistentJobQueue.nextJobAndIncRunCount(haveNetwork);
  if (jobHolder == null && nonPersistentOnly == false) {
    jobHolder=persistentJobQueue.nextJobAndIncRunCount(haveNetwork);
  }
  return jobHolder;
}
Program: 13062
Project: 13062
Buggy source:
private void ensureConsumerWhenNeeded(){
  Long nextRunNs=nonPersistentJobQueue.getNextJobDelayUntilNs();
  if (nextRunNs != null && nextRunNs <= System.nanoTime()) {
    addConsumer();
    return;
  }
  Long persistedJobRunNs=persistentJobQueue.getNextJobDelayUntilNs();
  if (persistedJobRunNs != null) {
    if (nextRunNs == null) {
      nextRunNs=persistedJobRunNs;
    }
 else     if (persistedJobRunNs < nextRunNs) {
      nextRunNs=persistedJobRunNs;
    }
  }
  if (nextRunNs != null) {
    long waitNs=nextRunNs - System.nanoTime();
    if (waitNs <= 0) {
      addConsumer();
    }
 else {
      ensureConsumerOnTime(waitNs);
    }
  }
}

Fixed version (ground truth):
private void ensureConsumerWhenNeeded(Boolean hasNetwork){
  if (hasNetwork == null) {
    hasNetwork=networkUtil instanceof NetworkEventProvider ? hasNetwork() : true;
  }
  Long nextRunNs=nonPersistentJobQueue.getNextJobDelayUntilNs(hasNetwork);
  if (nextRunNs != null && nextRunNs <= System.nanoTime()) {
    addConsumer();
    return;
  }
  Long persistedJobRunNs=persistentJobQueue.getNextJobDelayUntilNs(hasNetwork);
  if (persistedJobRunNs != null) {
    if (nextRunNs == null) {
      nextRunNs=persistedJobRunNs;
    }
 else     if (persistedJobRunNs < nextRunNs) {
      nextRunNs=persistedJobRunNs;
    }
  }
  if (nextRunNs != null) {
    long waitNs=nextRunNs - System.nanoTime();
    if (waitNs <= 0) {
      addConsumer();
    }
 else {
      ensureConsumerOnTime(waitNs);
    }
  }
}
Program: 13063
Project: 13063
Buggy source:
/** 
 * Set the   {@link NetworkUtil} class to be used by the job manager.By default  {@link com.path.android.jobqueue.network.NetworkUtilImpl} will be used.
 * @param networkUtil
 */
public void setNetworkUtil(NetworkUtil networkUtil){
  this.networkUtil=networkUtil;
}

Fixed version (ground truth):
/** 
 * Set the   {@link NetworkUtil} class to be used by the job manager.By default  {@link com.path.android.jobqueue.network.NetworkUtilImpl} will be used.
 * @param networkUtil
 */
public void setNetworkUtil(NetworkUtil networkUtil){
  this.networkUtil=networkUtil;
  if (networkUtil instanceof NetworkEventProvider) {
    ((NetworkEventProvider)networkUtil).setListener(this);
  }
}
Program: 13064
Project: 13064
Buggy source:
/** 
 * Returns the next available job in the data set It should also assign the sessionId as the RunningSessionId and persist that data if necessary. It should filter out all running jobs and
 * @return
 */
JobHolder nextJobAndIncRunCount(boolean hasNetwork);

Fixed version (ground truth):
/** 
 * Returns the next available job in the data set It should also assign the sessionId as the RunningSessionId and persist that data if necessary. It should filter out all running jobs and
 * @param hasNetwork if true, should return any job, if false, should return jobs that do NOT require network
 * @return
 */
JobHolder nextJobAndIncRunCount(boolean hasNetwork);
Program: 13065
Project: 13065
Buggy source:
/** 
 * returns when the next job should run, should return null if there are no jobs to run.
 * @return
 */
Long getNextJobDelayUntilNs();

Fixed version (ground truth):
/** 
 * returns when the next job should run (in nanoseconds), should return null if there are no jobs to run.
 * @param hasNetwork if true, should return nanoseconds for any job, if false, should return nanoseconds for nextjob's delay until.
 * @return
 */
Long getNextJobDelayUntilNs(boolean hasNetwork);
Program: 13066
Project: 13066
Buggy source:
/** 
 * {@inheritDoc}
 */
@Override public JobHolder poll(){
  JobHolder delayed=queue0.peek();
  if (delayed == null) {
    return queue1.poll();
  }
  JobHolder nonDelayed=queue1.peek();
  if (nonDelayed == null) {
    queue0.remove(delayed);
    return delayed;
  }
  int cmp=retrieveComparator.compare(delayed,nonDelayed);
  if (cmp == -1) {
    queue0.remove(delayed);
    return delayed;
  }
 else {
    queue1.remove(nonDelayed);
    return nonDelayed;
  }
}

Fixed version (ground truth):
/** 
 * {@inheritDoc}
 */
@Override public JobHolder poll(){
  JobHolder delayed=queue0.peek();
  if (delayed == null) {
    return queue1.poll();
  }
  if (decideQueue(delayed) != QeueuId.Q0) {
    queue0.remove(delayed);
    queue1.add(delayed);
    return poll();
  }
  JobHolder nonDelayed=queue1.peek();
  if (nonDelayed == null) {
    queue0.remove(delayed);
    return delayed;
  }
  if (decideQueue(nonDelayed) != QeueuId.Q1) {
    queue0.add(nonDelayed);
    queue1.remove(nonDelayed);
    return poll();
  }
  int cmp=retrieveComparator.compare(delayed,nonDelayed);
  if (cmp == -1) {
    queue0.remove(delayed);
    return delayed;
  }
 else {
    queue1.remove(nonDelayed);
    return nonDelayed;
  }
}
Program: 13067
Project: 13067
Buggy source:
/** 
 * {@inheritDoc}
 */
@Override public JobHolder peek(){
  JobHolder delayed=queue0.peek();
  JobHolder nonDelayed=queue1.peek();
  if (delayed == null) {
    return nonDelayed;
  }
  if (nonDelayed == null) {
    return delayed;
  }
  int cmp=retrieveComparator.compare(delayed,nonDelayed);
  if (cmp == -1) {
    return delayed;
  }
  return nonDelayed;
}

Fixed version (ground truth):
/** 
 * {@inheritDoc}
 */
@Override public JobHolder peek(){
  JobHolder delayed=queue0.peek();
  if (delayed != null && decideQueue(delayed) != QeueuId.Q0) {
    queue1.add(delayed);
    queue0.remove(delayed);
    return peek();
  }
  JobHolder nonDelayed=queue1.peek();
  if (nonDelayed != null && decideQueue(nonDelayed) != QeueuId.Q1) {
    queue0.add(nonDelayed);
    queue1.remove(nonDelayed);
    return peek();
  }
  if (delayed == null) {
    return nonDelayed;
  }
  if (nonDelayed == null) {
    return delayed;
  }
  int cmp=retrieveComparator.compare(delayed,nonDelayed);
  if (cmp == -1) {
    return delayed;
  }
  return nonDelayed;
}
Program: 13068
Project: 13068
Buggy source:
/** 
 * @param initialCapacity paseed to {@link MergedQueue#createQueue(int,java.util.Comparator)}
 * @param comparator paseed to {@link MergedQueue#createQueue(int,java.util.Comparator)}
 * @param retrieveComparator upon retrieval, if both queues return items, this comparator is used to decide whichone should be returned
 */
public MergedQueue(int initialCapacity,Comparator<JobHolder> comparator,Comparator<JobHolder> retrieveComparator){
  this.comparator=comparator;
  this.retrieveComparator=retrieveComparator;
  queue0=createQueue(initialCapacity,comparator);
  queue1=createQueue(initialCapacity,comparator);
}

Fixed version (ground truth):
/** 
 * @param initialCapacity passed to {@link MergedQueue#createQueue(MergedQueue.QeueuId,int,java.util.Comparator)}
 * @param comparator passed to {@link MergedQueue#createQueue(MergedQueue.QeueuId,int,java.util.Comparator)}
 * @param retrieveComparator upon retrieval, if both queues return items, this comparator is used to decide whichone should be returned
 */
public MergedQueue(int initialCapacity,Comparator<JobHolder> comparator,Comparator<JobHolder> retrieveComparator){
  this.comparator=comparator;
  this.retrieveComparator=retrieveComparator;
  queue0=createQueue(QeueuId.Q0,initialCapacity,comparator);
  queue1=createQueue(QeueuId.Q1,initialCapacity,comparator);
}
Program: 13069
Project: 13069
Buggy source:
/** 
 * called when we want to create the subsequent queues
 * @param initialCapacity
 * @param comparator
 * @return
 */
abstract protected Queue<JobHolder> createQueue(int initialCapacity,Comparator<JobHolder> comparator);

Fixed version (ground truth):
/** 
 * called when we want to create the subsequent queues
 * @param initialCapacity
 * @param comparator
 * @return
 */
abstract protected Queue<JobHolder> createQueue(QeueuId qeueuId,int initialCapacity,Comparator<JobHolder> comparator);
Program: 13070
Project: 13070
Buggy source:
/** 
 * create a network aware priority queue with given initial capacity * 2 and comparator
 * @param initialCapacity
 * @param comparator
 */
public NetworkAwarePriorityQueue(int initialCapacity,Comparator<JobHolder> comparator){
  super(initialCapacity,comparator,comparator);
}

Fixed version (ground truth):
/** 
 * create a network aware priority queue with given initial capacity * 2 and comparator
 * @param initialCapacity
 * @param comparator
 */
public NetworkAwarePriorityQueue(int initialCapacity,Comparator<JobHolder> comparator){
  super(initialCapacity,comparator,new TimeAwareComparator(comparator));
}
Program: 13071
Project: 13071
Buggy source:
/** 
 * create a   {@link TimeAwarePriorityQueue}
 * @param initialCapacity
 * @param comparator
 * @return
 */
@Override protected Queue<JobHolder> createQueue(int initialCapacity,Comparator<JobHolder> comparator){
  return new TimeAwarePriorityQueue(initialCapacity,comparator);
}

Fixed version (ground truth):
/** 
 * create a   {@link TimeAwarePriorityQueue}
 * @param ignoredQueueId
 * @param initialCapacity
 * @param comparator
 * @return
 */
@Override protected Queue<JobHolder> createQueue(QeueuId ignoredQueueId,int initialCapacity,Comparator<JobHolder> comparator){
  return new TimeAwarePriorityQueue(initialCapacity,comparator);
}
Program: 13072
Project: 13072
Buggy source:
/** 
 * {@inheritDoc}
 */
@Override public Long getNextJobDelayUntilNs(){
  JobHolder next=jobs.peek();
  return next == null ? null : next.getDelayUntilNs();
}

Fixed version (ground truth):
/** 
 * {@inheritDoc}
 */
@Override public Long getNextJobDelayUntilNs(boolean hasNetwork){
  JobHolder next=jobs.peek(hasNetwork);
  return next == null ? null : next.getDelayUntilNs();
}
Program: 13073
Project: 13073
Buggy source:
/** 
 * create a   {@link PriorityQueue} with given comparator
 * @param initialCapacity
 * @param comparator
 * @return
 */
@Override protected Queue<JobHolder> createQueue(int initialCapacity,Comparator<JobHolder> comparator){
  return new PriorityQueue<JobHolder>(initialCapacity,comparator);
}

Fixed version (ground truth):
/** 
 * create a   {@link PriorityQueue} with given comparator
 * @param qeueuId
 * @param initialCapacity
 * @param comparator
 * @return
 */
@Override protected Queue<JobHolder> createQueue(QeueuId qeueuId,int initialCapacity,Comparator<JobHolder> comparator){
  if (qeueuId == QeueuId.Q0) {
    return new PriorityQueue<JobHolder>(initialCapacity,comparator);
  }
 else {
    return new PriorityQueue<JobHolder>(initialCapacity,new ConsistentTimedComparator(comparator));
  }
}
Program: 13074
Project: 13074
Buggy source:
private boolean mustSwitchToRight(){
  return numberOfRowsInBuffer == blockSize || (leftBatchHasItems == false && numberOfLeftBatchesLoadedForBlock == numberOfLeftBatchesForBlock);
}

Fixed version (ground truth):
private boolean mustSwitchToRight(){
  return left.allLoaded() || numberOfRowsInBuffer == blockSize || (leftBatchHasItems == false && numberOfLeftBatchesLoadedForBlock == numberOfLeftBatchesForBlock);
}
Program: 13075
Project: 13075
Buggy source:
public void execute(String portalName,int maxRows,ResultReceiver resultReceiver){
  if (LOGGER.isDebugEnabled()) {
    LOGGER.debug("String_Node_Str",portalName,maxRows);
  }
  Portal portal=getSafePortal(portalName);
  portal.execute(resultReceiver,maxRows);
  AnalyzedStatement analyzedStatement=portal.getLastAnalyzedStatement();
  if (analyzedStatement instanceof AnalyzedBegin) {
    portal.sync(planner,jobsLogs);
    clearState();
  }
 else   if (analyzedStatement instanceof DeallocateAnalyzedStatement) {
    String stmtToDeallocate=((DeallocateAnalyzedStatement)analyzedStatement).preparedStmtName();
    if (stmtToDeallocate != null) {
      close((byte)'S',stmtToDeallocate);
    }
 else {
      if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("String_Node_Str");
      }
      preparedStatements.clear();
    }
  }
 else {
    pendingExecutions.add(portal);
  }
}

Fixed version (ground truth):
public void execute(String portalName,int maxRows,ResultReceiver resultReceiver){
  if (LOGGER.isDebugEnabled()) {
    LOGGER.debug("String_Node_Str",portalName,maxRows);
  }
  Portal portal=getSafePortal(portalName);
  portal.execute(resultReceiver,maxRows);
  AnalyzedStatement analyzedStatement=portal.getLastAnalyzedStatement();
  if (analyzedStatement instanceof AnalyzedBegin) {
    portal.sync(planner,jobsLogs);
    clearState();
  }
 else   if (analyzedStatement instanceof DeallocateAnalyzedStatement) {
    String stmtToDeallocate=((DeallocateAnalyzedStatement)analyzedStatement).preparedStmtName();
    if (stmtToDeallocate != null) {
      close((byte)'S',stmtToDeallocate);
    }
 else {
      if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("String_Node_Str");
      }
      preparedStatements.clear();
    }
    portal.sync(planner,jobsLogs);
  }
 else {
    pendingExecutions.add(portal);
  }
}
Program: 13076
Project: 13076
Buggy source:
@Test public void testDeallocateAllClearsAllPortalsAndPreparedStatements(){
  SQLExecutor sqlExecutor=SQLExecutor.builder(clusterService).build();
  DependencyCarrier executor=Mockito.mock(DependencyCarrier.class);
  Session session=new Session(sqlExecutor.analyzer,sqlExecutor.planner,new JobsLogs(() -> false),false,executor,SessionContext.create());
  session.parse("String_Node_Str","String_Node_Str",Collections.emptyList());
  session.bind("String_Node_Str","String_Node_Str",Collections.emptyList(),null);
  session.describe('S',"String_Node_Str");
  session.parse("String_Node_Str","String_Node_Str",Collections.emptyList());
  session.bind("String_Node_Str","String_Node_Str",Collections.emptyList(),null);
  session.execute("String_Node_Str",0,new BaseResultReceiver(){
    @Override public void setNextRow(    Row row){
    }
  }
);
  assertThat(session.portals.size(),greaterThan(0));
  assertThat(session.preparedStatements.size(),is(0));
}

Fixed version (ground truth):
@Test public void testDeallocateAllClearsAllPortalsAndPreparedStatements(){
  SQLExecutor sqlExecutor=SQLExecutor.builder(clusterService).build();
  DependencyCarrier executor=mock(DependencyCarrier.class);
  when(executor.threadPool()).thenReturn(mock(ThreadPool.class));
  Session session=new Session(sqlExecutor.analyzer,sqlExecutor.planner,new JobsLogs(() -> false),false,executor,SessionContext.create());
  session.parse("String_Node_Str","String_Node_Str",Collections.emptyList());
  session.bind("String_Node_Str","String_Node_Str",Collections.emptyList(),null);
  session.describe('S',"String_Node_Str");
  session.parse("String_Node_Str","String_Node_Str",Collections.emptyList());
  session.bind("String_Node_Str","String_Node_Str",Collections.emptyList(),null);
  session.execute("String_Node_Str",0,new BaseResultReceiver());
  assertThat(session.portals.size(),greaterThan(0));
  assertThat(session.preparedStatements.size(),is(0));
}
Program: 13077
Project: 13077
Buggy source:
@Test public void testDeallocatePreparedStatementClearsPreparedStatement(){
  SQLExecutor sqlExecutor=SQLExecutor.builder(clusterService).build();
  DependencyCarrier executor=Mockito.mock(DependencyCarrier.class);
  Session session=new Session(sqlExecutor.analyzer,sqlExecutor.planner,new JobsLogs(() -> false),false,executor,SessionContext.create());
  session.parse("String_Node_Str","String_Node_Str",Collections.emptyList());
  session.bind("String_Node_Str","String_Node_Str",Collections.emptyList(),null);
  session.describe('S',"String_Node_Str");
  session.parse("String_Node_Str","String_Node_Str",Collections.emptyList());
  session.bind("String_Node_Str","String_Node_Str",Collections.emptyList(),null);
  session.execute("String_Node_Str",0,new BaseResultReceiver(){
    @Override public void setNextRow(    Row row){
    }
  }
);
  assertThat(session.portals.size(),greaterThan(0));
  assertThat(session.preparedStatements.size(),is(1));
  assertThat(session.preparedStatements.get("String_Node_Str").query(),is("String_Node_Str"));
}

Fixed version (ground truth):
@Test public void testDeallocatePreparedStatementClearsPreparedStatement(){
  SQLExecutor sqlExecutor=SQLExecutor.builder(clusterService).build();
  DependencyCarrier executor=mock(DependencyCarrier.class);
  when(executor.threadPool()).thenReturn(mock(ThreadPool.class));
  Session session=new Session(sqlExecutor.analyzer,sqlExecutor.planner,new JobsLogs(() -> false),false,executor,SessionContext.create());
  session.parse("String_Node_Str","String_Node_Str",Collections.emptyList());
  session.bind("String_Node_Str","String_Node_Str",Collections.emptyList(),null);
  session.describe('S',"String_Node_Str");
  session.parse("String_Node_Str","String_Node_Str",Collections.emptyList());
  session.bind("String_Node_Str","String_Node_Str",Collections.emptyList(),null);
  session.execute("String_Node_Str",0,new BaseResultReceiver());
  assertThat(session.portals.size(),greaterThan(0));
  assertThat(session.preparedStatements.size(),is(1));
  assertThat(session.preparedStatements.get("String_Node_Str").query(),is("String_Node_Str"));
}
Program: 13078
Project: 13078
Buggy source:
@Test public void testGetParamType(){
  SQLExecutor sqlExecutor=SQLExecutor.builder(clusterService).build();
  DependencyCarrier executor=Mockito.mock(DependencyCarrier.class);
  Session session=new Session(sqlExecutor.analyzer,sqlExecutor.planner,new JobsLogs(() -> false),false,executor,SessionContext.create());
  session.parse("String_Node_Str","String_Node_Str",Collections.emptyList());
  assertThat(session.getParamType("String_Node_Str",0),is(DataTypes.UNDEFINED));
  assertThat(session.getParamType("String_Node_Str",2),is(DataTypes.UNDEFINED));
  Session.DescribeResult describe=session.describe('S',"String_Node_Str");
  assertThat(describe.getParameters(),equalTo(new DataType[]{DataTypes.LONG,DataTypes.LONG}));
  assertThat(session.getParamType("String_Node_Str",0),is(DataTypes.LONG));
  assertThat(session.getParamType("String_Node_Str",1),is(DataTypes.LONG));
  expectedException.expect(IllegalStateException.class);
  expectedException.expectMessage("String_Node_Str");
  assertThat(session.getParamType("String_Node_Str",3),is(DataTypes.UNDEFINED));
}

Fixed version (ground truth):
@Test public void testGetParamType(){
  SQLExecutor sqlExecutor=SQLExecutor.builder(clusterService).build();
  DependencyCarrier executor=mock(DependencyCarrier.class);
  Session session=new Session(sqlExecutor.analyzer,sqlExecutor.planner,new JobsLogs(() -> false),false,executor,SessionContext.create());
  session.parse("String_Node_Str","String_Node_Str",Collections.emptyList());
  assertThat(session.getParamType("String_Node_Str",0),is(DataTypes.UNDEFINED));
  assertThat(session.getParamType("String_Node_Str",2),is(DataTypes.UNDEFINED));
  Session.DescribeResult describe=session.describe('S',"String_Node_Str");
  assertThat(describe.getParameters(),equalTo(new DataType[]{DataTypes.LONG,DataTypes.LONG}));
  assertThat(session.getParamType("String_Node_Str",0),is(DataTypes.LONG));
  assertThat(session.getParamType("String_Node_Str",1),is(DataTypes.LONG));
  expectedException.expect(IllegalStateException.class);
  expectedException.expectMessage("String_Node_Str");
  assertThat(session.getParamType("String_Node_Str",3),is(DataTypes.UNDEFINED));
}
Program: 13079
Project: 13079
Buggy source:
@Test public void testProperCleanupOnSessionClose(){
  SQLExecutor sqlExecutor=SQLExecutor.builder(clusterService).build();
  DependencyCarrier executor=Mockito.mock(DependencyCarrier.class);
  Session session=new Session(sqlExecutor.analyzer,sqlExecutor.planner,new JobsLogs(() -> false),false,executor,SessionContext.create());
  session.parse("String_Node_Str","String_Node_Str",Collections.emptyList());
  session.bind("String_Node_Str","String_Node_Str",Collections.emptyList(),null);
  session.describe('S',"String_Node_Str");
  session.parse("String_Node_Str","String_Node_Str",Collections.emptyList());
  session.bind("String_Node_Str","String_Node_Str",Collections.emptyList(),null);
  session.describe('S',"String_Node_Str");
  session.execute("String_Node_Str",0,new BaseResultReceiver());
  assertThat(session.portals.size(),is(2));
  assertThat(session.preparedStatements.size(),is(2));
  assertThat(session.pendingExecutions.size(),is(1));
  session.close();
  assertThat(session.portals.size(),is(0));
  assertThat(session.preparedStatements.size(),is(0));
  assertThat(session.pendingExecutions.size(),is(0));
}

Fixed version (ground truth):
@Test public void testProperCleanupOnSessionClose(){
  SQLExecutor sqlExecutor=SQLExecutor.builder(clusterService).build();
  DependencyCarrier executor=mock(DependencyCarrier.class);
  Session session=new Session(sqlExecutor.analyzer,sqlExecutor.planner,new JobsLogs(() -> false),false,executor,SessionContext.create());
  session.parse("String_Node_Str","String_Node_Str",Collections.emptyList());
  session.bind("String_Node_Str","String_Node_Str",Collections.emptyList(),null);
  session.describe('S',"String_Node_Str");
  session.parse("String_Node_Str","String_Node_Str",Collections.emptyList());
  session.bind("String_Node_Str","String_Node_Str",Collections.emptyList(),null);
  session.describe('S',"String_Node_Str");
  session.execute("String_Node_Str",0,new BaseResultReceiver());
  assertThat(session.portals.size(),is(2));
  assertThat(session.preparedStatements.size(),is(2));
  assertThat(session.pendingExecutions.size(),is(1));
  session.close();
  assertThat(session.portals.size(),is(0));
  assertThat(session.preparedStatements.size(),is(0));
  assertThat(session.pendingExecutions.size(),is(0));
}
Program: 13080
Project: 13080
Buggy source:
private void fetchFromUnExhausted(){
synchronized (listenersByBucketIdx) {
    Iterator<Map.Entry<Integer,PageResultListener>> iterator=listenersByBucketIdx.entrySet().iterator();
    while (iterator.hasNext()) {
      Map.Entry<Integer,PageResultListener> element=iterator.next();
      Integer key=element.getKey();
      PageResultListener resultListener=element.getValue();
      if (exhausted.contains(key)) {
        setToEmptyBucket(key);
      }
 else {
        iterator.remove();
        resultListener.needMore(true);
      }
    }
  }
}

Fixed version (ground truth):
private void fetchFromUnExhausted(){
synchronized (buckets) {
    for (    Integer bucketIdx : buckets) {
      if (exhausted.contains(bucketIdx)) {
        setToEmptyBucket(bucketIdx);
      }
 else {
        PageResultListener resultListener=listenersByBucketIdx.remove(bucketIdx);
        resultListener.needMore(true);
      }
    }
  }
}
Program: 13081
Project: 13081
Buggy source:
private void fetchExhausted(Integer exhaustedBucket){
  for (  Integer bucketIdx : bucketsByIdx.keySet()) {
    if (!bucketIdx.equals(exhaustedBucket)) {
      setToEmptyBucket(bucketIdx);
    }
  }
  PageResultListener pageResultListener;
synchronized (listenersByBucketIdx) {
    pageResultListener=listenersByBucketIdx.remove(exhaustedBucket);
  }
  pageResultListener.needMore(true);
}

Fixed version (ground truth):
private void fetchExhausted(Integer exhaustedBucket){
synchronized (buckets) {
    for (    Integer bucketIdx : buckets) {
      if (!bucketIdx.equals(exhaustedBucket)) {
        setToEmptyBucket(bucketIdx);
      }
    }
    PageResultListener pageResultListener=listenersByBucketIdx.remove(exhaustedBucket);
    pageResultListener.needMore(true);
  }
}
Program: 13082
Project: 13082
Buggy source:
private void mergeBuckets(){
  List<KeyIterable<Integer,Row>> buckets=new ArrayList<>(numBuckets);
  for (  Map.Entry<Integer,Bucket> entry : bucketsByIdx.entrySet()) {
    if (entry.getValue() != null) {
      buckets.add(new KeyIterable<>(entry.getKey(),entry.getValue()));
    }
  }
  for (  Integer integer : bucketsByIdx.keySet()) {
    bucketsByIdx.put(integer,null);
  }
  pagingIterator.merge(buckets);
}

Fixed version (ground truth):
private void mergeBuckets(){
  List<KeyIterable<Integer,Row>> buckets=new ArrayList<>(numBuckets);
synchronized (lock) {
    for (    Map.Entry<Integer,Bucket> entry : bucketsByIdx.entrySet()) {
      buckets.add(new KeyIterable<>(entry.getKey(),entry.getValue()));
    }
    bucketsByIdx.clear();
  }
  pagingIterator.merge(buckets);
}
Program: 13083
Project: 13083
Buggy source:
private void releaseListenersAndCloseContext(@Nullable Throwable throwable){
synchronized (listenersByBucketIdx) {
    for (    PageResultListener resultListener : listenersByBucketIdx.values()) {
      resultListener.needMore(false);
    }
    listenersByBucketIdx.clear();
  }
  close(throwable);
}

Fixed version (ground truth):
private void releaseListenersAndCloseContext(@Nullable Throwable throwable){
synchronized (buckets) {
    for (    PageResultListener resultListener : listenersByBucketIdx.values()) {
      resultListener.needMore(false);
    }
    listenersByBucketIdx.clear();
  }
  close(throwable);
}
Program: 13084
Project: 13084
Buggy source:
@Override public void setBucket(int bucketIdx,Bucket rows,boolean isLast,PageResultListener pageResultListener){
synchronized (listenersByBucketIdx) {
    if (lastThrowable == null) {
      listenersByBucketIdx.put(bucketIdx,pageResultListener);
    }
 else {
      pageResultListener.needMore(false);
    }
  }
  boolean shouldTriggerConsumer=false;
synchronized (lock) {
    traceLog("String_Node_Str",bucketIdx);
    if (bucketsByIdx.putIfAbsent(bucketIdx,rows) != null) {
      kill(new IllegalStateException(String.format(Locale.ENGLISH,"String_Node_Str",nodeName,id,bucketIdx)));
    }
    setExhaustedUpstreams();
    if (isLast) {
      exhausted.add(bucketIdx);
    }
    if (bucketsByIdx.size() == numBuckets) {
      shouldTriggerConsumer=true;
    }
  }
  if (shouldTriggerConsumer) {
    mergeAndTriggerConsumer();
  }
}

Fixed version (ground truth):
@Override public void setBucket(int bucketIdx,Bucket rows,boolean isLast,PageResultListener pageResultListener){
synchronized (buckets) {
    buckets.add(bucketIdx);
    if (lastThrowable == null) {
      listenersByBucketIdx.put(bucketIdx,pageResultListener);
    }
 else {
      pageResultListener.needMore(false);
    }
  }
  boolean shouldTriggerConsumer=false;
synchronized (lock) {
    traceLog("String_Node_Str",bucketIdx);
    if (bucketsByIdx.putIfAbsent(bucketIdx,rows) != null) {
      kill(new IllegalStateException(String.format(Locale.ENGLISH,"String_Node_Str",nodeName,id,bucketIdx)));
    }
    setExhaustedUpstreams();
    if (isLast) {
      exhausted.add(bucketIdx);
    }
    if (bucketsByIdx.size() == numBuckets) {
      shouldTriggerConsumer=true;
    }
  }
  if (shouldTriggerConsumer) {
    mergeAndTriggerConsumer();
  }
}
Program: 13085
Project: 13085
Buggy source:
public PageDownstreamContext(Logger logger,String nodeName,int id,String name,RowConsumer rowConsumer,PagingIterator<Integer,Row> pagingIterator,Streamer<?>[] streamers,RamAccountingContext ramAccountingContext,int numBuckets){
  super(id,logger);
  this.nodeName=nodeName;
  this.name=name;
  this.streamers=streamers;
  this.ramAccountingContext=ramAccountingContext;
  this.numBuckets=numBuckets;
  traceEnabled=logger.isTraceEnabled();
  this.exhausted=new HashSet<>(numBuckets);
  this.pagingIterator=pagingIterator;
  this.bucketsByIdx=new HashMap<>(numBuckets);
  this.listenersByBucketIdx=new HashMap<>(numBuckets);
  batchPagingIterator=new BatchPagingIterator<>(pagingIterator,this::fetchMore,this::allUpstreamsExhausted,() -> releaseListenersAndCloseContext(null));
  this.consumer=rowConsumer;
}

Fixed version (ground truth):
public PageDownstreamContext(Logger logger,String nodeName,int id,String name,RowConsumer rowConsumer,PagingIterator<Integer,Row> pagingIterator,Streamer<?>[] streamers,RamAccountingContext ramAccountingContext,int numBuckets){
  super(id,logger);
  this.nodeName=nodeName;
  this.name=name;
  this.streamers=streamers;
  this.ramAccountingContext=ramAccountingContext;
  this.numBuckets=numBuckets;
  this.buckets=new HashSet<>(numBuckets);
  traceEnabled=logger.isTraceEnabled();
  this.exhausted=new HashSet<>(numBuckets);
  this.pagingIterator=pagingIterator;
  this.bucketsByIdx=new HashMap<>(numBuckets);
  this.listenersByBucketIdx=new HashMap<>(numBuckets);
  batchPagingIterator=new BatchPagingIterator<>(pagingIterator,this::fetchMore,this::allUpstreamsExhausted,() -> releaseListenersAndCloseContext(null));
  this.consumer=rowConsumer;
}
Program: 13086
Project: 13086
Buggy source:
@Override public void needMore(boolean needMore){
  if (needMore) {
    ctx.setBucket(0,b11,true,mock(PageResultListener.class));
  }
}

Fixed version (ground truth):
@Override public void needMore(boolean needMore){
  needMoreResult=needMore;
}
Program: 13087
Project: 13087
Buggy source:
/** 
 * Partition the items of a BatchIterator into blocks of   {@code size}. Example: <pre> inputBi: [1, 2, 3, 4, 5] partition(inputBi, 2, ArrayList::new, List::add) -> [[1, 2], [3, 4], [5]] </pre>
 * @param supplier Used to create the state per partition
 * @param accumulator Used to add items to the partitions state
 * @param stateLimiter Used to dynamically adjust the partition size.
 * @param < T > input item type
 * @param < A > output item type
 */
public static <T,A>BatchIterator<A> partition(BatchIterator<T> bi,int size,Supplier<A> supplier,BiConsumer<A,T> accumulator,Predicate<A> stateLimiter){
  return new MappedForwardingBatchIterator<T,A>(){
    private A element=null;
    private A state=supplier.get();
    private int idx=0;
    @Override protected BatchIterator<T> delegate(){
      return bi;
    }
    @Override public boolean moveNext(){
      boolean stateLimitReached=false;
      while (idx < size && stateLimitReached == false && bi.moveNext()) {
        accumulator.accept(state,bi.currentElement());
        stateLimitReached=stateLimiter.test(state);
        idx++;
      }
      if (idx == size || stateLimitReached || (idx > 0 && bi.allLoaded())) {
        element=state;
        state=supplier.get();
        idx=0;
        return true;
      }
      element=null;
      return false;
    }
    @Override public A currentElement(){
      return element;
    }
  }
;
}

Fixed version (ground truth):
/** 
 * Partition the items of a BatchIterator into blocks of   {@code size}. Example: <pre>  {@code inputBi: [1, 2, 3, 4, 5] partition(inputBi, 2, ArrayList::new, List::add) -> [[1, 2], [3, 4], [5]]}</pre>
 * @param supplier Used to create the state per partition
 * @param accumulator Used to add items to the partitions state
 * @param stateLimiter Used to dynamically adjust the partition size.
 * @param < T > input item type
 * @param < A > output item type
 */
public static <T,A>BatchIterator<A> partition(BatchIterator<T> bi,int size,Supplier<A> supplier,BiConsumer<A,T> accumulator,Predicate<A> stateLimiter){
  return new MappedForwardingBatchIterator<T,A>(){
    private A element=null;
    private A state=supplier.get();
    private int idx=0;
    @Override protected BatchIterator<T> delegate(){
      return bi;
    }
    @Override public boolean moveNext(){
      boolean stateLimitReached=false;
      while (idx < size && stateLimitReached == false && bi.moveNext()) {
        accumulator.accept(state,bi.currentElement());
        stateLimitReached=stateLimiter.test(state);
        idx++;
      }
      if (idx == size || stateLimitReached || (idx > 0 && bi.allLoaded())) {
        element=state;
        state=supplier.get();
        idx=0;
        return true;
      }
      element=null;
      return false;
    }
    @Override public A currentElement(){
      return element;
    }
  }
;
}
Program: 13088
Project: 13088
Buggy source:
/** 
 * Interrupt the operation, increasing the likelihood that it will terminate early with an error. This method can be called concurrently from a different thread while an operation is running. Implementations must: - terminate if they're otherwise waiting for input/data - terminate expensive & long running operations within a reasonable amount of time (< 2sec) Fast operations which are already running and can complete without further input may ignore the kill. Operations which have already completed may also ignore the kill.
 * @param throwable the reason for the interruption or null if there is none.
 */
void kill(@Nonnull Throwable throwable);

Fixed version (ground truth):
/** 
 * <p> Interrupt the operation, increasing the likelihood that it will terminate early with an error. This method can be called concurrently from a different thread while an operation is running. </p> Implementations must: <ul> <li>terminate if they're otherwise waiting for input/data</li> <li>terminate expensive and long running operations within a reasonable amount of time (&lt; 2sec)</li> </ul> Fast operations which are already running and can complete without further input may ignore the kill. Operations which have already completed may also ignore the kill.
 * @param throwable the reason for the interruption or null if there is none.
 */
void kill(@Nonnull Throwable throwable);
Program: 13089
Project: 13089
Buggy source:
public ExtendedOsStats(Cpu cpu){
  this.cpu=cpu;
}

Fixed version (ground truth):
public ExtendedOsStats(Cpu cpu,OsStats osStats){
  this.cpu=cpu;
  this.osStats=osStats;
}
Program: 13090
Project: 13090
Buggy source:
public void cpu(Cpu cpu){
  this.cpu=cpu;
}

Fixed version (ground truth):
@VisibleForTesting public void cpu(Cpu cpu){
  this.cpu=cpu;
}
Program: 13091
Project: 13091
Buggy source:
@Override public ExtendedOsStats osStats(){
  return OS_STATS;
}

Fixed version (ground truth):
@Override public ExtendedOsStats osStats(){
  return osStatsCache.getOrRefresh();
}
Program: 13092
Project: 13092
Buggy source:
private ExtendedOsStats osStatsProbe(){
  Sigar sigar=sigarService.sigar();
  ExtendedOsStats.Cpu cpu;
  try {
    CpuPerc cpuPerc=sigar.getCpuPerc();
    cpu=new ExtendedOsStats.Cpu((short)Math.round(cpuPerc.getSys() * 100),(short)Math.round(cpuPerc.getUser() * 100),(short)Math.round(cpuPerc.getIdle() * 100),(short)Math.round(cpuPerc.getStolen() * 100));
  }
 catch (  SigarException e) {
    cpu=new ExtendedOsStats.Cpu();
  }
  ExtendedOsStats stats=new ExtendedOsStats(cpu);
  stats.timestamp(System.currentTimeMillis());
  try {
    stats.loadAverage(sigar.getLoadAverage());
  }
 catch (  SigarException e) {
  }
  try {
    stats.uptime((long)sigar.getUptime().getUptime());
  }
 catch (  SigarException e) {
  }
  return stats;
}

Fixed version (ground truth):
private ExtendedOsStats osStatsProbe(){
  Sigar sigar=sigarService.sigar();
  ExtendedOsStats.Cpu cpu;
  OsStats osStats=OsProbe.getInstance().osStats();
  try {
    CpuPerc cpuPerc=sigar.getCpuPerc();
    cpu=new ExtendedOsStats.Cpu((short)Math.round(cpuPerc.getSys() * 100),(short)Math.round(cpuPerc.getUser() * 100),(short)Math.round(cpuPerc.getIdle() * 100),(short)Math.round(cpuPerc.getStolen() * 100));
  }
 catch (  SigarException e) {
    cpu=new ExtendedOsStats.Cpu();
  }
  ExtendedOsStats stats=new ExtendedOsStats(cpu,osStats);
  stats.timestamp(System.currentTimeMillis());
  try {
    stats.loadAverage(sigar.getLoadAverage());
  }
 catch (  SigarException e) {
  }
  try {
    stats.uptime((long)sigar.getUptime().getUptime());
  }
 catch (  SigarException e) {
  }
  return stats;
}
Program: 13093
Project: 13093
Buggy source:
@Override public R value(){
  if (row.isComplete()) {
    OsStats.Cgroup cgroup=row.osStats().getCgroup();
    if (cgroup == null) {
      return null;
    }
    return getter.apply(cgroup);
  }
  return null;
}

Fixed version (ground truth):
@Override public R value(){
  if (row.isComplete()) {
    OsStats.Cgroup cgroup=row.extendedOsStats().osStats().getCgroup();
    if (cgroup != null) {
      return getter.apply(cgroup);
    }
  }
  return null;
}
Program: 13094
Project: 13094
Buggy source:
@Override public Map<String,Object> value(){
  if (row.isComplete()) {
    OsStats.Cgroup cgroup=row.osStats().getCgroup();
    if (cgroup == null) {
      return null;
    }
    return super.value();
  }
  return null;
}

Fixed version (ground truth):
@Override public Map<String,Object> value(){
  if (row.isComplete()) {
    OsStats.Cgroup cgroup=row.extendedOsStats().osStats().getCgroup();
    if (cgroup != null) {
      return super.value();
    }
  }
  return null;
}
Program: 13095
Project: 13095
Buggy source:
@Test public void testSysNodesCgroup() throws Exception {
  if (Constants.LINUX) {
    SQLResponse response=execute("String_Node_Str" + "String_Node_Str" + "String_Node_Str"+ "String_Node_Str"+ "String_Node_Str"+ "String_Node_Str"+ "String_Node_Str"+ "String_Node_Str"+ "String_Node_Str"+ "String_Node_Str");
    assertThat(response.rowCount(),is(1L));
    assertThat((String)response.rows()[0][0],containsString("String_Node_Str"));
    assertThat((long)response.rows()[0][1],greaterThanOrEqualTo(-1L));
    assertThat((String)response.rows()[0][2],containsString("String_Node_Str"));
    assertThat((long)response.rows()[0][3],greaterThanOrEqualTo(-1L));
    assertThat((long)response.rows()[0][4],greaterThanOrEqualTo(-1L));
    assertThat((long)response.rows()[0][5],greaterThanOrEqualTo(-1L));
    assertThat((long)response.rows()[0][6],greaterThanOrEqualTo(-1L));
    assertThat((long)response.rows()[0][7],greaterThanOrEqualTo(-1L));
  }
 else {
    response=execute("String_Node_Str" + "String_Node_Str" + "String_Node_Str"+ "String_Node_Str"+ "String_Node_Str"+ "String_Node_Str"+ "String_Node_Str"+ "String_Node_Str"+ "String_Node_Str"+ "String_Node_Str"+ "String_Node_Str"+ "String_Node_Str");
    assertThat(response.rowCount(),is(1L));
    for (int i=0; i <= 10; i++) {
      assertNull(response.rows()[0][i]);
    }
  }
}

Fixed version (ground truth):
@Test public void testSysNodesCgroup() throws Exception {
  if (Constants.LINUX) {
    SQLResponse response=execute("String_Node_Str" + "String_Node_Str" + "String_Node_Str"+ "String_Node_Str"+ "String_Node_Str"+ "String_Node_Str"+ "String_Node_Str"+ "String_Node_Str"+ "String_Node_Str"+ "String_Node_Str");
    assertThat(response.rowCount(),is(1L));
    assertThat(response.rows()[0][0],notNullValue());
    assertThat((long)response.rows()[0][1],greaterThanOrEqualTo(0L));
    assertThat(response.rows()[0][2],notNullValue());
    assertThat((long)response.rows()[0][3],greaterThanOrEqualTo(0L));
    assertThat((long)response.rows()[0][4],anyOf(equalTo(-1L),greaterThanOrEqualTo(0L)));
    assertThat((long)response.rows()[0][5],greaterThanOrEqualTo(0L));
    assertThat((long)response.rows()[0][6],greaterThanOrEqualTo(0L));
    assertThat((long)response.rows()[0][7],greaterThanOrEqualTo(0L));
  }
 else {
    response=execute("String_Node_Str" + "String_Node_Str" + "String_Node_Str"+ "String_Node_Str"+ "String_Node_Str"+ "String_Node_Str"+ "String_Node_Str"+ "String_Node_Str"+ "String_Node_Str"+ "String_Node_Str"+ "String_Node_Str"+ "String_Node_Str");
    assertThat(response.rowCount(),is(1L));
    for (int i=0; i <= 10; i++) {
      assertNull(response.rows()[0][i]);
    }
  }
}
Program: 13096
Project: 13096
Buggy source:
@Override public ExtendedOsStats osStats(){
  ExtendedOsStats.Cpu cpuStats=new ExtendedOsStats.Cpu((short)0,(short)4,(short)94,(short)10);
  ExtendedOsStats osStats=new ExtendedOsStats(cpuStats);
  osStats.uptime(3600L);
  osStats.loadAverage(new double[]{1,5,15});
  return osStats;
}

Fixed version (ground truth):
@Override public ExtendedOsStats osStats(){
  ExtendedOsStats.Cpu cpuStats=new ExtendedOsStats.Cpu((short)0,(short)4,(short)94,(short)10);
  OsStats osStats=OsProbe.getInstance().osStats();
  ExtendedOsStats extendedOsStats=new ExtendedOsStats(cpuStats,osStats);
  extendedOsStats.uptime(3600L);
  extendedOsStats.loadAverage(new double[]{1,5,15});
  return extendedOsStats;
}
Program: 13097
Project: 13097
Buggy source:
static final CompletableFuture<Long> execute(BiConsumer<ClusterRerouteRequest,ActionListener<ClusterRerouteResponse>> rerouteAction,RerouteAnalyzedStatement stmt,Row parameters){
  ClusterRerouteRequest request;
  try {
    request=prepareRequest(stmt,parameters);
  }
 catch (  Throwable t) {
    return failedFuture(t);
  }
  FutureActionListener<ClusterRerouteResponse,Long> listener=new FutureActionListener<>(r -> r.isAcknowledged() ? 1L : -1L);
  rerouteAction.accept(request,listener);
  return listener;
}

Fixed version (ground truth):
public static CompletableFuture<Long> execute(BiConsumer<ClusterRerouteRequest,ActionListener<ClusterRerouteResponse>> rerouteAction,RerouteAnalyzedStatement stmt,Row parameters){
  ClusterRerouteRequest request;
  try {
    request=prepareRequest(stmt,parameters);
  }
 catch (  Throwable t) {
    return failedFuture(t);
  }
  FutureActionListener<ClusterRerouteResponse,Long> listener=new FutureActionListener<>(r -> r.isAcknowledged() ? 1L : -1L);
  rerouteAction.accept(request,listener);
  return listener;
}
Program: 13100
Project: 13100
Buggy source:
public MultiSourceSelect(Map<QualifiedName,AnalyzedRelation> sources,Collection<? extends Path> outputNames,QuerySpec querySpec,List<JoinPair> joinPairs){
}

Fixed version (ground truth):
public MultiSourceSelect(MultiSourceSelect mss,QuerySpec querySpec){
  this.sources=mss.sources;
  this.joinPairs=mss.joinPairs;
  this.splitter=new RelationSplitter(querySpec,sources.values().stream().map(rs -> rs.relation()).collect(Collectors.toList()),joinPairs);
  this.querySpec=querySpec;
  this.fields=mss.fields;
}
Program: 13101
Project: 13101
Buggy source:
@Override public AnalyzedRelation visitMultiSourceSelect(MultiSourceSelect mss,TransactionContext context){
  QuerySpec querySpec=mss.querySpec();
  querySpec.normalize(normalizer,context);
  mss=new MultiSourceSelect(Maps.transformValues(mss.sources(),RelationSource::relation),mss.fields(),querySpec,mss.joinPairs());
  mss.pushDownQuerySpecs();
  if (mss.sources().size() == 2) {
    Iterator<RelationSource> it=mss.sources().values().iterator();
    RelationSource leftSource=it.next();
    RelationSource rightSource=it.next();
    QualifiedName left=leftSource.qualifiedName();
    QualifiedName right=rightSource.qualifiedName();
    Rewriter.tryRewriteOuterToInnerJoin(normalizer,JoinPairs.ofRelationsWithMergedConditions(left,right,mss.joinPairs(),false),mss.querySpec(),left,right,leftSource.querySpec(),rightSource.querySpec());
  }
  return mss;
}

Fixed version (ground truth):
@Override public AnalyzedRelation visitMultiSourceSelect(MultiSourceSelect mss,TransactionContext context){
  QuerySpec querySpec=mss.querySpec();
  querySpec.normalize(normalizer,context);
  mss=new MultiSourceSelect(mss,querySpec);
  mss.pushDownQuerySpecs();
  if (mss.sources().size() == 2) {
    Iterator<RelationSource> it=mss.sources().values().iterator();
    RelationSource leftSource=it.next();
    RelationSource rightSource=it.next();
    QualifiedName left=leftSource.qualifiedName();
    QualifiedName right=rightSource.qualifiedName();
    Rewriter.tryRewriteOuterToInnerJoin(normalizer,JoinPairs.ofRelationsWithMergedConditions(left,right,mss.joinPairs(),false),mss.querySpec(),left,right,leftSource.querySpec(),rightSource.querySpec());
  }
  return mss;
}
Program: 13102
Project: 13102
Buggy source:
@Test public void testNestedSimpleSelectUsesFetch() throws Exception {
  QueryThenFetch qtf=e.plan("String_Node_Str");
  Collect collect=(Collect)qtf.subPlan();
  assertThat(collect.collectPhase().projections(),Matchers.contains(instanceOf(TopNProjection.class),instanceOf(TopNProjection.class),instanceOf(FetchProjection.class),instanceOf(OrderedTopNProjection.class)));
}

Fixed version (ground truth):
@Test public void testNestedSimpleSelectUsesFetch() throws Exception {
  QueryThenFetch qtf=e.plan("String_Node_Str");
  List<Projection> projections=((Collect)qtf.subPlan()).collectPhase().projections();
  assertThat(projections,Matchers.contains(instanceOf(TopNProjection.class),instanceOf(TopNProjection.class),instanceOf(FetchProjection.class),instanceOf(OrderedTopNProjection.class)));
  assertThat(projections.get(3).outputs(),isSQL("String_Node_Str"));
}
Program: 13103
Project: 13103
Buggy source:
private MultiConsumer(int numAccepts,BatchConsumer consumer,Function<BatchIterator[],BatchIterator> compositeBatchIteratorFactory){
  this.remainingAccepts=new AtomicInteger(numAccepts);
  this.iterators=new BatchIterator[numAccepts];
  this.consumer=consumer;
  this.compositeBatchIteratorFactory=compositeBatchIteratorFactory;
}

Fixed version (ground truth):
private MultiConsumer(int numAccepts,BatchConsumer consumer,Function<BatchIterator[],BatchIterator> compositeBatchIteratorFactory){
  this.remainingAccepts=numAccepts;
  this.iterators=new BatchIterator[numAccepts];
  this.consumer=consumer;
  this.compositeBatchIteratorFactory=compositeBatchIteratorFactory;
}
Program: 13104
Project: 13104
Buggy source:
@Override public void accept(BatchIterator iterator,@Nullable Throwable failure){
  int remaining=remainingAccepts.decrementAndGet();
  if (failure != null) {
    lastFailure=failure;
  }
synchronized (iterators) {
    iterators[remaining]=iterator;
  }
  if (remaining == 0) {
    if (lastFailure == null) {
      consumer.accept(compositeBatchIteratorFactory.apply(iterators),null);
    }
 else {
      consumer.accept(null,lastFailure);
    }
  }
}

Fixed version (ground truth):
@Override public void accept(BatchIterator iterator,@Nullable Throwable failure){
  int remaining;
synchronized (iterators) {
    remainingAccepts--;
    remaining=remainingAccepts;
    if (failure != null) {
      lastFailure=failure;
    }
    iterators[remaining]=iterator;
  }
  if (remaining == 0) {
    if (lastFailure == null) {
      consumer.accept(compositeBatchIteratorFactory.apply(iterators),null);
    }
 else {
      consumer.accept(null,lastFailure);
    }
  }
}