From 6b422ab82681d5e939e43eae2ebff0379a222199 Mon Sep 17 00:00:00 2001 From: Claus Stadler Date: Sun, 14 Jun 2026 18:07:48 +0200 Subject: [PATCH 1/3] GH-3994: Improved TDB2 index access for single pattern queries Co-authored-by: Rob Vesse --- .../apache/jena/dboe/base/record/Record.java | 49 ++ .../BPTreeDistinctKeyPrefixIterator.java | 45 +- .../jena/dboe/trans/bplustree/BPlusTree.java | 8 + .../geosparql/spatial/task/BasicTask.java | 2 +- jena-tdb2/pom.xml | 9 +- .../jena/tdb2/solver/OpExecutorTDB2.java | 33 +- .../tdb2/solver/skipscan/CandidateIndex.java | 32 + .../tdb2/solver/skipscan/EqualityLink.java | 30 + .../jena/tdb2/solver/skipscan/IndexMap.java | 43 ++ .../jena/tdb2/solver/skipscan/IndexMatch.java | 46 ++ .../tdb2/solver/skipscan/NodeIdUtils.java | 56 ++ .../skipscan/OpExecutorTDB2SkipScan.java | 601 ++++++++++++++++++ .../tdb2/solver/skipscan/OpExtSkipScan.java | 96 +++ .../tdb2/solver/skipscan/PatternQuery.java | 233 +++++++ .../solver/skipscan/SkipScanCandidate.java | 29 + .../tdb2/solver/skipscan/SkipScanRewrite.java | 253 ++++++++ .../skipscan/TransformDistinctPlacement.java | 239 +++++++ .../solver/skipscan/TransformSkipScan.java | 47 ++ .../solver/skipscan/TuplePatternSpec.java | 147 +++++ .../tdb2/solver/skipscan/ValueFilter.java | 25 + .../jena/tdb2/solver/skipscan/VarMap.java | 27 + .../org/apache/jena/tdb2/sys/SystemTDB.java | 5 + .../skipscan/AbstractDatasetGraphCompare.java | 149 +++++ .../GraphCompareSelectResultExecutable.java | 111 ++++ ...CompareSelectResultExecutableSkipScan.java | 64 ++ .../tdb2/solver/skipscan/TS_TDB_SkipScan.java | 35 + .../skipscan/TestAggregatorsSkipScan.java | 136 ++++ .../solver/skipscan/TestFindBestIndex.java | 140 ++++ .../skipscan/TestOpExecutorTDB2SkipScan.java | 350 ++++++++++ .../TestTransformDistinctPlacement.java | 360 +++++++++++ .../jena/tdb2/store/Test_SPARQL_TDB.java | 81 ++- 31 files changed, 3469 insertions(+), 12 deletions(-) create mode 100644 jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/CandidateIndex.java create mode 100644 jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/EqualityLink.java create mode 100644 jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/IndexMap.java create mode 100644 jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/IndexMatch.java create mode 100644 jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/NodeIdUtils.java create mode 100644 jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/OpExecutorTDB2SkipScan.java create mode 100644 jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/OpExtSkipScan.java create mode 100644 jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/PatternQuery.java create mode 100644 jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/SkipScanCandidate.java create mode 100644 jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/SkipScanRewrite.java create mode 100644 jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/TransformDistinctPlacement.java create mode 100644 jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/TransformSkipScan.java create mode 100644 jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/TuplePatternSpec.java create mode 100644 jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/ValueFilter.java create mode 100644 jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/VarMap.java create mode 100644 jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan/AbstractDatasetGraphCompare.java create mode 100644 jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan/GraphCompareSelectResultExecutable.java create mode 100644 jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan/GraphCompareSelectResultExecutableSkipScan.java create mode 100644 jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan/TS_TDB_SkipScan.java create mode 100644 jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan/TestAggregatorsSkipScan.java create mode 100644 jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan/TestFindBestIndex.java create mode 100644 jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan/TestOpExecutorTDB2SkipScan.java create mode 100644 jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan/TestTransformDistinctPlacement.java diff --git a/jena-db/jena-dboe-base/src/main/java/org/apache/jena/dboe/base/record/Record.java b/jena-db/jena-dboe-base/src/main/java/org/apache/jena/dboe/base/record/Record.java index 3cd96072d38..e9d5bd5a31d 100644 --- a/jena-db/jena-dboe-base/src/main/java/org/apache/jena/dboe/base/record/Record.java +++ b/jena-db/jena-dboe-base/src/main/java/org/apache/jena/dboe/base/record/Record.java @@ -167,4 +167,53 @@ static boolean compatible(Record record1, Record record2, boolean checkValue) { } return true; } + + /** + * Return a new record with the key increased by 1. + * Returned record shares the value array of the argument record. + */ + public static Record incrementKey(Record record) { + return new Record(incrementByteArray(record.getKey().clone()), record.getValue()); + } + + private static byte[] incrementByteArray(byte[] array) { + // Loop from the rightmost (least significant) byte to the left + for (int i = array.length - 1; i >= 0; i--) { + array[i]++; + // If it didn't roll over to 0, no carry is needed; we are done + if (array[i] != 0) { + return array; + } + } + // If we reach here, the entire array overflowed (e.g., [255, 255] -> [0, 0]) + throw new ArithmeticException("Byte array overflowed its maximum value"); + } + + /** + * Pad {@code record} with zeros such that the lengths of its + * key and value arrays match those of the {@code prototype} record. + * + * If no padding is needed then {@code record} is returned. + * Otherwise, a new record is created. + */ + public static Record padRight(Record record, Record prototype) { + byte[] rkey = record.getKey(); + byte[] rval = record.getValue(); + + byte[] pkey = prototype.getKey(); + byte[] pval = prototype.getValue(); + + byte[] key = pkey == null ? rkey : padRight(rkey, pkey.length); + byte[] val = pval == null ? rval : padRight(rval, pval.length); + return (key == rkey && val == rval) ? record : new Record(key, val); + } + + private static byte[] padRight(byte[] arr, int length) { + if (length == arr.length) { + return arr; + } else if (length < arr.length) { + return Arrays.copyOf(arr, arr.length); + } + return Arrays.copyOf(arr, length); + } } diff --git a/jena-db/jena-dboe-trans-data/src/main/java/org/apache/jena/dboe/trans/bplustree/BPTreeDistinctKeyPrefixIterator.java b/jena-db/jena-dboe-trans-data/src/main/java/org/apache/jena/dboe/trans/bplustree/BPTreeDistinctKeyPrefixIterator.java index e8d46c03aa6..83bb815f86c 100644 --- a/jena-db/jena-dboe-trans-data/src/main/java/org/apache/jena/dboe/trans/bplustree/BPTreeDistinctKeyPrefixIterator.java +++ b/jena-db/jena-dboe-trans-data/src/main/java/org/apache/jena/dboe/trans/bplustree/BPTreeDistinctKeyPrefixIterator.java @@ -57,10 +57,30 @@ public static Iterator create(BPTreeNode node, int keyPrefixLength) { return new BPTreeDistinctKeyPrefixIterator(node, keyPrefixLength, minRecord, maxRecord); } + /** Create an iterator of distinct keys over a custom sub-range. Arguments must not be null. */ + public static Iterator create(BPTreeNode node, int keyPrefixLength, Record minRecord, Record maxRecord) { + Objects.requireNonNull(minRecord); + Objects.requireNonNull(maxRecord); + + Record nodeMinRecord = node.minRecord(); + Record nodeMaxRecord = node.maxRecord(); + // If there's no records just return a null iterator + if (nodeMinRecord == null) { + return Iter.nullIter(); + } + + // Pad records to make their lengths match those of the nodes. + Record paddedMinRecord = Record.padRight(minRecord, nodeMinRecord); + Record paddedMaxRecord = Record.padRight(maxRecord, nodeMaxRecord); + + return new BPTreeDistinctKeyPrefixIterator(node, keyPrefixLength, paddedMinRecord, paddedMaxRecord); + } + // Convert path to a stack of iterators private final Deque> stack = new ArrayDeque<>(); private Iterator current; - private Record slot = null, minRecord, maxRecord; + private Record slot = null; + private final Record minRecord, maxRecord, maxRecordPlusOne; private byte[] lastPrefix = null; private boolean finished = false; @@ -70,6 +90,7 @@ public static Iterator create(BPTreeNode node, int keyPrefixLength) { this.keyPrefixLength = keyPrefixLength; this.minRecord = minRecord; this.maxRecord = maxRecord; + this.maxRecordPlusOne = Record.incrementKey(maxRecord); BPTreeRecords r = loadStack(node); current = getRecordsIterator(r); @@ -143,6 +164,12 @@ private Iterator moveOnCurrent() { return getRecordsIterator(r); } + protected final int comparePrefix(Record a, Record b) { + // Need to compare unsigned in general: + // E.g. [0, 5] is less than [0, -1] because the latter must be treated as [0, 255]. + return Arrays.compareUnsigned(a.getKey(), 0, this.keyPrefixLength, b.getKey(), 0, this.keyPrefixLength); + } + protected final boolean haveSamePrefix(Record a, Record b) { return Arrays.compare(a.getKey(), 0, this.keyPrefixLength, b.getKey(), 0, this.keyPrefixLength) == 0; } @@ -157,12 +184,18 @@ protected Iterator getRecordsIterator(BPTreeRecords records) { } else { // Check whether we need to scan the whole page or can process it by skipping or singleton yield Record lowRecord = records.getLowRecord(); - if (haveSamePrefix(lowRecord, records.getHighRecord())) { - // If the low and high keys for this page have the same prefix then just return a singleton iterator - iter = Iter.singletonIterator(lowRecord); + Record highRecord = records.getHighRecord(); + if (haveSamePrefix(lowRecord, highRecord)) { + // Check that the prefix is in range + if (comparePrefix(lowRecord, minRecord) >= 0 && comparePrefix(highRecord, maxRecord) <= 0) { + // If the low and high keys for this page have the same prefix then just return a singleton iterator + iter = Iter.singletonIterator(lowRecord); + } else { + iter = Iter.nullIterator(); + } } else { // Otherwise need to scan the whole page - iter = records.getRecordBuffer().iterator(); + iter = records.getRecordBuffer().iterator(minRecord, maxRecordPlusOne); } } records.bpTree.finishReadBlkMgr(); @@ -173,7 +206,7 @@ private BPTreeRecords loadStack(BPTreeNode node) { AccessPath path = new AccessPath(null); node.bpTree.startReadBlkMgr(); - node.internalMinRecord(path); + node.internalSearch(path, minRecord); List steps = path.getPath(); for (AccessStep step : steps) { BPTreeNode n = step.node; diff --git a/jena-db/jena-dboe-trans-data/src/main/java/org/apache/jena/dboe/trans/bplustree/BPlusTree.java b/jena-db/jena-dboe-trans-data/src/main/java/org/apache/jena/dboe/trans/bplustree/BPlusTree.java index 31876d5196f..04e1d2142c1 100644 --- a/jena-db/jena-dboe-trans-data/src/main/java/org/apache/jena/dboe/trans/bplustree/BPlusTree.java +++ b/jena-db/jena-dboe-trans-data/src/main/java/org/apache/jena/dboe/trans/bplustree/BPlusTree.java @@ -329,6 +329,14 @@ public Iterator distinctByKeyPrefix(int keyPrefixLength) { return BPTreeDistinctKeyPrefixIterator.create(root, keyPrefixLength); } + public Iterator distinctByKeyPrefix(int keyPrefixLength, Record fromRecInclusive, Record toRecInclusive) { + startReadBlkMgr(); + BPTreeNode root = getRootRead(); + releaseRootRead(root); + finishReadBlkMgr(); + return BPTreeDistinctKeyPrefixIterator.create(root, keyPrefixLength, fromRecInclusive, toRecInclusive); + } + /* @Override public Iterator iterator(Record minRec, Record maxRec, RecordMapper mapper) { diff --git a/jena-geosparql/src/main/java/org/apache/jena/geosparql/spatial/task/BasicTask.java b/jena-geosparql/src/main/java/org/apache/jena/geosparql/spatial/task/BasicTask.java index c08e2085b54..9646ccf3278 100644 --- a/jena-geosparql/src/main/java/org/apache/jena/geosparql/spatial/task/BasicTask.java +++ b/jena-geosparql/src/main/java/org/apache/jena/geosparql/spatial/task/BasicTask.java @@ -56,7 +56,7 @@ public interface TaskListener { /** * Whether the task has terminated. * - * @implNote The original name {@code isTerminated} collided with the package−private method in {@link Thread}. + * @implNote The original name {@code isTerminated} collided with the package-private method in {@link Thread}. */ default boolean hasTerminated() { TaskState state = getTaskState(); diff --git a/jena-tdb2/pom.xml b/jena-tdb2/pom.xml index 243fc6b5d01..62adab5e0f9 100644 --- a/jena-tdb2/pom.xml +++ b/jena-tdb2/pom.xml @@ -16,7 +16,7 @@ KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. - + SPDX-License-Identifier: Apache-2.0 --> @@ -32,7 +32,7 @@ org.apache.jena jena 6.3.0-SNAPSHOT - + ${maven.build.timestamp} @@ -73,6 +73,11 @@ test + + org.apache.commons + commons-math4-legacy + test + diff --git a/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/OpExecutorTDB2.java b/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/OpExecutorTDB2.java index ddc1012c089..7dadc1b7106 100644 --- a/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/OpExecutorTDB2.java +++ b/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/OpExecutorTDB2.java @@ -47,9 +47,13 @@ import org.apache.jena.sparql.engine.optimizer.reorder.ReorderTransformation; import org.apache.jena.sparql.expr.ExprList; import org.apache.jena.sparql.mgt.Explain; +import org.apache.jena.tdb2.solver.skipscan.OpExecutorTDB2SkipScan; +import org.apache.jena.tdb2.solver.skipscan.OpExtSkipScan; +import org.apache.jena.tdb2.solver.skipscan.SkipScanRewrite; import org.apache.jena.tdb2.store.DatasetGraphTDB; import org.apache.jena.tdb2.store.GraphTDB; import org.apache.jena.tdb2.store.NodeId; +import org.apache.jena.tdb2.sys.SystemTDB; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -92,13 +96,40 @@ protected QueryIterator exec(Op op, QueryIterator input) { // Retrieving nodes isn't so bad because they will be needed anyway. // And if their duplicates, likely to be cached. - // Need to work with SolverLib which wraps the NodeId bindgins with a converter. + // Need to work with SolverLib which wraps the NodeId bindings with a converter. @Override protected QueryIterator execute(OpDistinct opDistinct, QueryIterator input) { + if ( isForTDB ) { + boolean isSkipScanEnabled = execCxt.getContext().isTrueOrUndef(SystemTDB.symSkipScan); + if ( isSkipScanEnabled ) { + Op rewritten = SkipScanRewrite.tryRewriteAsSkipScan(opDistinct); + if (rewritten != null && !opDistinct.equals(rewritten)) { + OpExtSkipScan.setOpExecutorIfAbsent(execCxt.getContext(), this); + return exec(rewritten, input); + } + } + } + return super.execute(opDistinct, input); } + @Override + protected QueryIterator execute(OpGroup opGroup, QueryIterator input) { + if ( isForTDB ) { + boolean isSkipScanEnabled = execCxt.getContext().isTrueOrUndef(SystemTDB.symSkipScan); + if ( isSkipScanEnabled ) { + Op rewritten = SkipScanRewrite.tryRewriteAsSkipScan(opGroup); + if (rewritten != null) { + OpExtSkipScan.setOpExecutorIfAbsent(execCxt.getContext(), this); + return exec(rewritten, input); + } + } + } + + return super.execute(opGroup, input); + } + @Override protected QueryIterator execute(OpReduced opReduced, QueryIterator input) { return super.execute(opReduced, input); diff --git a/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/CandidateIndex.java b/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/CandidateIndex.java new file mode 100644 index 00000000000..46bc26271ce --- /dev/null +++ b/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/CandidateIndex.java @@ -0,0 +1,32 @@ +/* + * 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 + * + * https://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. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +package org.apache.jena.tdb2.solver.skipscan; + +import org.apache.jena.atlas.lib.tuple.Tuple; +import org.apache.jena.tdb2.store.tupletable.TupleIndexRecord; + +record CandidateIndex( + TupleIndexRecord index, + Tuple pattern, + int[] projectIndices, + ValueFilter residualConditions +) {} diff --git a/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/EqualityLink.java b/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/EqualityLink.java new file mode 100644 index 00000000000..72bce920c7d --- /dev/null +++ b/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/EqualityLink.java @@ -0,0 +1,30 @@ +/* + * 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 + * + * https://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. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +package org.apache.jena.tdb2.solver.skipscan; + +/** + * Declare that the value of a row at column index {@code equalToIdx} must be equal + * to the value at column index {@code idx}. + * This case occurs for queries with patterns such as (?s :p ?s): + * Here, column 2 and 0 are linked by an equality constraint. + */ +record EqualityLink(int idx, int equalToIdx) {} diff --git a/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/IndexMap.java b/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/IndexMap.java new file mode 100644 index 00000000000..b5ec7630376 --- /dev/null +++ b/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/IndexMap.java @@ -0,0 +1,43 @@ +/* + * 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 + * + * https://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. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +package org.apache.jena.tdb2.solver.skipscan; + +import java.util.Arrays; + +import org.apache.jena.graph.Node; +import org.apache.jena.tdb2.store.NodeId; + +record IndexMap( + Node[] nodeTuple, + NodeId[] tuple, + VarMap[] proj, + ValueFilter[] residualConditions, + EqualityLink[] equalityLinks) +{ + + @Override + public String toString() { + return "IndexMap [nodeTuple=" + Arrays.toString(nodeTuple) + ", tuple=" + Arrays.toString(tuple) + ", proj=" + + Arrays.toString(proj) + ", residualConditions=" + Arrays.toString(residualConditions) + ", links=" + + Arrays.toString(equalityLinks) + "]"; + } +} diff --git a/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/IndexMatch.java b/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/IndexMatch.java new file mode 100644 index 00000000000..03ffc4dae83 --- /dev/null +++ b/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/IndexMatch.java @@ -0,0 +1,46 @@ +/* + * 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 + * + * https://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. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +package org.apache.jena.tdb2.solver.skipscan; + +import java.util.Comparator; + +import org.apache.jena.graph.Node; + +record IndexMatch( + boolean canDoDirectDistinct, + ValueFilter[] residualConditions, + int keyLen, + int valLen) +{ + public int numNeededSlots() { + return keyLen + valLen; + } + + public int numResidualConditions() { + return (residualConditions == null) ? 0 : residualConditions.length; + } + + public static final Comparator COMPARATOR = Comparator.nullsLast(Comparator + .comparingInt(IndexMatch::numResidualConditions) + .thenComparing(Comparator.comparing(IndexMatch::canDoDirectDistinct).reversed()) + .thenComparing(IndexMatch::numNeededSlots)); +} diff --git a/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/NodeIdUtils.java b/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/NodeIdUtils.java new file mode 100644 index 00000000000..e7d9b75e321 --- /dev/null +++ b/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/NodeIdUtils.java @@ -0,0 +1,56 @@ +/* + * 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 + * + * https://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. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +package org.apache.jena.tdb2.solver.skipscan; + +import org.apache.jena.atlas.lib.tuple.Tuple; +import org.apache.jena.atlas.lib.tuple.TupleFactory; +import org.apache.jena.tdb2.store.NodeId; +import org.apache.jena.tdb2.store.NodeIdFactory; +import org.apache.jena.tdb2.store.NodeIdType; + +class NodeIdUtils { + /** Minimum value for a NodeId. Used as lower bound in range retrievals. */ + private static final NodeId NodeIdMin = NodeIdFactory.createPtr(0); + + /** Maximum value for a NodeId. Used as upper bound in range retrievals. */ + private static final NodeId NodeIdMax = NodeId.createRaw(NodeIdType.SPECIAL, Long.MAX_VALUE); + + public static Tuple anyToMin(Tuple tuple) { + int n = tuple.len(); + NodeId[] arr = new NodeId[n]; + for (int i = 0; i < n; ++i) { + NodeId x = tuple.get(i); + arr[i] = NodeId.isAny(x) ? NodeIdMin : x; + } + return TupleFactory.create(arr); + } + + public static Tuple anyToMax(Tuple tuple) { + int n = tuple.len(); + NodeId[] arr = new NodeId[n]; + for (int i = 0; i < n; ++i) { + NodeId x = tuple.get(i); + arr[i] = NodeId.isAny(x) ? NodeIdMax : x; + } + return TupleFactory.create(arr); + } +} diff --git a/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/OpExecutorTDB2SkipScan.java b/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/OpExecutorTDB2SkipScan.java new file mode 100644 index 00000000000..87449795776 --- /dev/null +++ b/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/OpExecutorTDB2SkipScan.java @@ -0,0 +1,601 @@ +/* + * 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 + * + * https://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. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +package org.apache.jena.tdb2.solver.skipscan; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.LongAdder; + +import org.apache.jena.atlas.iterator.Iter; +import org.apache.jena.atlas.lib.tuple.Tuple; +import org.apache.jena.atlas.lib.tuple.TupleFactory; +import org.apache.jena.atlas.lib.tuple.TupleMap; +import org.apache.jena.dboe.base.record.Record; +import org.apache.jena.dboe.base.record.RecordFactory; +import org.apache.jena.dboe.index.RangeIndex; +import org.apache.jena.dboe.trans.bplustree.BPlusTree; +import org.apache.jena.graph.Node; +import org.apache.jena.sparql.ARQConstants; +import org.apache.jena.sparql.algebra.Op; +import org.apache.jena.sparql.core.Var; +import org.apache.jena.sparql.core.VarAlloc; +import org.apache.jena.sparql.engine.ExecutionContext; +import org.apache.jena.sparql.engine.QueryIterator; +import org.apache.jena.sparql.engine.binding.Binding; +import org.apache.jena.sparql.engine.iterator.QueryIter; +import org.apache.jena.sparql.engine.iterator.QueryIterDistinct; +import org.apache.jena.sparql.engine.iterator.QueryIterFilterExpr; +import org.apache.jena.sparql.engine.iterator.QueryIterNullIterator; +import org.apache.jena.sparql.engine.iterator.QueryIterPlainWrapper; +import org.apache.jena.sparql.engine.iterator.QueryIterProject; +import org.apache.jena.sparql.engine.main.OpExecutor; +import org.apache.jena.sparql.expr.E_Equals; +import org.apache.jena.sparql.expr.E_LogicalAnd; +import org.apache.jena.sparql.expr.Expr; +import org.apache.jena.sparql.expr.ExprVar; +import org.apache.jena.sparql.util.Context; +import org.apache.jena.sparql.util.Symbol; +import org.apache.jena.tdb2.solver.BindingNodeId; +import org.apache.jena.tdb2.solver.BindingTDB; +import org.apache.jena.tdb2.store.DatasetGraphTDB; +import org.apache.jena.tdb2.store.GraphTDB; +import org.apache.jena.tdb2.store.NodeId; +import org.apache.jena.tdb2.store.NodeIdFactory; +import org.apache.jena.tdb2.store.nodetable.NodeTable; +import org.apache.jena.tdb2.store.nodetupletable.NodeTupleTable; +import org.apache.jena.tdb2.store.tupletable.TupleIndex; +import org.apache.jena.tdb2.store.tupletable.TupleIndexRecord; +import org.apache.jena.tdb2.store.tupletable.TupleTable; +import org.apache.jena.tdb2.sys.SystemTDB; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class OpExecutorTDB2SkipScan { + private static final Logger logger = LoggerFactory.getLogger(OpExecutorTDB2SkipScan.class); + + // The following symbols should only be used for debugging. + + /** Cache of the best candidate indexes for a {@link PatternQuery}'s configuration of constants and variables. */ + public static final Symbol symSkipScanBestIndexCache = SystemTDB.allocSymbol("skipScanBestIndexCache"); + + /** Symbol for tracking how often an OpExtSkipScan was executed using the specialized machinery. */ + public static final Symbol symSkipScanOkCounter = SystemTDB.allocSymbol("skipScanOkCounter"); + + /** Symbol for tracking how often an OpExtSkipScan was executed using the conventional machinery. */ + public static final Symbol symSkipScanFailoverCounter = SystemTDB.allocSymbol("skipScanFailoverCounter"); + + public static LongAdder getSkipScanOkCounter(Context cxt) { + return cxt.get(symSkipScanOkCounter); + } + + /** Return the skip scan count in the context. For debugging only. */ + public static long getSkipScanOkCount(Context cxt) { + LongAdder adder = getSkipScanOkCounter(cxt); + long value = (adder == null) ? 0 : adder.longValue(); + return value; + } + + public static LongAdder getSkipScanFailoverCounter(Context cxt) { + return cxt.get(symSkipScanFailoverCounter); + } + + /** Return the skip scan failover count in the context. For debugging only. */ + public static long getSkipScanFailoverCount(Context cxt) { + LongAdder adder = getSkipScanFailoverCounter(cxt); + long value = (adder == null) ? 0 : adder.longValue(); + return value; + } + + public static QueryIterator exec(PatternQuery patternQuery, QueryIterator input, ExecutionContext execCxt, OpExecutor opExecutor) { + // Set up a cache that maps the cacheKey(queryPattern) to the best index. + // See PatternQuery.toCacheKey() + Map indexCache = execCxt.getContext() + .computeIfAbsent(symSkipScanBestIndexCache, sym -> new ConcurrentHashMap<>()); + + // Get debug counters (may be null) + LongAdder skipScanOkCounter = getSkipScanOkCounter(execCxt.getContext()); + LongAdder skipScanFailoverCounter = getSkipScanFailoverCounter(execCxt.getContext()); + + QueryIterator qIter = QueryIter.flatMap(input, binding -> { + return exec(patternQuery, binding, execCxt, opExecutor, indexCache, skipScanOkCounter, skipScanFailoverCounter); + }, execCxt); + return qIter; + } + + private static QueryIterator exec(PatternQuery patternQuery, Binding binding, ExecutionContext execCxt, OpExecutor opExecutor, + Map indexCache, LongAdder skipScanOkCounter, LongAdder skipScanFailoverCounter) { + + PatternQuery subst = PatternQuery.substitute(patternQuery, binding); + + PatternQuery cacheKey = PatternQuery.toCacheKey(subst); + SkipScanCandidate bestCandidate = indexCache.computeIfAbsent(cacheKey, cq -> { + // System.err.println("NO CACHE HIT: " + canonicalQuery); + SkipScanCandidate r = findBestCandidate(patternQuery, execCxt); + return r; + }); + + QueryIterator innerIter = tryExec(subst, execCxt, bestCandidate); + + if (innerIter != null) { + if (skipScanOkCounter != null) { + skipScanOkCounter.increment(); + } + } else { + // Fail-over in case that no suitable index was found. + // Should never be needed with default TDB2 configurations. + if (skipScanFailoverCounter != null) { + skipScanFailoverCounter.increment(); + } + + // Execute the pattern without distinct. This avoids the infinite loop of + // attempting to rewrite distinct as skip-scan. + PatternQuery tmp = new PatternQuery(/*distinct=*/false, patternQuery.project(), patternQuery.tuple()); + Op op = tmp.effectiveOp(); + innerIter = opExecutor.executeOp(op, QueryIterPlainWrapper.create(Iter.singletonIter(binding))); + + if (patternQuery.distinct()) { + innerIter = new QueryIterDistinct(innerIter, null, execCxt); + } + } + return innerIter; + } + + public static SkipScanCandidate findBestCandidate(PatternQuery patternQuery, ExecutionContext execCxt) { + Node[] tuple = patternQuery.tuple(); + NodeTupleTable table = resolveTable(tuple.length, execCxt); + TuplePatternSpec lookup = TuplePatternSpec.create(tuple, patternQuery.project()); + List candidates = planCandidates(table, lookup); + SkipScanCandidate best = pickBest(candidates); + return best; + } + + public static QueryIterator tryExec(PatternQuery patternQuery, ExecutionContext execCxt, SkipScanCandidate candidate) { + Node[] tuple = patternQuery.tuple(); + NodeTupleTable table = resolveTable(tuple.length, execCxt); + TuplePatternSpec lookup = TuplePatternSpec.create(tuple, patternQuery.project()); + return tryExec(table, patternQuery.distinct(), lookup, execCxt, candidate); + } + + public static QueryIterator tryExec(NodeTupleTable nodeTupleTable, boolean distinct, TuplePatternSpec lookup, ExecutionContext execCxt, SkipScanCandidate best) { + // In the end we must build a tuple with the constants + if (logger.isDebugEnabled()) { + logger.debug("Best matching index: " + (best == null ? null : best.index())); + } + + if (best == null) { + return null; + } + return execCandidate(nodeTupleTable, distinct, lookup, best, execCxt); + } + + /** Must only be called if hasNeededColumns returned true. */ + @SuppressWarnings("unchecked") + public static IndexMatch computeIndexMatch(TupleMap tm, TuplePatternSpec patternSpec) { + Node[] quad = patternSpec.tuple(); + boolean canDoDirectDistinct = true; + + // An index is only usable if covers all needed slots of the query tuple. + // Start with marking all slots as not-covered. + int uncoveredSlotsMask = patternSpec.neededSlotsMask(); + + ValueFilter[] residualConditions = null; + int numResidualConditions = 0; + + int i; + int idxLen = tm.length(); + for (i = 0; i < idxLen; ++i) { + int tupleSlot = tm.mapIdx(i); + Node node = quad[tupleSlot]; + if (!node.isConcrete()) { + break; + } + // Mark the slot as covered by setting the slot's bit to 0. + uncoveredSlotsMask &= ~(1 << tupleSlot); + } + int keyLen = i; + + // The next slots of the index must map to the projection slots + // Any constant not matched by HEAD is considered projected and filtered on. + int j; // additional needed value slots + for (j = keyLen; j < idxLen && uncoveredSlotsMask != 0; ++j) { + int tupleSlot = tm.mapIdx(j); + Node node = quad[tupleSlot]; + if (node.isVariable()) { + Var v = Var.alloc(node); + uncoveredSlotsMask &= ~(1 << tupleSlot); + + // Consider: SELECT DISTINCT ?g ?p { GRAPH ?g { ?s :p ?s } } + // PGSO and PGOS are suitable indices + // If we pick PGOS we would evaluate the quality group for the S slot + // So we test restriction based on the order of the original slot indices + // S comes before O, so we test S = O instead of O = S + // The important part is just: all members of equality groups must be covered. + + boolean isProjected = patternSpec.projection().contains(v); + + // If the variable in not projected, then we need to skip over it + // This breaks simple distinct + if (!isProjected) { + canDoDirectDistinct = false; + } + } else { + if (residualConditions == null) { + residualConditions = new ValueFilter[idxLen - j]; + } + + // Add the constant node as a filter condition. + residualConditions[numResidualConditions++] = new ValueFilter<>(j, node); + } + } + int valLen = j - keyLen; + + if (uncoveredSlotsMask != 0) { + return null; + } + + // If there were residual conditions then strip trailing null values. + if (residualConditions != null && residualConditions.length != numResidualConditions) { + residualConditions = Arrays.copyOf(residualConditions, numResidualConditions); + } + + return new IndexMatch(canDoDirectDistinct, residualConditions, keyLen, valLen); + } + + /** Resolve the {@link NodeTupleTable} for a pattern of the given tuple length. */ + public static NodeTupleTable resolveTable(int tupleLength, ExecutionContext execCxt) { + if (tupleLength == 3) { + GraphTDB graph = (GraphTDB)execCxt.getActiveGraph(); + return graph.getNodeTupleTable(); + } else if (tupleLength == 4) { + DatasetGraphTDB ds = (DatasetGraphTDB)execCxt.getDataset(); + return ds.getQuadTable().getNodeTupleTable(); + } else { + throw new IllegalArgumentException("Unexpected tuple length: " + tupleLength); + } + } + + /** + * Enumerate the usable indexes for the given lookup. Each returned candidate carries + * the matched index, its {@link IndexMatch}, and the variable order the index produces. + * This is the planning phase: it does not touch the node table or execute anything, so + * callers may inspect candidate orders and choose a combination before executing. + */ + public static List planCandidates(NodeTupleTable nodeTupleTable, TuplePatternSpec lookup) { + TupleTable tupleTable = nodeTupleTable.getTupleTable(); + List candidates = new ArrayList<>(); + + for (TupleIndex tupleIndex : tupleTable.getIndexes()) { + if (logger.isDebugEnabled()) { + logger.debug("Trying index: " + tupleIndex); + } + SkipScanCandidate candidate = planCandidate(lookup, tupleIndex); + if (candidate != null) { + candidates.add(candidate); + } + } + return candidates; + } + + private static SkipScanCandidate planCandidate(TuplePatternSpec lookup, TupleIndex tupleIndex) { + // Only consider indexes backed by a BPlusTree + if (tupleIndex instanceof TupleIndexRecord recordIdx) { + RangeIndex rangeIndex = recordIdx.getRangeIndex(); + if (!(rangeIndex instanceof BPlusTree)) { + return null; + } + } + + TupleMap tm = tupleIndex.getMapping(); + IndexMatch match = computeIndexMatch(tm, lookup); + + if (match == null) { + return null; + } + + return new SkipScanCandidate(tupleIndex, match); + } + + /** Choose the best candidate using {@link IndexMatch#COMPARATOR}, or null if none. */ + public static SkipScanCandidate pickBest(List candidates) { + SkipScanCandidate best = null; + for (SkipScanCandidate candidate : candidates) { + if (best == null || IndexMatch.COMPARATOR.compare(candidate.match(), best.match()) < 0) { + best = candidate; + } + } + return best; + } + + /** Execute a previously planned candidate. */ + public static QueryIterator execCandidate(NodeTupleTable nodeTupleTable, boolean distinct, TuplePatternSpec lookup, + SkipScanCandidate candidate, ExecutionContext execCxt) { + NodeTable nodeTable = nodeTupleTable.getNodeTable(); + TupleIndex bestIndex = candidate.index(); + IndexMatch bestMatch = candidate.match(); + + TupleMap tm = bestIndex.getMapping(); + IndexMap im = tryComputeIndexMap(lookup, bestMatch, tm, nodeTable); + if (im == null) { + // If null then at least one Node had no corresponding NodeId in the nodeTable. + return new QueryIterNullIterator(execCxt); + } + + if (logger.isDebugEnabled()) { + logger.debug("IndexMap Match Data: " + im); + logger.debug("IndexMap Projection: " + Arrays.toString(im.proj())); + logger.debug("IndexMap Conditions: " + Arrays.toString(im.residualConditions())); + logger.debug("IndexMap Links: " + Arrays.toString(im.equalityLinks())); + logger.debug("IndexMap Query Tuple: " + Arrays.asList(im.tuple())); + } + + QueryIterator r = exec(bestIndex, nodeTable, lookup.projection(), im, execCxt); + + if (distinct && !bestMatch.canDoDirectDistinct()) { + r = new QueryIterDistinct(r, null, execCxt); + } + return r; + } + + /** + * Actual execution. + */ + @SuppressWarnings("removal") + public static QueryIterator exec(TupleIndex tupleIndex, NodeTable nodeTable, List projectVars, IndexMap map, ExecutionContext execCxt) { + // Cast validity of the arguments is assumed to be ensured! + TupleIndexRecord tupleIndexRecord = (TupleIndexRecord)tupleIndex; + RangeIndex rangeIndex = tupleIndexRecord.getRangeIndex(); + BPlusTree bpt = (BPlusTree)rangeIndex; + + int n = map.tuple().length; + Tuple pattern = TupleFactory.create(map.tuple()); + + Tuple minPattern = NodeIdUtils.anyToMin(pattern); + Tuple maxPattern = NodeIdUtils.anyToMax(pattern); + + RecordFactory rf = rangeIndex.getRecordFactory(); + Record minRecord = record(rf, minPattern); + Record maxRecord = record(rf, maxPattern); + + // VarMap[] proj = map.proj; + ValueFilter[] residualConditions = map.residualConditions(); + EqualityLink[] equalityLinks = map.equalityLinks(); + + Iterator bindingIdIt; + + VarMap[] finalProj; + Expr filterExpr = null; + if (equalityLinks == null) { + finalProj = map.proj(); + } else { + // For linked slots, such as {?s :p ?s} introduce dummy non-distinguished vars. + // {?s :p ?s} becomes {?s :p ?.foo} FILTER(?s = ?.foo) + + // The variables of the equalityLinks may not have been projected yet. + // So we must compute a proper projection. + + VarMap[] finalProjTmp = new VarMap[map.proj().length + 2 * equalityLinks.length]; + System.arraycopy(map.proj(), 0, finalProjTmp, 0, map.proj().length); + VarAlloc va = new VarAlloc(ARQConstants.allocVarAnonMarker + "X"); + int i = map.proj().length; + Set seenVars = null; + for (EqualityLink entry : equalityLinks) { + int primaryIdx = entry.equalToIdx(); + Var primaryVar = (Var)map.nodeTuple()[primaryIdx]; + if (!projectVars.contains(primaryVar) && (seenVars == null || !seenVars.contains(primaryVar))) { + if (seenVars == null) { + seenVars = new HashSet<>(); + } + seenVars.add(primaryVar); + finalProjTmp[i++] = new VarMap(primaryIdx, primaryVar); + } + + int secondaryIdx = entry.idx(); + Var extraVar = va.allocVar(); + finalProjTmp[i++] = new VarMap(secondaryIdx, extraVar); + + Expr contrib = new E_Equals(new ExprVar(primaryVar), new ExprVar(extraVar)); + filterExpr = logicalAnd(filterExpr, contrib); + } + finalProj = Arrays.copyOf(finalProjTmp, i); + } + + Iterator recordIt = bpt.distinctByKeyPrefix(n * NodeId.SIZE, minRecord, maxRecord); + + // Filter by recheck conditions first. + if (residualConditions != null) { + recordIt = Iter.filter(recordIt, record -> { + execCxt.checkCancelSignal(); + + byte[] recordKey = record.getKey(); + for (int i = 0; i < residualConditions.length; ++i) { + ValueFilter condition = residualConditions[i]; + int idxx = condition.idx(); + NodeId expected = condition.value(); + NodeId actual = extractNodeId(recordKey, idxx); + if (!expected.equals(actual)) { + return false; + } + } + return true; + }); + } + + // Build the initial BindingNodeId instances. + bindingIdIt = Iter.map(recordIt, record -> { + byte[] recordKey = record.getKey(); + BindingNodeId b = new BindingNodeId(); + for (VarMap varMap : finalProj) { + NodeId nodeId = extractNodeId(recordKey, varMap.idx()); + b.put(varMap.var(), nodeId); + } + return b; + }); + + Iterator bindingIt = Iter.map(bindingIdIt, bid -> new BindingTDB(bid, nodeTable)); + QueryIterator qIter = QueryIterPlainWrapper.create(bindingIt, execCxt); + + // Apply filters if needed. + // Presence of filters also implies presence of generated variables that need projecting away. + if (filterExpr != null) { + qIter = new QueryIterFilterExpr(qIter, filterExpr, execCxt); + qIter = QueryIterProject.create(qIter, projectVars, execCxt); + } + + return qIter; + } + + /** + * Maps Nodes to NodeIds. + * Returns null if any constraint is unsatisfiable due to the lack of a corresponding node id. + */ + public static IndexMap tryComputeIndexMap(TuplePatternSpec lookup, IndexMatch match, TupleMap tm, NodeTable nodeTable) { + Node[] quad = lookup.tuple(); + int neededSlots = match.numNeededSlots(); + + // Reorder the query tuple by the order of columns in the index. + Node[] nodeTuple = new Node[neededSlots]; + for (int i = 0; i < neededSlots; ++i) { + int tupleSlot = tm.mapIdx(i); + Node node = quad[tupleSlot]; + nodeTuple[i] = node; + } + + // Build the tuple of NodeIds + NodeId[] tuple = new NodeId[neededSlots]; + + int x; + for (x = 0; x < neededSlots; ++x) { + int tupleSlot = tm.mapIdx(x); + Node node = quad[tupleSlot]; + if (!node.isConcrete()) { + break; + } + NodeId nodeId = nodeTable.getNodeIdForNode(node); + + if (NodeId.isDoesNotExist(nodeId)) { + // Empty result set + return null; + } + + tuple[x] = nodeId; + } + + for (int y = x; y < neededSlots; ++y) { + tuple[y] = NodeId.NodeIdAny; + } + + ValueFilter[] mappedConditions = null; + EqualityLink[] mappedLinks = null; + + if (match.numResidualConditions() > 0) { + mappedConditions = remapValueConditions(match.residualConditions(), tm, nodeTable); + + // If mappedConditions is null then some nodes could not be mapped + if (mappedConditions == null) { + // skip + return null; + } + } + + if (lookup.equalityLinks() != null) { + mappedLinks = remapEqualityLinks(lookup.equalityLinks(), tm); + } + + VarMap[] newProj = remapProjection(lookup, tm); + return new IndexMap(nodeTuple, tuple, newProj, mappedConditions, mappedLinks); + } + + private static Expr logicalAnd(Expr base, Expr contrib) { + return base == null ? contrib : new E_LogicalAnd(base, contrib); + } + + private static NodeId extractNodeId(byte[] bytes, int index) { + NodeId nodeId = NodeIdFactory.get(bytes, index * NodeId.SIZE); + return nodeId; + } + + /** Create varMaps from the spec's projection and remap indices w.r.t. the tupleMap. */ + public static VarMap[] remapProjection(TuplePatternSpec lookup, TupleMap tupleMap) { + int[] proj = lookup.projs(); + int n = proj.length; + VarMap[] result = new VarMap[n]; + for (int i = 0; i < n; ++i) { + int tupleIdx = proj[i]; + Node node = lookup.tuple()[tupleIdx]; + Var var = Var.alloc(node); + int idx = tupleMap.unmapIdx(tupleIdx); + result[i] = new VarMap(idx, var); + } + return result; + } + + /** + * Remap indices of equality links w.r.t. the tupleMap. + */ + public static EqualityLink[] remapEqualityLinks(EqualityLink[] links, TupleMap tupleMap) { + int n = links.length; + EqualityLink[] result = new EqualityLink[n]; + for (int i = 0; i < n; ++i) { + EqualityLink link = links[i]; + int primary = tupleMap.unmapIdx(link.idx()); + int secondary = tupleMap.unmapIdx(link.equalToIdx()); + result[i] = new EqualityLink(primary, secondary); + } + return result; + } + + /** + * Remap indices w.r.t. the tupleMap and map Nodes to NodeIds. + * Returns null if any condition could not be mapped. + */ + public static ValueFilter[] remapValueConditions(ValueFilter[] conditions, TupleMap tupleMap, NodeTable nodeTable) { + int n = conditions.length; + @SuppressWarnings("unchecked") + ValueFilter[] result = new ValueFilter[n]; + for (int i = 0; i < n; ++i) { + ValueFilter condition = conditions[i]; + int slot = tupleMap.unmapIdx(condition.idx()); + NodeId nodeId = nodeTable.getNodeIdForNode(condition.value()); + if (nodeId == null) { + return null; + } + result[i] = new ValueFilter<>(slot, nodeId); + } + return result; + } + + /** Create a record directly from the tuple (without a tuple map) */ + private static Record record(RecordFactory factory, Tuple tuple) { + int n = tuple.len(); + byte[] b = new byte[n * NodeId.SIZE]; + for (int i = 0; i < n ; i++) { + NodeIdFactory.set(tuple.get(i), b, i * NodeId.SIZE); + } + return factory.create(b); + } +} diff --git a/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/OpExtSkipScan.java b/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/OpExtSkipScan.java new file mode 100644 index 00000000000..b1e4e59cf3a --- /dev/null +++ b/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/OpExtSkipScan.java @@ -0,0 +1,96 @@ +/* + * 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 + * + * https://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. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +package org.apache.jena.tdb2.solver.skipscan; + +import org.apache.jena.atlas.io.IndentedWriter; +import org.apache.jena.sparql.ARQInternalErrorException; +import org.apache.jena.sparql.algebra.Op; +import org.apache.jena.sparql.algebra.op.OpExt; +import org.apache.jena.sparql.engine.ExecutionContext; +import org.apache.jena.sparql.engine.QueryIterator; +import org.apache.jena.sparql.engine.main.OpExecutor; +import org.apache.jena.sparql.serializer.SerializationContext; +import org.apache.jena.sparql.util.Context; +import org.apache.jena.sparql.util.NodeIsomorphismMap; +import org.apache.jena.sparql.util.Symbol; + +public class OpExtSkipScan + extends OpExt +{ + protected PatternQuery patternQuery; + + private static Symbol symOpExecutor = Symbol.create("opExecutor"); + + public static void setOpExecutorIfAbsent(Context cxt, OpExecutor opExecutor) { + cxt.computeIfAbsent(symOpExecutor, x -> opExecutor); + } + + public static void setOpExecutor(Context cxt, OpExecutor opExecutor) { + cxt.set(symOpExecutor, opExecutor); + } + + public static OpExecutor getOpExecutor(Context cxt) { + return cxt.get(symOpExecutor); + } + + public OpExtSkipScan(PatternQuery patternQuery) { + super("skipScan"); + this.patternQuery = patternQuery; + } + + @Override + public Op effectiveOp() { + return patternQuery.effectiveOp(); + } + + private OpExecutor getOpExecutor(ExecutionContext execCxt) { + OpExecutor result = getOpExecutor(execCxt.getContext()); + if (result == null) { + // It would be possible to gracefully create a new exec context, but better be strict. + throw new ARQInternalErrorException("OpExecutor not set"); + } + return result; + } + + @Override + public QueryIterator eval(QueryIterator input, ExecutionContext execCxt) { + OpExecutor opExecutor = getOpExecutor(execCxt); + QueryIterator result = OpExecutorTDB2SkipScan.exec(patternQuery, input, execCxt, opExecutor); + return result; + } + + @Override + public void outputArgs(IndentedWriter out, SerializationContext sCxt) { + Op eop = effectiveOp(); + eop.output(out, sCxt); + } + + @Override + public int hashCode() { + return 31 * patternQuery.hashCode(); + } + + @Override + public boolean equalTo(Op other, NodeIsomorphismMap labelMap) { + return other instanceof OpExtSkipScan o && this.effectiveOp().equalTo(o.effectiveOp(), labelMap); + } +} diff --git a/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/PatternQuery.java b/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/PatternQuery.java new file mode 100644 index 00000000000..30d7078a92d --- /dev/null +++ b/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/PatternQuery.java @@ -0,0 +1,233 @@ +/* + * 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 + * + * https://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. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +package org.apache.jena.tdb2.solver.skipscan; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.apache.jena.graph.Node; +import org.apache.jena.graph.NodeFactory; +import org.apache.jena.graph.Triple; +import org.apache.jena.sparql.algebra.Op; +import org.apache.jena.sparql.algebra.OpVars; +import org.apache.jena.sparql.algebra.op.OpBGP; +import org.apache.jena.sparql.algebra.op.OpDistinct; +import org.apache.jena.sparql.algebra.op.OpProject; +import org.apache.jena.sparql.algebra.op.OpQuadBlock; +import org.apache.jena.sparql.algebra.op.OpQuadPattern; +import org.apache.jena.sparql.core.BasicPattern; +import org.apache.jena.sparql.core.Quad; +import org.apache.jena.sparql.core.Substitute; +import org.apache.jena.sparql.core.Var; +import org.apache.jena.sparql.core.VarAlloc; +import org.apache.jena.sparql.core.Vars; +import org.apache.jena.sparql.engine.binding.Binding; +import org.apache.jena.sparql.engine.join.ImmutableUniqueList; +import org.apache.jena.sparql.engine.join.ImmutableUniqueList.Builder; +import org.apache.jena.sparql.graph.NodeTransform; +import org.apache.jena.sparql.graph.NodeTransformLib; + +/** + * Single tuple access pattern. + * + * Captures variants such as: SELECT DISTINCT ?g ?p { GRAPH ?g { ?s ?p ?o } } + */ +public record PatternQuery(boolean distinct, List project, Node[] tuple) { + + /** + * Create a PatternOp structure from the argument. Returns null on failure. + * + * Tries to match the structure below. [Op] indicates optional presence. + *
{@code
+     * OpDistinct
+     *   [OpProject]
+     *     OpQuadPattern|OpBGP
+     * }
+ * + * And returns non-null iff it can be safely rewritten as follows: + *
{@code
+     * OpDistinct
+     *   [OpProject]
+     *     OpQuadPattern|OpBGP
+     * }
+ * + *

+ * Notes: + *

    + *
  • Quads in the default graph are returned as triples.
  • + *
  • The union default graph constant {@link Quad#unionGraph} is converted to a non-distinguished variable.
  • + *
+ * + * @param inputOp The input Op. + * @return A PatternOp instance or null. + */ + static PatternQuery createOrNull$(Op inputOp) { + PatternQuery result = null; + + Node g = null; + List projectVars = null; + boolean distinct = false; + Node[] tuple = null; + + Op op = inputOp; + if (op instanceof OpDistinct opD) { + distinct = true; + op = opD.getSubOp(); + } + + if (op instanceof OpProject opP) { + projectVars = ImmutableUniqueList.createUniqueList(opP.getVars()); + op = opP.getSubOp(); + } + + BasicPattern bp = null; + if (op instanceof OpQuadPattern opQuadPattern) { + bp = opQuadPattern.getBasicPattern(); + g = opQuadPattern.getGraphNode(); + } else if (op instanceof OpBGP opBgp) { + bp = opBgp.getPattern(); + } + + if (bp != null && bp.size() == 1) { + Triple t = bp.get(0); + + if (projectVars == null) { + Set varSet = new LinkedHashSet<>(); + Vars.addVarsFromTriple(varSet, t); + if (g != null && g.isVariable()) { + varSet.add(Var.alloc(g)); + } + projectVars = ImmutableUniqueList.createUniqueList(varSet); + } + + if (g == null || Quad.isDefaultGraph(g)) { + tuple = new Node[] { t.getSubject(), t.getPredicate(), t.getObject() }; + } else if (Quad.isUnionGraph(g)) { + VarAlloc varAlloc = new VarAlloc("G"); + tuple = new Node[] { varAlloc.allocVar(), t.getSubject(), t.getPredicate(), t.getObject() }; + } else { + tuple = new Node[] { g, t.getSubject(), t.getPredicate(), t.getObject() }; + } + + result = new PatternQuery(distinct, projectVars, tuple); //, filter, extend, reapplyProject); + } + return result; + } + + public Op effectiveOp() { + Op result = tupleToOp(tuple); + Set tupleVars = OpVars.visibleVars(result); + + if (!project.containsAll(tupleVars)) { + result = new OpProject(result, project); + } + + if (distinct) { + result = new OpDistinct(result); + } + return result; + } + + private static Op tupleToOp(Node[] t) { + Op result = switch (t.length) { + case 3 -> new OpBGP(new BasicPattern(List.of(Triple.create(t[0], t[1], t[2])))); + case 4 -> OpQuadBlock.create(t[0], new BasicPattern(List.of(Triple.create(t[1], t[2], t[3])))); + default -> throw new IllegalStateException(); + }; + return result; + } + + @Override + public String toString() { + return "PatternQuery [distinct=" + distinct + ", project=" + project + ", tuple=" + Arrays.toString(tuple) + "]"; + } + + /** Transform an array of nodes. Akin to {@link NodeTransformLib}. */ + private static Node[] transform(NodeTransform nodeTransform, Node[] tuple) { + int n = tuple.length; + Node[] newTuple = new Node[n]; + for (int i = 0; i < n; ++i) { + Node node = tuple[i]; + newTuple[i] = nodeTransform.apply(node); + } + return newTuple; + } + + /** Substitute all variables in a PatternQuery. Akin to {@link Substitute}. */ + public static PatternQuery substitute(PatternQuery patternQuery, Binding binding) { + Node[] newTuple = transform(n -> Var.lookup(binding, n), patternQuery.tuple); + Builder builder = ImmutableUniqueList.newUniqueListBuilder(); + for (Var v : patternQuery.project) { + if (!binding.contains(v)) { + builder.add(v); + } + } + ImmutableUniqueList newProject = builder.build(); + return new PatternQuery(patternQuery.distinct, newProject, newTuple); + } + + private static final Node CONST = NodeFactory.createLiteralString("C"); + + + /** + * Create a cache key representation of the argument: + *
    + *
  • Each unique variable is deterministically mapped to a fresh one in the order of their occurrence in the tuple.
  • + *
  • All constants are re-mapped to the same special constant.
  • + *
+ * + * For example (project (?p) (quad ?g :s ?p :o)) becomes (project (?V1) quad(?V0 :C ?V1 :C)) + */ + public static PatternQuery toCacheKey(PatternQuery patternQuery) { + Map map = new HashMap<>(); + VarAlloc varAlloc = new VarAlloc("V"); + + NodeTransform xform = n -> { + Node r; + if (n.isVariable()) { + r = map.computeIfAbsent(n, k -> varAlloc.allocVar()); + } else if (n.isConcrete()) { + r = map.computeIfAbsent(n, k -> CONST); + } else { + throw new IllegalStateException("Should never come here"); + } + return r; + }; + + Node[] newTuple = transform(xform, patternQuery.tuple()); + + List newProject = new ArrayList<>(patternQuery.tuple().length); + for (Var v : patternQuery.project()) { + Var newV = (Var)map.get(v); + if (newV != null) { + newProject.add(newV); + } + } + + return new PatternQuery(patternQuery.distinct(), newProject, newTuple); + } +} diff --git a/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/SkipScanCandidate.java b/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/SkipScanCandidate.java new file mode 100644 index 00000000000..b3e20896985 --- /dev/null +++ b/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/SkipScanCandidate.java @@ -0,0 +1,29 @@ +/* + * 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 + * + * https://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. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +package org.apache.jena.tdb2.solver.skipscan; + +import org.apache.jena.tdb2.store.tupletable.TupleIndex; + +/** + * A usable index together with the information needed to plan and execute a skip-scan. + */ +record SkipScanCandidate(TupleIndex index, IndexMatch match) {} diff --git a/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/SkipScanRewrite.java b/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/SkipScanRewrite.java new file mode 100644 index 00000000000..0f8cad94253 --- /dev/null +++ b/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/SkipScanRewrite.java @@ -0,0 +1,253 @@ +/* + * 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 + * + * https://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. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +package org.apache.jena.tdb2.solver.skipscan; + +import java.util.List; + +import org.apache.jena.sparql.algebra.Op; +import org.apache.jena.sparql.algebra.OpVisitorByTypeBase; +import org.apache.jena.sparql.algebra.OpWalker; +import org.apache.jena.sparql.algebra.Transformer; +import org.apache.jena.sparql.algebra.op.OpBGP; +import org.apache.jena.sparql.algebra.op.OpDistinct; +import org.apache.jena.sparql.algebra.op.OpExt; +import org.apache.jena.sparql.algebra.op.OpExtend; +import org.apache.jena.sparql.algebra.op.OpFilter; +import org.apache.jena.sparql.algebra.op.OpGroup; +import org.apache.jena.sparql.algebra.op.OpProject; +import org.apache.jena.sparql.algebra.op.OpQuadPattern; +import org.apache.jena.sparql.core.BasicPattern; +import org.apache.jena.sparql.core.Var; +import org.apache.jena.sparql.engine.join.ImmutableUniqueList; +import org.apache.jena.sparql.expr.Expr; +import org.apache.jena.sparql.expr.ExprAggregator; +import org.apache.jena.sparql.expr.ExprList; +import org.apache.jena.sparql.expr.aggregate.AggAvgDistinct; +import org.apache.jena.sparql.expr.aggregate.AggCountVarDistinct; +import org.apache.jena.sparql.expr.aggregate.AggGroupConcatDistinct; +import org.apache.jena.sparql.expr.aggregate.AggMax; +import org.apache.jena.sparql.expr.aggregate.AggMedianDistinct; +import org.apache.jena.sparql.expr.aggregate.AggMin; +import org.apache.jena.sparql.expr.aggregate.AggModeDistinct; +import org.apache.jena.sparql.expr.aggregate.AggSampleDistinct; +import org.apache.jena.sparql.expr.aggregate.AggSumDistinct; +import org.apache.jena.sparql.expr.aggregate.Aggregator; +import org.apache.jena.sparql.expr.aggregate.AggregatorFactory; + +public class SkipScanRewrite { + + /** + * Returns true iff the argument matches the structure below. + * Brackets indicate optional operation types. + * + *
{@code
+     * OpDistinct
+     *   OpProject
+     *     [OpFilter]
+     *       [OpExtend]
+     *         OpBGP|OpQuadPattern with a single triple/quad
+     * }
+ */ + public static boolean isSkipScanCandidate(Op inputOp) { + boolean result = false; + + Op op = inputOp; + if (op instanceof OpDistinct opD) { + op = opD.getSubOp(); + } + + if (op instanceof OpProject opP) { + op = opP.getSubOp(); + } + + if (op instanceof OpFilter opF) { + op = opF.getSubOp(); + } + + if (op instanceof OpExtend opE) { + op = opE.getSubOp(); + } + + BasicPattern bp = null; + if (op instanceof OpQuadPattern opQuadPattern) { + bp = opQuadPattern.getBasicPattern(); + } else if (op instanceof OpBGP opBgp) { + bp = opBgp.getPattern(); + } + + if (bp != null && bp.size() == 1) { + result = true; + } + return result; + } + + /** + * Attempt to rewrite an OpDistinct(...) as a skip scan. + */ + public static Op tryRewriteAsSkipScan(OpDistinct op) { + if (isSkipScanCandidate(op)) { + Op op1 = Transformer.transform(new TransformDistinctPlacement(), op); + + TransformSkipScan xform = new TransformSkipScan(); + Op op2 = Transformer.transform(xform, op1); + + // Only return the transformation result if a skip scan was injected. + if (xform.getNumAppliedSkipScanTransforms() > 0) { + return op2; + } + } + return null; + } + + public static Op tryRewriteAsSkipScan(OpGroup opGroup) { + // For now, restrict the skip scan rewrite to opGroups without expressions - just variables. + // For future optimization: If the expressions are deterministically dependent on the group vars, we could + // actually do a skip scan on the group vars. + if (opGroup.getGroupVars().getExprs().isEmpty()) { + // If all aggregators use the same variable then the same index can be used to answer all of them. + Var aggVar = null; + for (ExprAggregator exprAgg : opGroup.getAggregators()) { + Aggregator agg = exprAgg.getAggregator(); + Var contribVar = suitableVarOrNull(agg); + if (contribVar == null || (aggVar != null && !aggVar.equals(contribVar))) { + aggVar = null; + break; + } + aggVar = contribVar; + } + + if (aggVar != null) { + ImmutableUniqueList newProj = ImmutableUniqueList.newUniqueListBuilder() + .addAll(opGroup.getGroupVars().getVars()) + .add(aggVar) + .build(); + OpDistinct newOp = new OpDistinct(new OpProject(opGroup.getSubOp(), newProj)); + + Op patternOp = SkipScanRewrite.tryRewriteAsSkipScan(newOp); + if (patternOp != null) { + // Remove redundant distinct from aggregators - it is ensured by the pattern execution. + List newAggs = opGroup.getAggregators().stream() + .map(SkipScanRewrite::convertToNonDistinct).toList(); + patternOp = new OpGroup(patternOp, opGroup.getGroupVars(), newAggs); + return patternOp; + } + } + } + return null; + } + + /** + * If the aggregator is suitable for skip-scan execution then return its single + * value variable, else null. + * + *

An aggregator is suitable iff its result is invariant under removing duplicate + * values of a single value expression that is a plain variable. This covers every + * DISTINCT single-var aggregator (COUNT, SUM, AVG, MEDIAN, MODE, SAMPLE, GROUP_CONCAT) + * plus the non-distinct MIN, MAX and SAMPLE aggregators (for which DISTINCT is + * irrelevant).

+ */ + private static Var suitableVarOrNull(Aggregator agg) { + if (!isSkipScanSuitable(agg)) { + return null; + } + return varOrNull(agg); + } + + private static boolean isSkipScanSuitable(Aggregator agg) { + return agg instanceof AggCountVarDistinct + || agg instanceof AggSumDistinct + || agg instanceof AggAvgDistinct + || agg instanceof AggMedianDistinct + || agg instanceof AggModeDistinct + || agg instanceof AggSampleDistinct + || agg instanceof AggGroupConcatDistinct + // Non-distinct MIN/MAX are distinct-invariant. + || agg instanceof AggMin + || agg instanceof AggMax; + // For sample retain the original distribution - so exclude. + // || agg instanceof AggSample + } + + private static ExprAggregator convertToNonDistinct(ExprAggregator eAgg) { + Aggregator newAgg = convertToNonDistinct(eAgg.getAggregator()); + return new ExprAggregator(eAgg.getVar(), newAgg); + } + + /** + * Convert a (possibly DISTINCT) skip-scan-suitable aggregator into its non-distinct + * equivalent. Because the skip-scan input yields each value at most once per group, + * the non-distinct aggregator computes the same result. MIN/MAX/SAMPLE (already + * distinct-invariant) are returned unchanged. + */ + private static Aggregator convertToNonDistinct(Aggregator agg) { + Expr expr = agg.getExprList().get(0); + if (agg instanceof AggCountVarDistinct) { + return AggregatorFactory.createCountExpr(false, expr); + } else if (agg instanceof AggSumDistinct) { + return AggregatorFactory.createSum(false, expr); + } else if (agg instanceof AggAvgDistinct) { + return AggregatorFactory.createAvg(false, expr); + } else if (agg instanceof AggMedianDistinct) { + return AggregatorFactory.createMedian(false, expr); + } else if (agg instanceof AggModeDistinct) { + return AggregatorFactory.createMode(false, expr); + } else if (agg instanceof AggSampleDistinct) { + return AggregatorFactory.createSample(false, expr); + } else if (agg instanceof AggGroupConcatDistinct acd) { + return AggregatorFactory.createGroupConcat(false, expr, acd.getSeparator(), null); + } + // AggMin, AggMax, AggSample: already non-distinct and distinct-invariant. + return agg; + } + + /** Extract the first argument of the agg's exprList as a Var, or null. */ + private static Var varOrNull(Aggregator agg) { + ExprList el = agg.getExprList(); + if (el == null || el.size() != 1) { + return null; + } + Expr e = el.get(0); + return e.isVariable() ? e.asVar() : null; + } + + private static class AbortEarlyException extends RuntimeException { + private static final long serialVersionUID = 1L; + @Override public synchronized Throwable fillInStackTrace() { return this; } + } + + public static boolean usesSkipScan(Op op) { + boolean[] result = {false}; + try { + OpWalker.walk(op, new OpVisitorByTypeBase() { + @Override + public void visit(OpExt opExt) { + if (opExt instanceof OpExtSkipScan) { + result[0] = true; + throw new AbortEarlyException(); + } + } + }); + } catch (AbortEarlyException e) {} + return result[0]; + } +} + diff --git a/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/TransformDistinctPlacement.java b/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/TransformDistinctPlacement.java new file mode 100644 index 00000000000..5fbdf6adf35 --- /dev/null +++ b/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/TransformDistinctPlacement.java @@ -0,0 +1,239 @@ +/* + * 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 + * + * https://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. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +package org.apache.jena.tdb2.solver.skipscan; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.function.BiPredicate; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.apache.jena.atlas.lib.SetUtils; +import org.apache.jena.sparql.algebra.Op; +import org.apache.jena.sparql.algebra.OpVars; +import org.apache.jena.sparql.algebra.OpVisitorBase; +import org.apache.jena.sparql.algebra.TransformCopy; +import org.apache.jena.sparql.algebra.op.Op1; +import org.apache.jena.sparql.algebra.op.OpDistinct; +import org.apache.jena.sparql.algebra.op.OpExtend; +import org.apache.jena.sparql.algebra.op.OpFilter; +import org.apache.jena.sparql.algebra.op.OpProject; +import org.apache.jena.sparql.core.Var; +import org.apache.jena.sparql.core.VarExprList; +import org.apache.jena.sparql.expr.Expr; +import org.apache.jena.sparql.expr.ExprLib; +import org.apache.jena.sparql.expr.ExprList; + +public class TransformDistinctPlacement + extends TransformCopy +{ + @Override + public Op transform(OpDistinct opDistinct, Op subOp) { + Set projectVars = new LinkedHashSet<>(); + OpVars.visibleVars(subOp, projectVars); + Op result = OpVisitorDistinctPlacement.transform(projectVars, subOp); + return result; + } + + /** + * The visitor does the actual top-down rewrite. + * For each encountered Op, the visitor creates a new instance of itself + * that holds the transformation result. + */ + private static class OpVisitorDistinctPlacement + extends OpVisitorBase + { + private Set projectVars; + private Op result; + + public OpVisitorDistinctPlacement(Set projectVars) { + super(); + this.projectVars = Objects.requireNonNull(projectVars); + } + + public Op getResult() { + return result; + } + + public static Op transform(Set projectVars, Op op) { + OpVisitorDistinctPlacement visitor = new OpVisitorDistinctPlacement(projectVars); + op.visit(visitor); + Op r = visitor.getResult(); + // A null result means 'stop pushing': place the distinct+projection here. + Op result = r == null ? placeDistinctProject(projectVars, op) : r; + return result; + } + + /** Inject (distinct (project (projectVars') op)) */ + private static Op placeDistinctProject(Set projectVars, Op op) { + Set visibleVars = OpVars.visibleVars(op); + + Op projectionAdaptedOp = op; + + // If the visible variables differ from in-scope projectVars then place the projection. + Set inScopeProjectVars = SetUtils.intersection(projectVars, visibleVars); + if (!inScopeProjectVars.containsAll(visibleVars)) { + List projectVarList = new ArrayList<>(inScopeProjectVars); + projectionAdaptedOp = new OpProject(projectionAdaptedOp, projectVarList); + } + + return OpDistinct.create(projectionAdaptedOp); + } + + /** Process (distinct (projectVars) (project (vars) (.))). + * + * (distinct (?x ?y ?z) .) can be pushed over a (project (?y ?a) .) + * (distinct (?y) .) + * - so we can push over any project by creating the intersection of the involved variables. */ + @Override + public void visit(OpProject opProject) { + Set vars = new LinkedHashSet<>(opProject.getVars()); // Retain order + vars.retainAll(projectVars); + + // Create the intersection of the current distinct-vars and the project-vars. + // In the corner case where this set is empty, just don't push. + boolean canPush = !vars.isEmpty(); + if (canPush) { + Op subOp = opProject.getSubOp(); + // Proceed with the variables of the projection + // (possibly a sub-set of the original distinct-vars). + result = transform(vars, subOp); + } + } + + @Override + public void visit(OpExtend opExtend) { + tryPush(opExtend, (opE, subOpVars) -> canPush(projectVars, opE)); + // Post process the result: After pushing (distinct (vars) .) over (extend .), + // the variables visible from extend must remain the same. + if (result != null) { + List extendVars = opExtend.getVarExprList().getVars(); + boolean reapplyProject = !projectVars.containsAll(extendVars); + if (reapplyProject) { + result = new OpProject(result, new ArrayList<>(extendVars)); + } + } + } + + @Override + public void visit(OpFilter opFilter) { + tryPush(opFilter, (opF, subOpVars) -> canPush(projectVars, opF)); + } + + /** Merge nested distinct. */ + @Override + public void visit(OpDistinct opDistinct) { + Op subOp = opDistinct.getSubOp(); + result = transform(projectVars, subOp); + } + + private void tryPush(T op1, BiPredicate> canPush) { + if (canPush.test(op1, projectVars)) { + Op subOp = op1.getSubOp(); + // We could already prune projectVars to the visible vars of subOp here. + // But we postpone this to the point where we place the distinct operator + // using placeDistinctProject. + Op rewrittenSubOp = transform(projectVars, subOp); + result = op1.copy(rewrittenSubOp); + } else { + result = placeDistinctProject(projectVars, op1); + } + } + + private static boolean canPush(Set projectVars, OpExtend opExtend) { + VarExprList extend = opExtend.getVarExprList(); + boolean isStable = extend.getExprs().values().stream().allMatch(ExprLib::isStable); + if (!isStable) { + return false; + } + + Op subOp = opExtend.getSubOp(); + Set subOpVars = OpVars.visibleVars(subOp); + Set mentionedVars = varsMentioned(extend); + + if (!isSameCoverage(mentionedVars, subOpVars, projectVars)) { + return false; + } + + return true; + } + + private static boolean canPush(Set projectVars, OpFilter opFilter) { + ExprList filter = opFilter.getExprs(); + + // Don't push distinct over unstable expressions, such as rand() or uuid(). + boolean isStable = filter.getList().stream().allMatch(ExprLib::isStable); + if (!isStable) { + return false; + } + // Example: Can we push DISTINCT ?s ?p over (filter (?p = ?x) (bgp (:s ?p :o))) ? + + // filter(?p = ?x) mentions {?p, ?x} + Set filterVars = filter.getVarsMentioned(); + + // Assume subOp := (bgp (:s ?p :o)) which mentions {?p} + Op subOp = opFilter.getSubOp(); + Set subOpVars = OpVars.visibleVars(subOp); + + // Of the filter's variables {?p, ?x} only {?p} is in scope in the subOp + // and "grounds" the filter's {?p}. + Set inScopeFilterVars = SetUtils.intersection(filterVars, subOpVars); + + // If the distinct-transforms's projectVars contains all the filter's grounded vars then we can push. + if (projectVars.containsAll(inScopeFilterVars)) { + // Our DISTINCT ?s ?p covers all grounded variables of the filter expression, namely {p} + // So we can push. + return true; + } + return false; + } + + private static Set varsMentioned(VarExprList vel) { + Set mentionedVars = varsMentioned(vel.getExprs().values().stream()); + return mentionedVars; + } + + private static Set varsMentioned(Stream exprs) { + Set mentionedVars = exprs + .map(Expr::getVarsMentioned) + .flatMap(Collection::stream) + .collect(Collectors.toSet()); + return mentionedVars; + } + + /** + * True iff the exact same set of mentioned variables is covered by both + * the original projectVars and the sub op's visible variables. + */ + private static boolean isSameCoverage(Set mentionedVars, Set subOpVars, Set projectVars) { + Set coveredVarsBefore = SetUtils.intersection(mentionedVars, subOpVars); + Set coveredVarsAfter = SetUtils.intersection(mentionedVars, projectVars); + boolean result = coveredVarsBefore.equals(coveredVarsAfter); + return result; + } + } +} + diff --git a/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/TransformSkipScan.java b/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/TransformSkipScan.java new file mode 100644 index 00000000000..c598d7030ff --- /dev/null +++ b/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/TransformSkipScan.java @@ -0,0 +1,47 @@ +/* + * 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 + * + * https://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. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +package org.apache.jena.tdb2.solver.skipscan; + +import org.apache.jena.sparql.algebra.Op; +import org.apache.jena.sparql.algebra.TransformCopy; +import org.apache.jena.sparql.algebra.op.OpDistinct; + +public class TransformSkipScan + extends TransformCopy +{ + private int numAppliedTransforms = 0; + + public int getNumAppliedSkipScanTransforms() { + return numAppliedTransforms; + } + + @Override + public Op transform(OpDistinct opDistinct, Op subOp) { + Op result = super.transform(opDistinct, subOp); // effectively `new OpDistinct(subOp)`; + PatternQuery pq = PatternQuery.createOrNull$(result); + if (pq != null) { + result = new OpExtSkipScan(pq); + ++numAppliedTransforms; + } + return result; + } +} diff --git a/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/TuplePatternSpec.java b/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/TuplePatternSpec.java new file mode 100644 index 00000000000..ffbaa6e1ce9 --- /dev/null +++ b/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/TuplePatternSpec.java @@ -0,0 +1,147 @@ +/* + * 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 + * + * https://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. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +package org.apache.jena.tdb2.solver.skipscan; + +import java.util.Arrays; +import java.util.List; + +import org.apache.jena.graph.Node; +import org.apache.jena.sparql.core.Var; + +/** + * projs maps slot to the varMap. + */ +record TuplePatternSpec( + Node[] tuple, + List projection, // JoinKey is a list with unique elements. + VarMap[] varMaps, + int[] projs, // array of projected indices - get the var using tuple[projs[i]] + EqualityLink[] equalityLinks, + int neededSlotsMask) { // Omits the indices of unconstrained, undistinguished var. + + public Var getVar(int varId) { + return varMaps[varId].var(); + } + + /** Get the index of the variable or -1 if absent. */ + public int getIdxVar(Var var) { + for (VarMap e : varMaps) { + if (e.var().equals(var)) { + return e.idx(); + } + } + return -1; + } + + @Override + public String toString() { + return "IndexQuerySpec [tuple=" + Arrays.toString(tuple) + ", varMaps=" + Arrays.toString(varMaps) + ", projs=" + + Arrays.toString(projs) + ", equalityLinks=" + + Arrays.toString(equalityLinks) + ", neededSlots=" + Integer.toBinaryString(neededSlotsMask) + "]"; + } + + public static TuplePatternSpec create(Node[] quad, List projection) { + // Helper arrays are created with maximum possible size here. + int n = quad.length; + + // varMap will only holds vars that are present in the tuple. + VarMap[] varMaps = new VarMap[n]; + int numVarMaps = 0; + + EqualityLink[] equalityLinks = null; + int numEqualityLinks = 0; + + int[] projs = new int[n]; + int numProjs = 0; + + // Needed slots: those that are projected or participate in an equality condition with a constant or another column. + int[] neededSlots = new int[n]; + int numNeededSlots = 0; + + for (int i = 0; i < n; ++i) { + Node node = quad[i]; + if (node.isVariable()) { + boolean alreadySeen = false; + for (int j = 0; j < i; ++j) { + Node prevNode = quad[j]; + if (node.equals(prevNode)) { + if (equalityLinks == null) { + equalityLinks = new EqualityLink[n]; + } + equalityLinks[numEqualityLinks++] = new EqualityLink(i, j); + + // Add i as needed + neededSlots[numNeededSlots++] = i; + alreadySeen = true; + + // If the var was not projected then we now need to declare it as needed! + if (!projection.contains(node)) { + int i2 = indexOf(neededSlots, j, 0, numNeededSlots); + if (i2 == -1) { + neededSlots[numNeededSlots++] = j; + } + } + } + } + + if (!alreadySeen) { + Var v = Var.alloc(node); + varMaps[numVarMaps] = new VarMap(i, v); + + if (projection.contains(v)) { + projs[numProjs++] = i; + neededSlots[numNeededSlots++] = i; + } + + ++numVarMaps; + } + } else { + // Mark the slot as needed because it needs to be post-filtered by a constant. + neededSlots[numNeededSlots++] = i; + } + } + + int neededSlotMask = 0; + for (int i = 0; i < numNeededSlots; ++i) { + neededSlotMask |= 1 << neededSlots[i]; + } + + TuplePatternSpec result = new TuplePatternSpec( + quad, + projection, + Arrays.copyOf(varMaps, numVarMaps), + Arrays.copyOf(projs, numProjs), + equalityLinks == null ? null : Arrays.copyOf(equalityLinks, numEqualityLinks), + neededSlotMask); + return result; + } + + /** Find an item in a certain sub-range. */ + private static int indexOf(int[] arr, int valueToFind, int startIndex, int endIndex) { + for (int i = startIndex; i < endIndex; ++i) { + if (arr[i] == valueToFind) { + return i; + } + } + return -1; + } +} diff --git a/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/ValueFilter.java b/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/ValueFilter.java new file mode 100644 index 00000000000..de0f63350ab --- /dev/null +++ b/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/ValueFilter.java @@ -0,0 +1,25 @@ +/* + * 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 + * + * https://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. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +package org.apache.jena.tdb2.solver.skipscan; + +/** Map the index of a column to a constant value, such as a specific Node or NodeId. */ +record ValueFilter(int idx, T value) {} diff --git a/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/VarMap.java b/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/VarMap.java new file mode 100644 index 00000000000..f392f2b422a --- /dev/null +++ b/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/VarMap.java @@ -0,0 +1,27 @@ +/* + * 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 + * + * https://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. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +package org.apache.jena.tdb2.solver.skipscan; + +import org.apache.jena.sparql.core.Var; + +/** Map the index of a column to a variable. */ +record VarMap(int idx, Var var) {} diff --git a/jena-tdb2/src/main/java/org/apache/jena/tdb2/sys/SystemTDB.java b/jena-tdb2/src/main/java/org/apache/jena/tdb2/sys/SystemTDB.java index 57c9d8f7147..1122c3e82ec 100644 --- a/jena-tdb2/src/main/java/org/apache/jena/tdb2/sys/SystemTDB.java +++ b/jena-tdb2/src/main/java/org/apache/jena/tdb2/sys/SystemTDB.java @@ -41,6 +41,7 @@ import org.apache.jena.sys.JenaSystem; import org.apache.jena.tdb2.TDB2; import org.apache.jena.tdb2.TDBException; +import org.apache.jena.tdb2.solver.OpExecutorTDB2; import org.apache.jena.tdb2.store.NodeId; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -123,6 +124,10 @@ private SystemTDB() { } /** Experimental : triple and quad filtering at scan level */ public static final Symbol symTupleFilter = allocSymbol("tupleFilter"); + /** Allow skip scans for {@code OpDistinct} and {@code OpGroup} operators. + * Absent value is treated as allowed. See {@link OpExecutorTDB2}. */ + public static final Symbol symSkipScan = allocSymbol("skipScan"); + private static final String PropertyFileKey1 = tdbPropertyRoot+".settings"; private static final String PropertyFileKey2 = tdbSymbolPrefix+":settings"; diff --git a/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan/AbstractDatasetGraphCompare.java b/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan/AbstractDatasetGraphCompare.java new file mode 100644 index 00000000000..ee97fee0cc9 --- /dev/null +++ b/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan/AbstractDatasetGraphCompare.java @@ -0,0 +1,149 @@ +/* + * 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 + * + * https://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. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +package org.apache.jena.tdb2.solver.skipscan; + +import java.util.Arrays; +import java.util.Iterator; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import java.util.stream.Stream; + +import org.apache.commons.lang3.stream.IntStreams; +import org.apache.commons.numbers.combinatorics.Combinations; +import org.apache.jena.atlas.iterator.Iter; +import org.apache.jena.graph.Node; +import org.apache.jena.graph.NodeFactory; +import org.apache.jena.sparql.core.DatasetGraph; +import org.apache.jena.sparql.core.Quad; +import org.apache.jena.sparql.graph.NodeTransformLib; + +/** + * Test to check consistency of the find() method. + * + * Base class for generating tests that invoke the find() method of a dataset graph + * with all combinations of patterns. + */ +public abstract class AbstractDatasetGraphCompare { + private String testLabel; + + public AbstractDatasetGraphCompare(String testLabel) { + super(); + this.testLabel = testLabel; + } + + public String getTestLabel() { + return testLabel; + } + + /* Below: Quad generation for use with .find() or querying from dataset content. */ + + // Markers for find-quad generation w.r.t. a dataset and a + // "meta pattern" such as (IN, foo, OUT, OUT). + // IN becomes substituted with concrete values, out becomes ANY. + private static final Node IN = NodeFactory.createBlankNode("IN"); + private static final Node OUT = NodeFactory.createBlankNode("OUT"); + + /** + * Generate the set of find patterns for each quad in the source dataset. + * This is the set of combinations by substituting components with ANY. + * For example, the derivations for a concrete quad (g, s, p, o) are: + *
+     * {(g, s, p, ANY), (g, s, ANY, o), (g, s, ANY, ANY), ...}
+     * 
+ */ + public static Stream createFindQuads(DatasetGraph dataSource) { + Node[] baseMetaPattern = new Node[]{OUT, OUT, OUT, OUT}; + Stream result = IntStream.rangeClosed(0, 4).boxed() + .flatMap(k -> Iter.asStream(Combinations.of(4, k).iterator())) + .flatMap(ins -> { + Node[] metaPattern = Arrays.copyOf(baseMetaPattern, baseMetaPattern.length); + + // Use IN to mark the components that we want to substitute with concrete values. + // OUT becomes ANY. + IntStreams.of(ins).forEach(i -> metaPattern[i] = IN); + Quad metaQuad = toQuad(List.of(metaPattern).iterator()); + + Set lookups = createFindQuads(dataSource, metaQuad); + return lookups.stream(); + }); + return result; + } + + private static Quad toQuad(Iterator it) { + Quad r = Quad.create(it.next(), it.next(), it.next(), it.next()); + if (it.hasNext()) { + throw new IllegalArgumentException("Iterator of exactly 4 elements expected."); + } + return r; + } + + private static Node outToAny(Node pattern, Node concrete) { + Node r = (OUT.equals(pattern)) ? Node.ANY : concrete; + return r; + } + + private static Node inToAny(Node node) { + Node r = (IN.equals(node)) ? Node.ANY : node; + return r; + } + + private static Node outToAny(Node node) { + Node r = (OUT.equals(node)) ? Node.ANY : node; + return r; + } + + private static Quad inToAny(Quad metaQuad) { + return NodeTransformLib.transform(AbstractDatasetGraphCompare::inToAny, metaQuad); + } + + private static Quad outToAny(Quad metaQuad) { + return NodeTransformLib.transform(AbstractDatasetGraphCompare::outToAny, metaQuad); + } + + // !!! This method implicitly gets rid of 'IN' !!! + // Components of the input quads are processed as follows: + // If a component of pattern is OUT then it becomes is ANY. + // Otherwise, *always* return the corresponding component of 'concrete'. + private static Quad createFindQuad(Quad meta, Quad concrete) { + Quad result = Quad.create( + outToAny(meta.getGraph(), concrete.getGraph()), + outToAny(meta.getSubject(), concrete.getSubject()), + outToAny(meta.getPredicate(), concrete.getPredicate()), + outToAny(meta.getObject(), concrete.getObject())); + return result; + } + + /** + * Expand a pattern such as (IN, s, OUT, OUT) into { (g1, s, ANY, ANY), (g2, s, ANY, ANY) } + * based on the concrete quads in dsg. + */ + private static Set createFindQuads(DatasetGraph dsg, Quad metaQuad) { + // Replace IN and OUT with ANY - this retains only term nodes. + Quad p = outToAny(inToAny(metaQuad)); + Set result = Iter.collect(Iter.map(dsg.find(p), q -> createFindQuad(metaQuad, q)), + Collectors.toCollection(LinkedHashSet::new)); + return result; + } +} diff --git a/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan/GraphCompareSelectResultExecutable.java b/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan/GraphCompareSelectResultExecutable.java new file mode 100644 index 00000000000..b5cdc211c4c --- /dev/null +++ b/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan/GraphCompareSelectResultExecutable.java @@ -0,0 +1,111 @@ +/* + * 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 + * + * https://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. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +package org.apache.jena.tdb2.solver.skipscan; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.PrintStream; +import java.util.ArrayList; +import java.util.List; + +import org.junit.jupiter.api.function.Executable; + +import org.apache.jena.atlas.lib.ListUtils; +import org.apache.jena.query.Query; +import org.apache.jena.sparql.algebra.Table; +import org.apache.jena.sparql.core.DatasetGraph; +import org.apache.jena.sparql.engine.binding.Binding; +import org.apache.jena.sparql.exec.QueryExec; +import org.apache.jena.sparql.exec.QueryExecBuilder; +import org.apache.jena.sparql.exec.RowSetOps; +import org.apache.jena.system.Txn; + +/** + * JUnit test case executable to compare two datasets w.r.t. + * their result of a select query. + */ +public class GraphCompareSelectResultExecutable + implements Executable +{ + private static PrintStream out = System.err; + + private String testLabel; + private Query query; + private DatasetGraph referenceDsg; + private DatasetGraph systemUnderTestDsg; + + public GraphCompareSelectResultExecutable(String testLabel, Query query, DatasetGraph referenceDsg, DatasetGraph systemUnderTestDsg) { + super(); + this.testLabel = testLabel; + this.query = query; + this.referenceDsg = referenceDsg; + this.systemUnderTestDsg = systemUnderTestDsg; + } + + protected QueryExecBuilder mutateTestExecBuilder(QueryExecBuilder qExec) { return qExec; } + + public String getTestLabel() { + return testLabel; + } + + public Query getQuery() { + return query; + } + + /** + * Assert that graph.find() returned the same set of quads for the given pattern. + * Duplicates are ignored. + */ + @Override + public void execute() { + Table expectedTable = Txn.calculateRead(referenceDsg, + () -> QueryExec.dataset(referenceDsg).query(query).table()); + List expectedList = new ArrayList<>(); + expectedTable.rows().forEachRemaining(expectedList::add); + + Table actualTable = Txn.calculateRead(systemUnderTestDsg, + () -> mutateTestExecBuilder(QueryExec.dataset(systemUnderTestDsg).query(query)) + .table()); + List actualList = new ArrayList<>(); + actualTable.rows().forEachRemaining(actualList::add); + + boolean printActualResult = false; + if (printActualResult) { + RowSetOps.out(System.err, actualTable.toRowSet()); + System.err.println("Number of rows printed: " + actualTable.size()); + System.err.println(); + } + + boolean b = ListUtils.equalsUnordered(expectedList, actualList); + if ( ! b ) { + out.println("Fail: find(" + query + ")"); + out.println("Expected: " + expectedList + ", Actual: " + actualList); + } + + assertTrue(b, () -> getTestLabel()); + } + + @Override + public String toString() { + return getTestLabel() + " " + getQuery(); + } +} diff --git a/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan/GraphCompareSelectResultExecutableSkipScan.java b/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan/GraphCompareSelectResultExecutableSkipScan.java new file mode 100644 index 00000000000..8778b11f612 --- /dev/null +++ b/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan/GraphCompareSelectResultExecutableSkipScan.java @@ -0,0 +1,64 @@ +/* + * 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 + * + * https://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. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +package org.apache.jena.tdb2.solver.skipscan; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.concurrent.atomic.LongAdder; + +import org.apache.jena.query.Query; +import org.apache.jena.sparql.core.DatasetGraph; +import org.apache.jena.sparql.exec.QueryExecBuilder; + +/** Extension of the GraphCompare executable with verification that skip scan was actually used. */ +class GraphCompareSelectResultExecutableSkipScan + extends GraphCompareSelectResultExecutable { + + private LongAdder skipScanOkCounter = new LongAdder(); + private LongAdder skipScanFailoverCounter = new LongAdder(); + private boolean expectSkipScan; + + public GraphCompareSelectResultExecutableSkipScan(String testLabel, Query query, DatasetGraph referenceDsg, + DatasetGraph testDsg, boolean expectSkipScan) { + super(testLabel, query, referenceDsg, testDsg); + this.expectSkipScan = expectSkipScan; + } + + @Override + protected QueryExecBuilder mutateTestExecBuilder(QueryExecBuilder qExec) { + return qExec + .set(OpExecutorTDB2SkipScan.symSkipScanOkCounter, skipScanOkCounter) + .set(OpExecutorTDB2SkipScan.symSkipScanFailoverCounter, skipScanFailoverCounter); + } + + @Override + public void execute() { + super.execute(); + if (expectSkipScan) { + assertTrue(skipScanOkCounter.longValue() > 0, () -> "Expected skip scan to be used - " + getTestLabel()); + assertEquals(0, skipScanFailoverCounter.longValue(), () -> getTestLabel()); + } else { + assertTrue(skipScanOkCounter.longValue() == 0, () -> "Expected NO skip scan to be used - " + getTestLabel()); + } + } +} diff --git a/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan/TS_TDB_SkipScan.java b/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan/TS_TDB_SkipScan.java new file mode 100644 index 00000000000..b979cf2553a --- /dev/null +++ b/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan/TS_TDB_SkipScan.java @@ -0,0 +1,35 @@ +/* + * 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 + * + * https://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. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +package org.apache.jena.tdb2.solver.skipscan; + +import org.junit.platform.suite.api.SelectClasses; +import org.junit.platform.suite.api.Suite; + +@Suite +@SelectClasses({ + TestFindBestIndex.class + , TestTransformDistinctPlacement.class + , TestOpExecutorTDB2SkipScan.class + , TestAggregatorsSkipScan.class +}) +public class TS_TDB_SkipScan { +} diff --git a/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan/TestAggregatorsSkipScan.java b/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan/TestAggregatorsSkipScan.java new file mode 100644 index 00000000000..98cc9bc532e --- /dev/null +++ b/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan/TestAggregatorsSkipScan.java @@ -0,0 +1,136 @@ +/* + * 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 + * + * https://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. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +package org.apache.jena.tdb2.solver.skipscan; + +import org.junit.jupiter.api.Test; + +import org.apache.jena.query.Query; +import org.apache.jena.query.QueryFactory; +import org.apache.jena.sparql.core.DatasetGraph; +import org.apache.jena.sparql.sse.SSE; +import org.apache.jena.tdb2.TDB2Factory; +import org.apache.jena.tdb2.sys.CopyDSG; +import org.apache.jena.tdb2.sys.TDBInternal; + +/** + * Base class for testing multi-aggregator queries with skip scan. + * + *

Tests verify that skip scan is used for queries with multiple aggregators + * that operate on compatible variables (same variable with compatible distinct semantics).

+ */ +public class TestAggregatorsSkipScan { + protected DatasetGraph referenceDsg; + protected DatasetGraph systemUnderTestDsg; + + public TestAggregatorsSkipScan() { + setupDataset(); + } + + // @BeforeAll + public void setupDataset() { + referenceDsg = SSE.parseDatasetGraph( + """ + (dataset + (graph + (:s :p 5) + (:s :p 7) + ) + (graph :g1 + (:s :p 7) + (:s :p 11) + ) + (graph :g2 + (:s :p 7) + (:s :p 17) + ) + ) + """); + + // Set up the test TDB2 dataset + systemUnderTestDsg = TDBInternal.getDatasetGraphTDB(TDB2Factory.createDataset()); + CopyDSG.copy(referenceDsg, systemUnderTestDsg); + } + + /** Min/max on the same variable should use skip scan. */ + @Test + public void test_skipScan_01_spo() { + expectSkipScan("SELECT (min(?o) AS ?min) (max(?o) AS ?max) { ?s ?p ?o }"); + } + + /** Min/max on the same variable should use skip scan. */ + @Test + public void test_skipScan_01_gspo() { + expectSkipScan("SELECT (min(?o) AS ?min) (max(?o) AS ?max) { GRAPH ?g { ?s ?p ?o } }"); + } + + /** Min/max on the same variable should use skip scan. */ + @Test + public void test_skipScan_01_union() { + expectSkipScan("SELECT (min(?o) AS ?min) (max(?o) AS ?max) { GRAPH { ?s ?p ?o } }"); + } + + /** distinct sum/avg */ + @Test + public void test_skipScan_03() { + expectSkipScan("SELECT (avg(DISTINCT ?o) AS ?avg) (sum(DISTINCT ?o) AS ?sum) { GRAPH ?g { ?s ?p ?o } }"); + } + + /** Sample should prevent skip scan in order to preserve value distribution. */ + @Test + public void test_no_skipScan_02() { + expectNoSkipScan("SELECT (min(?o) AS ?min) (sample(?o) AS ?max) { ?s ?p ?o }"); + } + + /** Mix of distinct / non-distinct aggregator - should not use skip scan. */ + @Test + public void test_no_skipScan_03() { + expectNoSkipScan("SELECT (min(?o) AS ?min) (avg(?o) AS ?avg) { ?s ?p ?o }"); + } + + /** Aggregation by different variables - should not use skip scan. */ + @Test + public void test_no_skipScan_04() { + expectNoSkipScan("SELECT (count(DISTINCT ?p) AS ?countP) (count(DISTINCT ?o) AS ?countO) { ?s ?p ?o }"); + } + + /** Count of all bindings (not a restricted to a specific variable) - should not use skip scan. */ + @Test + public void test_no_skipScan_05() { + expectNoSkipScan("SELECT (count(DISTINCT *) AS ?c) { GRAPH ?g { ?s ?p ?o } }"); + } + + /** Count distinct of a single variable - should use skip scan. */ + @Test + public void test_skipScan_06() { + expectSkipScan("SELECT (count(DISTINCT ?p) AS ?c) { GRAPH ?g { ?s ?p ?o } }"); + } + + public void expectSkipScan(String queryString) { test(queryString, true); } + public void expectNoSkipScan(String queryString) { test(queryString, false); } + + private void test(String queryString, boolean expectSkipScan) { + Query query = QueryFactory.create(queryString); + GraphCompareSelectResultExecutableSkipScan executable = + new GraphCompareSelectResultExecutableSkipScan("test", query, referenceDsg, systemUnderTestDsg, expectSkipScan); + executable.execute(); + } +} diff --git a/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan/TestFindBestIndex.java b/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan/TestFindBestIndex.java new file mode 100644 index 00000000000..f8d20345328 --- /dev/null +++ b/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan/TestFindBestIndex.java @@ -0,0 +1,140 @@ +/* + * 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 + * + * https://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. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +package org.apache.jena.tdb2.solver.skipscan; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.Objects; + +import org.junit.jupiter.api.Test; + +import org.apache.jena.sparql.algebra.Op; +import org.apache.jena.sparql.core.DatasetGraph; +import org.apache.jena.sparql.engine.ExecutionContext; +import org.apache.jena.sparql.sse.SSE; +import org.apache.jena.system.Txn; +import org.apache.jena.tdb2.TDB2Factory; +import org.apache.jena.tdb2.sys.TDBInternal; + +public class TestFindBestIndex { + + private static final String TRIPLE_DATASET = """ + (dataset + (graph + (:s :p :oa) + (:s :p :ob) + ) + (graph :g1 + (:s :p :oa) + (:s :p :ob) + ) + (graph :g2 + (:s :p :oa) + (:s :p :ob) + ) + ) + """; + + @Test + public void testProject_s_01() { + testIndexSelection("(distinct (project (?s) (bgp (?s ?p ?o))))", "SPO"); + } + + @Test + public void testProject_p_01() { + testIndexSelection("(distinct (project (?p) (bgp (?s ?p ?o))))", "POS"); + } + + @Test + public void testProject_o_01() { + testIndexSelection("(distinct (project (?o) (bgp (?s ?p ?o))))", "OSP"); + } + + @Test + public void testProject_sp_01() { + testIndexSelection("(distinct (project (?s ?p) (bgp (?s ?p ?o))))", "SPO"); + } + + @Test + public void testProject_so_01() { + testIndexSelection("(distinct (project (?s ?o) (bgp (?s ?p ?o))))", "OSP"); + } + + @Test + public void testProject_po_01() { + testIndexSelection("(distinct (project (?p ?o) (bgp (?s ?p ?o))))", "POS"); + } + + @Test + public void testProject_spo_01() { + testIndexSelection("(distinct (project (?s ?p ?o) (bgp (?s ?p ?o))))", "SPO"); + } + + @Test + public void testNoDistinct_s_01() { + testIndexSelection("(project (?s) (bgp (?s ?p ?o)))", "SPO"); + } + + @Test + public void testNoDistinct_p_01() { + testIndexSelection("(project (?p) (bgp (?s ?p ?o)))", "POS"); + } + + @Test + public void testAllConstants_01() { + testIndexSelection("(distinct (project (?s) (bgp (:s :p :o))))", "SPO"); + } + + @Test + public void testMixedConstants_sp_01() { + testIndexSelection("(distinct (project (?p) (bgp (:s ?p :o))))", "OSP"); + } + + @Test + public void testMixedConstants_so_01() { + testIndexSelection("(distinct (project (?s ?o) (bgp (?s :p ?o))))", "POS"); + } + + @Test + public void testConstant_first_01() { + testIndexSelection("(distinct (project (?p ?o) (bgp (:s ?p ?o))))", "SPO"); + } + + private void testIndexSelection(String opStr, String expectedIndexName) { + DatasetGraph testDsg = TDBInternal.getDatasetGraphTDB(TDB2Factory.createDataset()); + DatasetGraph referenceDsg = SSE.parseDatasetGraph(TRIPLE_DATASET); + Txn.executeWrite(testDsg, () -> testDsg.addAll(referenceDsg)); + + ExecutionContext execCxt = ExecutionContext.create(testDsg); + Op op = SSE.parseOp(opStr); + PatternQuery pq = Objects.requireNonNull(PatternQuery.createOrNull$(op)); + + SkipScanCandidate candidate = OpExecutorTDB2SkipScan.findBestCandidate(pq, execCxt); + assertNotNull(candidate); + assertNotNull(candidate.index()); + + String actualIndexName = candidate.index().getName(); + assertTrue(actualIndexName.startsWith(expectedIndexName), + "Expected index starting with " + expectedIndexName + " but got " + actualIndexName); + } +} diff --git a/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan/TestOpExecutorTDB2SkipScan.java b/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan/TestOpExecutorTDB2SkipScan.java new file mode 100644 index 00000000000..63a65a4edaa --- /dev/null +++ b/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan/TestOpExecutorTDB2SkipScan.java @@ -0,0 +1,350 @@ +/* + * 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 + * + * https://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. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +package org.apache.jena.tdb2.solver.skipscan; + +import static org.junit.jupiter.api.DynamicContainer.dynamicContainer; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Stream; + +import org.junit.jupiter.api.DynamicNode; +import org.junit.jupiter.api.DynamicTest; +import org.junit.jupiter.api.TestFactory; + +import org.apache.commons.collections4.iterators.PermutationIterator; +import org.apache.jena.atlas.iterator.Iter; +import org.apache.jena.graph.Node; +import org.apache.jena.graph.NodeFactory; +import org.apache.jena.graph.Triple; +import org.apache.jena.query.Query; +import org.apache.jena.query.ReadWrite; +import org.apache.jena.sparql.core.BasicPattern; +import org.apache.jena.sparql.core.DatasetGraph; +import org.apache.jena.sparql.core.DatasetGraphFactory; +import org.apache.jena.sparql.core.Quad; +import org.apache.jena.sparql.core.Var; +import org.apache.jena.sparql.core.Vars; +import org.apache.jena.sparql.exec.QueryExec; +import org.apache.jena.sparql.expr.Expr; +import org.apache.jena.sparql.expr.ExprVar; +import org.apache.jena.sparql.expr.aggregate.AggCountDistinct; +import org.apache.jena.sparql.expr.aggregate.AggCountVarDistinct; +import org.apache.jena.sparql.sse.SSE; +import org.apache.jena.sparql.syntax.ElementNamedGraph; +import org.apache.jena.sparql.syntax.ElementTriplesBlock; +import org.apache.jena.system.AutoTxn; +import org.apache.jena.system.Txn; +import org.apache.jena.tdb2.TDB2Factory; +import org.apache.jena.tdb2.sys.CopyDSG; +import org.apache.jena.tdb2.sys.TDBInternal; +import org.apache.jena.vocabulary.RDF; +import org.apache.jena.vocabulary.RDFS; +import org.jspecify.annotations.NonNull; + +public class TestOpExecutorTDB2SkipScan + extends AbstractDatasetGraphCompare +{ + @FunctionalInterface + interface TestGenerator { + List createTests(DatasetGraph referenceDsg, DatasetGraph testDsg, DatasetGraph dataDsg); + } + + public TestOpExecutorTDB2SkipScan() { + super(""); + } + + @TestFactory + public List staticTest01() { + DatasetGraph referenceDsg = SSE.parseDatasetGraph( + """ + (dataset + (graph + (:s :p :oa) + (:s :p :ob) + ) + (graph :g1 + (:s :p :oa) + (:s :p :ob) + ) + (graph :g2 + (:s :p :oa) + (:s :p :ob) + ) + ) + """); + + return containerForDataset(referenceDsg); + } + + private List dynamicDatasetSpecs() { + return List.of(new DatasetSpec("dataset1", 3, 5, 100.0f, 5, 0.5f)); + } + + @TestFactory + public List dynamicTests() { + List result = new ArrayList<>(); + for (DatasetSpec datasetSpec : dynamicDatasetSpecs()) { + DatasetGraph referenceDsg = generateData(datasetSpec, DatasetGraphFactory.createTxnMem()); + List children = containerForDataset(referenceDsg); + result.add(dynamicContainer(datasetSpec.toString(), children)); + } + return result; + } + + private List containerForDataset(DatasetGraph referenceDsg) { + DynamicNode distinctTests = containerForDataset("distinct", referenceDsg, this::createTestsDistinct); + DynamicNode countVarDistinctTests = containerForDataset("countVarDistinct", referenceDsg, this::createTestsCountVarDistinct); + return List.of(distinctTests, countVarDistinctTests); + } + + private DynamicNode containerForDataset(String displayName, DatasetGraph referenceDsg, TestGenerator testGenerator) { + // dataDsg contains the constants used for generating queries against referenceDsg. + DatasetGraph dataDsg = createDataDsg(referenceDsg); + DatasetGraph testDsg = TDBInternal.getDatasetGraphTDB(TDB2Factory.createDataset()); + CopyDSG.copy(referenceDsg, testDsg); + expectNotEmpty(testDsg); + + addResourceObjectsAsSubjects(dataDsg); + + List tests = testGenerator.createTests(referenceDsg, testDsg, dataDsg); + return dynamicContainer(displayName, tests); + } + + /** + * In-place addition of all non-literal objects as subjects using + * {@code :o a rdfs:Resource} triples. + * The purpose is more extensive testing of lookups. + */ + public static void addResourceObjectsAsSubjects(DatasetGraph referenceDsg) { + DatasetGraph dataDsg = DatasetGraphFactory.create(); + dataDsg.prefixes().putAll(referenceDsg.prefixes()); + dataDsg.addAll(referenceDsg); + + // Add all (non-literal) objects to the source Data for more extensive testing of lookups. + try (Stream stream = dataDsg.stream()) { + List extra = stream.flatMap(q -> Stream.of(q.getPredicate(), q.getObject()) + .map(x -> Quad.create(q.getGraph(), x, RDF.Nodes.type, RDFS.Nodes.Resource))) + .toList(); + extra.forEach(dataDsg::add); + } + } + + /** Sub classes can use this method to generate dynamic tests. */ + public List createTestsDistinct(DatasetGraph referenceDsg, DatasetGraph testDsg, DatasetGraph dataDsg) { + List findQuads = createFindQuads(dataDsg).toList(); + + // patternToQuery(q) is used to create the actual query from the quad template. + List<@NonNull DynamicTest> tests = findQuads.stream().map(q -> { + Query query = createQueryDistinct(q); + return DynamicTest.dynamicTest( + getTestLabel() + " " + q, + new GraphCompareSelectResultExecutableSkipScan(getTestLabel(), query, referenceDsg, testDsg, true)); + }).toList(); + return tests; + } + + /** Sub classes can use this method to generate dynamic tests. */ + public List createTestsCountVarDistinct(DatasetGraph referenceDsg, DatasetGraph testDsg, DatasetGraph dataDsg) { + List findQuads = createFindQuads(dataDsg).toList(); + + List<@NonNull DynamicTest> tests = findQuads.stream().flatMap(rawQuad -> { + Quad quad = anyToVar(rawQuad); + List vars = new ArrayList<>(4); + Vars.addVarsFromQuad(vars, quad); + + if (vars.isEmpty()) { + // Skip test cases with empty vars because they don't hit OpExecutorTDB2Index.tryExec(opGroup, input, execCxt) + return Stream.of(); + } + + // Permutate all variables - the last one is used for + // (COUNT(DISTINCT ?v) AS ?c) + return Iter.asStream(new PermutationIterator<>(vars)).map(vs -> { + Query query = createQueryCountDistinctVar(quad, vs); + String queryStr = query.toString().replaceAll("\n", " ").replaceAll(" +", " "); + return DynamicTest.dynamicTest( + getTestLabel() + " " + queryStr, + new GraphCompareSelectResultExecutableSkipScan(getTestLabel(),query, referenceDsg, testDsg, true)); + }); + }).toList(); + return tests; + } + + public static Quad anyToVar(Quad quad) { + Node[] ns = quadToArray(quad); + Var[] vs = new Var[] {Var.alloc("g"), Var.alloc("s"), Var.alloc("p"), Var.alloc("o")}; + for (int i = 0; i < ns.length; ++i) { + if (Node.ANY.equals(ns[i])) { + ns[i] = vs[i]; + } + } + return arrayToQuad(ns); + } + + /** Turn a quad such as (:g :s ?p ?o) into a query SELECT DISTINCT ?p ?o { GRAPH :g { :s ?p ?o } }. */ + public static Query createQueryDistinct(Quad quad) { + Node[] ns = quadToArray(quad); + Node[] vs = new Node[] {Var.alloc("g"), Var.alloc("s"), Var.alloc("p"), Var.alloc("o")}; + + for (int i = 0; i < ns.length; ++i) { + if (Node.ANY.equals(ns[i])) { + ns[i] = vs[i]; + } + } + Quad nq = arrayToQuad(ns); + List ts = List.of(nq.asTriple()); + + Query q = new Query(); + q.setDistinct(true); + q.setQuerySelectType(); + q.setQueryResultStar(true); + q.setQueryPattern(new ElementNamedGraph(ns[0], new ElementTriplesBlock(new BasicPattern(ts)))); + return q; + } + + /** + * Creates queries such as: + *
{@code
+     * SELECT ?s ?p (COUNT(DISTINCT ?g) AS ?c) {
+     *   GRAPH ?g { ?s ?p :o }
+     * }
+     * GROUP BY ?s ?p
+     * }
+ * + *

If {@code vars} is empty then the query becomes:

+ *
{@code
+     * SELECT (COUNT(DISTINCT *) AS ?c) { GRAPH :g { :s :p :o } }
+     * }
+ * + * @param vars the variables to include in the query. + * The last var is used for count distinct. + * All other vars are used for grouping and projection. + */ + public static Query createQueryCountDistinctVar(Quad nq, List vars) { + Node g = nq.getGraph(); + List ts = List.of(nq.asTriple()); + + Query q = new Query(); + Var countVar = Var.alloc("c"); + if (!vars.isEmpty()) { + List groupVars = vars.subList(0, vars.size() - 1); + Var v = vars.getLast(); + groupVars.forEach(q::addGroupBy); + q.addProjectVars(groupVars); + Expr countDistinctExpr = q.allocAggregate(new AggCountVarDistinct(new ExprVar(v))); + q.getProject().add(countVar, countDistinctExpr); + } else { + Expr countDistinctExpr = q.allocAggregate(new AggCountDistinct()); + q.getProject().add(countVar, countDistinctExpr); + } + + q.setQuerySelectType(); + q.setQueryPattern(new ElementNamedGraph(g, new ElementTriplesBlock(new BasicPattern(ts)))); + return q; + } + + private static Node[] quadToArray(Quad quad) { + return new Node[] {quad.getGraph(), quad.getSubject(), quad.getPredicate(), quad.getObject() }; + } + + private static Quad arrayToQuad(Node[] arr) { + return Quad.create(arr[0], arr[1], arr[2], arr[3]); + } + + /* ----- Dataset Generation ----- */ + + record DatasetSpec(String displayName, int numG, int numP, float sPerPFactor, int numO, float sameOsRatio) { + @Override + public String toString() { + return "%s [g=%d, p=%d, ps=%.2f, o=%d, so=%.2f]".formatted( + displayName, numG, numP, sPerPFactor, numO, sameOsRatio); + } + } + + public static DatasetGraph generateData(DatasetSpec spec, DatasetGraph destDsg) { + try (AutoTxn refTxn = Txn.autoTxn(destDsg, ReadWrite.WRITE)) { + for (int v = 0; v < spec.numG(); ++v) { + Node g = v == 0 ? Quad.defaultGraphIRI : NodeFactory.createURI("http://www.example.org/g" + v); + for (int y = 0; y < spec.numP(); ++y) { + Node p = NodeFactory.createURI("http://www.example.org/p" + y); + int maxX = (int)((y + 1) * spec.sPerPFactor()); + for (int x = 0; x < maxX; ++x) { // 100 -> sFactor + Node s = NodeFactory.createURI("http://www.example.org/s" + x); + for (int z = 0; z < spec.numO(); ++z) { + Node o1 = NodeFactory.createURI("http://www.example.org/s" + z); + destDsg.add(g, s, p, o1); + } + + int maxZ = (int)(spec.numO() * spec.sameOsRatio()); + for (int z = 0; z < maxZ; ++z) { + Node o2 = NodeFactory.createURI("http://www.example.org/o" + z); + destDsg.add(g, s, p, o2); + } + } + } + } + refTxn.commit(); + } + return destDsg; + } + + /** Use a sample of the reference data for the parameters dataset. TODO consistent naming of that parameter-source dataset. */ + private DatasetGraph createDataDsg(DatasetGraph referenceDsg) { + // dataDsg contains the constants used for generating queries against referenceDsg. + DatasetGraph dataDsg = DatasetGraphFactory.createTxnMem(); + try (AutoTxn writeTxn = Txn.autoTxn(dataDsg, ReadWrite.WRITE); + AutoTxn readTxn = Txn.autoTxn(referenceDsg, ReadWrite.READ)) { + try (QueryExec qe = QueryExec.dataset(referenceDsg) + .query("CONSTRUCT { ?s ?p ?o } { ?s ?p ?o } ORDER BY ?s ?p ?o LIMIT 5").build()) { + qe.constructDataset(dataDsg); + } + + try (QueryExec qe = QueryExec.dataset(referenceDsg) + .query("CONSTRUCT { ?s ?p ?o } { ?s ?p ?o } ORDER BY DESC(?s) DESC(?p) DESC(?o) LIMIT 5").build()) { + qe.constructDataset(dataDsg); + } + + try (QueryExec qe = QueryExec.dataset(referenceDsg) + .query("CONSTRUCT { GRAPH ?g { ?s ?p ?o } } { GRAPH ?g { ?s ?p ?o } } ORDER BY ?g ?s ?p ?o LIMIT 5").build()) { + qe.constructDataset(dataDsg); + } + + try (QueryExec qe = QueryExec.dataset(referenceDsg) + .query("CONSTRUCT { GRAPH ?g { ?s ?p ?o } } { GRAPH ?g { ?s ?p ?o } } ORDER BY DESC(?g) DESC(?s) DESC(?p) DESC(?o) LIMIT 5").build()) { + qe.constructDataset(dataDsg); + } + + expectNotEmpty(dataDsg); + writeTxn.commit(); + } + return dataDsg; + } + + /* ----- Graph Utils ----- */ + + private static void expectNotEmpty(DatasetGraph dsg) { + if (Txn.calculateRead(dsg, dsg::isEmpty)) { + throw new IllegalStateException("Unexpected empty dataset"); + } + } +} diff --git a/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan/TestTransformDistinctPlacement.java b/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan/TestTransformDistinctPlacement.java new file mode 100644 index 00000000000..62c63cc75a4 --- /dev/null +++ b/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan/TestTransformDistinctPlacement.java @@ -0,0 +1,360 @@ +/* + * 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 + * + * https://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. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +package org.apache.jena.tdb2.solver.skipscan; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +import org.apache.jena.sparql.algebra.Op; +import org.apache.jena.sparql.algebra.Transform; +import org.apache.jena.sparql.algebra.Transformer; +import org.apache.jena.sparql.sse.SSE; + +/** + * Tests for TransformDistinctPlacement - the transform that pushes DISTINCT operations + * down through the algebra tree when it's safe to do so based on variable coverage. + *

+ * The transform pushes DISTINCT through stable filters and extends when the + * variables mentioned in those operations are fully covered by the sub-operator. + * If expressions are unstable (non-deterministic), + * the DISTINCT is not pushed and remains at the current level. + *

+ * Note: When a variable mentioned in a filter/extend is not present in the subOp, + * the variable is undefined. Pushing DISTINCT is still safe in this case because + * the undefined variable's evaluation doesn't depend on subOp cardinality - the + * result will be the same (undefined/false) regardless of duplicate removal. + */ +public class TestTransformDistinctPlacement +{ + private Transform transform = new TransformDistinctPlacement(); + + // ---- Filters ---- + + @Test + public void pushThroughFilter_stable_fullCoverage_01() { + // Should push DISTINCT through filter when all vars in filter are covered by subOp + // ?s, ?p, ?o are all provided by bgp, so filter can be pushed down + String input = "(distinct (filter (= ?o 1) (bgp (?s ?p ?o))))"; + String expected = "(filter (= ?o 1) (distinct (bgp (?s ?p ?o))))"; + testTransform(input, expected); + } + + @Test + public void pushThroughFilter_stable_fullCoverage_02() { + // Multiple conditions, all vars covered + String input = "(distinct (filter (&& (= ?s ) (= ?o 1)) (bgp (?s ?p ?o))))"; + String expected = "(filter (&& (= ?s ) (= ?o 1)) (distinct (bgp (?s ?p ?o))))"; + testTransform(input, expected); + } + + @Test + public void pushThroughFilter_stable_function_01() { + // STR() is a stable function (deterministic) - should push DISTINCT + String input = "(distinct (filter (str(?o)) (bgp (?s ?p ?o))))"; + String expected = "(filter (str(?o)) (distinct (bgp (?s ?p ?o))))"; + testTransform(input, expected); + } + + @Test + public void pushThroughFilter_partialCoverage_01() { + // Filter mentions ?x which is NOT in subOp - DISTINCT should still be pushed + // because ?x being undefined doesn't depend on subOp cardinality + String input = "(distinct (filter (= ?x 1) (bgp (?s ?p ?o))))"; + String expected = "(filter (= ?x 1) (distinct (bgp (?s ?p ?o))))"; + testTransform(input, expected); + } + + // ---- Extends (BIND/ASSIGN) ---- + + @Test + public void pushThroughExtend_stable_fullCoverage_01() { + // Should push DISTINCT through stable extend when all expression vars are covered + // ?o is provided by bgp, so the extend can be pushed down + String input = "(distinct (extend ((?x ?o)) (bgp (?s ?p ?o))))"; + String expected = "(extend ((?x ?o)) (distinct (bgp (?s ?p ?o))))"; + testTransform(input, expected); + } + + @Test + public void pushThroughExtend_stable_fullCoverage_02() { + // Multiple assignments, all vars covered by subOp + String input = "(distinct (extend ((?x ?o) (?y ?p)) (bgp (?s ?p ?o))))"; + String expected = "(extend ((?x ?o) (?y ?p)) (distinct (bgp (?s ?p ?o))))"; + testTransform(input, expected); + } + + @Test + public void pushThroughExtend_stable_function_01() { + // LANG() is a stable function (deterministic) - should push DISTINCT + String input = "(distinct (extend ((?x (lang ?o))) (bgp (?s ?p ?o))))"; + String expected = "(extend ((?x (lang ?o))) (distinct (bgp (?s ?p ?o))))"; + testTransform(input, expected); + } + + @Test + public void pushThroughExtend_partialCoverage_01() { + // Extend mentions ?z which is NOT in subOp - DISTINCT should be pushed + // because ?z being undefined doesn't depend on subOp cardinality + String input = "(distinct (extend ((?x ?z)) (bgp (?s ?p ?o))))"; + String expected = "(extend ((?x ?z)) (distinct (bgp (?s ?p ?o))))"; + testTransform(input, expected); + } + + // ---- Coverage analysis ---- + + @Test + public void coverage_full_01() { + // All variables in filter are covered by the bgp - should push + // ?s, ?p, ?o all in subOp + String input = "(distinct (filter (= ?s ?p) (bgp (?s ?p ?o))))"; + String expected = "(filter (= ?s ?p) (distinct (bgp (?s ?p ?o))))"; + testTransform(input, expected); + } + + @Test + public void coverage_partial_01() { + // Partial coverage: filter mentions ?s, ?p (in subOp) and ?x (not in subOp) + // DISTINCT should be pushed because ?x being undefined doesn't depend on subOp cardinality + String input = "(distinct (filter (&& (= ?s ?p) (= ?x 1)) (bgp (?s ?p ?o))))"; + String expected = "(filter (&& (= ?s ?p) (= ?x 1)) (distinct (bgp (?s ?p ?o))))"; + testTransform(input, expected); + } + + // ---- Nested structures ---- + + @Test + public void nested_transforms_01() { + // Multiple transforms in sequence - both filters should be pushed + String input = "(distinct (filter (= ?s ) (filter (= ?o 1) (bgp (?s ?p ?o)))))"; + String expected = "(filter (= ?s ) (filter (= ?o 1) (distinct (bgp (?s ?p ?o)))))"; + testTransform(input, expected); + } + + @Test + public void nested_transforms_02() { + // Mix of filter and extend + String input = "(distinct (filter (= ?s ) (extend ((?x ?o)) (bgp (?s ?p ?o)))))"; + String expected = "(filter (= ?s ) (extend ((?x ?o)) (distinct (bgp (?s ?p ?o)))))"; + testTransform(input, expected); + } + + @Test + public void nested_distinct_01() { + // Nested distinct operations + String input = "(distinct (distinct (bgp (?s ?p ?o))))"; + String expected = "(distinct (distinct (bgp (?s ?p ?o))))"; + testTransform(input, expected); + } + + // ---- Complex expressions ---- + + @Test + public void complexFilter_functionCall_01() { + // Filter with stable function STR() that depends on subOp vars + // STR() is deterministic so DISTINCT should be pushed + String input = "(distinct (filter (str(?o)) (bgp (?s ?p ?o))))"; + String expected = "(filter (str(?o)) (distinct (bgp (?s ?p ?o))))"; + testTransform(input, expected); + } + + @Test + public void complexFilter_multipleOps_01() { + // Complex filter with stable function STR() and equality + // Both are stable so DISTINCT should be pushed + String input = "(distinct (filter (&& (str(?o)) (= ?s ?p)) (bgp (?s ?p ?o))))"; + String expected = "(filter (&& (str(?o)) (= ?s ?p)) (distinct (bgp (?s ?p ?o))))"; + testTransform(input, expected); + } + + @Test + public void complexExtend_function_01() { + // Extend with stable function LANG() + // ?o is covered and LANG() is deterministic so DISTINCT should be pushed + String input = "(distinct (extend ((?x (lang ?o))) (bgp (?s ?p ?o))))"; + String expected = "(extend ((?x (lang ?o))) (distinct (bgp (?s ?p ?o))))"; + testTransform(input, expected); + } + + // ---- Edge cases ---- + + @Test + public void simpleBGP_01() { + // Simple BGP with distinct - no filter/extend to push through + String input = "(distinct (bgp (?s ?p ?o)))"; + String expected = "(distinct (bgp (?s ?p ?o)))"; + testTransform(input, expected); + } + + @Test + public void noSubOp_01() { + // DISTINCT with table unit - no subOp to push through + String input = "(distinct (table unit))"; + String expected = "(distinct (table unit))"; + testTransform(input, expected); + } + + @Test + public void unionScenario_01() { + // DISTINCT over union - should not push through union + String input = "(distinct (union (bgp (?s ?p ?o)) (bgp (?s ?p1 ?o1))))"; + String expected = "(distinct (union (bgp (?s ?p ?o)) (bgp (?s ?p1 ?o1))))"; + testTransform(input, expected); + } + + @Test + public void joinScenario_01() { + // DISTINCT over join with filter on one side + String input = "(distinct (filter (= ?o 1) (join (bgp (?s ?p ?o)) (bgp (?s ?p2 ?o2)))))"; + String expected = "(filter (= ?o 1) (distinct (join (bgp (?s ?p ?o)) (bgp (?s ?p2 ?o2)))))"; + testTransform(input, expected); + } + + // ---- Integration scenarios ---- + + @Test + public void integration_filter_extend_01() { + // Combined filter and extend scenario + String input = "(distinct (filter (= ?p ) (extend ((?x ?o)) (bgp (?s ?p ?o)))))"; + String expected = "(filter (= ?p ) (extend ((?x ?o)) (distinct (bgp (?s ?p ?o)))))"; + testTransform(input, expected); + } + + @Test + public void integration_project_filter_01() { + // Project with filter inside distinct + String input = "(distinct (project (?s) (filter (= ?p ) (bgp (?s ?p ?o)))))"; + // The filter mentions ?p which is not in the project vars (?s only) + // So it should not be pushed + String expected = "(distinct (project (?s) (filter (= ?p ) (bgp (?s ?p ?o)))))"; + testTransform(input, expected); + } + + @Test + public void leftJoinScenario_01() { + // DISTINCT over left join + String input = "(distinct (leftjoin (bgp (?s ?p ?o)) (bgp (?s ?p2 ?o2))))"; + String expected = "(distinct (leftjoin (bgp (?s ?p ?o)) (bgp (?s ?p2 ?o2))))"; + testTransform(input, expected); + } + + // ---- Unstable functions (should NOT push DISTINCT) ---- + + @Test + public void pushThroughFilter_unstable_rand_01() { + // RAND() is unstable - should NOT push DISTINCT + String input = "(distinct (filter (rand) (bgp (?s ?p ?o))))"; + String expected = "(distinct (filter (rand) (bgp (?s ?p ?o))))"; + testTransform(input, expected); + } + + @Test + public void pushThroughExtend_unstable_rand_01() { + // RAND() is unstable - should NOT push DISTINCT + String input = "(distinct (extend ((?x (rand))) (bgp (?s ?p ?o))))"; + String expected = "(distinct (extend ((?x (rand))) (bgp (?s ?p ?o))))"; + testTransform(input, expected); + } + + @Test + public void pushThroughFilter_unstable_uuid_01() { + // UUID() is unstable - should NOT push DISTINCT + String input = "(distinct (filter (uuid) (bgp (?s ?p ?o))))"; + String expected = "(distinct (filter (uuid) (bgp (?s ?p ?o))))"; + testTransform(input, expected); + } + + @Test + public void pushThroughExtend_unstable_uuid_01() { + // UUID() is unstable - should NOT push DISTINCT + String input = "(distinct (extend ((?x (uuid))) (bgp (?s ?p ?o))))"; + String expected = "(distinct (extend ((?x (uuid))) (bgp (?s ?p ?o))))"; + testTransform(input, expected); + } + + @Test + public void pushThroughFilter_unstable_bnode_01() { + // BNODE() is unstable - should NOT push DISTINCT + String input = "(distinct (filter (bnode) (bgp (?s ?p ?o))))"; + String expected = "(distinct (filter (bnode) (bgp (?s ?p ?o))))"; + testTransform(input, expected); + } + + @Test + public void pushThroughExtend_unstable_bnode_01() { + // BNODE() is unstable - should NOT push DISTINCT + String input = "(distinct (extend ((?x (bnode))) (bgp (?s ?p ?o))))"; + String expected = "(distinct (extend ((?x (bnode))) (bgp (?s ?p ?o))))"; + testTransform(input, expected); + } + + @Test + public void pushThroughFilter_mixed_stable_unstable_01() { + // Mix of stable (str) and unstable (rand) - should NOT push DISTINCT + String input = "(distinct (filter (&& (str(?o)) (rand)) (bgp (?s ?p ?o))))"; + String expected = "(distinct (filter (&& (str(?o)) (rand)) (bgp (?s ?p ?o))))"; + testTransform(input, expected); + } + + @Test + public void pushThroughExtend_mixed_stable_unstable_01() { + // Mix of stable (lang) and unstable (uuid) - should NOT push DISTINCT + String input = "(distinct (extend ((?x (&& (lang ?o) (uuid)))) (bgp (?s ?p ?o))))"; + String expected = "(distinct (extend ((?x (&& (lang ?o) (uuid)))) (bgp (?s ?p ?o))))"; + testTransform(input, expected); + } + + @Test + public void pushThroughProject_01() { + String input = "(distinct (project (?s ?p) (project (?p) (bgp (?s ?p ?o)))))"; + String expected = "(distinct (project (?p) (bgp (?s ?p ?o))))"; + testTransform(input, expected); + } + + @Test + public void pushThroughProject_02() { + String input = "(distinct (project (?s ?p) (filter (bound(?p)) (project (?p) (bgp (?s ?p ?o))))))"; + String expected = "(filter (bound(?p)) (distinct (project (?p) (bgp (?s ?p ?o)))))"; + testTransform(input, expected); + } + + @Test + public void pushThroughProject_02b() { + String input = "(distinct (project (?s ?p) (filter (bound(?s)) (project (?p) (bgp (?s ?p ?o))))))"; + String expected = "(filter (bound(?s)) (distinct (project (?p) (bgp (?s ?p ?o)))))"; + testTransform(input, expected); + } + + @Test + public void pushThroughProject_03() { + String input = "(distinct (project (?s ?p) (filter (bound(?s)) (project (?p ?x) (bgp (?s ?p ?o))))))"; + String expected = "(filter (bound(?s)) (distinct (project (?p) (bgp (?s ?p ?o)))))"; + testTransform(input, expected); + } + + private void testTransform(String input, String expected) { + Op inputOp = SSE.parseOp(input); + Op expectedOp = SSE.parseOp(expected); + Op result = Transformer.transform(transform, inputOp); + assertEquals(expectedOp, result, "Transform result should match expected structure"); + } +} diff --git a/jena-tdb2/src/test/java/org/apache/jena/tdb2/store/Test_SPARQL_TDB.java b/jena-tdb2/src/test/java/org/apache/jena/tdb2/store/Test_SPARQL_TDB.java index fd9fc01f3d6..9d6927acaee 100644 --- a/jena-tdb2/src/test/java/org/apache/jena/tdb2/store/Test_SPARQL_TDB.java +++ b/jena-tdb2/src/test/java/org/apache/jena/tdb2/store/Test_SPARQL_TDB.java @@ -22,6 +22,7 @@ package org.apache.jena.tdb2.store; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; import org.junit.jupiter.api.Test; @@ -30,8 +31,16 @@ import org.apache.jena.graph.Graph; import org.apache.jena.graph.NodeFactory; import org.apache.jena.graph.Triple; -import org.apache.jena.query.*; +import org.apache.jena.query.Dataset; +import org.apache.jena.query.Query; +import org.apache.jena.query.QueryExecution; +import org.apache.jena.query.QueryExecutionFactory; +import org.apache.jena.query.QueryFactory; +import org.apache.jena.query.ReadWrite; +import org.apache.jena.query.ResultSet; +import org.apache.jena.query.ResultSetFormatter; import org.apache.jena.rdf.model.Model; +import org.apache.jena.sparql.algebra.Table; import org.apache.jena.sparql.core.DatasetGraph; import org.apache.jena.sparql.exec.QueryExec; import org.apache.jena.sparql.exec.RowSet; @@ -41,7 +50,11 @@ import org.apache.jena.tdb2.DatabaseMgr; import org.apache.jena.tdb2.TDB2; import org.apache.jena.tdb2.TDB2Factory; -import org.apache.jena.update.*; +import org.apache.jena.update.UpdateAction; +import org.apache.jena.update.UpdateExecution; +import org.apache.jena.update.UpdateExecutionFactory; +import org.apache.jena.update.UpdateFactory; +import org.apache.jena.update.UpdateRequest; /** * Test SPARQL @@ -157,6 +170,70 @@ public void sparql7() { }); } + /** Test skip scan with union default graph constant. */ + @Test + public void sparql8() { + DatasetGraph dsg = TDB2Factory.createDataset().asDatasetGraph(); + Txn.executeWrite(dsg, () -> { + dsg.add(SSE.parseQuad("(

123)")); + }); + dsg.getContext().setTrue(TDB2.symUnionDefaultGraph); + + Table actual = Txn.calculateRead(dsg, () -> QueryExec.dataset(dsg) + .query("SELECT DISTINCT ?p { ?s ?p ?o }").table()); + assertEquals(1, actual.size()); + } + + /** Test whether passing a blank node from a skip scan result to + * another skip scan retrieval works. */ + @Test + public void sparql9() { + DatasetGraph dsg = TDB2Factory.createDataset().asDatasetGraph(); + Txn.executeWrite(dsg, () -> { + dsg.add(SSE.parseQuad("( _:x)")); + dsg.add(SSE.parseQuad("( :o)")); + }); + dsg.getContext().setTrue(TDB2.symUnionDefaultGraph); + + Table actualTable = Txn.calculateRead(dsg, () -> QueryExec.dataset(dsg) + .query(""" + SELECT ?p { + { + { SELECT DISTINCT ?o { ?s ?p ?o } } # Should match _:x + FILTER(isBlank(?o)) + } + LATERAL { + { SELECT DISTINCT ?p ?o { ?s ?p ?o } } + } + } + """).table()); + Table expectedTable = SSE.parseTable("(table (vars ?p) (row (?p )))"); + assertEquals(expectedTable, actualTable); + } + + /** Test that index access optimization does not break non-deterministic functions. */ + @Test + public void sparql10() { + DatasetGraph dsg = TDB2Factory.createDataset().asDatasetGraph(); + int n = 100; + Txn.executeWrite(dsg, () -> { + for (int i = 0; i < n; ++i) { + dsg.add(SSE.parseQuad("( :o" + i + ")")); + } + }); + dsg.getContext().setTrue(TDB2.symUnionDefaultGraph); + + Table actualTable = Txn.calculateRead(dsg, () -> QueryExec.dataset(dsg) + .query(""" + SELECT DISTINCT ?p ?x { + ?s ?p ?o + BIND(rand() AS ?x) + } + """).table()); + // Extremely unlikely that rand() would return the same value n times! + assertNotEquals(actualTable.size(), 1); + } + private static void add(Dataset dataset, String graphName, Triple triple) { Txn.executeWrite(dataset, () -> { Graph g2 = dataset.asDatasetGraph().getGraph(NodeFactory.createURI(graphName)); From 99f1a873f5cf8058331273c9b4400f3fef0d1090 Mon Sep 17 00:00:00 2001 From: Claus Stadler Date: Fri, 23 Oct 2026 13:37:57 +0200 Subject: [PATCH 2/3] Fixes based on the Claude review. Also included the test cases. --- .../main/java/tdb2/cmdline/ModTDBDataset.java | 2 +- .../apache/jena/dboe/base/record/Record.java | 30 ++-- .../BPTreeDistinctKeyPrefixIterator.java | 97 ++++++----- .../trans/bplustree/BPTreeRangeIterator.java | 6 +- .../jena/dboe/trans/bplustree/BPlusTree.java | 14 +- .../bplustree/TestBPTreeDistinctKeys.java | 2 + .../tdb2/solver/skipscan/CandidateIndex.java | 32 ---- .../jena/tdb2/solver/skipscan/IndexMatch.java | 1 + .../tdb2/solver/skipscan/NodeIdUtils.java | 56 ------ .../skipscan/OpExecutorTDB2SkipScan.java | 60 ++++--- .../tdb2/solver/skipscan/OpExtSkipScan.java | 7 +- .../tdb2/solver/skipscan/PatternQuery.java | 27 ++- .../tdb2/solver/skipscan/SkipScanRewrite.java | 24 --- .../skipscan/TransformDistinctPlacement.java | 2 +- .../solver/skipscan/TuplePatternSpec.java | 17 +- .../Test05_EqualityLinkArrayOverflow.java | 82 +++++++++ .../Test07_ResidualConditionsUnreachable.java | 121 +++++++++++++ .../skipscan/Test09_NonRecordIndexGuard.java | 86 +++++++++ .../skipscan/Test10_RemapValueConditions.java | 108 ++++++++++++ .../Test13_OpExtSkipScanContract.java | 82 +++++++++ .../skipscan/TestOpExecutorTDB2SkipScan.java | 12 +- .../solver/skipscan_3995/SkipScanTestLib.java | 138 +++++++++++++++ .../skipscan_3995/TS_SkipScan_3995.java | 65 +++++++ .../Test01_DistinctPlacementProjection.java | 93 ++++++++++ .../Test02_InputBindingDropped.java | 73 ++++++++ .../Test03_CacheKeySubstitution.java | 77 ++++++++ .../Test04_NodeIdMaxUpperBound.java | 99 +++++++++++ .../Test06_RecordPadRightUpperBound.java | 102 +++++++++++ .../Test08_PatternQueryCacheKey.java | 89 ++++++++++ .../Test11_KeyPrefixLengthValidation.java | 98 +++++++++++ .../Test12_PrefixIteratorRange.java | 164 ++++++++++++++++++ .../Test14_AddResourceObjectsAsSubjects.java | 92 ++++++++++ .../jena/tdb2/store/Test_SPARQL_TDB.java | 8 +- 33 files changed, 1739 insertions(+), 227 deletions(-) delete mode 100644 jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/CandidateIndex.java delete mode 100644 jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/NodeIdUtils.java create mode 100644 jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan/Test05_EqualityLinkArrayOverflow.java create mode 100644 jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan/Test07_ResidualConditionsUnreachable.java create mode 100644 jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan/Test09_NonRecordIndexGuard.java create mode 100644 jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan/Test10_RemapValueConditions.java create mode 100644 jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan/Test13_OpExtSkipScanContract.java create mode 100644 jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan_3995/SkipScanTestLib.java create mode 100644 jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan_3995/TS_SkipScan_3995.java create mode 100644 jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan_3995/Test01_DistinctPlacementProjection.java create mode 100644 jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan_3995/Test02_InputBindingDropped.java create mode 100644 jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan_3995/Test03_CacheKeySubstitution.java create mode 100644 jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan_3995/Test04_NodeIdMaxUpperBound.java create mode 100644 jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan_3995/Test06_RecordPadRightUpperBound.java create mode 100644 jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan_3995/Test08_PatternQueryCacheKey.java create mode 100644 jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan_3995/Test11_KeyPrefixLengthValidation.java create mode 100644 jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan_3995/Test12_PrefixIteratorRange.java create mode 100644 jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan_3995/Test14_AddResourceObjectsAsSubjects.java diff --git a/jena-cmds/src/main/java/tdb2/cmdline/ModTDBDataset.java b/jena-cmds/src/main/java/tdb2/cmdline/ModTDBDataset.java index a6f2d56c193..e5f3a3af6f6 100644 --- a/jena-cmds/src/main/java/tdb2/cmdline/ModTDBDataset.java +++ b/jena-cmds/src/main/java/tdb2/cmdline/ModTDBDataset.java @@ -73,7 +73,7 @@ public void processArgs(CmdArgModule cmdLine) { public Dataset createDataset() { if ( inMemFile != null ) { Dataset ds = TDB2Factory.createDataset(); - RDFDataMgr.read(ds, inMemFile); + ds.executeWrite(()->RDFDataMgr.read(ds, inMemFile)); return ds; } diff --git a/jena-db/jena-dboe-base/src/main/java/org/apache/jena/dboe/base/record/Record.java b/jena-db/jena-dboe-base/src/main/java/org/apache/jena/dboe/base/record/Record.java index e9d5bd5a31d..83254b3f61d 100644 --- a/jena-db/jena-dboe-base/src/main/java/org/apache/jena/dboe/base/record/Record.java +++ b/jena-db/jena-dboe-base/src/main/java/org/apache/jena/dboe/base/record/Record.java @@ -24,6 +24,7 @@ import static java.lang.String.format; import java.util.Arrays; +import java.util.Objects; import org.apache.jena.atlas.lib.Bytes; import org.apache.jena.dboe.sys.SystemIndex; @@ -170,10 +171,12 @@ static boolean compatible(Record record1, Record record2, boolean checkValue) { /** * Return a new record with the key increased by 1. - * Returned record shares the value array of the argument record. + * In case of overflow, the result is null. */ - public static Record incrementKey(Record record) { - return new Record(incrementByteArray(record.getKey().clone()), record.getValue()); + public static Record incrementKeyOrNull(Record record) { + Objects.requireNonNull(record); + byte[] keyBytes = incrementByteArray(record.getKey().clone()); + return keyBytes == null ? null : new Record(keyBytes, record.getValue()); } private static byte[] incrementByteArray(byte[] array) { @@ -186,7 +189,7 @@ private static byte[] incrementByteArray(byte[] array) { } } // If we reach here, the entire array overflowed (e.g., [255, 255] -> [0, 0]) - throw new ArithmeticException("Byte array overflowed its maximum value"); + return null; } /** @@ -196,24 +199,27 @@ private static byte[] incrementByteArray(byte[] array) { * If no padding is needed then {@code record} is returned. * Otherwise, a new record is created. */ - public static Record padRight(Record record, Record prototype) { + public static Record padRight(Record record, Record prototype, byte padValue) { byte[] rkey = record.getKey(); byte[] rval = record.getValue(); byte[] pkey = prototype.getKey(); byte[] pval = prototype.getValue(); - byte[] key = pkey == null ? rkey : padRight(rkey, pkey.length); - byte[] val = pval == null ? rval : padRight(rval, pval.length); + byte[] key = pkey == null ? rkey : padRight(rkey, pkey.length, padValue); + byte[] val = pval == null ? rval : padRight(rval, pval.length, padValue); return (key == rkey && val == rval) ? record : new Record(key, val); } - private static byte[] padRight(byte[] arr, int length) { - if (length == arr.length) { + private static byte[] padRight(byte[] arr, int length, byte padValue) { + if (length <= arr.length) { return arr; - } else if (length < arr.length) { - return Arrays.copyOf(arr, arr.length); } - return Arrays.copyOf(arr, length); + byte[] r = Arrays.copyOf(arr, length); // Implicitly pads with 0 bytes + if (padValue != 0) { + // Pad with non-zero bytes. + Arrays.fill(r, arr.length, length, padValue); + } + return r; } } diff --git a/jena-db/jena-dboe-trans-data/src/main/java/org/apache/jena/dboe/trans/bplustree/BPTreeDistinctKeyPrefixIterator.java b/jena-db/jena-dboe-trans-data/src/main/java/org/apache/jena/dboe/trans/bplustree/BPTreeDistinctKeyPrefixIterator.java index 83bb815f86c..e369a5ca057 100644 --- a/jena-db/jena-dboe-trans-data/src/main/java/org/apache/jena/dboe/trans/bplustree/BPTreeDistinctKeyPrefixIterator.java +++ b/jena-db/jena-dboe-trans-data/src/main/java/org/apache/jena/dboe/trans/bplustree/BPTreeDistinctKeyPrefixIterator.java @@ -37,30 +37,20 @@ class BPTreeDistinctKeyPrefixIterator implements Iterator { static Logger log = LoggerFactory.getLogger(BPTreeDistinctKeyPrefixIterator.class); public static Iterator create(BPTreeNode node, int keyPrefixLength) { - if (keyPrefixLength < 1) { - throw new IllegalArgumentException("keyPrefixLength must be >= 1"); - } else if (keyPrefixLength > node.params.recordFactory.keyLength()) { + return create(node, keyPrefixLength, null, null); + } + + /** + * Create an iterator of distinct keys over a custom sub-range. + * The minimum and maximum records may be null to match all records w.r.t. the given keyPrefixLength. + * Note that a keyPrefixLength of 0 on a non-empty BPTreeNode will return only the first node - + * as all other nodes are considered equal to it by the zero-length prefix. + */ + public static Iterator create(BPTreeNode node, int keyPrefixLength, Record minRecordInclusive, Record maxRecordExclusive) { + if (keyPrefixLength > node.params.recordFactory.keyLength()) { throw new IllegalArgumentException( "Maximum keyPrefixLength for this B+Tree is " + node.params.recordFactory.keyLength()); } - Record minRecord = node.minRecord(); - Record maxRecord = node.maxRecord(); - // If there's no records just return a null iterator - if (minRecord == null) { - return Iter.nullIter(); - } - // If there's only a single distinct prefix then just return a singleton - if (Arrays.compare(minRecord.getKey(), 0, keyPrefixLength, maxRecord.getKey(), 0, keyPrefixLength) == 0) { - return Iter.singletonIterator(minRecord); - } - // Otherwise need the full iterator - return new BPTreeDistinctKeyPrefixIterator(node, keyPrefixLength, minRecord, maxRecord); - } - - /** Create an iterator of distinct keys over a custom sub-range. Arguments must not be null. */ - public static Iterator create(BPTreeNode node, int keyPrefixLength, Record minRecord, Record maxRecord) { - Objects.requireNonNull(minRecord); - Objects.requireNonNull(maxRecord); Record nodeMinRecord = node.minRecord(); Record nodeMaxRecord = node.maxRecord(); @@ -69,9 +59,24 @@ public static Iterator create(BPTreeNode node, int keyPrefixLength, Reco return Iter.nullIter(); } + // If there's only a single distinct prefix then just return a singleton + if (haveSamePrefix(nodeMinRecord, nodeMaxRecord, keyPrefixLength)) { + if (isPrefixInRequestRange(nodeMinRecord, keyPrefixLength, minRecordInclusive, maxRecordExclusive)) { + return Iter.singletonIterator(nodeMinRecord); + } else { + return Iter.nullIter(); + } + } + // Pad records to make their lengths match those of the nodes. - Record paddedMinRecord = Record.padRight(minRecord, nodeMinRecord); - Record paddedMaxRecord = Record.padRight(maxRecord, nodeMaxRecord); + // Also, the down-stream machinery expects paddedMinRecord to be non-null. + Record paddedMinRecord; + if (minRecordInclusive == null) { + paddedMinRecord = nodeMinRecord; + } else { + paddedMinRecord = Record.padRight(minRecordInclusive, nodeMinRecord, (byte)0x00); + } + Record paddedMaxRecord = maxRecordExclusive == null ? null : Record.padRight(maxRecordExclusive, nodeMaxRecord, (byte)0xff); return new BPTreeDistinctKeyPrefixIterator(node, keyPrefixLength, paddedMinRecord, paddedMaxRecord); } @@ -80,17 +85,16 @@ public static Iterator create(BPTreeNode node, int keyPrefixLength, Reco private final Deque> stack = new ArrayDeque<>(); private Iterator current; private Record slot = null; - private final Record minRecord, maxRecord, maxRecordPlusOne; + private final Record minRecordInclusive, maxRecordExclusive; private byte[] lastPrefix = null; private boolean finished = false; private final int keyPrefixLength; - BPTreeDistinctKeyPrefixIterator(BPTreeNode node, int keyPrefixLength, Record minRecord, Record maxRecord) { + BPTreeDistinctKeyPrefixIterator(BPTreeNode node, int keyPrefixLength, Record minRecordInclusive, Record maxRecordExclusive) { this.keyPrefixLength = keyPrefixLength; - this.minRecord = minRecord; - this.maxRecord = maxRecord; - this.maxRecordPlusOne = Record.incrementKey(maxRecord); + this.minRecordInclusive = Objects.requireNonNull(minRecordInclusive); + this.maxRecordExclusive = maxRecordExclusive; BPTreeRecords r = loadStack(node); current = getRecordsIterator(r); @@ -154,8 +158,16 @@ private Iterator moveOnCurrent() { // iterator for this entire subtree and skip further recursion Record subtreeMin = n.minRecord(); Record subtreeMax = n.maxRecord(); - if (haveSamePrefix(subtreeMin, subtreeMax)) { - return Iter.singletonIterator(subtreeMin); + if (haveSamePrefix(subtreeMin, subtreeMax, keyPrefixLength)) { + Iterator recordIter; + // Check that the prefix is in range + if (isPrefixInRequestRange(subtreeMin, keyPrefixLength, minRecordInclusive, maxRecordExclusive)) { + // If the low and high keys for this page have the same prefix then just return a singleton iterator + recordIter = Iter.singletonIterator(subtreeMin); + } else { + recordIter = Iter.nullIterator(); + } + return recordIter; } r = loadStack(n); } else { @@ -164,14 +176,20 @@ private Iterator moveOnCurrent() { return getRecordsIterator(r); } - protected final int comparePrefix(Record a, Record b) { + private static int comparePrefix(Record a, Record b, int keyPrefixLength) { // Need to compare unsigned in general: // E.g. [0, 5] is less than [0, -1] because the latter must be treated as [0, 255]. - return Arrays.compareUnsigned(a.getKey(), 0, this.keyPrefixLength, b.getKey(), 0, this.keyPrefixLength); + return Arrays.compareUnsigned(a.getKey(), 0, keyPrefixLength, b.getKey(), 0, keyPrefixLength); + } + + private static boolean haveSamePrefix(Record a, Record b, int keyPrefixLength) { + return comparePrefix(a, b, keyPrefixLength) == 0; } - protected final boolean haveSamePrefix(Record a, Record b) { - return Arrays.compare(a.getKey(), 0, this.keyPrefixLength, b.getKey(), 0, this.keyPrefixLength) == 0; + protected static boolean isPrefixInRequestRange(Record record, int keyPrefixLength, Record minRecordInclusive, Record maxRecordExclusive) { + return + (minRecordInclusive == null || comparePrefix(record, minRecordInclusive, keyPrefixLength) >= 0) && + (maxRecordExclusive == null || comparePrefix(record, maxRecordExclusive, keyPrefixLength) < 0); } // ---- Places we touch blocks. @@ -185,9 +203,9 @@ protected Iterator getRecordsIterator(BPTreeRecords records) { // Check whether we need to scan the whole page or can process it by skipping or singleton yield Record lowRecord = records.getLowRecord(); Record highRecord = records.getHighRecord(); - if (haveSamePrefix(lowRecord, highRecord)) { + if (haveSamePrefix(lowRecord, highRecord, keyPrefixLength)) { // Check that the prefix is in range - if (comparePrefix(lowRecord, minRecord) >= 0 && comparePrefix(highRecord, maxRecord) <= 0) { + if (isPrefixInRequestRange(lowRecord, keyPrefixLength, minRecordInclusive, maxRecordExclusive)) { // If the low and high keys for this page have the same prefix then just return a singleton iterator iter = Iter.singletonIterator(lowRecord); } else { @@ -195,7 +213,8 @@ protected Iterator getRecordsIterator(BPTreeRecords records) { } } else { // Otherwise need to scan the whole page - iter = records.getRecordBuffer().iterator(minRecord, maxRecordPlusOne); + // Note: Adjacent records with the same prefix are filtered out in this class's hasNext() method + iter = records.getRecordBuffer().iterator(minRecordInclusive, maxRecordExclusive); } } records.bpTree.finishReadBlkMgr(); @@ -206,11 +225,11 @@ private BPTreeRecords loadStack(BPTreeNode node) { AccessPath path = new AccessPath(null); node.bpTree.startReadBlkMgr(); - node.internalSearch(path, minRecord); + node.internalSearch(path, minRecordInclusive); List steps = path.getPath(); for (AccessStep step : steps) { BPTreeNode n = step.node; - Iterator it = n.iterator(this.minRecord, this.maxRecord); + Iterator it = n.iterator(minRecordInclusive, maxRecordExclusive); //this.maxRecordInclusive); if (it == null || !it.hasNext()) { continue; } diff --git a/jena-db/jena-dboe-trans-data/src/main/java/org/apache/jena/dboe/trans/bplustree/BPTreeRangeIterator.java b/jena-db/jena-dboe-trans-data/src/main/java/org/apache/jena/dboe/trans/bplustree/BPTreeRangeIterator.java index b713b3465e4..465c70c639d 100644 --- a/jena-db/jena-dboe-trans-data/src/main/java/org/apache/jena/dboe/trans/bplustree/BPTreeRangeIterator.java +++ b/jena-db/jena-dboe-trans-data/src/main/java/org/apache/jena/dboe/trans/bplustree/BPTreeRangeIterator.java @@ -34,10 +34,10 @@ class BPTreeRangeIterator implements Iterator { static Logger log = LoggerFactory.getLogger(BPTreeRangeIterator.class); - public static Iterator create(BPTreeNode node, Record minRec, Record maxRec) { - if ( minRec != null && maxRec != null && Record.keyGE(minRec, maxRec) ) + public static Iterator create(BPTreeNode node, Record minRecInclusive, Record maxRecExclusive) { + if ( minRecInclusive != null && maxRecExclusive != null && Record.keyGE(minRecInclusive, maxRecExclusive) ) return Iter.nullIter(); - return new BPTreeRangeIterator(node, minRec, maxRec); + return new BPTreeRangeIterator(node, minRecInclusive, maxRecExclusive); } // Convert path to a stack of iterators diff --git a/jena-db/jena-dboe-trans-data/src/main/java/org/apache/jena/dboe/trans/bplustree/BPlusTree.java b/jena-db/jena-dboe-trans-data/src/main/java/org/apache/jena/dboe/trans/bplustree/BPlusTree.java index 04e1d2142c1..ca5b1d29a7d 100644 --- a/jena-db/jena-dboe-trans-data/src/main/java/org/apache/jena/dboe/trans/bplustree/BPlusTree.java +++ b/jena-db/jena-dboe-trans-data/src/main/java/org/apache/jena/dboe/trans/bplustree/BPlusTree.java @@ -312,29 +312,25 @@ public Iterator iterator() { } @Override - public Iterator iterator(Record fromRec, Record toRec) { + public Iterator iterator(Record fromRecInclusive, Record toRecExclusive) { startReadBlkMgr(); BPTreeNode root = getRootRead(); releaseRootRead(root); finishReadBlkMgr(); - return BPTreeRangeIterator.create(root, fromRec, toRec); + return BPTreeRangeIterator.create(root, fromRecInclusive, toRecExclusive); //return iterator(fromRec, toRec, RecordFactory.mapperRecord); } public Iterator distinctByKeyPrefix(int keyPrefixLength) { - startReadBlkMgr(); - BPTreeNode root = getRootRead(); - releaseRootRead(root); - finishReadBlkMgr(); - return BPTreeDistinctKeyPrefixIterator.create(root, keyPrefixLength); + return distinctByKeyPrefix(keyPrefixLength, null, null); } - public Iterator distinctByKeyPrefix(int keyPrefixLength, Record fromRecInclusive, Record toRecInclusive) { + public Iterator distinctByKeyPrefix(int keyPrefixLength, Record fromRecInclusive, Record toRecExclusive) { startReadBlkMgr(); BPTreeNode root = getRootRead(); releaseRootRead(root); finishReadBlkMgr(); - return BPTreeDistinctKeyPrefixIterator.create(root, keyPrefixLength, fromRecInclusive, toRecInclusive); + return BPTreeDistinctKeyPrefixIterator.create(root, keyPrefixLength, fromRecInclusive, toRecExclusive); } /* diff --git a/jena-db/jena-dboe-trans-data/src/test/java/org/apache/jena/dboe/trans/bplustree/TestBPTreeDistinctKeys.java b/jena-db/jena-dboe-trans-data/src/test/java/org/apache/jena/dboe/trans/bplustree/TestBPTreeDistinctKeys.java index d100dfe34b5..53746b3d576 100644 --- a/jena-db/jena-dboe-trans-data/src/test/java/org/apache/jena/dboe/trans/bplustree/TestBPTreeDistinctKeys.java +++ b/jena-db/jena-dboe-trans-data/src/test/java/org/apache/jena/dboe/trans/bplustree/TestBPTreeDistinctKeys.java @@ -33,6 +33,7 @@ import java.util.*; import java.util.stream.Stream; +import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedClass; import org.junit.jupiter.params.provider.Arguments; @@ -128,6 +129,7 @@ private static List populateKeys(BPlusTree bpt, byte[] keys, int keyPos } @Test + @Disabled("SELECT DISTINCT ?zz { ?s ?p ?o } can result in 0 length prefixes") public void bptree_distinct_by_key_bad_01() { BPlusTree bpt = makeRangeIndex(this.treeOrder, 0); assertThrows(IllegalArgumentException.class, ()->bpt.distinctByKeyPrefix(0)); diff --git a/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/CandidateIndex.java b/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/CandidateIndex.java deleted file mode 100644 index 46bc26271ce..00000000000 --- a/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/CandidateIndex.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * 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 - * - * https://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. - * - * SPDX-License-Identifier: Apache-2.0 - */ - -package org.apache.jena.tdb2.solver.skipscan; - -import org.apache.jena.atlas.lib.tuple.Tuple; -import org.apache.jena.tdb2.store.tupletable.TupleIndexRecord; - -record CandidateIndex( - TupleIndexRecord index, - Tuple pattern, - int[] projectIndices, - ValueFilter residualConditions -) {} diff --git a/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/IndexMatch.java b/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/IndexMatch.java index 03ffc4dae83..8868ebed422 100644 --- a/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/IndexMatch.java +++ b/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/IndexMatch.java @@ -27,6 +27,7 @@ record IndexMatch( boolean canDoDirectDistinct, + /** Residual conditions are in index space, so (idx=1) w.r.t. a POS index refers to the O slot. */ ValueFilter[] residualConditions, int keyLen, int valLen) diff --git a/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/NodeIdUtils.java b/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/NodeIdUtils.java deleted file mode 100644 index e7d9b75e321..00000000000 --- a/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/NodeIdUtils.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * 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 - * - * https://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. - * - * SPDX-License-Identifier: Apache-2.0 - */ - -package org.apache.jena.tdb2.solver.skipscan; - -import org.apache.jena.atlas.lib.tuple.Tuple; -import org.apache.jena.atlas.lib.tuple.TupleFactory; -import org.apache.jena.tdb2.store.NodeId; -import org.apache.jena.tdb2.store.NodeIdFactory; -import org.apache.jena.tdb2.store.NodeIdType; - -class NodeIdUtils { - /** Minimum value for a NodeId. Used as lower bound in range retrievals. */ - private static final NodeId NodeIdMin = NodeIdFactory.createPtr(0); - - /** Maximum value for a NodeId. Used as upper bound in range retrievals. */ - private static final NodeId NodeIdMax = NodeId.createRaw(NodeIdType.SPECIAL, Long.MAX_VALUE); - - public static Tuple anyToMin(Tuple tuple) { - int n = tuple.len(); - NodeId[] arr = new NodeId[n]; - for (int i = 0; i < n; ++i) { - NodeId x = tuple.get(i); - arr[i] = NodeId.isAny(x) ? NodeIdMin : x; - } - return TupleFactory.create(arr); - } - - public static Tuple anyToMax(Tuple tuple) { - int n = tuple.len(); - NodeId[] arr = new NodeId[n]; - for (int i = 0; i < n; ++i) { - NodeId x = tuple.get(i); - arr[i] = NodeId.isAny(x) ? NodeIdMax : x; - } - return TupleFactory.create(arr); - } -} diff --git a/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/OpExecutorTDB2SkipScan.java b/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/OpExecutorTDB2SkipScan.java index 87449795776..f552225076b 100644 --- a/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/OpExecutorTDB2SkipScan.java +++ b/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/OpExecutorTDB2SkipScan.java @@ -48,6 +48,7 @@ import org.apache.jena.sparql.engine.QueryIterator; import org.apache.jena.sparql.engine.binding.Binding; import org.apache.jena.sparql.engine.iterator.QueryIter; +import org.apache.jena.sparql.engine.iterator.QueryIterCommonParent; import org.apache.jena.sparql.engine.iterator.QueryIterDistinct; import org.apache.jena.sparql.engine.iterator.QueryIterFilterExpr; import org.apache.jena.sparql.engine.iterator.QueryIterNullIterator; @@ -135,7 +136,7 @@ private static QueryIterator exec(PatternQuery patternQuery, Binding binding, Ex PatternQuery cacheKey = PatternQuery.toCacheKey(subst); SkipScanCandidate bestCandidate = indexCache.computeIfAbsent(cacheKey, cq -> { // System.err.println("NO CACHE HIT: " + canonicalQuery); - SkipScanCandidate r = findBestCandidate(patternQuery, execCxt); + SkipScanCandidate r = findBestCandidate(subst, execCxt); return r; }); @@ -162,7 +163,13 @@ private static QueryIterator exec(PatternQuery patternQuery, Binding binding, Ex innerIter = new QueryIterDistinct(innerIter, null, execCxt); } } - return innerIter; + + // FIXME Ugly but just for testing + // innerIter = QueryIterPlainWrapper.create(Iter.iter(innerIter).filter(b -> Algebra.compatible(b, binding))); + // innerIter = QueryIter.flatMap(innerIter, b -> Algebra.compatible(b, binding) ? QueryIterSingleton.create(binding, execCxt) : QueryIt, execCxt); + + QueryIter result = new QueryIterCommonParent(innerIter, binding, execCxt); + return result; } public static SkipScanCandidate findBestCandidate(PatternQuery patternQuery, ExecutionContext execCxt) { @@ -250,6 +257,9 @@ public static IndexMatch computeIndexMatch(TupleMap tm, TuplePatternSpec pattern // Add the constant node as a filter condition. residualConditions[numResidualConditions++] = new ValueFilter<>(j, node); + + // The residual condition on the index column (j) effectively covers the corresponding slot. + uncoveredSlotsMask &= ~(1 << tupleSlot); } } int valLen = j - keyLen; @@ -301,14 +311,10 @@ public static List planCandidates(NodeTupleTable nodeTupleTab return candidates; } - private static SkipScanCandidate planCandidate(TuplePatternSpec lookup, TupleIndex tupleIndex) { + static SkipScanCandidate planCandidate(TuplePatternSpec lookup, TupleIndex tupleIndex) { // Only consider indexes backed by a BPlusTree - if (tupleIndex instanceof TupleIndexRecord recordIdx) { - RangeIndex rangeIndex = recordIdx.getRangeIndex(); - if (!(rangeIndex instanceof BPlusTree)) { - return null; - } - } + if (!(tupleIndex instanceof TupleIndexRecord r) || !(r.getRangeIndex() instanceof BPlusTree)) + return null; TupleMap tm = tupleIndex.getMapping(); IndexMatch match = computeIndexMatch(tm, lookup); @@ -374,12 +380,9 @@ public static QueryIterator exec(TupleIndex tupleIndex, NodeTable nodeTable, Lis int n = map.tuple().length; Tuple pattern = TupleFactory.create(map.tuple()); - Tuple minPattern = NodeIdUtils.anyToMin(pattern); - Tuple maxPattern = NodeIdUtils.anyToMax(pattern); - RecordFactory rf = rangeIndex.getRecordFactory(); - Record minRecord = record(rf, minPattern); - Record maxRecord = record(rf, maxPattern); + Record minRecord = record(rf, pattern, false); + Record maxRecord = record(rf, pattern, true); // VarMap[] proj = map.proj; ValueFilter[] residualConditions = map.residualConditions(); @@ -424,7 +427,8 @@ public static QueryIterator exec(TupleIndex tupleIndex, NodeTable nodeTable, Lis finalProj = Arrays.copyOf(finalProjTmp, i); } - Iterator recordIt = bpt.distinctByKeyPrefix(n * NodeId.SIZE, minRecord, maxRecord); + Record maxRecordExclusive = Record.incrementKeyOrNull(maxRecord); + Iterator recordIt = bpt.distinctByKeyPrefix(n * NodeId.SIZE, minRecord, maxRecordExclusive); // Filter by recheck conditions first. if (residualConditions != null) { @@ -579,22 +583,36 @@ public static ValueFilter[] remapValueConditions(ValueFilter[] con ValueFilter[] result = new ValueFilter[n]; for (int i = 0; i < n; ++i) { ValueFilter condition = conditions[i]; - int slot = tupleMap.unmapIdx(condition.idx()); + // int slot = tupleMap.unmapIdx(condition.idx()); + int idx = condition.idx(); NodeId nodeId = nodeTable.getNodeIdForNode(condition.value()); - if (nodeId == null) { + if (NodeId.isDoesNotExist(nodeId)) { return null; } - result[i] = new ValueFilter<>(slot, nodeId); + result[i] = new ValueFilter<>(idx, nodeId); } return result; } - /** Create a record directly from the tuple (without a tuple map) */ - private static Record record(RecordFactory factory, Tuple tuple) { + /** + * Create a record directly from the tuple (without a tuple map). + * @param anyToMax If false then Node.ANY becomes a sequence of 0x00 bytes. + * If true then Node.ANY becomes a sequence of 0xff bytes. + */ + private static Record record(RecordFactory factory, Tuple tuple, boolean anyToMax) { int n = tuple.len(); byte[] b = new byte[n * NodeId.SIZE]; for (int i = 0; i < n ; i++) { - NodeIdFactory.set(tuple.get(i), b, i * NodeId.SIZE); + NodeId nodeId = tuple.get(i); + if (NodeId.isAny(nodeId)) { + // If anyToMax is false then just leave the bytes zero. + if (anyToMax) { + int offset = i * NodeId.SIZE; + Arrays.fill(b, offset, offset + NodeId.SIZE, (byte)0xFF); + } + } else { + NodeIdFactory.set(tuple.get(i), b, i * NodeId.SIZE); + } } return factory.create(b); } diff --git a/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/OpExtSkipScan.java b/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/OpExtSkipScan.java index b1e4e59cf3a..d721d501dea 100644 --- a/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/OpExtSkipScan.java +++ b/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/OpExtSkipScan.java @@ -32,22 +32,19 @@ import org.apache.jena.sparql.util.Context; import org.apache.jena.sparql.util.NodeIsomorphismMap; import org.apache.jena.sparql.util.Symbol; +import org.apache.jena.tdb2.sys.SystemTDB; public class OpExtSkipScan extends OpExt { protected PatternQuery patternQuery; - private static Symbol symOpExecutor = Symbol.create("opExecutor"); + static final Symbol symOpExecutor = SystemTDB.allocSymbol("opExecutor"); public static void setOpExecutorIfAbsent(Context cxt, OpExecutor opExecutor) { cxt.computeIfAbsent(symOpExecutor, x -> opExecutor); } - public static void setOpExecutor(Context cxt, OpExecutor opExecutor) { - cxt.set(symOpExecutor, opExecutor); - } - public static OpExecutor getOpExecutor(Context cxt) { return cxt.get(symOpExecutor); } diff --git a/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/PatternQuery.java b/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/PatternQuery.java index 30d7078a92d..4e808172a0c 100644 --- a/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/PatternQuery.java +++ b/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/PatternQuery.java @@ -27,6 +27,7 @@ import java.util.LinkedHashSet; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Set; import org.apache.jena.graph.Node; @@ -44,12 +45,12 @@ import org.apache.jena.sparql.core.Substitute; import org.apache.jena.sparql.core.Var; import org.apache.jena.sparql.core.VarAlloc; -import org.apache.jena.sparql.core.Vars; import org.apache.jena.sparql.engine.binding.Binding; import org.apache.jena.sparql.engine.join.ImmutableUniqueList; import org.apache.jena.sparql.engine.join.ImmutableUniqueList.Builder; import org.apache.jena.sparql.graph.NodeTransform; import org.apache.jena.sparql.graph.NodeTransformLib; +import org.apache.jena.sparql.util.VarUtils; /** * Single tuple access pattern. @@ -117,7 +118,7 @@ public record PatternQuery(boolean distinct, List project, Node[] tuple) { if (projectVars == null) { Set varSet = new LinkedHashSet<>(); - Vars.addVarsFromTriple(varSet, t); + VarUtils.addVarsFromTriple(varSet, t); if (g != null && g.isVariable()) { varSet.add(Var.alloc(g)); } @@ -230,4 +231,26 @@ public static PatternQuery toCacheKey(PatternQuery patternQuery) { return new PatternQuery(patternQuery.distinct(), newProject, newTuple); } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + Arrays.hashCode(tuple); + result = prime * result + Objects.hash(distinct, project); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + PatternQuery other = (PatternQuery) obj; + return distinct == other.distinct && Objects.equals(project, other.project) + && Arrays.equals(tuple, other.tuple); + } } diff --git a/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/SkipScanRewrite.java b/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/SkipScanRewrite.java index 0f8cad94253..e0e440626cd 100644 --- a/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/SkipScanRewrite.java +++ b/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/SkipScanRewrite.java @@ -24,12 +24,9 @@ import java.util.List; import org.apache.jena.sparql.algebra.Op; -import org.apache.jena.sparql.algebra.OpVisitorByTypeBase; -import org.apache.jena.sparql.algebra.OpWalker; import org.apache.jena.sparql.algebra.Transformer; import org.apache.jena.sparql.algebra.op.OpBGP; import org.apache.jena.sparql.algebra.op.OpDistinct; -import org.apache.jena.sparql.algebra.op.OpExt; import org.apache.jena.sparql.algebra.op.OpExtend; import org.apache.jena.sparql.algebra.op.OpFilter; import org.apache.jena.sparql.algebra.op.OpGroup; @@ -228,26 +225,5 @@ private static Var varOrNull(Aggregator agg) { Expr e = el.get(0); return e.isVariable() ? e.asVar() : null; } - - private static class AbortEarlyException extends RuntimeException { - private static final long serialVersionUID = 1L; - @Override public synchronized Throwable fillInStackTrace() { return this; } - } - - public static boolean usesSkipScan(Op op) { - boolean[] result = {false}; - try { - OpWalker.walk(op, new OpVisitorByTypeBase() { - @Override - public void visit(OpExt opExt) { - if (opExt instanceof OpExtSkipScan) { - result[0] = true; - throw new AbortEarlyException(); - } - } - }); - } catch (AbortEarlyException e) {} - return result[0]; - } } diff --git a/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/TransformDistinctPlacement.java b/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/TransformDistinctPlacement.java index 5fbdf6adf35..6c530f6168d 100644 --- a/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/TransformDistinctPlacement.java +++ b/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/TransformDistinctPlacement.java @@ -133,7 +133,7 @@ public void visit(OpExtend opExtend) { List extendVars = opExtend.getVarExprList().getVars(); boolean reapplyProject = !projectVars.containsAll(extendVars); if (reapplyProject) { - result = new OpProject(result, new ArrayList<>(extendVars)); + result = new OpProject(result, new ArrayList<>(projectVars)); } } } diff --git a/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/TuplePatternSpec.java b/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/TuplePatternSpec.java index ffbaa6e1ce9..8c84f398e2b 100644 --- a/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/TuplePatternSpec.java +++ b/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/TuplePatternSpec.java @@ -38,20 +38,6 @@ record TuplePatternSpec( EqualityLink[] equalityLinks, int neededSlotsMask) { // Omits the indices of unconstrained, undistinguished var. - public Var getVar(int varId) { - return varMaps[varId].var(); - } - - /** Get the index of the variable or -1 if absent. */ - public int getIdxVar(Var var) { - for (VarMap e : varMaps) { - if (e.var().equals(var)) { - return e.idx(); - } - } - return -1; - } - @Override public String toString() { return "IndexQuerySpec [tuple=" + Arrays.toString(tuple) + ", varMaps=" + Arrays.toString(varMaps) + ", projs=" @@ -89,7 +75,7 @@ public static TuplePatternSpec create(Node[] quad, List projection) { } equalityLinks[numEqualityLinks++] = new EqualityLink(i, j); - // Add i as needed + // Declare i as a needed slot neededSlots[numNeededSlots++] = i; alreadySeen = true; @@ -100,6 +86,7 @@ public static TuplePatternSpec create(Node[] quad, List projection) { neededSlots[numNeededSlots++] = j; } } + break; } } diff --git a/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan/Test05_EqualityLinkArrayOverflow.java b/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan/Test05_EqualityLinkArrayOverflow.java new file mode 100644 index 00000000000..f698441ea9b --- /dev/null +++ b/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan/Test05_EqualityLinkArrayOverflow.java @@ -0,0 +1,82 @@ +/* + * 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 + * + * https://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. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +package org.apache.jena.tdb2.solver.skipscan; + +import static org.apache.jena.tdb2.solver.skipscan_3995.SkipScanTestLib.assertSkipScanAgrees; +import static org.apache.jena.tdb2.solver.skipscan_3995.SkipScanTestLib.tdb2; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +import java.util.List; + +import org.apache.jena.graph.Node; +import org.apache.jena.sparql.core.Var; +import org.apache.jena.tdb2.store.DatasetGraphTDB; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Finding 5 - {@code TuplePatternSpec:93}. + * + *

{@code equalityLinks} and {@code neededSlots} are sized {@code n}, the tuple length:

+ *
{@code
+ * EqualityLink[] equalityLinks = null;   // ... new EqualityLink[n]
+ * int[] neededSlots = new int[n];
+ * }
+ *

but the nested i/j loop appends one entry per pair of equal slots - up to n(n-1)/2 - so a + * variable occurring three or more times overflows both arrays.

+ */ +public class Test05_EqualityLinkArrayOverflow { + + private static final String DATA = """ + :same :same :same . + :s1 :p :o1 . + :same { :same :same :same } + """; + + /** Three occurrences of one variable in a triple pattern. */ + @Test + public void distinct_tripleWithOneVarInEverySlot() { + DatasetGraphTDB dsg = tdb2(DATA); + assertSkipScanAgrees(dsg, "SELECT DISTINCT ?s { ?s ?s ?s }"); + } + + /** Four occurrences, in a quad pattern. */ + @Test + @Disabled("Skip scan not (yet) expected to be used for effectively: SELECT * { SELECT DISTINCT ?s { ?s [] [] } FILTER EXISTS { ?s ?s ?s } }") + public void distinct_quadWithOneVarInEverySlot() { + DatasetGraphTDB dsg = tdb2(DATA); + assertSkipScanAgrees(dsg, "SELECT DISTINCT ?s { GRAPH ?s { ?s ?s ?s } }"); + } + + /** The same, directly at {@code TuplePatternSpec.create}. */ + @Test + public void tuplePatternSpec_repeatedVariable() { + Var s = Var.alloc("s"); + Node[] triple = new Node[] {s, s, s}; + assertDoesNotThrow(() -> TuplePatternSpec.create(triple, List.of(s)), + "TuplePatternSpec.create overflows its helper arrays for (?s ?s ?s)"); + + Node[] quad = new Node[] {s, s, s, s}; + assertDoesNotThrow(() -> TuplePatternSpec.create(quad, List.of(s)), + "TuplePatternSpec.create overflows its helper arrays for (?s ?s ?s ?s)"); + } +} diff --git a/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan/Test07_ResidualConditionsUnreachable.java b/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan/Test07_ResidualConditionsUnreachable.java new file mode 100644 index 00000000000..771c1546d8c --- /dev/null +++ b/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan/Test07_ResidualConditionsUnreachable.java @@ -0,0 +1,121 @@ +/* + * 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 + * + * https://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. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +package org.apache.jena.tdb2.solver.skipscan; + +import static org.apache.jena.tdb2.solver.skipscan_3995.SkipScanTestLib.tdb2; +import static org.apache.jena.tdb2.solver.skipscan_3995.SkipScanTestLib.tripleTable; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; + +import org.apache.jena.atlas.lib.tuple.TupleMap; +import org.apache.jena.graph.Node; +import org.apache.jena.graph.NodeFactory; +import org.apache.jena.sparql.core.Var; +import org.apache.jena.tdb2.solver.skipscan_3995.SkipScanTestLib; +import org.apache.jena.tdb2.store.DatasetGraphTDB; +import org.apache.jena.tdb2.store.tupletable.TupleIndex; +import org.junit.jupiter.api.Test; + +// Residual condidions should +// SELECT DISTINCT ?p { :s ?p :foo } should use either: +// (SPO with recheck slot[2]=:foo) or +// OPS (with recheck slot[2]=:s) + +/** + * Finding 7 - {@code OpExecutorTDB2SkipScan:252}. + * + *

In {@code computeIndexMatch}, the branch that records a constant as a residual condition + * never clears that slot's bit:

+ *
{@code
+ * } else {
+ *     if ( residualConditions == null )
+ *         residualConditions = new ValueFilter[idxLen - j];
+ *     residualConditions[numResidualConditions++] = new ValueFilter<>(j, node);
+ *     // uncoveredSlotsMask is not updated
+ * }
+ * }
+ *

so {@code uncoveredSlotsMask != 0} still holds at the end and the index is rejected. Any + * index with a constant after the first variable is therefore unusable, and + * {@code residualConditions} can never be non-empty - which makes + * {@code remapValueConditions}, the {@code Iter.filter} over the records, and + * {@code IndexMatch.numResidualConditions} in the plan comparator unreachable.

+ */ +public class Test07_ResidualConditionsUnreachable { + + private static final String DATA = """ + :s1 :p :o1 . + :s1 :p :o2 . + :s2 :p2 :o3 . + """; + + private static final Node p = NodeFactory.createURI("http://example/p"); + + /** + * Fix-agnostic: residual conditions are a feature of the design, so some pattern and index + * must produce them. None does. + */ + @Test + public void residualConditionsAreReachable() { + DatasetGraphTDB dsg = tdb2(DATA); + // Var s = Var.alloc("s"); + Var p = Var.alloc("p"); + + List patterns = List.of(new Node[] { + NodeFactory.createURI("http://example/s1"), p, NodeFactory.createURI("http://example/o1")}); + List> projections = List.of(List.of(p)); + + boolean seen = false; + for ( Node[] pattern : patterns ) { + for ( List projection : projections ) { + TuplePatternSpec spec = TuplePatternSpec.create(pattern, projection); + for ( TupleIndex index : tripleTable(dsg).getTupleTable().getIndexes() ) { + TupleMap tupleMap = index.getMapping(); + IndexMatch match = OpExecutorTDB2SkipScan.computeIndexMatch(tupleMap, spec); + if ( match != null && match.numResidualConditions() > 0 ) + seen = true; + } + } + } + assertTrue(seen, "No pattern/index combination ever produces a residual condition, so the " + + "whole residual-condition code path is unreachable"); + } + + /** + * The concrete case: for {@code (?s :p ?o)} projecting {@code ?s}, SPO offers an (s,p) prefix + * with a filter on the predicate column, but the index is rejected outright. + */ + @Test + public void spoIsUsableForAConstantPredicate() { + DatasetGraphTDB dsg = tdb2(DATA); + Var s = Var.alloc("s"); + Var o = Var.alloc("o"); + + TuplePatternSpec spec = TuplePatternSpec.create(new Node[] {s, p, o}, List.of(s)); + TupleMap spo = SkipScanTestLib.tripleIndex(dsg, "SPO").getMapping(); + + assertNotNull(OpExecutorTDB2SkipScan.computeIndexMatch(spo, spec), + "SPO is unusable for (?s :p ?o) projecting ?s, although the constant predicate " + + "could be applied as a residual condition"); + } +} diff --git a/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan/Test09_NonRecordIndexGuard.java b/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan/Test09_NonRecordIndexGuard.java new file mode 100644 index 00000000000..e02ccf03213 --- /dev/null +++ b/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan/Test09_NonRecordIndexGuard.java @@ -0,0 +1,86 @@ +/* + * 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 + * + * https://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. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +package org.apache.jena.tdb2.solver.skipscan; + +import static org.apache.jena.tdb2.solver.skipscan_3995.SkipScanTestLib.tdb2; +import static org.apache.jena.tdb2.solver.skipscan_3995.SkipScanTestLib.tripleIndex; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; + +import java.util.List; + +import org.apache.jena.graph.Node; +import org.apache.jena.sparql.core.Var; +import org.apache.jena.tdb2.store.DatasetGraphTDB; +import org.apache.jena.tdb2.store.tupletable.TupleIndex; +import org.apache.jena.tdb2.store.tupletable.TupleIndexRecord; +import org.apache.jena.tdb2.store.tupletable.TupleIndexWrapper; +import org.junit.jupiter.api.Test; + +/** + * Finding 9 - {@code OpExecutorTDB2SkipScan:306}. + * + *
{@code
+ * if ( tupleIndex instanceof TupleIndexRecord recordIdx ) {
+ *     RangeIndex rangeIndex = recordIdx.getRangeIndex();
+ *     if ( !(rangeIndex instanceof BPlusTree) )
+ *         return null;
+ * }
+ * }
+ *

An index that is not a {@code TupleIndexRecord} at all does not match the pattern, so it + * passes the guard - and then {@code exec} does an unchecked cast:

+ *
{@code
+ * TupleIndexRecord tupleIndexRecord = (TupleIndexRecord)tupleIndex;
+ * }
+ */ +public class Test09_NonRecordIndexGuard { + + private static final String DATA = """ + :s1 :p :o1 . + :s1 :p :o2 . + """; + + /** + * Either the guard rejects the index, or the candidate must carry something + * {@code exec} can cast. {@link TupleIndexWrapper} is a {@code TupleIndex} that is not a + * {@code TupleIndexRecord}. + */ + @Test + public void candidateIndexIsCastable() { + DatasetGraphTDB dsg = tdb2(DATA); + Var s = Var.alloc("s"); + Var o = Var.alloc("o"); + Var pv = Var.alloc("p"); + Node[] pattern = new Node[] {s, pv, o}; + TuplePatternSpec spec = TuplePatternSpec.create(pattern, List.of(s)); + + TupleIndex wrapped = new TupleIndexWrapper(tripleIndex(dsg, "SPO")); + SkipScanCandidate candidate = OpExecutorTDB2SkipScan.planCandidate(spec, wrapped); + if ( candidate == null ) + // The guard rejected it, which is one correct outcome. + return; + + TupleIndex index = candidate.index(); + assertInstanceOf(TupleIndexRecord.class, index, + "planCandidate accepted a TupleIndex that is not a TupleIndexRecord; " + + "OpExecutorTDB2SkipScan.exec casts to TupleIndexRecord and throws ClassCastException"); + } +} diff --git a/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan/Test10_RemapValueConditions.java b/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan/Test10_RemapValueConditions.java new file mode 100644 index 00000000000..e62cf996371 --- /dev/null +++ b/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan/Test10_RemapValueConditions.java @@ -0,0 +1,108 @@ +/* + * 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 + * + * https://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. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +package org.apache.jena.tdb2.solver.skipscan; + +import static org.apache.jena.tdb2.solver.skipscan_3995.SkipScanTestLib.tdb2; +import static org.apache.jena.tdb2.solver.skipscan_3995.SkipScanTestLib.tripleTable; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + +import org.apache.jena.atlas.lib.tuple.TupleMap; +import org.apache.jena.graph.Node; +import org.apache.jena.graph.NodeFactory; +import org.apache.jena.system.Txn; +import org.apache.jena.tdb2.store.DatasetGraphTDB; +import org.apache.jena.tdb2.store.NodeId; +import org.apache.jena.tdb2.store.nodetable.NodeTable; +import org.apache.jena.tdb2.store.tupletable.TupleIndex; +import org.junit.jupiter.api.Test; + +/** + * Finding 10 - {@code OpExecutorTDB2SkipScan:582}. + * + *
{@code
+ * int slot = tupleMap.unmapIdx(condition.idx());
+ * NodeId nodeId = nodeTable.getNodeIdForNode(condition.value());
+ * if ( nodeId == null )
+ *     return null;
+ * }
+ *

Two problems. First, {@code condition.idx()} is already an index-space column - unlike + * {@code projs} and {@code equalityLinks}, which hold tuple slots, the {@code j} stored by + * {@code computeIndexMatch} is the index position - and the filter reads it back with + * {@code extractNodeId(recordKey, idx)}, also index-space. Remapping it points the filter at a + * different column. Second, {@code getNodeIdForNode} returns {@code NodeId.NodeDoesNotExist}, + * never {@code null}, so an unknown constant yields a filter that matches nothing instead of + * short-circuiting to an empty result.

+ * + *

Latent while finding 7 keeps {@code residualConditions} unreachable; live as soon as it is + * fixed.

+ */ +public class Test10_RemapValueConditions { + + private static final String DATA = """ + :s1 :p :o1 . + :s1 :p :o2 . + """; + + /** The column of a residual condition is already in index space: it must not be remapped. */ + @Test + public void columnIsNotRemapped() { + DatasetGraphTDB dsg = tdb2(DATA); + NodeTable nodeTable = tripleTable(dsg).getNodeTable(); + Node o1 = NodeFactory.createURI("http://example/o1"); + + Txn.executeRead(dsg, () -> { + for ( TupleIndex index : tripleTable(dsg).getTupleTable().getIndexes() ) { + TupleMap tupleMap = index.getMapping(); + for ( int column = 0; column < tupleMap.length(); column++ ) { + @SuppressWarnings("unchecked") + ValueFilter[] mapped = OpExecutorTDB2SkipScan.remapValueConditions( + new ValueFilter[] {new ValueFilter<>(column, o1)}, tupleMap, nodeTable); + assertNotNull(mapped); + final int expected = column; + assertEquals(expected, mapped[0].idx(), + () -> "Residual condition column " + expected + " of index " + index.getName() + + " was remapped; the filter would read a different column"); + } + } + }); + } + + /** "Returns null if any condition could not be mapped" - an absent term has no NodeId. */ + @Test + public void unknownConstantGivesNull() { + DatasetGraphTDB dsg = tdb2(DATA); + NodeTable nodeTable = tripleTable(dsg).getNodeTable(); + Node absent = NodeFactory.createURI("http://example/not-in-the-database"); + TupleMap tupleMap = tripleTable(dsg).getTupleTable().getIndexes()[0].getMapping(); + + Txn.executeRead(dsg, () -> { + @SuppressWarnings("unchecked") + ValueFilter[] mapped = OpExecutorTDB2SkipScan.remapValueConditions( + new ValueFilter[] {new ValueFilter<>(0, absent)}, tupleMap, nodeTable); + assertNull(mapped, + "remapValueConditions must return null for a constant with no NodeId; " + + "getNodeIdForNode returns NodeId.NodeDoesNotExist, never null"); + }); + } +} diff --git a/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan/Test13_OpExtSkipScanContract.java b/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan/Test13_OpExtSkipScanContract.java new file mode 100644 index 00000000000..554af9f0944 --- /dev/null +++ b/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan/Test13_OpExtSkipScanContract.java @@ -0,0 +1,82 @@ +/* + * 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 + * + * https://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. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +package org.apache.jena.tdb2.solver.skipscan; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; + +import org.apache.jena.graph.Node; +import org.apache.jena.graph.NodeFactory; +import org.apache.jena.sparql.core.Var; +import org.apache.jena.sparql.util.NodeIsomorphismMap; +import org.apache.jena.sparql.util.Symbol; +import org.apache.jena.tdb2.sys.SystemTDB; +import org.junit.jupiter.api.Test; + +/** + * Finding 13 - {@code OpExtSkipScan:89}. + * + *
{@code
+ * @Override public int hashCode() { return 31 * patternQuery.hashCode(); }
+ * @Override public boolean equalTo(Op other, NodeIsomorphismMap labelMap) {
+ *     return other instanceof OpExtSkipScan o && this.effectiveOp().equalTo(o.effectiveOp(), labelMap);
+ * }
+ * }
+ *

{@code hashCode} goes through {@code PatternQuery.hashCode()}, which is array-identity + * based (finding 8), while {@code equalTo} compares the effective op. Two structurally identical + * nodes are therefore equal with different hash codes, which breaks any hash-based use of + * {@code Op}.

+ * + *

Also: the executor is stashed under a bare {@code Symbol.create("opExecutor")} rather than + * a TDB-namespaced symbol.

+ */ +public class Test13_OpExtSkipScanContract { + + private static final Node p = NodeFactory.createURI("http://example/p"); + + private static OpExtSkipScan op() { + Node[] tuple = new Node[] {Var.alloc("s"), p, Var.alloc("o")}; + return new OpExtSkipScan(new PatternQuery(true, List.of(Var.alloc("s")), tuple)); + } + + /** Equal ops must have equal hash codes. */ + @Test + public void equalOpsHaveEqualHashCodes() { + OpExtSkipScan a = op(); + OpExtSkipScan b = op(); + assertTrue(a.equalTo(b, new NodeIsomorphismMap()), + "Two structurally identical OpExtSkipScan nodes are not equal"); + assertEquals(a.hashCode(), b.hashCode(), + "Two equal OpExtSkipScan nodes have different hash codes"); + } + + /** Context keys must be namespaced; {@code "opExecutor"} is a bare, collidable name. */ + @Test + public void opExecutorSymbolIsNamespaced() { + Symbol symbol = OpExtSkipScan.symOpExecutor; + assertTrue(symbol.getSymbol().startsWith(SystemTDB.symbolNamespace), + () -> "The OpExecutor is stored under an un-namespaced context symbol: " + + symbol.getSymbol()); + } +} diff --git a/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan/TestOpExecutorTDB2SkipScan.java b/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan/TestOpExecutorTDB2SkipScan.java index 63a65a4edaa..1f55afac91e 100644 --- a/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan/TestOpExecutorTDB2SkipScan.java +++ b/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan/TestOpExecutorTDB2SkipScan.java @@ -27,10 +27,6 @@ import java.util.List; import java.util.stream.Stream; -import org.junit.jupiter.api.DynamicNode; -import org.junit.jupiter.api.DynamicTest; -import org.junit.jupiter.api.TestFactory; - import org.apache.commons.collections4.iterators.PermutationIterator; import org.apache.jena.atlas.iterator.Iter; import org.apache.jena.graph.Node; @@ -43,7 +39,6 @@ import org.apache.jena.sparql.core.DatasetGraphFactory; import org.apache.jena.sparql.core.Quad; import org.apache.jena.sparql.core.Var; -import org.apache.jena.sparql.core.Vars; import org.apache.jena.sparql.exec.QueryExec; import org.apache.jena.sparql.expr.Expr; import org.apache.jena.sparql.expr.ExprVar; @@ -52,6 +47,7 @@ import org.apache.jena.sparql.sse.SSE; import org.apache.jena.sparql.syntax.ElementNamedGraph; import org.apache.jena.sparql.syntax.ElementTriplesBlock; +import org.apache.jena.sparql.util.VarUtils; import org.apache.jena.system.AutoTxn; import org.apache.jena.system.Txn; import org.apache.jena.tdb2.TDB2Factory; @@ -60,6 +56,9 @@ import org.apache.jena.vocabulary.RDF; import org.apache.jena.vocabulary.RDFS; import org.jspecify.annotations.NonNull; +import org.junit.jupiter.api.DynamicNode; +import org.junit.jupiter.api.DynamicTest; +import org.junit.jupiter.api.TestFactory; public class TestOpExecutorTDB2SkipScan extends AbstractDatasetGraphCompare @@ -147,6 +146,7 @@ public static void addResourceObjectsAsSubjects(DatasetGraph referenceDsg) { .toList(); extra.forEach(dataDsg::add); } + referenceDsg.addAll(dataDsg); } /** Sub classes can use this method to generate dynamic tests. */ @@ -170,7 +170,7 @@ public List createTestsCountVarDistinct(DatasetGraph referenceDsg, List<@NonNull DynamicTest> tests = findQuads.stream().flatMap(rawQuad -> { Quad quad = anyToVar(rawQuad); List vars = new ArrayList<>(4); - Vars.addVarsFromQuad(vars, quad); + VarUtils.addVarsFromQuad(vars, quad); if (vars.isEmpty()) { // Skip test cases with empty vars because they don't hit OpExecutorTDB2Index.tryExec(opGroup, input, execCxt) diff --git a/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan_3995/SkipScanTestLib.java b/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan_3995/SkipScanTestLib.java new file mode 100644 index 00000000000..c09b66e6881 --- /dev/null +++ b/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan_3995/SkipScanTestLib.java @@ -0,0 +1,138 @@ +/* + * 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 + * + * https://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. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +package org.apache.jena.tdb2.solver.skipscan_3995; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.LongAdder; + +import org.apache.jena.atlas.lib.ListUtils; +import org.apache.jena.query.Query; +import org.apache.jena.query.QueryFactory; +import org.apache.jena.riot.Lang; +import org.apache.jena.riot.RDFParser; +import org.apache.jena.sparql.algebra.Table; +import org.apache.jena.sparql.engine.binding.Binding; +import org.apache.jena.sparql.exec.QueryExec; +import org.apache.jena.sparql.exec.QueryExecBuilder; +import org.apache.jena.system.Txn; +import org.apache.jena.tdb2.TDB2Factory; +import org.apache.jena.tdb2.solver.skipscan.OpExecutorTDB2SkipScan; +import org.apache.jena.tdb2.store.DatasetGraphTDB; +import org.apache.jena.tdb2.store.NodeId; +import org.apache.jena.tdb2.store.nodetable.NodeTable; +import org.apache.jena.tdb2.store.nodetupletable.NodeTupleTable; +import org.apache.jena.tdb2.store.tupletable.TupleIndex; +import org.apache.jena.tdb2.sys.SystemTDB; +import org.apache.jena.tdb2.sys.TDBInternal; + +/** + * Helpers for the PR #3995 review tests. + * + *

The central operation is {@link #assertSkipScanAgrees}: run the same query twice over the + * same TDB2 database, once with {@link SystemTDB#symSkipScan} off (the reference answer produced + * by the general machinery) and once with it on, and require the two to agree. It also requires + * that the skip scan was actually engaged, so a test cannot pass vacuously because the rewrite + * declined to fire.

+ */ +public class SkipScanTestLib { + + public static final String PREFIXES = """ + PREFIX : + PREFIX xsd: + """; + + /** Create a TDB2 database and load the given TriG data (the {@link #PREFIXES} are prepended). */ + public static DatasetGraphTDB tdb2(String trigData) { + DatasetGraphTDB dsg = TDBInternal.getDatasetGraphTDB(TDB2Factory.createDataset()); + Txn.executeWrite(dsg, () -> RDFParser.fromString(PREFIXES + trigData, Lang.TRIG).parse(dsg)); + return dsg; + } + + /** Execute a query (the {@link #PREFIXES} are prepended) and return the rows. */ + public static List rows(DatasetGraphTDB dsg, String queryString, boolean skipScan, + LongAdder okCounter, LongAdder failoverCounter) { + Query query = QueryFactory.create(PREFIXES + queryString); + Table table = Txn.calculateRead(dsg, () -> { + QueryExecBuilder builder = QueryExec.dataset(dsg).query(query).set(SystemTDB.symSkipScan, skipScan); + if ( okCounter != null ) + builder = builder.set(OpExecutorTDB2SkipScan.symSkipScanOkCounter, okCounter); + if ( failoverCounter != null ) + builder = builder.set(OpExecutorTDB2SkipScan.symSkipScanFailoverCounter, failoverCounter); + return builder.table(); + }); + List result = new ArrayList<>(); + table.rows().forEachRemaining(result::add); + return result; + } + + /** The reference answer: the same query with the skip scan disabled. */ + public static List reference(DatasetGraphTDB dsg, String queryString) { + return rows(dsg, queryString, false, null, null); + } + + /** + * Require that the skip scan answers the query exactly as the general machinery does. + * Also requires that the skip scan was used at least once and never failed over, + * so that the comparison really does exercise the new code path. + */ + public static void assertSkipScanAgrees(DatasetGraphTDB dsg, String queryString) { + List expected = reference(dsg, queryString); + + LongAdder ok = new LongAdder(); + LongAdder failover = new LongAdder(); + List actual = rows(dsg, queryString, true, ok, failover); + + assertTrue(ok.longValue() > 0, + () -> "Skip scan was not used - this test does not exercise the skip scan path: " + queryString); + assertEquals(0L, failover.longValue(), + () -> "Skip scan failed over to the general machinery: " + queryString); + assertTrue(ListUtils.equalsUnordered(expected, actual), + () -> "Skip scan answered differently from the general machinery." + + "\n Query: " + queryString.strip() + + "\n Expected " + expected.size() + " bindings: " + expected + + "\n Actual " + actual.size() + " bindings: " + actual); + } + + /** The {@link NodeTupleTable} of the default graph (triples). */ + public static NodeTupleTable tripleTable(DatasetGraphTDB dsg) { + return dsg.getTripleTable().getNodeTupleTable(); + } + + /** Find a triple index by name, e.g. {@code "SPO"}. */ + public static TupleIndex tripleIndex(DatasetGraphTDB dsg, String name) { + for ( TupleIndex index : tripleTable(dsg).getTupleTable().getIndexes() ) { + if ( name.equals(index.getName()) ) + return index; + } + throw new IllegalArgumentException("No such index: " + name); + } + + /** The NodeId a term is stored under, or {@link NodeId#NodeDoesNotExist}. */ + public static NodeId nodeId(DatasetGraphTDB dsg, org.apache.jena.graph.Node node) { + NodeTable nodeTable = tripleTable(dsg).getNodeTable(); + return Txn.calculateRead(dsg, () -> nodeTable.getNodeIdForNode(node)); + } +} diff --git a/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan_3995/TS_SkipScan_3995.java b/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan_3995/TS_SkipScan_3995.java new file mode 100644 index 00000000000..b9a753368b8 --- /dev/null +++ b/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan_3995/TS_SkipScan_3995.java @@ -0,0 +1,65 @@ +/* + * 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 + * + * https://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. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +package org.apache.jena.tdb2.solver.skipscan_3995; + +import org.apache.jena.tdb2.solver.skipscan.Test05_EqualityLinkArrayOverflow; +import org.apache.jena.tdb2.solver.skipscan.Test07_ResidualConditionsUnreachable; +import org.apache.jena.tdb2.solver.skipscan.Test09_NonRecordIndexGuard; +import org.apache.jena.tdb2.solver.skipscan.Test10_RemapValueConditions; +import org.apache.jena.tdb2.solver.skipscan.Test13_OpExtSkipScanContract; +import org.junit.platform.suite.api.SelectClasses; +import org.junit.platform.suite.api.Suite; + +/** + * Review tests for PR #3995 + * (GH-3994: Improved TDB2 index access for single pattern queries). + * + *

One class per review finding, numbered to match. Each test states the behaviour the code + * should have, so these tests fail against the PR as it stands - each failure + * is the finding. Two exceptions, noted in their own javadoc, pass today and are guards: + * {@link Test11_KeyPrefixLengthValidation#distinctWithNoProjectedVariables()} and + * {@link Test15_UnusedCodeAndWeakAssertion#distinctOverRandIsNotCollapsed()}.

+ * + *

Most of the query-level tests run the same query twice over the same TDB2 database, with + * {@code SystemTDB.symSkipScan} off and on, and require the answers to agree - see + * {@link SkipScanTestLib#assertSkipScanAgrees}. They also require that the skip scan was + * actually engaged, so none of them can pass vacuously.

+ */ +@Suite +@SelectClasses({ + Test01_DistinctPlacementProjection.class + , Test02_InputBindingDropped.class + , Test03_CacheKeySubstitution.class + , Test04_NodeIdMaxUpperBound.class + , Test05_EqualityLinkArrayOverflow.class + , Test06_RecordPadRightUpperBound.class + , Test07_ResidualConditionsUnreachable.class + , Test08_PatternQueryCacheKey.class + , Test09_NonRecordIndexGuard.class + , Test10_RemapValueConditions.class + , Test11_KeyPrefixLengthValidation.class + , Test12_PrefixIteratorRange.class + , Test13_OpExtSkipScanContract.class + , Test14_AddResourceObjectsAsSubjects.class +}) +public class TS_SkipScan_3995 { +} diff --git a/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan_3995/Test01_DistinctPlacementProjection.java b/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan_3995/Test01_DistinctPlacementProjection.java new file mode 100644 index 00000000000..6fcb94c202a --- /dev/null +++ b/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan_3995/Test01_DistinctPlacementProjection.java @@ -0,0 +1,93 @@ +/* + * 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 + * + * https://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. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +package org.apache.jena.tdb2.solver.skipscan_3995; + +import static org.apache.jena.tdb2.solver.skipscan_3995.SkipScanTestLib.assertSkipScanAgrees; +import static org.apache.jena.tdb2.solver.skipscan_3995.SkipScanTestLib.tdb2; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.Set; + +import org.junit.jupiter.api.Test; + +import org.apache.jena.sparql.algebra.Op; +import org.apache.jena.sparql.algebra.OpVars; +import org.apache.jena.sparql.algebra.Transformer; +import org.apache.jena.sparql.core.Var; +import org.apache.jena.sparql.sse.SSE; +import org.apache.jena.tdb2.solver.skipscan.TransformDistinctPlacement; +import org.apache.jena.tdb2.store.DatasetGraphTDB; + +/** + * Finding 1 - {@code TransformDistinctPlacement:136}. + * + *

After pushing DISTINCT below an {@code OpExtend}, the re-applied projection is built from + * the extend-defined variables alone:

+ *
{@code
+ * List extendVars = opExtend.getVarExprList().getVars();
+ * if ( !projectVars.containsAll(extendVars) )
+ *     result = new OpProject(result, new ArrayList<>(extendVars));
+ * }
+ *

so every pattern variable - the DISTINCT and GROUP BY variables included - is projected + * away. The transform must preserve the variables visible from the operator it replaces.

+ */ +public class Test01_DistinctPlacementProjection { + + private static final String DATA = """ + :s1 :p :o1 . + :s1 :p :o2 . + :s2 :p2 :o3 . + """; + + /** + * The transform replaces the OpDistinct, so the result must make the same variables visible. + * Here that is {@code ?o}: the re-applied projection keeps only {@code ?z} instead. + */ + @Test + public void visibleVarsArePreserved_extend() { + Op input = SSE.parseOp("(distinct (project (?o) (extend ((?z ?o)) (bgp (?s :p ?o)))))"); + Op output = Transformer.transform(new TransformDistinctPlacement(), input); + + Set before = OpVars.visibleVars(input); + Set after = OpVars.visibleVars(output); + assertEquals(before, after, + () -> "Pushing DISTINCT over the extend changed the visible variables." + + "\n Input: " + input + + "\n Output: " + output); + } + + /** {@code SELECT DISTINCT ?o { ?s :p ?o BIND(?o AS ?z) }} must still bind {@code ?o}. */ + @Test + public void distinctOverBind() { + DatasetGraphTDB dsg = tdb2(DATA); + assertSkipScanAgrees(dsg, "SELECT DISTINCT ?o { ?s :p ?o BIND(?o AS ?z) }"); + } + + /** The same defect reached through the OpGroup rewrite: the GROUP BY variable is lost. */ + @Test + public void groupByOverBind() { + DatasetGraphTDB dsg = tdb2(DATA); + assertSkipScanAgrees(dsg, """ + SELECT ?p (MIN(?o) AS ?m) { ?s ?p ?o BIND(LANG(?o) AS ?l) } GROUP BY ?p + """); + } +} diff --git a/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan_3995/Test02_InputBindingDropped.java b/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan_3995/Test02_InputBindingDropped.java new file mode 100644 index 00000000000..52314b3ff02 --- /dev/null +++ b/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan_3995/Test02_InputBindingDropped.java @@ -0,0 +1,73 @@ +/* + * 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 + * + * https://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. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +package org.apache.jena.tdb2.solver.skipscan_3995; + +import static org.apache.jena.tdb2.solver.skipscan_3995.SkipScanTestLib.assertSkipScanAgrees; +import static org.apache.jena.tdb2.solver.skipscan_3995.SkipScanTestLib.tdb2; + +import org.junit.jupiter.api.Test; + +import org.apache.jena.tdb2.store.DatasetGraphTDB; + +/** + * Finding 2 - {@code OpExecutorTDB2SkipScan:451}. + * + *

Result rows are built with {@code new BindingNodeId()}, with no parent binding, so every + * variable carried by the input binding is dropped:

+ *
{@code
+ * bindingIdIt = Iter.map(recordIt, record -> {
+ *     BindingNodeId b = new BindingNodeId();     // no parent
+ *     ...
+ * });
+ * }
+ *

The fail-over path executes {@code opExecutor.executeOp(op, )} and so does + * keep them, which makes the two paths disagree.

+ * + *

These queries put the skip scan on the right of a sequence/join, so it is evaluated with a + * non-empty input binding.

+ */ +public class Test02_InputBindingDropped { + + private static final String DATA = """ + :a :q :b . + :s1 :p :o1 . + :s1 :p :o2 . + """; + + /** {@code ?x} and {@code ?y} come from the input binding and must survive. */ + @Test + public void joinWithDistinctSubSelect() { + DatasetGraphTDB dsg = tdb2(DATA); + assertSkipScanAgrees(dsg, """ + SELECT * { ?x :q ?y { SELECT DISTINCT ?p { ?s ?p ?o } } } + """); + } + + /** The same, with the sub-select naming two variables. */ + @Test + public void joinWithDistinctSubSelect_twoVars() { + DatasetGraphTDB dsg = tdb2(DATA); + assertSkipScanAgrees(dsg, """ + SELECT * { ?x :q ?y { SELECT DISTINCT ?s ?p { ?s ?p ?o } } } + """); + } +} diff --git a/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan_3995/Test03_CacheKeySubstitution.java b/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan_3995/Test03_CacheKeySubstitution.java new file mode 100644 index 00000000000..88b1a2c40cf --- /dev/null +++ b/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan_3995/Test03_CacheKeySubstitution.java @@ -0,0 +1,77 @@ +/* + * 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 + * + * https://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. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +package org.apache.jena.tdb2.solver.skipscan_3995; + +import static org.apache.jena.tdb2.solver.skipscan_3995.SkipScanTestLib.assertSkipScanAgrees; +import static org.apache.jena.tdb2.solver.skipscan_3995.SkipScanTestLib.tdb2; + +import org.junit.jupiter.api.Test; + +import org.apache.jena.tdb2.store.DatasetGraphTDB; + +/** + * Finding 3 - {@code OpExecutorTDB2SkipScan:138}. + * + *

The index cache is keyed on the substituted pattern but the candidate is computed + * from the unsubstituted one:

+ *
{@code
+ * PatternQuery subst = PatternQuery.substitute(patternQuery, binding);
+ * PatternQuery cacheKey = PatternQuery.toCacheKey(subst);
+ * SkipScanCandidate bestCandidate = indexCache.computeIfAbsent(cacheKey,
+ *     cq -> findBestCandidate(patternQuery, execCxt));   // not subst
+ * }
+ *

so the IndexMatch (key length, value length, residual conditions, canDoDirectDistinct) + * describes a different pattern from the one executed. The constant substituted in from the + * binding ends up neither in the key prefix nor in the residual conditions, so it is never + * applied, and a stale {@code canDoDirectDistinct} suppresses the de-duplication.

+ */ +public class Test03_CacheKeySubstitution { + + private static final String DATA = """ + :s1 :p :o1 . + :s1 :p :o2 . + :s2 :p2 :o1 . + :s3 :p3 :o9 . + :a :q :o1 . + """; + + /** + * {@code ?o} is bound to {@code :o1} by the outer pattern before the sub-select runs, so the + * executed pattern is {@code (?s ?p :o1)} while the plan was made for {@code (?s ?p ?o)}. + */ + @Test + public void substitutedConstantIsApplied() { + DatasetGraphTDB dsg = tdb2(DATA); + assertSkipScanAgrees(dsg, """ + SELECT * { ?x :q ?o { SELECT DISTINCT ?p ?o { ?s ?p ?o } } } + """); + } + + /** The same shape with the subject substituted instead. */ + @Test + public void substitutedSubject() { + DatasetGraphTDB dsg = tdb2(DATA); + assertSkipScanAgrees(dsg, """ + SELECT * { VALUES ?s { :s1 :s2 } { SELECT DISTINCT ?s ?p { ?s ?p ?o } } } + """); + } +} diff --git a/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan_3995/Test04_NodeIdMaxUpperBound.java b/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan_3995/Test04_NodeIdMaxUpperBound.java new file mode 100644 index 00000000000..896e7980c57 --- /dev/null +++ b/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan_3995/Test04_NodeIdMaxUpperBound.java @@ -0,0 +1,99 @@ +/* + * 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 + * + * https://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. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +package org.apache.jena.tdb2.solver.skipscan_3995; + +import static org.apache.jena.tdb2.solver.skipscan_3995.SkipScanTestLib.assertSkipScanAgrees; +import static org.apache.jena.tdb2.solver.skipscan_3995.SkipScanTestLib.tdb2; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; + +import java.util.Arrays; + +import org.apache.jena.dboe.base.record.Record; +import org.apache.jena.dboe.base.record.RecordFactory; +import org.apache.jena.dboe.test.RecordLib; +import org.apache.jena.dboe.trans.bplustree.BPlusTree; +import org.apache.jena.dboe.trans.bplustree.BPlusTreeFactory; +import org.apache.jena.tdb2.store.DatasetGraphTDB; +import org.junit.jupiter.api.Test; + +/** + * Finding 4 - {@code NodeIdUtils:35}. + * + *
{@code
+ * private static final NodeId NodeIdMax = NodeId.createRaw(NodeIdType.SPECIAL, Long.MAX_VALUE);
+ * }
+ *

encodes to {@code 0xF0FFFFFFFFFFFFFF}, which is not an upper bound over storable NodeIds: + * inline negative {@code xsd:double} values encode above it. Range upper bounds built with + * {@code anyToMax} therefore silently exclude real records.

+ */ +public class Test04_NodeIdMaxUpperBound { + + private static final String DATA = """ + :s1 :p "-1.0E7"^^xsd:double . + :s1 :p :o1 . + :s1 :p "abc" . + """; + + /** A negative double must not disappear from a DISTINCT over the object slot. */ + @Test + public void distinctObjectIncludesNegativeDouble() { + DatasetGraphTDB dsg = tdb2(DATA); + assertSkipScanAgrees(dsg, "SELECT DISTINCT ?o { ?s :p ?o }"); + } + + /** + * The same through a longer key prefix (SPO rather than POS). + * + *

Note that {@code SELECT DISTINCT ?p ?o { ?s ?p ?o }} does not show the defect: + * there the first ranged slot is the predicate, whose NodeId is below {@code NodeIdMax}, so + * the record sorts inside the range whatever the object is. The bound only cuts records + * short when the oversized NodeId sits in the first ranged slot.

+ */ + @Test + public void distinctObjectWithConstantSubject() { + DatasetGraphTDB dsg = tdb2(DATA); + assertSkipScanAgrees(dsg, "SELECT DISTINCT ?o { :s1 :p ?o }"); + } + + /** + * An all-0xFF key is the only safe upper bound, so the fix for this finding needs one - + * but {@link Record#incrementKey} throws on it, and + * {@code BPTreeDistinctKeyPrefixIterator} computes {@code incrementKey(maxRecord)} eagerly + * in its constructor. The range iterator must accept a maximal upper bound. + */ + @Test + public void rangeIteratorAcceptsMaximalUpperBound() { + RecordFactory factory = RecordLib.recordFactory; + BPlusTree bpt = BPlusTreeFactory.makeMem(2, 2, RecordLib.TestRecordLength, 0); + bpt.nonTransactional(); + for ( int i = 0; i < 20; i++ ) + bpt.insert(RecordLib.intToRecord(i)); + + byte[] allFF = new byte[RecordLib.TestRecordLength]; + Arrays.fill(allFF, (byte)0xFF); + Record min = factory.create(new byte[RecordLib.TestRecordLength]); + Record max = factory.create(allFF); + + assertDoesNotThrow(() -> bpt.distinctByKeyPrefix(1, min, max), + "An all-0xFF upper bound - the only correct maximum - is rejected"); + } +} diff --git a/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan_3995/Test06_RecordPadRightUpperBound.java b/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan_3995/Test06_RecordPadRightUpperBound.java new file mode 100644 index 00000000000..e605fc6c6ce --- /dev/null +++ b/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan_3995/Test06_RecordPadRightUpperBound.java @@ -0,0 +1,102 @@ +/* + * 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 + * + * https://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. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +package org.apache.jena.tdb2.solver.skipscan_3995; + +import static org.apache.jena.tdb2.solver.skipscan_3995.SkipScanTestLib.assertSkipScanAgrees; +import static org.apache.jena.tdb2.solver.skipscan_3995.SkipScanTestLib.tdb2; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.Arrays; + +import org.junit.jupiter.api.Test; + +import org.apache.jena.atlas.lib.Bytes; +import org.apache.jena.dboe.base.record.Record; +import org.apache.jena.dboe.base.record.RecordFactory; +import org.apache.jena.tdb2.store.DatasetGraphTDB; + +/** + * Finding 6 - {@code Record:211}. + * + *
{@code
+ * private static byte[] padRight(byte[] arr, int length) {
+ *     if ( length == arr.length )      return arr;
+ *     else if ( length < arr.length )  return Arrays.copyOf(arr, arr.length);
+ *     return Arrays.copyOf(arr, length);
+ * }
+ * }
+ *

Zero-padding is right for a lower bound and wrong for an upper bound, and + * {@code BPTreeDistinctKeyPrefixIterator.create} uses the one method for both:

+ *
{@code
+ * Record paddedMinRecord = Record.padRight(minRecord, nodeMinRecord);
+ * Record paddedMaxRecord = Record.padRight(maxRecord, nodeMaxRecord);
+ * }
+ */ +public class Test06_RecordPadRightUpperBound { + + private static final String DATA = """ + :s1 :p :o1 . + :s1 :p :o2 . + :s2 :p2 :o3 . + """; + + /** + * A padded upper bound must still bound every record that shares its prefix. + * Zero-padding produces the smallest such record instead of the largest. + */ + @Test + public void paddedUpperBoundStillBounds() { + RecordFactory factory = new RecordFactory(3, 0); + Record prototype = factory.create(new byte[] {0, 0, 0}); + + Record partialMax = new Record(new byte[] {0x05}, null); + Record paddedMax = Record.padRight(partialMax, prototype, (byte)0xff); + + // A stored record with the same leading byte: it must not sort above the upper bound. + Record stored = factory.create(new byte[] {0x05, 0x00, 0x7F}); + + assertTrue(Arrays.compareUnsigned(paddedMax.getKey(), stored.getKey()) >= 0, + () -> "Padding an upper bound with zeros excludes records inside the range." + + "\n Upper bound: " + Bytes.asHex(paddedMax.getKey()) + + "\n Stored: " + Bytes.asHex(stored.getKey())); + } + + /** "If no padding is needed then record is returned" - but a shorter prototype forces a copy. */ + @Test + public void noPaddingNeededReturnsTheSameRecord() { + Record record = new RecordFactory(3, 0).create(new byte[] {1, 2, 3}); + Record shorterPrototype = new RecordFactory(1, 0).create(new byte[] {0}); + assertSame(record, Record.padRight(record, shorterPrototype, (byte)0xff), + "padRight created a new Record although no padding was needed"); + } + + /** + * End to end: every needed slot is a constant, so the skip scan builds a 1-slot range over a + * 3-slot key. The zero-padded upper bound makes the range empty. + */ + @Test + public void distinctWithConstantSubjectOnly() { + DatasetGraphTDB dsg = tdb2(DATA); + assertSkipScanAgrees(dsg, "SELECT DISTINCT ?zz { :s1 ?p ?o }"); + } +} diff --git a/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan_3995/Test08_PatternQueryCacheKey.java b/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan_3995/Test08_PatternQueryCacheKey.java new file mode 100644 index 00000000000..37a017fbd32 --- /dev/null +++ b/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan_3995/Test08_PatternQueryCacheKey.java @@ -0,0 +1,89 @@ +/* + * 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 + * + * https://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. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +package org.apache.jena.tdb2.solver.skipscan_3995; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.jupiter.api.Test; + +import org.apache.jena.graph.Node; +import org.apache.jena.graph.NodeFactory; +import org.apache.jena.sparql.core.Var; +import org.apache.jena.tdb2.solver.skipscan.PatternQuery; + +/** + * Finding 8 - {@code PatternQuery:59}. + * + *
{@code
+ * public record PatternQuery(boolean distinct, List project, Node[] tuple) { ... }
+ * }
+ *

A record with an array component gets array-identity {@code equals} and {@code hashCode}, + * so the index cache keyed on it - {@code Map}, keyed by + * {@code PatternQuery.toCacheKey(subst)} - never hits. {@code findBestCandidate} (which + * enumerates every index) runs again for every input binding, and the cache in the execution + * context grows by one entry per binding and is never evicted.

+ */ +public class Test08_PatternQueryCacheKey { + + private static final Node p = NodeFactory.createURI("http://example/p"); + + private static PatternQuery patternQuery() { + Node[] tuple = new Node[] {Var.alloc("s"), p, Var.alloc("o")}; + return new PatternQuery(true, List.of(Var.alloc("s")), tuple); + } + + /** Two PatternQuery values with the same contents must be equal. */ + @Test + public void equalContentsAreEqual() { + PatternQuery a = patternQuery(); + PatternQuery b = patternQuery(); + assertEquals(a, b, "PatternQuery uses array identity for its tuple component"); + assertEquals(a.hashCode(), b.hashCode(), "PatternQuery hashCode uses array identity"); + } + + /** {@code toCacheKey} exists to canonicalise a pattern, so its results must be equal. */ + @Test + public void cacheKeysAreEqual() { + PatternQuery pq = patternQuery(); + PatternQuery k1 = PatternQuery.toCacheKey(pq); + PatternQuery k2 = PatternQuery.toCacheKey(pq); + assertEquals(k1, k2, "toCacheKey does not produce equal keys for the same pattern"); + assertEquals(k1.hashCode(), k2.hashCode(), "toCacheKey does not produce equal hash codes"); + } + + /** What the cache actually needs: a second lookup with an equal key must hit. */ + @Test + public void cacheHits() { + Object candidate = new Object(); + Map cache = new HashMap<>(); + cache.put(PatternQuery.toCacheKey(patternQuery()), candidate); + + assertSame(candidate, cache.get(PatternQuery.toCacheKey(patternQuery())), + "The index cache never hits, so the best index is re-planned for every input binding"); + assertEquals(1, cache.size()); + } +} diff --git a/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan_3995/Test11_KeyPrefixLengthValidation.java b/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan_3995/Test11_KeyPrefixLengthValidation.java new file mode 100644 index 00000000000..1d5a716983b --- /dev/null +++ b/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan_3995/Test11_KeyPrefixLengthValidation.java @@ -0,0 +1,98 @@ +/* + * 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 + * + * https://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. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +package org.apache.jena.tdb2.solver.skipscan_3995; + +import static org.apache.jena.tdb2.solver.skipscan_3995.SkipScanTestLib.assertSkipScanAgrees; +import static org.apache.jena.tdb2.solver.skipscan_3995.SkipScanTestLib.tdb2; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import org.apache.jena.dboe.base.record.Record; +import org.apache.jena.dboe.test.RecordLib; +import org.apache.jena.dboe.trans.bplustree.BPlusTree; +import org.apache.jena.dboe.trans.bplustree.BPlusTreeFactory; +import org.apache.jena.tdb2.store.DatasetGraphTDB; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Finding 11 - {@code BPTreeDistinctKeyPrefixIterator:61}. + * + *

The 2-argument {@code create} validates the prefix length:

+ *
{@code
+ * if ( keyPrefixLength < 1 )
+ *     throw new IllegalArgumentException("keyPrefixLength must be >= 1");
+ * else if ( keyPrefixLength > node.params.recordFactory.keyLength() )
+ *     throw new IllegalArgumentException(...);
+ * }
+ *

The new 4-argument overload added by this PR drops both checks. With a length of 0 every + * {@code Arrays.compare} over the prefix returns 0, so {@code haveSamePrefix} and + * {@code comparePrefix} are vacuously true; with a length beyond the key, the comparisons read + * past the prefix.

+ * + *

See {@link #distinctWithNoProjectedVariables()}: the skip scan executor really does pass 0, + * so this validation and the caller have to be fixed together.

+ */ +public class Test11_KeyPrefixLengthValidation { + + private static BPlusTree tree() { + BPlusTree bpt = BPlusTreeFactory.makeMem(2, 2, RecordLib.TestRecordLength, 0); + bpt.nonTransactional(); + for ( int i = 0; i < 20; i++ ) + bpt.insert(RecordLib.intToRecord(i)); + return bpt; + } + + @Test + @Disabled("A range of 0 should gracefully match all records.") + public void prefixLengthZeroIsRejected() { + BPlusTree bpt = tree(); + Record min = RecordLib.intToRecord(0); + Record max = RecordLib.intToRecord(19); + assertThrows(IllegalArgumentException.class, () -> bpt.distinctByKeyPrefix(0, min, max), + "The ranged overload accepts a prefix length of 0"); + } + + @Test + public void prefixLengthBeyondTheKeyIsRejected() { + BPlusTree bpt = tree(); + Record min = RecordLib.intToRecord(0); + Record max = RecordLib.intToRecord(19); + assertThrows(IllegalArgumentException.class, + () -> bpt.distinctByKeyPrefix(RecordLib.TestRecordLength + 1, min, max), + "The ranged overload accepts a prefix length beyond the key length"); + } + + /** + * {@code SELECT DISTINCT ?zz { ?s ?p ?o }} has no needed slots, so the executor calls + * {@code bpt.distinctByKeyPrefix(0, min, max)}. It currently returns the right answer only + * because a zero-length prefix makes every comparison vacuously true. This test passes today + * and guards the degenerate case once the validation above is restored. + */ + @Test + public void distinctWithNoProjectedVariables() { + DatasetGraphTDB dsg = tdb2(""" + :s1 :p :o1 . + :s1 :p :o2 . + """); + assertSkipScanAgrees(dsg, "SELECT DISTINCT ?zz { ?s ?p ?o }"); + } +} diff --git a/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan_3995/Test12_PrefixIteratorRange.java b/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan_3995/Test12_PrefixIteratorRange.java new file mode 100644 index 00000000000..dd03c289b1e --- /dev/null +++ b/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan_3995/Test12_PrefixIteratorRange.java @@ -0,0 +1,164 @@ +/* + * 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 + * + * https://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. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +package org.apache.jena.tdb2.solver.skipscan_3995; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; + +import org.apache.jena.atlas.lib.Bytes; +import org.apache.jena.dboe.base.record.Record; +import org.apache.jena.dboe.test.RecordLib; +import org.apache.jena.dboe.trans.bplustree.BPlusTree; +import org.apache.jena.dboe.trans.bplustree.BPlusTreeFactory; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Finding 12 - {@code BPTreeDistinctKeyPrefixIterator}: the ranged iterator yields records + * outside the requested range. + * + *

Two short-circuits return a page's or subtree's lowest record without checking it against + * the range. {@code moveOnCurrent:158} has no check at all:

+ *
{@code
+ * if ( haveSamePrefix(subtreeMin, subtreeMax) )
+ *     return Iter.singletonIterator(subtreeMin);
+ * }
+ *

and the check this PR added at {@code getRecordsIterator:190} compares prefixes, + * not records:

+ *
{@code
+ * if ( comparePrefix(lowRecord, minRecord) >= 0 && comparePrefix(highRecord, maxRecord) <= 0 )
+ *     iter = Iter.singletonIterator(lowRecord);
+ * }
+ *

so when {@code lowRecord} and {@code minRecord} share a prefix - exactly the case this + * shortcut is for - a record below the lower bound passes the test and is emitted. See + * {@link #singletonPageShortcutRespectsLowerBound()} for the three-line case.

+ * + *

{@link #rangedDistinctByPrefix()} is a whole-contract sweep rather than one tree shape: + * over many sub-ranges it requires exactly one record per distinct key prefix, each inside the + * requested range. The keys are laid out so that many records share a 3-byte prefix, which is + * what produces the uniform-prefix leaf pages and subtrees both shortcuts trigger on, and the + * range boundaries fall inside such a group.

+ */ +public class Test12_PrefixIteratorRange { + + /** Keys {@code [0, 0, group, member]}: every group of members shares a 3-byte prefix. */ + private static final int GROUPS = 40; + private static final int MEMBERS = 24; + + private static List keys() { + List keys = new ArrayList<>(); + for ( int group = 0; group < GROUPS; group++ ) { + for ( int member = 0; member < MEMBERS; member++ ) + keys.add((group << 8) | member); + } + return keys; + } + + private static byte[] prefixOf(int key, int prefixLength) { + return Arrays.copyOf(Bytes.packInt(key), prefixLength); + } + + /** + * The smallest case: every record shares one 3-byte prefix, and the range starts one past + * the lowest. The single record returned must be inside the range. + */ + @Test + @Disabled("Test seems invalid: Records are only compared by the first n bytes, where n is the prefix length.") + public void singletonPageShortcutRespectsLowerBound() { + BPlusTree bpt = BPlusTreeFactory.makeMem(2, 2, RecordLib.TestRecordLength, 0); + bpt.nonTransactional(); + for ( int key = 0; key <= 5; key++ ) + bpt.insert(RecordLib.intToRecord(key)); + + Iterator iter = bpt.distinctByKeyPrefix(3, RecordLib.intToRecord(1), RecordLib.intToRecord(5)); + List actual = new ArrayList<>(); + while ( iter.hasNext() ) + actual.add(RecordLib.recordToInt(iter.next())); + + assertEquals(List.of(1), actual, + "The ranged iterator returned a record below the lower bound"); + } + + @Test + @Disabled("Test seems invalid; only the first prefixLen bytes are used to compare the records of the bpt against the first prefixLen bytes of the query range [x, y[") + public void rangedDistinctByPrefix() { + List keys = keys(); + + for ( int order : new int[] {2, 3, 4} ) { + BPlusTree bpt = BPlusTreeFactory.makeMem(order, 2, RecordLib.TestRecordLength, 0); + bpt.nonTransactional(); + for ( int key : keys ) + bpt.insert(RecordLib.intToRecord(key)); + + for ( int prefixLength : new int[] {3, 4} ) { + // Range boundaries on group boundaries and inside groups. + for ( int fromGroup = 0; fromGroup < GROUPS; fromGroup += 7 ) { + for ( int offset : new int[] {0, 1, MEMBERS / 2, MEMBERS - 1} ) { + int from = (fromGroup << 8) | offset; + int to = ((fromGroup + 5) << 8) | (MEMBERS - 1 - offset); + if ( to < from ) + continue; + check(bpt, order, prefixLength, keys, from, to); + } + } + } + } + } + + private static void check(BPlusTree bpt, int order, int prefixLength, List keys, int from, int to) { + List expected = new ArrayList<>(); + for ( int key : keys.stream().sorted().toList() ) { + if ( key < from || key > to ) + continue; + String prefix = Bytes.asHex(prefixOf(key, prefixLength)); + if ( expected.isEmpty() || !expected.get(expected.size() - 1).equals(prefix) ) + expected.add(prefix); + } + + List actual = new ArrayList<>(); + Record minInc = RecordLib.intToRecord(from); + Record maxExc = RecordLib.intToRecord(to); + Iterator iter = bpt.distinctByKeyPrefix(prefixLength, + minInc, + maxExc); + while ( iter.hasNext() ) { + Record record = iter.next(); + int key = RecordLib.recordToInt(record); + assertTrue(key >= from && key <= to, + () -> "Record outside the requested range" + + " [order=" + order + ", prefixLength=" + prefixLength + "]" + + "\n Range: [" + from + ", " + to + "]" + + "\n Record: " + key); + actual.add(Bytes.asHex(prefixOf(key, prefixLength))); + } + + assertEquals(expected, actual, + () -> "Wrong set of distinct prefixes" + + " [order=" + order + ", prefixLength=" + prefixLength + "]" + + "\n Range: [" + from + ", " + to + "]"); + } +} diff --git a/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan_3995/Test14_AddResourceObjectsAsSubjects.java b/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan_3995/Test14_AddResourceObjectsAsSubjects.java new file mode 100644 index 00000000000..dff61a6e2ba --- /dev/null +++ b/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan_3995/Test14_AddResourceObjectsAsSubjects.java @@ -0,0 +1,92 @@ +/* + * 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 + * + * https://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. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +package org.apache.jena.tdb2.solver.skipscan_3995; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.stream.Stream; + +import org.junit.jupiter.api.Test; + +import org.apache.jena.graph.Node; +import org.apache.jena.graph.NodeFactory; +import org.apache.jena.riot.Lang; +import org.apache.jena.riot.RDFParser; +import org.apache.jena.sparql.core.DatasetGraph; +import org.apache.jena.sparql.core.DatasetGraphFactory; +import org.apache.jena.sparql.core.Quad; +import org.apache.jena.tdb2.solver.skipscan.TestOpExecutorTDB2SkipScan; +import org.apache.jena.vocabulary.RDF; +import org.apache.jena.vocabulary.RDFS; + +/** + * Finding 14 - {@code TestOpExecutorTDB2SkipScan:138}. + * + *
{@code
+ * public static void addResourceObjectsAsSubjects(DatasetGraph referenceDsg) {
+ *     DatasetGraph dataDsg = DatasetGraphFactory.create();
+ *     dataDsg.addAll(referenceDsg);
+ *     ...
+ *     extra.forEach(dataDsg::add);      // the local copy, not the argument
+ * }
+ * }
+ *

Every write goes to a fresh local dataset that is dropped on return, so the method - named + * and documented as an "in-place addition" and called for its effect on the argument - does + * nothing. The extra lookup shapes it exists to generate are never tested.

+ */ +public class Test14_AddResourceObjectsAsSubjects { + + @Test + public void argumentIsModifiedInPlace() { + DatasetGraph dsg = DatasetGraphFactory.create(); + RDFParser.fromString(""" + PREFIX : + :s1 :p :o1 . + :s1 :p :o2 . + """, Lang.TRIG).parse(dsg); + + long before = count(dsg); + TestOpExecutorTDB2SkipScan.addResourceObjectsAsSubjects(dsg); + long after = count(dsg); + + assertTrue(after > before, + () -> "addResourceObjectsAsSubjects did not modify its argument" + + " (" + before + " quads before, " + after + " after)"); + + Node o1 = NodeFactory.createURI("http://example/o1"); + assertTrue(hasQuad(dsg, o1), "The object :o1 was not added as a subject"); + } + + private static long count(DatasetGraph dsg) { + try ( Stream stream = dsg.stream() ) { + return stream.count(); + } + } + + private static boolean hasQuad(DatasetGraph dsg, Node subject) { + try ( Stream stream = dsg.stream() ) { + return stream.anyMatch(q -> subject.equals(q.getSubject()) + && RDF.Nodes.type.equals(q.getPredicate()) + && RDFS.Nodes.Resource.equals(q.getObject())); + } + } +} diff --git a/jena-tdb2/src/test/java/org/apache/jena/tdb2/store/Test_SPARQL_TDB.java b/jena-tdb2/src/test/java/org/apache/jena/tdb2/store/Test_SPARQL_TDB.java index 9d6927acaee..cb0a6e27049 100644 --- a/jena-tdb2/src/test/java/org/apache/jena/tdb2/store/Test_SPARQL_TDB.java +++ b/jena-tdb2/src/test/java/org/apache/jena/tdb2/store/Test_SPARQL_TDB.java @@ -21,6 +21,8 @@ package org.apache.jena.tdb2.store; +import static org.apache.jena.tdb2.solver.skipscan_3995.SkipScanTestLib.rows; +import static org.apache.jena.tdb2.solver.skipscan_3995.SkipScanTestLib.tdb2; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; @@ -230,8 +232,12 @@ public void sparql10() { BIND(rand() AS ?x) } """).table()); + // 0 rows are always be unexpected. + int numRows = actualTable.size(); + assertNotEquals(numRows, 0); + // Extremely unlikely that rand() would return the same value n times! - assertNotEquals(actualTable.size(), 1); + assertNotEquals(numRows, 1); } private static void add(Dataset dataset, String graphName, Triple triple) { From 2d940c590714cf582b3e29b2e39f96b3cca5250a Mon Sep 17 00:00:00 2001 From: Claus Stadler Date: Fri, 23 Oct 2026 14:43:42 +0200 Subject: [PATCH 3/3] Added further bug fixes found by Codex Astra/mid --- .../BPTreeDistinctKeyPrefixIterator.java | 57 ++--- .../jena/dboe/trans/bplustree/BPlusTree.java | 6 + .../jena/tdb2/solver/skipscan/IndexMatch.java | 8 +- .../skipscan/OpExecutorTDB2SkipScan.java | 33 ++- .../tdb2/solver/skipscan/OpExtSkipScan.java | 2 +- .../skipscan/Test10_RemapValueConditions.java | 7 +- .../Test13_OpExtSkipScanContract.java | 11 + .../Test03_CacheKeySubstitution.java | 32 ++- .../Test12_PrefixIteratorRange.java | 207 +++++++++--------- 9 files changed, 201 insertions(+), 162 deletions(-) diff --git a/jena-db/jena-dboe-trans-data/src/main/java/org/apache/jena/dboe/trans/bplustree/BPTreeDistinctKeyPrefixIterator.java b/jena-db/jena-dboe-trans-data/src/main/java/org/apache/jena/dboe/trans/bplustree/BPTreeDistinctKeyPrefixIterator.java index e369a5ca057..73c87aed2ba 100644 --- a/jena-db/jena-dboe-trans-data/src/main/java/org/apache/jena/dboe/trans/bplustree/BPTreeDistinctKeyPrefixIterator.java +++ b/jena-db/jena-dboe-trans-data/src/main/java/org/apache/jena/dboe/trans/bplustree/BPTreeDistinctKeyPrefixIterator.java @@ -41,44 +41,51 @@ public static Iterator create(BPTreeNode node, int keyPrefixLength) { } /** - * Create an iterator of distinct keys over a custom sub-range. - * The minimum and maximum records may be null to match all records w.r.t. the given keyPrefixLength. - * Note that a keyPrefixLength of 0 on a non-empty BPTreeNode will return only the first node - - * as all other nodes are considered equal to it by the zero-length prefix. + * Iterate distinct key prefixes in the half-open range [min, max). + * Only the first keyPrefixLength bytes of either bound are significant; each + * bound must contain at least that many bytes. Null denotes an unbounded end. + * A zero-length prefix represents a single distinct value on a non-empty tree. */ public static Iterator create(BPTreeNode node, int keyPrefixLength, Record minRecordInclusive, Record maxRecordExclusive) { - if (keyPrefixLength > node.params.recordFactory.keyLength()) { - throw new IllegalArgumentException( - "Maximum keyPrefixLength for this B+Tree is " + node.params.recordFactory.keyLength()); + int keyLength = node.params.recordFactory.keyLength(); + if (keyPrefixLength < 0 || keyPrefixLength > keyLength) { + throw new IllegalArgumentException("keyPrefixLength must be between 0 and " + keyLength); + } + + // Tree traversal and record-buffer scans compare whole keys. Map prefix + // bounds to the first full key of each prefix, including the exclusive max. + Record min = normalizeBound(minRecordInclusive, keyPrefixLength, keyLength); + Record max = normalizeBound(maxRecordExclusive, keyPrefixLength, keyLength); + if (min != null && max != null && Record.keyGE(min, max)) { + return Iter.nullIter(); } Record nodeMinRecord = node.minRecord(); Record nodeMaxRecord = node.maxRecord(); - // If there's no records just return a null iterator if (nodeMinRecord == null) { return Iter.nullIter(); } - // If there's only a single distinct prefix then just return a singleton if (haveSamePrefix(nodeMinRecord, nodeMaxRecord, keyPrefixLength)) { - if (isPrefixInRequestRange(nodeMinRecord, keyPrefixLength, minRecordInclusive, maxRecordExclusive)) { - return Iter.singletonIterator(nodeMinRecord); - } else { - return Iter.nullIter(); - } + return isPrefixInRequestRange(nodeMinRecord, keyPrefixLength, min, max) + ? Iter.singletonIterator(nodeMinRecord) : Iter.nullIter(); } - // Pad records to make their lengths match those of the nodes. - // Also, the down-stream machinery expects paddedMinRecord to be non-null. - Record paddedMinRecord; - if (minRecordInclusive == null) { - paddedMinRecord = nodeMinRecord; - } else { - paddedMinRecord = Record.padRight(minRecordInclusive, nodeMinRecord, (byte)0x00); - } - Record paddedMaxRecord = maxRecordExclusive == null ? null : Record.padRight(maxRecordExclusive, nodeMaxRecord, (byte)0xff); + // The downstream search requires a non-null lower bound. + return new BPTreeDistinctKeyPrefixIterator(node, keyPrefixLength, + min == null ? nodeMinRecord : min, max); + } - return new BPTreeDistinctKeyPrefixIterator(node, keyPrefixLength, paddedMinRecord, paddedMaxRecord); + private static Record normalizeBound(Record bound, int keyPrefixLength, int keyLength) { + if (bound == null) { + return null; + } + if (bound.getKey().length < keyPrefixLength) { + throw new IllegalArgumentException("Range bound is shorter than keyPrefixLength"); + } + byte[] key = new byte[keyLength]; + System.arraycopy(bound.getKey(), 0, key, 0, keyPrefixLength); + return new Record(key, null); } // Convert path to a stack of iterators @@ -229,7 +236,7 @@ private BPTreeRecords loadStack(BPTreeNode node) { List steps = path.getPath(); for (AccessStep step : steps) { BPTreeNode n = step.node; - Iterator it = n.iterator(minRecordInclusive, maxRecordExclusive); //this.maxRecordInclusive); + Iterator it = n.iterator(minRecordInclusive, maxRecordExclusive); if (it == null || !it.hasNext()) { continue; } diff --git a/jena-db/jena-dboe-trans-data/src/main/java/org/apache/jena/dboe/trans/bplustree/BPlusTree.java b/jena-db/jena-dboe-trans-data/src/main/java/org/apache/jena/dboe/trans/bplustree/BPlusTree.java index ca5b1d29a7d..f855e5364ea 100644 --- a/jena-db/jena-dboe-trans-data/src/main/java/org/apache/jena/dboe/trans/bplustree/BPlusTree.java +++ b/jena-db/jena-dboe-trans-data/src/main/java/org/apache/jena/dboe/trans/bplustree/BPlusTree.java @@ -325,6 +325,12 @@ public Iterator distinctByKeyPrefix(int keyPrefixLength) { return distinctByKeyPrefix(keyPrefixLength, null, null); } + /** + * Return one record per distinct prefix in [fromRecInclusive, toRecExclusive). + * Only the first keyPrefixLength bytes of each bound are significant; bounds + * must contain at least that many bytes. Null bounds are unbounded. Prefix + * lengths from zero through the full key length are supported. + */ public Iterator distinctByKeyPrefix(int keyPrefixLength, Record fromRecInclusive, Record toRecExclusive) { startReadBlkMgr(); BPTreeNode root = getRootRead(); diff --git a/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/IndexMatch.java b/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/IndexMatch.java index 8868ebed422..6a5d7ac4718 100644 --- a/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/IndexMatch.java +++ b/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/IndexMatch.java @@ -23,12 +23,10 @@ import java.util.Comparator; -import org.apache.jena.graph.Node; - record IndexMatch( boolean canDoDirectDistinct, - /** Residual conditions are in index space, so (idx=1) w.r.t. a POS index refers to the O slot. */ - ValueFilter[] residualConditions, + /** Index-space columns to filter; values come from the current query, not the cached plan. */ + int[] residualColumns, int keyLen, int valLen) { @@ -37,7 +35,7 @@ public int numNeededSlots() { } public int numResidualConditions() { - return (residualConditions == null) ? 0 : residualConditions.length; + return (residualColumns == null) ? 0 : residualColumns.length; } public static final Comparator COMPARATOR = Comparator.nullsLast(Comparator diff --git a/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/OpExecutorTDB2SkipScan.java b/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/OpExecutorTDB2SkipScan.java index f552225076b..11ae152c6bf 100644 --- a/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/OpExecutorTDB2SkipScan.java +++ b/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/OpExecutorTDB2SkipScan.java @@ -201,7 +201,6 @@ public static QueryIterator tryExec(NodeTupleTable nodeTupleTable, boolean disti } /** Must only be called if hasNeededColumns returned true. */ - @SuppressWarnings("unchecked") public static IndexMatch computeIndexMatch(TupleMap tm, TuplePatternSpec patternSpec) { Node[] quad = patternSpec.tuple(); boolean canDoDirectDistinct = true; @@ -210,7 +209,7 @@ public static IndexMatch computeIndexMatch(TupleMap tm, TuplePatternSpec pattern // Start with marking all slots as not-covered. int uncoveredSlotsMask = patternSpec.neededSlotsMask(); - ValueFilter[] residualConditions = null; + int[] residualColumns = null; int numResidualConditions = 0; int i; @@ -251,12 +250,12 @@ public static IndexMatch computeIndexMatch(TupleMap tm, TuplePatternSpec pattern canDoDirectDistinct = false; } } else { - if (residualConditions == null) { - residualConditions = new ValueFilter[idxLen - j]; + if (residualColumns == null) { + residualColumns = new int[idxLen - j]; } - // Add the constant node as a filter condition. - residualConditions[numResidualConditions++] = new ValueFilter<>(j, node); + // Cache only the column; the constant may differ on the next cache hit. + residualColumns[numResidualConditions++] = j; // The residual condition on the index column (j) effectively covers the corresponding slot. uncoveredSlotsMask &= ~(1 << tupleSlot); @@ -268,12 +267,12 @@ public static IndexMatch computeIndexMatch(TupleMap tm, TuplePatternSpec pattern return null; } - // If there were residual conditions then strip trailing null values. - if (residualConditions != null && residualConditions.length != numResidualConditions) { - residualConditions = Arrays.copyOf(residualConditions, numResidualConditions); + // Trim unused residual-column capacity. + if (residualColumns != null && residualColumns.length != numResidualConditions) { + residualColumns = Arrays.copyOf(residualColumns, numResidualConditions); } - return new IndexMatch(canDoDirectDistinct, residualConditions, keyLen, valLen); + return new IndexMatch(canDoDirectDistinct, residualColumns, keyLen, valLen); } /** Resolve the {@link NodeTupleTable} for a pattern of the given tuple length. */ @@ -517,7 +516,7 @@ public static IndexMap tryComputeIndexMap(TuplePatternSpec lookup, IndexMatch ma EqualityLink[] mappedLinks = null; if (match.numResidualConditions() > 0) { - mappedConditions = remapValueConditions(match.residualConditions(), tm, nodeTable); + mappedConditions = remapValueConditions(match.residualColumns(), nodeTuple, nodeTable); // If mappedConditions is null then some nodes could not be mapped if (mappedConditions == null) { @@ -574,18 +573,16 @@ public static EqualityLink[] remapEqualityLinks(EqualityLink[] links, TupleMap t } /** - * Remap indices w.r.t. the tupleMap and map Nodes to NodeIds. + * Bind cached index-space columns to values from the current index-ordered tuple. * Returns null if any condition could not be mapped. */ - public static ValueFilter[] remapValueConditions(ValueFilter[] conditions, TupleMap tupleMap, NodeTable nodeTable) { - int n = conditions.length; + public static ValueFilter[] remapValueConditions(int[] columns, Node[] nodeTuple, NodeTable nodeTable) { + int n = columns.length; @SuppressWarnings("unchecked") ValueFilter[] result = new ValueFilter[n]; for (int i = 0; i < n; ++i) { - ValueFilter condition = conditions[i]; - // int slot = tupleMap.unmapIdx(condition.idx()); - int idx = condition.idx(); - NodeId nodeId = nodeTable.getNodeIdForNode(condition.value()); + int idx = columns[i]; + NodeId nodeId = nodeTable.getNodeIdForNode(nodeTuple[idx]); if (NodeId.isDoesNotExist(nodeId)) { return null; } diff --git a/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/OpExtSkipScan.java b/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/OpExtSkipScan.java index d721d501dea..16328117360 100644 --- a/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/OpExtSkipScan.java +++ b/jena-tdb2/src/main/java/org/apache/jena/tdb2/solver/skipscan/OpExtSkipScan.java @@ -83,7 +83,7 @@ public void outputArgs(IndentedWriter out, SerializationContext sCxt) { @Override public int hashCode() { - return 31 * patternQuery.hashCode(); + return effectiveOp().hashCode(); } @Override diff --git a/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan/Test10_RemapValueConditions.java b/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan/Test10_RemapValueConditions.java index e62cf996371..366375cd616 100644 --- a/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan/Test10_RemapValueConditions.java +++ b/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan/Test10_RemapValueConditions.java @@ -75,9 +75,8 @@ public void columnIsNotRemapped() { for ( TupleIndex index : tripleTable(dsg).getTupleTable().getIndexes() ) { TupleMap tupleMap = index.getMapping(); for ( int column = 0; column < tupleMap.length(); column++ ) { - @SuppressWarnings("unchecked") ValueFilter[] mapped = OpExecutorTDB2SkipScan.remapValueConditions( - new ValueFilter[] {new ValueFilter<>(column, o1)}, tupleMap, nodeTable); + new int[] {column}, new Node[] {o1, o1, o1}, nodeTable); assertNotNull(mapped); final int expected = column; assertEquals(expected, mapped[0].idx(), @@ -94,12 +93,10 @@ public void unknownConstantGivesNull() { DatasetGraphTDB dsg = tdb2(DATA); NodeTable nodeTable = tripleTable(dsg).getNodeTable(); Node absent = NodeFactory.createURI("http://example/not-in-the-database"); - TupleMap tupleMap = tripleTable(dsg).getTupleTable().getIndexes()[0].getMapping(); Txn.executeRead(dsg, () -> { - @SuppressWarnings("unchecked") ValueFilter[] mapped = OpExecutorTDB2SkipScan.remapValueConditions( - new ValueFilter[] {new ValueFilter<>(0, absent)}, tupleMap, nodeTable); + new int[] {0}, new Node[] {absent}, nodeTable); assertNull(mapped, "remapValueConditions must return null for a constant with no NodeId; " + "getNodeIdForNode returns NodeId.NodeDoesNotExist, never null"); diff --git a/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan/Test13_OpExtSkipScanContract.java b/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan/Test13_OpExtSkipScanContract.java index 554af9f0944..2410c12299c 100644 --- a/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan/Test13_OpExtSkipScanContract.java +++ b/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan/Test13_OpExtSkipScanContract.java @@ -79,4 +79,15 @@ public void opExecutorSymbolIsNamespaced() { () -> "The OpExecutor is stored under an un-namespaced context symbol: " + symbol.getSymbol()); } + @Test + public void equivalentEffectiveProjectionsHaveEqualHashes() { + var s = Var.alloc("s"); + var o = Var.alloc("o"); + Node[] tuple = {s, p, o}; + var a = new OpExtSkipScan(new PatternQuery(true, List.of(s, o), tuple)); + var b = new OpExtSkipScan(new PatternQuery(true, List.of(o, s), tuple)); + assertTrue(a.equalTo(b, new NodeIsomorphismMap())); + assertEquals(a.hashCode(), b.hashCode()); + assertEquals(1, new java.util.HashSet<>(List.of(a, b)).size()); + } } diff --git a/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan_3995/Test03_CacheKeySubstitution.java b/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan_3995/Test03_CacheKeySubstitution.java index 88b1a2c40cf..aaf02c08e27 100644 --- a/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan_3995/Test03_CacheKeySubstitution.java +++ b/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan_3995/Test03_CacheKeySubstitution.java @@ -24,9 +24,15 @@ import static org.apache.jena.tdb2.solver.skipscan_3995.SkipScanTestLib.assertSkipScanAgrees; import static org.apache.jena.tdb2.solver.skipscan_3995.SkipScanTestLib.tdb2; -import org.junit.jupiter.api.Test; - +import org.apache.jena.dboe.base.file.Location; +import org.apache.jena.riot.Lang; +import org.apache.jena.riot.RDFParser; +import org.apache.jena.sparql.engine.optimizer.reorder.ReorderLib; +import org.apache.jena.system.Txn; +import org.apache.jena.tdb2.params.StoreParams; import org.apache.jena.tdb2.store.DatasetGraphTDB; +import org.apache.jena.tdb2.store.TDB2StorageBuilder; +import org.junit.jupiter.api.Test; /** * Finding 3 - {@code OpExecutorTDB2SkipScan:138}. @@ -74,4 +80,26 @@ public void substitutedSubject() { SELECT * { VALUES ?s { :s1 :s2 } { SELECT DISTINCT ?s ?p { ?s ?p ?o } } } """); } + @Test + public void cachedResidualColumnsUseCurrentConstants() { + var params = StoreParams.builder("residual-cache-test") + .tripleIndexes(new String[] {"SPO", "OSP"}).build(); + var dsg = TDB2StorageBuilder.build( + Location.mem(), params, + ReorderLib.identity()); + try { + Txn.executeWrite(dsg, () -> RDFParser.fromString( + SkipScanTestLib.PREFIXES + ":s1 :p1 :o1 . :s2 :p2 :o2 .", + Lang.TRIG).parse(dsg)); + assertSkipScanAgrees(dsg, """ + SELECT * { + { SELECT DISTINCT ?s { ?s :p1 ?o } } + UNION { SELECT DISTINCT ?s { ?s :p2 ?o } } + UNION { SELECT DISTINCT ?s { ?s :absent ?o } } + } + """); + } finally { + dsg.close(); + } + } } diff --git a/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan_3995/Test12_PrefixIteratorRange.java b/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan_3995/Test12_PrefixIteratorRange.java index dd03c289b1e..6de138c3b21 100644 --- a/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan_3995/Test12_PrefixIteratorRange.java +++ b/jena-tdb2/src/test/java/org/apache/jena/tdb2/solver/skipscan_3995/Test12_PrefixIteratorRange.java @@ -22,143 +22,138 @@ package org.apache.jena.tdb2.solver.skipscan_3995; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.apache.jena.tdb2.solver.skipscan_3995.SkipScanTestLib.assertSkipScanAgrees; +import static org.apache.jena.tdb2.solver.skipscan_3995.SkipScanTestLib.tdb2; import java.util.ArrayList; import java.util.Arrays; -import java.util.Iterator; import java.util.List; import org.apache.jena.atlas.lib.Bytes; import org.apache.jena.dboe.base.record.Record; -import org.apache.jena.dboe.test.RecordLib; +import org.apache.jena.dboe.base.record.RecordFactory; import org.apache.jena.dboe.trans.bplustree.BPlusTree; import org.apache.jena.dboe.trans.bplustree.BPlusTreeFactory; -import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; -/** - * Finding 12 - {@code BPTreeDistinctKeyPrefixIterator}: the ranged iterator yields records - * outside the requested range. - * - *

Two short-circuits return a page's or subtree's lowest record without checking it against - * the range. {@code moveOnCurrent:158} has no check at all:

- *
{@code
- * if ( haveSamePrefix(subtreeMin, subtreeMax) )
- *     return Iter.singletonIterator(subtreeMin);
- * }
- *

and the check this PR added at {@code getRecordsIterator:190} compares prefixes, - * not records:

- *
{@code
- * if ( comparePrefix(lowRecord, minRecord) >= 0 && comparePrefix(highRecord, maxRecord) <= 0 )
- *     iter = Iter.singletonIterator(lowRecord);
- * }
- *

so when {@code lowRecord} and {@code minRecord} share a prefix - exactly the case this - * shortcut is for - a record below the lower bound passes the test and is emitted. See - * {@link #singletonPageShortcutRespectsLowerBound()} for the three-line case.

- * - *

{@link #rangedDistinctByPrefix()} is a whole-contract sweep rather than one tree shape: - * over many sub-ranges it requires exactly one record per distinct key prefix, each inside the - * requested range. The keys are laid out so that many records share a 3-byte prefix, which is - * what produces the uniform-prefix leaf pages and subtrees both shortcuts trigger on, and the - * range boundaries fall inside such a group.

- */ +/** Half-open prefix ranges must agree across shortcuts, traversal and leaf scans. */ public class Test12_PrefixIteratorRange { + private static final RecordFactory RF = new RecordFactory(4, 0); - /** Keys {@code [0, 0, group, member]}: every group of members shares a 3-byte prefix. */ - private static final int GROUPS = 40; - private static final int MEMBERS = 24; + private static Record record(int key) { + return RF.create(Bytes.packInt(key)); + } - private static List keys() { - List keys = new ArrayList<>(); - for ( int group = 0; group < GROUPS; group++ ) { - for ( int member = 0; member < MEMBERS; member++ ) - keys.add((group << 8) | member); - } - return keys; + private static BPlusTree tree(int order, List keys) { + BPlusTree tree = BPlusTreeFactory.makeMem(order, 2, 4, 0); + tree.nonTransactional(); + keys.forEach(k -> tree.insert(record(k))); + return tree; } - private static byte[] prefixOf(int key, int prefixLength) { - return Arrays.copyOf(Bytes.packInt(key), prefixLength); + private static List prefixes(BPlusTree tree, int length, Record min, Record max) { + List result = new ArrayList<>(); + tree.distinctByKeyPrefix(length, min, max).forEachRemaining(r -> { + byte[] prefix = new byte[4]; + System.arraycopy(r.getKey(), 0, prefix, 0, length); + result.add(Bytes.getInt(prefix)); + }); + return result; } - /** - * The smallest case: every record shares one 3-byte prefix, and the range starts one past - * the lowest. The single record returned must be inside the range. - */ @Test - @Disabled("Test seems invalid: Records are only compared by the first n bytes, where n is the prefix length.") - public void singletonPageShortcutRespectsLowerBound() { - BPlusTree bpt = BPlusTreeFactory.makeMem(2, 2, RecordLib.TestRecordLength, 0); - bpt.nonTransactional(); - for ( int key = 0; key <= 5; key++ ) - bpt.insert(RecordLib.intToRecord(key)); - - Iterator iter = bpt.distinctByKeyPrefix(3, RecordLib.intToRecord(1), RecordLib.intToRecord(5)); - List actual = new ArrayList<>(); - while ( iter.hasNext() ) - actual.add(RecordLib.recordToInt(iter.next())); - - assertEquals(List.of(1), actual, - "The ranged iterator returned a record below the lower bound"); + public void exclusiveShortUpperBound() { + BPlusTree tree = tree(4, List.of(0, 256)); + assertEquals(List.of(0), prefixes(tree, 3, + RF.create(new byte[] {0, 0, 0}), RF.create(new byte[] {0, 0, 1}))); } @Test - @Disabled("Test seems invalid; only the first prefixLen bytes are used to compare the records of the bpt against the first prefixLen bytes of the query range [x, y[") - public void rangedDistinctByPrefix() { - List keys = keys(); - - for ( int order : new int[] {2, 3, 4} ) { - BPlusTree bpt = BPlusTreeFactory.makeMem(order, 2, RecordLib.TestRecordLength, 0); - bpt.nonTransactional(); - for ( int key : keys ) - bpt.insert(RecordLib.intToRecord(key)); + public void suffixesDoNotAffectBounds() { + assertEquals(List.of(0), prefixes(tree(4, List.of(0)), 3, record(1), null)); + BPlusTree tree = tree(4, List.of(0, 256)); + assertEquals(List.of(0, 256), prefixes(tree, 3, record(1), null)); + assertEquals(List.of(0), prefixes(tree, 3, null, record(257))); + assertEquals(List.of(), prefixes(tree, 3, record(0), record(255))); + assertEquals(List.of(), prefixes(tree, 3, record(512), record(0))); + } - for ( int prefixLength : new int[] {3, 4} ) { - // Range boundaries on group boundaries and inside groups. - for ( int fromGroup = 0; fromGroup < GROUPS; fromGroup += 7 ) { - for ( int offset : new int[] {0, 1, MEMBERS / 2, MEMBERS - 1} ) { - int from = (fromGroup << 8) | offset; - int to = ((fromGroup + 5) << 8) | (MEMBERS - 1 - offset); - if ( to < from ) - continue; - check(bpt, order, prefixLength, keys, from, to); + @Test + public void rangesAcrossTreeShapes() { + List keys = new ArrayList<>(); + for (int group = 0; group < 40; group++) { + for (int member = 0; member < 24; member++) + keys.add((group << 8) | member); + } + // Exercise unsigned ordering as well as the highest possible key. + keys.add(0x80000000); + keys.add(0xffffff00); + keys.add(0xffffffff); + for (int order : new int[] {2, 3, 4}) { + BPlusTree tree = tree(order, keys); + for (int length : new int[] {0, 1, 2, 3, 4}) { + List bounds = new ArrayList<>(); + bounds.add(null); + for (int key : new int[] {0, 1, 255, 256, 257, 2048, 4095, 9999, + 0x80000000, 0xffffff00, 0xffffffff}) { + bounds.add(record(key)); + bounds.add(RF.create(Arrays.copyOf(record(key).getKey(), length))); + } + for (Record min : bounds) { + for (Record max : bounds) { + List expected = new ArrayList<>(); + for (int key : keys) { + byte[] bytes = record(key).getKey(); + if ((min == null || Arrays.compareUnsigned(bytes, 0, length, min.getKey(), 0, length) >= 0) + && (max == null || Arrays.compareUnsigned(bytes, 0, length, max.getKey(), 0, length) < 0)) { + byte[] prefix = new byte[4]; + System.arraycopy(bytes, 0, prefix, 0, length); + int value = Bytes.getInt(prefix); + if (expected.isEmpty() || expected.get(expected.size() - 1) != value) + expected.add(value); + } + } + assertEquals(expected, prefixes(tree, length, min, max), + "order=" + order + " length=" + length + " min=" + min + " max=" + max); } } } } } - private static void check(BPlusTree bpt, int order, int prefixLength, List keys, int from, int to) { - List expected = new ArrayList<>(); - for ( int key : keys.stream().sorted().toList() ) { - if ( key < from || key > to ) - continue; - String prefix = Bytes.asHex(prefixOf(key, prefixLength)); - if ( expected.isEmpty() || !expected.get(expected.size() - 1).equals(prefix) ) - expected.add(prefix); - } + @Test + public void unboundedMaximumAndZeroLengthPrefix() { + BPlusTree tree = tree(2, List.of(0, -1)); + assertNull(Record.incrementKeyOrNull(record(-1))); + assertEquals(List.of(-1), prefixes(tree, 4, record(-1), null)); + assertEquals(List.of(0), prefixes(tree, 0, null, null)); + assertEquals(List.of(0), prefixes(tree, 0, RF.create(new byte[0]), null)); + assertEquals(List.of(), prefixes(tree, 0, null, RF.create(new byte[0]))); + assertEquals(List.of(), prefixes(tree(2, List.of()), 0, null, null)); + } - List actual = new ArrayList<>(); - Record minInc = RecordLib.intToRecord(from); - Record maxExc = RecordLib.intToRecord(to); - Iterator iter = bpt.distinctByKeyPrefix(prefixLength, - minInc, - maxExc); - while ( iter.hasNext() ) { - Record record = iter.next(); - int key = RecordLib.recordToInt(record); - assertTrue(key >= from && key <= to, - () -> "Record outside the requested range" - + " [order=" + order + ", prefixLength=" + prefixLength + "]" - + "\n Range: [" + from + ", " + to + "]" - + "\n Record: " + key); - actual.add(Bytes.asHex(prefixOf(key, prefixLength))); + @Test + public void invalidBoundsAndLengths() { + for (BPlusTree tree : List.of(tree(2, List.of()), tree(2, List.of(0)), tree(2, List.of(0, 256)))) { + assertThrows(IllegalArgumentException.class, () -> tree.distinctByKeyPrefix(-1)); + assertThrows(IllegalArgumentException.class, () -> tree.distinctByKeyPrefix(5)); + assertThrows(IllegalArgumentException.class, + () -> tree.distinctByKeyPrefix(3, RF.create(new byte[2]), null)); + assertThrows(IllegalArgumentException.class, + () -> tree.distinctByKeyPrefix(3, null, RF.create(new byte[2]))); } + } - assertEquals(expected, actual, - () -> "Wrong set of distinct prefixes" - + " [order=" + order + ", prefixLength=" + prefixLength + "]" - + "\n Range: [" + from + ", " + to + "]"); + @Test + public void adjacentInlineLiteralsDoNotLeakAcrossExclusiveBound() { + var dsg = tdb2(":s1 :p 1 . :s2 :q 2 ."); + try { + assertSkipScanAgrees(dsg, "SELECT DISTINCT ?zz { ?s ?p 0 }"); + assertSkipScanAgrees(dsg, "SELECT DISTINCT ?zz { ?s ?p 1 }"); + } finally { + dsg.close(); + } } }