bitflicker64 commented on code in PR #3395: URL: https://github.com/apache/hugegraph/pull/3395#discussion_r4353907817
########## hugegraph-store/hg-store-test/src/main/java/org/apache/hugegraph/store/node/grpc/query/FilterIteratorContractTest.java: ########## @@ -0,0 +1,307 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.hugegraph.store.node.grpc.query; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +import org.apache.hugegraph.rocksdb.access.RocksDBSession.BackendColumn; +import org.apache.hugegraph.rocksdb.access.ScanIterator; +import org.apache.hugegraph.store.business.itrv2.IntersectionFilterIterator; +import org.apache.hugegraph.store.business.itrv2.IntersectionWrapper; +import org.apache.hugegraph.store.business.itrv2.MapValueFilterIterator; +import org.apache.hugegraph.store.business.itrv2.UnionFilterIterator; +import org.apache.hugegraph.store.business.itrv2.io.SortShuffleSerializer; +import org.apache.hugegraph.store.grpc.query.QueryRequest; +import org.apache.hugegraph.store.grpc.query.QueryResponse; +import org.apache.hugegraph.store.node.grpc.query.model.QueryPlan; +import org.junit.Test; + +import io.grpc.stub.StreamObserver; + +public class FilterIteratorContractTest extends AggregativeQueryTestSupport { + + @Test + public void testMapFilterSupportsDirectNextAndRepeatedProbes() { + Map<String, Integer> counts = new LinkedHashMap<>(); + counts.put("skip-first", 1); + counts.put("first", 2); + counts.put("skip-middle", 3); + counts.put("second", 2); + counts.put("third", 2); + counts.put("skip-last", 0); + Iterator<String> iterator = new MapValueFilterIterator<>(counts, count -> count == 2); + + assertEquals("first", iterator.next()); + assertTrue(iterator.hasNext()); + assertTrue(iterator.hasNext()); + assertEquals("second", iterator.next()); + assertEquals("third", iterator.next()); + assertFalse(iterator.hasNext()); + assertFalse(iterator.hasNext()); + assertThrows(NoSuchElementException.class, iterator::next); + } + + @Test + public void testMapFilterDoesNotRepeatConsumedValue() { + Iterator<String> iterator = new MapValueFilterIterator<>(Map.of("only", 1), count -> count > 0); + + assertTrue(iterator.hasNext()); + assertEquals("only", iterator.next()); + assertThrows(NoSuchElementException.class, iterator::next); + assertFalse(iterator.hasNext()); + } + + @Test + public void testEmptyAndRejectedMapsRemainExhausted() { + for (Map<String, Integer> counts : List.of(Map.<String, Integer>of(), Map.of("rejected", 1))) { + Iterator<String> iterator = new MapValueFilterIterator<>(counts, count -> count == 2); + assertFalse(iterator.hasNext()); + assertFalse(iterator.hasNext()); + assertThrows(NoSuchElementException.class, iterator::next); + } + } + + @Test + public void testUnionUniqueStreamPreservesPendingResults() { + assertFilterContract(FilterKind.UNION_UNIQUE); + } + + @Test + public void testUnionBufferedResultsPreservePendingResults() { + assertFilterContract(FilterKind.UNION_BUFFERED); + } + + @Test + public void testIntersectionInMemoryPreservesPendingResults() { + assertFilterContract(FilterKind.INTERSECTION); + } + + @Test + public void testEmptyUnionRemainsExhausted() { + IntersectionWrapper<BackendColumn> wrapper = new IntersectionWrapper<>( + new RowIterator(List.of()), column -> column.name[0]); + wrapper.proc(); + try (ScanIterator iterator = new UnionFilterIterator<>(new RowIterator(List.of()), wrapper, + BackendColumn::compareTo, + SortShuffleSerializer.ofBackendColumnSerializer())) { + assertFalse(iterator.hasNext()); + assertFalse(iterator.hasNext()); + assertThrows(NoSuchElementException.class, iterator::next); + } + } + + @Test + public void testCloseDiscardsPendingResultsWithoutProbingClosedSource() { + for (FilterKind kind : FilterKind.values()) { + FilterFixture fixture = filter(kind); + assertTrue(fixture.iterator.hasNext()); + + fixture.iterator.close(); + + assertClosedWithoutProbingSource(fixture); + } + } + + @Test + public void testCloseFailureStillDiscardsPendingResultsAndStopsProbing() { + for (FilterKind kind : FilterKind.values()) { + FilterFixture fixture = filter(kind); + IllegalStateException failure = new IllegalStateException("source close failed"); + fixture.source.closeFailure = failure; + assertTrue(fixture.iterator.hasNext()); + + assertSame(failure, assertThrows(IllegalStateException.class, fixture.iterator::close)); + + assertClosedWithoutProbingSource(fixture); + } + } + + @Test(timeout = 5000) + public void testUnionUniqueStreamDoesNotLoseRecordsBetweenSingleRecordBatches() throws Exception { + assertSingleRecordBatches(FilterKind.UNION_UNIQUE); + } + + @Test(timeout = 5000) + public void testUnionBufferedResultsDoNotLoseRecordsBetweenSingleRecordBatches() throws Exception { + assertSingleRecordBatches(FilterKind.UNION_BUFFERED); + } + + @Test(timeout = 5000) + public void testIntersectionDoesNotLoseRecordsBetweenSingleRecordBatches() throws Exception { + assertSingleRecordBatches(FilterKind.INTERSECTION); + } + + private static void assertFilterContract(FilterKind kind) { + FilterFixture fixture = filter(kind); + List<Integer> keys = new ArrayList<>(); + try (ScanIterator iterator = fixture.iterator) { + // Intersection initializes its reduction on the first probe; keep that API unchanged. + if (kind == FilterKind.INTERSECTION) { + assertTrue(iterator.hasNext()); + assertTrue(iterator.hasNext()); + } + BackendColumn first = iterator.next(); + keys.add((int) first.name[0]); + while (iterator.hasNext()) { + assertTrue(iterator.hasNext()); + assertTrue(iterator.hasNext()); + BackendColumn column = iterator.next(); + keys.add((int) column.name[0]); + } + assertFalse(iterator.hasNext()); + assertThrows(NoSuchElementException.class, iterator::next); + } + keys.sort(Integer::compareTo); + assertEquals(List.of(1, 2, 3), keys); + assertTrue(fixture.source.closed); + } + + private static void assertClosedWithoutProbingSource(FilterFixture fixture) { + int probes = fixture.source.probes; + assertFalse(fixture.iterator.hasNext()); + assertFalse(fixture.iterator.hasNext()); + assertFalse(fixture.iterator.isValid()); + assertThrows(NoSuchElementException.class, fixture.iterator::next); + assertEquals(probes, fixture.source.probes); + assertTrue(fixture.source.closed); + } + + private static void assertSingleRecordBatches(FilterKind kind) throws Exception { + FilterFixture fixture = filter(kind); + ThreadPoolExecutor pool = pool(1); + QueryPlan plan = new QueryPlan(); + AggregativeQueryService service = new AggregativeQueryService(pool, 500, 1) { + @Override + AggregativeQueryObserver newObserver(StreamObserver<QueryResponse> sender) { + return fixture(super.newObserver(sender), fixture.iterator, plan, null); + } + }; + ResponseRecorder response = new ResponseRecorder(); + try { + service.query(response).onNext(QueryRequest.newBuilder().setQueryId(kind.name()).build()); + assertTrue(response.finished.await(2, TimeUnit.SECONDS)); + + List<Integer> keys = new ArrayList<>(); + assertEquals(3, response.responses.size()); + for (int i = 0; i < response.responses.size(); i++) { + QueryResponse batch = response.responses.get(i); + assertTrue(batch.getIsOk()); + assertEquals(kind.name(), batch.getQueryId()); + assertEquals(1, batch.getDataCount()); + assertEquals(i == response.responses.size() - 1, batch.getIsFinished()); + keys.add((int) batch.getData(0).getKey().byteAt(0)); + } + keys.sort(Integer::compareTo); + assertEquals(List.of(1, 2, 3), keys); + assertEquals(1, response.completed.get()); + assertEquals(0, response.errors.get()); + assertTrue(fixture.source.closed); + service.shutdownQueries(); + } finally { + pool.shutdownNow(); + pool.awaitTermination(1, TimeUnit.SECONDS); + fixture.iterator.close(); + } + } + + private static FilterFixture filter(FilterKind kind) { + BackendColumn first = BackendColumn.of(new byte[]{1}, new byte[]{11}); + BackendColumn second = BackendColumn.of(new byte[]{2}, new byte[]{12}); + BackendColumn third = BackendColumn.of(new byte[]{3}, new byte[]{13}); + List<BackendColumn> rows = kind == FilterKind.UNION_UNIQUE ? List.of(first, second, third) : + Arrays.asList(first, second, third, first, second, third); Review Comment: Important: these fixtures reuse three BackendColumn objects, so the counts here merge rows by identity. BackendColumn overrides equals but not hashCode (RocksDBSession.java:1075), and real scans build a new object per row (RocksDBScanIterator.java:179). With a new object per row, IntersectionFilterIterator (size 2) over 100 keys read twice returns 0 rows instead of 100, and UnionFilterIterator returns 200 instead of 100. Only the in-memory paths are affected (below 100000 intersection or up to 10000 union candidates); the intersection spill path compares by name and is correct. Older than this PR and not blocking. Could the fixtures build a new BackendColumn.of(...) per row, with hashCode from name and value added here or in a follow-up issue? -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
