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

knowledgepixels / nanopub-query / 28155243323

25 Jun 2026 07:50AM UTC coverage: 61.331% (-0.05%) from 61.38%
28155243323

push

github

web-flow
Merge pull request #131 from knowledgepixels/fix/issue-125-convenience-edge-invalidation

fix(spaces): clean up convenience structural edges on invalidation (#125 finding #5)

542 of 976 branches covered (55.53%)

Branch coverage included in aggregate %.

1577 of 2479 relevant lines covered (63.61%)

9.66 hits per line

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

20.0
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_LOADED = vf.createIRI(NPA.NAMESPACE, "loaded");
15✔
72
    private static final IRI NPA_TO_LOAD = vf.createIRI(NPA.NAMESPACE, "toLoad");
15✔
73

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

84
    private static AuthorityResolver instance;
85

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

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

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

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

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

118
    // ---------------- Public entry points ----------------
119

120
    /**
121
     * Poll entry point. Behaviour:
122
     * <ul>
123
     *   <li>If no current space-state graph or the trust state has flipped → full build.</li>
124
     *   <li>Otherwise → {@link #runIncrementalCycle incremental cycle} on the load-number
125
     *       delta {@code (processedUpTo, currentLoadCounter]}. No-op if {@code
126
     *       processedUpTo == currentLoadCounter}.</li>
127
     * </ul>
128
     * Safe to call repeatedly on a schedule. Gated by {@link FeatureFlags#spacesEnabled()}.
129
     */
130
    public void tick() {
131
        if (!FeatureFlags.spacesEnabled()) return;
6!
132
        String trustStateHash = TrustStateRegistry.get().getCurrentHash().orElse(null);
18✔
133
        if (trustStateHash == null) {
6!
134
            logger.debug("AuthorityResolver.tick: no current trust state yet — skipping");
9✔
135
            return;
3✔
136
        }
137
        IRI currentGraph = getCurrentSpaceStateGraph();
×
138
        String currentGraphName = (currentGraph == null) ? null
×
139
                : currentGraph.stringValue().substring(SpacesVocab.NPASS_NAMESPACE.length());
×
140
        if (currentGraphName == null || !currentGraphName.startsWith(trustStateHash + "_")) {
×
141
            logger.info("AuthorityResolver.tick: trust-state flip detected (now {}); running full build",
×
142
                    abbrev(trustStateHash));
×
143
            runFullBuild(trustStateHash);
×
144
            return;
×
145
        }
146
        runIncrementalCycle(currentGraph);
×
147
    }
×
148

149
    /**
150
     * Periodic worker. If {@code npa:needsFullRebuild} was raised by an
151
     * incremental cycle's structural DELETE, runs a from-scratch rebuild into
152
     * a fresh space-state graph (using the current trust-state hash and load
153
     * counter) and clears the flag. No-op when the flag is not set. Safe to
154
     * call concurrently with {@link #tick()} when both are scheduled on the
155
     * same single-threaded executor.
156
     */
157
    public void periodicRebuildTick() {
158
        if (!FeatureFlags.spacesEnabled()) return;
×
159
        if (!readNeedsFullRebuild()) return;
×
160
        String trustStateHash = TrustStateRegistry.get().getCurrentHash().orElse(null);
×
161
        if (trustStateHash == null) {
×
162
            logger.debug("AuthorityResolver.periodicRebuildTick: no current trust state — deferring");
×
163
            return;
×
164
        }
165
        logger.info("AuthorityResolver.periodicRebuildTick: needsFullRebuild flag set; rebuilding");
×
166
        runFullBuild(trustStateHash);
×
167
        clearNeedsFullRebuild();
×
168
    }
×
169

170
    /**
171
     * Startup cleanup: drop any {@code npass:*} graph that the
172
     * {@code npa:hasCurrentSpaceState} pointer isn't pointing at. Orphans come
173
     * from crashes mid-build. Safe to call at any time; idempotent.
174
     */
175
    public void cleanOrphans() {
176
        if (!FeatureFlags.spacesEnabled()) return;
×
177
        IRI current = getCurrentSpaceStateGraph();
×
178
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
179
            int dropped = 0;
×
180
            try (RepositoryResult<org.eclipse.rdf4j.model.Resource> ctxs = conn.getContextIDs()) {
×
181
                List<IRI> toDrop = new ArrayList<>();
×
182
                while (ctxs.hasNext()) {
×
183
                    org.eclipse.rdf4j.model.Resource ctx = ctxs.next();
×
184
                    if (!(ctx instanceof IRI iri)) continue;
×
185
                    if (!iri.stringValue().startsWith(SpacesVocab.NPASS_NAMESPACE)) continue;
×
186
                    if (iri.equals(current)) continue;
×
187
                    toDrop.add(iri);
×
188
                }
×
189
                for (IRI iri : toDrop) {
×
190
                    conn.begin(IsolationLevels.SERIALIZABLE);
×
191
                    conn.clear(iri);
×
192
                    conn.commit();
×
193
                    dropped++;
×
194
                    logger.info("AuthorityResolver.cleanOrphans: dropped orphan graph {}", iri);
×
195
                }
×
196
            }
197
            if (dropped == 0) {
×
198
                logger.debug("AuthorityResolver.cleanOrphans: no orphan space-state graphs");
×
199
            }
200
        } catch (Exception ex) {
×
201
            logger.info("AuthorityResolver.cleanOrphans: failed: {}", ex.toString());
×
202
        }
×
203
    }
×
204

205
    // ---------------- Full build ----------------
206

207
    /**
208
     * Mutex-protected full build of the space-state graph for the given trust
209
     * state. Captures {@code M = currentLoadCounter}, mirrors trust-approved
210
     * rows, (PR 2b: runs per-tier UPDATE loops from scratch), stamps
211
     * {@code processedUpTo = M}, flips the pointer, drops the previous graph.
212
     */
213
    synchronized void runFullBuild(String trustStateHash) {
214
        long startNanos = System.nanoTime();
×
215
        long loadCounter = getCurrentLoadCounter();
×
216
        IRI newGraph = SpacesVocab.forSpaceState(trustStateHash, loadCounter);
×
217
        IRI oldGraph = getCurrentSpaceStateGraph();
×
218
        if (newGraph.equals(oldGraph)) {
×
219
            logger.debug("AuthorityResolver.runFullBuild: already current at {}", newGraph);
×
220
            return;
×
221
        }
222

223
        // 1. Mirror trust-approved rows into the new graph.
224
        int mirrored = mirrorTrustState(trustStateHash, newGraph);
×
225

226
        // 2. Per-tier UPDATE loops (from scratch: lastProcessed = -1 so the
227
        //    delta filter FILTER(?ln > ?lastProcessed) includes everything).
228
        TierInsertedTriples counts = runAllTierLoops(newGraph, -1);
×
229

230
        // 3. Stamp processedUpTo inside the new graph.
231
        writeProcessedUpTo(newGraph, loadCounter);
×
232

233
        // 4. Flip the current-space-state pointer.
234
        flipPointer(newGraph);
×
235

236
        // 5. Drop the old graph if one existed.
237
        if (oldGraph != null) {
×
238
            dropGraph(oldGraph);
×
239
        }
240

241
        TierSubjectTotals totals = computeTierSubjectTotals(newGraph);
×
242
        long durationMs = (System.nanoTime() - startNanos) / 1_000_000L;
×
243
        lastSubjectTotals = totals;
×
244
        lastInsertedTriplesTotal = (long) counts.admin + counts.alias + counts.presetAttachment
×
245
                + counts.presetAssignmentRef
246
                + counts.attachment + counts.maintainer + counts.member + counts.observer
247
                + counts.subSpace + counts.subSpacePrefix + counts.maintainedResource;
248
        lastFullBuildDurationMs = durationMs;
×
249
        lastProcessedUpToLag = 0L;
×
250
        logger.info("AuthorityResolver: full build complete — graph={} mirrored={} rows loadCounter={} "
×
251
                        + "subjects: adminRIs={} attachmentRAs={} nonAdminRIs={} "
252
                        + "(inserted-triples: admin={} alias={} preset-attachment={} preset-assignment-ref={} attachment={} maintainer={} member={} observer={} "
253
                        + "subspace={} subspace-prefix={} maintained-resource={}) durationMs={}",
254
                newGraph, mirrored, loadCounter,
×
255
                totals.adminRIs(), totals.attachmentRAs(), totals.nonAdminRIs(),
×
256
                counts.admin, counts.alias, counts.presetAttachment, counts.presetAssignmentRef, counts.attachment, counts.maintainer, counts.member, counts.observer,
×
257
                counts.subSpace, counts.subSpacePrefix, counts.maintainedResource,
×
258
                durationMs);
×
259
    }
×
260

261
    // ---------------- Incremental cycle ----------------
262

263
    /**
264
     * Single delta cycle on the current space-state graph. Bounded by
265
     * {@code (processedUpTo, currentLoadCounter]}; no-op if the range is empty.
266
     *
267
     * <p>Order:
268
     * <ol>
269
     *   <li>Apply invalidation DELETEs (admin RI, RoleAssignment, non-admin RI)
270
     *       and the RoleDeclaration ASK. Any DELETE on a structural kind sets
271
     *       {@code npa:needsFullRebuild} to bound the staleness from sticky
272
     *       downstream entries; the periodic worker turns that into a from-scratch
273
     *       rebuild on its next pass.</li>
274
     *   <li>Run per-tier INSERTs in the same order as the full build.</li>
275
     *   <li>Late-arrival sweep: if any structural row was added, re-run downstream
276
     *       tier INSERTs with {@code lastProcessed = -1} to catch candidates whose
277
     *       enabling event landed in this same cycle. Dedup filters protect
278
     *       against double-insert.</li>
279
     *   <li>Bump {@code processedUpTo} to {@code currentLoadCounter}.</li>
280
     * </ol>
281
     */
282
    synchronized void runIncrementalCycle(IRI graph) {
283
        long startNanos = System.nanoTime();
×
284
        long currentLoadCounter = getCurrentLoadCounter();
×
285
        long lastProcessed = readProcessedUpTo(graph);
×
286
        if (lastProcessed < 0) {
×
287
            logger.warn("AuthorityResolver.runIncrementalCycle: missing processedUpTo on {}; skipping",
×
288
                    graph);
289
            return;
×
290
        }
291
        lastProcessedUpToLag = currentLoadCounter - lastProcessed;
×
292
        if (currentLoadCounter <= lastProcessed) {
×
293
            logger.debug("AuthorityResolver.runIncrementalCycle: caught up at load {} on {}",
×
294
                    currentLoadCounter, graph);
×
295
            return;
×
296
        }
297

298
        boolean structuralInvalidation = applyInvalidations(graph, lastProcessed);
×
299
        TierInsertedTriples counts = runAllTierLoops(graph, lastProcessed);
×
300
        boolean structuralAdds = (counts.admin > 0)
×
301
                || (counts.alias > 0)
302
                || (counts.presetAttachment > 0)
303
                || (counts.attachment > 0)
304
                || (counts.subSpace > 0)
305
                || newRoleDeclarationsArrived(lastProcessed)
×
306
                || newPresetAssignmentsArrived(lastProcessed);
×
307
        if (structuralAdds) {
×
308
            // Late-arrival sweep: leaf tiers (attachment/maintainer/member/observer)
309
            // can promote candidates whose enabling event arrived in this same cycle.
310
            // Sub-space admit is also re-run here for Mode-B late-arrival (a new
311
            // partner declaration can validate an older primary that the regular
312
            // pass's load-number filter excluded). The URL-prefix fallback also
313
            // re-runs so newly-orphaned children pick up derived edges. Skip the
314
            // admin tier — its only enabling event is the admin grant itself,
315
            // already handled by the regular pass.
316
            TierInsertedTriples lateCounts = runDownstreamWithoutLoadFilter(graph);
×
317
            counts.alias              += lateCounts.alias;
×
318
            counts.presetAttachment   += lateCounts.presetAttachment;
×
319
            counts.presetAssignmentRef += lateCounts.presetAssignmentRef;
×
320
            counts.attachment         += lateCounts.attachment;
×
321
            counts.maintainer         += lateCounts.maintainer;
×
322
            counts.member             += lateCounts.member;
×
323
            counts.observer           += lateCounts.observer;
×
324
            counts.subSpace           += lateCounts.subSpace;
×
325
            counts.subSpacePrefix     += lateCounts.subSpacePrefix;
×
326
            counts.maintainedResource += lateCounts.maintainedResource;
×
327
        }
328

329
        writeProcessedUpTo(graph, currentLoadCounter);
×
330

331
        TierSubjectTotals totals = computeTierSubjectTotals(graph);
×
332
        long durationMs = (System.nanoTime() - startNanos) / 1_000_000L;
×
333
        lastSubjectTotals = totals;
×
334
        lastInsertedTriplesTotal = (long) counts.admin + counts.alias + counts.presetAttachment
×
335
                + counts.presetAssignmentRef
336
                + counts.attachment + counts.maintainer + counts.member + counts.observer
337
                + counts.subSpace + counts.subSpacePrefix + counts.maintainedResource;
338
        lastIncrementalCycleDurationMs = durationMs;
×
339
        logger.info("AuthorityResolver: incremental cycle complete — graph={} delta=({}, {}] "
×
340
                        + "subjects: adminRIs={} attachmentRAs={} nonAdminRIs={} "
341
                        + "(inserted-triples: admin={} alias={} preset-attachment={} preset-assignment-ref={} attachment={} maintainer={} member={} observer={} "
342
                        + "subspace={} subspace-prefix={} maintained-resource={}) "
343
                        + "structuralInvalidation={} structuralAdds={} durationMs={}",
344
                graph, lastProcessed, currentLoadCounter,
×
345
                totals.adminRIs(), totals.attachmentRAs(), totals.nonAdminRIs(),
×
346
                counts.admin, counts.alias, counts.presetAttachment, counts.presetAssignmentRef, counts.attachment, counts.maintainer, counts.member, counts.observer,
×
347
                counts.subSpace, counts.subSpacePrefix, counts.maintainedResource,
×
348
                structuralInvalidation, structuralAdds, durationMs);
×
349
    }
×
350

351
    /**
352
     * Runs the four invalidation-DELETE / ASK steps. Sets {@code npa:needsFullRebuild}
353
     * when admin-RI, RoleAssignment, or RoleDeclaration invalidations matched (the
354
     * three structural kinds). Leaf-tier RI deletes don't set the flag.
355
     *
356
     * @return true iff at least one structural kind was invalidated
357
     */
358
    boolean applyInvalidations(IRI graph, long lastProcessed) {
359
        boolean structural = false;
×
360
        if (wouldInvalidate(graph, lastProcessed, /*adminPinned=*/ true,
×
361
                            adminInvalidationCheckWhere(graph, lastProcessed))) {
×
362
            executeUpdate(adminInvalidationDelete(graph, lastProcessed));
×
363
            structural = true;
×
364
        }
365
        if (wouldInvalidate(graph, lastProcessed, /*adminPinned=*/ false,
×
366
                            roleAssignmentInvalidationCheckWhere(graph, lastProcessed))) {
×
367
            executeUpdate(roleAssignmentInvalidationDelete(graph, lastProcessed));
×
368
            structural = true;
×
369
        }
370
        // Role-declaration invalidation is deliberately NOT acted on (see
371
        // nonAdminTierUpdate): a role assignment is governed by the admin-validated
372
        // attachment, not by the declaration author's later supersession/retraction, so
373
        // an invalidated RD neither deletes rows nor triggers a rebuild.
374
        // Sub-space declarations are structural — invalidating one (Mode A) or one
375
        // of two co-declarations (Mode B) changes the validated parent/child
376
        // topology. The DELETE removes the per-declaration row; the convenience-edge
377
        // cleanup then drops the now-unbacked direct triples (issue #125 finding #5)
378
        // instead of leaving them sticky until the periodic rebuild. The structural
379
        // flag still fires so downstream rows derived through a removed edge stay
380
        // rebuild-bounded.
381
        if (wouldInvalidate(graph, lastProcessed, /*adminPinned=*/ false,
×
382
                            subSpaceInvalidationCheckWhere(graph, lastProcessed))) {
×
383
            executeUpdate(subSpaceInvalidationDelete(graph, lastProcessed));
×
384
            executeUpdate(subSpaceConvenienceEdgeCleanup(graph, lastProcessed));
×
385
            structural = true;
×
386
        }
387
        // Space-alias declarations are structural — invalidating one removes an
388
        // owl:sameAs edge that feeds the admin-authority closure (issue #113). The
389
        // DELETE removes the per-declaration row; the convenience-edge cleanup then
390
        // drops the now-unbacked npa:sameAsSpace edge (issue #125 finding #5 — the
391
        // load-bearing case), so admin authority can no longer outlive a retraction
392
        // until the next periodic rebuild.
393
        if (wouldInvalidate(graph, lastProcessed, /*adminPinned=*/ false,
×
394
                            aliasInvalidationCheckWhere(graph, lastProcessed))) {
×
395
            executeUpdate(aliasInvalidationDelete(graph, lastProcessed));
×
396
            executeUpdate(aliasConvenienceEdgeCleanup(graph, lastProcessed));
×
397
            structural = true;
×
398
        }
399
        // Preset-derived RoleAssignment removal (issue #302). NOT npx:invalidates: a newer
400
        // admin-authored same-(preset,resource) assignment supersedes by dct:created (a
401
        // gen:DeactivatedPresetAssignment, or any newer assignment that is no longer active).
402
        // Structural — sticky downstream non-admin RIs derived through a removed attachment
403
        // are bounded by the periodic full rebuild. The DELETE is scoped by
404
        // npa:derivedFromPreset so directly-published gen:hasRole attachments are never
405
        // touched; the §4.3 re-INSERT re-materializes only currently-active pairs in the same
406
        // cycle. See doc/design-preset-role-materialization.md §4.4.
407
        if (wouldInvalidate(graph, lastProcessed, /*adminPinned=*/ false,
×
408
                            presetDeactivationCheckWhere(graph, lastProcessed))) {
×
409
            executeUpdate(presetDeactivationDelete(graph, lastProcessed));
×
410
            structural = true;
×
411
        }
412
        // Leaf-tier RI deletes — no flag.
413
        executeUpdate(leafTierInvalidationDelete(graph, lastProcessed));
×
414
        // Ref-scoped preset-assignment listing stamps whose assignment nanopub was
415
        // hard-retracted (issue #122) — no flag (display leaf, nothing downstream).
416
        executeUpdate(presetAssignmentRefInvalidationDelete(graph, lastProcessed));
×
417
        // Maintained-resource declaration deletes — no flag (leaf relation, no
418
        // downstream caches to bound). The per-declaration delete removes the row; the
419
        // convenience-edge cleanup drops the now-unbacked isMaintainedBy edges (issue
420
        // #125 finding #5). Guarded so the orphan-sweep only scans when something was
421
        // actually invalidated (the delete itself was already a no-op otherwise).
422
        if (wouldInvalidate(graph, lastProcessed, /*adminPinned=*/ false,
×
423
                            maintainedResourceInvalidationCheckWhere(graph, lastProcessed))) {
×
424
            executeUpdate(maintainedResourceInvalidationDelete(graph, lastProcessed));
×
425
            executeUpdate(maintainedResourceConvenienceEdgeCleanup(graph, lastProcessed));
×
426
        }
427
        if (structural) setNeedsFullRebuild();
×
428
        return structural;
×
429
    }
430

431
    /**
432
     * Runs the four leaf tiers (attachment/maintainer/member/observer) with
433
     * {@code lastProcessed = -1} so the load-number filter on the candidate
434
     * side admits everything. Dedup filters in the tier templates prevent
435
     * double-insert. Used by the late-arrival sweep.
436
     */
437
    TierInsertedTriples runDownstreamWithoutLoadFilter(IRI graph) {
438
        TierInsertedTriples c = new TierInsertedTriples();
×
439
        // Alias late-arrival: catches alias declarations whose canonical admin grant
440
        // became valid only in this same cycle (the load-number filter on the
441
        // declaration's nanopub would otherwise exclude it). Runs first so the
442
        // attachment / role tiers below see this cycle's fresh npa:sameAsSpace edges.
443
        c.alias = runTierLabeled("alias(late)", graph, aliasAdmitUpdate(graph, -1));
×
444
        // Sub-space late-arrival: catches Mode-B candidates whose primary
445
        // declaration is older than lastProcessed but whose partner just landed.
446
        c.subSpace = runTierLabeled("subspace(late)", graph,
×
447
                subSpaceAdmitUpdate(graph, -1));
×
448
        // Maintained-resource late-arrival: catches declarations that landed
449
        // before the publisher's admin grant became valid in this state.
450
        c.maintainedResource = runTierLabeled("maintained-resource(late)", graph,
×
451
                maintainedResourceAdmitUpdate(graph, -1));
×
452
        // URL-prefix fallback: re-run after the late-arrival sub-space admit so
453
        // any newly-validated children get their fallback edges suppressed (for
454
        // future inserts) and any newly-orphaned children pick up fallback edges.
455
        c.subSpacePrefix = runTierLabeled("subspace-prefix(late)", graph,
×
456
                subSpacePrefixFallbackUpdate(graph));
×
457
        // Preset-attachment late-arrival: catches assignments whose preset declaration or
458
        // admin grant only became valid in this same cycle. Runs before attachment(late)
459
        // so the non-admin late tiers below see this cycle's fresh preset-derived RAs.
460
        c.presetAttachment = runTierLabeled("preset-attachment(late)", graph,
×
461
                presetAttachmentValidationUpdate(graph, -1));
×
462
        // Ref-scoped preset-assignment late stamp: catches assignments whose authorizing
463
        // admin grant only became valid this cycle (the load filter would skip the older
464
        // assignment nanopub). Mirrors the preset-attachment late sweep above.
465
        c.presetAssignmentRef = runTierLabeled("preset-assignment-ref(late)", graph,
×
466
                presetAssignmentRefStampUpdate(graph, -1));
×
467
        c.attachment = runTierLabeled("attachment(late)", graph,
×
468
                attachmentValidationUpdate(graph, -1));
×
469
        c.maintainer = runTierLabeled("maintainer(late)", graph,
×
470
                nonAdminTierUpdate(graph, -1, GEN.MAINTAINER_ROLE, PUBLISHER_IS_ADMIN));
×
471
        c.member = runTierLabeled("member(admin-pub,late)", graph,
×
472
                nonAdminTierUpdate(graph, -1, GEN.MEMBER_ROLE, PUBLISHER_IS_ADMIN));
×
473
        c.member += runTierLabeled("member(maint-pub,late)", graph,
×
474
                nonAdminTierUpdate(graph, -1,
×
475
                        GEN.MEMBER_ROLE, publisherIsTieredRole(GEN.MAINTAINER_ROLE)));
×
476
        c.observer = runTierLabeled("observer(admin-pub,late)", graph,
×
477
                nonAdminTierUpdate(graph, -1, GEN.OBSERVER_ROLE, PUBLISHER_IS_ADMIN));
×
478
        c.observer += runTierLabeled("observer(maint-pub,late)", graph,
×
479
                nonAdminTierUpdate(graph, -1,
×
480
                        GEN.OBSERVER_ROLE, publisherIsTieredRole(GEN.MAINTAINER_ROLE)));
×
481
        c.observer += runTierLabeled("observer(member-pub,late)", graph,
×
482
                nonAdminTierUpdate(graph, -1,
×
483
                        GEN.OBSERVER_ROLE, publisherIsTieredRole(GEN.MEMBER_ROLE)));
×
484
        c.observer += runTierLabeled("observer(self,late)", graph,
×
485
                nonAdminTierUpdate(graph, -1, GEN.OBSERVER_ROLE, PUBLISHER_IS_SELF));
×
486
        return c;
×
487
    }
488

489
    /**
490
     * Cheap ASK: did any new {@code npa:RoleDeclaration} extraction land in the
491
     * load-number delta {@code (lastProcessed, ∞)}? Used by the late-arrival
492
     * trigger so an RD that arrives in the same cycle as a matching candidate
493
     * still gets validated.
494
     */
495
    boolean newRoleDeclarationsArrived(long lastProcessed) {
496
        String ask = String.format("""
×
497
                PREFIX npa: <%1$s>
498
                ASK {
499
                  GRAPH <%2$s> {
500
                    ?rd a npa:RoleDeclaration ;
501
                        npa:viaNanopub ?np .
502
                  }
503
                  GRAPH <%3$s> {
504
                    ?np npa:hasLoadNumber ?ln .
505
                    FILTER (?ln > %4$d)
506
                  }
507
                }
508
                """, NPA.NAMESPACE, SpacesVocab.SPACES_GRAPH, NPA.GRAPH, lastProcessed);
×
509
        return runAsk(ask);
×
510
    }
511

512
    /**
513
     * Cheap ASK: did any new {@code npa:PresetAssignment} or {@code npa:PresetDeclaration}
514
     * extraction land in the load-number delta {@code (lastProcessed, ∞)}? Drives the
515
     * late-arrival re-run so a preset assignment that arrives in the same cycle as its
516
     * declaration (or admin grant) still materializes, and so an arriving newer assignment
517
     * triggers the deactivation/latest-wins re-evaluation.
518
     */
519
    boolean newPresetAssignmentsArrived(long lastProcessed) {
520
        String ask = String.format("""
×
521
                PREFIX npa: <%1$s>
522
                ASK {
523
                  GRAPH <%2$s> {
524
                    ?x a ?t ;
525
                       npa:viaNanopub ?np .
526
                    FILTER (?t = npa:PresetAssignment || ?t = npa:PresetDeclaration)
527
                  }
528
                  GRAPH <%3$s> {
529
                    ?np npa:hasLoadNumber ?ln .
530
                    FILTER (?ln > %4$d)
531
                  }
532
                }
533
                """, NPA.NAMESPACE, SpacesVocab.SPACES_GRAPH, NPA.GRAPH, lastProcessed);
×
534
        return runAsk(ask);
×
535
    }
536

537
    // ---------------- Tier UPDATE loops ----------------
538

539
    /**
540
     * Per-tier inserted-triple tallies for one build or cycle. Counts the sum
541
     * of {@code (graphSize_after - graphSize_before)} across all iterations of
542
     * each tier's fixed-point INSERT loop — i.e. inserted *triples*, not
543
     * distinct subjects (a single RoleInstantiation insert writes 4–5 triples).
544
     *
545
     * <p>Used internally by the {@link #runIncrementalCycle structuralAdds}
546
     * boolean check (we only care whether any tier inserted at all).
547
     * Not what the log lines report: see {@link TierSubjectTotals} +
548
     * {@link #computeTierSubjectTotals} for the distinct-subject totals
549
     * surfaced to operators.
550
     */
551
    static final class TierInsertedTriples {
×
552
        int admin;
553
        int alias;
554
        int presetAttachment;
555
        int presetAssignmentRef;
556
        int attachment;
557
        int maintainer;
558
        int member;
559
        int observer;
560
        int subSpace;
561
        int subSpacePrefix;
562
        int maintainedResource;
563
    }
564

565
    /**
566
     * Snapshot of distinct-subject totals in a space-state graph at a moment
567
     * in time. Independent of which tier-loop added each subject.
568
     */
569
    record TierSubjectTotals(long adminRIs, long attachmentRAs, long nonAdminRIs) {}
36✔
570

571
    /**
572
     * Runs the five tier loops in order: admin → {@code gen:hasRole} attachment
573
     * validation → maintainer → member → observer. Each loop iterates a SPARQL
574
     * INSERT to fixed point (no new triples added). Returns per-tier counts.
575
     *
576
     * @param graph         target space-state graph
577
     * @param lastProcessed load-number horizon; use {@code -1} for full build
578
     */
579
    TierInsertedTriples runAllTierLoops(IRI graph, long lastProcessed) {
580
        TierInsertedTriples c = new TierInsertedTriples();
×
581
        c.admin = runTierLabeled("admin", graph, adminTierUpdate(graph, lastProcessed));
×
582
        // Alias admit runs after the admin closure has settled (both the authority
583
        // gate and the anti-hijack check read the admin set) and before attachment /
584
        // role tiers (their alias-aware admin lookups consume the npa:sameAsSpace edge
585
        // this pass emits). See issue #113.
586
        c.alias = runTierLabeled("alias", graph, aliasAdmitUpdate(graph, lastProcessed));
×
587
        // Sub-space admit runs after admin closure has settled (Mode A + Mode B both
588
        // need the admin set). Independent of role tiers — order between subspace
589
        // and attachment / maintainer / member / observer doesn't matter.
590
        c.subSpace = runTierLabeled("subspace", graph, subSpaceAdmitUpdate(graph, lastProcessed));
×
591
        // Maintained-resource admit also depends only on the admin closure. Single
592
        // Mode A: publisher must be admin of the maintaining space. No co-declaration
593
        // partner, no URL-prefix fallback.
594
        c.maintainedResource = runTierLabeled("maintained-resource", graph,
×
595
                maintainedResourceAdmitUpdate(graph, lastProcessed));
×
596
        // URL-prefix sub-space fallback runs after the explicit-declaration admit
597
        // pass commits so the per-child suppression check sees this cycle's fresh
598
        // validations. No load filter — depends on which Spaces exist, not on
599
        // delta-arrivals; the dedup FILTER NOT EXISTS prevents re-insertion.
600
        c.subSpacePrefix = runTierLabeled("subspace-prefix", graph,
×
601
                subSpacePrefixFallbackUpdate(graph));
×
602
        // Preset-attachment runs immediately before the regular attachment tier so the
603
        // gen:RoleAssignment rows it materializes (from active, admin-authored preset
604
        // assignments) are picked up by the downstream non-admin tiers in the same pass,
605
        // exactly like directly-published attachments. See
606
        // doc/design-preset-role-materialization.md.
607
        c.presetAttachment = runTierLabeled("preset-attachment", graph,
×
608
                presetAttachmentValidationUpdate(graph, lastProcessed));
×
609
        // Ref-scoped preset-assignment listing stamp (issue #122). Display-only leaf —
610
        // independent of the role tiers and of structuralAdds; order doesn't matter.
611
        c.presetAssignmentRef = runTierLabeled("preset-assignment-ref", graph,
×
612
                presetAssignmentRefStampUpdate(graph, lastProcessed));
×
613
        c.attachment = runTierLabeled("attachment", graph,
×
614
                attachmentValidationUpdate(graph, lastProcessed));
×
615
        c.maintainer = runTierLabeled("maintainer", graph, nonAdminTierUpdate(graph, lastProcessed,
×
616
                GEN.MAINTAINER_ROLE, PUBLISHER_IS_ADMIN));
617
        // Member tier: admin OR maintainer publisher — split into two simpler updates
618
        // so the query planner doesn't struggle with the UNION.
619
        c.member = runTierLabeled("member(admin-pub)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
620
                GEN.MEMBER_ROLE, PUBLISHER_IS_ADMIN));
621
        c.member += runTierLabeled("member(maint-pub)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
622
                GEN.MEMBER_ROLE, publisherIsTieredRole(GEN.MAINTAINER_ROLE)));
×
623
        // Observer tier: self-evidence OR a downward grant from any higher tier.
624
        // ObserverRole is the default tier when a role definition omits an
625
        // explicit subclass (see "Role types" in design-space-repositories.md), so
626
        // most "X assigned Y this role" nanopubs land here. Restricting the tier
627
        // to PUBLISHER_IS_SELF would silently drop those grants. The four
628
        // sub-loops mirror the trust-state's downward-only chain: admin grants
629
        // anything; maintainers and members grant observer; everyone may
630
        // self-attest.
631
        c.observer = runTierLabeled("observer(admin-pub)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
632
                GEN.OBSERVER_ROLE, PUBLISHER_IS_ADMIN));
633
        c.observer += runTierLabeled("observer(maint-pub)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
634
                GEN.OBSERVER_ROLE, publisherIsTieredRole(GEN.MAINTAINER_ROLE)));
×
635
        c.observer += runTierLabeled("observer(member-pub)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
636
                GEN.OBSERVER_ROLE, publisherIsTieredRole(GEN.MEMBER_ROLE)));
×
637
        c.observer += runTierLabeled("observer(self)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
638
                GEN.OBSERVER_ROLE, PUBLISHER_IS_SELF));
639
        return c;
×
640
    }
641

642
    /**
643
     * Builds a publisher constraint requiring the publisher to be a validated holder
644
     * of the given tier's role (maintainer or member) in the target space.
645
     * Owns its own AccountState resolution so ?publisher is bound through the
646
     * targeted (pkh → agent) lookup rather than enumerated.
647
     */
648
    private static String publisherIsTieredRole(IRI tierClass) {
649
        // Re-keyed on the assignment's ref (alias → canonical already resolved by the
650
        // attachment tier). Relies on materialized non-admin RIs carrying their role
651
        // property (npa:regularProperty / npa:inverseProperty) — supplied by the
652
        // enrichment in nonAdminTierUpdate; without it this constraint matched nothing.
653
        return """
×
654
                ?acct a npa:AccountState ;
655
                      npa:pubkey ?pkh ;
656
                      npa:agent  ?publisher .
657
                ?tierRI a gen:RoleInstantiation ;
658
                        npa:forSpaceRef ?spaceRef ;
659
                        npa:forAgent ?publisher .
660
                ?rdT a npa:RoleDeclaration ;
661
                     npa:hasRoleType <%1$s> .
662
                { ?tierRI npa:regularProperty ?predT . ?rdT gen:hasRegularProperty ?predT . }
663
                UNION
664
                { ?tierRI npa:inverseProperty ?predT . ?rdT gen:hasInverseProperty ?predT . }
665
                """.formatted(tierClass);
×
666
    }
667

668
    /** Wraps {@link #runTierLoop} with tier-name context for logs/exceptions. */
669
    private int runTierLabeled(String tier, IRI graph, String sparqlUpdate) {
670
        try {
671
            return runTierLoop(graph, sparqlUpdate);
×
672
        } catch (RuntimeException ex) {
×
673
            logger.error("AuthorityResolver: tier={} failed with SPARQL UPDATE:\n{}\n", tier, sparqlUpdate, ex);
×
674
            throw ex;
×
675
        }
676
    }
677

678
    /**
679
     * Runs a single tier's INSERT to fixed point. Counts rows by probing
680
     * graph size before/after each INSERT; stops when the size doesn't change.
681
     *
682
     * @return total number of triples inserted by this tier across all iterations
683
     */
684
    int runTierLoop(IRI graph, String sparqlUpdate) {
685
        int total = 0;
×
686
        long before = graphSize(graph);
×
687
        while (true) {
688
            // Note: no explicit transaction wrapping here. In tests we observed that
689
            // HTTPRepository's RDF4J-transaction protocol silently no-op'd cross-graph
690
            // SPARQL UPDATEs with UNION sub-patterns inside conn.begin()/commit(),
691
            // while the same UPDATE POSTed directly to /statements applied correctly.
692
            // A bare prepareUpdate().execute() takes the direct /statements path and
693
            // runs the UPDATE atomically per SPARQL 1.1 semantics — which is all we
694
            // need; there's nothing else to commit atomically alongside the UPDATE.
695
            try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
696
                conn.prepareUpdate(QueryLanguage.SPARQL, sparqlUpdate).execute();
×
697
            }
698
            long after = graphSize(graph);
×
699
            long added = after - before;
×
700
            if (added <= 0) break;
×
701
            total += added;
×
702
            before = after;
×
703
        }
×
704
        return total;
×
705
    }
706

707
    private long graphSize(IRI graph) {
708
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
709
            return conn.size(graph);
×
710
        }
711
    }
712

713
    /**
714
     * Distinct-subject totals in the given space-state graph, broken down by
715
     * RoleInstantiation kind (admin-pinned vs not) and RoleAssignment.
716
     * Three SELECT-COUNT queries — cheap, called once per build/cycle for
717
     * the user-facing log line. Returns zeros on failure (logged) so a flaky
718
     * count read can't wedge the cycle.
719
     */
720
    TierSubjectTotals computeTierSubjectTotals(IRI graph) {
721
        long adminRIs       = countDistinctSubjects(graph, """
×
722
                ?ri a gen:RoleInstantiation ; npa:inverseProperty gen:hasAdmin .
723
                """, "ri");
724
        long attachmentRAs  = countDistinctSubjects(graph, """
×
725
                ?ra a gen:RoleAssignment .
726
                """, "ra");
727
        long nonAdminRIs    = countDistinctSubjects(graph, """
×
728
                ?ri a gen:RoleInstantiation .
729
                FILTER NOT EXISTS { ?ri npa:inverseProperty gen:hasAdmin }
730
                """, "ri");
731
        return new TierSubjectTotals(adminRIs, attachmentRAs, nonAdminRIs);
×
732
    }
733

734
    private long countDistinctSubjects(IRI graph, String wherePattern, String varName) {
735
        String query = String.format("""
×
736
                PREFIX npa: <%1$s>
737
                PREFIX gen: <%2$s>
738
                SELECT (COUNT(DISTINCT ?%3$s) AS ?n) WHERE {
739
                  GRAPH <%4$s> {
740
                    %5$s
741
                  }
742
                }
743
                """, NPA.NAMESPACE, GEN.NAMESPACE, varName, graph, wherePattern);
744
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO);
×
745
             TupleQueryResult r = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) {
×
746
            if (!r.hasNext()) return 0;
×
747
            return Long.parseLong(r.next().getBinding("n").getValue().stringValue());
×
748
        } catch (Exception ex) {
×
749
            logger.warn("AuthorityResolver: countDistinctSubjects on {} failed: {}",
×
750
                    graph, ex.toString());
×
751
            return 0;
×
752
        }
753
    }
754

755
    // ---------------- SPARQL templates ----------------
756

757
    /**
758
     * Reusable invalidation filter on a bound nanopub-IRI variable. Pass the bare
759
     * variable name (no leading {@code ?}); e.g. {@code invalidationFilter("np")}
760
     * produces an outer-scoped {@code FILTER NOT EXISTS { GRAPH npa:graph
761
     * { ?_inv_np npx:invalidates ?np . } }}.
762
     *
763
     * <p>Joins on the raw {@code npx:invalidates} triple in {@code npa:graph},
764
     * which {@link com.knowledgepixels.query.NanopubLoader} writes into the
765
     * spaces repo from two complementary directions, making the filter symmetric
766
     * in load order:
767
     * <ul>
768
     *   <li>At the invalidator's own load: the loader's space-repo trigger fires
769
     *       whenever the nanopub has either its own space-relevant extractions
770
     *       OR an {@code npx:invalidates}/{@code npx:retracts}/{@code npx:supersedes}
771
     *       triple, so a pure-retraction nanopub still lands its raw triple plus
772
     *       {@code npa:hasLoadNumber} stamp in {@code npa:graph}.</li>
773
     *   <li>At the invalidated target's load (when the invalidator landed
774
     *       earlier): {@code NanopubLoader.getInvalidatingStatements} reads the
775
     *       triple back from the meta repo and mirrors it into the target's own
776
     *       write to the spaces repo.</li>
777
     * </ul>
778
     *
779
     * <p>The earlier shape joined on a structured {@code npa:Invalidation} entry
780
     * in {@code npa:spacesGraph} that was only emitted on the invalidator's side
781
     * AND only when the invalidated target's meta had already loaded, leaving a
782
     * window where a superseding nanopub loaded before its target produced no
783
     * entry and the stale row was never filtered out (see also the matching
784
     * change in the tier-specific {@code *InvalidationCheckWhere}/{@code
785
     * *InvalidationDelete} templates below).
786
     *
787
     * <p>Important: this filter must be placed OUTSIDE the surrounding
788
     * {@code GRAPH npa:spacesGraph { ... }} block, not nested inside it. When
789
     * nested, RDF4J's planner couples the FILTER NOT EXISTS evaluation into the
790
     * join order (per-row scan multiplied by the candidate set), which we
791
     * measured turning a 39ms query into a 60s+ timeout on the live observer-tier
792
     * data. Outside the GRAPH block, the planner defers the filter until
793
     * {@code ?np}/{@code ?rdNp} are bound and does a targeted index lookup.
794
     *
795
     * <p>Variable names must match {@code [A-Za-z0-9_]+} per SPARQL grammar —
796
     * embedding a {@code ?} inside {@code ?_inv_?np} would yield a parse error.
797
     */
798
    private static String invalidationFilter(String bareVarName) {
799
        return "FILTER NOT EXISTS { GRAPH <" + NPA.GRAPH + "> {"
30✔
800
                + " ?_inv_" + bareVarName
801
                + " <" + NPX.INVALIDATES + "> ?" + bareVarName + " . "
802
                + samePublisherClause("_inv_" + bareVarName, bareVarName)
6✔
803
                + " } }";
804
    }
805

806
    /**
807
     * SPARQL triple pair (placed inside a {@code GRAPH npa:graph { ... }} block)
808
     * requiring the invalidating nanopub and its target to share a signing public
809
     * key — the self-retraction authority gate for issue #112. Without it, the
810
     * materializer honors {@code npx:invalidates}/{@code retracts}/{@code supersedes}
811
     * from <em>any</em> validly-signed nanopub, so any agent can erase another
812
     * space's materialized state (griefing/DoS of the view — fail-closed, no
813
     * privilege escalation, but real). Additions are already admin-gated; this is
814
     * the symmetric gate on removals.
815
     *
816
     * <p>Both {@code npa:hasValidSignatureForPublicKeyHash} triples live in
817
     * {@code npa:graph} of the spaces repo: the target via its own space-load, the
818
     * invalidator via the symmetric retractor propagation in
819
     * {@link com.knowledgepixels.query.NanopubLoader} (forward {@code
820
     * loadInvalidateStatements} + reverse {@code loadInvalidatorIntoSpacesRepo}),
821
     * so the join is populated regardless of load order.
822
     *
823
     * <p>"Same pubkey" is intentionally stricter than "same agent": a retraction
824
     * signed by a different key the author owns (key rotation) is not honored, and
825
     * cross-admin supersession is out of scope here (would need an admin-authority
826
     * arm). The pubkey-bridge variable is suffixed with {@code targetVar} so two
827
     * filters in one query (e.g. on {@code ?np} and {@code ?rdNp}) don't collide.
828
     *
829
     * @param invVar    invalidator nanopub variable name (no leading {@code ?})
830
     * @param targetVar invalidated-target nanopub variable name (no leading {@code ?})
831
     */
832
    private static String samePublisherClause(String invVar, String targetVar) {
833
        String pk = "?_invpk_" + targetVar;
9✔
834
        return "?" + invVar + " <" + NPA.HAS_VALID_SIGNATURE_FOR_PUBLIC_KEY_HASH + "> " + pk + " . "
30✔
835
                + "?" + targetVar + " <" + NPA.HAS_VALID_SIGNATURE_FOR_PUBLIC_KEY_HASH + "> " + pk + " .";
836
    }
837

838
    /**
839
     * Admin tier: seed from {@code npadef:...hasRootAdmin} (trusted by construction)
840
     * plus closed-over admin grants; insert any {@code gen:RoleInstantiation} with
841
     * {@code npa:inverseProperty gen:hasAdmin} whose publisher (resolved via mirrored
842
     * trust-approved AccountState) is already in the admin set.
843
     *
844
     * <p>The seed is gated by {@link #spaceRefAliveFilter} (not the per-nanopub
845
     * {@code invalidationFilter("defNp")}): the {@code hasRootAdmin} seed is anchored
846
     * to the root NPID, which is the immutable space-ref identity, so superseding the
847
     * root <em>nanopub</em> with a continuation revision must not strip the seed —
848
     * only retracting every definition of the ref removes it. See issue #110.
849
     */
850
    static String adminTierUpdate(IRI graph, long lastProcessed) {
851
        // Order tuned for RDF4J's evaluator:
852
        //   1. Anchor on the small (seed UNION closed-over) set to bind ?publisher
853
        //      and ?space cheaply.
854
        //   2. Resolve ?pkh from the mirrored AccountState row (?publisher bound).
855
        //   3. Probe instantiations using the now-bound (?space, ?pkh) — targeted
856
        //      lookup, not a full RoleInstantiation scan.
857
        //   4. Load-number filter on bound ?np.
858
        //   5. Dedup at the end.
859
        // Authority is keyed on the space *ref* (npa:forSpaceRef), not the bare Space
860
        // IRI: two refs that share an IRI but have different roots are independent
861
        // domains (see doc/design-spaceref-isolation.md). The instantiation evidence in
862
        // the extraction graph is IRI-keyed (a gen:hasAdmin nanopub names the bare IRI),
863
        // so we project it per-ref by joining each instantiation naming ?space to the
864
        // admin rows of every ref of ?space whose admin set contains the publisher. The
865
        // inserted subject is minted per (?ri, ?spaceRef) so one instantiation validating
866
        // into N refs yields N distinct rows. TRANSITIONAL-DUAL-EMIT (Phase 4: remove):
867
        // forSpace is still emitted alongside forSpaceRef so the not-yet-migrated
868
        // downstream tiers / pre-ref read queries keep functioning on a mixed-version
869
        // fleet; it is dropped once everything keys on forSpaceRef.
870
        return """
69✔
871
                PREFIX npa:  <%1$s>
872
                PREFIX gen:  <%2$s>
873
                INSERT { GRAPH <%3$s> {
874
                  ?sri a gen:RoleInstantiation ;
875
                       npa:forSpaceRef ?spaceRef ;
876
                       npa:forSpace ?space ;
877
                       npa:inverseProperty gen:hasAdmin ;
878
                       # Stamp the admin tier so consumers read tier uniformly across all
879
                       # RoleInstantiations (?ri npa:hasRoleType ?tier) with no admin
880
                       # special-case — matching the non-admin path (issue #125, #127).
881
                       npa:hasRoleType gen:AdminRole ;
882
                       npa:forAgent ?agent ;
883
                       npa:viaNanopub ?np .
884
                } }
885
                WHERE {
886
                  # 1. Anchor: who is already an admin of which space ref?
887
                  {
888
                    # Seed branch: root-admin of a space ref that is still alive
889
                    # (has at least one non-invalidated definition). NOT filtered on
890
                    # ?def's own invalidation — superseding the root nanopub with a
891
                    # continuation revision must keep the seed; only a fully-retracted
892
                    # ref drops it (issue #110).
893
                    GRAPH <%4$s> {
894
                      ?def a npa:SpaceDefinition ;
895
                           npa:forSpaceRef  ?spaceRef ;
896
                           npa:hasRootAdmin ?publisher .
897
                      ?spaceRef npa:spaceIri ?space .
898
                    }
899
                    %7$s
900
                  }
901
                  UNION
902
                  {
903
                    # Closed-over branch: an existing admin of this ref. Recurse on the
904
                    # ref, then resolve its bare IRI to probe the IRI-keyed instantiation.
905
                    GRAPH <%3$s> {
906
                      ?prev a gen:RoleInstantiation ;
907
                            npa:forSpaceRef     ?spaceRef ;
908
                            npa:inverseProperty gen:hasAdmin ;
909
                            npa:forAgent        ?publisher .
910
                    }
911
                    GRAPH <%4$s> {
912
                      ?spaceRef npa:spaceIri ?space .
913
                    }
914
                  }
915
                  # 2. Mirror: resolve ?publisher → ?pkh via the trust-approved row.
916
                  GRAPH <%3$s> {
917
                    ?acct a npa:AccountState ;
918
                          npa:agent  ?publisher ;
919
                          npa:pubkey ?pkh .
920
                  }
921
                  # 3. Targeted instantiation lookup by space + pubkey (IRI-keyed).
922
                  GRAPH <%4$s> {
923
                    ?ri a gen:RoleInstantiation ;
924
                        npa:forSpace        ?space ;
925
                        npa:inverseProperty gen:hasAdmin ;
926
                        npa:forAgent        ?agent ;
927
                        npa:pubkeyHash      ?pkh ;
928
                        npa:viaNanopub      ?np .
929
                  }
930
                  # 3a. Mint the per-ref state subject: (?ri, ?spaceRef) → ?sri.
931
                  BIND(IRI(CONCAT(STR(?ri), "__", ENCODE_FOR_URI(STR(?spaceRef)))) AS ?sri)
932
                  %6$s
933
                  # 4. Load-number filter on bound ?np.
934
                  GRAPH <%8$s> {
935
                    ?np npa:hasLoadNumber ?ln .
936
                    FILTER (?ln > %5$d)
937
                  }
938
                  # 5. Dedup last — keyed on (ref, agent).
939
                  FILTER NOT EXISTS { GRAPH <%3$s> {
940
                    ?existing a gen:RoleInstantiation ;
941
                              npa:forSpaceRef ?spaceRef ;
942
                              npa:forAgent ?agent ;
943
                              npa:inverseProperty gen:hasAdmin .
944
                  } }
945
                }
946
                """.formatted(
3✔
947
                NPA.NAMESPACE,
948
                GEN.NAMESPACE,
949
                graph,
950
                SpacesVocab.SPACES_GRAPH,
951
                lastProcessed,
15✔
952
                invalidationFilter("np"),
12✔
953
                spaceRefAliveFilter(),
18✔
954
                NPA.GRAPH);
955
    }
956

957
    /**
958
     * Seed-survival filter for the admin tier (issue #110). The {@code hasRootAdmin}
959
     * seed is anchored to the root NPID, which is the immutable space-ref identity, so
960
     * it must survive supersession of the root <em>nanopub</em> by a continuation
961
     * revision (a later definition re-roots to the same ref via
962
     * {@code gen:hasRootDefinition} and so carries no {@code hasRootAdmin} of its own).
963
     * The previous {@code invalidationFilter("defNp")} dropped the seed the moment the
964
     * root revision was superseded, leaving the whole admin closure — and everything
965
     * cascading from it — unmaterialized for any space whose definition had ever been
966
     * updated.
967
     *
968
     * <p>Expressed positively: the seed survives iff the space ref still has at least
969
     * one non-invalidated {@link SpacesVocab#SPACE_DEFINITION}. A fully-retracted ref
970
     * (every definition invalidated) has no live definition, so the {@code FILTER
971
     * EXISTS} fails and the seed correctly disappears. Anchored on the already-bound
972
     * {@code ?spaceRef}, so it's a targeted lookup over that ref's (few) definitions.
973
     */
974
    private static String spaceRefAliveFilter() {
975
        return """
33✔
976
                FILTER EXISTS {
977
                  GRAPH <%1$s> {
978
                    ?liveDef a npa:SpaceDefinition ;
979
                             npa:forSpaceRef ?spaceRef ;
980
                             npa:viaNanopub  ?liveNp .
981
                  }
982
                  %2$s
983
                }
984
                """.formatted(SpacesVocab.SPACES_GRAPH, invalidationFilter("liveNp"));
9✔
985
    }
986

987
    /**
988
     * {@code gen:hasRole} attachment validation: an attachment is validated iff its
989
     * publisher is already a validated admin of the target space. Adds
990
     * {@code gen:RoleAssignment} rows to the space-state graph.
991
     */
992
    static String attachmentValidationUpdate(IRI graph, long lastProcessed) {
993
        // Ref-keyed (see doc/design-spaceref-isolation.md). The attachment names a bare
994
        // Space IRI; it is validated per-ref for every ref of that IRI whose admin set
995
        // contains the publisher (direct), or — when the named IRI is an owl:sameAs alias
996
        // — for the canonical ref it maps to (issue #113). ?targetRef is the ref the
997
        // RoleAssignment attaches to; the inserted subject is minted per (?ra, ?targetRef)
998
        // so one attachment validating into N refs yields N distinct rows.
999
        // TRANSITIONAL-DUAL-EMIT (Phase 4: remove): forSpace (the attached IRI, possibly an
1000
        // alias) is kept so the non-admin tier can probe the IRI-keyed instantiations
1001
        // naming it, and so pre-ref read queries keep functioning on a mixed-version fleet.
1002
        return """
69✔
1003
                PREFIX npa:  <%1$s>
1004
                PREFIX gen:  <%2$s>
1005
                INSERT { GRAPH <%3$s> {
1006
                  ?ra2 a gen:RoleAssignment ;
1007
                       npa:forSpaceRef ?targetRef ;
1008
                       npa:forSpace ?space ;
1009
                       gen:hasRole  ?role ;
1010
                       npa:viaNanopub ?np .
1011
                } }
1012
                WHERE {
1013
                  GRAPH <%4$s> {
1014
                    ?ra a gen:RoleAssignment ;
1015
                        npa:forSpace ?space ;
1016
                        gen:hasRole  ?role ;
1017
                        npa:pubkeyHash ?pkh ;
1018
                        npa:viaNanopub ?np .
1019
                  }
1020
                  GRAPH <%7$s> {
1021
                    ?np npa:hasLoadNumber ?ln .
1022
                    FILTER (?ln > %5$d)
1023
                  }
1024
                  GRAPH <%3$s> {
1025
                    ?acct a npa:AccountState ;
1026
                          npa:agent  ?publisher ;
1027
                          npa:pubkey ?pkh .
1028
                  }
1029
                  # Per-ref admin gate. ?targetRef = a ref of ?space the publisher admins
1030
                  # (direct), or the canonical ref ?space is an owl:sameAs alias of.
1031
                  {
1032
                    GRAPH <%4$s> { ?targetRef npa:spaceIri ?space . }
1033
                    GRAPH <%3$s> {
1034
                      ?adminRI a gen:RoleInstantiation ;
1035
                               npa:forSpaceRef ?targetRef ;
1036
                               npa:inverseProperty gen:hasAdmin ;
1037
                               npa:forAgent ?publisher .
1038
                    }
1039
                  }
1040
                  UNION
1041
                  {
1042
                    GRAPH <%3$s> {
1043
                      ?space npa:sameAsSpace ?targetRef .
1044
                      ?adminRI a gen:RoleInstantiation ;
1045
                               npa:forSpaceRef ?targetRef ;
1046
                               npa:inverseProperty gen:hasAdmin ;
1047
                               npa:forAgent ?publisher .
1048
                    }
1049
                  }
1050
                  BIND(IRI(CONCAT(STR(?ra), "__", ENCODE_FOR_URI(STR(?targetRef)))) AS ?ra2)
1051
                  %6$s
1052
                  FILTER NOT EXISTS { GRAPH <%3$s> {
1053
                    ?existing a gen:RoleAssignment ;
1054
                              npa:forSpaceRef ?targetRef ;
1055
                              gen:hasRole  ?role .
1056
                  } }
1057
                }
1058
                """.formatted(
3✔
1059
                NPA.NAMESPACE,
1060
                GEN.NAMESPACE,
1061
                graph,
1062
                SpacesVocab.SPACES_GRAPH,
1063
                lastProcessed,
15✔
1064
                invalidationFilter("np"),
18✔
1065
                NPA.GRAPH);
1066
    }
1067

1068
    /**
1069
     * Preset-bundled role materialization (Nanodash issue #302). For each active,
1070
     * admin-authored {@code gen:PresetAssignment} targeting a {@code gen:Space}, inserts
1071
     * one {@code gen:RoleAssignment} per role the preset bundles — exactly as if
1072
     * {@code <space> gen:hasRole <role>} had been published by the assignment's publisher.
1073
     * The materialized rows carry {@code npa:derivedFromPreset} (the assignment nanopub)
1074
     * so the deactivation delete and read-side marking can scope to them without touching
1075
     * directly-published attachments. See {@code doc/design-preset-role-materialization.md}.
1076
     *
1077
     * <p>Activation is resolved by an <b>authorization-scoped latest-wins</b> over the
1078
     * {@code (preset, resource)} pair, NOT {@code npx:invalidates} (§3): the candidate set
1079
     * for the {@code MAX(dct:created)} comparison is restricted to assignments whose
1080
     * publisher is also a validated admin of the target ref, so an unauthorized key's newer
1081
     * assignment cannot shadow an admin's activation (the #113-class anti-hijack rule).
1082
     */
1083
    static String presetAttachmentValidationUpdate(IRI graph, long lastProcessed) {
1084
        // Ref-keyed like attachmentValidationUpdate: the assignment names a bare resource
1085
        // IRI; it is validated per-ref for every Space ref of that IRI whose admin set
1086
        // contains the publisher. The inserted subject is minted per (assignment, ref, role)
1087
        // — one assignment fans out to N roles and N refs. Non-Space targets resolve no
1088
        // ?targetRef and so insert nothing (correct no-op; maintained-resource / individual
1089
        // targets are future work, see design doc §2). TRANSITIONAL-DUAL-EMIT (Phase 4:
1090
        // remove): forSpace kept alongside forSpaceRef so the non-admin tiers can probe the
1091
        // IRI-keyed instantiations and pre-ref read queries keep functioning.
1092
        return """
69✔
1093
                PREFIX npa:  <%1$s>
1094
                PREFIX gen:  <%2$s>
1095
                INSERT { GRAPH <%3$s> {
1096
                  ?ra2 a gen:RoleAssignment ;
1097
                       npa:forSpaceRef ?targetRef ;
1098
                       npa:forSpace    ?resource ;
1099
                       gen:hasRole     ?role ;
1100
                       npa:viaNanopub  ?assignNp ;
1101
                       npa:derivedFromPreset ?assignNp .
1102
                } }
1103
                WHERE {
1104
                  # 1. Anchor: active preset assignments in the extraction graph.
1105
                  GRAPH <%4$s> {
1106
                    ?pa a npa:PresetAssignment ;
1107
                        npa:ofPreset    ?preset ;
1108
                        npa:forResource ?resource ;
1109
                        npa:isActivated true ;
1110
                        npa:pubkeyHash  ?pkh ;
1111
                        npa:viaNanopub  ?assignNp ;
1112
                        <http://purl.org/dc/terms/created> ?created .
1113
                  }
1114
                  # 2. Load-number filter on the assignment nanopub.
1115
                  GRAPH <%7$s> {
1116
                    ?assignNp npa:hasLoadNumber ?ln .
1117
                    FILTER (?ln > %5$d)
1118
                  }
1119
                  # 3. Resolve publisher pkh -> agent via the mirrored trust-approved row.
1120
                  GRAPH <%3$s> {
1121
                    ?acct a npa:AccountState ;
1122
                          npa:agent  ?publisher ;
1123
                          npa:pubkey ?pkh .
1124
                  }
1125
                  # 4. Target must be a Space ref the publisher admins — direct, or the
1126
                  #    canonical ref ?resource is an owl:sameAs alias of (issue #113 parity
1127
                  #    with attachmentValidationUpdate, so a preset assigned against an alias
1128
                  #    IRI still materializes against the canonical ref).
1129
                  {
1130
                    GRAPH <%4$s> { ?targetRef npa:spaceIri ?resource . }
1131
                    GRAPH <%3$s> {
1132
                      ?adminRI a gen:RoleInstantiation ;
1133
                               npa:forSpaceRef ?targetRef ;
1134
                               npa:inverseProperty gen:hasAdmin ;
1135
                               npa:forAgent ?publisher .
1136
                    }
1137
                  }
1138
                  UNION
1139
                  {
1140
                    GRAPH <%3$s> {
1141
                      ?resource npa:sameAsSpace ?targetRef .
1142
                      ?adminRI a gen:RoleInstantiation ;
1143
                               npa:forSpaceRef ?targetRef ;
1144
                               npa:inverseProperty gen:hasAdmin ;
1145
                               npa:forAgent ?publisher .
1146
                    }
1147
                  }
1148
                  # 5. Resolve the assignment's referenced preset IRI (node or kind) to its
1149
                  #    canonical kind, mirroring how Nanodash views key on dct:isVersionOf
1150
                  #    (ViewDisplay.getViewKindIri). Every declaration carries npa:ofPreset for
1151
                  #    both its node IRI and kind, so either reference maps to the same ?kind.
1152
                  GRAPH <%4$s> {
1153
                    ?pdMap a npa:PresetDeclaration ;
1154
                           npa:ofPreset   ?preset ;
1155
                           npa:presetKind ?kind .
1156
                  }
1157
                  # 5a. Roles come from the LATEST live declaration of that kind, restricted to
1158
                  #     Space-targeted presets — so a superseded preset version's roles never leak
1159
                  #     (the per-view-kind latest-wins, ported to materialization).
1160
                  GRAPH <%4$s> {
1161
                    ?pd a npa:PresetDeclaration ;
1162
                        npa:presetKind           ?kind ;
1163
                        npa:presetRole           ?role ;
1164
                        npa:appliesToInstancesOf gen:Space ;
1165
                        npa:viaNanopub           ?pdNp ;
1166
                        <http://purl.org/dc/terms/created> ?pdCreated .
1167
                  }
1168
                  # 5b. Latest-declaration-per-kind: reject if a newer LIVE declaration of the
1169
                  #     same kind exists (tiebreak on subject IRI for equal timestamps).
1170
                  FILTER NOT EXISTS {
1171
                    GRAPH <%4$s> {
1172
                      ?pdNewer a npa:PresetDeclaration ;
1173
                               npa:presetKind ?kind ;
1174
                               npa:viaNanopub ?pdNpNewer ;
1175
                               <http://purl.org/dc/terms/created> ?pdCreatedNewer .
1176
                      FILTER (?pdCreatedNewer > ?pdCreated
1177
                              || (?pdCreatedNewer = ?pdCreated && STR(?pdNewer) > STR(?pd)))
1178
                    }
1179
                    %8$s
1180
                  }
1181
                  # 5c. The chosen declaration must itself be live (not superseded/retracted).
1182
                  %9$s
1183
                  # 6. Mint the per (assignment, ref, role) subject.
1184
                  BIND(IRI(CONCAT(STR(?pa), "__", ENCODE_FOR_URI(STR(?targetRef)),
1185
                                  "__", ENCODE_FOR_URI(STR(?role)))) AS ?ra2)
1186
                  # 7. Authorization-scoped latest-wins (anti-hijack, design doc §3): reject
1187
                  #    if a newer same-(preset,resource) assignment exists whose publisher is
1188
                  #    ALSO a validated admin of ?targetRef. Filtering the shadowing candidate
1189
                  #    to admin-authored rows BEFORE taking the latest is what stops an
1190
                  #    unauthorized key from suppressing an admin's activation. Placed after
1191
                  #    the main vars are bound so the planner defers it (RDF4J quirk).
1192
                  FILTER NOT EXISTS {
1193
                    GRAPH <%4$s> {
1194
                      ?paNewer a npa:PresetAssignment ;
1195
                               npa:ofPreset    ?preset ;
1196
                               npa:forResource ?resource ;
1197
                               npa:pubkeyHash  ?pkhNewer ;
1198
                               <http://purl.org/dc/terms/created> ?createdNewer .
1199
                      FILTER (?createdNewer > ?created
1200
                              || (?createdNewer = ?created && STR(?paNewer) > STR(?pa)))
1201
                    }
1202
                    GRAPH <%3$s> {
1203
                      ?acctNewer a npa:AccountState ;
1204
                                 npa:agent  ?publisherNewer ;
1205
                                 npa:pubkey ?pkhNewer .
1206
                      ?adminRINewer a gen:RoleInstantiation ;
1207
                                    npa:forSpaceRef ?targetRef ;
1208
                                    npa:inverseProperty gen:hasAdmin ;
1209
                                    npa:forAgent ?publisherNewer .
1210
                    }
1211
                  }
1212
                  # 8. Defensive: drop if the assignment nanopub itself was hard-retracted.
1213
                  %6$s
1214
                  # 9. Dedup last — keyed on (ref, role).
1215
                  FILTER NOT EXISTS { GRAPH <%3$s> {
1216
                    ?existing a gen:RoleAssignment ;
1217
                              npa:forSpaceRef ?targetRef ;
1218
                              gen:hasRole ?role .
1219
                  } }
1220
                }
1221
                """.formatted(
3✔
1222
                NPA.NAMESPACE,
1223
                GEN.NAMESPACE,
1224
                graph,
1225
                SpacesVocab.SPACES_GRAPH,
1226
                lastProcessed,
15✔
1227
                invalidationFilter("assignNp"),
27✔
1228
                NPA.GRAPH,
1229
                invalidationFilter("pdNpNewer"),
15✔
1230
                invalidationFilter("pdNp"));
6✔
1231
    }
1232

1233
    /**
1234
     * Stamps a ref-scoped, admin-validated mirror of each {@code npa:PresetAssignment}
1235
     * into the state graph (issue #122). The publisher-agnostic extraction row
1236
     * ({@link SpacesExtractor#extractPresetAssignment}) is keyed only by
1237
     * {@code npa:forResource}, so a consumer listing a space's preset assignments by IRI
1238
     * sees the union across <em>all</em> refs claiming that IRI. This stamp adds
1239
     * {@code npa:forSpaceRef ?targetRef} so the "Assigned presets" listing is no longer
1240
     * merged across refs of the same IRI — the one remaining About-tab listing that still
1241
     * merged across refs (every other ref-scoped listing already has a {@code forSpaceRef}
1242
     * companion).
1243
     *
1244
     * <p>Faithful per-assignment mirror — deliberately <em>not</em> role-gated and
1245
     * <em>not</em> latest-wins-resolved, unlike {@link #presetAttachmentValidationUpdate}:
1246
     * <ul>
1247
     *   <li>No {@code npa:PresetDeclaration}/role join, so a preset that bundles only
1248
     *       <em>views</em> (no roles) is still listed.</li>
1249
     *   <li>Emits active <em>and</em> deactivated rows (carries {@code npa:isActivated})
1250
     *       so the listing can show state; a deactivation is just a newer admin-authored
1251
     *       row, so no {@code dct:created}-driven removal is needed here (contrast §4.4).</li>
1252
     *   <li>Latest-wins is deferred to the consumer query, which ranges only over these
1253
     *       admin-authored rows — so it is authorization-scoped for free (design §3): a
1254
     *       non-admin of the ref can never get a row stamped, so it cannot enter the
1255
     *       latest-wins race.</li>
1256
     * </ul>
1257
     *
1258
     * <p>Display-only leaf: nothing downstream derives from these rows (contrast the
1259
     * preset-derived {@code gen:RoleAssignment}), so the caller must <em>not</em> feed this
1260
     * tier's count into {@code structuralAdds}. The {@code npa:forSpaceRef} predicate also
1261
     * distinguishes a stamped row from the IRI-keyed extraction row (which never carries it),
1262
     * so {@link #presetAssignmentRefInvalidationDelete} can target exactly these rows.
1263
     * Reuses steps 1–4 of {@link #presetAttachmentValidationUpdate}; see
1264
     * doc/design-preset-role-materialization.md §3 and issue #122.
1265
     */
1266
    static String presetAssignmentRefStampUpdate(IRI graph, long lastProcessed) {
1267
        return """
69✔
1268
                PREFIX npa:  <%1$s>
1269
                PREFIX gen:  <%2$s>
1270
                INSERT { GRAPH <%3$s> {
1271
                  ?paRef a npa:PresetAssignment ;
1272
                         npa:ofPreset    ?preset ;
1273
                         npa:forResource ?resource ;
1274
                         npa:forSpaceRef ?targetRef ;
1275
                         npa:isActivated ?activated ;
1276
                         npa:viaNanopub  ?assignNp ;
1277
                         <http://purl.org/dc/terms/created> ?created .
1278
                } }
1279
                WHERE {
1280
                  # 1. Anchor: every assignment row (active or not) in the extraction graph.
1281
                  GRAPH <%4$s> {
1282
                    ?pa a npa:PresetAssignment ;
1283
                        npa:ofPreset    ?preset ;
1284
                        npa:forResource ?resource ;
1285
                        npa:isActivated ?activated ;
1286
                        npa:pubkeyHash  ?pkh ;
1287
                        npa:viaNanopub  ?assignNp ;
1288
                        <http://purl.org/dc/terms/created> ?created .
1289
                  }
1290
                  # 2. Load-number filter on the assignment nanopub (delta window).
1291
                  GRAPH <%6$s> {
1292
                    ?assignNp npa:hasLoadNumber ?ln .
1293
                    FILTER (?ln > %5$d)
1294
                  }
1295
                  # 3. Resolve publisher pkh -> agent via the mirrored trust-approved row.
1296
                  GRAPH <%3$s> {
1297
                    ?acct a npa:AccountState ;
1298
                          npa:agent  ?publisher ;
1299
                          npa:pubkey ?pkh .
1300
                  }
1301
                  # 4. Target must be a Space ref the publisher admins. ?targetRef = that ref;
1302
                  #    fan-out to N refs the publisher admins (per-ref isolation, consistent
1303
                  #    with the role materializer and design-spaceref-isolation.md). Direct,
1304
                  #    or the canonical ref ?resource is an owl:sameAs alias of (issue #113),
1305
                  #    so an assignment naming an alias is still listed under the canonical ref.
1306
                  {
1307
                    GRAPH <%4$s> { ?targetRef npa:spaceIri ?resource . }
1308
                    GRAPH <%3$s> {
1309
                      ?adminRI a gen:RoleInstantiation ;
1310
                               npa:forSpaceRef ?targetRef ;
1311
                               npa:inverseProperty gen:hasAdmin ;
1312
                               npa:forAgent ?publisher .
1313
                    }
1314
                  }
1315
                  UNION
1316
                  {
1317
                    GRAPH <%3$s> {
1318
                      ?resource npa:sameAsSpace ?targetRef .
1319
                      ?adminRI a gen:RoleInstantiation ;
1320
                               npa:forSpaceRef ?targetRef ;
1321
                               npa:inverseProperty gen:hasAdmin ;
1322
                               npa:forAgent ?publisher .
1323
                    }
1324
                  }
1325
                  # 5. Defensive: drop if the assignment nanopub itself was hard-retracted.
1326
                  %7$s
1327
                  # 6. Mint per (assignment, ref); dedup on the bound subject. No latest-wins
1328
                  #    here — a deactivation is just a newer admin-authored row, and the
1329
                  #    consumer resolves latest dct:created per (preset,resource) over these
1330
                  #    admin-authored rows (so the resolution is authorization-scoped).
1331
                  BIND(IRI(CONCAT(STR(?pa), "__", ENCODE_FOR_URI(STR(?targetRef)))) AS ?paRef)
1332
                  FILTER NOT EXISTS { GRAPH <%3$s> { ?paRef a npa:PresetAssignment . } }
1333
                }
1334
                """.formatted(
3✔
1335
                NPA.NAMESPACE,
1336
                GEN.NAMESPACE,
1337
                graph,
1338
                SpacesVocab.SPACES_GRAPH,
1339
                lastProcessed,
27✔
1340
                NPA.GRAPH,
1341
                invalidationFilter("assignNp"));
6✔
1342
    }
1343

1344
    /**
1345
     * Non-admin tier publisher constraints (inserted as a SPARQL sub-pattern).
1346
     * Each constraint owns the AccountState (pkh → agent) lookup so the join
1347
     * variable is bound through a targeted pattern. The observer-self variant
1348
     * binds {@code npa:agent ?agent} directly — no separate {@code ?publisher}
1349
     * variable, no post-join equality filter — which lets the planner anchor
1350
     * the AccountState lookup on the already-bound {@code ?agent} instead of
1351
     * enumerating all approved publishers and filtering at the end.
1352
     */
1353
    static final String PUBLISHER_IS_ADMIN = """
1354
            ?acct a npa:AccountState ;
1355
                  npa:pubkey ?pkh ;
1356
                  npa:agent  ?publisher .
1357
            # Admin of the assignment's ref. The ref already resolves alias →
1358
            # canonical (the attachment tier bound ?spaceRef through the owl:sameAs
1359
            # alias edge for aliased IRIs, issue #113), so no alias arm is needed here.
1360
            ?adminRI a gen:RoleInstantiation ;
1361
                     npa:forSpaceRef ?spaceRef ;
1362
                     npa:inverseProperty gen:hasAdmin ;
1363
                     npa:forAgent ?publisher .
1364
            """;
1365

1366
    /** Observer self-evidence: the assignee's own pubkey signed the instantiation. */
1367
    static final String PUBLISHER_IS_SELF = """
1368
            ?acct a npa:AccountState ;
1369
                  npa:pubkey ?pkh ;
1370
                  npa:agent  ?agent .
1371
            """;
1372

1373
    /**
1374
     * Maintainer / Member / Observer tier INSERT. Same shape: find an instantiation
1375
     * whose predicate matches a RoleDeclaration of the given tier attached to the
1376
     * target space, and whose publisher passes the tier-specific constraint.
1377
     */
1378
    static String nonAdminTierUpdate(IRI graph, long lastProcessed,
1379
                                     IRI tierClass, String publisherConstraint) {
1380
        // Order tuned for RDF4J's evaluator (which executes BGPs roughly in order).
1381
        // The crucial choice is the *anchor*: instantiation-first plans send the
1382
        // planner exploring the full ~thousands of candidate RIs and only filter
1383
        // by tier at the very end. Attachment-first anchors on the small set of
1384
        // gen:RoleAssignment rows already validated in this space-state graph
1385
        // (~hundreds, often zero) and walks outward by bound (?role, ?space).
1386
        //
1387
        //   1. Anchor on RoleAssignments in this space-state graph (small).
1388
        //   1a. Resolve the IRIs that denote the assignment's ref — its canonical
1389
        //      IRI plus any validated owl:sameAs aliases — so an instantiation that
1390
        //      names an alias of the space still matches (issue #113). Bound here so
1391
        //      the instantiation lookup below stays anchored by ?instSpace.
1392
        //   2. Match the tier-pinned RoleDeclaration by ?role.
1393
        //   3. Pair role-decl direction to instantiation direction in one UNION
1394
        //      so only (reg, reg)/(inv, inv) combos are explored.
1395
        //   4. Targeted instantiation lookup — (?instSpace, ?pred) are bound.
1396
        //   5. Publisher constraint (incl. AccountState resolution).
1397
        //   6. Load-number filter on bound ?np.
1398
        //   7. Dedup at the end.
1399
        return """
69✔
1400
                PREFIX npa:  <%1$s>
1401
                PREFIX gen:  <%2$s>
1402
                INSERT { GRAPH <%3$s> {
1403
                  ?ri2 a gen:RoleInstantiation ;
1404
                       npa:forSpaceRef ?spaceRef ;
1405
                       # TRANSITIONAL-DUAL-EMIT (Phase 4: remove): forSpace alongside
1406
                       # forSpaceRef so pre-ref read queries (e.g. get-space-members) keep
1407
                       # functioning on a mixed-version fleet; downstream tiers key on the ref.
1408
                       npa:forSpace ?space ;
1409
                       npa:forAgent ?agent ;
1410
                       ?dirPred ?pred ;
1411
                       # Persist the tier and role IRI that are already bound at this point —
1412
                       # the loop's tierClass arg (%7$s) and the anchoring attachment's ?role
1413
                       # (step 1) — so ref-scoped consumers key on identity rather than
1414
                       # re-deriving the tier from the bare predicate against GLOBAL
1415
                       # RoleDeclarations. The bare-predicate re-derivation bleeds tiers
1416
                       # across spaces that declare the same predicate at different tiers
1417
                       # (issue #125): consumers should match ?ri2 npa:hasRoleType <tier>
1418
                       # / gen:hasRole ?role, exactly as the *-roles-ref queries do.
1419
                       npa:hasRoleType <%7$s> ;
1420
                       gen:hasRole ?role ;
1421
                       npa:viaNanopub ?np .
1422
                } }
1423
                WHERE {
1424
                  # 1. Anchor: validated attachments in this space-state graph (ref-keyed).
1425
                  GRAPH <%3$s> {
1426
                    ?ra a gen:RoleAssignment ;
1427
                        gen:hasRole     ?role ;
1428
                        npa:forSpaceRef ?spaceRef ;
1429
                        npa:forSpace    ?space .
1430
                  }
1431
                  # 1a. The IRIs that denote this ref: its canonical IRI, plus any validated
1432
                  #     owl:sameAs aliases of it (issue #113) — so an instantiation naming an
1433
                  #     alias of the space still materializes here. Bound BEFORE the
1434
                  #     instantiation BGP so that lookup stays anchored by ?instSpace (planner
1435
                  #     note above); ?spaceRef is already bound, so each arm is a targeted
1436
                  #     lookup yielding a tiny IRI set. The alias arm only follows admin-
1437
                  #     validated npa:sameAsSpace edges, so it grants no authority the admin
1438
                  #     tier would not (anti-hijack is enforced upstream, not relaxed here).
1439
                  {
1440
                    GRAPH <%4$s> { ?spaceRef npa:spaceIri ?instSpace . }
1441
                  }
1442
                  UNION
1443
                  {
1444
                    GRAPH <%3$s> { ?instSpace npa:sameAsSpace ?spaceRef . }
1445
                  }
1446
                  # 2. Tier-pinned RoleDeclaration (?role bound from the attachment). Its
1447
                  #    nanopub's invalidation is intentionally NOT consulted (see step 7), so
1448
                  #    no ?rdNp binding is needed.
1449
                  GRAPH <%4$s> {
1450
                    ?rd a npa:RoleDeclaration ;
1451
                        npa:hasRoleType <%7$s> ;
1452
                        npa:role        ?role .
1453
                    # 3. Pair role-decl direction to the instantiation in one UNION so only
1454
                    #    matching combos are explored, binding (?instSpace, ?agent) per arm.
1455
                    #    ?dirPred carries the resolved direction so the materialized row
1456
                    #    records the role property (read by get-space-members and
1457
                    #    publisherIsTieredRole) — identical shape whichever arm matched.
1458
                    #
1459
                    #    The first two arms handle instantiations the extractor already
1460
                    #    classified (npa:regularProperty / npa:inverseProperty). The last two
1461
                    #    resolve a custom predicate the extractor left neutral (npa:rolePredicate
1462
                    #    with raw npa:bindingSubject / npa:bindingObject): the role declaration
1463
                    #    supplies the direction, which fixes which raw endpoint is the space vs
1464
                    #    the agent. INVERSE = <space> pred <agent>; REGULAR = <agent> pred <space>.
1465
                    {
1466
                      ?rd gen:hasRegularProperty ?pred .
1467
                      ?ri npa:regularProperty ?pred ;
1468
                          npa:forSpace ?instSpace ;
1469
                          npa:forAgent ?agent .
1470
                      BIND(npa:regularProperty AS ?dirPred)
1471
                    }
1472
                    UNION
1473
                    {
1474
                      ?rd gen:hasInverseProperty ?pred .
1475
                      ?ri npa:inverseProperty ?pred ;
1476
                          npa:forSpace ?instSpace ;
1477
                          npa:forAgent ?agent .
1478
                      BIND(npa:inverseProperty AS ?dirPred)
1479
                    }
1480
                    UNION
1481
                    {
1482
                      ?rd gen:hasInverseProperty ?pred .
1483
                      ?ri npa:rolePredicate   ?pred ;
1484
                          npa:bindingSubject  ?instSpace ;
1485
                          npa:bindingObject   ?agent .
1486
                      BIND(npa:inverseProperty AS ?dirPred)
1487
                    }
1488
                    UNION
1489
                    {
1490
                      ?rd gen:hasRegularProperty ?pred .
1491
                      ?ri npa:rolePredicate   ?pred ;
1492
                          npa:bindingObject   ?instSpace ;
1493
                          npa:bindingSubject  ?agent .
1494
                      BIND(npa:regularProperty AS ?dirPred)
1495
                    }
1496
                    # 4. Common instantiation columns. ?instSpace was resolved to this ref
1497
                    #    above (canonical or owl:sameAs alias), so an alias-named instantiation
1498
                    #    joins the same ?spaceRef as a canonical one. The materialized row still
1499
                    #    carries npa:forSpace ?space (the attachment's IRI) for the transitional
1500
                    #    dual-emit, so pre-ref reads see the member under the space's primary IRI.
1501
                    ?ri a gen:RoleInstantiation ;
1502
                        npa:pubkeyHash ?pkh ;
1503
                        npa:viaNanopub ?np .
1504
                  }
1505
                  # 5. Publisher constraint (incl. AccountState resolution).
1506
                  GRAPH <%3$s> {
1507
                    %8$s
1508
                  }
1509
                  # 5a. Mint the per-ref state subject: (?ri, ?spaceRef) → ?ri2.
1510
                  BIND(IRI(CONCAT(STR(?ri), "__", ENCODE_FOR_URI(STR(?spaceRef)))) AS ?ri2)
1511
                  # 6. Load-number filter on bound ?np.
1512
                  GRAPH <%9$s> {
1513
                    ?np npa:hasLoadNumber ?ln .
1514
                    FILTER (?ln > %5$d)
1515
                  }
1516
                  # 7. Instantiation invalidation filter — outside the GRAPH block so the
1517
                  #    planner defers it until ?np is bound. Role-DECLARATION invalidation is
1518
                  #    deliberately NOT consulted: the tier already anchors on the admin-
1519
                  #    validated attachment (?ra), which is removed when an admin retracts it,
1520
                  #    so admin control is fully enforced there. Letting the declaration's
1521
                  #    author (usually not the space admin) supersede/retract their declaration
1522
                  #    strip a space's members is the same cross-author-strip anti-pattern as
1523
                  #    issue #112. Role IRIs are version-pinned, so the attached definition is
1524
                  #    immutable regardless of the declaration nanopub's later lifecycle.
1525
                  %6$s
1526
                  # 8. Dedup last — keyed on (ref, agent, nanopub).
1527
                  FILTER NOT EXISTS { GRAPH <%3$s> {
1528
                    ?existing a gen:RoleInstantiation ;
1529
                              npa:forSpaceRef ?spaceRef ;
1530
                              npa:forAgent ?agent ;
1531
                              npa:viaNanopub ?np .
1532
                  } }
1533
                }
1534
                """.formatted(
3✔
1535
                NPA.NAMESPACE,
1536
                GEN.NAMESPACE,
1537
                graph,
1538
                SpacesVocab.SPACES_GRAPH,
1539
                lastProcessed,
15✔
1540
                invalidationFilter("np"),
42✔
1541
                tierClass,
1542
                publisherConstraint,
1543
                NPA.GRAPH);
1544
    }
1545

1546
    /**
1547
     * Sub-space admit pass. Copies validated {@code npa:SubSpaceDeclaration}
1548
     * extraction rows into the space-state graph (preserving the {@code npasub:}
1549
     * subject) and emits convenience {@code <child> npa:isSubSpaceOf <parent>} and
1550
     * {@code <parent> npa:hasSubSpace <child>} direct triples. Two satisfaction
1551
     * modes joined by UNION:
1552
     * <ul>
1553
     *   <li>Mode A — the declaration's publisher is a validated admin of both the
1554
     *       child and the parent space.</li>
1555
     *   <li>Mode B — a different non-invalidated declaration for the same
1556
     *       {@code (child, parent)} pair exists, and the two publishers between
1557
     *       them cover both admin sides (i.e. one of them is admin of the child,
1558
     *       one of them is admin of the parent — possibly the same one twice if
1559
     *       both happen to be admin of both).</li>
1560
     * </ul>
1561
     *
1562
     * <p>Mode-B late-arrival: when only the partner declaration is new in this
1563
     * cycle (the primary is older than {@code lastProcessed}), the load-number
1564
     * filter on {@code ?np} excludes the candidate. The late-arrival sweep
1565
     * ({@link #runDownstreamWithoutLoadFilter}) re-runs this pass without the
1566
     * load filter and catches it.
1567
     */
1568
    static String subSpaceAdmitUpdate(IRI graph, long lastProcessed) {
1569
        return """
69✔
1570
                PREFIX npa: <%1$s>
1571
                PREFIX gen: <%2$s>
1572
                INSERT { GRAPH <%3$s> {
1573
                  ?d a npa:SubSpaceDeclaration ;
1574
                     npa:childSpace  ?child ;
1575
                     npa:parentSpace ?parent ;
1576
                     npa:viaNanopub  ?np .
1577
                  ?childRef  npa:isSubSpaceOf ?parentRef .
1578
                  ?parentRef npa:hasSubSpace  ?childRef  .
1579
                  # Reified per-(nanopub, ref-pair) provenance link (issue #125 finding #5):
1580
                  # carries npa:viaNanopub plus both the ref and IRI endpoints, so the
1581
                  # invalidation cleanup can drop the convenience edges below once no
1582
                  # surviving link backs them — instead of leaving them sticky until the
1583
                  # next periodic full rebuild.
1584
                  ?ssLink a npa:SubSpaceLink ;
1585
                          npa:viaNanopub     ?np ;
1586
                          npa:childSpaceRef  ?childRef ;
1587
                          npa:parentSpaceRef ?parentRef ;
1588
                          npa:childSpace     ?child ;
1589
                          npa:parentSpace    ?parent .
1590
                  # TRANSITIONAL-DUAL-EMIT (Phase 1.5; remove in Phase 4): IRI-valued
1591
                  # sub-space edge alongside the ref-to-ref one, so pre-ref published
1592
                  # queries that key on the bare Space IRI keep binding on a mixed-version
1593
                  # fleet. See doc/report-2026-06-12-mixed-fleet-spaceref-breakage.md.
1594
                  ?child  npa:isSubSpaceOf ?parent .
1595
                  ?parent npa:hasSubSpace  ?child  .
1596
                } }
1597
                WHERE {
1598
                  # 1. Anchor: candidate declarations from the extraction graph.
1599
                  GRAPH <%4$s> {
1600
                    ?d a npa:SubSpaceDeclaration ;
1601
                       npa:childSpace  ?child ;
1602
                       npa:parentSpace ?parent ;
1603
                       npa:pubkeyHash  ?pkh ;
1604
                       npa:viaNanopub  ?np .
1605
                  }
1606
                  # 2. Mirror: resolve ?pkh → ?publisher via the trust-approved row.
1607
                  GRAPH <%3$s> {
1608
                    ?acct a npa:AccountState ;
1609
                          npa:pubkey ?pkh ;
1610
                          npa:agent  ?publisher .
1611
                  }
1612
                  # 3. Authority gate, ref-keyed. The edge is emitted ref-to-ref between
1613
                  #    the child ref and parent ref the authorizing admin governs; the
1614
                  #    admin rows' dual-emitted npa:forSpace binds the refs to the child /
1615
                  #    parent IRIs (cross-product when an IRI has several governed refs).
1616
                  {
1617
                    # Mode A — publisher is admin of BOTH a child ref and a parent ref.
1618
                    GRAPH <%3$s> {
1619
                      ?riC a gen:RoleInstantiation ;
1620
                           npa:inverseProperty gen:hasAdmin ;
1621
                           npa:forSpace ?child ;
1622
                           npa:forSpaceRef ?childRef ;
1623
                           npa:forAgent ?publisher .
1624
                      ?riP a gen:RoleInstantiation ;
1625
                           npa:inverseProperty gen:hasAdmin ;
1626
                           npa:forSpace ?parent ;
1627
                           npa:forSpaceRef ?parentRef ;
1628
                           npa:forAgent ?publisher .
1629
                    }
1630
                  }
1631
                  UNION
1632
                  {
1633
                    # Mode B — co-declaration whose publisher covers the side this
1634
                    # one's publisher doesn't. Between {publisher, publisher2},
1635
                    # both admin sides must be covered.
1636
                    GRAPH <%4$s> {
1637
                      ?d2 a npa:SubSpaceDeclaration ;
1638
                          npa:childSpace  ?child ;
1639
                          npa:parentSpace ?parent ;
1640
                          npa:pubkeyHash  ?pkh2 ;
1641
                          npa:viaNanopub  ?np2 .
1642
                      FILTER (?np2 != ?np)
1643
                    }
1644
                    %8$s
1645
                    GRAPH <%3$s> {
1646
                      ?acct2 a npa:AccountState ;
1647
                             npa:pubkey ?pkh2 ;
1648
                             npa:agent  ?publisher2 .
1649
                      ?riA a gen:RoleInstantiation ;
1650
                           npa:inverseProperty gen:hasAdmin ;
1651
                           npa:forSpace ?child ;
1652
                           npa:forSpaceRef ?childRef .
1653
                      { ?riA npa:forAgent ?publisher } UNION { ?riA npa:forAgent ?publisher2 }
1654
                      ?riB a gen:RoleInstantiation ;
1655
                           npa:inverseProperty gen:hasAdmin ;
1656
                           npa:forSpace ?parent ;
1657
                           npa:forSpaceRef ?parentRef .
1658
                      { ?riB npa:forAgent ?publisher } UNION { ?riB npa:forAgent ?publisher2 }
1659
                    }
1660
                  }
1661
                  # 4. Invalidation filter on the primary declaration's nanopub.
1662
                  %6$s
1663
                  # 5. Load-number filter on bound ?np.
1664
                  GRAPH <%7$s> {
1665
                    ?np npa:hasLoadNumber ?ln .
1666
                    FILTER (?ln > %5$d)
1667
                  }
1668
                  # 6. Mint the per-(nanopub, ref-pair) provenance link IRI and dedup on it
1669
                  #    (not on the bare edge). Keyed on ?np so every backing declaration of
1670
                  #    the same ref-pair records its own removable link; the convenience
1671
                  #    edges above are re-asserted idempotently.
1672
                  BIND(IRI(CONCAT("http://purl.org/nanopub/admin/spacelink/subspace/",
1673
                                  MD5(CONCAT(STR(?np), "|", STR(?childRef), "|", STR(?parentRef))))) AS ?ssLink)
1674
                  FILTER NOT EXISTS { GRAPH <%3$s> {
1675
                    ?ssLink a npa:SubSpaceLink .
1676
                  } }
1677
                }
1678
                """.formatted(
3✔
1679
                NPA.NAMESPACE,
1680
                GEN.NAMESPACE,
1681
                graph,
1682
                SpacesVocab.SPACES_GRAPH,
1683
                lastProcessed,
15✔
1684
                invalidationFilter("np"),
27✔
1685
                NPA.GRAPH,
1686
                invalidationFilter("np2"));
6✔
1687
    }
1688

1689
    /**
1690
     * Maintained-resource admit pass. Copies validated
1691
     * {@code npa:MaintainedResourceDeclaration} extraction rows into the space-state
1692
     * graph (preserving the {@code npamrd:} subject) and emits convenience
1693
     * {@code <r> npa:isMaintainedBy <s>} and {@code <s> npa:hasMaintainedResource <r>}
1694
     * direct triples. Single satisfaction mode:
1695
     * <ul>
1696
     *   <li>Mode A — the declaration's publisher is a validated admin of the
1697
     *       maintaining space.</li>
1698
     * </ul>
1699
     *
1700
     * <p>No Mode B because only one space is involved; the two-sides-must-be-covered
1701
     * concern that drives sub-space Mode B doesn't apply. Late-arrival is still
1702
     * possible (declaration lands before the publisher's admin grant becomes valid):
1703
     * the load-number filter on {@code ?np} excludes the candidate, and the
1704
     * late-arrival sweep ({@link #runDownstreamWithoutLoadFilter}) re-runs this pass
1705
     * without the load filter and catches it.
1706
     */
1707
    static String maintainedResourceAdmitUpdate(IRI graph, long lastProcessed) {
1708
        return """
69✔
1709
                PREFIX npa: <%1$s>
1710
                PREFIX gen: <%2$s>
1711
                INSERT { GRAPH <%3$s> {
1712
                  ?d a npa:MaintainedResourceDeclaration ;
1713
                     npa:resourceIri     ?r ;
1714
                     npa:maintainerSpace ?s ;
1715
                     npa:viaNanopub      ?np .
1716
                  ?r npa:isMaintainedBy        ?sRef .
1717
                  ?sRef npa:hasMaintainedResource ?r .
1718
                  # Reified per-(nanopub, resource→ref) provenance link (issue #125 finding
1719
                  # #5): lets the invalidation cleanup drop the convenience edges below once
1720
                  # no surviving link backs them, instead of leaving them sticky.
1721
                  ?mrLink a npa:MaintainedResourceLink ;
1722
                          npa:viaNanopub         ?np ;
1723
                          npa:resourceIri        ?r ;
1724
                          npa:maintainerSpaceRef ?sRef ;
1725
                          npa:maintainerSpace    ?s .
1726
                  # TRANSITIONAL-DUAL-EMIT (Phase 1.5; remove in Phase 4): IRI-valued
1727
                  # maintained-resource edge alongside the resource→ref one, so pre-ref
1728
                  # published queries (e.g. get-view-displays' maintained hop) keep binding
1729
                  # on a mixed-version fleet. This is the edge whose absence broke 1.15.0 —
1730
                  # see doc/report-2026-06-12-mixed-fleet-spaceref-breakage.md.
1731
                  ?r npa:isMaintainedBy        ?s .
1732
                  ?s npa:hasMaintainedResource ?r .
1733
                } }
1734
                WHERE {
1735
                  # 1. Anchor: candidate declarations from the extraction graph.
1736
                  GRAPH <%4$s> {
1737
                    ?d a npa:MaintainedResourceDeclaration ;
1738
                       npa:resourceIri     ?r ;
1739
                       npa:maintainerSpace ?s ;
1740
                       npa:pubkeyHash      ?pkh ;
1741
                       npa:viaNanopub      ?np .
1742
                  }
1743
                  # 2. Mirror: resolve ?pkh → ?publisher via the trust-approved row.
1744
                  GRAPH <%3$s> {
1745
                    ?acct a npa:AccountState ;
1746
                          npa:pubkey ?pkh ;
1747
                          npa:agent  ?publisher .
1748
                    # 3. Authority gate (Mode A only): publisher is admin of a ref of the
1749
                    #    maintaining space. ?sRef = that ref (resource → ref edge).
1750
                    ?riA a gen:RoleInstantiation ;
1751
                         npa:inverseProperty gen:hasAdmin ;
1752
                         npa:forSpace ?s ;
1753
                         npa:forSpaceRef ?sRef ;
1754
                         npa:forAgent ?publisher .
1755
                  }
1756
                  # 4. Invalidation filter on the declaration's nanopub.
1757
                  %6$s
1758
                  # 5. Load-number filter on bound ?np.
1759
                  GRAPH <%7$s> {
1760
                    ?np npa:hasLoadNumber ?ln .
1761
                    FILTER (?ln > %5$d)
1762
                  }
1763
                  # 6. Mint the per-(nanopub, resource→ref) provenance link IRI and dedup on
1764
                  #    it (not on the bare edge), so every backing declaration records its own
1765
                  #    removable link; the convenience edges above are re-asserted idempotently.
1766
                  BIND(IRI(CONCAT("http://purl.org/nanopub/admin/spacelink/maintained/",
1767
                                  MD5(CONCAT(STR(?np), "|", STR(?r), "|", STR(?sRef))))) AS ?mrLink)
1768
                  FILTER NOT EXISTS { GRAPH <%3$s> {
1769
                    ?mrLink a npa:MaintainedResourceLink .
1770
                  } }
1771
                }
1772
                """.formatted(
3✔
1773
                NPA.NAMESPACE,
1774
                GEN.NAMESPACE,
1775
                graph,
1776
                SpacesVocab.SPACES_GRAPH,
1777
                lastProcessed,
15✔
1778
                invalidationFilter("np"),
18✔
1779
                NPA.GRAPH);
1780
    }
1781

1782
    /**
1783
     * Space-alias admit pass (issue #113). Copies validated
1784
     * {@code npa:SpaceAliasDeclaration} extraction rows into the space-state graph
1785
     * (preserving the {@code npaalias:} subject) and emits the directional
1786
     * {@code <alias> npa:sameAsSpace <canonical>} edge consumed by the alias-aware
1787
     * admin-authority lookups in {@link #attachmentValidationUpdate},
1788
     * {@link #PUBLISHER_IS_ADMIN}, and {@link #publisherIsTieredRole}.
1789
     *
1790
     * <p>Two gates, both read against the (already-settled) admin closure in the
1791
     * space-state graph:
1792
     * <ul>
1793
     *   <li><b>Authority</b> — the declaration's publisher (resolved via the mirrored
1794
     *       trust-approved {@code AccountState}) is a validated admin of the
1795
     *       <em>canonical</em> space. The alias is declared inside the canonical
1796
     *       space's own {@code gen:Space} nanopub, so this is the same evidence rule
1797
     *       as a {@code gen:hasRole} attachment.</li>
1798
     *   <li><b>Anti-hijack</b> — the alias must not be an independently-governed live
1799
     *       space: it must have no admin who is not also an admin of the canonical
1800
     *       space ({@code admins(alias) ⊆ admins(canonical)}). The common rename case
1801
     *       (the alias's own definition was superseded, so it has no live admin
1802
     *       closure) passes trivially; an attacker publishing
1803
     *       {@code <evil> owl:sameAs <activeSpace>} is rejected because the active
1804
     *       space has admins not in evil's set.</li>
1805
     * </ul>
1806
     *
1807
     * <p>Late-arrival: when the canonical admin grant only becomes valid in the same
1808
     * cycle as the declaration, the load-number filter on {@code ?np} excludes the
1809
     * candidate; the late-arrival sweep ({@link #runDownstreamWithoutLoadFilter})
1810
     * re-runs this pass without the load filter and catches it.
1811
     */
1812
    static String aliasAdmitUpdate(IRI graph, long lastProcessed) {
1813
        // Ref-keyed (see doc/design-spaceref-isolation.md). The declaration names bare
1814
        // canonical/alias IRIs. It is admitted per canonical *ref* whose admin set
1815
        // contains the publisher; the emitted edge is ref-valued on the canonical side
1816
        // (<alias> npa:sameAsSpace <canonicalRef>), which is what the alias-aware admin
1817
        // lookups in the attachment tier consume. Anti-hijack compares the alias IRI's
1818
        // admins against that specific canonical ref's admins — strictly tighter than the
1819
        // old bare-IRI form.
1820
        return """
69✔
1821
                PREFIX npa: <%1$s>
1822
                PREFIX gen: <%2$s>
1823
                INSERT { GRAPH <%3$s> {
1824
                  ?d a npa:SpaceAliasDeclaration ;
1825
                     npa:canonicalSpace ?canonical ;
1826
                     npa:aliasSpace     ?alias ;
1827
                     npa:viaNanopub     ?np .
1828
                  ?alias npa:sameAsSpace ?canonRef .
1829
                  # Reified per-(nanopub, alias→canonical ref) provenance link (issue #125
1830
                  # finding #5). The alias edge feeds the admin-authority closure, so this
1831
                  # is the load-bearing case: the cleanup can now drop the edge when its
1832
                  # declaration is invalidated, rather than letting admin authority outlive
1833
                  # a retraction until the next periodic full rebuild.
1834
                  ?alLink a npa:SpaceAliasLink ;
1835
                          npa:viaNanopub        ?np ;
1836
                          npa:aliasSpace        ?alias ;
1837
                          npa:canonicalSpaceRef ?canonRef ;
1838
                          npa:canonicalSpace    ?canonical .
1839
                  # TRANSITIONAL-DUAL-EMIT (Phase 1.5; remove in Phase 4): IRI-valued
1840
                  # alias edge alongside the ref-valued one, so pre-ref published queries
1841
                  # that resolve owl:sameAs by bare canonical IRI keep binding on a
1842
                  # mixed-version fleet. Internal alias-aware lookups (attachment tier)
1843
                  # join through npa:forSpaceRef, which is ref-valued, so this IRI-valued
1844
                  # object never satisfies them — it is inert internally, read-only for
1845
                  # legacy consumers. See doc/report-2026-06-12-mixed-fleet-spaceref-breakage.md.
1846
                  ?alias npa:sameAsSpace ?canonical .
1847
                } }
1848
                WHERE {
1849
                  # 1. Anchor: candidate alias declarations from the extraction graph.
1850
                  GRAPH <%4$s> {
1851
                    ?d a npa:SpaceAliasDeclaration ;
1852
                       npa:canonicalSpace ?canonical ;
1853
                       npa:aliasSpace     ?alias ;
1854
                       npa:pubkeyHash     ?pkh ;
1855
                       npa:viaNanopub     ?np .
1856
                  }
1857
                  # 2. Authority gate per canonical ref: ?canonRef is a ref of ?canonical
1858
                  #    whose admin set contains the declaration's publisher.
1859
                  GRAPH <%4$s> { ?canonRef npa:spaceIri ?canonical . }
1860
                  GRAPH <%3$s> {
1861
                    ?acct a npa:AccountState ;
1862
                          npa:pubkey ?pkh ;
1863
                          npa:agent  ?publisher .
1864
                    ?adminRI a gen:RoleInstantiation ;
1865
                             npa:inverseProperty gen:hasAdmin ;
1866
                             npa:forSpaceRef ?canonRef ;
1867
                             npa:forAgent ?publisher .
1868
                  }
1869
                  # 3. Anti-hijack: the alias IRI must have no admin who is not also an
1870
                  #    admin of this canonical ref (admins(alias) ⊆ admins(canonRef)).
1871
                  FILTER NOT EXISTS {
1872
                    GRAPH <%3$s> {
1873
                      ?aliasAdmin a gen:RoleInstantiation ;
1874
                                  npa:inverseProperty gen:hasAdmin ;
1875
                                  npa:forSpace ?alias ;
1876
                                  npa:forAgent ?otherAgent .
1877
                    }
1878
                    FILTER NOT EXISTS {
1879
                      GRAPH <%3$s> {
1880
                        ?canonAdmin a gen:RoleInstantiation ;
1881
                                    npa:inverseProperty gen:hasAdmin ;
1882
                                    npa:forSpaceRef ?canonRef ;
1883
                                    npa:forAgent ?otherAgent .
1884
                      }
1885
                    }
1886
                  }
1887
                  # 4. Invalidation filter on the declaration's nanopub.
1888
                  %6$s
1889
                  # 5. Load-number filter on bound ?np.
1890
                  GRAPH <%7$s> {
1891
                    ?np npa:hasLoadNumber ?ln .
1892
                    FILTER (?ln > %5$d)
1893
                  }
1894
                  # 6. Mint the per-(nanopub, alias→canonical ref) provenance link IRI and
1895
                  #    dedup on it (not on the bare edge), so every backing declaration records
1896
                  #    its own removable link; the convenience edges above are re-asserted
1897
                  #    idempotently.
1898
                  BIND(IRI(CONCAT("http://purl.org/nanopub/admin/spacelink/alias/",
1899
                                  MD5(CONCAT(STR(?np), "|", STR(?alias), "|", STR(?canonRef))))) AS ?alLink)
1900
                  FILTER NOT EXISTS { GRAPH <%3$s> {
1901
                    ?alLink a npa:SpaceAliasLink .
1902
                  } }
1903
                }
1904
                """.formatted(
3✔
1905
                NPA.NAMESPACE,
1906
                GEN.NAMESPACE,
1907
                graph,
1908
                SpacesVocab.SPACES_GRAPH,
1909
                lastProcessed,
15✔
1910
                invalidationFilter("np"),
18✔
1911
                NPA.GRAPH);
1912
    }
1913

1914
    /**
1915
     * URL-prefix sub-space fallback admit pass. For every pair of {@code SpaceRef}
1916
     * aggregates where the child's {@code npa:hasIdPrefix} matches the parent's
1917
     * {@code npa:spaceIri}, emits convenience {@code <child> npa:isSubSpaceOf <parent>}
1918
     * and {@code <parent> npa:hasSubSpace <child>} direct triples plus a reified
1919
     * {@code npa:DerivedSubSpaceLink} tag carrying {@code npa:derivationKind
1920
     * npa:byUrlPrefix} so consumers can hide derived edges.
1921
     *
1922
     * <p>Per-child suppression: any validated {@code npa:SubSpaceDeclaration} on the
1923
     * child in {@code npass:<…>} suppresses every fallback edge for that child.
1924
     * Suppression checks the validated set (not raw extraction-graph declarations)
1925
     * so an unapproved or in-flight Mode B declaration doesn't silently hide both
1926
     * the URL-prefix fallback and the (still-invalid) explicit relation.
1927
     *
1928
     * <p>Run order: must run after {@link #subSpaceAdmitUpdate} commits in the
1929
     * same cycle so the suppression check sees this cycle's freshly-validated
1930
     * declarations.
1931
     *
1932
     * <p>No load-number filter: the fallback depends on which Spaces exist (parent
1933
     * + child {@code SpaceRef}s), not on which were just added. Always full-scan;
1934
     * the dedup {@code FILTER NOT EXISTS} on the tag IRI prevents re-insertion.
1935
     *
1936
     * <p>No invalidation handling: derived edges have no source nanopub. Two
1937
     * staleness modes: (a) child later gets first validated declaration → old
1938
     * derived edges stay sticky until the next periodic rebuild (same policy as
1939
     * admin-RI invalidation); (b) child loses last validated declaration → the
1940
     * regular fallback pass on the next cycle re-engages, adds derived edges
1941
     * incrementally, no rebuild needed.
1942
     */
1943
    static String subSpacePrefixFallbackUpdate(IRI graph) {
1944
        return """
48✔
1945
                PREFIX npa: <%1$s>
1946
                INSERT { GRAPH <%2$s> {
1947
                  ?childRef  npa:isSubSpaceOf ?parentRef .
1948
                  ?parentRef npa:hasSubSpace  ?childRef  .
1949
                  # TRANSITIONAL-DUAL-EMIT (Phase 1.5; remove in Phase 4): IRI-valued
1950
                  # derived sub-space edge alongside the ref-to-ref one, mirroring the
1951
                  # explicit sub-space pass, so pre-ref published queries keep binding on a
1952
                  # mixed-version fleet. See doc/report-2026-06-12-mixed-fleet-spaceref-breakage.md.
1953
                  ?child  npa:isSubSpaceOf ?parent .
1954
                  ?parent npa:hasSubSpace  ?child  .
1955
                  ?tagIri a npa:DerivedSubSpaceLink ;
1956
                          npa:childSpace     ?child ;
1957
                          npa:parentSpace    ?parent ;
1958
                          # Ref endpoints too (issue #125 finding #5), so the sub-space
1959
                          # orphan-sweep recognizes a prefix-derived ref edge as backed and
1960
                          # never deletes it. Derived links have no source nanopub, so they
1961
                          # are never invalidation-deleted; the fallback self-heals each cycle.
1962
                          npa:childSpaceRef  ?childRef ;
1963
                          npa:parentSpaceRef ?parentRef ;
1964
                          npa:derivationKind npa:byUrlPrefix .
1965
                } }
1966
                WHERE {
1967
                  # 1. Anchor: child SpaceRef → its path-prefixes (extracted at load
1968
                  #    time from the Space IRI; see SpacesExtractor.enumerateIdPrefixes).
1969
                  GRAPH <%3$s> {
1970
                    ?childRef  npa:spaceIri    ?child ;
1971
                               npa:hasIdPrefix ?parent .
1972
                    # 2. Parent SpaceRef must exist for the same IRI as the prefix.
1973
                    ?parentRef npa:spaceIri    ?parent .
1974
                  }
1975
                  # 3. Suppress fallback for any child that has a validated declaration
1976
                  #    in this state graph. Per-child IRI, all-or-nothing.
1977
                  FILTER NOT EXISTS {
1978
                    GRAPH <%2$s> {
1979
                      ?d a npa:SubSpaceDeclaration ;
1980
                         npa:childSpace ?child .
1981
                    }
1982
                  }
1983
                  # 4. Mint a deterministic tag IRI per (child ref, parent ref) — the edge
1984
                  #    is emitted ref-to-ref, so the tag and dedup are per ref-pair.
1985
                  BIND(IRI(CONCAT("http://purl.org/nanopub/admin/derivedlink/",
1986
                                  MD5(CONCAT(STR(?childRef), "|", STR(?parentRef))))) AS ?tagIri)
1987
                  # 5. Dedup: don't re-insert if this tag is already present.
1988
                  FILTER NOT EXISTS {
1989
                    GRAPH <%2$s> {
1990
                      ?tagIri a npa:DerivedSubSpaceLink .
1991
                    }
1992
                  }
1993
                }
1994
                """.formatted(
3✔
1995
                NPA.NAMESPACE,
1996
                graph,
1997
                SpacesVocab.SPACES_GRAPH);
1998
    }
1999

2000
    // ---------------- Invalidation templates (incremental cycle) ----------------
2001

2002
    /**
2003
     * WHERE clause shared by the admin-RI invalidation ASK precheck and the
2004
     * matching DELETE. Identifies admin-tier {@code gen:RoleInstantiation} rows
2005
     * in the space-state graph whose {@code npa:viaNanopub} is the target of an
2006
     * {@code npx:invalidates} triple in {@code npa:graph} whose subject nanopub
2007
     * has a load number in {@code (lastProcessed, ∞)}.
2008
     */
2009
    static String adminInvalidationCheckWhere(IRI graph, long lastProcessed) {
2010
        return String.format("""
60✔
2011
                  GRAPH <%1$s> {
2012
                    ?ri a gen:RoleInstantiation ;
2013
                        npa:inverseProperty gen:hasAdmin ;
2014
                        npa:viaNanopub ?np .
2015
                  }
2016
                  GRAPH <%2$s> {
2017
                    ?invNp <%3$s> ?np ;
2018
                           npa:hasLoadNumber ?ln .
2019
                    FILTER (?ln > %4$d)
2020
                    %5$s
2021
                  }
2022
                """, graph, NPA.GRAPH, NPX.INVALIDATES, lastProcessed,
18✔
2023
                samePublisherClause("invNp", "np"));
6✔
2024
    }
2025

2026
    /** DELETE template for admin-tier RoleInstantiations whose source nanopub was invalidated. */
2027
    static String adminInvalidationDelete(IRI graph, long lastProcessed) {
2028
        return String.format("""
63✔
2029
                PREFIX npa: <%1$s>
2030
                PREFIX gen: <%2$s>
2031
                DELETE { GRAPH <%3$s> {
2032
                  ?ri ?p ?o .
2033
                } }
2034
                WHERE {
2035
                  GRAPH <%3$s> { ?ri ?p ?o . }
2036
                %4$s
2037
                }
2038
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
2039
                adminInvalidationCheckWhere(graph, lastProcessed));
6✔
2040
    }
2041

2042
    /** WHERE clause for RoleAssignment invalidation. */
2043
    static String roleAssignmentInvalidationCheckWhere(IRI graph, long lastProcessed) {
2044
        return String.format("""
60✔
2045
                  GRAPH <%1$s> {
2046
                    ?ra a gen:RoleAssignment ;
2047
                        npa:viaNanopub ?np .
2048
                  }
2049
                  GRAPH <%2$s> {
2050
                    ?invNp <%3$s> ?np ;
2051
                           npa:hasLoadNumber ?ln .
2052
                    FILTER (?ln > %4$d)
2053
                    %5$s
2054
                  }
2055
                """, graph, NPA.GRAPH, NPX.INVALIDATES, lastProcessed,
18✔
2056
                samePublisherClause("invNp", "np"));
6✔
2057
    }
2058

2059
    /** DELETE template for RoleAssignments whose source nanopub was invalidated. */
2060
    static String roleAssignmentInvalidationDelete(IRI graph, long lastProcessed) {
2061
        return String.format("""
63✔
2062
                PREFIX npa: <%1$s>
2063
                PREFIX gen: <%2$s>
2064
                DELETE { GRAPH <%3$s> {
2065
                  ?ra ?p ?o .
2066
                } }
2067
                WHERE {
2068
                  GRAPH <%3$s> { ?ra ?p ?o . }
2069
                %4$s
2070
                }
2071
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
2072
                roleAssignmentInvalidationCheckWhere(graph, lastProcessed));
6✔
2073
    }
2074

2075
    /**
2076
     * DELETE template for non-admin (leaf-tier) RoleInstantiations whose source
2077
     * nanopub was invalidated. Identified as {@code gen:RoleInstantiation} rows
2078
     * lacking the admin-pinning {@code npa:inverseProperty gen:hasAdmin} triple.
2079
     * No flag is set; leaf-tier removals are recoverable on the next cycle.
2080
     */
2081
    static String leafTierInvalidationDelete(IRI graph, long lastProcessed) {
2082
        return String.format("""
84✔
2083
                PREFIX npa: <%1$s>
2084
                PREFIX gen: <%2$s>
2085
                DELETE { GRAPH <%3$s> {
2086
                  ?ri ?p ?o .
2087
                } }
2088
                WHERE {
2089
                  GRAPH <%3$s> {
2090
                    ?ri a gen:RoleInstantiation ;
2091
                        npa:viaNanopub ?np .
2092
                    FILTER NOT EXISTS { ?ri npa:inverseProperty gen:hasAdmin }
2093
                    ?ri ?p ?o .
2094
                  }
2095
                  GRAPH <%4$s> {
2096
                    ?invNp <%5$s> ?np ;
2097
                           npa:hasLoadNumber ?ln .
2098
                    FILTER (?ln > %6$d)
2099
                    %7$s
2100
                  }
2101
                }
2102
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
2103
                NPA.GRAPH, NPX.INVALIDATES, lastProcessed,
18✔
2104
                samePublisherClause("invNp", "np"));
6✔
2105
    }
2106

2107
    /**
2108
     * WHERE clause shared by the sub-space invalidation ASK precheck and the
2109
     * matching DELETE. Identifies validated {@code npa:SubSpaceDeclaration} rows
2110
     * in the space-state graph whose {@code npa:viaNanopub} is the target of an
2111
     * {@code npx:invalidates} triple in {@code npa:graph} whose subject nanopub
2112
     * has a load number in {@code (lastProcessed, ∞)}.
2113
     */
2114
    static String subSpaceInvalidationCheckWhere(IRI graph, long lastProcessed) {
2115
        return String.format("""
60✔
2116
                  GRAPH <%1$s> {
2117
                    ?d a npa:SubSpaceDeclaration ;
2118
                       npa:viaNanopub ?np .
2119
                  }
2120
                  GRAPH <%2$s> {
2121
                    ?invNp <%3$s> ?np ;
2122
                           npa:hasLoadNumber ?ln .
2123
                    FILTER (?ln > %4$d)
2124
                    %5$s
2125
                  }
2126
                """, graph, NPA.GRAPH, NPX.INVALIDATES, lastProcessed,
18✔
2127
                samePublisherClause("invNp", "np"));
6✔
2128
    }
2129

2130
    /**
2131
     * DELETE template for validated {@code npa:SubSpaceDeclaration} rows whose
2132
     * source nanopub was invalidated. Removes the per-declaration row by subject;
2133
     * the convenience direct triples ({@code <child> npa:isSubSpaceOf <parent>}
2134
     * and inverse) are then dropped by {@link #subSpaceConvenienceEdgeCleanup} in the
2135
     * same cycle (issue #125 finding #5) once no surviving link backs them.
2136
     */
2137
    static String subSpaceInvalidationDelete(IRI graph, long lastProcessed) {
2138
        return String.format("""
63✔
2139
                PREFIX npa: <%1$s>
2140
                PREFIX gen: <%2$s>
2141
                DELETE { GRAPH <%3$s> {
2142
                  ?d ?p ?o .
2143
                } }
2144
                WHERE {
2145
                  GRAPH <%3$s> { ?d ?p ?o . }
2146
                %4$s
2147
                }
2148
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
2149
                subSpaceInvalidationCheckWhere(graph, lastProcessed));
6✔
2150
    }
2151

2152
    /**
2153
     * DELETE template for validated {@code npa:MaintainedResourceDeclaration} rows
2154
     * whose source nanopub was invalidated. Removes the per-declaration row by
2155
     * subject; the convenience direct triples ({@code <r> npa:isMaintainedBy <s>}
2156
     * and inverse) are then dropped by {@link #maintainedResourceConvenienceEdgeCleanup}
2157
     * in the same cycle (issue #125 finding #5). No structural-rebuild flag —
2158
     * maintained-resource is a leaf relation, no downstream consumers depend on its
2159
     * closure, so the prompt edge cleanup fully resolves its invalidation.
2160
     */
2161
    static String maintainedResourceInvalidationDelete(IRI graph, long lastProcessed) {
2162
        return String.format("""
84✔
2163
                PREFIX npa: <%1$s>
2164
                PREFIX gen: <%2$s>
2165
                DELETE { GRAPH <%3$s> {
2166
                  ?d ?p ?o .
2167
                } }
2168
                WHERE {
2169
                  GRAPH <%3$s> {
2170
                    ?d a npa:MaintainedResourceDeclaration ;
2171
                       npa:viaNanopub ?np .
2172
                    ?d ?p ?o .
2173
                  }
2174
                  GRAPH <%4$s> {
2175
                    ?invNp <%5$s> ?np ;
2176
                           npa:hasLoadNumber ?ln .
2177
                    FILTER (?ln > %6$d)
2178
                    %7$s
2179
                  }
2180
                }
2181
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
2182
                NPA.GRAPH, NPX.INVALIDATES, lastProcessed,
18✔
2183
                samePublisherClause("invNp", "np"));
6✔
2184
    }
2185

2186
    /**
2187
     * WHERE clause shared by the alias invalidation ASK precheck and the matching
2188
     * DELETE. Identifies validated {@code npa:SpaceAliasDeclaration} rows in the
2189
     * space-state graph whose {@code npa:viaNanopub} is the target of an
2190
     * {@code npx:invalidates} triple in {@code npa:graph} whose subject nanopub has a
2191
     * load number in {@code (lastProcessed, ∞)}.
2192
     */
2193
    static String aliasInvalidationCheckWhere(IRI graph, long lastProcessed) {
2194
        return String.format("""
60✔
2195
                  GRAPH <%1$s> {
2196
                    ?d a npa:SpaceAliasDeclaration ;
2197
                       npa:viaNanopub ?np .
2198
                  }
2199
                  GRAPH <%2$s> {
2200
                    ?invNp <%3$s> ?np ;
2201
                           npa:hasLoadNumber ?ln .
2202
                    FILTER (?ln > %4$d)
2203
                    %5$s
2204
                  }
2205
                """, graph, NPA.GRAPH, NPX.INVALIDATES, lastProcessed,
18✔
2206
                samePublisherClause("invNp", "np"));
6✔
2207
    }
2208

2209
    /**
2210
     * DELETE template for validated {@code npa:SpaceAliasDeclaration} rows whose
2211
     * source nanopub was invalidated. Removes the per-declaration row by subject; the
2212
     * convenience {@code <alias> npa:sameAsSpace <canonical>} edge is then dropped by
2213
     * {@link #aliasConvenienceEdgeCleanup} in the same cycle (issue #125 finding #5),
2214
     * so an alias can no longer grant admin authority after its declaration is retracted.
2215
     * The alias feeds the authority closure, so this kind is still structural and flips
2216
     * {@code npa:needsFullRebuild} to bound any rows already derived through the edge.
2217
     */
2218
    static String aliasInvalidationDelete(IRI graph, long lastProcessed) {
2219
        return String.format("""
63✔
2220
                PREFIX npa: <%1$s>
2221
                PREFIX gen: <%2$s>
2222
                DELETE { GRAPH <%3$s> {
2223
                  ?d ?p ?o .
2224
                } }
2225
                WHERE {
2226
                  GRAPH <%3$s> { ?d ?p ?o . }
2227
                %4$s
2228
                }
2229
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
2230
                aliasInvalidationCheckWhere(graph, lastProcessed));
6✔
2231
    }
2232

2233
    /**
2234
     * WHERE clause shared by the maintained-resource invalidation ASK precheck and the
2235
     * matching cleanup. Identifies validated {@code npa:MaintainedResourceDeclaration}
2236
     * rows in the space-state graph whose {@code npa:viaNanopub} is the target of an
2237
     * {@code npx:invalidates} triple in {@code npa:graph} whose subject nanopub has a
2238
     * load number in {@code (lastProcessed, ∞)}.
2239
     */
2240
    static String maintainedResourceInvalidationCheckWhere(IRI graph, long lastProcessed) {
2241
        return String.format("""
×
2242
                  GRAPH <%1$s> {
2243
                    ?d a npa:MaintainedResourceDeclaration ;
2244
                       npa:viaNanopub ?np .
2245
                  }
2246
                  GRAPH <%2$s> {
2247
                    ?invNp <%3$s> ?np ;
2248
                           npa:hasLoadNumber ?ln .
2249
                    FILTER (?ln > %4$d)
2250
                    %5$s
2251
                  }
2252
                """, graph, NPA.GRAPH, NPX.INVALIDATES, lastProcessed,
×
2253
                samePublisherClause("invNp", "np"));
×
2254
    }
2255

2256
    /**
2257
     * Convenience-edge cleanup for invalidated sub-space declarations (issue #125
2258
     * finding #5). Run after {@link #subSpaceInvalidationDelete} (which removes the
2259
     * {@code npa:SubSpaceDeclaration} rows). Two phases as one multi-operation update:
2260
     * <ol>
2261
     *   <li>delete every {@code npa:SubSpaceLink} provenance link whose
2262
     *       {@code npa:viaNanopub} was invalidated (same {@code npx:invalidates} +
2263
     *       same-publisher gate as the declaration delete);</li>
2264
     *   <li>orphan-sweep: delete the convenience {@code npa:isSubSpaceOf} /
2265
     *       {@code npa:hasSubSpace} edges (both ref- and IRI-valued) that no surviving
2266
     *       link backs — neither a {@code npa:SubSpaceLink} (explicit declaration) nor a
2267
     *       {@code npa:DerivedSubSpaceLink} (URL-prefix fallback).</li>
2268
     * </ol>
2269
     * Edges backed by another surviving declaration or by the URL-prefix fallback are
2270
     * kept. The {@code npa:needsFullRebuild} flag still fires for the structural kind, so
2271
     * downstream rows derived through a removed edge remain rebuild-bounded; this only
2272
     * stops the convenience edges themselves from going sticky.
2273
     */
2274
    static String subSpaceConvenienceEdgeCleanup(IRI graph, long lastProcessed) {
2275
        return String.format("""
72✔
2276
                PREFIX npa: <%1$s>
2277
                # 1. Drop sub-space provenance links whose source nanopub was invalidated.
2278
                DELETE { GRAPH <%2$s> { ?l ?p ?o . } }
2279
                WHERE {
2280
                  GRAPH <%2$s> {
2281
                    ?l a npa:SubSpaceLink ;
2282
                       npa:viaNanopub ?np .
2283
                    ?l ?p ?o .
2284
                  }
2285
                  GRAPH <%3$s> {
2286
                    ?invNp <%4$s> ?np ;
2287
                           npa:hasLoadNumber ?ln .
2288
                    FILTER (?ln > %5$d)
2289
                    %6$s
2290
                  }
2291
                } ;
2292
                # 2. Orphan-sweep isSubSpaceOf edges (ref- and IRI-valued) with no backing link.
2293
                DELETE { GRAPH <%2$s> { ?c npa:isSubSpaceOf ?p . } }
2294
                WHERE {
2295
                  GRAPH <%2$s> {
2296
                    ?c npa:isSubSpaceOf ?p .
2297
                    FILTER NOT EXISTS {
2298
                      { ?l a npa:SubSpaceLink } UNION { ?l a npa:DerivedSubSpaceLink }
2299
                      { { ?l npa:childSpaceRef ?c . ?l npa:parentSpaceRef ?p }
2300
                        UNION
2301
                        { ?l npa:childSpace ?c . ?l npa:parentSpace ?p } }
2302
                    }
2303
                  }
2304
                } ;
2305
                # 3. Orphan-sweep the inverse hasSubSpace edges symmetrically.
2306
                DELETE { GRAPH <%2$s> { ?p npa:hasSubSpace ?c . } }
2307
                WHERE {
2308
                  GRAPH <%2$s> {
2309
                    ?p npa:hasSubSpace ?c .
2310
                    FILTER NOT EXISTS {
2311
                      { ?l a npa:SubSpaceLink } UNION { ?l a npa:DerivedSubSpaceLink }
2312
                      { { ?l npa:childSpaceRef ?c . ?l npa:parentSpaceRef ?p }
2313
                        UNION
2314
                        { ?l npa:childSpace ?c . ?l npa:parentSpace ?p } }
2315
                    }
2316
                  }
2317
                }
2318
                """, NPA.NAMESPACE, graph, NPA.GRAPH, NPX.INVALIDATES, lastProcessed,
18✔
2319
                samePublisherClause("invNp", "np"));
6✔
2320
    }
2321

2322
    /**
2323
     * Convenience-edge cleanup for invalidated maintained-resource declarations (issue
2324
     * #125 finding #5). Run after {@link #maintainedResourceInvalidationDelete}. Deletes
2325
     * the {@code npa:MaintainedResourceLink} provenance links whose source nanopub was
2326
     * invalidated, then orphan-sweeps the {@code npa:isMaintainedBy} /
2327
     * {@code npa:hasMaintainedResource} edges (ref- and IRI-valued) that no surviving link
2328
     * backs. See {@link #subSpaceConvenienceEdgeCleanup} for the two-phase structure.
2329
     */
2330
    static String maintainedResourceConvenienceEdgeCleanup(IRI graph, long lastProcessed) {
2331
        return String.format("""
72✔
2332
                PREFIX npa: <%1$s>
2333
                # 1. Drop maintained-resource provenance links whose source nanopub was invalidated.
2334
                DELETE { GRAPH <%2$s> { ?l ?p ?o . } }
2335
                WHERE {
2336
                  GRAPH <%2$s> {
2337
                    ?l a npa:MaintainedResourceLink ;
2338
                       npa:viaNanopub ?np .
2339
                    ?l ?p ?o .
2340
                  }
2341
                  GRAPH <%3$s> {
2342
                    ?invNp <%4$s> ?np ;
2343
                           npa:hasLoadNumber ?ln .
2344
                    FILTER (?ln > %5$d)
2345
                    %6$s
2346
                  }
2347
                } ;
2348
                # 2. Orphan-sweep isMaintainedBy edges (ref- and IRI-valued) with no backing link.
2349
                DELETE { GRAPH <%2$s> { ?r npa:isMaintainedBy ?o . } }
2350
                WHERE {
2351
                  GRAPH <%2$s> {
2352
                    ?r npa:isMaintainedBy ?o .
2353
                    FILTER NOT EXISTS {
2354
                      ?l a npa:MaintainedResourceLink ;
2355
                         npa:resourceIri ?r .
2356
                      { ?l npa:maintainerSpaceRef ?o } UNION { ?l npa:maintainerSpace ?o }
2357
                    }
2358
                  }
2359
                } ;
2360
                # 3. Orphan-sweep the inverse hasMaintainedResource edges symmetrically.
2361
                DELETE { GRAPH <%2$s> { ?o npa:hasMaintainedResource ?r . } }
2362
                WHERE {
2363
                  GRAPH <%2$s> {
2364
                    ?o npa:hasMaintainedResource ?r .
2365
                    FILTER NOT EXISTS {
2366
                      ?l a npa:MaintainedResourceLink ;
2367
                         npa:resourceIri ?r .
2368
                      { ?l npa:maintainerSpaceRef ?o } UNION { ?l npa:maintainerSpace ?o }
2369
                    }
2370
                  }
2371
                }
2372
                """, NPA.NAMESPACE, graph, NPA.GRAPH, NPX.INVALIDATES, lastProcessed,
18✔
2373
                samePublisherClause("invNp", "np"));
6✔
2374
    }
2375

2376
    /**
2377
     * Convenience-edge cleanup for invalidated space-alias declarations (issue #125
2378
     * finding #5 — the load-bearing case, since the alias edge feeds the admin-authority
2379
     * closure). Run after {@link #aliasInvalidationDelete}. Deletes the
2380
     * {@code npa:SpaceAliasLink} provenance links whose source nanopub was invalidated,
2381
     * then orphan-sweeps the {@code npa:sameAsSpace} edges (ref- and IRI-valued) that no
2382
     * surviving link backs. See {@link #subSpaceConvenienceEdgeCleanup} for the two-phase
2383
     * structure.
2384
     */
2385
    static String aliasConvenienceEdgeCleanup(IRI graph, long lastProcessed) {
2386
        return String.format("""
72✔
2387
                PREFIX npa: <%1$s>
2388
                # 1. Drop alias provenance links whose source nanopub was invalidated.
2389
                DELETE { GRAPH <%2$s> { ?l ?p ?o . } }
2390
                WHERE {
2391
                  GRAPH <%2$s> {
2392
                    ?l a npa:SpaceAliasLink ;
2393
                       npa:viaNanopub ?np .
2394
                    ?l ?p ?o .
2395
                  }
2396
                  GRAPH <%3$s> {
2397
                    ?invNp <%4$s> ?np ;
2398
                           npa:hasLoadNumber ?ln .
2399
                    FILTER (?ln > %5$d)
2400
                    %6$s
2401
                  }
2402
                } ;
2403
                # 2. Orphan-sweep sameAsSpace edges (ref- and IRI-valued) with no backing link.
2404
                DELETE { GRAPH <%2$s> { ?alias npa:sameAsSpace ?o . } }
2405
                WHERE {
2406
                  GRAPH <%2$s> {
2407
                    ?alias npa:sameAsSpace ?o .
2408
                    FILTER NOT EXISTS {
2409
                      ?l a npa:SpaceAliasLink ;
2410
                         npa:aliasSpace ?alias .
2411
                      { ?l npa:canonicalSpaceRef ?o } UNION { ?l npa:canonicalSpace ?o }
2412
                    }
2413
                  }
2414
                }
2415
                """, NPA.NAMESPACE, graph, NPA.GRAPH, NPX.INVALIDATES, lastProcessed,
18✔
2416
                samePublisherClause("invNp", "np"));
6✔
2417
    }
2418

2419
    /**
2420
     * WHERE clause shared by the preset-deactivation ASK precheck and the matching DELETE
2421
     * (Nanodash issue #302). Binds {@code ?ra} = a materialized preset-derived
2422
     * {@code gen:RoleAssignment} ({@code npa:derivedFromPreset}) for which a <em>newer,
2423
     * admin-authored</em> same-{@code (preset, resource)} assignment exists by
2424
     * {@code dct:created} (load number in {@code (lastProcessed, ∞)}). This is NOT an
2425
     * {@code npx:invalidates} check — preset activation is latest-wins by timestamp.
2426
     *
2427
     * <p>Authorization-scoped (anti-hijack, design doc §3/§4.4): the newer assignment's
2428
     * publisher must itself be a validated admin of the row's {@code npa:forSpaceRef}, so an
2429
     * unauthorized key's newer assignment can neither delete nor shadow an admin's
2430
     * materialized role. {@code dct:created} is written as a full IRI (not a {@code dct:}
2431
     * prefix) because {@link #wouldInvalidate}'s ASK wrapper only declares {@code npa:} /
2432
     * {@code gen:}.
2433
     */
2434
    static String presetDeactivationCheckWhere(IRI graph, long lastProcessed) {
2435
        return String.format("""
60✔
2436
                  GRAPH <%1$s> {
2437
                    ?ra a gen:RoleAssignment ;
2438
                        npa:derivedFromPreset ?assignNp ;
2439
                        npa:forSpaceRef ?targetRef .
2440
                  }
2441
                  GRAPH <%2$s> {
2442
                    ?pa a npa:PresetAssignment ;
2443
                        npa:viaNanopub  ?assignNp ;
2444
                        npa:ofPreset    ?preset ;
2445
                        npa:forResource ?resource ;
2446
                        <http://purl.org/dc/terms/created> ?created .
2447
                    ?paNewer a npa:PresetAssignment ;
2448
                             npa:ofPreset    ?preset ;
2449
                             npa:forResource ?resource ;
2450
                             npa:pubkeyHash  ?pkhNewer ;
2451
                             npa:viaNanopub  ?assignNpNewer ;
2452
                             <http://purl.org/dc/terms/created> ?createdNewer .
2453
                    FILTER (?createdNewer > ?created
2454
                            || (?createdNewer = ?created && STR(?paNewer) > STR(?pa)))
2455
                  }
2456
                  GRAPH <%3$s> {
2457
                    ?assignNpNewer npa:hasLoadNumber ?lnNewer .
2458
                    FILTER (?lnNewer > %4$d)
2459
                  }
2460
                  GRAPH <%1$s> {
2461
                    ?acctNewer a npa:AccountState ;
2462
                               npa:agent  ?publisherNewer ;
2463
                               npa:pubkey ?pkhNewer .
2464
                    ?adminRINewer a gen:RoleInstantiation ;
2465
                                  npa:forSpaceRef ?targetRef ;
2466
                                  npa:inverseProperty gen:hasAdmin ;
2467
                                  npa:forAgent ?publisherNewer .
2468
                  }
2469
                """, graph, SpacesVocab.SPACES_GRAPH, NPA.GRAPH, lastProcessed);
6✔
2470
    }
2471

2472
    /**
2473
     * DELETE template for preset-derived {@code gen:RoleAssignment} rows superseded by a
2474
     * newer admin-authored same-pair assignment (issue #302). Removes the whole row by
2475
     * subject; scoped via {@code npa:derivedFromPreset} so directly-published attachments
2476
     * are never touched. The {@link #presetAttachmentValidationUpdate} re-INSERT in the
2477
     * same cycle re-materializes the pair iff the newest assignment is still active.
2478
     */
2479
    static String presetDeactivationDelete(IRI graph, long lastProcessed) {
2480
        return String.format("""
63✔
2481
                PREFIX npa: <%1$s>
2482
                PREFIX gen: <%2$s>
2483
                DELETE { GRAPH <%3$s> {
2484
                  ?ra ?p ?o .
2485
                } }
2486
                WHERE {
2487
                  GRAPH <%3$s> { ?ra ?p ?o . }
2488
                %4$s
2489
                }
2490
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
2491
                presetDeactivationCheckWhere(graph, lastProcessed));
6✔
2492
    }
2493

2494
    /**
2495
     * DELETE template for ref-scoped preset-assignment stamps ({@link
2496
     * #presetAssignmentRefStampUpdate}) whose underlying assignment nanopub was
2497
     * hard-retracted (issue #122). Removes the whole row by subject; scoped to
2498
     * state-graph {@code npa:PresetAssignment} rows that carry {@code npa:forSpaceRef}
2499
     * (the IRI-keyed extraction rows never do), so it can never touch them.
2500
     *
2501
     * <p>Leaf delete — no structural flag: nothing downstream derives from a listing
2502
     * stamp, so a stale row only mis-displays a retracted assignment until this cycle's
2503
     * delete runs. Admin-grant revocation is bounded by the periodic full rebuild (same
2504
     * sticky-convenience policy as the alias / sub-space declaration edges). A
2505
     * <em>deactivation</em> needs no delete here: it is represented as a newer
2506
     * admin-authored stamp with {@code npa:isActivated false}, resolved by the consumer's
2507
     * latest-wins.
2508
     */
2509
    static String presetAssignmentRefInvalidationDelete(IRI graph, long lastProcessed) {
2510
        return String.format("""
84✔
2511
                PREFIX npa: <%1$s>
2512
                PREFIX gen: <%2$s>
2513
                DELETE { GRAPH <%3$s> {
2514
                  ?paRef ?p ?o .
2515
                } }
2516
                WHERE {
2517
                  GRAPH <%3$s> {
2518
                    ?paRef a npa:PresetAssignment ;
2519
                           npa:forSpaceRef ?targetRef ;
2520
                           npa:viaNanopub  ?assignNp .
2521
                    ?paRef ?p ?o .
2522
                  }
2523
                  GRAPH <%4$s> {
2524
                    ?invNp <%5$s> ?assignNp ;
2525
                           npa:hasLoadNumber ?ln .
2526
                    FILTER (?ln > %6$d)
2527
                    %7$s
2528
                  }
2529
                }
2530
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
2531
                NPA.GRAPH, NPX.INVALIDATES, lastProcessed,
18✔
2532
                samePublisherClause("invNp", "assignNp"));
6✔
2533
    }
2534

2535
    /** Wraps an ASK by joining the shared prefixes. */
2536
    private boolean wouldInvalidate(IRI graph, long lastProcessed,
2537
                                    boolean adminPinned, String whereClause) {
2538
        // adminPinned is informational only — kept to make call sites read clearly;
2539
        // the WHERE clause already encodes the kind via its own type predicates.
2540
        String ask = String.format("""
×
2541
                PREFIX npa: <%1$s>
2542
                PREFIX gen: <%2$s>
2543
                ASK { %3$s }
2544
                """, NPA.NAMESPACE, GEN.NAMESPACE, whereClause);
2545
        return runAsk(ask);
×
2546
    }
2547

2548
    private boolean runAsk(String sparql) {
2549
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
2550
            return conn.prepareBooleanQuery(QueryLanguage.SPARQL, sparql).evaluate();
×
2551
        }
2552
    }
2553

2554
    private void executeUpdate(String sparqlUpdate) {
2555
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
2556
            conn.prepareUpdate(QueryLanguage.SPARQL, sparqlUpdate).execute();
×
2557
        }
2558
    }
×
2559

2560
    // ---------------- Mirror step ----------------
2561

2562
    /**
2563
     * Copies trust-approved {@code npa:AccountState} rows from {@code npat:<T>}
2564
     * in the {@code trust} repo into {@code newGraph} in the {@code spaces} repo,
2565
     * inside one spaces-side serializable transaction.
2566
     *
2567
     * @return number of rows mirrored (useful for metrics / logging)
2568
     */
2569
    int mirrorTrustState(String trustStateHash, IRI newGraph) {
2570
        IRI trustStateIri = NPAT.forHash(trustStateHash);
×
2571
        int count = 0;
×
2572
        try (RepositoryConnection trustConn = TripleStore.get().getRepoConnection(TRUST_REPO);
×
2573
             RepositoryConnection spacesConn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
2574
            trustConn.begin(IsolationLevels.READ_COMMITTED);
×
2575
            spacesConn.begin(IsolationLevels.SERIALIZABLE);
×
2576
            // Walk rdf:type triples in the trust state's graph; for each AccountState,
2577
            // check status and copy the approved ones verbatim (minus status-specific
2578
            // detail triples, which we don't need for validation).
2579
            try (RepositoryResult<Statement> typeRows = trustConn.getStatements(
×
2580
                    null, RDF.TYPE, NPA_ACCOUNT_STATE, trustStateIri)) {
2581
                while (typeRows.hasNext()) {
×
2582
                    Statement st = typeRows.next();
×
2583
                    if (!(st.getSubject() instanceof IRI accountStateIri)) continue;
×
2584
                    Value status = trustConn.getStatements(accountStateIri, NPA_TRUST_STATUS, null, trustStateIri)
×
2585
                            .stream().findFirst().map(Statement::getObject).orElse(null);
×
2586
                    if (!(status instanceof IRI statusIri) || !APPROVED_SET.contains(statusIri)) continue;
×
2587
                    Value agent = trustConn.getStatements(accountStateIri, NPA_AGENT, null, trustStateIri)
×
2588
                            .stream().findFirst().map(Statement::getObject).orElse(null);
×
2589
                    Value pubkey = trustConn.getStatements(accountStateIri, NPA_PUBKEY, null, trustStateIri)
×
2590
                            .stream().findFirst().map(Statement::getObject).orElse(null);
×
2591
                    if (agent == null || pubkey == null) {
×
2592
                        logger.warn("AuthorityResolver.mirror: account {} missing agent or pubkey; skipping",
×
2593
                                accountStateIri);
2594
                        continue;
×
2595
                    }
2596
                    spacesConn.add(accountStateIri, RDF.TYPE, NPA_ACCOUNT_STATE, newGraph);
×
2597
                    spacesConn.add(accountStateIri, NPA_AGENT, agent, newGraph);
×
2598
                    spacesConn.add(accountStateIri, NPA_PUBKEY, pubkey, newGraph);
×
2599
                    spacesConn.add(accountStateIri, NPA_TRUST_STATUS, statusIri, newGraph);
×
2600
                    count++;
×
2601
                }
×
2602
            }
2603
            // Mirror canonical foaf:name triples for approved agents. The trust
2604
            // loader emits one per agent (across approved keys, MAX(ratio) wins).
2605
            // Copying them into the space-state graph means consumers reading
2606
            // ?agent foaf:name ?n inside the state graph hit local data, with no
2607
            // cross-repo SERVICE.
2608
            try (RepositoryResult<Statement> nameRows = trustConn.getStatements(
×
2609
                    null, FOAF.NAME, null, trustStateIri)) {
2610
                while (nameRows.hasNext()) {
×
2611
                    Statement st = nameRows.next();
×
2612
                    spacesConn.add(st.getSubject(), st.getPredicate(), st.getObject(), newGraph);
×
2613
                }
×
2614
            }
2615
            spacesConn.commit();
×
2616
            trustConn.commit();
×
2617
        }
2618
        return count;
×
2619
    }
2620

2621
    // ---------------- Pointer + counter helpers ----------------
2622

2623
    /**
2624
     * Reads the current {@code npa:hasCurrentSpaceState} pointer from the
2625
     * {@code npa:graph} admin graph of the {@code spaces} repo. Returns
2626
     * {@code null} if no pointer exists yet.
2627
     */
2628
    IRI getCurrentSpaceStateGraph() {
2629
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
2630
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
2631
                    SpacesVocab.HAS_CURRENT_SPACE_STATE);
2632
            return (v instanceof IRI iri) ? iri : null;
×
2633
        } catch (Exception ex) {
×
2634
            logger.warn("AuthorityResolver: failed to read hasCurrentSpaceState pointer: {}", ex.toString());
×
2635
            return null;
×
2636
        }
2637
    }
2638

2639
    long getCurrentLoadCounter() {
2640
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
2641
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
2642
                    SpacesVocab.CURRENT_LOAD_COUNTER);
2643
            if (v == null) return 0;
×
2644
            try {
2645
                return Long.parseLong(v.stringValue());
×
2646
            } catch (NumberFormatException ex) {
×
2647
                logger.warn("AuthorityResolver: non-numeric currentLoadCounter: {}", v);
×
2648
                return 0;
×
2649
            }
2650
        } catch (Exception ex) {
×
2651
            logger.warn("AuthorityResolver: failed to read currentLoadCounter: {}", ex.toString());
×
2652
            return 0;
×
2653
        }
2654
    }
2655

2656
    /**
2657
     * Atomic pointer flip: a single SPARQL {@code DELETE … INSERT … WHERE}
2658
     * replaces the old pointer with the new one in one statement, so readers
2659
     * never see a zero-pointer window.
2660
     */
2661
    void flipPointer(IRI newGraph) {
2662
        String update = String.format("""
×
2663
                DELETE { GRAPH <%s> { <%s> <%s> ?old } }
2664
                INSERT { GRAPH <%s> { <%s> <%s> <%s> } }
2665
                WHERE  { OPTIONAL { GRAPH <%s> { <%s> <%s> ?old } } }
2666
                """,
2667
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.HAS_CURRENT_SPACE_STATE,
2668
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.HAS_CURRENT_SPACE_STATE, newGraph,
2669
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.HAS_CURRENT_SPACE_STATE);
2670
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
2671
            conn.begin(IsolationLevels.SERIALIZABLE);
×
2672
            conn.prepareUpdate(QueryLanguage.SPARQL, update).execute();
×
2673
            conn.commit();
×
2674
        }
2675
    }
×
2676

2677
    void writeProcessedUpTo(IRI graph, long loadCounter) {
2678
        String update = String.format("""
×
2679
                DELETE { GRAPH <%s> { <%s> <%s> ?old } }
2680
                INSERT { GRAPH <%s> { <%s> <%s> "%d"^^<http://www.w3.org/2001/XMLSchema#long> } }
2681
                WHERE  { OPTIONAL { GRAPH <%s> { <%s> <%s> ?old } } }
2682
                """,
2683
                graph, graph, SpacesVocab.PROCESSED_UP_TO,
2684
                graph, graph, SpacesVocab.PROCESSED_UP_TO, loadCounter,
×
2685
                graph, graph, SpacesVocab.PROCESSED_UP_TO);
2686
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
2687
            conn.begin(IsolationLevels.SERIALIZABLE);
×
2688
            conn.prepareUpdate(QueryLanguage.SPARQL, update).execute();
×
2689
            conn.commit();
×
2690
        }
2691
    }
×
2692

2693
    /**
2694
     * Reads {@code processedUpTo} from the given space-state graph.
2695
     * Returns {@code -1} if absent (graph not fully built yet).
2696
     */
2697
    long readProcessedUpTo(IRI graph) {
2698
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
2699
            String query = String.format(
×
2700
                    "SELECT ?n WHERE { GRAPH <%s> { <%s> <%s> ?n } }",
2701
                    graph, graph, SpacesVocab.PROCESSED_UP_TO);
2702
            try (TupleQueryResult r = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) {
×
2703
                if (!r.hasNext()) return -1;
×
2704
                BindingSet b = r.next();
×
2705
                return Long.parseLong(b.getBinding("n").getValue().stringValue());
×
2706
            }
×
2707
        } catch (Exception ex) {
×
2708
            logger.warn("AuthorityResolver: failed to read processedUpTo for {}: {}", graph, ex.toString());
×
2709
            return -1;
×
2710
        }
2711
    }
2712

2713
    /**
2714
     * Reads the {@code npa:needsFullRebuild} flag (boolean literal) from
2715
     * {@code npa:graph} in the {@code spaces} repo. Defaults to {@code false}
2716
     * when the triple is absent.
2717
     */
2718
    boolean readNeedsFullRebuild() {
2719
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
2720
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
2721
                    SpacesVocab.NEEDS_FULL_REBUILD);
2722
            return v != null && Boolean.parseBoolean(v.stringValue());
×
2723
        } catch (Exception ex) {
×
2724
            logger.warn("AuthorityResolver: failed to read needsFullRebuild: {}", ex.toString());
×
2725
            return false;
×
2726
        }
2727
    }
2728

2729
    void setNeedsFullRebuild() {
2730
        writeNeedsFullRebuild(true);
×
2731
    }
×
2732

2733
    void clearNeedsFullRebuild() {
2734
        writeNeedsFullRebuild(false);
×
2735
    }
×
2736

2737
    private void writeNeedsFullRebuild(boolean value) {
2738
        String update = String.format("""
×
2739
                DELETE { GRAPH <%s> { <%s> <%s> ?old } }
2740
                INSERT { GRAPH <%s> { <%s> <%s> "%s"^^<http://www.w3.org/2001/XMLSchema#boolean> } }
2741
                WHERE  { OPTIONAL { GRAPH <%s> { <%s> <%s> ?old } } }
2742
                """,
2743
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.NEEDS_FULL_REBUILD,
2744
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.NEEDS_FULL_REBUILD, value,
×
2745
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.NEEDS_FULL_REBUILD);
2746
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
2747
            conn.begin(IsolationLevels.SERIALIZABLE);
×
2748
            conn.prepareUpdate(QueryLanguage.SPARQL, update).execute();
×
2749
            conn.commit();
×
2750
        }
2751
    }
×
2752

2753
    void dropGraph(IRI graph) {
2754
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
2755
            conn.begin(IsolationLevels.SERIALIZABLE);
×
2756
            conn.clear(graph);
×
2757
            conn.commit();
×
2758
            logger.info("AuthorityResolver: dropped old space-state graph {}", graph);
×
2759
        }
2760
    }
×
2761

2762
    // ---------------- Trust-repo pointer lookup (used by TrustStateRegistry's bootstrap) ----------------
2763

2764
    /**
2765
     * Queries the {@code trust} repo directly for the current trust-state hash.
2766
     * Prefer {@link TrustStateRegistry#getCurrentHash()} in normal operation —
2767
     * this helper exists for tests and diagnostics.
2768
     *
2769
     * @return the current trust-state hash, or empty if none is set
2770
     */
2771
    Optional<String> readTrustRepoCurrentHash() {
2772
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(TRUST_REPO)) {
×
2773
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
2774
                    NPA_HAS_CURRENT_TRUST_STATE);
2775
            if (!(v instanceof IRI iri)) return Optional.empty();
×
2776
            String s = iri.stringValue();
×
2777
            if (!s.startsWith(NPAT.NAMESPACE)) return Optional.empty();
×
2778
            return Optional.of(s.substring(NPAT.NAMESPACE.length()));
×
2779
        } catch (Exception ex) {
×
2780
            logger.warn("AuthorityResolver: failed to read trust-repo current pointer: {}", ex.toString());
×
2781
            return Optional.empty();
×
2782
        }
2783
    }
2784

2785
    private static String abbrev(String hash) {
2786
        return hash.length() > 12 ? hash.substring(0, 12) + "…" : hash;
×
2787
    }
2788

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

© 2026 Coveralls, Inc