Skip to content

TDB2: SPARQL Update COPY/MOVE (and ADD after an earlier write) can silently lose triples (regression since 4.0.0) #4407

Open

Description

@MatthiasVanDE

Version

Apache Jena 6.2.0 (jena-tdb2), also 6.3.0-SNAPSHOT (2026-11-13), 5.6.0, 5.0.0, 4.10.0, 4.0.0.
Not affected: 3.17.0. Java 21 (Temurin).

What happened?

Inside a single SPARQL Update request (= one write transaction) on a TDB2 dataset, COPY <a> TO <b> and MOVE <a> TO <b> silently drop the last triples of the source graph from the copy.
No exception, no log message; COPY reports success and the destination graph just has fewer triples than the source.
ADD and MOVE are also affected when a preceding operation in the same request has already modified the indexes (for example DROP GRAPH <c> ; ADD <a> TO <b> where <b> does not exist yet; see the table below for what is and is not affected).

Minimal reproduction

Self-contained, one file, only Jena API and synthetic data (urn:test: IRIs):

// java -cp "<jena-tdb2 + dependencies>/*" Minimal.java [mem|disk] [N]
import java.nio.file.Files;
import org.apache.jena.graph.*;
import org.apache.jena.query.*;
import org.apache.jena.sparql.core.DatasetGraph;
import org.apache.jena.system.Txn;
import org.apache.jena.tdb2.TDB2Factory;
import org.apache.jena.update.UpdateAction;

public class Minimal {
    public static void main(String[] args) throws Exception {
        boolean disk = args.length > 0 && args[0].equals("disk");
        int n = args.length > 1 ? Integer.parseInt(args[1]) : 800;
        Dataset ds = disk ? TDB2Factory.connectDataset(Files.createTempDirectory("tdb2").toString())
                          : TDB2Factory.createDataset();
        DatasetGraph dsg = ds.asDatasetGraph();
        Node a = NodeFactory.createURI("urn:test:a"), b = NodeFactory.createURI("urn:test:b");
        Node p = NodeFactory.createURI("urn:test:p");
        Txn.executeWrite(ds, () -> {
            for (int i = 0; i < n; i++)                      // graph a: n triples
                dsg.getGraph(a).add(Triple.create(NodeFactory.createURI("urn:test:s/a/" + i), p, NodeFactory.createURI("urn:test:o/" + i)));
            for (int i = 0; i < Math.max(10, n / 10); i++)   // graph b: some other triples
                dsg.getGraph(b).add(Triple.create(NodeFactory.createURI("urn:test:s/b/" + i), p, NodeFactory.createURI("urn:test:o/" + i)));
        });
        // One update request = one write transaction. COPY first clears <b>, then adds the triples of <a>.
        Txn.executeWrite(ds, () -> UpdateAction.parseExecute("COPY <urn:test:a> TO <urn:test:b>", ds));
        long size = Txn.calculateRead(ds, () -> dsg.getGraph(b).size());
        System.out.println((disk ? "disk" : "mem") + ": graph b has " + size + " triples, expected " + n
                           + (size == n ? "" : "  (" + (n - size) + " missing)"));
    }
}

Expected

Graph <urn:test:b> contains exactly the n triples of <urn:test:a>.

Actual (the same on every run; the data is deterministic)

Jena mem 800 mem 10000 disk 100000
3.17.0 800 (ok) 10000 (ok) 100000 (ok)
4.0.0, 4.10.0, 5.0.0, 5.6.0, 6.2.0, 6.3.0-SNAPSHOT 795 (5 missing) 9870 (130 missing) 99949 (51 missing)

With 100,000 triples in memory 2,980 are missing (3 %).
On disk (default memory-mapped file mode) the loss only starts at larger sizes in this layout: sampled sizes from 100 to 28,000 were exact, 29,000 and 30,000 lose triples (28 and 44), 100,000 loses 51. (Direct file mode: only tried at 800 and 10,000, exact there.) Whether smaller graphs are affected on a store with a different layout - for example with many other graphs, or after many earlier transactions - I could not tell.

Which operations lose data (Jena 6.2.0, in-memory TDB2, a = 800 / 10,000 / 100,000 triples; every row checked in 5 / 5 / 3 fresh datasets)

Lost: always the last triples of the source graph in index order (e.g. indices 795..799 of 800), contiguous.

One update request Result
COPY <a> TO <b> where <b> already has triples lost
MOVE <a> TO <b> where <b> already has triples lost
DROP GRAPH <c> ; COPY <a> TO <b> / DROP GRAPH <c> ; MOVE <a> TO <b> lost
DROP GRAPH <c> ; ADD <a> TO <b> where <b> does not exist yet lost
DROP GRAPH <c> ; MOVE <a> TO <b> where <b> does not exist yet lost
ADD <a> TO <b> (no earlier write in the request) exact
MOVE <a> TO <b> where <b> does not exist, nothing before it exact
DROP GRAPH <c> ; ADD <a> TO <b> where <b> already has triples exact
separate requests: DROP GRAPH <c> then MOVE <a> TO <b> with <b> not existing exact
CLEAR GRAPH <b> ; INSERT { GRAPH <b> {?s ?p ?o} } WHERE { GRAPH <a> {?s ?p ?o} } exact
DROP GRAPH <c> ; INSERT { GRAPH <b> {?s ?p ?o} } WHERE { GRAPH <a> {?s ?p ?o} } exact

Below SPARQL, the same thing happens with the plain graph API in one write transaction:

Txn.executeWrite(ds, () -> {
    Graph b = dsg.getGraph(B);
    b.clear();
    GraphOps.addAll(b, dsg.getGraph(A).find());                 // loses the tail of A
    // GraphOps.addAll(b, dsg.getGraph(A).find().toList().iterator());   // exact
});

The full matrix (all scenarios above, 800 / 10,000 / 100,000 triples, in-memory and on disk, several rounds each, per version) is produced by Repro.java, included at the end of this report.

Analysis

UpdateEngineWorker.gsAddTriples (unchanged in main, checked at d5b47b7) reads and writes in one pass:

protected static void gsAddTriples(DatasetGraph dsg, Target src, Target dest) {
    Graph gSrc = graphOrThrow(dsg, src);
    Graph gDest = graphOrThrow(dsg, dest);
    GraphOps.addAll(gDest, gSrc.find());
}

COPY and MOVE call it after gsClear(dsg, dest), so the transaction has already modified the indexes; ADD only does so when an earlier operation of the request has.

Instrumenting the loop shows that it is the iterator that ends early, not the writes (iterated 795 of 800, and the 5 never-iterated triples are the last 5 of the source graph). On TDB2 the source iterator is a BPTreeRangeIterator, which walks RecordBufferIterators (an index into the live record buffer of a leaf block) and a list of child pages that was collected up front. As far as I can tell from BPTreeRecords.promote() and BptTxnState.modifiableRecordsBlock, blocks that were allocated or already copied in the current write transaction are modified in place, while blocks from before the transaction are copy-on-write (so an iterator over them stays consistent). If the last leaf of the source graph's key range was already touched in this transaction (here by clearing <b> or dropping <c>; in my data their keys follow those of <a> in the index) and the following inserts into the destination split that leaf, the iterator keeps looking at the shrunken block and does not visit the new right sibling, so the tail is skipped.
I have not instrumented the splits; please treat the exact mechanism as a hypothesis. The behaviour (tail missing, only when the same transaction touched the neighbourhood before) fits it.

The iterator behaviour itself is not new: the graph-API snippet above loses the same triples in 3.17.0. What changed is the SPARQL layer. In 3.17.0 gsAddTriples read everything first (so COPY/MOVE/ADD were exact there):

// Avoids concurrency problems by reading fully before writing
DataBag<Triple> db = BagFactory.newDefaultBag(policy, SerializationFactoryFinder.tripleSerializationFactory());
try {
    Iterator<Triple> triples = gSrc.find(null, null, null);
    db.addAll(triples);
    Iter.close(triples);
    GraphOps.addAll(gDest, db.iterator());
} finally { db.close(); }

This was replaced by GraphOps.addAll(gDest, gSrc.find()) in 6555f52 ("Remove unused SinkQuadOutput ansd SinkTripleOutput. Clear-up.", 2021-01-24), apparently as part of an unrelated cleanup; 4.0.0 is the first release with it.
UpdateModify (INSERT/DELETE ... WHERE) still materialises the solutions in a DataBag before writing, which is why the INSERT ... WHERE variants above are exact.

Suggestion (untested beyond the experiment below)

Restore the read-before-write in gsAddTriples, for example materialise into a list (or a DataBag with the existing spill policy for large graphs, as before 4.0.0):

protected static void gsAddTriples(DatasetGraph dsg, Target src, Target dest) {
    Graph gSrc = graphOrThrow(dsg, src);
    Graph gDest = graphOrThrow(dsg, dest);
    List<Triple> triples = gSrc.find().toList();   // read fully before writing
    GraphOps.addAll(gDest, triples.iterator());
}

With only this change applied to 6.2.0 (patched UpdateEngineWorker class first on the classpath), every SPARQL scenario above is exact, in memory and on disk, at 800 / 10,000 / 100,000 triples (3 rounds each). Only the graph-API control that still streams find() directly keeps losing triples, as expected. A DataBag (as before 4.0.0) would avoid holding a very large source graph on the heap; I have not checked which fits Jena's style best.

A fix in the TDB2 B+tree iterator (an iterator that stays valid when the leaf it is reading is modified in place, or one that detects this and re-seeks) would also protect other callers that iterate Graph.find()/DatasetGraph.find() while writing in the same transaction; I do not know what Jena promises there, so that may be a larger discussion than this issue.

Related (not necessarily TDB2; two separate problems found while testing; happy to file them as separate issues)

  1. UpdateExec with an overall timeout cancels the second WHERE operation of a request immediately.
    UpdateEngineWorker.updateRemainingQueryTimeout starts the remaining time at -1 in the else branch (second and later operations) and subtracts the elapsed time from it, so the remaining time is clamped to 0 and the next query is cancelled at once, whatever the timeout:

    String two = "DELETE { GRAPH <urn:test:b> {?s ?p ?o} } WHERE { GRAPH <urn:test:b> {?s ?p ?o} } ; "
               + "INSERT { GRAPH <urn:test:b> {?s ?p ?o} } WHERE { GRAPH <urn:test:a> {?s ?p ?o} }";
    Txn.executeWrite(ds, () -> UpdateExec.dataset(ds.asDatasetGraph()).update(two)
            .timeout(600_000, TimeUnit.MILLISECONDS).execute());
    // -> org.apache.jena.query.QueryCancelledException after ~1 ms (5.6.0, 6.2.0, 6.3.0-SNAPSHOT)

    The same request with one operation, or without .timeout(...), works. Setting ARQ.queryTimeout/ARQ.updateTimeout in the dataset context did not trigger it in my test.
    Candidate fix: in the else branch use remainingOverallTimeoutMillis = timeout.overallTimeoutMillis() - elapsedMillis;. With that single-line change in 6.2.0 the two-operation request above completes normally. This looks to date from the update-timeout support (Support for Timeout on Updates #2821 / GH-2821: Support for Timeouts on Updates #2822).

  2. IndexOutOfBoundsException in DefaultDataBag.iterator when a WHERE has exactly as many solutions as the spill threshold.

    ds.getContext().set(ARQ.spillToDiskThreshold, 100L);
    // INSERT { GRAPH <urn:test:b> {?s ?p ?o} } WHERE { GRAPH <urn:test:a> {?s ?p ?o} }   with exactly 100 triples in <a>
    // -> java.lang.IndexOutOfBoundsException: Index 0 out of bounds for length 0   (5.6.0, 6.2.0, 6.3.0-SNAPSHOT)

    With 99, 101 or 250 solutions it works. Cause, as far as I can see: DefaultDataBag.add only calls spill() when an item arrives after the threshold was reached, but iterator() decides between memory and spill file with policy.isThresholdExceeded(), which is already true after the threshold-th item. With exactly threshold items nothing was spilled, but iterator() takes getSpillFiles().get(0) of an empty list. Using the existing spilled flag in iterator() instead of policy.isThresholdExceeded() made the failing case work in 6.2.0 (99 / 100 / 101 / 250 all fine).
    ARQ.spillToDiskThreshold is unset by default (policy never()), so only users who enabled spilling are affected.

Relevant output and stacktrace

ARQ 6.2.0 / Java 21.0.13
mode  N        group  scenario                                         bad/rounds  missing(min..max)
mem   800      BUG?   COPY a TO b (b non-empty)                               5/5               5..5
mem   800      BUG?   MOVE a TO b (b non-empty)                               5/5               5..5
mem   800      BUG?   ADD a TO b (b non-empty)                                0/5               0..0
mem   800      BUG?   DROP c ; ADD a TO b                                     0/5               0..0
mem   800      BUG?   DROP c ; COPY a TO b                                    5/5               5..5
mem   800      BUG?   DROP c ; MOVE a TO b                                    5/5               5..5
mem   800      control DROP c ; MOVE a TO b (b does not exist)                5/5               5..5
mem   800      control DROP c ; ADD a TO b (b does not exist)                 5/5               5..5
mem   800      control CLEAR b ; INSERT..WHERE (read-all-then-write)          0/5               0..0
mem   10000    BUG?   COPY a TO b (b non-empty)                               5/5           130..130
disk  100000   BUG?   COPY a TO b (b non-empty)                               3/3             51..51
...

(Repro.java below prints the full table.)

Repro.java (full matrix, run with java -cp "<jena jars>/*" Repro.java [sizes] [rounds] [modes])
// Repro for: SPARQL Update COPY / MOVE / ADD on TDB2 silently losing triples
// within a single update request (one write transaction).
//
// Run (Java 17+/21, Jena jars on the classpath):
//   java -cp "<jena jars>/*" Repro.java [sizes=800,10000,100000] [rounds=5] [modes=mem,disk]
//
// Every scenario starts from a fresh TDB2 dataset in which <urn:test:a> holds N
// triples, <urn:test:b> holds N/10 other triples and <urn:test:c> holds 5 triples.
// The setup is committed; then ONE update request is executed in ONE write
// transaction, and graph <urn:test:b> is compared with the expected content.
import java.nio.file.*;
import java.util.*;
import java.util.stream.*;

import org.apache.jena.graph.*;
import org.apache.jena.query.*;
import org.apache.jena.sparql.core.DatasetGraph;
import org.apache.jena.sparql.graph.GraphOps;
import org.apache.jena.system.Txn;
import org.apache.jena.tdb2.TDB2Factory;
import org.apache.jena.update.UpdateAction;

public class Repro {
    static final Node A = NodeFactory.createURI("urn:test:a");
    static final Node B = NodeFactory.createURI("urn:test:b");
    static final Node C = NodeFactory.createURI("urn:test:c");
    static final Node P = NodeFactory.createURI("urn:test:p");

    /** -Drandom=1 : random subject IRIs (different per round) instead of urn:test:s/a/0 .. n-1 */
    static final boolean RANDOM = System.getProperty("random") != null;
    static Set<Triple> triples(String g, int n, Random rnd) {
        Set<Triple> s = new HashSet<>();
        for (int i = 0; i < n; i++) {
            String id = RANDOM ? Long.toHexString(rnd.nextLong()) : Integer.toString(i);
            s.add(Triple.create(NodeFactory.createURI("urn:test:s/" + g + "/" + id), P,
                                org.apache.jena.sparql.expr.NodeValue.makeInteger(i).asNode()));
        }
        return s;
    }

    /** A scenario: group, name, does b exist beforehand, the operation, and the expected content of b. */
    interface Op { void run(Dataset ds, DatasetGraph dsg); }
    interface Expect { Set<Triple> of(Set<Triple> a, Set<Triple> b); }
    record Sc(String group, String name, boolean bExists, Op op, Expect expect) {}

    static Op update(String... requests) {
        // each request is ONE update request = ONE write transaction
        return (ds, dsg) -> { for (String r : requests) Txn.executeWrite(ds, () -> UpdateAction.parseExecute(r, ds)); };
    }
    static final String DROPC = "DROP GRAPH <urn:test:c>";
    static final String COPY = "COPY <urn:test:a> TO <urn:test:b>";
    static final String MOVE = "MOVE <urn:test:a> TO <urn:test:b>";
    static final String ADD = "ADD <urn:test:a> TO <urn:test:b>";
    static final String CLEARB = "CLEAR GRAPH <urn:test:b>";
    static final String INS = "INSERT { GRAPH <urn:test:b> { ?s ?p ?o } } WHERE { GRAPH <urn:test:a> { ?s ?p ?o } }";

    static Expect copyLike = (a, b) -> a;
    static Expect addLike = (a, b) -> { Set<Triple> u = new HashSet<>(b); u.addAll(a); return u; };

    static List<Sc> scenarios() {
        List<Sc> l = new ArrayList<>();
        // --- Reported cases (expected: b == a) -----------------------------------------
        l.add(new Sc("BUG?", "COPY a TO b (b non-empty)", true, update(COPY), copyLike));
        l.add(new Sc("BUG?", "MOVE a TO b (b non-empty)", true, update(MOVE), copyLike));
        l.add(new Sc("BUG?", "ADD a TO b (b non-empty)", true, update(ADD), addLike));
        l.add(new Sc("BUG?", "DROP c ; ADD a TO b", true, update(DROPC + " ; " + ADD), addLike));
        l.add(new Sc("BUG?", "DROP c ; COPY a TO b", true, update(DROPC + " ; " + COPY), copyLike));
        l.add(new Sc("BUG?", "DROP c ; MOVE a TO b", true, update(DROPC + " ; " + MOVE), copyLike));
        // --- Controls --------------------------------------------------------------------
        l.add(new Sc("control", "MOVE a TO b (b does not exist)", false, update(MOVE), copyLike));
        l.add(new Sc("control", "ADD a TO b (b does not exist)", false, update(ADD), addLike));
        l.add(new Sc("control", "DROP c ; MOVE a TO b (b does not exist)", false, update(DROPC + " ; " + MOVE), copyLike));
        l.add(new Sc("control", "DROP c ; ADD a TO b (b does not exist)", false, update(DROPC + " ; " + ADD), addLike));
        l.add(new Sc("control", "separate requests: DROP c | MOVE a TO b", true, update(DROPC, MOVE), copyLike));
        l.add(new Sc("control", "separate requests: DROP c | ADD a TO b", true, update(DROPC, ADD), addLike));
        l.add(new Sc("control", "separate requests: DROP c | MOVE (b does not exist)", false, update(DROPC, MOVE), copyLike));
        l.add(new Sc("control", "separate requests: CLEAR b | ADD a TO b", true, update(CLEARB, ADD), copyLike));
        l.add(new Sc("control", "CLEAR b ; INSERT..WHERE (read-all-then-write)", true, update(CLEARB + " ; " + INS), copyLike));
        l.add(new Sc("control", "DROP c ; INSERT..WHERE (read-all-then-write)", true, update(DROPC + " ; " + INS), addLike));
        // --- Same thing below SPARQL, with the Graph API in one write transaction ---------
        l.add(new Sc("graph-API", "b.clear(); GraphOps.addAll(b, a.find())", true,
            (ds, dsg) -> Txn.executeWrite(ds, () -> { Graph b = dsg.getGraph(B); b.clear(); GraphOps.addAll(b, dsg.getGraph(A).find()); }), copyLike));
        l.add(new Sc("graph-API", "b.clear(); addAll(b, a.find().toList())", true,
            (ds, dsg) -> Txn.executeWrite(ds, () -> { Graph b = dsg.getGraph(B); b.clear(); GraphOps.addAll(b, dsg.getGraph(A).find().toList().iterator()); }), copyLike));
        l.add(new Sc("graph-API", "removeGraph(c); addAll(b, a.find())", true,
            (ds, dsg) -> Txn.executeWrite(ds, () -> { dsg.removeGraph(C); GraphOps.addAll(dsg.getGraph(B), dsg.getGraph(A).find()); }), addLike));
        l.add(new Sc("graph-API", "removeGraph(c); addAll(b, a.find().toList())", true,
            (ds, dsg) -> Txn.executeWrite(ds, () -> { dsg.removeGraph(C); GraphOps.addAll(dsg.getGraph(B), dsg.getGraph(A).find().toList().iterator()); }), addLike));
        return l;
    }

    public static void main(String[] args) throws Exception {
        int[] sizes = Arrays.stream((args.length > 0 ? args[0] : "800,10000,100000").split(",")).mapToInt(Integer::parseInt).toArray();
        int rounds = args.length > 1 ? Integer.parseInt(args[1]) : 5;
        List<String> modes = Arrays.asList((args.length > 2 ? args[2] : "mem,disk").split(","));
        System.out.println("ARQ " + ARQ.VERSION + " / Java " + System.getProperty("java.version"));
        System.out.printf("%-5s %-8s %-6s %-48s %10s %18s %s%n", "mode", "N", "group", "scenario", "bad/rounds", "missing(min..max)", "extra");
        for (String mode : modes)
            for (int n : sizes)
                for (Sc sc : scenarios()) {
                    int bad = 0, minMiss = Integer.MAX_VALUE, maxMiss = 0, maxExtra = 0;
                    for (int r = 0; r < rounds; r++) {
                        Random rnd = new Random(1000L + r);
                        Path dir = mode.equals("disk") ? Files.createTempDirectory("tdb2-repro") : null;
                        Dataset ds = dir == null ? TDB2Factory.createDataset() : TDB2Factory.connectDataset(dir.toString());
                        DatasetGraph dsg = ds.asDatasetGraph();
                        Set<Triple> a = triples("a", n, rnd), b = triples("b", Math.max(10, n / 10), rnd), c = triples("c", 5, rnd);
                        Txn.executeWrite(ds, () -> {
                            a.forEach(t -> dsg.getGraph(A).add(t));
                            if (sc.bExists) b.forEach(t -> dsg.getGraph(B).add(t));
                            c.forEach(t -> dsg.getGraph(C).add(t));
                        });
                        sc.op.run(ds, dsg);
                        Set<Triple> expected = sc.expect.of(a, sc.bExists ? b : Set.of());
                        Set<Triple> actual = Txn.calculateRead(ds, () -> dsg.getGraph(B).find().toSet());
                        long countViaSparql = Txn.calculateRead(ds, () -> { try (QueryExecution qe = QueryExecutionFactory.create(
                            "SELECT (COUNT(*) AS ?n) WHERE { GRAPH <urn:test:b> { ?s ?p ?o } }", ds)) {
                            return (long) qe.execSelect().next().getLiteral("n").getInt(); } });
                        int missing = (int) expected.stream().filter(t -> !actual.contains(t)).count();
                        int extra = (int) actual.stream().filter(t -> !expected.contains(t)).count();
                        if (countViaSparql != actual.size()) System.out.println("  note: SPARQL COUNT " + countViaSparql + " != find() " + actual.size());
                        if (missing > 0 || extra > 0) bad++;
                        if (System.getProperty("show") != null && missing > 0) System.out.println("   missing e.g. " + expected.stream().filter(t -> !actual.contains(t)).sorted(Comparator.comparing(Object::toString)).limit(8).toList());
                        minMiss = Math.min(minMiss, missing); maxMiss = Math.max(maxMiss, missing); maxExtra = Math.max(maxExtra, extra);
                        ds.close();
                        if (dir != null) try (Stream<Path> w = Files.walk(dir)) { w.sorted(Comparator.reverseOrder()).forEach(p -> p.toFile().delete()); }
                    }
                    System.out.printf("%-5s %-8d %-6s %-48s %10s %18s %d%n", mode, n, sc.group, sc.name,
                        bad + "/" + rounds, minMiss + ".." + maxMiss, maxExtra);
                }
    }
}

Disclosure: the investigation and this write-up were prepared with the help of an AI coding assistant (Claude). The reproduction above is self-contained and deterministic so that it can be checked independently of that.

Activity

  1. afs commented on Nov 13, 2026

    @afs
    Member

    Disclosure: the investigation and this write-up were prepared with the help of an AI coding assistant (Claude).

    While we welcome AI-written reports, we do ask that for something succinct and human as well all the details. Details are great but a summary is still necessary. Al created reports increase the review workload and reviewing is a limited resource.

    If a report is going to take a long time to interpret, then likely handling it will be delayed.

    As it is AI, including @Test would be appreciated.

     

    Is TDB2 only?

    This is says "plain graph" but that is ambiguous. Presumably it is TDB2?

        Txn.executeWrite(ds, () -> {
        Graph b = dsg.getGraph(B);
        b.clear();
        GraphOps.addAll(b, dsg.getGraph(A).find());                 // loses the tail of A
        // GraphOps.addAll(b, dsg.getGraph(A).find().toList().iterator());   // exact
    });
    

    A fix in the TDB2 B+tree iterator (an iterator that stays valid when the leaf it is reading is modified in place, or one that detects this and re-seeks) would also protect other callers that iterate Graph.find()/DatasetGraph.find() while writing in the same transaction; I do not know what Jena promises there, so that may be a larger discussion than this issue.

    That seems a rather important point.

    Related (not necessarily TDB2; two separate problems found while testing; happy to file them as separate issues)

    These are separate.

  2. MatthiasVanDE commented on Nov 14, 2026

    @MatthiasVanDE
    Author

    @afs ,
    Thanks for looking at this, and sorry for the wall of text. To be honest, I didn't know this issue had been posted. My AI coding assistant filed it under my account while working on a bigger task. I've checked the findings myself since then, and they hold up.

    In short: on TDB2, COPY a TO b and MOVE a TO b silently lose the last few triples of a, for example 795 of 800. ADD does the same if an earlier operation in the same request has already written something. This started in 4.0.0, when gsAddTriples stopped reading the source graph fully before writing to the target. Reading it fully first again fixes it.

    TDB2 only? Yes. That snippet was TDB2, sorry for the vague "plain graph". On 6.2.0:

    TDB2 loses triples, both through SPARQL and through the Graph API directly.
    TDB1 throws a ConcurrentModificationException. It fails too, but loudly.
    createTxnMem() and create() copy every triple.
    Test: a JUnit test is below. On 6.2.0, 4 of its 5 cases fail. On 3.17.0, and on 6.2.0 with the gsAddTriples fix, all 5 pass.

    Related: agreed, they're separate. I'll file each as a short issue of its own with a test.

    Happy to open a PR with the fix and the test if that helps.

  3. MatthiasVanDE commented on Nov 14, 2026

    @MatthiasVanDE
    Author

    Forgot the test, here it is (org.apache.jena.tdb2.store):

    /*
     * 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.store;
    
    import static org.junit.jupiter.api.Assertions.assertEquals;
    
    import org.junit.jupiter.api.Test;
    
    import org.apache.jena.graph.Node;
    import org.apache.jena.graph.NodeFactory;
    import org.apache.jena.sparql.core.DatasetGraph;
    import org.apache.jena.system.Txn;
    import org.apache.jena.tdb2.DatabaseMgr;
    import org.apache.jena.update.UpdateAction;
    
    /** SPARQL Update COPY/MOVE/ADD on TDB2 must copy every triple of the source graph (GH-4407). */
    public class TestUpdateGraphCopyTDB {
        // Large enough to span several B+tree leaves; 800 is enough for the in-memory dataset.
        private static final int N = 800;
    
        private static final Node gA = NodeFactory.createURI("http://example/a");
        private static final Node gB = NodeFactory.createURI("http://example/b");
        private static final Node gC = NodeFactory.createURI("http://example/c");
        private static final Node p  = NodeFactory.createURI("http://example/p");
    
        private static DatasetGraph dataset(boolean withB) {
            DatasetGraph dsg = DatabaseMgr.createDatasetGraph();
            Txn.executeWrite(dsg, () -> {
                for ( int i = 0 ; i < N ; i++ )
                    dsg.add(gA, NodeFactory.createURI("http://example/s/a/" + i), p, NodeFactory.createURI("http://example/o/" + i));
                for ( int i = 0 ; i < 5 ; i++ )
                    dsg.add(gC, NodeFactory.createURI("http://example/s/c/" + i), p, NodeFactory.createURI("http://example/o/" + i));
                if ( withB ) {
                    for ( int i = 0 ; i < N / 10 ; i++ )
                        dsg.add(gB, NodeFactory.createURI("http://example/s/b/" + i), p, NodeFactory.createURI("http://example/o/" + i));
                }
            });
            return dsg;
        }
    
        private static void test(boolean withB, String request, long expectedB) {
            DatasetGraph dsg = dataset(withB);
            // One request, one write transaction.
            Txn.executeWrite(dsg, () -> UpdateAction.parseExecute(request, dsg));
            long sizeB = Txn.calculateRead(dsg, () -> dsg.getGraph(gB).size());
            assertEquals(expectedB, sizeB, request);
        }
    
        @Test public void update_copy() {
            test(true, "COPY <http://example/a> TO <http://example/b>", N);
        }
    
        @Test public void update_move() {
            test(true, "MOVE <http://example/a> TO <http://example/b>", N);
        }
    
        @Test public void update_add_after_write() {
            test(false, "DROP GRAPH <http://example/c> ; ADD <http://example/a> TO <http://example/b>", N);
        }
    
        @Test public void update_move_after_write() {
            test(false, "DROP GRAPH <http://example/c> ; MOVE <http://example/a> TO <http://example/b>", N);
        }
    
        // Passes in 6.2.0: no earlier write in the transaction.
        @Test public void update_add() {
            test(false, "ADD <http://example/a> TO <http://example/b>", N);
        }
    }
  4. deepikavalluru commented on Nov 17, 2026

    @deepikavalluru
    Contributor

    Hi, I'd like to work on this issue. I've recently contributed a fix to Apache Jena and would like to investigate this issue as my next contribution. Is it still available?

  5. MatthiasVanDE commented on Nov 17, 2026

    @MatthiasVanDE
    Author

    Not that I know of, so feel free! The fix could go in gsAddTriples or in TDB2 itself, so it's probably worth checking the approach with @afs first.

  6. deepikavalluru commented on Nov 17, 2026

    @deepikavalluru
    Contributor

    Thanks! I'll investigate this issue. Before implementing a fix, I'd like to check the preferred approach with @afs.

    The current implementation streams the source graph iterator directly into the destination using GraphOps.addAll(gDest, gSrc.find()). Would it be preferable to materialize the source triples in gsAddTriples(), or should we investigate a fix within TDB2 itself?

  7. afs commented on Nov 17, 2026

    @afs
    Member

    A solution should be to UpdateEngineWorker.gsAddTriples.

    A fix in the TDB2 B+tree iterator

    The report is dangerously misleading. The report reads as if a fix is to change BPTreeRangeIterator. The fundamental contract of Java iterators is that the only modification allowed is Iterator.remove (very few Jena iterators support .remove). A special iterator is an architectural change. e.g. work on #3995 is for different iterator.

    Fix the general part, not the storage.

    The bad news is that SerializationFactoryFinder.tripleSerializationFactory() was removed.

    The good news is that a replacement can use binary formats Thrift (or Protobuf) to write quads.

    A good solution will try to stash, say, 10,000 inserts in an array and if the addition fit, insert from the array and finish. If they don't fit, uses a data bag.

    You might want to look at #4409 as a warm up.

  8. deepikavalluru commented on Nov 18, 2026

    @deepikavalluru
    Contributor

    A solution should be to UpdateEngineWorker.gsAddTriples.

    A fix in the TDB2 B+tree iterator

    The report is dangerously misleading. The report reads as if a fix is to change BPTreeRangeIterator. The fundamental contract of Java iterators is that the only modification allowed is Iterator.remove (very few Jena iterators support .remove). A special iterator is an architectural change. e.g. work on #3995 is for different iterator.

    Fix the general part, not the storage.

    The bad news is that SerializationFactoryFinder.tripleSerializationFactory() was removed.

    The good news is that a replacement can use binary formats Thrift (or Protobuf) to write quads.

    A good solution will try to stash, say, 10,000 inserts in an array and if the addition fit, insert from the array and finish. If they don't fit, uses a data bag.

    You might want to look at #4409 as a warm up.

  9. deepikavalluru commented on Nov 18, 2026

    @deepikavalluru
    Contributor

    One implementation detail I'm still considering is the serialization factory required by DataBag. I found that the existing SerializationFactoryFinder only exposes a binding serialization factory. The Thrift APIs appear to support triple serialization, but their deserialization currently uses a StreamRDF callback interface rather than directly providing an Iterator.

    Would you recommend Thrift or Protobuf for the SerializationFactory implementation?
    Is there an existing Jena utility or preferred pattern for adapting the deserializer to the required iterator interface?

    @afs, I'd like to make sure the implementation follows Jena's existing conventions before proceeding.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions