Skip to content

/upsert (and /update) fail to retract prior values when the subject's prior value is still in the novelty window — replace-by-@id appends instead of replacing #1602

Closed

Description

@IX-Erich

Affects: stock fluree/server:4.1.0 and 4.1.1 (4.1.1 is worse — see below). FLUREE_INDEXING_ENABLED=true, single-node transaction server, default graph.
Type: correctness — silent violation of the documented upsert "replace" contract.
Repro: self-contained, stock image + Python stdlib, ~2 min.

Summary

A declarative insert-only /upsert ("replace by @id") does not reliably retract a subject's existing values for the asserted predicates when the subject's prior value is still in the novelty overlay (not yet folded into the index). The upsert appends instead of replacing, producing multiple values for what should be a single-valued predicate.

The trigger is not upsert burst rate against an old subject — it is that the value being replaced was written 1–2 commits earlier and is still unindexed. This is the ordinary create-an-entity-then-set-its-status-a-moment-later pattern, so it fires under normal application load on any ledger with indexing active.

Relationship to open issues on the same boundary

This looks like the /upsert write-side case of a novelty/index handoff class you
already have open
:

Each of those is a read/aggregate path that mishandles values still in novelty. This
report is the same shape on the write path: the retract-generation reads a view that
excludes novelty, so it cancels nothing and the insert appends.

Not a duplicate of #1412 ("Re-inserting existing triples yields duplicate triples +
assert/retract churn; upsert of existing triples registers no new transaction"). That one
concerns re-inserting identical triples, where RDF set semantics are the relevant
question. Here the values differ (BACKLOG → IN_PROGRESS) and the subject ends up
holding both, so dedup does not apply and no amount of set-semantics reasoning
explains it.

Not a duplicate of #1192 (ours, closed) either — that was identical-triple
accumulation and undeletability on the V3 line.

Two presentations, one root cause

The same defect surfaces two different ways depending on whether the predicate has a sh:maxCount 1 shape:

Predicate What you see
No shape The write commits (HTTP 200) and the subject silently accumulates — state ends up with 3 values instead of 1. Survives a process restart → this is persisted on-disk data, not a read-time phantom.
sh:maxCount 1 shape The upsert is spuriously rejected: Transaction error: SHACL validation failed … Expected at most 1 value(s) but found 2 — on a subject that verifiably holds exactly one value. The node effectively becomes unwritable through the normal path.

That second row is the sharp diagnostic: within a single transaction, the SHACL validator sees the prior flake (it counts "2") while the upsert's retract cannot (it cancels nothing). Two reads of the same subject in the same staging pass disagree about whether the prior value exists. Whatever view the retract-generation uses is stale with respect to the immediately-preceding commits; the validator's view is not (on 4.1.0).

Minimal reproduction (stock image, ~2 min)

docker run -d --name flu -e FLUREE_INDEXING_ENABLED=true -p 8090:8090 \
  fluree/server:4.1.0 -- --server-role transaction --events-auth-mode none
# wait for {"status":"ok"} on http://localhost:8090/health, then:
python3 repro.py http://localhost:8090 flu

repro.py (stdlib only) — creates each subject inside the novelty depth, then upserts it immediately, and ends with a container restart to prove the accumulation is persisted:

import json, subprocess, sys, time, urllib.request
BASE, CONTAINER = sys.argv[1].rstrip("/"), sys.argv[2]
E = "http://example.org/"; CTX = {"ex": E}
L = f"repro-{int(time.time())}"

def post(path, body):
    r = urllib.request.Request(BASE+path, data=json.dumps(body).encode(),
        headers={"Content-Type": "application/json"}, method="POST")
    try:    x = urllib.request.urlopen(r, timeout=60); return x.status, x.read().decode()
    except urllib.error.HTTPError as e: return e.code, e.read().decode()
    except Exception as e: return 0, str(e)

def upsert(nodes):  # bare JSON-LD doc + ?ledger= routing (no envelope)
    r = urllib.request.Request(f"{BASE}/v1/fluree/upsert?ledger={L}",
        data=json.dumps({"@context": CTX, "@graph": nodes}).encode(),
        headers={"Content-Type": "application/json"}, method="POST")
    try:    x = urllib.request.urlopen(r, timeout=60); return x.status, x.read().decode()
    except urllib.error.HTTPError as e: return e.code, e.read().decode()

def states(subj):
    _, b = post("/v1/fluree/query", {"from": L, "@context": CTX,
        "select": ["?p","?o"], "where": {"@id": subj, "?p":"?o"}})
    return [o for p,o in json.loads(b) if isinstance(p,str) and p.endswith("state")]

def wait_health(t=120):
    t0=time.time()
    while time.time()-t0<t:
        try:
            if urllib.request.urlopen(BASE+"/health",timeout=5).status==200: return
        except Exception: pass
        time.sleep(2)

post("/v1/fluree/create", {"ledger": L})
for i in range(1500):  # build novelty depth (indexer lags this)
    post("/v1/fluree/insert", {"ledger": L, "@context": CTX,
        "insert": [{"@id": f"{E}filler-{i}", "ex:v": "x"}]})

subs = [f"{E}issue-{k}" for k in range(10)]
for s in subs:  # create-then-upsert-twice, INSIDE the novelty window
    post("/v1/fluree/insert", {"ledger": L, "@context": CTX,
        "insert": [{"@id": s, "@type": "ex:Issue", "ex:state": {"@id":"ex:BACKLOG"}}]})
    upsert([{"@id": s, "ex:state": {"@id": "ex:IN_PROGRESS"}}])
    upsert([{"@id": s, "ex:state": {"@id": "ex:DONE"}}])

time.sleep(8)
pre = sum(1 for s in subs if len(states(s)) > 1)
print(f"multi-valued before restart: {pre}/10  (expected 0 — each should hold only ex:DONE)")
subprocess.run(["docker","restart",CONTAINER], check=True, capture_output=True)
wait_health(); time.sleep(5)
post_ = sum(1 for s in subs if len(states(s)) > 1)
print(f"multi-valued AFTER restart:  {post_}/10  (>0 => persisted, not a read phantom)")
for s in subs:
    v = states(s)
    if len(v) > 1: print(f"  {s}: {sorted(v)}")

Observed

# stock fluree/server:4.1.0, indexing on, no shape
multi-valued before restart: 10/10  (expected 0 — each should hold only ex:DONE)
multi-valued AFTER restart:  10/10  (>0 => persisted, not a read phantom)
  http://example.org/issue-0: ['ex:BACKLOG', 'ex:DONE', 'ex:IN_PROGRESS']
  ...

Every subject accumulated all three states; the restart confirms it is persisted on disk. On a fresh/shallow ledger (delete the 1500-filler loop) the same script prints 0/10 — correct — which is why a naïve "N upserts → expect 1 value" test passes and the defect hides.

Version behavior (a regression worth bisecting)

  • 4.1.0 — with a sh:maxCount 1 shape, mostly fails loud: the validator sees the un-retracted prior and rejects the write (~17/20 spurious rejections in our runs). Without a shape, silent persisted accumulation (10/10 above).
  • 4.1.1 — fails silent even with the shape: validation misses the prior value along with the retract, so corrupting writes pass SHACL and persist (in our runs, subjects that weren't rejected accumulated ×3 and survived restart). 4.1.1 appears to have widened the window — the append-only segmented-novelty rewrite (perf: append-only segmented novelty — O(batch) write path #1302, new in 4.1.1) touches exactly the overlay the upsert retract reads.

Source localization (from 4.1.x source)

Upsert "replace" retractions are generated in generate_upsert_deletions() (fluree-db-transact/src/stage.rs). On the default graph it reads current values via:

fluree_db_query::execute_pattern(ledger.as_graph_db_ref(0), &query_vars, pattern).await?

as_graph_db_ref does bundle the novelty overlay (GraphDbRef { snapshot, overlay: &*self.novelty, t: max(novelty.t, snapshot.t) }), so this read should see recently-committed flakes — but under novelty depth it returns nothing for a value written by a just-prior commit. We localized this by experiment: the values that need retracting are absent from the LedgerState handed to staging — the staging view is stale w.r.t. the immediately-preceding commits, upstream of the retract lookup itself. Looks adjacent to #1385 (read-your-writes), whose fix was scoped to the embedded owned-state API and called the server LocalCommitter path "already correct" — under rapid sequential server commits with indexing lag, it appears not to be.

A fix we ruled out (so you don't have to)

We tried unioning the default-graph retract with a direct overlay scan mirroring the named-graph not-indexed fallback (query_novelty_for_graph, which reads ledger.novelty.for_each_overlay_flake). Built on stock and re-run against the repro, it did not fix it — because that scan reads the same ledger handle. This confirms the missing values are not in that handle at all; the staleness is in the staging / ledger-cache handoff, not the retract read primitive.

Expected vs. actual

  • Expected: after insert(state=BACKLOG) → upsert(state=IN_PROGRESS) → upsert(state=DONE), the subject holds exactly state = DONE. Documented contract: "Upsert: Replace mode. Deletes existing values for provided predicates, then inserts." (fluree-db-transact/src/ir.rs).
  • Actual: the subject holds {BACKLOG, IN_PROGRESS, DONE} (no shape) or the second/third upsert is spuriously SHACL-rejected (shape).

Impact

Any create-then-update-soon workflow on an indexing-enabled ledger corrupts single-valued predicates. With sh:maxCount 1 shapes it either hard-fails valid writes (4.1.0) or silently bricks the node toward unwritability (4.1.1). Updates to long-settled subjects (prior value already indexed) are unaffected. Application-side workarounds — serialize + read-back-verify, or space create/update beyond the indexing window — are viable but are not a substitute for the retract seeing a fresh staging view.

Minor companion finding (not a separate issue)

On stock 4.1.0, POST /v1/fluree/insert and /v1/fluree/upsert JSON-LD-process the entire request body: a body shaped {"ledger": "...", "@context": {...}, "insert": [...]} is routed correctly by the ledger key and also mints one orphan blank node per call (_:fdb-…-0-b0 carrying literal insert→subject and ledger→name). On a migrated ledger those dict-orphaned subjects fail overlay translation on every read. The repro above sidesteps this by sending the bare @graph doc + ?ledger= routing. Stock 4.1.1 mints zero such nodes — so this is already fixed on 4.1.1, and may share the transact-ingestion code path with the staging-view change above (useful bisect cross-check). /update consumes its envelope correctly on both.

Activity

  1. IX-Erich commented on Aug 6, 2026

    @IX-Erich
    Author

    Correction: this may be retract-then-resurrect, not a retract miss

    New production evidence from today refines — and partly contradicts — the framing above. I described the retract as never happening. A node we were able to bracket with verified reads says the retract does happen, is observable, and is then undone later with no intervening write.

    The timeline

    A single subject on a production ledger, state and updatedAt both sh:maxCount 1. Three writes over ~10 hours, each an insert-only /upsert replacing the prior value. After each write we read the node back from the transaction server and recorded the result:

    time (UTC) event value read back
    02:55:37 create → BACKLOG —
    12:30:31 upsert → IN_PROGRESS 1 value. BACKLOG confirmed gone
    13:10:52 upsert → IN_REVIEW 1 value. IN_PROGRESS confirmed gone
    ~15:45 no write of any kind 3 values: BACKLOG, IN_PROGRESS, IN_REVIEW

    updatedAt moved in lockstep — all three timestamps present at the end, exactly matching the three writes.

    So both retractions committed and were visible as committed. Hours later, with nothing written to the subject in between, the retracted values were back. createdAt, written once and never retracted, stayed single-valued throughout.

    Why this distinction matters for where to look

    "The retract was never generated" and "the retract was generated, applied, and later lost" point at different code. The second is consistent with the retraction living in the novelty overlay and the pre-retraction state being what survives when the index publishes — i.e. the loss happens at the novelty→index handoff, not at retract generation in the staging pass.

    Two things fit that reading:

    1. The window matches the publish cadence. On this ledger index publishes are sporadic and hours apart (we measured 3h51m / 89 commits between two of them). The resurfacing above landed inside such a gap.
    2. It explains a string of failed reproductions. We could not reproduce accumulation in a sandbox across five attempts, including with FLUREE_REINDEX_MIN_BYTES set high enough that the index never published at all — which we had treated as the strongest test. If the corruption appears at an index publish, an environment where the index never publishes removes the trigger rather than maximising it. None of our sandbox attempts had an index publish between the write and the read.

    What this does and does not change about the report above

    The reproduction in the original report still stands — it produces persistent multi-value accumulation on stock 4.1.0, and it survives a container restart.

    But note it cannot discriminate between the two mechanisms: it writes, then reads at the end. Both "retract never happened" and "retract happened then was lost" produce the same final state. The production timeline discriminates only because we happened to read between the writes and again much later.

    If it's useful, a repro that would separate them: write, read back and assert single-valued, then force or wait for an index publish, then read again. If the value reappears only after the publish, that localises it to the handoff.

    I'd also treat the sh:maxCount 1 presentation described above in the same light — a validator that counts a prior flake the retract "cannot see" is equally consistent with the retraction being present in one view and absent in another, rather than never generated.

    Happy to run a discriminating repro against a build if that's useful; we have the production ledger where this occurs and can bracket reads around a publish.

  2. IX-Erich commented on Aug 6, 2026

    @IX-Erich
    Author

    Closing this — we ran the bisect the issue calls for above, and the behaviour is already fixed in 4.1.3.

    Stock images, identical harness and host, arms run back-to-back, 30 subjects each (/insert BACKLOG → /upsert IN_PROGRESS → /upsert DONE after ~600 filler commits):

    stock image subjects accumulated (of 30)
    4.1.0 23
    4.1.1 22
    4.1.2 22
    4.1.3 0
    4.1.4 0 (confirmed on a re-run)

    4.1.0 was re-run last as a live positive control and still reproduced (21/30), so the zeros are not environmental drift.

    The fix looks like #1508 ("Fix duplicate triples from re-asserted facts in the V6 incremental indexer", shipped in 4.1.3) — dedup_fact_lifecycles resolving each fact's in-window event sequence to a single final op is precisely the behaviour missing here.

    One repro note that may be useful to anyone hitting this on ≤4.1.2, since it cost us several false negatives: it races in-flight index publishing, so it needs FLUREE_REINDEX_MIN_BYTES in a middle band (250000 for us) plus sustained concurrent write load. Setting it low (indexer keeps pace) or very high (no publishes at all) both read clean, as do serial writes — maximum novelty depth alone does not reproduce it.

    Apologies for the noise; this was filed against 4.1.0 without first checking the newer releases.

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