• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

knowledgepixels / nanopub-query / 30987047601

05 Aug 2026 07:57AM UTC coverage: 61.613% (+1.7%) from 59.947%
30987047601

Pull #159

github

web-flow
Merge 9b6c82124 into b478d344d
Pull Request #159: fix(spaces): stop acting on failed reads, and self-heal a half-built space state

661 of 1220 branches covered (54.18%)

Branch coverage included in aggregate %.

1944 of 3008 relevant lines covered (64.63%)

9.79 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

35.29
src/main/java/com/knowledgepixels/query/AuthorityResolver.java
1
package com.knowledgepixels.query;
2

3
import java.util.ArrayList;
4
import java.util.List;
5
import java.util.Optional;
6
import java.util.Set;
7

8
import org.eclipse.rdf4j.common.transaction.IsolationLevels;
9
import org.eclipse.rdf4j.model.IRI;
10
import org.eclipse.rdf4j.model.Statement;
11
import org.eclipse.rdf4j.model.Value;
12
import org.eclipse.rdf4j.model.ValueFactory;
13
import org.eclipse.rdf4j.model.impl.SimpleValueFactory;
14
import org.eclipse.rdf4j.model.vocabulary.FOAF;
15
import org.eclipse.rdf4j.model.vocabulary.RDF;
16
import org.eclipse.rdf4j.query.BindingSet;
17
import org.eclipse.rdf4j.query.QueryLanguage;
18
import org.eclipse.rdf4j.query.TupleQueryResult;
19
import org.eclipse.rdf4j.repository.RepositoryConnection;
20
import org.eclipse.rdf4j.repository.RepositoryResult;
21
import org.nanopub.vocabulary.NPA;
22
import org.nanopub.vocabulary.NPX;
23
import org.slf4j.Logger;
24
import org.slf4j.LoggerFactory;
25

26
import com.knowledgepixels.query.vocabulary.GEN;
27
import com.knowledgepixels.query.vocabulary.NPAT;
28
import com.knowledgepixels.query.vocabulary.SpacesVocab;
29

30
/**
31
 * Drives the space-state materialization pipeline. Three entry points scheduled
32
 * by {@code MainVerticle}:
33
 * <ul>
34
 *   <li>{@link #tick()} — detects trust-state flips (full build) and otherwise
35
 *       advances the current space-state graph by an {@link #runIncrementalCycle
36
 *       incremental cycle} bounded by {@code (processedUpTo, currentLoadCounter]}.</li>
37
 *   <li>{@link #periodicRebuildTick()} — checks the {@code npa:needsFullRebuild}
38
 *       flag set by structural invalidations and re-runs the full build into a
39
 *       fresh graph, atomically flips the pointer, drops the old graph.</li>
40
 *   <li>{@link #cleanOrphans()} — startup cleanup of {@code npass:*} graphs the
41
 *       pointer isn't referencing.</li>
42
 * </ul>
43
 *
44
 * <p>Incremental cycle order: invalidation DELETEs (admin RI / RoleAssignment /
45
 * non-admin RI) → mirror-step delta is implicit (rebuilt only on full build) →
46
 * per-tier INSERTs (admin → alias → attachment → maintainer → member → observer) →
47
 * late-arrival sweep (re-run downstream tiers without the load-number filter
48
 * iff this cycle added any structural rows). Sets {@code npa:needsFullRebuild}
49
 * when an admin RI / RoleAssignment / RoleDeclaration was invalidated; periodic
50
 * worker turns the flag into a from-scratch rebuild.
51
 *
52
 * <p>See {@code doc/design-space-repositories.md} — this implements the "Full
53
 * build", "Incremental cycle", and "Periodic full rebuild" procedures.
54
 */
55
public final class AuthorityResolver {
56

57
    private static final Logger logger = LoggerFactory.getLogger(AuthorityResolver.class);
9✔
58

59
    private static final ValueFactory vf = SimpleValueFactory.getInstance();
6✔
60

61
    private static final String SPACES_REPO = "spaces";
62
    private static final String TRUST_REPO = "trust";
63

64
    /** NPA constants pulled in locally (trust-side). */
65
    private static final IRI NPA_HAS_CURRENT_TRUST_STATE =
9✔
66
            vf.createIRI(NPA.NAMESPACE, "hasCurrentTrustState");
6✔
67
    private static final IRI NPA_ACCOUNT_STATE = vf.createIRI(NPA.NAMESPACE, "AccountState");
15✔
68
    private static final IRI NPA_AGENT = vf.createIRI(NPA.NAMESPACE, "agent");
15✔
69
    private static final IRI NPA_PUBKEY = vf.createIRI(NPA.NAMESPACE, "pubkey");
15✔
70
    private static final IRI NPA_TRUST_STATUS = vf.createIRI(NPA.NAMESPACE, "trustStatus");
15✔
71
    private static final IRI NPA_VIA_NANOPUB = vf.createIRI(NPA.NAMESPACE, "viaNanopub");
15✔
72
    private static final IRI NPA_LOADED = vf.createIRI(NPA.NAMESPACE, "loaded");
15✔
73
    private static final IRI NPA_TO_LOAD = vf.createIRI(NPA.NAMESPACE, "toLoad");
15✔
74

75
    /**
76
     * Trust-approved set: rows with one of these {@code npa:trustStatus} values
77
     * are mirrored into the space-state graph. Per
78
     * {@code doc/design-trust-state-repos.md}, these are the two "authority-
79
     * approving" statuses; {@code npa:contested}, {@code npa:skipped}, and the
80
     * transient statuses are distinct values of the same predicate and are
81
     * excluded automatically by this positive-list filter.
82
     */
83
    private static final Set<IRI> APPROVED_SET = Set.of(NPA_LOADED, NPA_TO_LOAD);
15✔
84

85
    private static AuthorityResolver instance;
86

87
    /** Returns the singleton. */
88
    public static synchronized AuthorityResolver get() {
89
        if (instance == null) {
6✔
90
            instance = new AuthorityResolver();
12✔
91
        }
92
        return instance;
6✔
93
    }
94

95
    private AuthorityResolver() {
6✔
96
    }
3✔
97

98
    // ---------------- Operational metrics snapshot ----------------
99
    //
100
    // Updated at the end of each runFullBuild / runIncrementalCycle, read by
101
    // MetricsCollector via the get*() accessors below. volatile is enough —
102
    // writers serialise via the synchronized methods, and readers (Prometheus
103
    // scrapes) only need most-recent visibility, not transactional consistency
104
    // across the snapshot. Defaults to zero values so a scrape that races a
105
    // boot before the first cycle returns 0, not NaN.
106

107
    private volatile TierSubjectTotals lastSubjectTotals = new TierSubjectTotals(0L, 0L, 0L);
24✔
108
    private volatile long lastInsertedTriplesTotal;
109
    private volatile long lastFullBuildDurationMs;
110
    private volatile long lastIncrementalCycleDurationMs;
111
    private volatile long lastProcessedUpToLag;
112

113
    public TierSubjectTotals getLastSubjectTotals() { return lastSubjectTotals; }
9✔
114
    public long getLastInsertedTriplesTotal() { return lastInsertedTriplesTotal; }
9✔
115
    public long getLastFullBuildDurationMs() { return lastFullBuildDurationMs; }
9✔
116
    public long getLastIncrementalCycleDurationMs() { return lastIncrementalCycleDurationMs; }
9✔
117
    public long getLastProcessedUpToLag() { return lastProcessedUpToLag; }
9✔
118

119
    /**
120
     * Raised when the space-state bookkeeping in the {@code spaces} repo cannot be
121
     * <em>read</em>, as opposed to being legitimately absent.
122
     *
123
     * <p>The distinction is the whole point. Before 2026-08-05 every reader here
124
     * collapsed both cases onto the same value — {@code null} pointer, load counter
125
     * {@code 0}, {@code processedUpTo} {@code -1} — so a degraded RDF4J looked
126
     * identical to a fresh install. On that day RDF4J was answering reads with
127
     * {@code Read timed out}; {@link #tick()} saw a {@code null} pointer, logged a
128
     * "trust-state flip" that had not happened, and ran a full build whose every
129
     * source read also failed. The build inserted nothing, published the resulting
130
     * empty graph, and dropped the previous good one — 2730 triples of live space
131
     * state, on a query server that then served zero rows to every state query for
132
     * hours. A sibling instance that stayed healthy still had all of it.
133
     *
134
     * <p>Throwing instead lets the caller abort. Doing nothing this tick is always
135
     * safe; acting on a failed read is not.
136
     */
137
    static class SpaceStateUnavailableException extends RuntimeException {
138
        SpaceStateUnavailableException(String message, Throwable cause) {
139
            super(message, cause);
12✔
140
        }
3✔
141
    }
142

143
    // ---------------- Public entry points ----------------
144

145
    /**
146
     * Poll entry point. Behaviour:
147
     * <ul>
148
     *   <li>If no current space-state graph or the trust state has flipped → full build.</li>
149
     *   <li>Otherwise → {@link #runIncrementalCycle incremental cycle} on the load-number
150
     *       delta {@code (processedUpTo, currentLoadCounter]}. No-op if {@code
151
     *       processedUpTo == currentLoadCounter}.</li>
152
     * </ul>
153
     * Safe to call repeatedly on a schedule. Gated by {@link FeatureFlags#spacesEnabled()}.
154
     */
155
    public void tick() {
156
        if (!FeatureFlags.spacesEnabled()) return;
6!
157
        String trustStateHash = TrustStateRegistry.get().getCurrentHash().orElse(null);
18✔
158
        if (trustStateHash == null) {
6✔
159
            logger.debug("AuthorityResolver.tick: no current trust state yet — skipping");
9✔
160
            return;
3✔
161
        }
162
        // Any of the reads below may throw SpaceStateUnavailableException. Let it
163
        // propagate: the caller logs "AuthorityResolver tick failed" and we retry on
164
        // the next tick with the state untouched.
165
        IRI currentGraph = getCurrentSpaceStateGraph();
9✔
166
        String currentGraphName = (currentGraph == null) ? null
6!
167
                : currentGraph.stringValue().substring(SpacesVocab.NPASS_NAMESPACE.length());
18✔
168
        if (currentGraphName == null) {
6!
169
            logger.info("AuthorityResolver.tick: no current space-state graph; running full build");
×
170
            runFullBuild(trustStateHash);
×
171
            return;
×
172
        }
173
        if (!currentGraphName.startsWith(trustStateHash + "_")) {
15!
174
            logger.info("AuthorityResolver.tick: trust-state flip detected (now {}); running full build",
×
175
                    abbrev(trustStateHash));
×
176
            runFullBuild(trustStateHash);
×
177
            return;
×
178
        }
179
        // A pointer at a graph that never got its processedUpTo stamp means the build
180
        // that published it did not finish. runIncrementalCycle used to log "missing
181
        // processedUpTo; skipping" and return — every 2 s, forever, with every
182
        // state-backed query answering empty in the meantime. Rebuild instead.
183
        if (readProcessedUpTo(currentGraph) < 0) {
18✔
184
            logger.warn("AuthorityResolver.tick: current space-state graph {} has no processedUpTo "
12✔
185
                    + "stamp (incomplete or damaged build); running full build", currentGraph);
186
            runFullBuild(trustStateHash);
9✔
187
            return;
3✔
188
        }
189
        runIncrementalCycle(currentGraph);
9✔
190
    }
3✔
191

192
    /**
193
     * Periodic worker. If {@code npa:needsFullRebuild} was raised by an
194
     * incremental cycle's structural DELETE, runs a from-scratch rebuild into
195
     * a fresh space-state graph (using the current trust-state hash and load
196
     * counter) and clears the flag. No-op when the flag is not set. Safe to
197
     * call concurrently with {@link #tick()} when both are scheduled on the
198
     * same single-threaded executor.
199
     */
200
    public void periodicRebuildTick() {
201
        if (!FeatureFlags.spacesEnabled()) return;
×
202
        if (!readNeedsFullRebuild()) return;
×
203
        String trustStateHash = TrustStateRegistry.get().getCurrentHash().orElse(null);
×
204
        if (trustStateHash == null) {
×
205
            logger.debug("AuthorityResolver.periodicRebuildTick: no current trust state — deferring");
×
206
            return;
×
207
        }
208
        logger.info("AuthorityResolver.periodicRebuildTick: needsFullRebuild flag set; rebuilding");
×
209
        runFullBuild(trustStateHash);
×
210
        clearNeedsFullRebuild();
×
211
    }
×
212

213
    /**
214
     * Startup cleanup: drop any {@code npass:*} graph that the
215
     * {@code npa:hasCurrentSpaceState} pointer isn't pointing at. Orphans come
216
     * from crashes mid-build. Safe to call at any time; idempotent.
217
     */
218
    public synchronized void cleanOrphans() {
219
        if (!FeatureFlags.spacesEnabled()) return;
6!
220
        IRI current;
221
        try {
222
            current = getCurrentSpaceStateGraph();
×
223
        } catch (SpaceStateUnavailableException ex) {
3✔
224
            // Every npass:* graph is "not the current one" when the pointer cannot be
225
            // read, so continuing here would drop the live state along with the
226
            // orphans. Skipping costs nothing: orphans are inert, and the next start
227
            // will clean them up.
228
            logger.warn("AuthorityResolver.cleanOrphans: cannot read the current-state pointer, "
12✔
229
                    + "skipping so orphan cleanup cannot delete the live graph: {}", ex.toString());
3✔
230
            return;
3✔
231
        }
×
232
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
233
            int dropped = 0;
×
234
            try (RepositoryResult<org.eclipse.rdf4j.model.Resource> ctxs = conn.getContextIDs()) {
×
235
                List<IRI> toDrop = new ArrayList<>();
×
236
                while (ctxs.hasNext()) {
×
237
                    org.eclipse.rdf4j.model.Resource ctx = ctxs.next();
×
238
                    if (!(ctx instanceof IRI iri)) continue;
×
239
                    if (!iri.stringValue().startsWith(SpacesVocab.NPASS_NAMESPACE)) continue;
×
240
                    if (iri.equals(current)) continue;
×
241
                    toDrop.add(iri);
×
242
                }
×
243
                for (IRI iri : toDrop) {
×
244
                    conn.begin(IsolationLevels.SERIALIZABLE);
×
245
                    conn.clear(iri);
×
246
                    conn.commit();
×
247
                    dropped++;
×
248
                    logger.info("AuthorityResolver.cleanOrphans: dropped orphan graph {}", iri);
×
249
                }
×
250
            }
251
            if (dropped == 0) {
×
252
                logger.debug("AuthorityResolver.cleanOrphans: no orphan space-state graphs");
×
253
            }
254
        } catch (Exception ex) {
×
255
            logger.info("AuthorityResolver.cleanOrphans: failed: {}", ex.toString());
×
256
        }
×
257
    }
×
258

259
    // ---------------- Full build ----------------
260

261
    /**
262
     * Mutex-protected full build of the space-state graph for the given trust
263
     * state. Captures {@code M = currentLoadCounter}, mirrors trust-approved
264
     * rows, (PR 2b: runs per-tier UPDATE loops from scratch), stamps
265
     * {@code processedUpTo = M}, flips the pointer, drops the previous graph.
266
     */
267
    synchronized void runFullBuild(String trustStateHash) {
268
        long startNanos = System.nanoTime();
6✔
269
        long loadCounter = getCurrentLoadCounter();
9✔
270
        IRI newGraph = SpacesVocab.forSpaceState(trustStateHash, loadCounter);
12✔
271
        IRI oldGraph = getCurrentSpaceStateGraph();
9✔
272
        boolean rebuildInPlace = newGraph.equals(oldGraph);
12✔
273
        if (rebuildInPlace) {
6✔
274
            // "Already current" is only true if that graph was actually finished.
275
            // Without the processedUpTo check this early return was the second half
276
            // of the 2026-08-05 trap: once a damaged graph was published, the pointer
277
            // name still matched, so every subsequent full build returned here and
278
            // the instance could never repair itself.
279
            if (readProcessedUpTo(oldGraph) >= 0) {
18✔
280
                logger.debug("AuthorityResolver.runFullBuild: already current at {}", newGraph);
12✔
281
                return;
3✔
282
            }
283
            logger.warn("AuthorityResolver.runFullBuild: {} is the current graph but has no "
12✔
284
                    + "processedUpTo stamp; rebuilding it in place", newGraph);
285
            dropGraph(newGraph);
9✔
286
        }
287

288
        // 1. Mirror trust-approved rows into the new graph.
289
        int mirrored = mirrorTrustState(trustStateHash, newGraph);
15✔
290

291
        // 2. Per-tier UPDATE loops (from scratch: lastProcessed = -1 so the
292
        //    delta filter FILTER(?ln > ?lastProcessed) includes everything).
293
        TierInsertedTriples counts = runAllTierLoops(newGraph, -1);
15✔
294

295
        // 2b. Refuse to publish an empty build over a state we already have — but only
296
        // when the emptiness cannot be true.
297
        //
298
        // Steps 4 and 5 below are destructive, so a build that read nothing must not
299
        // reach them. The trap is that "produced nothing" has two causes: every source
300
        // read failed, or the sources really are empty. Refusing in the second case
301
        // would pin a stale space state forever, and stale trust data is
302
        // over-permissive — revocations would stop propagating. That is the wrong way
303
        // to fail for a trust-derived state.
304
        //
305
        // So the condition is: nothing was produced *while the trust state still has
306
        // content to mirror*. That is the shape of a read failure. A genuinely empty
307
        // trust state yields an empty build and is published normally.
308
        //
309
        // Only guarded when a previous state exists: a genuinely empty first build on
310
        // a fresh instance has nothing to lose and must still be allowed to publish.
311
        //
312
        // Note this would NOT have fired on 2026-08-05: that build reported
313
        // subspace-prefix=2478, so it was not empty. The wipe there came from the
314
        // registry's trust state collapsing (correctly reflected) plus 2478 triples
315
        // that were reported inserted and then measured as zero. This guard is for the
316
        // total-read-failure case, which the same outage came close to several times.
317
        long insertedTotal = totalInserted(counts);
9✔
318
        if (mirrored == 0 && insertedTotal == 0 && oldGraph != null
30!
319
                && trustStateHasContent(trustStateHash)) {
6✔
320
            logger.error("AuthorityResolver.runFullBuild: build produced an empty state graph "
12✔
321
                    + "(mirrored=0, inserted=0) while trust state {} still has content and {} "
322
                    + "holds the current state — refusing to flip the pointer or drop it. "
323
                    + "This is the shape of a total read failure; the next tick will retry.",
324
                    abbrev(trustStateHash), oldGraph);
6✔
325
            if (!rebuildInPlace) {
6!
326
                dropGraph(newGraph);
9✔
327
            }
328
            return;
3✔
329
        }
330

331
        // 3. Stamp processedUpTo inside the new graph.
332
        writeProcessedUpTo(newGraph, loadCounter);
12✔
333

334
        // 4. Flip the current-space-state pointer.
335
        flipPointer(newGraph);
9✔
336

337
        // 5. Drop the old graph if a *different* one existed. Dropping it when
338
        //    rebuilding in place would delete what we just built.
339
        if (oldGraph != null && !rebuildInPlace) {
12✔
340
            dropGraph(oldGraph);
9✔
341
        }
342

343
        TierSubjectTotals totals = computeTierSubjectTotals(newGraph);
12✔
344
        long durationMs = (System.nanoTime() - startNanos) / 1_000_000L;
18✔
345
        lastSubjectTotals = totals;
9✔
346
        lastInsertedTriplesTotal = insertedTotal;
9✔
347
        lastFullBuildDurationMs = durationMs;
9✔
348
        lastProcessedUpToLag = 0L;
9✔
349
        logger.info("AuthorityResolver: full build complete — graph={} mirrored={} rows loadCounter={} "
36✔
350
                        + "subjects: adminRIs={} attachmentRAs={} nonAdminRIs={} "
351
                        + "(inserted-triples: admin={} alias={} preset-attachment={} preset-assignment-ref={} attachment={} maintainer={} member={} observer={} "
352
                        + "subspace={} subspace-prefix={} maintained-resource={} governing-space-ref={}) durationMs={}",
353
                newGraph, mirrored, loadCounter,
30✔
354
                totals.adminRIs(), totals.attachmentRAs(), totals.nonAdminRIs(),
57✔
355
                counts.admin, counts.alias, counts.presetAttachment, counts.presetAssignmentRef, counts.attachment, counts.maintainer, counts.member, counts.observer,
144✔
356
                counts.subSpace, counts.subSpacePrefix, counts.maintainedResource, counts.governingSpaceRef,
69✔
357
                durationMs);
6✔
358
    }
3✔
359

360
    // ---------------- Incremental cycle ----------------
361

362
    /**
363
     * Single delta cycle on the current space-state graph. Bounded by
364
     * {@code (processedUpTo, currentLoadCounter]}; no-op if the range is empty.
365
     *
366
     * <p>Order:
367
     * <ol>
368
     *   <li>Apply invalidation DELETEs (admin RI, RoleAssignment, non-admin RI)
369
     *       and the RoleDeclaration ASK. Any DELETE on a structural kind sets
370
     *       {@code npa:needsFullRebuild} to bound the staleness from sticky
371
     *       downstream entries; the periodic worker turns that into a from-scratch
372
     *       rebuild on its next pass.</li>
373
     *   <li>Run per-tier INSERTs in the same order as the full build.</li>
374
     *   <li>Late-arrival sweep: if any structural row was added, re-run downstream
375
     *       tier INSERTs with {@code lastProcessed = -1} to catch candidates whose
376
     *       enabling event landed in this same cycle. Dedup filters protect
377
     *       against double-insert.</li>
378
     *   <li>Bump {@code processedUpTo} to {@code currentLoadCounter}.</li>
379
     * </ol>
380
     */
381
    synchronized void runIncrementalCycle(IRI graph) {
382
        long startNanos = System.nanoTime();
×
383
        long currentLoadCounter = getCurrentLoadCounter();
×
384
        long lastProcessed = readProcessedUpTo(graph);
×
385
        if (lastProcessed < 0) {
×
386
            // tick() now catches this first and rebuilds, so reaching here means a
387
            // direct caller. Still refuse to run a delta against a graph that was
388
            // never finished — the deltas would be layered onto missing base rows.
389
            logger.warn("AuthorityResolver.runIncrementalCycle: missing processedUpTo on {}; "
×
390
                    + "skipping (a full build is needed to repair this graph)", graph);
391
            return;
×
392
        }
393
        lastProcessedUpToLag = currentLoadCounter - lastProcessed;
×
394
        if (currentLoadCounter <= lastProcessed) {
×
395
            logger.debug("AuthorityResolver.runIncrementalCycle: caught up at load {} on {}",
×
396
                    currentLoadCounter, graph);
×
397
            return;
×
398
        }
399

400
        boolean structuralInvalidation = applyInvalidations(graph, lastProcessed);
×
401
        TierInsertedTriples counts = runAllTierLoops(graph, lastProcessed);
×
402
        boolean structuralAdds = (counts.admin > 0)
×
403
                || (counts.alias > 0)
404
                || (counts.presetAttachment > 0)
405
                || (counts.attachment > 0)
406
                || (counts.subSpace > 0)
407
                || newRoleDeclarationsArrived(lastProcessed)
×
408
                || newPresetAssignmentsArrived(lastProcessed);
×
409
        if (structuralAdds) {
×
410
            // Late-arrival sweep: leaf tiers (attachment/maintainer/member/observer)
411
            // can promote candidates whose enabling event arrived in this same cycle.
412
            // Sub-space admit is also re-run here for Mode-B late-arrival (a new
413
            // partner declaration can validate an older primary that the regular
414
            // pass's load-number filter excluded). The URL-prefix fallback also
415
            // re-runs so newly-orphaned children pick up derived edges. Skip the
416
            // admin tier — its only enabling event is the admin grant itself,
417
            // already handled by the regular pass.
418
            TierInsertedTriples lateCounts = runDownstreamWithoutLoadFilter(graph);
×
419
            counts.alias              += lateCounts.alias;
×
420
            counts.presetAttachment   += lateCounts.presetAttachment;
×
421
            counts.presetAssignmentRef += lateCounts.presetAssignmentRef;
×
422
            counts.attachment         += lateCounts.attachment;
×
423
            counts.maintainer         += lateCounts.maintainer;
×
424
            counts.member             += lateCounts.member;
×
425
            counts.observer           += lateCounts.observer;
×
426
            counts.subSpace           += lateCounts.subSpace;
×
427
            counts.subSpacePrefix     += lateCounts.subSpacePrefix;
×
428
            counts.governingSpaceRef  += lateCounts.governingSpaceRef;
×
429
            counts.maintainedResource += lateCounts.maintainedResource;
×
430
        }
431

432
        writeProcessedUpTo(graph, currentLoadCounter);
×
433

434
        TierSubjectTotals totals = computeTierSubjectTotals(graph);
×
435
        long durationMs = (System.nanoTime() - startNanos) / 1_000_000L;
×
436
        lastSubjectTotals = totals;
×
437
        lastInsertedTriplesTotal = (long) counts.admin + counts.alias + counts.presetAttachment
×
438
                + counts.presetAssignmentRef
439
                + counts.attachment + counts.maintainer + counts.member + counts.observer
440
                + counts.subSpace + counts.subSpacePrefix + counts.maintainedResource
441
                + counts.governingSpaceRef;
442
        lastIncrementalCycleDurationMs = durationMs;
×
443
        logger.info("AuthorityResolver: incremental cycle complete — graph={} delta=({}, {}] "
×
444
                        + "subjects: adminRIs={} attachmentRAs={} nonAdminRIs={} "
445
                        + "(inserted-triples: admin={} alias={} preset-attachment={} preset-assignment-ref={} attachment={} maintainer={} member={} observer={} "
446
                        + "subspace={} subspace-prefix={} maintained-resource={} governing-space-ref={}) "
447
                        + "structuralInvalidation={} structuralAdds={} durationMs={}",
448
                graph, lastProcessed, currentLoadCounter,
×
449
                totals.adminRIs(), totals.attachmentRAs(), totals.nonAdminRIs(),
×
450
                counts.admin, counts.alias, counts.presetAttachment, counts.presetAssignmentRef, counts.attachment, counts.maintainer, counts.member, counts.observer,
×
451
                counts.subSpace, counts.subSpacePrefix, counts.maintainedResource, counts.governingSpaceRef,
×
452
                structuralInvalidation, structuralAdds, durationMs);
×
453
    }
×
454

455
    /**
456
     * Runs the four invalidation-DELETE / ASK steps. Sets {@code npa:needsFullRebuild}
457
     * when admin-RI, RoleAssignment, or RoleDeclaration invalidations matched (the
458
     * three structural kinds). Leaf-tier RI deletes don't set the flag.
459
     *
460
     * @return true iff at least one structural kind was invalidated
461
     */
462
    boolean applyInvalidations(IRI graph, long lastProcessed) {
463
        boolean structural = false;
×
464
        if (wouldInvalidate(graph, lastProcessed, /*adminPinned=*/ true,
×
465
                            adminInvalidationCheckWhere(graph, lastProcessed))) {
×
466
            executeUpdate(adminInvalidationDelete(graph, lastProcessed));
×
467
            structural = true;
×
468
        }
469
        if (wouldInvalidate(graph, lastProcessed, /*adminPinned=*/ false,
×
470
                            roleAssignmentInvalidationCheckWhere(graph, lastProcessed))) {
×
471
            executeUpdate(roleAssignmentInvalidationDelete(graph, lastProcessed));
×
472
            structural = true;
×
473
        }
474
        // Role-declaration invalidation is deliberately NOT acted on (see
475
        // nonAdminTierUpdate): a role assignment is governed by the admin-validated
476
        // attachment, not by the declaration author's later supersession/retraction, so
477
        // an invalidated RD neither deletes rows nor triggers a rebuild.
478
        // Sub-space declarations are structural — invalidating one (Mode A) or one
479
        // of two co-declarations (Mode B) changes the validated parent/child
480
        // topology. The DELETE removes the per-declaration row; the convenience-edge
481
        // cleanup then drops the now-unbacked direct triples (issue #125 finding #5)
482
        // instead of leaving them sticky until the periodic rebuild. The structural
483
        // flag still fires so downstream rows derived through a removed edge stay
484
        // rebuild-bounded.
485
        if (wouldInvalidate(graph, lastProcessed, /*adminPinned=*/ false,
×
486
                            subSpaceInvalidationCheckWhere(graph, lastProcessed))) {
×
487
            executeUpdate(subSpaceInvalidationDelete(graph, lastProcessed));
×
488
            executeUpdate(subSpaceConvenienceEdgeCleanup(graph, lastProcessed));
×
489
            structural = true;
×
490
        }
491
        // Space-alias declarations are structural — invalidating one removes an
492
        // owl:sameAs edge that feeds the admin-authority closure (issue #113). The
493
        // DELETE removes the per-declaration row; the convenience-edge cleanup then
494
        // drops the now-unbacked npa:sameAsSpace edge (issue #125 finding #5 — the
495
        // load-bearing case), so admin authority can no longer outlive a retraction
496
        // until the next periodic rebuild.
497
        if (wouldInvalidate(graph, lastProcessed, /*adminPinned=*/ false,
×
498
                            aliasInvalidationCheckWhere(graph, lastProcessed))) {
×
499
            executeUpdate(aliasInvalidationDelete(graph, lastProcessed));
×
500
            executeUpdate(aliasConvenienceEdgeCleanup(graph, lastProcessed));
×
501
            structural = true;
×
502
        }
503
        // Preset-derived RoleAssignment removal (issue #302). NOT npx:invalidates: a newer
504
        // admin-authored same-(preset,resource) assignment supersedes by dct:created (a
505
        // gen:DeactivatedPresetAssignment, or any newer assignment that is no longer active).
506
        // Structural — sticky downstream non-admin RIs derived through a removed attachment
507
        // are bounded by the periodic full rebuild. The DELETE is scoped by
508
        // npa:derivedFromPreset so directly-published gen:hasRole attachments are never
509
        // touched; the §4.3 re-INSERT re-materializes only currently-active pairs in the same
510
        // cycle. See doc/design-preset-role-materialization.md §4.4.
511
        if (wouldInvalidate(graph, lastProcessed, /*adminPinned=*/ false,
×
512
                            presetDeactivationCheckWhere(graph, lastProcessed))) {
×
513
            executeUpdate(presetDeactivationDelete(graph, lastProcessed));
×
514
            structural = true;
×
515
        }
516
        // Admin role-instantiation revocation (issue #129). STRUCTURAL — admin RIs feed every
517
        // downstream tier, so a removed admin must bound the staleness via a full rebuild
518
        // (mirrors adminInvalidationDelete). Root admins are exempt inside the check-where.
519
        if (wouldInvalidate(graph, lastProcessed, /*adminPinned=*/ true,
×
520
                            adminRevocationCheckWhere(graph, lastProcessed))) {
×
521
            executeUpdate(adminRevocationDelete(graph, lastProcessed));
×
522
            structural = true;
×
523
        }
524
        // Role detachment (issue #129). STRUCTURAL — removing a (ref, role) attachment
525
        // (direct or preset-derived) cascades to the instantiations anchored on it, bounded
526
        // by the periodic full rebuild. The attachment-tier inline filters then keep the
527
        // detached role suppressed until a newer attachment / preset assignment out-ranks it.
528
        if (wouldInvalidate(graph, lastProcessed, /*adminPinned=*/ false,
×
529
                            roleDetachmentCheckWhere(graph, lastProcessed))) {
×
530
            executeUpdate(roleDetachmentDelete(graph, lastProcessed));
×
531
            structural = true;
×
532
        }
533
        // Non-admin role-instantiation revocation (issue #129), run once per tier so the
534
        // authorization arms are the compile-time set for that tier (mirrors the inline
535
        // suppression filter). STRUCTURAL: a revoked maintainer or member is a sub-granting
536
        // authority — members/observers they granted are validated via the maint-pub /
537
        // member-pub arms of nonAdminTierUpdate, so removing the revoked agent's own RI must
538
        // schedule a full rebuild to re-evaluate (and drop) those now-unauthorized downstream
539
        // grants. The inline suppression filter prevents re-materialization on that rebuild.
540
        for (IRI revTier : List.of(GEN.MAINTAINER_ROLE, GEN.MEMBER_ROLE, GEN.OBSERVER_ROLE)) {
×
541
            if (wouldInvalidate(graph, lastProcessed, /*adminPinned=*/ false,
×
542
                                roleRevocationCheckWhere(graph, lastProcessed, revTier))) {
×
543
                executeUpdate(roleRevocationDelete(graph, lastProcessed, revTier));
×
544
                structural = true;
×
545
            }
546
        }
×
547
        // Leaf-tier RI deletes — no flag.
548
        executeUpdate(leafTierInvalidationDelete(graph, lastProcessed));
×
549
        // Ref-scoped preset-assignment listing stamps whose assignment nanopub was
550
        // hard-retracted (issue #122) — no flag (display leaf, nothing downstream).
551
        executeUpdate(presetAssignmentRefInvalidationDelete(graph, lastProcessed));
×
552
        // Maintained-resource declaration deletes — no flag (leaf relation, no
553
        // downstream caches to bound). The per-declaration delete removes the row; the
554
        // convenience-edge cleanup drops the now-unbacked isMaintainedBy edges (issue
555
        // #125 finding #5). Guarded so the orphan-sweep only scans when something was
556
        // actually invalidated (the delete itself was already a no-op otherwise).
557
        if (wouldInvalidate(graph, lastProcessed, /*adminPinned=*/ false,
×
558
                            maintainedResourceInvalidationCheckWhere(graph, lastProcessed))) {
×
559
            executeUpdate(maintainedResourceInvalidationDelete(graph, lastProcessed));
×
560
            executeUpdate(maintainedResourceConvenienceEdgeCleanup(graph, lastProcessed));
×
561
        }
562
        if (structural) setNeedsFullRebuild();
×
563
        return structural;
×
564
    }
565

566
    /**
567
     * Runs the four leaf tiers (attachment/maintainer/member/observer) with
568
     * {@code lastProcessed = -1} so the load-number filter on the candidate
569
     * side admits everything. Dedup filters in the tier templates prevent
570
     * double-insert. Used by the late-arrival sweep.
571
     */
572
    TierInsertedTriples runDownstreamWithoutLoadFilter(IRI graph) {
573
        TierInsertedTriples c = new TierInsertedTriples();
×
574
        // Alias late-arrival: catches alias declarations whose canonical admin grant
575
        // became valid only in this same cycle (the load-number filter on the
576
        // declaration's nanopub would otherwise exclude it). Runs first so the
577
        // attachment / role tiers below see this cycle's fresh npa:sameAsSpace edges.
578
        c.alias = runTierLabeled("alias(late)", graph, aliasAdmitUpdate(graph, -1));
×
579
        // Sub-space late-arrival: catches Mode-B candidates whose primary
580
        // declaration is older than lastProcessed but whose partner just landed.
581
        c.subSpace = runTierLabeled("subspace(late)", graph,
×
582
                subSpaceAdmitUpdate(graph, -1));
×
583
        // Maintained-resource late-arrival: catches declarations that landed
584
        // before the publisher's admin grant became valid in this state.
585
        c.maintainedResource = runTierLabeled("maintained-resource(late)", graph,
×
586
                maintainedResourceAdmitUpdate(graph, -1));
×
587
        // URL-prefix fallback: re-run after the late-arrival sub-space admit so
588
        // any newly-validated children get their fallback edges suppressed (for
589
        // future inserts) and any newly-orphaned children pick up fallback edges.
590
        c.subSpacePrefix = runTierLabeled("subspace-prefix(late)", graph,
×
591
                subSpacePrefixFallbackUpdate(graph));
×
592
        // Reflexive governing-space-ref late sweep (issue #130): catches refs whose
593
        // SpaceRef aggregate became visible only this cycle. Self-healing dedup.
594
        c.governingSpaceRef = runTierLabeled("governing-space-ref(late)", graph,
×
595
                governingSpaceRefReflexiveUpdate(graph));
×
596
        // Preset-attachment late-arrival: catches assignments whose preset declaration or
597
        // admin grant only became valid in this same cycle. Runs before attachment(late)
598
        // so the non-admin late tiers below see this cycle's fresh preset-derived RAs.
599
        c.presetAttachment = runTierLabeled("preset-attachment(late)", graph,
×
600
                presetAttachmentValidationUpdate(graph, -1));
×
601
        // Ref-scoped preset-assignment late stamp: catches assignments whose authorizing
602
        // admin grant only became valid this cycle (the load filter would skip the older
603
        // assignment nanopub). Mirrors the preset-attachment late sweep above.
604
        c.presetAssignmentRef = runTierLabeled("preset-assignment-ref(late)", graph,
×
605
                presetAssignmentRefStampUpdate(graph, -1));
×
606
        c.attachment = runTierLabeled("attachment(late)", graph,
×
607
                attachmentValidationUpdate(graph, -1));
×
608
        c.maintainer = runTierLabeled("maintainer(late)", graph,
×
609
                nonAdminTierUpdate(graph, -1, GEN.MAINTAINER_ROLE, PUBLISHER_IS_ADMIN));
×
610
        c.member = runTierLabeled("member(admin-pub,late)", graph,
×
611
                nonAdminTierUpdate(graph, -1, GEN.MEMBER_ROLE, PUBLISHER_IS_ADMIN));
×
612
        c.member += runTierLabeled("member(maint-pub,late)", graph,
×
613
                nonAdminTierUpdate(graph, -1,
×
614
                        GEN.MEMBER_ROLE, publisherIsTieredRole(GEN.MAINTAINER_ROLE)));
×
615
        c.observer = runTierLabeled("observer(admin-pub,late)", graph,
×
616
                nonAdminTierUpdate(graph, -1, GEN.OBSERVER_ROLE, PUBLISHER_IS_ADMIN));
×
617
        c.observer += runTierLabeled("observer(maint-pub,late)", graph,
×
618
                nonAdminTierUpdate(graph, -1,
×
619
                        GEN.OBSERVER_ROLE, publisherIsTieredRole(GEN.MAINTAINER_ROLE)));
×
620
        c.observer += runTierLabeled("observer(member-pub,late)", graph,
×
621
                nonAdminTierUpdate(graph, -1,
×
622
                        GEN.OBSERVER_ROLE, publisherIsTieredRole(GEN.MEMBER_ROLE)));
×
623
        c.observer += runTierLabeled("observer(self,late)", graph,
×
624
                nonAdminTierUpdate(graph, -1, GEN.OBSERVER_ROLE, PUBLISHER_IS_SELF));
×
625
        return c;
×
626
    }
627

628
    /**
629
     * Cheap ASK: did any new {@code npa:RoleDeclaration} extraction land in the
630
     * load-number delta {@code (lastProcessed, ∞)}? Used by the late-arrival
631
     * trigger so an RD that arrives in the same cycle as a matching candidate
632
     * still gets validated.
633
     */
634
    boolean newRoleDeclarationsArrived(long lastProcessed) {
635
        String ask = String.format("""
×
636
                PREFIX npa: <%1$s>
637
                ASK {
638
                  GRAPH <%2$s> {
639
                    ?rd a npa:RoleDeclaration ;
640
                        npa:viaNanopub ?np .
641
                  }
642
                  GRAPH <%3$s> {
643
                    ?np npa:hasLoadNumber ?ln .
644
                    FILTER (?ln > %4$d)
645
                  }
646
                }
647
                """, NPA.NAMESPACE, SpacesVocab.SPACES_GRAPH, NPA.GRAPH, lastProcessed);
×
648
        return runAsk(ask);
×
649
    }
650

651
    /**
652
     * Cheap ASK: did any new {@code npa:PresetAssignment} or {@code npa:PresetDeclaration}
653
     * extraction land in the load-number delta {@code (lastProcessed, ∞)}? Drives the
654
     * late-arrival re-run so a preset assignment that arrives in the same cycle as its
655
     * declaration (or admin grant) still materializes, and so an arriving newer assignment
656
     * triggers the deactivation/latest-wins re-evaluation.
657
     */
658
    boolean newPresetAssignmentsArrived(long lastProcessed) {
659
        String ask = String.format("""
×
660
                PREFIX npa: <%1$s>
661
                ASK {
662
                  GRAPH <%2$s> {
663
                    ?x a ?t ;
664
                       npa:viaNanopub ?np .
665
                    FILTER (?t = npa:PresetAssignment || ?t = npa:PresetDeclaration)
666
                  }
667
                  GRAPH <%3$s> {
668
                    ?np npa:hasLoadNumber ?ln .
669
                    FILTER (?ln > %4$d)
670
                  }
671
                }
672
                """, NPA.NAMESPACE, SpacesVocab.SPACES_GRAPH, NPA.GRAPH, lastProcessed);
×
673
        return runAsk(ask);
×
674
    }
675

676
    // ---------------- Tier UPDATE loops ----------------
677

678
    /**
679
     * Per-tier inserted-triple tallies for one build or cycle. Counts the sum
680
     * of {@code (graphSize_after - graphSize_before)} across all iterations of
681
     * each tier's fixed-point INSERT loop — i.e. inserted *triples*, not
682
     * distinct subjects (a single RoleInstantiation insert writes 4–5 triples).
683
     *
684
     * <p>Used internally by the {@link #runIncrementalCycle structuralAdds}
685
     * boolean check (we only care whether any tier inserted at all).
686
     * Not what the log lines report: see {@link TierSubjectTotals} +
687
     * {@link #computeTierSubjectTotals} for the distinct-subject totals
688
     * surfaced to operators.
689
     */
690
    /**
691
     * Total triples inserted across every tier. Used both for the metrics gauge and
692
     * for the empty-build guard in {@link #runFullBuild}, so the two can never
693
     * disagree about what "this build produced nothing" means.
694
     */
695
    static long totalInserted(TierInsertedTriples c) {
696
        return (long) c.admin + c.alias + c.presetAttachment + c.presetAssignmentRef
144✔
697
                + c.attachment + c.maintainer + c.member + c.observer
698
                + c.subSpace + c.subSpacePrefix + c.maintainedResource
699
                + c.governingSpaceRef;
700
    }
701

702
    static final class TierInsertedTriples {
9✔
703
        int admin;
704
        int alias;
705
        int presetAttachment;
706
        int presetAssignmentRef;
707
        int attachment;
708
        int maintainer;
709
        int member;
710
        int observer;
711
        int subSpace;
712
        int subSpacePrefix;
713
        int maintainedResource;
714
        int governingSpaceRef;
715
    }
716

717
    /**
718
     * Snapshot of distinct-subject totals in a space-state graph at a moment
719
     * in time. Independent of which tier-loop added each subject.
720
     */
721
    record TierSubjectTotals(long adminRIs, long attachmentRAs, long nonAdminRIs) {}
36✔
722

723
    /**
724
     * Runs the five tier loops in order: admin → {@code gen:hasRole} attachment
725
     * validation → maintainer → member → observer. Each loop iterates a SPARQL
726
     * INSERT to fixed point (no new triples added). Returns per-tier counts.
727
     *
728
     * @param graph         target space-state graph
729
     * @param lastProcessed load-number horizon; use {@code -1} for full build
730
     */
731
    TierInsertedTriples runAllTierLoops(IRI graph, long lastProcessed) {
732
        TierInsertedTriples c = new TierInsertedTriples();
×
733
        c.admin = runTierLabeled("admin", graph, adminTierUpdate(graph, lastProcessed));
×
734
        // Alias admit runs after the admin closure has settled (both the authority
735
        // gate and the anti-hijack check read the admin set) and before attachment /
736
        // role tiers (their alias-aware admin lookups consume the npa:sameAsSpace edge
737
        // this pass emits). See issue #113.
738
        c.alias = runTierLabeled("alias", graph, aliasAdmitUpdate(graph, lastProcessed));
×
739
        // Sub-space admit runs after admin closure has settled (Mode A + Mode B both
740
        // need the admin set). Independent of role tiers — order between subspace
741
        // and attachment / maintainer / member / observer doesn't matter.
742
        c.subSpace = runTierLabeled("subspace", graph, subSpaceAdmitUpdate(graph, lastProcessed));
×
743
        // Maintained-resource admit also depends only on the admin closure. Single
744
        // Mode A: publisher must be admin of the maintaining space. No co-declaration
745
        // partner, no URL-prefix fallback.
746
        c.maintainedResource = runTierLabeled("maintained-resource", graph,
×
747
                maintainedResourceAdmitUpdate(graph, lastProcessed));
×
748
        // URL-prefix sub-space fallback runs after the explicit-declaration admit
749
        // pass commits so the per-child suppression check sees this cycle's fresh
750
        // validations. No load filter — depends on which Spaces exist, not on
751
        // delta-arrivals; the dedup FILTER NOT EXISTS prevents re-insertion.
752
        c.subSpacePrefix = runTierLabeled("subspace-prefix", graph,
×
753
                subSpacePrefixFallbackUpdate(graph));
×
754
        // Reflexive governing-space-ref edges (issue #130). Self-healing, no load filter;
755
        // runs after the maintained-resource admit so a maintained resource that is itself
756
        // a space already has its maintained governing edge by now (the two are independent
757
        // anyway — different subjects/objects). Order vs. other tiers doesn't matter.
758
        c.governingSpaceRef = runTierLabeled("governing-space-ref", graph,
×
759
                governingSpaceRefReflexiveUpdate(graph));
×
760
        // Preset-attachment runs immediately before the regular attachment tier so the
761
        // gen:RoleAssignment rows it materializes (from active, admin-authored preset
762
        // assignments) are picked up by the downstream non-admin tiers in the same pass,
763
        // exactly like directly-published attachments. See
764
        // doc/design-preset-role-materialization.md.
765
        c.presetAttachment = runTierLabeled("preset-attachment", graph,
×
766
                presetAttachmentValidationUpdate(graph, lastProcessed));
×
767
        // Ref-scoped preset-assignment listing stamp (issue #122). Display-only leaf —
768
        // independent of the role tiers and of structuralAdds; order doesn't matter.
769
        c.presetAssignmentRef = runTierLabeled("preset-assignment-ref", graph,
×
770
                presetAssignmentRefStampUpdate(graph, lastProcessed));
×
771
        c.attachment = runTierLabeled("attachment", graph,
×
772
                attachmentValidationUpdate(graph, lastProcessed));
×
773
        c.maintainer = runTierLabeled("maintainer", graph, nonAdminTierUpdate(graph, lastProcessed,
×
774
                GEN.MAINTAINER_ROLE, PUBLISHER_IS_ADMIN));
775
        // Member tier: admin OR maintainer publisher — split into two simpler updates
776
        // so the query planner doesn't struggle with the UNION.
777
        c.member = runTierLabeled("member(admin-pub)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
778
                GEN.MEMBER_ROLE, PUBLISHER_IS_ADMIN));
779
        c.member += runTierLabeled("member(maint-pub)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
780
                GEN.MEMBER_ROLE, publisherIsTieredRole(GEN.MAINTAINER_ROLE)));
×
781
        // Observer tier: self-evidence OR a downward grant from any higher tier.
782
        // ObserverRole is the default tier when a role definition omits an
783
        // explicit subclass (see "Role types" in design-space-repositories.md), so
784
        // most "X assigned Y this role" nanopubs land here. Restricting the tier
785
        // to PUBLISHER_IS_SELF would silently drop those grants. The four
786
        // sub-loops mirror the trust-state's downward-only chain: admin grants
787
        // anything; maintainers and members grant observer; everyone may
788
        // self-attest.
789
        c.observer = runTierLabeled("observer(admin-pub)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
790
                GEN.OBSERVER_ROLE, PUBLISHER_IS_ADMIN));
791
        c.observer += runTierLabeled("observer(maint-pub)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
792
                GEN.OBSERVER_ROLE, publisherIsTieredRole(GEN.MAINTAINER_ROLE)));
×
793
        c.observer += runTierLabeled("observer(member-pub)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
794
                GEN.OBSERVER_ROLE, publisherIsTieredRole(GEN.MEMBER_ROLE)));
×
795
        c.observer += runTierLabeled("observer(self)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
796
                GEN.OBSERVER_ROLE, PUBLISHER_IS_SELF));
797
        return c;
×
798
    }
799

800
    /**
801
     * Builds a publisher constraint requiring the publisher to be a validated holder
802
     * of the given tier's role (maintainer or member) in the target space.
803
     * Owns its own AccountState resolution so ?publisher is bound through the
804
     * targeted (pkh → agent) lookup rather than enumerated.
805
     */
806
    private static String publisherIsTieredRole(IRI tierClass) {
807
        // Re-keyed on the assignment's ref (alias → canonical already resolved by the
808
        // attachment tier). Relies on materialized non-admin RIs carrying their role
809
        // property (npa:regularProperty / npa:inverseProperty) — supplied by the
810
        // enrichment in nonAdminTierUpdate; without it this constraint matched nothing.
811
        return """
×
812
                ?acct a npa:AccountState ;
813
                      npa:pubkey ?pkh ;
814
                      npa:agent  ?publisher .
815
                ?tierRI a gen:RoleInstantiation ;
816
                        npa:forSpaceRef ?spaceRef ;
817
                        npa:forAgent ?publisher .
818
                ?rdT a npa:RoleDeclaration ;
819
                     npa:hasRoleType <%1$s> .
820
                { ?tierRI npa:regularProperty ?predT . ?rdT gen:hasRegularProperty ?predT . }
821
                UNION
822
                { ?tierRI npa:inverseProperty ?predT . ?rdT gen:hasInverseProperty ?predT . }
823
                """.formatted(tierClass);
×
824
    }
825

826
    // ---------------- Role revocation / detachment (issue #129) ----------------
827

828
    /**
829
     * {@code xsd:dateTime} epoch literal — the latest-wins fallback for any assertion that
830
     * lacks {@code dct:created}. Per issue #129's "treat missing as epoch": a positive
831
     * assertion without a timestamp sorts oldest (always loses), and a negative
832
     * (revocation / detachment) without one is inert (can never out-rank a timestamped
833
     * positive). Written as a full datatype IRI since the tier templates only declare
834
     * {@code npa:} / {@code gen:}.
835
     */
836
    private static final String EPOCH_DT =
837
            "\"1970-01-01T00:00:00.000Z\"^^<http://www.w3.org/2001/XMLSchema#dateTime>";
838

839
    /** Inner {@code GRAPH} block matching a revoker who is a validated admin of {@code ?spaceRef}. */
840
    private static String revokerAdminGraphBlock(IRI graph) {
841
        return String.format("""
27✔
842
                GRAPH <%1$s> {
843
                  ?revAcct a npa:AccountState ; npa:pubkey ?revPkh ; npa:agent ?revAgent .
844
                  ?revRI a gen:RoleInstantiation ;
845
                         npa:forSpaceRef ?spaceRef ;
846
                         npa:inverseProperty gen:hasAdmin ;
847
                         npa:forAgent ?revAgent .
848
                }""", graph);
849
    }
850

851
    /** Inner {@code GRAPH} block matching a revoker who holds {@code tier} in {@code ?spaceRef}. */
852
    private static String revokerTierGraphBlock(IRI graph, IRI tier) {
853
        return String.format("""
39✔
854
                GRAPH <%1$s> {
855
                  ?revAcct a npa:AccountState ; npa:pubkey ?revPkh ; npa:agent ?revAgent .
856
                  ?revRI a gen:RoleInstantiation ;
857
                         npa:forSpaceRef ?spaceRef ;
858
                         npa:forAgent ?revAgent ;
859
                         npa:hasRoleType <%2$s> .
860
                }""", graph, tier);
861
    }
862

863
    /** Inner {@code GRAPH} block matching a self-revoke: the revoker's key belongs to {@code ?agent}. */
864
    private static String revokerSelfGraphBlock(IRI graph) {
865
        return String.format("""
27✔
866
                GRAPH <%1$s> {
867
                  ?revAcct a npa:AccountState ; npa:pubkey ?revPkh ; npa:agent ?agent .
868
                }""", graph);
869
    }
870

871
    /**
872
     * Authorization arms for an instantiation revocation targeting a <em>compile-time</em>
873
     * tier — issue #129's matrix, the single arm builder used by BOTH the inline suppression
874
     * filter and the (per-tier-scoped) displacement DELETE, so the two paths can never
875
     * authorize different revokers and flip-flop a row. UNION of only the arms the matrix
876
     * permits for {@code targetTier}: admin of {@code ?spaceRef} (revokes any non-admin); a
877
     * maintainer (member/observer targets); a member (observer target); plus the assignee
878
     * itself (self-leave, any tier). A revoker must hold a tier strictly higher than the
879
     * target. Compile-time selection (no runtime {@code ?tier} variable) deliberately avoids
880
     * the SPARQL pitfall where a {@code FILTER} inside a {@code UNION} branch cannot see a
881
     * {@code ?tier} bound in the enclosing group.
882
     */
883
    private static String revocationAuthorityArmsForTier(IRI graph, IRI targetTier) {
884
        List<String> arms = new ArrayList<>();
12✔
885
        arms.add("{ " + revokerAdminGraphBlock(graph) + " }");
18✔
886
        if (GEN.MEMBER_ROLE.equals(targetTier) || GEN.OBSERVER_ROLE.equals(targetTier)) {
24✔
887
            arms.add("{ " + revokerTierGraphBlock(graph, GEN.MAINTAINER_ROLE) + " }");
21✔
888
        }
889
        if (GEN.OBSERVER_ROLE.equals(targetTier)) {
12✔
890
            arms.add("{ " + revokerTierGraphBlock(graph, GEN.MEMBER_ROLE) + " }");
21✔
891
        }
892
        arms.add("{ " + revokerSelfGraphBlock(graph) + " }");
18✔
893
        return String.join("\nUNION\n", arms);
12✔
894
    }
895

896
    /**
897
     * Inline suppression filter for {@code nonAdminTierUpdate}: rejects a candidate
898
     * instantiation ({@code ?ri}, created {@code ?candCreated}) whose {@code (space, agent,
899
     * role)} key has a newer authorized {@code npa:RoleRevocation}, using
900
     * {@link #revocationAuthorityArmsForTier} for {@code targetTier} (the loop tier) — the same
901
     * builder the displacement DELETE uses, so suppression and re-materialization always agree.
902
     * The revocation's named space is matched against any IRI denoting {@code ?spaceRef}
903
     * (canonical or validated {@code owl:sameAs} alias, issue #113), so an alias-named
904
     * revocation is not a silent no-op. Latest-wins by {@code dct:created} ({@link #EPOCH_DT}
905
     * fallback) with an {@code STR()} subject tiebreak. Not wrapped in {@code invalidationFilter}:
906
     * per issue #129 the only un-revoke path is a newer positive re-assignment.
907
     */
908
    private static String nonAdminRevocationSuppressionFilter(IRI graph, IRI targetTier) {
909
        return String.format("""
51✔
910
                FILTER NOT EXISTS {
911
                  { GRAPH <%2$s> { ?spaceRef npa:spaceIri ?revSpace . } }
912
                  UNION
913
                  { GRAPH <%1$s> { ?revSpace npa:sameAsSpace ?spaceRef . } }
914
                  GRAPH <%2$s> {
915
                    ?rev a npa:RoleRevocation ;
916
                         npa:forSpace    ?revSpace ;
917
                         npa:forAgent    ?agent ;
918
                         npa:revokedRole ?role ;
919
                         npa:pubkeyHash  ?revPkh .
920
                    OPTIONAL { ?rev <http://purl.org/dc/terms/created> ?revCreatedRaw . }
921
                  }
922
                  BIND(COALESCE(?revCreatedRaw, %4$s) AS ?revCreated)
923
                  FILTER (?revCreated > ?candCreated
924
                          || (?revCreated = ?candCreated && STR(?rev) > STR(?ri)))
925
                  { %3$s }
926
                }""", graph, SpacesVocab.SPACES_GRAPH,
927
                revocationAuthorityArmsForTier(graph, targetTier), EPOCH_DT);
18✔
928
    }
929

930
    /**
931
     * Inline suppression filter for {@code adminTierUpdate}: rejects an admin instantiation
932
     * ({@code ?ri}, created {@code ?candCreated}) whose {@code (ref, agent)} key has a newer
933
     * authorized admin {@code npa:RoleRevocation} ({@code revokedRole = gen:AdminRole}) —
934
     * authorized by an admin of the ref (admins revoke admins) or by the agent itself
935
     * (self-leave). <b>Root admins are exempt</b> (issue #129/#110): a nested
936
     * {@code FILTER NOT EXISTS} on {@code npa:hasRootAdmin} makes any revocation against a
937
     * root admin structurally inert, overriding self-leave. {@code gen:AdminRole} resolves
938
     * via the {@code gen:} prefix the admin-tier template declares.
939
     */
940
    private static String adminRevocationSuppressionFilter(IRI graph) {
941
        return String.format("""
48✔
942
                FILTER NOT EXISTS {
943
                  FILTER NOT EXISTS { GRAPH <%2$s> {
944
                    ?rootDef a npa:SpaceDefinition ;
945
                             npa:forSpaceRef  ?spaceRef ;
946
                             npa:hasRootAdmin ?agent .
947
                  } }
948
                  { GRAPH <%2$s> { ?spaceRef npa:spaceIri ?revSpace . } }
949
                  UNION
950
                  { GRAPH <%1$s> { ?revSpace npa:sameAsSpace ?spaceRef . } }
951
                  GRAPH <%2$s> {
952
                    ?rev a npa:RoleRevocation ;
953
                         npa:forSpace    ?revSpace ;
954
                         npa:forAgent    ?agent ;
955
                         npa:revokedRole gen:AdminRole ;
956
                         npa:pubkeyHash  ?revPkh .
957
                    OPTIONAL { ?rev <http://purl.org/dc/terms/created> ?revCreatedRaw . }
958
                  }
959
                  BIND(COALESCE(?revCreatedRaw, %4$s) AS ?revCreated)
960
                  FILTER (?revCreated > ?candCreated
961
                          || (?revCreated = ?candCreated && STR(?rev) > STR(?ri)))
962
                  { %3$s }
963
                }""", graph, SpacesVocab.SPACES_GRAPH,
964
                "{ " + revokerAdminGraphBlock(graph) + " }\nUNION\n{ "
6✔
965
                        + revokerSelfGraphBlock(graph) + " }",
21✔
966
                EPOCH_DT);
967
    }
968

969
    /**
970
     * Inline suppression filter for the attachment tiers ({@code attachmentValidationUpdate}
971
     * and {@code presetAttachmentValidationUpdate}): rejects a {@code (targetRef, role)}
972
     * attachment whose effective timestamp ({@code ?<createdVar>}) is out-ranked by a newer
973
     * admin-authored {@code npa:RoleDetachment} (issue #129). Authority = admin of
974
     * {@code ?targetRef} (matching who may attach). Non-sticky latest-wins: a newer
975
     * attachment / preset assignment naturally re-attaches because its timestamp beats the
976
     * detachment. The detachment's named space is matched against any IRI denoting
977
     * {@code ?targetRef} (canonical or {@code owl:sameAs} alias).
978
     *
979
     * @param createdVar     bare name of the attachment's effective-created variable
980
     * @param attachSubjVar  bare name of the attachment subject variable (for the STR tiebreak)
981
     */
982
    private static String roleDetachmentSuppressionFilter(IRI graph, String createdVar, String attachSubjVar) {
983
        return String.format("""
75✔
984
                FILTER NOT EXISTS {
985
                  { GRAPH <%2$s> { ?targetRef npa:spaceIri ?detSpace . } }
986
                  UNION
987
                  { GRAPH <%1$s> { ?detSpace npa:sameAsSpace ?targetRef . } }
988
                  GRAPH <%2$s> {
989
                    ?det a npa:RoleDetachment ;
990
                         npa:forSpace    ?detSpace ;
991
                         npa:revokedRole ?role ;
992
                         npa:pubkeyHash  ?detPkh .
993
                    OPTIONAL { ?det <http://purl.org/dc/terms/created> ?detCreatedRaw . }
994
                  }
995
                  BIND(COALESCE(?detCreatedRaw, %5$s) AS ?detCreated)
996
                  FILTER (?detCreated > ?%3$s
997
                          || (?detCreated = ?%3$s && STR(?det) > STR(?%4$s)))
998
                  GRAPH <%1$s> {
999
                    ?detAcct a npa:AccountState ; npa:pubkey ?detPkh ; npa:agent ?detAgent .
1000
                    ?detAdminRI a gen:RoleInstantiation ;
1001
                                npa:forSpaceRef ?targetRef ;
1002
                                npa:inverseProperty gen:hasAdmin ;
1003
                                npa:forAgent ?detAgent .
1004
                  }
1005
                }""", graph, SpacesVocab.SPACES_GRAPH, createdVar, attachSubjVar, EPOCH_DT);
1006
    }
1007

1008
    /** Wraps {@link #runTierLoop} with tier-name context for logs/exceptions. */
1009
    private int runTierLabeled(String tier, IRI graph, String sparqlUpdate) {
1010
        try {
1011
            return runTierLoop(graph, sparqlUpdate);
×
1012
        } catch (RuntimeException ex) {
×
1013
            logger.error("AuthorityResolver: tier={} failed with SPARQL UPDATE:\n{}\n", tier, sparqlUpdate, ex);
×
1014
            throw ex;
×
1015
        }
1016
    }
1017

1018
    /**
1019
     * Runs a single tier's INSERT to fixed point. Counts rows by probing
1020
     * graph size before/after each INSERT; stops when the size doesn't change.
1021
     *
1022
     * @return total number of triples inserted by this tier across all iterations
1023
     */
1024
    int runTierLoop(IRI graph, String sparqlUpdate) {
1025
        int total = 0;
×
1026
        long before = graphSize(graph);
×
1027
        while (true) {
1028
            // Note: no explicit transaction wrapping here. In tests we observed that
1029
            // HTTPRepository's RDF4J-transaction protocol silently no-op'd cross-graph
1030
            // SPARQL UPDATEs with UNION sub-patterns inside conn.begin()/commit(),
1031
            // while the same UPDATE POSTed directly to /statements applied correctly.
1032
            // A bare prepareUpdate().execute() takes the direct /statements path and
1033
            // runs the UPDATE atomically per SPARQL 1.1 semantics — which is all we
1034
            // need; there's nothing else to commit atomically alongside the UPDATE.
1035
            try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1036
                conn.prepareUpdate(QueryLanguage.SPARQL, sparqlUpdate).execute();
×
1037
            }
1038
            long after = graphSize(graph);
×
1039
            long added = after - before;
×
1040
            if (added <= 0) break;
×
1041
            total += added;
×
1042
            before = after;
×
1043
        }
×
1044
        return total;
×
1045
    }
1046

1047
    private long graphSize(IRI graph) {
1048
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1049
            return conn.size(graph);
×
1050
        }
1051
    }
1052

1053
    /**
1054
     * Distinct-subject totals in the given space-state graph, broken down by
1055
     * RoleInstantiation kind (admin-pinned vs not) and RoleAssignment.
1056
     * Three SELECT-COUNT queries — cheap, called once per build/cycle for
1057
     * the user-facing log line. Returns zeros on failure (logged) so a flaky
1058
     * count read can't wedge the cycle.
1059
     */
1060
    TierSubjectTotals computeTierSubjectTotals(IRI graph) {
1061
        long adminRIs       = countDistinctSubjects(graph, """
×
1062
                ?ri a gen:RoleInstantiation ; npa:inverseProperty gen:hasAdmin .
1063
                """, "ri");
1064
        long attachmentRAs  = countDistinctSubjects(graph, """
×
1065
                ?ra a gen:RoleAssignment .
1066
                """, "ra");
1067
        long nonAdminRIs    = countDistinctSubjects(graph, """
×
1068
                ?ri a gen:RoleInstantiation .
1069
                FILTER NOT EXISTS { ?ri npa:inverseProperty gen:hasAdmin }
1070
                """, "ri");
1071
        return new TierSubjectTotals(adminRIs, attachmentRAs, nonAdminRIs);
×
1072
    }
1073

1074
    private long countDistinctSubjects(IRI graph, String wherePattern, String varName) {
1075
        String query = String.format("""
×
1076
                PREFIX npa: <%1$s>
1077
                PREFIX gen: <%2$s>
1078
                SELECT (COUNT(DISTINCT ?%3$s) AS ?n) WHERE {
1079
                  GRAPH <%4$s> {
1080
                    %5$s
1081
                  }
1082
                }
1083
                """, NPA.NAMESPACE, GEN.NAMESPACE, varName, graph, wherePattern);
1084
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO);
×
1085
             TupleQueryResult r = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) {
×
1086
            if (!r.hasNext()) return 0;
×
1087
            return Long.parseLong(r.next().getBinding("n").getValue().stringValue());
×
1088
        } catch (Exception ex) {
×
1089
            logger.warn("AuthorityResolver: countDistinctSubjects on {} failed: {}",
×
1090
                    graph, ex.toString());
×
1091
            return 0;
×
1092
        }
1093
    }
1094

1095
    // ---------------- SPARQL templates ----------------
1096

1097
    /**
1098
     * Reusable invalidation filter on a bound nanopub-IRI variable. Pass the bare
1099
     * variable name (no leading {@code ?}); e.g. {@code invalidationFilter("np")}
1100
     * produces an outer-scoped {@code FILTER NOT EXISTS { GRAPH npa:graph
1101
     * { ?_inv_np npx:invalidates ?np . } }}.
1102
     *
1103
     * <p>Joins on the raw {@code npx:invalidates} triple in {@code npa:graph},
1104
     * which {@link com.knowledgepixels.query.NanopubLoader} writes into the
1105
     * spaces repo from two complementary directions, making the filter symmetric
1106
     * in load order:
1107
     * <ul>
1108
     *   <li>At the invalidator's own load: the loader's space-repo trigger fires
1109
     *       whenever the nanopub has either its own space-relevant extractions
1110
     *       OR an {@code npx:invalidates}/{@code npx:retracts}/{@code npx:supersedes}
1111
     *       triple, so a pure-retraction nanopub still lands its raw triple plus
1112
     *       {@code npa:hasLoadNumber} stamp in {@code npa:graph}.</li>
1113
     *   <li>At the invalidated target's load (when the invalidator landed
1114
     *       earlier): {@code NanopubLoader.getInvalidatingStatements} reads the
1115
     *       triple back from the meta repo and mirrors it into the target's own
1116
     *       write to the spaces repo.</li>
1117
     * </ul>
1118
     *
1119
     * <p>The earlier shape joined on a structured {@code npa:Invalidation} entry
1120
     * in {@code npa:spacesGraph} that was only emitted on the invalidator's side
1121
     * AND only when the invalidated target's meta had already loaded, leaving a
1122
     * window where a superseding nanopub loaded before its target produced no
1123
     * entry and the stale row was never filtered out (see also the matching
1124
     * change in the tier-specific {@code *InvalidationCheckWhere}/{@code
1125
     * *InvalidationDelete} templates below).
1126
     *
1127
     * <p>Important: this filter must be placed OUTSIDE the surrounding
1128
     * {@code GRAPH npa:spacesGraph { ... }} block, not nested inside it. When
1129
     * nested, RDF4J's planner couples the FILTER NOT EXISTS evaluation into the
1130
     * join order (per-row scan multiplied by the candidate set), which we
1131
     * measured turning a 39ms query into a 60s+ timeout on the live observer-tier
1132
     * data. Outside the GRAPH block, the planner defers the filter until
1133
     * {@code ?np}/{@code ?rdNp} are bound and does a targeted index lookup.
1134
     *
1135
     * <p>Variable names must match {@code [A-Za-z0-9_]+} per SPARQL grammar —
1136
     * embedding a {@code ?} inside {@code ?_inv_?np} would yield a parse error.
1137
     */
1138
    private static String invalidationFilter(String bareVarName) {
1139
        return "FILTER NOT EXISTS { GRAPH <" + NPA.GRAPH + "> {"
30✔
1140
                + " ?_inv_" + bareVarName
1141
                + " <" + NPX.INVALIDATES + "> ?" + bareVarName + " . "
1142
                + samePublisherClause("_inv_" + bareVarName, bareVarName)
6✔
1143
                + " } }";
1144
    }
1145

1146
    /**
1147
     * SPARQL triple pair (placed inside a {@code GRAPH npa:graph { ... }} block)
1148
     * requiring the invalidating nanopub and its target to share a signing public
1149
     * key — the self-retraction authority gate for issue #112. Without it, the
1150
     * materializer honors {@code npx:invalidates}/{@code retracts}/{@code supersedes}
1151
     * from <em>any</em> validly-signed nanopub, so any agent can erase another
1152
     * space's materialized state (griefing/DoS of the view — fail-closed, no
1153
     * privilege escalation, but real). Additions are already admin-gated; this is
1154
     * the symmetric gate on removals.
1155
     *
1156
     * <p>Both {@code npa:hasValidSignatureForPublicKeyHash} triples live in
1157
     * {@code npa:graph} of the spaces repo: the target via its own space-load, the
1158
     * invalidator via the symmetric retractor propagation in
1159
     * {@link com.knowledgepixels.query.NanopubLoader} (forward {@code
1160
     * loadInvalidateStatements} + reverse {@code loadInvalidatorIntoSpacesRepo}),
1161
     * so the join is populated regardless of load order.
1162
     *
1163
     * <p>"Same pubkey" is intentionally stricter than "same agent": a retraction
1164
     * signed by a different key the author owns (key rotation) is not honored, and
1165
     * cross-admin supersession is out of scope here (would need an admin-authority
1166
     * arm). The pubkey-bridge variable is suffixed with {@code targetVar} so two
1167
     * filters in one query (e.g. on {@code ?np} and {@code ?rdNp}) don't collide.
1168
     *
1169
     * @param invVar    invalidator nanopub variable name (no leading {@code ?})
1170
     * @param targetVar invalidated-target nanopub variable name (no leading {@code ?})
1171
     */
1172
    private static String samePublisherClause(String invVar, String targetVar) {
1173
        String pk = "?_invpk_" + targetVar;
9✔
1174
        return "?" + invVar + " <" + NPA.HAS_VALID_SIGNATURE_FOR_PUBLIC_KEY_HASH + "> " + pk + " . "
30✔
1175
                + "?" + targetVar + " <" + NPA.HAS_VALID_SIGNATURE_FOR_PUBLIC_KEY_HASH + "> " + pk + " .";
1176
    }
1177

1178
    /**
1179
     * Admin tier: seed from {@code npadef:...hasRootAdmin} (trusted by construction)
1180
     * plus closed-over admin grants; insert any {@code gen:RoleInstantiation} with
1181
     * {@code npa:inverseProperty gen:hasAdmin} whose publisher (resolved via mirrored
1182
     * trust-approved AccountState) is already in the admin set.
1183
     *
1184
     * <p>The seed is gated by {@link #spaceRefAliveFilter} (not the per-nanopub
1185
     * {@code invalidationFilter("defNp")}): the {@code hasRootAdmin} seed is anchored
1186
     * to the root NPID, which is the immutable space-ref identity, so superseding the
1187
     * root <em>nanopub</em> with a continuation revision must not strip the seed —
1188
     * only retracting every definition of the ref removes it. See issue #110.
1189
     */
1190
    static String adminTierUpdate(IRI graph, long lastProcessed) {
1191
        // Order tuned for RDF4J's evaluator:
1192
        //   1. Anchor on the small (seed UNION closed-over) set to bind ?publisher
1193
        //      and ?space cheaply.
1194
        //   2. Resolve ?pkh from the mirrored AccountState row (?publisher bound).
1195
        //   3. Probe instantiations using the now-bound (?space, ?pkh) — targeted
1196
        //      lookup, not a full RoleInstantiation scan.
1197
        //   4. Load-number filter on bound ?np.
1198
        //   5. Dedup at the end.
1199
        // Authority is keyed on the space *ref* (npa:forSpaceRef), not the bare Space
1200
        // IRI: two refs that share an IRI but have different roots are independent
1201
        // domains (see doc/design-spaceref-isolation.md). The instantiation evidence in
1202
        // the extraction graph is IRI-keyed (a gen:hasAdmin nanopub names the bare IRI),
1203
        // so we project it per-ref by joining each instantiation naming ?space to the
1204
        // admin rows of every ref of ?space whose admin set contains the publisher. The
1205
        // inserted subject is minted per (?ri, ?spaceRef) so one instantiation validating
1206
        // into N refs yields N distinct rows. TRANSITIONAL-DUAL-EMIT (Phase 4: remove):
1207
        // forSpace is still emitted alongside forSpaceRef so the not-yet-migrated
1208
        // downstream tiers / pre-ref read queries keep functioning on a mixed-version
1209
        // fleet; it is dropped once everything keys on forSpaceRef.
1210
        return """
69✔
1211
                PREFIX npa:  <%1$s>
1212
                PREFIX gen:  <%2$s>
1213
                INSERT { GRAPH <%3$s> {
1214
                  ?sri a gen:RoleInstantiation ;
1215
                       npa:forSpaceRef ?spaceRef ;
1216
                       npa:forSpace ?space ;
1217
                       npa:inverseProperty gen:hasAdmin ;
1218
                       # Stamp the admin tier so consumers read tier uniformly across all
1219
                       # RoleInstantiations (?ri npa:hasRoleType ?tier) with no admin
1220
                       # special-case — matching the non-admin path (issue #125, #127).
1221
                       npa:hasRoleType gen:AdminRole ;
1222
                       npa:forAgent ?agent ;
1223
                       npa:viaNanopub ?np .
1224
                } }
1225
                WHERE {
1226
                  # 1. Anchor: who is already an admin of which space ref?
1227
                  {
1228
                    # Seed branch: root-admin of a space ref that is still alive
1229
                    # (has at least one non-invalidated definition). NOT filtered on
1230
                    # ?def's own invalidation — superseding the root nanopub with a
1231
                    # continuation revision must keep the seed; only a fully-retracted
1232
                    # ref drops it (issue #110).
1233
                    GRAPH <%4$s> {
1234
                      ?def a npa:SpaceDefinition ;
1235
                           npa:forSpaceRef  ?spaceRef ;
1236
                           npa:hasRootAdmin ?publisher .
1237
                      ?spaceRef npa:spaceIri ?space .
1238
                    }
1239
                    %7$s
1240
                  }
1241
                  UNION
1242
                  {
1243
                    # Closed-over branch: an existing admin of this ref. Recurse on the
1244
                    # ref, then resolve its bare IRI to probe the IRI-keyed instantiation.
1245
                    GRAPH <%3$s> {
1246
                      ?prev a gen:RoleInstantiation ;
1247
                            npa:forSpaceRef     ?spaceRef ;
1248
                            npa:inverseProperty gen:hasAdmin ;
1249
                            npa:forAgent        ?publisher .
1250
                    }
1251
                    GRAPH <%4$s> {
1252
                      ?spaceRef npa:spaceIri ?space .
1253
                    }
1254
                  }
1255
                  # 2. Mirror: resolve ?publisher → ?pkh via the trust-approved row.
1256
                  GRAPH <%3$s> {
1257
                    ?acct a npa:AccountState ;
1258
                          npa:agent  ?publisher ;
1259
                          npa:pubkey ?pkh .
1260
                  }
1261
                  # 3. Targeted instantiation lookup by space + pubkey (IRI-keyed).
1262
                  GRAPH <%4$s> {
1263
                    ?ri a gen:RoleInstantiation ;
1264
                        npa:forSpace        ?space ;
1265
                        npa:inverseProperty gen:hasAdmin ;
1266
                        npa:forAgent        ?agent ;
1267
                        npa:pubkeyHash      ?pkh ;
1268
                        npa:viaNanopub      ?np .
1269
                    # Candidate grant timestamp for the admin-revocation latest-wins (#129).
1270
                    OPTIONAL { ?ri <http://purl.org/dc/terms/created> ?candCreatedRaw . }
1271
                  }
1272
                  BIND(COALESCE(?candCreatedRaw, %9$s) AS ?candCreated)
1273
                  # 3a. Mint the per-ref state subject: (?ri, ?spaceRef) → ?sri.
1274
                  BIND(IRI(CONCAT(STR(?ri), "__", ENCODE_FOR_URI(STR(?spaceRef)))) AS ?sri)
1275
                  %6$s
1276
                  # 4. Load-number filter on bound ?np.
1277
                  GRAPH <%8$s> {
1278
                    ?np npa:hasLoadNumber ?ln .
1279
                    FILTER (?ln > %5$d)
1280
                  }
1281
                  # 4a. Admin-revocation latest-wins (issue #129): suppress if a newer
1282
                  #     authorized admin revocation shadows (ref, agent) — unless ?agent is a
1283
                  #     root admin (constitutional exemption, overrides self-leave).
1284
                  %10$s
1285
                  # 5. Dedup last — keyed on (ref, agent).
1286
                  FILTER NOT EXISTS { GRAPH <%3$s> {
1287
                    ?existing a gen:RoleInstantiation ;
1288
                              npa:forSpaceRef ?spaceRef ;
1289
                              npa:forAgent ?agent ;
1290
                              npa:inverseProperty gen:hasAdmin .
1291
                  } }
1292
                }
1293
                """.formatted(
3✔
1294
                NPA.NAMESPACE,
1295
                GEN.NAMESPACE,
1296
                graph,
1297
                SpacesVocab.SPACES_GRAPH,
1298
                lastProcessed,
15✔
1299
                invalidationFilter("np"),
12✔
1300
                spaceRefAliveFilter(),
39✔
1301
                NPA.GRAPH,
1302
                EPOCH_DT,
1303
                adminRevocationSuppressionFilter(graph));
6✔
1304
    }
1305

1306
    /**
1307
     * Seed-survival filter for the admin tier (issue #110). The {@code hasRootAdmin}
1308
     * seed is anchored to the root NPID, which is the immutable space-ref identity, so
1309
     * it must survive supersession of the root <em>nanopub</em> by a continuation
1310
     * revision (a later definition re-roots to the same ref via
1311
     * {@code gen:hasRootDefinition} and so carries no {@code hasRootAdmin} of its own).
1312
     * The previous {@code invalidationFilter("defNp")} dropped the seed the moment the
1313
     * root revision was superseded, leaving the whole admin closure — and everything
1314
     * cascading from it — unmaterialized for any space whose definition had ever been
1315
     * updated.
1316
     *
1317
     * <p>Expressed positively: the seed survives iff the space ref still has at least
1318
     * one non-invalidated {@link SpacesVocab#SPACE_DEFINITION}. A fully-retracted ref
1319
     * (every definition invalidated) has no live definition, so the {@code FILTER
1320
     * EXISTS} fails and the seed correctly disappears. Anchored on the already-bound
1321
     * {@code ?spaceRef}, so it's a targeted lookup over that ref's (few) definitions.
1322
     */
1323
    private static String spaceRefAliveFilter() {
1324
        return """
33✔
1325
                FILTER EXISTS {
1326
                  GRAPH <%1$s> {
1327
                    ?liveDef a npa:SpaceDefinition ;
1328
                             npa:forSpaceRef ?spaceRef ;
1329
                             npa:viaNanopub  ?liveNp .
1330
                  }
1331
                  %2$s
1332
                }
1333
                """.formatted(SpacesVocab.SPACES_GRAPH, invalidationFilter("liveNp"));
9✔
1334
    }
1335

1336
    /**
1337
     * {@code gen:hasRole} attachment validation: an attachment is validated iff its
1338
     * publisher is already a validated admin of the target space. Adds
1339
     * {@code gen:RoleAssignment} rows to the space-state graph.
1340
     */
1341
    static String attachmentValidationUpdate(IRI graph, long lastProcessed) {
1342
        // Ref-keyed (see doc/design-spaceref-isolation.md). The attachment names a bare
1343
        // Space IRI; it is validated per-ref for every ref of that IRI whose admin set
1344
        // contains the publisher (direct), or — when the named IRI is an owl:sameAs alias
1345
        // — for the canonical ref it maps to (issue #113). ?targetRef is the ref the
1346
        // RoleAssignment attaches to; the inserted subject is minted per (?ra, ?targetRef)
1347
        // so one attachment validating into N refs yields N distinct rows.
1348
        // TRANSITIONAL-DUAL-EMIT (Phase 4: remove): forSpace (the attached IRI, possibly an
1349
        // alias) is kept so the non-admin tier can probe the IRI-keyed instantiations
1350
        // naming it, and so pre-ref read queries keep functioning on a mixed-version fleet.
1351
        return """
69✔
1352
                PREFIX npa:  <%1$s>
1353
                PREFIX gen:  <%2$s>
1354
                INSERT { GRAPH <%3$s> {
1355
                  ?ra2 a gen:RoleAssignment ;
1356
                       npa:forSpaceRef ?targetRef ;
1357
                       npa:forSpace ?space ;
1358
                       gen:hasRole  ?role ;
1359
                       npa:viaNanopub ?np .
1360
                } }
1361
                WHERE {
1362
                  GRAPH <%4$s> {
1363
                    ?ra a gen:RoleAssignment ;
1364
                        npa:forSpace ?space ;
1365
                        gen:hasRole  ?role ;
1366
                        npa:pubkeyHash ?pkh ;
1367
                        npa:viaNanopub ?np .
1368
                    # Attachment timestamp for the detachment latest-wins (issue #129).
1369
                    OPTIONAL { ?ra <http://purl.org/dc/terms/created> ?attCreatedRaw . }
1370
                  }
1371
                  BIND(COALESCE(?attCreatedRaw, %8$s) AS ?attCreated)
1372
                  GRAPH <%7$s> {
1373
                    ?np npa:hasLoadNumber ?ln .
1374
                    FILTER (?ln > %5$d)
1375
                  }
1376
                  GRAPH <%3$s> {
1377
                    ?acct a npa:AccountState ;
1378
                          npa:agent  ?publisher ;
1379
                          npa:pubkey ?pkh .
1380
                  }
1381
                  # Per-ref admin gate. ?targetRef = a ref of ?space the publisher admins
1382
                  # (direct), or the canonical ref ?space is an owl:sameAs alias of.
1383
                  {
1384
                    GRAPH <%4$s> { ?targetRef npa:spaceIri ?space . }
1385
                    GRAPH <%3$s> {
1386
                      ?adminRI a gen:RoleInstantiation ;
1387
                               npa:forSpaceRef ?targetRef ;
1388
                               npa:inverseProperty gen:hasAdmin ;
1389
                               npa:forAgent ?publisher .
1390
                    }
1391
                  }
1392
                  UNION
1393
                  {
1394
                    GRAPH <%3$s> {
1395
                      ?space npa:sameAsSpace ?targetRef .
1396
                      ?adminRI a gen:RoleInstantiation ;
1397
                               npa:forSpaceRef ?targetRef ;
1398
                               npa:inverseProperty gen:hasAdmin ;
1399
                               npa:forAgent ?publisher .
1400
                    }
1401
                  }
1402
                  BIND(IRI(CONCAT(STR(?ra), "__", ENCODE_FOR_URI(STR(?targetRef)))) AS ?ra2)
1403
                  %6$s
1404
                  # Detachment latest-wins (issue #129): suppress if a newer admin-authored
1405
                  # gen:detachedRole out-ranks this (ref, role) attachment.
1406
                  %9$s
1407
                  FILTER NOT EXISTS { GRAPH <%3$s> {
1408
                    ?existing a gen:RoleAssignment ;
1409
                              npa:forSpaceRef ?targetRef ;
1410
                              gen:hasRole  ?role .
1411
                  } }
1412
                }
1413
                """.formatted(
3✔
1414
                NPA.NAMESPACE,
1415
                GEN.NAMESPACE,
1416
                graph,
1417
                SpacesVocab.SPACES_GRAPH,
1418
                lastProcessed,
15✔
1419
                invalidationFilter("np"),
45✔
1420
                NPA.GRAPH,
1421
                EPOCH_DT,
1422
                roleDetachmentSuppressionFilter(graph, "attCreated", "ra"));
6✔
1423
    }
1424

1425
    /**
1426
     * Preset-bundled role materialization (Nanodash issue #302). For each active,
1427
     * admin-authored {@code gen:PresetAssignment} targeting a {@code gen:Space}, inserts
1428
     * one {@code gen:RoleAssignment} per role the preset bundles — exactly as if
1429
     * {@code <space> gen:hasRole <role>} had been published by the assignment's publisher.
1430
     * The materialized rows carry {@code npa:derivedFromPreset} (the assignment nanopub)
1431
     * so the deactivation delete and read-side marking can scope to them without touching
1432
     * directly-published attachments. See {@code doc/design-preset-role-materialization.md}.
1433
     *
1434
     * <p>Activation is resolved by an <b>authorization-scoped latest-wins</b> over the
1435
     * {@code (preset, resource)} pair, NOT {@code npx:invalidates} (§3): the candidate set
1436
     * for the {@code MAX(dct:created)} comparison is restricted to assignments whose
1437
     * publisher is also a validated admin of the target ref, so an unauthorized key's newer
1438
     * assignment cannot shadow an admin's activation (the #113-class anti-hijack rule).
1439
     */
1440
    static String presetAttachmentValidationUpdate(IRI graph, long lastProcessed) {
1441
        // Ref-keyed like attachmentValidationUpdate: the assignment names a bare resource
1442
        // IRI; it is validated per-ref for every Space ref of that IRI whose admin set
1443
        // contains the publisher. The inserted subject is minted per (assignment, ref, role)
1444
        // — one assignment fans out to N roles and N refs. Non-Space targets resolve no
1445
        // ?targetRef and so insert nothing (correct no-op; maintained-resource / individual
1446
        // targets are future work, see design doc §2). TRANSITIONAL-DUAL-EMIT (Phase 4:
1447
        // remove): forSpace kept alongside forSpaceRef so the non-admin tiers can probe the
1448
        // IRI-keyed instantiations and pre-ref read queries keep functioning.
1449
        return """
69✔
1450
                PREFIX npa:  <%1$s>
1451
                PREFIX gen:  <%2$s>
1452
                INSERT { GRAPH <%3$s> {
1453
                  ?ra2 a gen:RoleAssignment ;
1454
                       npa:forSpaceRef ?targetRef ;
1455
                       npa:forSpace    ?resource ;
1456
                       gen:hasRole     ?role ;
1457
                       npa:viaNanopub  ?assignNp ;
1458
                       npa:derivedFromPreset ?assignNp .
1459
                } }
1460
                WHERE {
1461
                  # 1. Anchor: active preset assignments in the extraction graph.
1462
                  GRAPH <%4$s> {
1463
                    ?pa a npa:PresetAssignment ;
1464
                        npa:ofPreset    ?preset ;
1465
                        npa:forResource ?resource ;
1466
                        npa:isActivated true ;
1467
                        npa:pubkeyHash  ?pkh ;
1468
                        npa:viaNanopub  ?assignNp ;
1469
                        <http://purl.org/dc/terms/created> ?created .
1470
                  }
1471
                  # 2. Load-number filter on the assignment nanopub.
1472
                  GRAPH <%7$s> {
1473
                    ?assignNp npa:hasLoadNumber ?ln .
1474
                    FILTER (?ln > %5$d)
1475
                  }
1476
                  # 3. Resolve publisher pkh -> agent via the mirrored trust-approved row.
1477
                  GRAPH <%3$s> {
1478
                    ?acct a npa:AccountState ;
1479
                          npa:agent  ?publisher ;
1480
                          npa:pubkey ?pkh .
1481
                  }
1482
                  # 4. Target must be a Space ref the publisher admins — direct, or the
1483
                  #    canonical ref ?resource is an owl:sameAs alias of (issue #113 parity
1484
                  #    with attachmentValidationUpdate, so a preset assigned against an alias
1485
                  #    IRI still materializes against the canonical ref).
1486
                  {
1487
                    GRAPH <%4$s> { ?targetRef npa:spaceIri ?resource . }
1488
                    GRAPH <%3$s> {
1489
                      ?adminRI a gen:RoleInstantiation ;
1490
                               npa:forSpaceRef ?targetRef ;
1491
                               npa:inverseProperty gen:hasAdmin ;
1492
                               npa:forAgent ?publisher .
1493
                    }
1494
                  }
1495
                  UNION
1496
                  {
1497
                    GRAPH <%3$s> {
1498
                      ?resource npa:sameAsSpace ?targetRef .
1499
                      ?adminRI a gen:RoleInstantiation ;
1500
                               npa:forSpaceRef ?targetRef ;
1501
                               npa:inverseProperty gen:hasAdmin ;
1502
                               npa:forAgent ?publisher .
1503
                    }
1504
                  }
1505
                  # 5. Resolve the assignment's referenced preset IRI (node or kind) to its
1506
                  #    canonical kind, mirroring how Nanodash views key on dct:isVersionOf
1507
                  #    (ViewDisplay.getViewKindIri). Every declaration carries npa:ofPreset for
1508
                  #    both its node IRI and kind, so either reference maps to the same ?kind.
1509
                  GRAPH <%4$s> {
1510
                    ?pdMap a npa:PresetDeclaration ;
1511
                           npa:ofPreset   ?preset ;
1512
                           npa:presetKind ?kind .
1513
                  }
1514
                  # 5a. Roles come from the LATEST live declaration of that kind, restricted to
1515
                  #     Space-targeted presets — so a superseded preset version's roles never leak
1516
                  #     (the per-view-kind latest-wins, ported to materialization).
1517
                  GRAPH <%4$s> {
1518
                    ?pd a npa:PresetDeclaration ;
1519
                        npa:presetKind           ?kind ;
1520
                        npa:presetRole           ?role ;
1521
                        npa:appliesToInstancesOf gen:Space ;
1522
                        npa:viaNanopub           ?pdNp ;
1523
                        <http://purl.org/dc/terms/created> ?pdCreated .
1524
                  }
1525
                  # 5b. Latest-declaration-per-kind: reject if a newer LIVE declaration of the
1526
                  #     same kind exists (tiebreak on subject IRI for equal timestamps).
1527
                  FILTER NOT EXISTS {
1528
                    GRAPH <%4$s> {
1529
                      ?pdNewer a npa:PresetDeclaration ;
1530
                               npa:presetKind ?kind ;
1531
                               npa:viaNanopub ?pdNpNewer ;
1532
                               <http://purl.org/dc/terms/created> ?pdCreatedNewer .
1533
                      FILTER (?pdCreatedNewer > ?pdCreated
1534
                              || (?pdCreatedNewer = ?pdCreated && STR(?pdNewer) > STR(?pd)))
1535
                    }
1536
                    %8$s
1537
                  }
1538
                  # 5c. The chosen declaration must itself be live (not superseded/retracted).
1539
                  %9$s
1540
                  # 6. Mint the per (assignment, ref, role) subject.
1541
                  BIND(IRI(CONCAT(STR(?pa), "__", ENCODE_FOR_URI(STR(?targetRef)),
1542
                                  "__", ENCODE_FOR_URI(STR(?role)))) AS ?ra2)
1543
                  # 7. Authorization-scoped latest-wins (anti-hijack, design doc §3): reject
1544
                  #    if a newer same-(preset,resource) assignment exists whose publisher is
1545
                  #    ALSO a validated admin of ?targetRef. Filtering the shadowing candidate
1546
                  #    to admin-authored rows BEFORE taking the latest is what stops an
1547
                  #    unauthorized key from suppressing an admin's activation. Placed after
1548
                  #    the main vars are bound so the planner defers it (RDF4J quirk).
1549
                  FILTER NOT EXISTS {
1550
                    GRAPH <%4$s> {
1551
                      ?paNewer a npa:PresetAssignment ;
1552
                               npa:ofPreset    ?preset ;
1553
                               npa:forResource ?resource ;
1554
                               npa:pubkeyHash  ?pkhNewer ;
1555
                               <http://purl.org/dc/terms/created> ?createdNewer .
1556
                      FILTER (?createdNewer > ?created
1557
                              || (?createdNewer = ?created && STR(?paNewer) > STR(?pa)))
1558
                    }
1559
                    GRAPH <%3$s> {
1560
                      ?acctNewer a npa:AccountState ;
1561
                                 npa:agent  ?publisherNewer ;
1562
                                 npa:pubkey ?pkhNewer .
1563
                      ?adminRINewer a gen:RoleInstantiation ;
1564
                                    npa:forSpaceRef ?targetRef ;
1565
                                    npa:inverseProperty gen:hasAdmin ;
1566
                                    npa:forAgent ?publisherNewer .
1567
                    }
1568
                  }
1569
                  # 8. Defensive: drop if the assignment nanopub itself was hard-retracted.
1570
                  %6$s
1571
                  # 8a. Detachment latest-wins (issue #129): suppress if a newer admin-authored
1572
                  #     gen:detachedRole out-ranks this preset-derived (ref, role) attachment.
1573
                  #     Non-sticky: a newer PresetAssignment (newer ?created) re-attaches.
1574
                  %10$s
1575
                  # 9. Dedup last — keyed on (ref, role).
1576
                  FILTER NOT EXISTS { GRAPH <%3$s> {
1577
                    ?existing a gen:RoleAssignment ;
1578
                              npa:forSpaceRef ?targetRef ;
1579
                              gen:hasRole ?role .
1580
                  } }
1581
                }
1582
                """.formatted(
3✔
1583
                NPA.NAMESPACE,
1584
                GEN.NAMESPACE,
1585
                graph,
1586
                SpacesVocab.SPACES_GRAPH,
1587
                lastProcessed,
15✔
1588
                invalidationFilter("assignNp"),
27✔
1589
                NPA.GRAPH,
1590
                invalidationFilter("pdNpNewer"),
15✔
1591
                invalidationFilter("pdNp"),
21✔
1592
                roleDetachmentSuppressionFilter(graph, "created", "pa"));
6✔
1593
    }
1594

1595
    /**
1596
     * Stamps a ref-scoped, admin-validated mirror of each {@code npa:PresetAssignment}
1597
     * into the state graph (issue #122). The publisher-agnostic extraction row
1598
     * ({@link SpacesExtractor#extractPresetAssignment}) is keyed only by
1599
     * {@code npa:forResource}, so a consumer listing a space's preset assignments by IRI
1600
     * sees the union across <em>all</em> refs claiming that IRI. This stamp adds
1601
     * {@code npa:forSpaceRef ?targetRef} so the "Assigned presets" listing is no longer
1602
     * merged across refs of the same IRI — the one remaining About-tab listing that still
1603
     * merged across refs (every other ref-scoped listing already has a {@code forSpaceRef}
1604
     * companion).
1605
     *
1606
     * <p>Faithful per-assignment mirror — deliberately <em>not</em> role-gated and
1607
     * <em>not</em> latest-wins-resolved, unlike {@link #presetAttachmentValidationUpdate}:
1608
     * <ul>
1609
     *   <li>No {@code npa:PresetDeclaration}/role join, so a preset that bundles only
1610
     *       <em>views</em> (no roles) is still listed.</li>
1611
     *   <li>Emits active <em>and</em> deactivated rows (carries {@code npa:isActivated})
1612
     *       so the listing can show state; a deactivation is just a newer admin-authored
1613
     *       row, so no {@code dct:created}-driven removal is needed here (contrast §4.4).</li>
1614
     *   <li>Latest-wins is deferred to the consumer query, which ranges only over these
1615
     *       admin-authored rows — so it is authorization-scoped for free (design §3): a
1616
     *       non-admin of the ref can never get a row stamped, so it cannot enter the
1617
     *       latest-wins race.</li>
1618
     * </ul>
1619
     *
1620
     * <p>Display-only leaf: nothing downstream derives from these rows (contrast the
1621
     * preset-derived {@code gen:RoleAssignment}), so the caller must <em>not</em> feed this
1622
     * tier's count into {@code structuralAdds}. The {@code npa:forSpaceRef} predicate also
1623
     * distinguishes a stamped row from the IRI-keyed extraction row (which never carries it),
1624
     * so {@link #presetAssignmentRefInvalidationDelete} can target exactly these rows.
1625
     * Reuses steps 1–4 of {@link #presetAttachmentValidationUpdate}; see
1626
     * doc/design-preset-role-materialization.md §3 and issue #122.
1627
     */
1628
    static String presetAssignmentRefStampUpdate(IRI graph, long lastProcessed) {
1629
        return """
69✔
1630
                PREFIX npa:  <%1$s>
1631
                PREFIX gen:  <%2$s>
1632
                INSERT { GRAPH <%3$s> {
1633
                  ?paRef a npa:PresetAssignment ;
1634
                         npa:ofPreset    ?preset ;
1635
                         npa:forResource ?resource ;
1636
                         npa:forSpaceRef ?targetRef ;
1637
                         npa:isActivated ?activated ;
1638
                         npa:viaNanopub  ?assignNp ;
1639
                         <http://purl.org/dc/terms/created> ?created .
1640
                } }
1641
                WHERE {
1642
                  # 1. Anchor: every assignment row (active or not) in the extraction graph.
1643
                  GRAPH <%4$s> {
1644
                    ?pa a npa:PresetAssignment ;
1645
                        npa:ofPreset    ?preset ;
1646
                        npa:forResource ?resource ;
1647
                        npa:isActivated ?activated ;
1648
                        npa:pubkeyHash  ?pkh ;
1649
                        npa:viaNanopub  ?assignNp ;
1650
                        <http://purl.org/dc/terms/created> ?created .
1651
                  }
1652
                  # 2. Load-number filter on the assignment nanopub (delta window).
1653
                  GRAPH <%6$s> {
1654
                    ?assignNp npa:hasLoadNumber ?ln .
1655
                    FILTER (?ln > %5$d)
1656
                  }
1657
                  # 3. Resolve publisher pkh -> agent via the mirrored trust-approved row.
1658
                  GRAPH <%3$s> {
1659
                    ?acct a npa:AccountState ;
1660
                          npa:agent  ?publisher ;
1661
                          npa:pubkey ?pkh .
1662
                  }
1663
                  # 4. Target must be a Space ref the publisher admins. ?targetRef = that ref;
1664
                  #    fan-out to N refs the publisher admins (per-ref isolation, consistent
1665
                  #    with the role materializer and design-spaceref-isolation.md). Direct,
1666
                  #    or the canonical ref ?resource is an owl:sameAs alias of (issue #113),
1667
                  #    so an assignment naming an alias is still listed under the canonical ref.
1668
                  {
1669
                    GRAPH <%4$s> { ?targetRef npa:spaceIri ?resource . }
1670
                    GRAPH <%3$s> {
1671
                      ?adminRI a gen:RoleInstantiation ;
1672
                               npa:forSpaceRef ?targetRef ;
1673
                               npa:inverseProperty gen:hasAdmin ;
1674
                               npa:forAgent ?publisher .
1675
                    }
1676
                  }
1677
                  UNION
1678
                  {
1679
                    GRAPH <%3$s> {
1680
                      ?resource npa:sameAsSpace ?targetRef .
1681
                      ?adminRI a gen:RoleInstantiation ;
1682
                               npa:forSpaceRef ?targetRef ;
1683
                               npa:inverseProperty gen:hasAdmin ;
1684
                               npa:forAgent ?publisher .
1685
                    }
1686
                  }
1687
                  # 5. Defensive: drop if the assignment nanopub itself was hard-retracted.
1688
                  %7$s
1689
                  # 6. Mint per (assignment, ref); dedup on the bound subject. No latest-wins
1690
                  #    here — a deactivation is just a newer admin-authored row, and the
1691
                  #    consumer resolves latest dct:created per (preset,resource) over these
1692
                  #    admin-authored rows (so the resolution is authorization-scoped).
1693
                  BIND(IRI(CONCAT(STR(?pa), "__", ENCODE_FOR_URI(STR(?targetRef)))) AS ?paRef)
1694
                  FILTER NOT EXISTS { GRAPH <%3$s> { ?paRef a npa:PresetAssignment . } }
1695
                }
1696
                """.formatted(
3✔
1697
                NPA.NAMESPACE,
1698
                GEN.NAMESPACE,
1699
                graph,
1700
                SpacesVocab.SPACES_GRAPH,
1701
                lastProcessed,
27✔
1702
                NPA.GRAPH,
1703
                invalidationFilter("assignNp"));
6✔
1704
    }
1705

1706
    /**
1707
     * Non-admin tier publisher constraints (inserted as a SPARQL sub-pattern).
1708
     * Each constraint owns the AccountState (pkh → agent) lookup so the join
1709
     * variable is bound through a targeted pattern. The observer-self variant
1710
     * binds {@code npa:agent ?agent} directly — no separate {@code ?publisher}
1711
     * variable, no post-join equality filter — which lets the planner anchor
1712
     * the AccountState lookup on the already-bound {@code ?agent} instead of
1713
     * enumerating all approved publishers and filtering at the end.
1714
     */
1715
    static final String PUBLISHER_IS_ADMIN = """
1716
            ?acct a npa:AccountState ;
1717
                  npa:pubkey ?pkh ;
1718
                  npa:agent  ?publisher .
1719
            # Admin of the assignment's ref. The ref already resolves alias →
1720
            # canonical (the attachment tier bound ?spaceRef through the owl:sameAs
1721
            # alias edge for aliased IRIs, issue #113), so no alias arm is needed here.
1722
            ?adminRI a gen:RoleInstantiation ;
1723
                     npa:forSpaceRef ?spaceRef ;
1724
                     npa:inverseProperty gen:hasAdmin ;
1725
                     npa:forAgent ?publisher .
1726
            """;
1727

1728
    /** Observer self-evidence: the assignee's own pubkey signed the instantiation. */
1729
    static final String PUBLISHER_IS_SELF = """
1730
            ?acct a npa:AccountState ;
1731
                  npa:pubkey ?pkh ;
1732
                  npa:agent  ?agent .
1733
            """;
1734

1735
    /**
1736
     * Maintainer / Member / Observer tier INSERT. Same shape: find an instantiation
1737
     * whose predicate matches a RoleDeclaration of the given tier attached to the
1738
     * target space, and whose publisher passes the tier-specific constraint.
1739
     */
1740
    static String nonAdminTierUpdate(IRI graph, long lastProcessed,
1741
                                     IRI tierClass, String publisherConstraint) {
1742
        // Order tuned for RDF4J's evaluator (which executes BGPs roughly in order).
1743
        // The crucial choice is the *anchor*: instantiation-first plans send the
1744
        // planner exploring the full ~thousands of candidate RIs and only filter
1745
        // by tier at the very end. Attachment-first anchors on the small set of
1746
        // gen:RoleAssignment rows already validated in this space-state graph
1747
        // (~hundreds, often zero) and walks outward by bound (?role, ?space).
1748
        //
1749
        //   1. Anchor on RoleAssignments in this space-state graph (small).
1750
        //   1a. Resolve the IRIs that denote the assignment's ref — its canonical
1751
        //      IRI plus any validated owl:sameAs aliases — so an instantiation that
1752
        //      names an alias of the space still matches (issue #113). Bound here so
1753
        //      the instantiation lookup below stays anchored by ?instSpace.
1754
        //   2. Match the tier-pinned RoleDeclaration by ?role.
1755
        //   3. Pair role-decl direction to instantiation direction in one UNION
1756
        //      so only (reg, reg)/(inv, inv) combos are explored.
1757
        //   4. Targeted instantiation lookup — (?instSpace, ?pred) are bound.
1758
        //   5. Publisher constraint (incl. AccountState resolution).
1759
        //   6. Load-number filter on bound ?np.
1760
        //   7. Dedup at the end.
1761
        return """
69✔
1762
                PREFIX npa:  <%1$s>
1763
                PREFIX gen:  <%2$s>
1764
                INSERT { GRAPH <%3$s> {
1765
                  ?ri2 a gen:RoleInstantiation ;
1766
                       npa:forSpaceRef ?spaceRef ;
1767
                       # TRANSITIONAL-DUAL-EMIT (Phase 4: remove): forSpace alongside
1768
                       # forSpaceRef so pre-ref read queries (e.g. get-space-members) keep
1769
                       # functioning on a mixed-version fleet; downstream tiers key on the ref.
1770
                       npa:forSpace ?space ;
1771
                       npa:forAgent ?agent ;
1772
                       ?dirPred ?pred ;
1773
                       # Persist the tier and role IRI that are already bound at this point —
1774
                       # the loop's tierClass arg (%7$s) and the anchoring attachment's ?role
1775
                       # (step 1) — so ref-scoped consumers key on identity rather than
1776
                       # re-deriving the tier from the bare predicate against GLOBAL
1777
                       # RoleDeclarations. The bare-predicate re-derivation bleeds tiers
1778
                       # across spaces that declare the same predicate at different tiers
1779
                       # (issue #125): consumers should match ?ri2 npa:hasRoleType <tier>
1780
                       # / gen:hasRole ?role, exactly as the *-roles-ref queries do.
1781
                       npa:hasRoleType <%7$s> ;
1782
                       gen:hasRole ?role ;
1783
                       npa:viaNanopub ?np .
1784
                } }
1785
                WHERE {
1786
                  # 1. Anchor: validated attachments in this space-state graph (ref-keyed).
1787
                  GRAPH <%3$s> {
1788
                    ?ra a gen:RoleAssignment ;
1789
                        gen:hasRole     ?role ;
1790
                        npa:forSpaceRef ?spaceRef ;
1791
                        npa:forSpace    ?space .
1792
                  }
1793
                  # 1a. The IRIs that denote this ref: its canonical IRI, plus any validated
1794
                  #     owl:sameAs aliases of it (issue #113) — so an instantiation naming an
1795
                  #     alias of the space still materializes here. Bound BEFORE the
1796
                  #     instantiation BGP so that lookup stays anchored by ?instSpace (planner
1797
                  #     note above); ?spaceRef is already bound, so each arm is a targeted
1798
                  #     lookup yielding a tiny IRI set. The alias arm only follows admin-
1799
                  #     validated npa:sameAsSpace edges, so it grants no authority the admin
1800
                  #     tier would not (anti-hijack is enforced upstream, not relaxed here).
1801
                  {
1802
                    GRAPH <%4$s> { ?spaceRef npa:spaceIri ?instSpace . }
1803
                  }
1804
                  UNION
1805
                  {
1806
                    GRAPH <%3$s> { ?instSpace npa:sameAsSpace ?spaceRef . }
1807
                  }
1808
                  # 2. Tier-pinned RoleDeclaration (?role bound from the attachment). Its
1809
                  #    nanopub's invalidation is intentionally NOT consulted (see step 7), so
1810
                  #    no ?rdNp binding is needed.
1811
                  GRAPH <%4$s> {
1812
                    ?rd a npa:RoleDeclaration ;
1813
                        npa:hasRoleType <%7$s> ;
1814
                        npa:role        ?role .
1815
                    # 3. Pair role-decl direction to the instantiation in one UNION so only
1816
                    #    matching combos are explored, binding (?instSpace, ?agent) per arm.
1817
                    #    ?dirPred carries the resolved direction so the materialized row
1818
                    #    records the role property (read by get-space-members and
1819
                    #    publisherIsTieredRole) — identical shape whichever arm matched.
1820
                    #
1821
                    #    The first two arms handle instantiations the extractor already
1822
                    #    classified (npa:regularProperty / npa:inverseProperty). The last two
1823
                    #    resolve a custom predicate the extractor left neutral (npa:rolePredicate
1824
                    #    with raw npa:bindingSubject / npa:bindingObject): the role declaration
1825
                    #    supplies the direction, which fixes which raw endpoint is the space vs
1826
                    #    the agent. INVERSE = <space> pred <agent>; REGULAR = <agent> pred <space>.
1827
                    {
1828
                      ?rd gen:hasRegularProperty ?pred .
1829
                      ?ri npa:regularProperty ?pred ;
1830
                          npa:forSpace ?instSpace ;
1831
                          npa:forAgent ?agent .
1832
                      BIND(npa:regularProperty AS ?dirPred)
1833
                    }
1834
                    UNION
1835
                    {
1836
                      ?rd gen:hasInverseProperty ?pred .
1837
                      ?ri npa:inverseProperty ?pred ;
1838
                          npa:forSpace ?instSpace ;
1839
                          npa:forAgent ?agent .
1840
                      BIND(npa:inverseProperty AS ?dirPred)
1841
                    }
1842
                    UNION
1843
                    {
1844
                      ?rd gen:hasInverseProperty ?pred .
1845
                      ?ri npa:rolePredicate   ?pred ;
1846
                          npa:bindingSubject  ?instSpace ;
1847
                          npa:bindingObject   ?agent .
1848
                      BIND(npa:inverseProperty AS ?dirPred)
1849
                    }
1850
                    UNION
1851
                    {
1852
                      ?rd gen:hasRegularProperty ?pred .
1853
                      ?ri npa:rolePredicate   ?pred ;
1854
                          npa:bindingObject   ?instSpace ;
1855
                          npa:bindingSubject  ?agent .
1856
                      BIND(npa:regularProperty AS ?dirPred)
1857
                    }
1858
                    # 4. Common instantiation columns. ?instSpace was resolved to this ref
1859
                    #    above (canonical or owl:sameAs alias), so an alias-named instantiation
1860
                    #    joins the same ?spaceRef as a canonical one. The materialized row still
1861
                    #    carries npa:forSpace ?space (the attachment's IRI) for the transitional
1862
                    #    dual-emit, so pre-ref reads see the member under the space's primary IRI.
1863
                    ?ri a gen:RoleInstantiation ;
1864
                        npa:pubkeyHash ?pkh ;
1865
                        npa:viaNanopub ?np .
1866
                    # Candidate grant timestamp for the revocation latest-wins (issue #129);
1867
                    # absent ⇒ epoch (always loses).
1868
                    OPTIONAL { ?ri <http://purl.org/dc/terms/created> ?candCreatedRaw . }
1869
                  }
1870
                  BIND(COALESCE(?candCreatedRaw, %11$s) AS ?candCreated)
1871
                  # 5. Publisher constraint (incl. AccountState resolution).
1872
                  GRAPH <%3$s> {
1873
                    %8$s
1874
                  }
1875
                  # 5a. Mint the per-ref state subject: (?ri, ?spaceRef) → ?ri2.
1876
                  BIND(IRI(CONCAT(STR(?ri), "__", ENCODE_FOR_URI(STR(?spaceRef)))) AS ?ri2)
1877
                  # 6. Load-number filter on bound ?np.
1878
                  GRAPH <%9$s> {
1879
                    ?np npa:hasLoadNumber ?ln .
1880
                    FILTER (?ln > %5$d)
1881
                  }
1882
                  # 7. Instantiation invalidation filter — outside the GRAPH block so the
1883
                  #    planner defers it until ?np is bound. Role-DECLARATION invalidation is
1884
                  #    deliberately NOT consulted: the tier already anchors on the admin-
1885
                  #    validated attachment (?ra), which is removed when an admin retracts it,
1886
                  #    so admin control is fully enforced there. Letting the declaration's
1887
                  #    author (usually not the space admin) supersede/retract their declaration
1888
                  #    strip a space's members is the same cross-author-strip anti-pattern as
1889
                  #    issue #112. Role IRIs are version-pinned, so the attached definition is
1890
                  #    immutable regardless of the declaration nanopub's later lifecycle.
1891
                  %6$s
1892
                  # 7a. Revocation latest-wins (issue #129): suppress if a newer authorized
1893
                  #     gen:RevokedRoleInstantiation shadows this (space, agent, role) key.
1894
                  %10$s
1895
                  # 8. Dedup last — keyed on (ref, agent, nanopub).
1896
                  FILTER NOT EXISTS { GRAPH <%3$s> {
1897
                    ?existing a gen:RoleInstantiation ;
1898
                              npa:forSpaceRef ?spaceRef ;
1899
                              npa:forAgent ?agent ;
1900
                              npa:viaNanopub ?np .
1901
                  } }
1902
                }
1903
                """.formatted(
3✔
1904
                NPA.NAMESPACE,
1905
                GEN.NAMESPACE,
1906
                graph,
1907
                SpacesVocab.SPACES_GRAPH,
1908
                lastProcessed,
15✔
1909
                invalidationFilter("np"),
54✔
1910
                tierClass,
1911
                publisherConstraint,
1912
                NPA.GRAPH,
1913
                nonAdminRevocationSuppressionFilter(graph, tierClass),
18✔
1914
                EPOCH_DT);
1915
    }
1916

1917
    /**
1918
     * Sub-space admit pass. Copies validated {@code npa:SubSpaceDeclaration}
1919
     * extraction rows into the space-state graph (preserving the {@code npasub:}
1920
     * subject) and emits convenience {@code <child> npa:isSubSpaceOf <parent>} and
1921
     * {@code <parent> npa:hasSubSpace <child>} direct triples. Two satisfaction
1922
     * modes joined by UNION:
1923
     * <ul>
1924
     *   <li>Mode A — the declaration's publisher is a validated admin of both the
1925
     *       child and the parent space.</li>
1926
     *   <li>Mode B — a different non-invalidated declaration for the same
1927
     *       {@code (child, parent)} pair exists, and the two publishers between
1928
     *       them cover both admin sides (i.e. one of them is admin of the child,
1929
     *       one of them is admin of the parent — possibly the same one twice if
1930
     *       both happen to be admin of both).</li>
1931
     * </ul>
1932
     *
1933
     * <p>Mode-B late-arrival: when only the partner declaration is new in this
1934
     * cycle (the primary is older than {@code lastProcessed}), the load-number
1935
     * filter on {@code ?np} excludes the candidate. The late-arrival sweep
1936
     * ({@link #runDownstreamWithoutLoadFilter}) re-runs this pass without the
1937
     * load filter and catches it.
1938
     */
1939
    static String subSpaceAdmitUpdate(IRI graph, long lastProcessed) {
1940
        return """
69✔
1941
                PREFIX npa: <%1$s>
1942
                PREFIX gen: <%2$s>
1943
                INSERT { GRAPH <%3$s> {
1944
                  ?d a npa:SubSpaceDeclaration ;
1945
                     npa:childSpace  ?child ;
1946
                     npa:parentSpace ?parent ;
1947
                     npa:viaNanopub  ?np .
1948
                  ?childRef  npa:isSubSpaceOf ?parentRef .
1949
                  ?parentRef npa:hasSubSpace  ?childRef  .
1950
                  # Reified per-(nanopub, ref-pair) provenance link (issue #125 finding #5):
1951
                  # carries npa:viaNanopub plus both the ref and IRI endpoints, so the
1952
                  # invalidation cleanup can drop the convenience edges below once no
1953
                  # surviving link backs them — instead of leaving them sticky until the
1954
                  # next periodic full rebuild.
1955
                  ?ssLink a npa:SubSpaceLink ;
1956
                          npa:viaNanopub     ?np ;
1957
                          npa:childSpaceRef  ?childRef ;
1958
                          npa:parentSpaceRef ?parentRef ;
1959
                          npa:childSpace     ?child ;
1960
                          npa:parentSpace    ?parent .
1961
                  # TRANSITIONAL-DUAL-EMIT (Phase 1.5; remove in Phase 4): IRI-valued
1962
                  # sub-space edge alongside the ref-to-ref one, so pre-ref published
1963
                  # queries that key on the bare Space IRI keep binding on a mixed-version
1964
                  # fleet. See doc/report-2026-06-12-mixed-fleet-spaceref-breakage.md.
1965
                  ?child  npa:isSubSpaceOf ?parent .
1966
                  ?parent npa:hasSubSpace  ?child  .
1967
                } }
1968
                WHERE {
1969
                  # 1. Anchor: candidate declarations from the extraction graph.
1970
                  GRAPH <%4$s> {
1971
                    ?d a npa:SubSpaceDeclaration ;
1972
                       npa:childSpace  ?child ;
1973
                       npa:parentSpace ?parent ;
1974
                       npa:pubkeyHash  ?pkh ;
1975
                       npa:viaNanopub  ?np .
1976
                  }
1977
                  # 2. Mirror: resolve ?pkh → ?publisher via the trust-approved row.
1978
                  GRAPH <%3$s> {
1979
                    ?acct a npa:AccountState ;
1980
                          npa:pubkey ?pkh ;
1981
                          npa:agent  ?publisher .
1982
                  }
1983
                  # 3. Authority gate, ref-keyed. The edge is emitted ref-to-ref between
1984
                  #    the child ref and parent ref the authorizing admin governs; the
1985
                  #    admin rows' dual-emitted npa:forSpace binds the refs to the child /
1986
                  #    parent IRIs (cross-product when an IRI has several governed refs).
1987
                  {
1988
                    # Mode A — publisher is admin of BOTH a child ref and a parent ref.
1989
                    GRAPH <%3$s> {
1990
                      ?riC a gen:RoleInstantiation ;
1991
                           npa:inverseProperty gen:hasAdmin ;
1992
                           npa:forSpace ?child ;
1993
                           npa:forSpaceRef ?childRef ;
1994
                           npa:forAgent ?publisher .
1995
                      ?riP a gen:RoleInstantiation ;
1996
                           npa:inverseProperty gen:hasAdmin ;
1997
                           npa:forSpace ?parent ;
1998
                           npa:forSpaceRef ?parentRef ;
1999
                           npa:forAgent ?publisher .
2000
                    }
2001
                  }
2002
                  UNION
2003
                  {
2004
                    # Mode B — co-declaration whose publisher covers the side this
2005
                    # one's publisher doesn't. Between {publisher, publisher2},
2006
                    # both admin sides must be covered.
2007
                    GRAPH <%4$s> {
2008
                      ?d2 a npa:SubSpaceDeclaration ;
2009
                          npa:childSpace  ?child ;
2010
                          npa:parentSpace ?parent ;
2011
                          npa:pubkeyHash  ?pkh2 ;
2012
                          npa:viaNanopub  ?np2 .
2013
                      FILTER (?np2 != ?np)
2014
                    }
2015
                    %8$s
2016
                    GRAPH <%3$s> {
2017
                      ?acct2 a npa:AccountState ;
2018
                             npa:pubkey ?pkh2 ;
2019
                             npa:agent  ?publisher2 .
2020
                      ?riA a gen:RoleInstantiation ;
2021
                           npa:inverseProperty gen:hasAdmin ;
2022
                           npa:forSpace ?child ;
2023
                           npa:forSpaceRef ?childRef .
2024
                      { ?riA npa:forAgent ?publisher } UNION { ?riA npa:forAgent ?publisher2 }
2025
                      ?riB a gen:RoleInstantiation ;
2026
                           npa:inverseProperty gen:hasAdmin ;
2027
                           npa:forSpace ?parent ;
2028
                           npa:forSpaceRef ?parentRef .
2029
                      { ?riB npa:forAgent ?publisher } UNION { ?riB npa:forAgent ?publisher2 }
2030
                    }
2031
                  }
2032
                  # 4. Invalidation filter on the primary declaration's nanopub.
2033
                  %6$s
2034
                  # 5. Load-number filter on bound ?np.
2035
                  GRAPH <%7$s> {
2036
                    ?np npa:hasLoadNumber ?ln .
2037
                    FILTER (?ln > %5$d)
2038
                  }
2039
                  # 6. Mint the per-(nanopub, ref-pair) provenance link IRI and dedup on it
2040
                  #    (not on the bare edge). Keyed on ?np so every backing declaration of
2041
                  #    the same ref-pair records its own removable link; the convenience
2042
                  #    edges above are re-asserted idempotently.
2043
                  BIND(IRI(CONCAT("http://purl.org/nanopub/admin/spacelink/subspace/",
2044
                                  MD5(CONCAT(STR(?np), "|", STR(?childRef), "|", STR(?parentRef))))) AS ?ssLink)
2045
                  FILTER NOT EXISTS { GRAPH <%3$s> {
2046
                    ?ssLink a npa:SubSpaceLink .
2047
                  } }
2048
                }
2049
                """.formatted(
3✔
2050
                NPA.NAMESPACE,
2051
                GEN.NAMESPACE,
2052
                graph,
2053
                SpacesVocab.SPACES_GRAPH,
2054
                lastProcessed,
15✔
2055
                invalidationFilter("np"),
27✔
2056
                NPA.GRAPH,
2057
                invalidationFilter("np2"));
6✔
2058
    }
2059

2060
    /**
2061
     * Maintained-resource admit pass. Copies validated
2062
     * {@code npa:MaintainedResourceDeclaration} extraction rows into the space-state
2063
     * graph (preserving the {@code npamrd:} subject) and emits convenience
2064
     * {@code <r> npa:isMaintainedBy <s>} and {@code <s> npa:hasMaintainedResource <r>}
2065
     * direct triples. Single satisfaction mode:
2066
     * <ul>
2067
     *   <li>Mode A — the declaration's publisher is a validated admin of the
2068
     *       maintaining space.</li>
2069
     * </ul>
2070
     *
2071
     * <p>No Mode B because only one space is involved; the two-sides-must-be-covered
2072
     * concern that drives sub-space Mode B doesn't apply. Late-arrival is still
2073
     * possible (declaration lands before the publisher's admin grant becomes valid):
2074
     * the load-number filter on {@code ?np} excludes the candidate, and the
2075
     * late-arrival sweep ({@link #runDownstreamWithoutLoadFilter}) re-runs this pass
2076
     * without the load filter and catches it.
2077
     */
2078
    static String maintainedResourceAdmitUpdate(IRI graph, long lastProcessed) {
2079
        return """
69✔
2080
                PREFIX npa: <%1$s>
2081
                PREFIX gen: <%2$s>
2082
                INSERT { GRAPH <%3$s> {
2083
                  ?d a npa:MaintainedResourceDeclaration ;
2084
                     npa:resourceIri     ?r ;
2085
                     npa:maintainerSpace ?s ;
2086
                     npa:viaNanopub      ?np .
2087
                  ?r npa:isMaintainedBy        ?sRef .
2088
                  ?sRef npa:hasMaintainedResource ?r .
2089
                  # Uniform ref-valued resource→governing-space-ref edge (issue #130). The
2090
                  # same predicate the reflexive space self-edge uses, so a single consumer
2091
                  # hop covers both "resource maintained by space S" and "resource IS a space".
2092
                  # Backed by the same MaintainedResourceLink below, so the invalidation
2093
                  # cleanup sweeps it alongside isMaintainedBy.
2094
                  ?r npa:hasGoverningSpaceRef  ?sRef .
2095
                  # Reified per-(nanopub, resource→ref) provenance link (issue #125 finding
2096
                  # #5): lets the invalidation cleanup drop the convenience edges below once
2097
                  # no surviving link backs them, instead of leaving them sticky.
2098
                  ?mrLink a npa:MaintainedResourceLink ;
2099
                          npa:viaNanopub         ?np ;
2100
                          npa:resourceIri        ?r ;
2101
                          npa:maintainerSpaceRef ?sRef ;
2102
                          npa:maintainerSpace    ?s .
2103
                  # TRANSITIONAL-DUAL-EMIT (Phase 1.5; remove in Phase 4): IRI-valued
2104
                  # maintained-resource edge alongside the resource→ref one, so pre-ref
2105
                  # published queries (e.g. get-view-displays' maintained hop) keep binding
2106
                  # on a mixed-version fleet. This is the edge whose absence broke 1.15.0 —
2107
                  # see doc/report-2026-06-12-mixed-fleet-spaceref-breakage.md.
2108
                  ?r npa:isMaintainedBy        ?s .
2109
                  ?s npa:hasMaintainedResource ?r .
2110
                } }
2111
                WHERE {
2112
                  # 1. Anchor: candidate declarations from the extraction graph.
2113
                  GRAPH <%4$s> {
2114
                    ?d a npa:MaintainedResourceDeclaration ;
2115
                       npa:resourceIri     ?r ;
2116
                       npa:maintainerSpace ?s ;
2117
                       npa:pubkeyHash      ?pkh ;
2118
                       npa:viaNanopub      ?np .
2119
                  }
2120
                  # 2. Mirror: resolve ?pkh → ?publisher via the trust-approved row.
2121
                  GRAPH <%3$s> {
2122
                    ?acct a npa:AccountState ;
2123
                          npa:pubkey ?pkh ;
2124
                          npa:agent  ?publisher .
2125
                    # 3. Authority gate (Mode A only): publisher is admin of a ref of the
2126
                    #    maintaining space. ?sRef = that ref (resource → ref edge).
2127
                    ?riA a gen:RoleInstantiation ;
2128
                         npa:inverseProperty gen:hasAdmin ;
2129
                         npa:forSpace ?s ;
2130
                         npa:forSpaceRef ?sRef ;
2131
                         npa:forAgent ?publisher .
2132
                  }
2133
                  # 4. Invalidation filter on the declaration's nanopub.
2134
                  %6$s
2135
                  # 5. Load-number filter on bound ?np.
2136
                  GRAPH <%7$s> {
2137
                    ?np npa:hasLoadNumber ?ln .
2138
                    FILTER (?ln > %5$d)
2139
                  }
2140
                  # 6. Mint the per-(nanopub, resource→ref) provenance link IRI and dedup on
2141
                  #    it (not on the bare edge), so every backing declaration records its own
2142
                  #    removable link; the convenience edges above are re-asserted idempotently.
2143
                  BIND(IRI(CONCAT("http://purl.org/nanopub/admin/spacelink/maintained/",
2144
                                  MD5(CONCAT(STR(?np), "|", STR(?r), "|", STR(?sRef))))) AS ?mrLink)
2145
                  FILTER NOT EXISTS { GRAPH <%3$s> {
2146
                    ?mrLink a npa:MaintainedResourceLink .
2147
                  } }
2148
                }
2149
                """.formatted(
3✔
2150
                NPA.NAMESPACE,
2151
                GEN.NAMESPACE,
2152
                graph,
2153
                SpacesVocab.SPACES_GRAPH,
2154
                lastProcessed,
15✔
2155
                invalidationFilter("np"),
18✔
2156
                NPA.GRAPH);
2157
    }
2158

2159
    /**
2160
     * Space-alias admit pass (issue #113). Copies validated
2161
     * {@code npa:SpaceAliasDeclaration} extraction rows into the space-state graph
2162
     * (preserving the {@code npaalias:} subject) and emits the directional
2163
     * {@code <alias> npa:sameAsSpace <canonical>} edge consumed by the alias-aware
2164
     * admin-authority lookups in {@link #attachmentValidationUpdate},
2165
     * {@link #PUBLISHER_IS_ADMIN}, and {@link #publisherIsTieredRole}.
2166
     *
2167
     * <p>Two gates, both read against the (already-settled) admin closure in the
2168
     * space-state graph:
2169
     * <ul>
2170
     *   <li><b>Authority</b> — the declaration's publisher (resolved via the mirrored
2171
     *       trust-approved {@code AccountState}) is a validated admin of the
2172
     *       <em>canonical</em> space. The alias is declared inside the canonical
2173
     *       space's own {@code gen:Space} nanopub, so this is the same evidence rule
2174
     *       as a {@code gen:hasRole} attachment.</li>
2175
     *   <li><b>Anti-hijack</b> — the alias must not be an independently-governed live
2176
     *       space: it must have no admin who is not also an admin of the canonical
2177
     *       space ({@code admins(alias) ⊆ admins(canonical)}). The common rename case
2178
     *       (the alias's own definition was superseded, so it has no live admin
2179
     *       closure) passes trivially; an attacker publishing
2180
     *       {@code <evil> owl:sameAs <activeSpace>} is rejected because the active
2181
     *       space has admins not in evil's set.</li>
2182
     * </ul>
2183
     *
2184
     * <p>Late-arrival: when the canonical admin grant only becomes valid in the same
2185
     * cycle as the declaration, the load-number filter on {@code ?np} excludes the
2186
     * candidate; the late-arrival sweep ({@link #runDownstreamWithoutLoadFilter})
2187
     * re-runs this pass without the load filter and catches it.
2188
     */
2189
    static String aliasAdmitUpdate(IRI graph, long lastProcessed) {
2190
        // Ref-keyed (see doc/design-spaceref-isolation.md). The declaration names bare
2191
        // canonical/alias IRIs. It is admitted per canonical *ref* whose admin set
2192
        // contains the publisher; the emitted edge is ref-valued on the canonical side
2193
        // (<alias> npa:sameAsSpace <canonicalRef>), which is what the alias-aware admin
2194
        // lookups in the attachment tier consume. Anti-hijack compares the alias IRI's
2195
        // admins against that specific canonical ref's admins — strictly tighter than the
2196
        // old bare-IRI form.
2197
        return """
69✔
2198
                PREFIX npa: <%1$s>
2199
                PREFIX gen: <%2$s>
2200
                INSERT { GRAPH <%3$s> {
2201
                  ?d a npa:SpaceAliasDeclaration ;
2202
                     npa:canonicalSpace ?canonical ;
2203
                     npa:aliasSpace     ?alias ;
2204
                     npa:viaNanopub     ?np .
2205
                  ?alias npa:sameAsSpace ?canonRef .
2206
                  # Reified per-(nanopub, alias→canonical ref) provenance link (issue #125
2207
                  # finding #5). The alias edge feeds the admin-authority closure, so this
2208
                  # is the load-bearing case: the cleanup can now drop the edge when its
2209
                  # declaration is invalidated, rather than letting admin authority outlive
2210
                  # a retraction until the next periodic full rebuild.
2211
                  ?alLink a npa:SpaceAliasLink ;
2212
                          npa:viaNanopub        ?np ;
2213
                          npa:aliasSpace        ?alias ;
2214
                          npa:canonicalSpaceRef ?canonRef ;
2215
                          npa:canonicalSpace    ?canonical .
2216
                  # TRANSITIONAL-DUAL-EMIT (Phase 1.5; remove in Phase 4): IRI-valued
2217
                  # alias edge alongside the ref-valued one, so pre-ref published queries
2218
                  # that resolve owl:sameAs by bare canonical IRI keep binding on a
2219
                  # mixed-version fleet. Internal alias-aware lookups (attachment tier)
2220
                  # join through npa:forSpaceRef, which is ref-valued, so this IRI-valued
2221
                  # object never satisfies them — it is inert internally, read-only for
2222
                  # legacy consumers. See doc/report-2026-06-12-mixed-fleet-spaceref-breakage.md.
2223
                  ?alias npa:sameAsSpace ?canonical .
2224
                } }
2225
                WHERE {
2226
                  # 1. Anchor: candidate alias declarations from the extraction graph.
2227
                  GRAPH <%4$s> {
2228
                    ?d a npa:SpaceAliasDeclaration ;
2229
                       npa:canonicalSpace ?canonical ;
2230
                       npa:aliasSpace     ?alias ;
2231
                       npa:pubkeyHash     ?pkh ;
2232
                       npa:viaNanopub     ?np .
2233
                  }
2234
                  # 2. Authority gate per canonical ref: ?canonRef is a ref of ?canonical
2235
                  #    whose admin set contains the declaration's publisher.
2236
                  GRAPH <%4$s> { ?canonRef npa:spaceIri ?canonical . }
2237
                  GRAPH <%3$s> {
2238
                    ?acct a npa:AccountState ;
2239
                          npa:pubkey ?pkh ;
2240
                          npa:agent  ?publisher .
2241
                    ?adminRI a gen:RoleInstantiation ;
2242
                             npa:inverseProperty gen:hasAdmin ;
2243
                             npa:forSpaceRef ?canonRef ;
2244
                             npa:forAgent ?publisher .
2245
                  }
2246
                  # 3. Anti-hijack: the alias IRI must have no admin who is not also an
2247
                  #    admin of this canonical ref (admins(alias) ⊆ admins(canonRef)).
2248
                  FILTER NOT EXISTS {
2249
                    GRAPH <%3$s> {
2250
                      ?aliasAdmin a gen:RoleInstantiation ;
2251
                                  npa:inverseProperty gen:hasAdmin ;
2252
                                  npa:forSpace ?alias ;
2253
                                  npa:forAgent ?otherAgent .
2254
                    }
2255
                    FILTER NOT EXISTS {
2256
                      GRAPH <%3$s> {
2257
                        ?canonAdmin a gen:RoleInstantiation ;
2258
                                    npa:inverseProperty gen:hasAdmin ;
2259
                                    npa:forSpaceRef ?canonRef ;
2260
                                    npa:forAgent ?otherAgent .
2261
                      }
2262
                    }
2263
                  }
2264
                  # 4. Invalidation filter on the declaration's nanopub.
2265
                  %6$s
2266
                  # 5. Load-number filter on bound ?np.
2267
                  GRAPH <%7$s> {
2268
                    ?np npa:hasLoadNumber ?ln .
2269
                    FILTER (?ln > %5$d)
2270
                  }
2271
                  # 6. Mint the per-(nanopub, alias→canonical ref) provenance link IRI and
2272
                  #    dedup on it (not on the bare edge), so every backing declaration records
2273
                  #    its own removable link; the convenience edges above are re-asserted
2274
                  #    idempotently.
2275
                  BIND(IRI(CONCAT("http://purl.org/nanopub/admin/spacelink/alias/",
2276
                                  MD5(CONCAT(STR(?np), "|", STR(?alias), "|", STR(?canonRef))))) AS ?alLink)
2277
                  FILTER NOT EXISTS { GRAPH <%3$s> {
2278
                    ?alLink a npa:SpaceAliasLink .
2279
                  } }
2280
                }
2281
                """.formatted(
3✔
2282
                NPA.NAMESPACE,
2283
                GEN.NAMESPACE,
2284
                graph,
2285
                SpacesVocab.SPACES_GRAPH,
2286
                lastProcessed,
15✔
2287
                invalidationFilter("np"),
18✔
2288
                NPA.GRAPH);
2289
    }
2290

2291
    /**
2292
     * URL-prefix sub-space fallback admit pass. For every pair of {@code SpaceRef}
2293
     * aggregates where the child's {@code npa:hasIdPrefix} matches the parent's
2294
     * {@code npa:spaceIri}, emits convenience {@code <child> npa:isSubSpaceOf <parent>}
2295
     * and {@code <parent> npa:hasSubSpace <child>} direct triples plus a reified
2296
     * {@code npa:DerivedSubSpaceLink} tag carrying {@code npa:derivationKind
2297
     * npa:byUrlPrefix} so consumers can hide derived edges.
2298
     *
2299
     * <p>Per-child suppression: any validated {@code npa:SubSpaceDeclaration} on the
2300
     * child in {@code npass:<…>} suppresses every fallback edge for that child.
2301
     * Suppression checks the validated set (not raw extraction-graph declarations)
2302
     * so an unapproved or in-flight Mode B declaration doesn't silently hide both
2303
     * the URL-prefix fallback and the (still-invalid) explicit relation.
2304
     *
2305
     * <p>Run order: must run after {@link #subSpaceAdmitUpdate} commits in the
2306
     * same cycle so the suppression check sees this cycle's freshly-validated
2307
     * declarations.
2308
     *
2309
     * <p>No load-number filter: the fallback depends on which Spaces exist (parent
2310
     * + child {@code SpaceRef}s), not on which were just added. Always full-scan;
2311
     * the dedup {@code FILTER NOT EXISTS} on the tag IRI prevents re-insertion.
2312
     *
2313
     * <p>No invalidation handling: derived edges have no source nanopub. Two
2314
     * staleness modes: (a) child later gets first validated declaration → old
2315
     * derived edges stay sticky until the next periodic rebuild (same policy as
2316
     * admin-RI invalidation); (b) child loses last validated declaration → the
2317
     * regular fallback pass on the next cycle re-engages, adds derived edges
2318
     * incrementally, no rebuild needed.
2319
     */
2320
    static String subSpacePrefixFallbackUpdate(IRI graph) {
2321
        return """
48✔
2322
                PREFIX npa: <%1$s>
2323
                INSERT { GRAPH <%2$s> {
2324
                  ?childRef  npa:isSubSpaceOf ?parentRef .
2325
                  ?parentRef npa:hasSubSpace  ?childRef  .
2326
                  # TRANSITIONAL-DUAL-EMIT (Phase 1.5; remove in Phase 4): IRI-valued
2327
                  # derived sub-space edge alongside the ref-to-ref one, mirroring the
2328
                  # explicit sub-space pass, so pre-ref published queries keep binding on a
2329
                  # mixed-version fleet. See doc/report-2026-06-12-mixed-fleet-spaceref-breakage.md.
2330
                  ?child  npa:isSubSpaceOf ?parent .
2331
                  ?parent npa:hasSubSpace  ?child  .
2332
                  ?tagIri a npa:DerivedSubSpaceLink ;
2333
                          npa:childSpace     ?child ;
2334
                          npa:parentSpace    ?parent ;
2335
                          # Ref endpoints too (issue #125 finding #5), so the sub-space
2336
                          # orphan-sweep recognizes a prefix-derived ref edge as backed and
2337
                          # never deletes it. Derived links have no source nanopub, so they
2338
                          # are never invalidation-deleted; the fallback self-heals each cycle.
2339
                          npa:childSpaceRef  ?childRef ;
2340
                          npa:parentSpaceRef ?parentRef ;
2341
                          npa:derivationKind npa:byUrlPrefix .
2342
                } }
2343
                WHERE {
2344
                  # 1. Anchor: child SpaceRef → its path-prefixes (extracted at load
2345
                  #    time from the Space IRI; see SpacesExtractor.enumerateIdPrefixes).
2346
                  GRAPH <%3$s> {
2347
                    ?childRef  npa:spaceIri    ?child ;
2348
                               npa:hasIdPrefix ?parent .
2349
                    # 2. Parent SpaceRef must exist for the same IRI as the prefix.
2350
                    ?parentRef npa:spaceIri    ?parent .
2351
                  }
2352
                  # 3. Suppress fallback for any child that has a validated declaration
2353
                  #    in this state graph. Per-child IRI, all-or-nothing.
2354
                  FILTER NOT EXISTS {
2355
                    GRAPH <%2$s> {
2356
                      ?d a npa:SubSpaceDeclaration ;
2357
                         npa:childSpace ?child .
2358
                    }
2359
                  }
2360
                  # 4. Mint a deterministic tag IRI per (child ref, parent ref) — the edge
2361
                  #    is emitted ref-to-ref, so the tag and dedup are per ref-pair.
2362
                  BIND(IRI(CONCAT("http://purl.org/nanopub/admin/derivedlink/",
2363
                                  MD5(CONCAT(STR(?childRef), "|", STR(?parentRef))))) AS ?tagIri)
2364
                  # 5. Dedup: don't re-insert if this tag is already present.
2365
                  FILTER NOT EXISTS {
2366
                    GRAPH <%2$s> {
2367
                      ?tagIri a npa:DerivedSubSpaceLink .
2368
                    }
2369
                  }
2370
                }
2371
                """.formatted(
3✔
2372
                NPA.NAMESPACE,
2373
                graph,
2374
                SpacesVocab.SPACES_GRAPH);
2375
    }
2376

2377
    /**
2378
     * Reflexive governing-space-ref pass (issue #130). For every {@code SpaceRef}
2379
     * aggregate {@code ?spaceRef} (identified by {@code npa:spaceIri ?space} in the
2380
     * extraction graph), emits {@code <space> npa:hasGoverningSpaceRef <spaceRef>} into
2381
     * the space-state graph — the space pointing at its own ref through the same predicate
2382
     * a maintained resource uses to point at its maintaining space's ref (emitted in
2383
     * {@link #maintainedResourceAdmitUpdate}).
2384
     *
2385
     * <p>This removes the zero-hop special case from consumer authority gates: instead of
2386
     * {@code ?resource npa:isMaintainedBy? ?space} (a bare-IRI optional path that breaks
2387
     * once the hop is ref-valued), a consumer does a single mandatory
2388
     * {@code ?resource npa:hasGoverningSpaceRef ?spaceRef} that binds whether the resource
2389
     * is a maintained resource or a space itself. A space IRI claimed by several refs emits
2390
     * one edge per ref — the non-ref consumer variant's merged-across-refs behaviour falls
2391
     * out naturally; the ref variant pins {@code ?passedRef}.
2392
     *
2393
     * <p>Self-healing, like {@link #subSpacePrefixFallbackUpdate}: the edge has no source
2394
     * nanopub (it follows purely from a {@code SpaceRef} existing), so there is no
2395
     * invalidation handling and no load-number filter — always full-scan, with the dedup
2396
     * {@code FILTER NOT EXISTS} on the edge preventing re-insertion. A {@code SpaceRef}
2397
     * disappearing is itself a structural-rebuild event, which clears its reflexive edge.
2398
     */
2399
    static String governingSpaceRefReflexiveUpdate(IRI graph) {
2400
        return """
48✔
2401
                PREFIX npa: <%1$s>
2402
                INSERT { GRAPH <%2$s> {
2403
                  ?space npa:hasGoverningSpaceRef ?spaceRef .
2404
                } }
2405
                WHERE {
2406
                  GRAPH <%3$s> { ?spaceRef npa:spaceIri ?space . }
2407
                  FILTER NOT EXISTS { GRAPH <%2$s> {
2408
                    ?space npa:hasGoverningSpaceRef ?spaceRef .
2409
                  } }
2410
                }
2411
                """.formatted(
3✔
2412
                NPA.NAMESPACE,
2413
                graph,
2414
                SpacesVocab.SPACES_GRAPH);
2415
    }
2416

2417
    // ---------------- Invalidation templates (incremental cycle) ----------------
2418

2419
    /**
2420
     * WHERE clause shared by the admin-RI invalidation ASK precheck and the
2421
     * matching DELETE. Identifies admin-tier {@code gen:RoleInstantiation} rows
2422
     * in the space-state graph whose {@code npa:viaNanopub} is the target of an
2423
     * {@code npx:invalidates} triple in {@code npa:graph} whose subject nanopub
2424
     * has a load number in {@code (lastProcessed, ∞)}.
2425
     */
2426
    static String adminInvalidationCheckWhere(IRI graph, long lastProcessed) {
2427
        return String.format("""
60✔
2428
                  GRAPH <%1$s> {
2429
                    ?ri a gen:RoleInstantiation ;
2430
                        npa:inverseProperty gen:hasAdmin ;
2431
                        npa:viaNanopub ?np .
2432
                  }
2433
                  GRAPH <%2$s> {
2434
                    ?invNp <%3$s> ?np ;
2435
                           npa:hasLoadNumber ?ln .
2436
                    FILTER (?ln > %4$d)
2437
                    %5$s
2438
                  }
2439
                """, graph, NPA.GRAPH, NPX.INVALIDATES, lastProcessed,
18✔
2440
                samePublisherClause("invNp", "np"));
6✔
2441
    }
2442

2443
    /** DELETE template for admin-tier RoleInstantiations whose source nanopub was invalidated. */
2444
    static String adminInvalidationDelete(IRI graph, long lastProcessed) {
2445
        return String.format("""
63✔
2446
                PREFIX npa: <%1$s>
2447
                PREFIX gen: <%2$s>
2448
                DELETE { GRAPH <%3$s> {
2449
                  ?ri ?p ?o .
2450
                } }
2451
                WHERE {
2452
                  GRAPH <%3$s> { ?ri ?p ?o . }
2453
                %4$s
2454
                }
2455
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
2456
                adminInvalidationCheckWhere(graph, lastProcessed));
6✔
2457
    }
2458

2459
    /** WHERE clause for RoleAssignment invalidation. */
2460
    static String roleAssignmentInvalidationCheckWhere(IRI graph, long lastProcessed) {
2461
        return String.format("""
60✔
2462
                  GRAPH <%1$s> {
2463
                    ?ra a gen:RoleAssignment ;
2464
                        npa:viaNanopub ?np .
2465
                  }
2466
                  GRAPH <%2$s> {
2467
                    ?invNp <%3$s> ?np ;
2468
                           npa:hasLoadNumber ?ln .
2469
                    FILTER (?ln > %4$d)
2470
                    %5$s
2471
                  }
2472
                """, graph, NPA.GRAPH, NPX.INVALIDATES, lastProcessed,
18✔
2473
                samePublisherClause("invNp", "np"));
6✔
2474
    }
2475

2476
    /** DELETE template for RoleAssignments whose source nanopub was invalidated. */
2477
    static String roleAssignmentInvalidationDelete(IRI graph, long lastProcessed) {
2478
        return String.format("""
63✔
2479
                PREFIX npa: <%1$s>
2480
                PREFIX gen: <%2$s>
2481
                DELETE { GRAPH <%3$s> {
2482
                  ?ra ?p ?o .
2483
                } }
2484
                WHERE {
2485
                  GRAPH <%3$s> { ?ra ?p ?o . }
2486
                %4$s
2487
                }
2488
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
2489
                roleAssignmentInvalidationCheckWhere(graph, lastProcessed));
6✔
2490
    }
2491

2492
    /**
2493
     * DELETE template for non-admin (leaf-tier) RoleInstantiations whose source
2494
     * nanopub was invalidated. Identified as {@code gen:RoleInstantiation} rows
2495
     * lacking the admin-pinning {@code npa:inverseProperty gen:hasAdmin} triple.
2496
     * No flag is set; leaf-tier removals are recoverable on the next cycle.
2497
     */
2498
    static String leafTierInvalidationDelete(IRI graph, long lastProcessed) {
2499
        return String.format("""
84✔
2500
                PREFIX npa: <%1$s>
2501
                PREFIX gen: <%2$s>
2502
                DELETE { GRAPH <%3$s> {
2503
                  ?ri ?p ?o .
2504
                } }
2505
                WHERE {
2506
                  GRAPH <%3$s> {
2507
                    ?ri a gen:RoleInstantiation ;
2508
                        npa:viaNanopub ?np .
2509
                    FILTER NOT EXISTS { ?ri npa:inverseProperty gen:hasAdmin }
2510
                    ?ri ?p ?o .
2511
                  }
2512
                  GRAPH <%4$s> {
2513
                    ?invNp <%5$s> ?np ;
2514
                           npa:hasLoadNumber ?ln .
2515
                    FILTER (?ln > %6$d)
2516
                    %7$s
2517
                  }
2518
                }
2519
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
2520
                NPA.GRAPH, NPX.INVALIDATES, lastProcessed,
18✔
2521
                samePublisherClause("invNp", "np"));
6✔
2522
    }
2523

2524
    /**
2525
     * WHERE clause shared by the sub-space invalidation ASK precheck and the
2526
     * matching DELETE. Identifies validated {@code npa:SubSpaceDeclaration} rows
2527
     * in the space-state graph whose {@code npa:viaNanopub} is the target of an
2528
     * {@code npx:invalidates} triple in {@code npa:graph} whose subject nanopub
2529
     * has a load number in {@code (lastProcessed, ∞)}.
2530
     */
2531
    static String subSpaceInvalidationCheckWhere(IRI graph, long lastProcessed) {
2532
        return String.format("""
60✔
2533
                  GRAPH <%1$s> {
2534
                    ?d a npa:SubSpaceDeclaration ;
2535
                       npa:viaNanopub ?np .
2536
                  }
2537
                  GRAPH <%2$s> {
2538
                    ?invNp <%3$s> ?np ;
2539
                           npa:hasLoadNumber ?ln .
2540
                    FILTER (?ln > %4$d)
2541
                    %5$s
2542
                  }
2543
                """, graph, NPA.GRAPH, NPX.INVALIDATES, lastProcessed,
18✔
2544
                samePublisherClause("invNp", "np"));
6✔
2545
    }
2546

2547
    /**
2548
     * DELETE template for validated {@code npa:SubSpaceDeclaration} rows whose
2549
     * source nanopub was invalidated. Removes the per-declaration row by subject;
2550
     * the convenience direct triples ({@code <child> npa:isSubSpaceOf <parent>}
2551
     * and inverse) are then dropped by {@link #subSpaceConvenienceEdgeCleanup} in the
2552
     * same cycle (issue #125 finding #5) once no surviving link backs them.
2553
     */
2554
    static String subSpaceInvalidationDelete(IRI graph, long lastProcessed) {
2555
        return String.format("""
63✔
2556
                PREFIX npa: <%1$s>
2557
                PREFIX gen: <%2$s>
2558
                DELETE { GRAPH <%3$s> {
2559
                  ?d ?p ?o .
2560
                } }
2561
                WHERE {
2562
                  GRAPH <%3$s> { ?d ?p ?o . }
2563
                %4$s
2564
                }
2565
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
2566
                subSpaceInvalidationCheckWhere(graph, lastProcessed));
6✔
2567
    }
2568

2569
    /**
2570
     * DELETE template for validated {@code npa:MaintainedResourceDeclaration} rows
2571
     * whose source nanopub was invalidated. Removes the per-declaration row by
2572
     * subject; the convenience direct triples ({@code <r> npa:isMaintainedBy <s>}
2573
     * and inverse) are then dropped by {@link #maintainedResourceConvenienceEdgeCleanup}
2574
     * in the same cycle (issue #125 finding #5). No structural-rebuild flag —
2575
     * maintained-resource is a leaf relation, no downstream consumers depend on its
2576
     * closure, so the prompt edge cleanup fully resolves its invalidation.
2577
     */
2578
    static String maintainedResourceInvalidationDelete(IRI graph, long lastProcessed) {
2579
        return String.format("""
84✔
2580
                PREFIX npa: <%1$s>
2581
                PREFIX gen: <%2$s>
2582
                DELETE { GRAPH <%3$s> {
2583
                  ?d ?p ?o .
2584
                } }
2585
                WHERE {
2586
                  GRAPH <%3$s> {
2587
                    ?d a npa:MaintainedResourceDeclaration ;
2588
                       npa:viaNanopub ?np .
2589
                    ?d ?p ?o .
2590
                  }
2591
                  GRAPH <%4$s> {
2592
                    ?invNp <%5$s> ?np ;
2593
                           npa:hasLoadNumber ?ln .
2594
                    FILTER (?ln > %6$d)
2595
                    %7$s
2596
                  }
2597
                }
2598
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
2599
                NPA.GRAPH, NPX.INVALIDATES, lastProcessed,
18✔
2600
                samePublisherClause("invNp", "np"));
6✔
2601
    }
2602

2603
    /**
2604
     * WHERE clause shared by the alias invalidation ASK precheck and the matching
2605
     * DELETE. Identifies validated {@code npa:SpaceAliasDeclaration} rows in the
2606
     * space-state graph whose {@code npa:viaNanopub} is the target of an
2607
     * {@code npx:invalidates} triple in {@code npa:graph} whose subject nanopub has a
2608
     * load number in {@code (lastProcessed, ∞)}.
2609
     */
2610
    static String aliasInvalidationCheckWhere(IRI graph, long lastProcessed) {
2611
        return String.format("""
60✔
2612
                  GRAPH <%1$s> {
2613
                    ?d a npa:SpaceAliasDeclaration ;
2614
                       npa:viaNanopub ?np .
2615
                  }
2616
                  GRAPH <%2$s> {
2617
                    ?invNp <%3$s> ?np ;
2618
                           npa:hasLoadNumber ?ln .
2619
                    FILTER (?ln > %4$d)
2620
                    %5$s
2621
                  }
2622
                """, graph, NPA.GRAPH, NPX.INVALIDATES, lastProcessed,
18✔
2623
                samePublisherClause("invNp", "np"));
6✔
2624
    }
2625

2626
    /**
2627
     * DELETE template for validated {@code npa:SpaceAliasDeclaration} rows whose
2628
     * source nanopub was invalidated. Removes the per-declaration row by subject; the
2629
     * convenience {@code <alias> npa:sameAsSpace <canonical>} edge is then dropped by
2630
     * {@link #aliasConvenienceEdgeCleanup} in the same cycle (issue #125 finding #5),
2631
     * so an alias can no longer grant admin authority after its declaration is retracted.
2632
     * The alias feeds the authority closure, so this kind is still structural and flips
2633
     * {@code npa:needsFullRebuild} to bound any rows already derived through the edge.
2634
     */
2635
    static String aliasInvalidationDelete(IRI graph, long lastProcessed) {
2636
        return String.format("""
63✔
2637
                PREFIX npa: <%1$s>
2638
                PREFIX gen: <%2$s>
2639
                DELETE { GRAPH <%3$s> {
2640
                  ?d ?p ?o .
2641
                } }
2642
                WHERE {
2643
                  GRAPH <%3$s> { ?d ?p ?o . }
2644
                %4$s
2645
                }
2646
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
2647
                aliasInvalidationCheckWhere(graph, lastProcessed));
6✔
2648
    }
2649

2650
    /**
2651
     * WHERE clause shared by the maintained-resource invalidation ASK precheck and the
2652
     * matching cleanup. Identifies validated {@code npa:MaintainedResourceDeclaration}
2653
     * rows in the space-state graph whose {@code npa:viaNanopub} is the target of an
2654
     * {@code npx:invalidates} triple in {@code npa:graph} whose subject nanopub has a
2655
     * load number in {@code (lastProcessed, ∞)}.
2656
     */
2657
    static String maintainedResourceInvalidationCheckWhere(IRI graph, long lastProcessed) {
2658
        return String.format("""
×
2659
                  GRAPH <%1$s> {
2660
                    ?d a npa:MaintainedResourceDeclaration ;
2661
                       npa:viaNanopub ?np .
2662
                  }
2663
                  GRAPH <%2$s> {
2664
                    ?invNp <%3$s> ?np ;
2665
                           npa:hasLoadNumber ?ln .
2666
                    FILTER (?ln > %4$d)
2667
                    %5$s
2668
                  }
2669
                """, graph, NPA.GRAPH, NPX.INVALIDATES, lastProcessed,
×
2670
                samePublisherClause("invNp", "np"));
×
2671
    }
2672

2673
    /**
2674
     * Convenience-edge cleanup for invalidated sub-space declarations (issue #125
2675
     * finding #5). Run after {@link #subSpaceInvalidationDelete} (which removes the
2676
     * {@code npa:SubSpaceDeclaration} rows). Two phases as one multi-operation update:
2677
     * <ol>
2678
     *   <li>delete every {@code npa:SubSpaceLink} provenance link whose
2679
     *       {@code npa:viaNanopub} was invalidated (same {@code npx:invalidates} +
2680
     *       same-publisher gate as the declaration delete);</li>
2681
     *   <li>orphan-sweep: delete the convenience {@code npa:isSubSpaceOf} /
2682
     *       {@code npa:hasSubSpace} edges (both ref- and IRI-valued) that no surviving
2683
     *       link backs — neither a {@code npa:SubSpaceLink} (explicit declaration) nor a
2684
     *       {@code npa:DerivedSubSpaceLink} (URL-prefix fallback).</li>
2685
     * </ol>
2686
     * Edges backed by another surviving declaration or by the URL-prefix fallback are
2687
     * kept. The {@code npa:needsFullRebuild} flag still fires for the structural kind, so
2688
     * downstream rows derived through a removed edge remain rebuild-bounded; this only
2689
     * stops the convenience edges themselves from going sticky.
2690
     */
2691
    static String subSpaceConvenienceEdgeCleanup(IRI graph, long lastProcessed) {
2692
        return String.format("""
72✔
2693
                PREFIX npa: <%1$s>
2694
                # 1. Drop sub-space provenance links whose source nanopub was invalidated.
2695
                DELETE { GRAPH <%2$s> { ?l ?p ?o . } }
2696
                WHERE {
2697
                  GRAPH <%2$s> {
2698
                    ?l a npa:SubSpaceLink ;
2699
                       npa:viaNanopub ?np .
2700
                    ?l ?p ?o .
2701
                  }
2702
                  GRAPH <%3$s> {
2703
                    ?invNp <%4$s> ?np ;
2704
                           npa:hasLoadNumber ?ln .
2705
                    FILTER (?ln > %5$d)
2706
                    %6$s
2707
                  }
2708
                } ;
2709
                # 2. Orphan-sweep isSubSpaceOf edges (ref- and IRI-valued) with no backing link.
2710
                DELETE { GRAPH <%2$s> { ?c npa:isSubSpaceOf ?p . } }
2711
                WHERE {
2712
                  GRAPH <%2$s> {
2713
                    ?c npa:isSubSpaceOf ?p .
2714
                    FILTER NOT EXISTS {
2715
                      { ?l a npa:SubSpaceLink } UNION { ?l a npa:DerivedSubSpaceLink }
2716
                      { { ?l npa:childSpaceRef ?c . ?l npa:parentSpaceRef ?p }
2717
                        UNION
2718
                        { ?l npa:childSpace ?c . ?l npa:parentSpace ?p } }
2719
                    }
2720
                  }
2721
                } ;
2722
                # 3. Orphan-sweep the inverse hasSubSpace edges symmetrically.
2723
                DELETE { GRAPH <%2$s> { ?p npa:hasSubSpace ?c . } }
2724
                WHERE {
2725
                  GRAPH <%2$s> {
2726
                    ?p npa:hasSubSpace ?c .
2727
                    FILTER NOT EXISTS {
2728
                      { ?l a npa:SubSpaceLink } UNION { ?l a npa:DerivedSubSpaceLink }
2729
                      { { ?l npa:childSpaceRef ?c . ?l npa:parentSpaceRef ?p }
2730
                        UNION
2731
                        { ?l npa:childSpace ?c . ?l npa:parentSpace ?p } }
2732
                    }
2733
                  }
2734
                }
2735
                """, NPA.NAMESPACE, graph, NPA.GRAPH, NPX.INVALIDATES, lastProcessed,
18✔
2736
                samePublisherClause("invNp", "np"));
6✔
2737
    }
2738

2739
    /**
2740
     * Convenience-edge cleanup for invalidated maintained-resource declarations (issue
2741
     * #125 finding #5). Run after {@link #maintainedResourceInvalidationDelete}. Deletes
2742
     * the {@code npa:MaintainedResourceLink} provenance links whose source nanopub was
2743
     * invalidated, then orphan-sweeps the {@code npa:isMaintainedBy} /
2744
     * {@code npa:hasMaintainedResource} edges (ref- and IRI-valued) that no surviving link
2745
     * backs. See {@link #subSpaceConvenienceEdgeCleanup} for the two-phase structure.
2746
     */
2747
    static String maintainedResourceConvenienceEdgeCleanup(IRI graph, long lastProcessed) {
2748
        return String.format("""
72✔
2749
                PREFIX npa: <%1$s>
2750
                # 1. Drop maintained-resource provenance links whose source nanopub was invalidated.
2751
                DELETE { GRAPH <%2$s> { ?l ?p ?o . } }
2752
                WHERE {
2753
                  GRAPH <%2$s> {
2754
                    ?l a npa:MaintainedResourceLink ;
2755
                       npa:viaNanopub ?np .
2756
                    ?l ?p ?o .
2757
                  }
2758
                  GRAPH <%3$s> {
2759
                    ?invNp <%4$s> ?np ;
2760
                           npa:hasLoadNumber ?ln .
2761
                    FILTER (?ln > %5$d)
2762
                    %6$s
2763
                  }
2764
                } ;
2765
                # 2. Orphan-sweep isMaintainedBy edges (ref- and IRI-valued) with no backing link.
2766
                DELETE { GRAPH <%2$s> { ?r npa:isMaintainedBy ?o . } }
2767
                WHERE {
2768
                  GRAPH <%2$s> {
2769
                    ?r npa:isMaintainedBy ?o .
2770
                    FILTER NOT EXISTS {
2771
                      ?l a npa:MaintainedResourceLink ;
2772
                         npa:resourceIri ?r .
2773
                      { ?l npa:maintainerSpaceRef ?o } UNION { ?l npa:maintainerSpace ?o }
2774
                    }
2775
                  }
2776
                } ;
2777
                # 3. Orphan-sweep the inverse hasMaintainedResource edges symmetrically.
2778
                DELETE { GRAPH <%2$s> { ?o npa:hasMaintainedResource ?r . } }
2779
                WHERE {
2780
                  GRAPH <%2$s> {
2781
                    ?o npa:hasMaintainedResource ?r .
2782
                    FILTER NOT EXISTS {
2783
                      ?l a npa:MaintainedResourceLink ;
2784
                         npa:resourceIri ?r .
2785
                      { ?l npa:maintainerSpaceRef ?o } UNION { ?l npa:maintainerSpace ?o }
2786
                    }
2787
                  }
2788
                } ;
2789
                # 4. Orphan-sweep the maintained arm of hasGoverningSpaceRef (issue #130).
2790
                #    Only the ref-valued maintained edge is removed here — it is backed by a
2791
                #    MaintainedResourceLink. The reflexive space self-edge (subject = a space
2792
                #    IRI that has its own SpaceRef) is NOT a maintained edge and is left to the
2793
                #    self-healing reflexive pass, so the guard keeps any ?r that is itself a space.
2794
                DELETE { GRAPH <%2$s> { ?r npa:hasGoverningSpaceRef ?o . } }
2795
                WHERE {
2796
                  GRAPH <%2$s> {
2797
                    ?r npa:hasGoverningSpaceRef ?o .
2798
                    FILTER NOT EXISTS {
2799
                      ?l a npa:MaintainedResourceLink ;
2800
                         npa:resourceIri ?r ;
2801
                         npa:maintainerSpaceRef ?o .
2802
                    }
2803
                    FILTER NOT EXISTS { GRAPH <%7$s> { ?o npa:spaceIri ?r . } }
2804
                  }
2805
                }
2806
                """, NPA.NAMESPACE, graph, NPA.GRAPH, NPX.INVALIDATES, lastProcessed,
18✔
2807
                samePublisherClause("invNp", "np"), SpacesVocab.SPACES_GRAPH);
18✔
2808
    }
2809

2810
    /**
2811
     * Convenience-edge cleanup for invalidated space-alias declarations (issue #125
2812
     * finding #5 — the load-bearing case, since the alias edge feeds the admin-authority
2813
     * closure). Run after {@link #aliasInvalidationDelete}. Deletes the
2814
     * {@code npa:SpaceAliasLink} provenance links whose source nanopub was invalidated,
2815
     * then orphan-sweeps the {@code npa:sameAsSpace} edges (ref- and IRI-valued) that no
2816
     * surviving link backs. See {@link #subSpaceConvenienceEdgeCleanup} for the two-phase
2817
     * structure.
2818
     */
2819
    static String aliasConvenienceEdgeCleanup(IRI graph, long lastProcessed) {
2820
        return String.format("""
72✔
2821
                PREFIX npa: <%1$s>
2822
                # 1. Drop alias provenance links whose source nanopub was invalidated.
2823
                DELETE { GRAPH <%2$s> { ?l ?p ?o . } }
2824
                WHERE {
2825
                  GRAPH <%2$s> {
2826
                    ?l a npa:SpaceAliasLink ;
2827
                       npa:viaNanopub ?np .
2828
                    ?l ?p ?o .
2829
                  }
2830
                  GRAPH <%3$s> {
2831
                    ?invNp <%4$s> ?np ;
2832
                           npa:hasLoadNumber ?ln .
2833
                    FILTER (?ln > %5$d)
2834
                    %6$s
2835
                  }
2836
                } ;
2837
                # 2. Orphan-sweep sameAsSpace edges (ref- and IRI-valued) with no backing link.
2838
                DELETE { GRAPH <%2$s> { ?alias npa:sameAsSpace ?o . } }
2839
                WHERE {
2840
                  GRAPH <%2$s> {
2841
                    ?alias npa:sameAsSpace ?o .
2842
                    FILTER NOT EXISTS {
2843
                      ?l a npa:SpaceAliasLink ;
2844
                         npa:aliasSpace ?alias .
2845
                      { ?l npa:canonicalSpaceRef ?o } UNION { ?l npa:canonicalSpace ?o }
2846
                    }
2847
                  }
2848
                }
2849
                """, NPA.NAMESPACE, graph, NPA.GRAPH, NPX.INVALIDATES, lastProcessed,
18✔
2850
                samePublisherClause("invNp", "np"));
6✔
2851
    }
2852

2853
    /**
2854
     * WHERE clause shared by the preset-deactivation ASK precheck and the matching DELETE
2855
     * (Nanodash issue #302). Binds {@code ?ra} = a materialized preset-derived
2856
     * {@code gen:RoleAssignment} ({@code npa:derivedFromPreset}) for which a <em>newer,
2857
     * admin-authored</em> same-{@code (preset, resource)} assignment exists by
2858
     * {@code dct:created} (load number in {@code (lastProcessed, ∞)}). This is NOT an
2859
     * {@code npx:invalidates} check — preset activation is latest-wins by timestamp.
2860
     *
2861
     * <p>Authorization-scoped (anti-hijack, design doc §3/§4.4): the newer assignment's
2862
     * publisher must itself be a validated admin of the row's {@code npa:forSpaceRef}, so an
2863
     * unauthorized key's newer assignment can neither delete nor shadow an admin's
2864
     * materialized role. {@code dct:created} is written as a full IRI (not a {@code dct:}
2865
     * prefix) because {@link #wouldInvalidate}'s ASK wrapper only declares {@code npa:} /
2866
     * {@code gen:}.
2867
     */
2868
    static String presetDeactivationCheckWhere(IRI graph, long lastProcessed) {
2869
        return String.format("""
60✔
2870
                  GRAPH <%1$s> {
2871
                    ?ra a gen:RoleAssignment ;
2872
                        npa:derivedFromPreset ?assignNp ;
2873
                        npa:forSpaceRef ?targetRef .
2874
                  }
2875
                  GRAPH <%2$s> {
2876
                    ?pa a npa:PresetAssignment ;
2877
                        npa:viaNanopub  ?assignNp ;
2878
                        npa:ofPreset    ?preset ;
2879
                        npa:forResource ?resource ;
2880
                        <http://purl.org/dc/terms/created> ?created .
2881
                    ?paNewer a npa:PresetAssignment ;
2882
                             npa:ofPreset    ?preset ;
2883
                             npa:forResource ?resource ;
2884
                             npa:pubkeyHash  ?pkhNewer ;
2885
                             npa:viaNanopub  ?assignNpNewer ;
2886
                             <http://purl.org/dc/terms/created> ?createdNewer .
2887
                    FILTER (?createdNewer > ?created
2888
                            || (?createdNewer = ?created && STR(?paNewer) > STR(?pa)))
2889
                  }
2890
                  GRAPH <%3$s> {
2891
                    ?assignNpNewer npa:hasLoadNumber ?lnNewer .
2892
                    FILTER (?lnNewer > %4$d)
2893
                  }
2894
                  GRAPH <%1$s> {
2895
                    ?acctNewer a npa:AccountState ;
2896
                               npa:agent  ?publisherNewer ;
2897
                               npa:pubkey ?pkhNewer .
2898
                    ?adminRINewer a gen:RoleInstantiation ;
2899
                                  npa:forSpaceRef ?targetRef ;
2900
                                  npa:inverseProperty gen:hasAdmin ;
2901
                                  npa:forAgent ?publisherNewer .
2902
                  }
2903
                """, graph, SpacesVocab.SPACES_GRAPH, NPA.GRAPH, lastProcessed);
6✔
2904
    }
2905

2906
    /**
2907
     * DELETE template for preset-derived {@code gen:RoleAssignment} rows superseded by a
2908
     * newer admin-authored same-pair assignment (issue #302). Removes the whole row by
2909
     * subject; scoped via {@code npa:derivedFromPreset} so directly-published attachments
2910
     * are never touched. The {@link #presetAttachmentValidationUpdate} re-INSERT in the
2911
     * same cycle re-materializes the pair iff the newest assignment is still active.
2912
     */
2913
    static String presetDeactivationDelete(IRI graph, long lastProcessed) {
2914
        return String.format("""
63✔
2915
                PREFIX npa: <%1$s>
2916
                PREFIX gen: <%2$s>
2917
                DELETE { GRAPH <%3$s> {
2918
                  ?ra ?p ?o .
2919
                } }
2920
                WHERE {
2921
                  GRAPH <%3$s> { ?ra ?p ?o . }
2922
                %4$s
2923
                }
2924
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
2925
                presetDeactivationCheckWhere(graph, lastProcessed));
6✔
2926
    }
2927

2928
    /**
2929
     * WHERE clause matching a materialized <em>non-admin</em> {@code gen:RoleInstantiation}
2930
     * row whose {@code (forSpaceRef, forAgent, gen:hasRole)} key is shadowed by a newer
2931
     * authorized {@code npa:RoleRevocation} (issue #129). The grant timestamp comes from the
2932
     * originating instantiation in the extraction graph (the materialized row carries no
2933
     * {@code dct:created}); the revocation nanopub's load number must be in
2934
     * {@code (lastProcessed, ∞)} so only revocations new in this cycle trigger a delete.
2935
     * Authorization is keyed on the row's bound {@code ?tier} (the matrix: a strictly-higher
2936
     * tier in the ref, or self). Not an {@code npx:invalidates} check.
2937
     */
2938
    static String roleRevocationCheckWhere(IRI graph, long lastProcessed, IRI targetTier) {
2939
        return String.format("""
60✔
2940
                  GRAPH <%1$s> {
2941
                    ?ri2 a gen:RoleInstantiation ;
2942
                         npa:forSpaceRef ?spaceRef ;
2943
                         npa:forAgent    ?agent ;
2944
                         gen:hasRole     ?role ;
2945
                         npa:hasRoleType <%7$s> ;
2946
                         npa:viaNanopub  ?np .
2947
                  }
2948
                  OPTIONAL { GRAPH <%2$s> {
2949
                    ?riSrc npa:viaNanopub ?np ;
2950
                           <http://purl.org/dc/terms/created> ?candCreatedRaw .
2951
                  } }
2952
                  BIND(COALESCE(?candCreatedRaw, %5$s) AS ?candCreated)
2953
                  { GRAPH <%2$s> { ?spaceRef npa:spaceIri ?revSpace . } }
2954
                  UNION
2955
                  { GRAPH <%1$s> { ?revSpace npa:sameAsSpace ?spaceRef . } }
2956
                  GRAPH <%2$s> {
2957
                    ?rev a npa:RoleRevocation ;
2958
                         npa:forSpace    ?revSpace ;
2959
                         npa:forAgent    ?agent ;
2960
                         npa:revokedRole ?role ;
2961
                         npa:pubkeyHash  ?revPkh ;
2962
                         npa:viaNanopub  ?revNp .
2963
                    OPTIONAL { ?rev <http://purl.org/dc/terms/created> ?revCreatedRaw . }
2964
                  }
2965
                  BIND(COALESCE(?revCreatedRaw, %5$s) AS ?revCreated)
2966
                  GRAPH <%3$s> {
2967
                    ?revNp npa:hasLoadNumber ?lnRev .
2968
                    FILTER (?lnRev > %4$d)
2969
                  }
2970
                  FILTER (?revCreated > ?candCreated
2971
                          || (?revCreated = ?candCreated && STR(?rev) > STR(?ri2)))
2972
                  { %6$s }
2973
                """, graph, SpacesVocab.SPACES_GRAPH, NPA.GRAPH, lastProcessed,
30✔
2974
                EPOCH_DT, revocationAuthorityArmsForTier(graph, targetTier), targetTier);
18✔
2975
    }
2976

2977
    /**
2978
     * DELETE template removing a non-admin {@code gen:RoleInstantiation} row of {@code
2979
     * targetTier} shadowed by a newer authorized revocation (issue #129). Removes the whole
2980
     * row by subject. Run once per non-admin tier (maintainer/member/observer) so the
2981
     * authorization arms are the compile-time set for that tier — matching the inline
2982
     * suppression filter, no runtime {@code ?tier} (see {@link #revocationAuthorityArmsForTier}).
2983
     * Caller sets {@code needsFullRebuild} (a revoked maintainer/member is a sub-granting
2984
     * authority).
2985
     */
2986
    static String roleRevocationDelete(IRI graph, long lastProcessed, IRI targetTier) {
2987
        return String.format("""
66✔
2988
                PREFIX npa: <%1$s>
2989
                PREFIX gen: <%2$s>
2990
                DELETE { GRAPH <%3$s> {
2991
                  ?ri2 ?p ?o .
2992
                } }
2993
                WHERE {
2994
                  GRAPH <%3$s> { ?ri2 ?p ?o . }
2995
                %4$s
2996
                }
2997
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
2998
                roleRevocationCheckWhere(graph, lastProcessed, targetTier));
6✔
2999
    }
3000

3001
    /**
3002
     * WHERE clause matching a materialized <em>admin</em> {@code gen:RoleInstantiation} row
3003
     * whose {@code (forSpaceRef, forAgent)} key is shadowed by a newer authorized admin
3004
     * {@code npa:RoleRevocation} ({@code revokedRole = gen:AdminRole}), authorized by an
3005
     * admin of the ref or by the agent itself. <b>Root admins are exempt</b> (constitutional,
3006
     * issue #129/#110): the nested {@code FILTER NOT EXISTS} on {@code npa:hasRootAdmin}
3007
     * makes the revocation inert. The revocation nanopub's load number must be in
3008
     * {@code (lastProcessed, ∞)}.
3009
     */
3010
    static String adminRevocationCheckWhere(IRI graph, long lastProcessed) {
3011
        return String.format("""
60✔
3012
                  GRAPH <%1$s> {
3013
                    ?sri a gen:RoleInstantiation ;
3014
                         npa:forSpaceRef     ?spaceRef ;
3015
                         npa:inverseProperty gen:hasAdmin ;
3016
                         npa:forAgent        ?agent ;
3017
                         npa:viaNanopub      ?np .
3018
                  }
3019
                  FILTER NOT EXISTS { GRAPH <%2$s> {
3020
                    ?rootDef a npa:SpaceDefinition ;
3021
                             npa:forSpaceRef  ?spaceRef ;
3022
                             npa:hasRootAdmin ?agent .
3023
                  } }
3024
                  OPTIONAL { GRAPH <%2$s> {
3025
                    ?riSrc npa:viaNanopub ?np ;
3026
                           <http://purl.org/dc/terms/created> ?candCreatedRaw .
3027
                  } }
3028
                  BIND(COALESCE(?candCreatedRaw, %5$s) AS ?candCreated)
3029
                  { GRAPH <%2$s> { ?spaceRef npa:spaceIri ?revSpace . } }
3030
                  UNION
3031
                  { GRAPH <%1$s> { ?revSpace npa:sameAsSpace ?spaceRef . } }
3032
                  GRAPH <%2$s> {
3033
                    ?rev a npa:RoleRevocation ;
3034
                         npa:forSpace    ?revSpace ;
3035
                         npa:forAgent    ?agent ;
3036
                         npa:revokedRole gen:AdminRole ;
3037
                         npa:pubkeyHash  ?revPkh ;
3038
                         npa:viaNanopub  ?revNp .
3039
                    OPTIONAL { ?rev <http://purl.org/dc/terms/created> ?revCreatedRaw . }
3040
                  }
3041
                  BIND(COALESCE(?revCreatedRaw, %5$s) AS ?revCreated)
3042
                  GRAPH <%3$s> {
3043
                    ?revNp npa:hasLoadNumber ?lnRev .
3044
                    FILTER (?lnRev > %4$d)
3045
                  }
3046
                  FILTER (?revCreated > ?candCreated
3047
                          || (?revCreated = ?candCreated && STR(?rev) > STR(?sri)))
3048
                  { %6$s }
3049
                """, graph, SpacesVocab.SPACES_GRAPH, NPA.GRAPH, lastProcessed, EPOCH_DT,
27✔
3050
                "{ " + revokerAdminGraphBlock(graph) + " }\nUNION\n{ "
6✔
3051
                        + revokerSelfGraphBlock(graph) + " }");
9✔
3052
    }
3053

3054
    /**
3055
     * DELETE template removing an admin {@code gen:RoleInstantiation} row shadowed by a newer
3056
     * authorized admin revocation (issue #129). Removes the whole row by subject.
3057
     * <b>Structural</b> — admin RIs feed every downstream tier — so the caller sets
3058
     * {@code npa:needsFullRebuild} (mirrors {@code adminInvalidationDelete}). The
3059
     * {@code adminTierUpdate} inline suppression filter prevents re-materialization.
3060
     */
3061
    static String adminRevocationDelete(IRI graph, long lastProcessed) {
3062
        return String.format("""
63✔
3063
                PREFIX npa: <%1$s>
3064
                PREFIX gen: <%2$s>
3065
                DELETE { GRAPH <%3$s> {
3066
                  ?sri ?p ?o .
3067
                } }
3068
                WHERE {
3069
                  GRAPH <%3$s> { ?sri ?p ?o . }
3070
                %4$s
3071
                }
3072
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
3073
                adminRevocationCheckWhere(graph, lastProcessed));
6✔
3074
    }
3075

3076
    /**
3077
     * WHERE clause matching a materialized {@code gen:RoleAssignment} row (direct
3078
     * <em>or</em> preset-derived) whose {@code (forSpaceRef, gen:hasRole)} key is shadowed by
3079
     * a newer admin-authored {@code npa:RoleDetachment} (issue #129). The attachment
3080
     * timestamp comes from whichever extraction row shares the materialized row's
3081
     * {@code npa:viaNanopub} (a {@code RoleAssignment} for direct attachments, a
3082
     * {@code PresetAssignment} for preset-derived ones). The detachment nanopub's load number
3083
     * must be in {@code (lastProcessed, ∞)}; authority = admin of the ref.
3084
     */
3085
    static String roleDetachmentCheckWhere(IRI graph, long lastProcessed) {
3086
        return String.format("""
60✔
3087
                  GRAPH <%1$s> {
3088
                    ?ra2 a gen:RoleAssignment ;
3089
                         npa:forSpaceRef ?targetRef ;
3090
                         gen:hasRole     ?role ;
3091
                         npa:viaNanopub  ?np .
3092
                  }
3093
                  OPTIONAL { GRAPH <%2$s> {
3094
                    ?attSrc npa:viaNanopub ?np ;
3095
                            <http://purl.org/dc/terms/created> ?attCreatedRaw .
3096
                  } }
3097
                  BIND(COALESCE(?attCreatedRaw, %5$s) AS ?attCreated)
3098
                  { GRAPH <%2$s> { ?targetRef npa:spaceIri ?detSpace . } }
3099
                  UNION
3100
                  { GRAPH <%1$s> { ?detSpace npa:sameAsSpace ?targetRef . } }
3101
                  GRAPH <%2$s> {
3102
                    ?det a npa:RoleDetachment ;
3103
                         npa:forSpace    ?detSpace ;
3104
                         npa:revokedRole ?role ;
3105
                         npa:pubkeyHash  ?detPkh ;
3106
                         npa:viaNanopub  ?detNp .
3107
                    OPTIONAL { ?det <http://purl.org/dc/terms/created> ?detCreatedRaw . }
3108
                  }
3109
                  BIND(COALESCE(?detCreatedRaw, %5$s) AS ?detCreated)
3110
                  GRAPH <%3$s> {
3111
                    ?detNp npa:hasLoadNumber ?lnDet .
3112
                    FILTER (?lnDet > %4$d)
3113
                  }
3114
                  FILTER (?detCreated > ?attCreated
3115
                          || (?detCreated = ?attCreated && STR(?det) > STR(?ra2)))
3116
                  GRAPH <%1$s> {
3117
                    ?detAcct a npa:AccountState ; npa:pubkey ?detPkh ; npa:agent ?detAgent .
3118
                    ?detAdminRI a gen:RoleInstantiation ;
3119
                                npa:forSpaceRef ?targetRef ;
3120
                                npa:inverseProperty gen:hasAdmin ;
3121
                                npa:forAgent ?detAgent .
3122
                  }
3123
                """, graph, SpacesVocab.SPACES_GRAPH, NPA.GRAPH, lastProcessed, EPOCH_DT);
18✔
3124
    }
3125

3126
    /**
3127
     * DELETE template removing a {@code gen:RoleAssignment} row (direct or preset-derived)
3128
     * shadowed by a newer admin-authored {@code gen:detachedRole} (issue #129). Removes the
3129
     * whole row by subject. <b>Structural</b> — instantiations anchored on the removed
3130
     * attachment are bounded by the periodic full rebuild (the cascade), so the caller sets
3131
     * {@code npa:needsFullRebuild}. The attachment-tier inline filters prevent
3132
     * re-materialization until a newer attachment / preset assignment out-ranks the detach
3133
     * (non-sticky).
3134
     */
3135
    static String roleDetachmentDelete(IRI graph, long lastProcessed) {
3136
        return String.format("""
63✔
3137
                PREFIX npa: <%1$s>
3138
                PREFIX gen: <%2$s>
3139
                DELETE { GRAPH <%3$s> {
3140
                  ?ra2 ?p ?o .
3141
                } }
3142
                WHERE {
3143
                  GRAPH <%3$s> { ?ra2 ?p ?o . }
3144
                %4$s
3145
                }
3146
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
3147
                roleDetachmentCheckWhere(graph, lastProcessed));
6✔
3148
    }
3149

3150
    /**
3151
     * DELETE template for ref-scoped preset-assignment stamps ({@link
3152
     * #presetAssignmentRefStampUpdate}) whose underlying assignment nanopub was
3153
     * hard-retracted (issue #122). Removes the whole row by subject; scoped to
3154
     * state-graph {@code npa:PresetAssignment} rows that carry {@code npa:forSpaceRef}
3155
     * (the IRI-keyed extraction rows never do), so it can never touch them.
3156
     *
3157
     * <p>Leaf delete — no structural flag: nothing downstream derives from a listing
3158
     * stamp, so a stale row only mis-displays a retracted assignment until this cycle's
3159
     * delete runs. Admin-grant revocation is bounded by the periodic full rebuild (same
3160
     * sticky-convenience policy as the alias / sub-space declaration edges). A
3161
     * <em>deactivation</em> needs no delete here: it is represented as a newer
3162
     * admin-authored stamp with {@code npa:isActivated false}, resolved by the consumer's
3163
     * latest-wins.
3164
     */
3165
    static String presetAssignmentRefInvalidationDelete(IRI graph, long lastProcessed) {
3166
        return String.format("""
84✔
3167
                PREFIX npa: <%1$s>
3168
                PREFIX gen: <%2$s>
3169
                DELETE { GRAPH <%3$s> {
3170
                  ?paRef ?p ?o .
3171
                } }
3172
                WHERE {
3173
                  GRAPH <%3$s> {
3174
                    ?paRef a npa:PresetAssignment ;
3175
                           npa:forSpaceRef ?targetRef ;
3176
                           npa:viaNanopub  ?assignNp .
3177
                    ?paRef ?p ?o .
3178
                  }
3179
                  GRAPH <%4$s> {
3180
                    ?invNp <%5$s> ?assignNp ;
3181
                           npa:hasLoadNumber ?ln .
3182
                    FILTER (?ln > %6$d)
3183
                    %7$s
3184
                  }
3185
                }
3186
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
3187
                NPA.GRAPH, NPX.INVALIDATES, lastProcessed,
18✔
3188
                samePublisherClause("invNp", "assignNp"));
6✔
3189
    }
3190

3191
    /** Wraps an ASK by joining the shared prefixes. */
3192
    private boolean wouldInvalidate(IRI graph, long lastProcessed,
3193
                                    boolean adminPinned, String whereClause) {
3194
        // adminPinned is informational only — kept to make call sites read clearly;
3195
        // the WHERE clause already encodes the kind via its own type predicates.
3196
        String ask = String.format("""
×
3197
                PREFIX npa: <%1$s>
3198
                PREFIX gen: <%2$s>
3199
                ASK { %3$s }
3200
                """, NPA.NAMESPACE, GEN.NAMESPACE, whereClause);
3201
        return runAsk(ask);
×
3202
    }
3203

3204
    private boolean runAsk(String sparql) {
3205
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
3206
            return conn.prepareBooleanQuery(QueryLanguage.SPARQL, sparql).evaluate();
×
3207
        }
3208
    }
3209

3210
    private void executeUpdate(String sparqlUpdate) {
3211
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
3212
            conn.prepareUpdate(QueryLanguage.SPARQL, sparqlUpdate).execute();
×
3213
        }
3214
    }
×
3215

3216
    // ---------------- Mirror step ----------------
3217

3218
    /**
3219
     * Copies trust-approved {@code npa:AccountState} rows from {@code npat:<T>}
3220
     * in the {@code trust} repo into {@code newGraph} in the {@code spaces} repo,
3221
     * inside one spaces-side serializable transaction.
3222
     *
3223
     * @return number of rows mirrored (useful for metrics / logging)
3224
     */
3225
    /**
3226
     * Whether the given trust state's graph holds anything at all.
3227
     *
3228
     * <p>Used by {@link #runFullBuild} to tell a build that read nothing because the store
3229
     * would not answer from a build that read nothing because there is nothing to read. Only
3230
     * the first is a reason to withhold the result; withholding the second would freeze a
3231
     * stale space state in place, and stale trust data is over-permissive.
3232
     *
3233
     * <p>Throws rather than guessing if the trust repo cannot be read — {@link #runFullBuild}
3234
     * then aborts without publishing or dropping anything, which is the safe direction.
3235
     *
3236
     * @param trustStateHash the trust state hash
3237
     * @return true if the trust state graph contains at least one triple
3238
     */
3239
    boolean trustStateHasContent(String trustStateHash) {
3240
        IRI trustStateIri = NPAT.forHash(trustStateHash);
×
3241
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(TRUST_REPO)) {
×
3242
            String query = String.format("ASK { GRAPH <%s> { ?s ?p ?o } }", trustStateIri);
×
3243
            return conn.prepareBooleanQuery(QueryLanguage.SPARQL, query).evaluate();
×
3244
        } catch (Exception ex) {
×
3245
            throw new SpaceStateUnavailableException(
×
3246
                    "failed to read trust state graph " + trustStateIri, ex);
3247
        }
3248
    }
3249

3250
    int mirrorTrustState(String trustStateHash, IRI newGraph) {
3251
        IRI trustStateIri = NPAT.forHash(trustStateHash);
×
3252
        int count = 0;
×
3253
        try (RepositoryConnection trustConn = TripleStore.get().getRepoConnection(TRUST_REPO);
×
3254
             RepositoryConnection spacesConn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
3255
            trustConn.begin(IsolationLevels.READ_COMMITTED);
×
3256
            spacesConn.begin(IsolationLevels.SERIALIZABLE);
×
3257
            // Walk rdf:type triples in the trust state's graph; for each AccountState,
3258
            // check status and copy the approved ones verbatim (minus status-specific
3259
            // detail triples, which we don't need for validation).
3260
            try (RepositoryResult<Statement> typeRows = trustConn.getStatements(
×
3261
                    null, RDF.TYPE, NPA_ACCOUNT_STATE, trustStateIri)) {
3262
                while (typeRows.hasNext()) {
×
3263
                    Statement st = typeRows.next();
×
3264
                    if (!(st.getSubject() instanceof IRI accountStateIri)) continue;
×
3265
                    Value status = trustConn.getStatements(accountStateIri, NPA_TRUST_STATUS, null, trustStateIri)
×
3266
                            .stream().findFirst().map(Statement::getObject).orElse(null);
×
3267
                    if (!(status instanceof IRI statusIri) || !APPROVED_SET.contains(statusIri)) continue;
×
3268
                    Value agent = trustConn.getStatements(accountStateIri, NPA_AGENT, null, trustStateIri)
×
3269
                            .stream().findFirst().map(Statement::getObject).orElse(null);
×
3270
                    Value pubkey = trustConn.getStatements(accountStateIri, NPA_PUBKEY, null, trustStateIri)
×
3271
                            .stream().findFirst().map(Statement::getObject).orElse(null);
×
3272
                    if (agent == null || pubkey == null) {
×
3273
                        logger.warn("AuthorityResolver.mirror: account {} missing agent or pubkey; skipping",
×
3274
                                accountStateIri);
3275
                        continue;
×
3276
                    }
3277
                    spacesConn.add(accountStateIri, RDF.TYPE, NPA_ACCOUNT_STATE, newGraph);
×
3278
                    spacesConn.add(accountStateIri, NPA_AGENT, agent, newGraph);
×
3279
                    spacesConn.add(accountStateIri, NPA_PUBKEY, pubkey, newGraph);
×
3280
                    spacesConn.add(accountStateIri, NPA_TRUST_STATUS, statusIri, newGraph);
×
3281
                    // Mirror the authorizing introduction provenance when present (issue #125
3282
                    // finding #4). Optional: absent for snapshots from registries that predate
3283
                    // nanopub-registry#117/#118, so consumers (e.g. get-space-members-ref) must
3284
                    // treat npa:viaNanopub on an AccountState as best-effort, not guaranteed.
3285
                    Value viaNanopub = trustConn.getStatements(accountStateIri, NPA_VIA_NANOPUB, null, trustStateIri)
×
3286
                            .stream().findFirst().map(Statement::getObject).orElse(null);
×
3287
                    if (viaNanopub != null) {
×
3288
                        spacesConn.add(accountStateIri, NPA_VIA_NANOPUB, viaNanopub, newGraph);
×
3289
                    }
3290
                    count++;
×
3291
                }
×
3292
            }
3293
            // Mirror canonical foaf:name triples for approved agents. The trust
3294
            // loader emits one per agent (across approved keys, MAX(ratio) wins).
3295
            // Copying them into the space-state graph means consumers reading
3296
            // ?agent foaf:name ?n inside the state graph hit local data, with no
3297
            // cross-repo SERVICE.
3298
            try (RepositoryResult<Statement> nameRows = trustConn.getStatements(
×
3299
                    null, FOAF.NAME, null, trustStateIri)) {
3300
                while (nameRows.hasNext()) {
×
3301
                    Statement st = nameRows.next();
×
3302
                    spacesConn.add(st.getSubject(), st.getPredicate(), st.getObject(), newGraph);
×
3303
                }
×
3304
            }
3305
            spacesConn.commit();
×
3306
            trustConn.commit();
×
3307
        }
3308
        return count;
×
3309
    }
3310

3311
    // ---------------- Pointer + counter helpers ----------------
3312

3313
    /**
3314
     * Reads the current {@code npa:hasCurrentSpaceState} pointer from the
3315
     * {@code npa:graph} admin graph of the {@code spaces} repo. Returns
3316
     * {@code null} if no pointer exists yet.
3317
     */
3318
    IRI getCurrentSpaceStateGraph() {
3319
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
3320
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
3321
                    SpacesVocab.HAS_CURRENT_SPACE_STATE);
3322
            return (v instanceof IRI iri) ? iri : null;
×
3323
        } catch (Exception ex) {
3✔
3324
            throw new SpaceStateUnavailableException("failed to read hasCurrentSpaceState pointer", ex);
18✔
3325
        }
3326
    }
3327

3328
    long getCurrentLoadCounter() {
3329
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
3330
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
3331
                    SpacesVocab.CURRENT_LOAD_COUNTER);
3332
            if (v == null) return 0;
×
3333
            try {
3334
                return Long.parseLong(v.stringValue());
×
3335
            } catch (NumberFormatException ex) {
×
3336
                // Was "return 0", which would name the new graph <hash>_0 and make it
3337
                // differ from the real current graph — so the build proceeded and then
3338
                // dropped the good one. Corrupt bookkeeping must stop the build.
3339
                throw new SpaceStateUnavailableException("non-numeric currentLoadCounter: " + v, ex);
×
3340
            }
3341
        } catch (SpaceStateUnavailableException ex) {
×
3342
            throw ex;
×
3343
        } catch (Exception ex) {
3✔
3344
            throw new SpaceStateUnavailableException("failed to read currentLoadCounter", ex);
18✔
3345
        }
3346
    }
3347

3348
    /**
3349
     * Atomic pointer flip: a single SPARQL {@code DELETE … INSERT … WHERE}
3350
     * replaces the old pointer with the new one in one statement, so readers
3351
     * never see a zero-pointer window.
3352
     */
3353
    void flipPointer(IRI newGraph) {
3354
        String update = String.format("""
×
3355
                DELETE { GRAPH <%s> { <%s> <%s> ?old } }
3356
                INSERT { GRAPH <%s> { <%s> <%s> <%s> } }
3357
                WHERE  { OPTIONAL { GRAPH <%s> { <%s> <%s> ?old } } }
3358
                """,
3359
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.HAS_CURRENT_SPACE_STATE,
3360
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.HAS_CURRENT_SPACE_STATE, newGraph,
3361
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.HAS_CURRENT_SPACE_STATE);
3362
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
3363
            conn.begin(IsolationLevels.SERIALIZABLE);
×
3364
            conn.prepareUpdate(QueryLanguage.SPARQL, update).execute();
×
3365
            conn.commit();
×
3366
        }
3367
    }
×
3368

3369
    void writeProcessedUpTo(IRI graph, long loadCounter) {
3370
        String update = String.format("""
×
3371
                DELETE { GRAPH <%s> { <%s> <%s> ?old } }
3372
                INSERT { GRAPH <%s> { <%s> <%s> "%d"^^<http://www.w3.org/2001/XMLSchema#long> } }
3373
                WHERE  { OPTIONAL { GRAPH <%s> { <%s> <%s> ?old } } }
3374
                """,
3375
                graph, graph, SpacesVocab.PROCESSED_UP_TO,
3376
                graph, graph, SpacesVocab.PROCESSED_UP_TO, loadCounter,
×
3377
                graph, graph, SpacesVocab.PROCESSED_UP_TO);
3378
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
3379
            conn.begin(IsolationLevels.SERIALIZABLE);
×
3380
            conn.prepareUpdate(QueryLanguage.SPARQL, update).execute();
×
3381
            conn.commit();
×
3382
        }
3383
    }
×
3384

3385
    /**
3386
     * Reads {@code processedUpTo} from the given space-state graph.
3387
     * Returns {@code -1} if absent (graph not fully built yet).
3388
     */
3389
    long readProcessedUpTo(IRI graph) {
3390
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
3391
            String query = String.format(
×
3392
                    "SELECT ?n WHERE { GRAPH <%s> { <%s> <%s> ?n } }",
3393
                    graph, graph, SpacesVocab.PROCESSED_UP_TO);
3394
            try (TupleQueryResult r = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) {
×
3395
                if (!r.hasNext()) return -1;
×
3396
                BindingSet b = r.next();
×
3397
                return Long.parseLong(b.getBinding("n").getValue().stringValue());
×
3398
            }
×
3399
        } catch (Exception ex) {
3!
3400
            // Must not collapse to -1: callers read -1 as "this graph was never
3401
            // finished" and rebuild from scratch. A timed-out read returning -1 would
3402
            // make a healthy state look damaged and trigger a destructive rebuild.
3403
            throw new SpaceStateUnavailableException("failed to read processedUpTo for " + graph, ex);
24✔
3404
        }
3405
    }
3406

3407
    /**
3408
     * Reads the {@code npa:needsFullRebuild} flag (boolean literal) from
3409
     * {@code npa:graph} in the {@code spaces} repo. Defaults to {@code false}
3410
     * when the triple is absent.
3411
     */
3412
    boolean readNeedsFullRebuild() {
3413
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
3414
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
3415
                    SpacesVocab.NEEDS_FULL_REBUILD);
3416
            return v != null && Boolean.parseBoolean(v.stringValue());
×
3417
        } catch (Exception ex) {
×
3418
            logger.warn("AuthorityResolver: failed to read needsFullRebuild: {}", ex.toString());
×
3419
            return false;
×
3420
        }
3421
    }
3422

3423
    void setNeedsFullRebuild() {
3424
        writeNeedsFullRebuild(true);
×
3425
    }
×
3426

3427
    void clearNeedsFullRebuild() {
3428
        writeNeedsFullRebuild(false);
×
3429
    }
×
3430

3431
    private void writeNeedsFullRebuild(boolean value) {
3432
        String update = String.format("""
×
3433
                DELETE { GRAPH <%s> { <%s> <%s> ?old } }
3434
                INSERT { GRAPH <%s> { <%s> <%s> "%s"^^<http://www.w3.org/2001/XMLSchema#boolean> } }
3435
                WHERE  { OPTIONAL { GRAPH <%s> { <%s> <%s> ?old } } }
3436
                """,
3437
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.NEEDS_FULL_REBUILD,
3438
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.NEEDS_FULL_REBUILD, value,
×
3439
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.NEEDS_FULL_REBUILD);
3440
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
3441
            conn.begin(IsolationLevels.SERIALIZABLE);
×
3442
            conn.prepareUpdate(QueryLanguage.SPARQL, update).execute();
×
3443
            conn.commit();
×
3444
        }
3445
    }
×
3446

3447
    void dropGraph(IRI graph) {
3448
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
3449
            conn.begin(IsolationLevels.SERIALIZABLE);
×
3450
            conn.clear(graph);
×
3451
            conn.commit();
×
3452
            logger.info("AuthorityResolver: dropped old space-state graph {}", graph);
×
3453
        }
3454
    }
×
3455

3456
    // ---------------- Trust-repo pointer lookup (used by TrustStateRegistry's bootstrap) ----------------
3457

3458
    /**
3459
     * Queries the {@code trust} repo directly for the current trust-state hash.
3460
     * Prefer {@link TrustStateRegistry#getCurrentHash()} in normal operation —
3461
     * this helper exists for tests and diagnostics.
3462
     *
3463
     * @return the current trust-state hash, or empty if none is set
3464
     */
3465
    Optional<String> readTrustRepoCurrentHash() {
3466
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(TRUST_REPO)) {
×
3467
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
3468
                    NPA_HAS_CURRENT_TRUST_STATE);
3469
            if (!(v instanceof IRI iri)) return Optional.empty();
×
3470
            String s = iri.stringValue();
×
3471
            if (!s.startsWith(NPAT.NAMESPACE)) return Optional.empty();
×
3472
            return Optional.of(s.substring(NPAT.NAMESPACE.length()));
×
3473
        } catch (Exception ex) {
×
3474
            logger.warn("AuthorityResolver: failed to read trust-repo current pointer: {}", ex.toString());
×
3475
            return Optional.empty();
×
3476
        }
3477
    }
3478

3479
    private static String abbrev(String hash) {
3480
        return hash.length() > 12 ? hash.substring(0, 12) + "…" : hash;
33!
3481
    }
3482

3483
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc