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

knowledgepixels / nanopub-query / 26118107010

19 May 2026 06:47PM UTC coverage: 58.355% (+0.1%) from 58.251%
26118107010

push

github

web-flow
Merge pull request #102 from knowledgepixels/fix/invalidation-join-load-order-race

fix(AuthorityResolver): join raw npx:invalidates so materialiser is symmetric in load order

480 of 900 branches covered (53.33%)

Branch coverage included in aggregate %.

1301 of 2152 relevant lines covered (60.46%)

9.33 hits per line

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

14.99
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 → 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 log = 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
            log.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
            log.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
            log.debug("AuthorityResolver.periodicRebuildTick: no current trust state — deferring");
×
163
            return;
×
164
        }
165
        log.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
                    log.info("AuthorityResolver.cleanOrphans: dropped orphan graph {}", iri);
×
195
                }
×
196
            }
197
            if (dropped == 0) {
×
198
                log.debug("AuthorityResolver.cleanOrphans: no orphan space-state graphs");
×
199
            }
200
        } catch (Exception ex) {
×
201
            log.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
            log.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.attachment
×
245
                + counts.maintainer + counts.member + counts.observer
246
                + counts.subSpace + counts.subSpacePrefix + counts.maintainedResource;
247
        lastFullBuildDurationMs = durationMs;
×
248
        lastProcessedUpToLag = 0L;
×
249
        log.info("AuthorityResolver: full build complete — graph={} mirrored={} rows loadCounter={} "
×
250
                        + "subjects: adminRIs={} attachmentRAs={} nonAdminRIs={} "
251
                        + "(inserted-triples: admin={} attachment={} maintainer={} member={} observer={} "
252
                        + "subspace={} subspace-prefix={} maintained-resource={}) durationMs={}",
253
                newGraph, mirrored, loadCounter,
×
254
                totals.adminRIs(), totals.attachmentRAs(), totals.nonAdminRIs(),
×
255
                counts.admin, counts.attachment, counts.maintainer, counts.member, counts.observer,
×
256
                counts.subSpace, counts.subSpacePrefix, counts.maintainedResource,
×
257
                durationMs);
×
258
    }
×
259

260
    // ---------------- Incremental cycle ----------------
261

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

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

322
        writeProcessedUpTo(graph, currentLoadCounter);
×
323

324
        TierSubjectTotals totals = computeTierSubjectTotals(graph);
×
325
        long durationMs = (System.nanoTime() - startNanos) / 1_000_000L;
×
326
        lastSubjectTotals = totals;
×
327
        lastInsertedTriplesTotal = (long) counts.admin + counts.attachment
×
328
                + counts.maintainer + counts.member + counts.observer
329
                + counts.subSpace + counts.subSpacePrefix + counts.maintainedResource;
330
        lastIncrementalCycleDurationMs = durationMs;
×
331
        log.info("AuthorityResolver: incremental cycle complete — graph={} delta=({}, {}] "
×
332
                        + "subjects: adminRIs={} attachmentRAs={} nonAdminRIs={} "
333
                        + "(inserted-triples: admin={} attachment={} maintainer={} member={} observer={} "
334
                        + "subspace={} subspace-prefix={} maintained-resource={}) "
335
                        + "structuralInvalidation={} structuralAdds={} durationMs={}",
336
                graph, lastProcessed, currentLoadCounter,
×
337
                totals.adminRIs(), totals.attachmentRAs(), totals.nonAdminRIs(),
×
338
                counts.admin, counts.attachment, counts.maintainer, counts.member, counts.observer,
×
339
                counts.subSpace, counts.subSpacePrefix, counts.maintainedResource,
×
340
                structuralInvalidation, structuralAdds, durationMs);
×
341
    }
×
342

343
    /**
344
     * Runs the four invalidation-DELETE / ASK steps. Sets {@code npa:needsFullRebuild}
345
     * when admin-RI, RoleAssignment, or RoleDeclaration invalidations matched (the
346
     * three structural kinds). Leaf-tier RI deletes don't set the flag.
347
     *
348
     * @return true iff at least one structural kind was invalidated
349
     */
350
    boolean applyInvalidations(IRI graph, long lastProcessed) {
351
        boolean structural = false;
×
352
        if (wouldInvalidate(graph, lastProcessed, /*adminPinned=*/ true,
×
353
                            adminInvalidationCheckWhere(graph, lastProcessed))) {
×
354
            executeUpdate(adminInvalidationDelete(graph, lastProcessed));
×
355
            structural = true;
×
356
        }
357
        if (wouldInvalidate(graph, lastProcessed, /*adminPinned=*/ false,
×
358
                            roleAssignmentInvalidationCheckWhere(graph, lastProcessed))) {
×
359
            executeUpdate(roleAssignmentInvalidationDelete(graph, lastProcessed));
×
360
            structural = true;
×
361
        }
362
        // RoleDeclaration ASK only — RDs aren't materialized into the space-state
363
        // graph, so there's nothing to DELETE here. The flag still flips because
364
        // sticky downstream RIs derived from the now-invalidated RD need a
365
        // from-scratch recompute.
366
        if (wouldInvalidate(graph, lastProcessed, /*adminPinned=*/ false,
×
367
                            roleDeclarationInvalidationCheckWhere(lastProcessed))) {
×
368
            structural = true;
×
369
        }
370
        // Sub-space declarations are structural — invalidating one (Mode A) or one
371
        // of two co-declarations (Mode B) changes the validated parent/child
372
        // topology. The DELETE removes the per-declaration row; the convenience
373
        // direct triples are left sticky and cleaned on the next periodic rebuild.
374
        if (wouldInvalidate(graph, lastProcessed, /*adminPinned=*/ false,
×
375
                            subSpaceInvalidationCheckWhere(graph, lastProcessed))) {
×
376
            executeUpdate(subSpaceInvalidationDelete(graph, lastProcessed));
×
377
            structural = true;
×
378
        }
379
        // Leaf-tier RI deletes — no flag.
380
        executeUpdate(leafTierInvalidationDelete(graph, lastProcessed));
×
381
        // Maintained-resource declaration deletes — no flag (leaf relation, no
382
        // downstream caches to bound).
383
        executeUpdate(maintainedResourceInvalidationDelete(graph, lastProcessed));
×
384
        if (structural) setNeedsFullRebuild();
×
385
        return structural;
×
386
    }
387

388
    /**
389
     * Runs the four leaf tiers (attachment/maintainer/member/observer) with
390
     * {@code lastProcessed = -1} so the load-number filter on the candidate
391
     * side admits everything. Dedup filters in the tier templates prevent
392
     * double-insert. Used by the late-arrival sweep.
393
     */
394
    TierInsertedTriples runDownstreamWithoutLoadFilter(IRI graph) {
395
        TierInsertedTriples c = new TierInsertedTriples();
×
396
        // Sub-space late-arrival: catches Mode-B candidates whose primary
397
        // declaration is older than lastProcessed but whose partner just landed.
398
        c.subSpace = runTierLabeled("subspace(late)", graph,
×
399
                subSpaceAdmitUpdate(graph, -1));
×
400
        // Maintained-resource late-arrival: catches declarations that landed
401
        // before the publisher's admin grant became valid in this state.
402
        c.maintainedResource = runTierLabeled("maintained-resource(late)", graph,
×
403
                maintainedResourceAdmitUpdate(graph, -1));
×
404
        // URL-prefix fallback: re-run after the late-arrival sub-space admit so
405
        // any newly-validated children get their fallback edges suppressed (for
406
        // future inserts) and any newly-orphaned children pick up fallback edges.
407
        c.subSpacePrefix = runTierLabeled("subspace-prefix(late)", graph,
×
408
                subSpacePrefixFallbackUpdate(graph));
×
409
        c.attachment = runTierLabeled("attachment(late)", graph,
×
410
                attachmentValidationUpdate(graph, -1));
×
411
        c.maintainer = runTierLabeled("maintainer(late)", graph,
×
412
                nonAdminTierUpdate(graph, -1, GEN.MAINTAINER_ROLE, PUBLISHER_IS_ADMIN));
×
413
        c.member = runTierLabeled("member(admin-pub,late)", graph,
×
414
                nonAdminTierUpdate(graph, -1, GEN.MEMBER_ROLE, PUBLISHER_IS_ADMIN));
×
415
        c.member += runTierLabeled("member(maint-pub,late)", graph,
×
416
                nonAdminTierUpdate(graph, -1,
×
417
                        GEN.MEMBER_ROLE, publisherIsTieredRole(GEN.MAINTAINER_ROLE)));
×
418
        c.observer = runTierLabeled("observer(admin-pub,late)", graph,
×
419
                nonAdminTierUpdate(graph, -1, GEN.OBSERVER_ROLE, PUBLISHER_IS_ADMIN));
×
420
        c.observer += runTierLabeled("observer(maint-pub,late)", graph,
×
421
                nonAdminTierUpdate(graph, -1,
×
422
                        GEN.OBSERVER_ROLE, publisherIsTieredRole(GEN.MAINTAINER_ROLE)));
×
423
        c.observer += runTierLabeled("observer(member-pub,late)", graph,
×
424
                nonAdminTierUpdate(graph, -1,
×
425
                        GEN.OBSERVER_ROLE, publisherIsTieredRole(GEN.MEMBER_ROLE)));
×
426
        c.observer += runTierLabeled("observer(self,late)", graph,
×
427
                nonAdminTierUpdate(graph, -1, GEN.OBSERVER_ROLE, PUBLISHER_IS_SELF));
×
428
        return c;
×
429
    }
430

431
    /**
432
     * Cheap ASK: did any new {@code npa:RoleDeclaration} extraction land in the
433
     * load-number delta {@code (lastProcessed, ∞)}? Used by the late-arrival
434
     * trigger so an RD that arrives in the same cycle as a matching candidate
435
     * still gets validated.
436
     */
437
    boolean newRoleDeclarationsArrived(long lastProcessed) {
438
        String ask = String.format("""
×
439
                PREFIX npa: <%1$s>
440
                ASK {
441
                  GRAPH <%2$s> {
442
                    ?rd a npa:RoleDeclaration ;
443
                        npa:viaNanopub ?np .
444
                  }
445
                  GRAPH <%3$s> {
446
                    ?np npa:hasLoadNumber ?ln .
447
                    FILTER (?ln > %4$d)
448
                  }
449
                }
450
                """, NPA.NAMESPACE, SpacesVocab.SPACES_GRAPH, NPA.GRAPH, lastProcessed);
×
451
        return runAsk(ask);
×
452
    }
453

454
    // ---------------- Tier UPDATE loops ----------------
455

456
    /**
457
     * Per-tier inserted-triple tallies for one build or cycle. Counts the sum
458
     * of {@code (graphSize_after - graphSize_before)} across all iterations of
459
     * each tier's fixed-point INSERT loop — i.e. inserted *triples*, not
460
     * distinct subjects (a single RoleInstantiation insert writes 4–5 triples).
461
     *
462
     * <p>Used internally by the {@link #runIncrementalCycle structuralAdds}
463
     * boolean check (we only care whether any tier inserted at all).
464
     * Not what the log lines report: see {@link TierSubjectTotals} +
465
     * {@link #computeTierSubjectTotals} for the distinct-subject totals
466
     * surfaced to operators.
467
     */
468
    static final class TierInsertedTriples {
×
469
        int admin;
470
        int attachment;
471
        int maintainer;
472
        int member;
473
        int observer;
474
        int subSpace;
475
        int subSpacePrefix;
476
        int maintainedResource;
477
    }
478

479
    /**
480
     * Snapshot of distinct-subject totals in a space-state graph at a moment
481
     * in time. Independent of which tier-loop added each subject.
482
     */
483
    record TierSubjectTotals(long adminRIs, long attachmentRAs, long nonAdminRIs) {}
36✔
484

485
    /**
486
     * Runs the five tier loops in order: admin → {@code gen:hasRole} attachment
487
     * validation → maintainer → member → observer. Each loop iterates a SPARQL
488
     * INSERT to fixed point (no new triples added). Returns per-tier counts.
489
     *
490
     * @param graph         target space-state graph
491
     * @param lastProcessed load-number horizon; use {@code -1} for full build
492
     */
493
    TierInsertedTriples runAllTierLoops(IRI graph, long lastProcessed) {
494
        TierInsertedTriples c = new TierInsertedTriples();
×
495
        c.admin = runTierLabeled("admin", graph, adminTierUpdate(graph, lastProcessed));
×
496
        // Sub-space admit runs after admin closure has settled (Mode A + Mode B both
497
        // need the admin set). Independent of role tiers — order between subspace
498
        // and attachment / maintainer / member / observer doesn't matter.
499
        c.subSpace = runTierLabeled("subspace", graph, subSpaceAdmitUpdate(graph, lastProcessed));
×
500
        // Maintained-resource admit also depends only on the admin closure. Single
501
        // Mode A: publisher must be admin of the maintaining space. No co-declaration
502
        // partner, no URL-prefix fallback.
503
        c.maintainedResource = runTierLabeled("maintained-resource", graph,
×
504
                maintainedResourceAdmitUpdate(graph, lastProcessed));
×
505
        // URL-prefix sub-space fallback runs after the explicit-declaration admit
506
        // pass commits so the per-child suppression check sees this cycle's fresh
507
        // validations. No load filter — depends on which Spaces exist, not on
508
        // delta-arrivals; the dedup FILTER NOT EXISTS prevents re-insertion.
509
        c.subSpacePrefix = runTierLabeled("subspace-prefix", graph,
×
510
                subSpacePrefixFallbackUpdate(graph));
×
511
        c.attachment = runTierLabeled("attachment", graph,
×
512
                attachmentValidationUpdate(graph, lastProcessed));
×
513
        c.maintainer = runTierLabeled("maintainer", graph, nonAdminTierUpdate(graph, lastProcessed,
×
514
                GEN.MAINTAINER_ROLE, PUBLISHER_IS_ADMIN));
515
        // Member tier: admin OR maintainer publisher — split into two simpler updates
516
        // so the query planner doesn't struggle with the UNION.
517
        c.member = runTierLabeled("member(admin-pub)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
518
                GEN.MEMBER_ROLE, PUBLISHER_IS_ADMIN));
519
        c.member += runTierLabeled("member(maint-pub)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
520
                GEN.MEMBER_ROLE, publisherIsTieredRole(GEN.MAINTAINER_ROLE)));
×
521
        // Observer tier: self-evidence OR a downward grant from any higher tier.
522
        // ObserverRole is the default tier when a role definition omits an
523
        // explicit subclass (see "Role types" in design-space-repositories.md), so
524
        // most "X assigned Y this role" nanopubs land here. Restricting the tier
525
        // to PUBLISHER_IS_SELF would silently drop those grants. The four
526
        // sub-loops mirror the trust-state's downward-only chain: admin grants
527
        // anything; maintainers and members grant observer; everyone may
528
        // self-attest.
529
        c.observer = runTierLabeled("observer(admin-pub)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
530
                GEN.OBSERVER_ROLE, PUBLISHER_IS_ADMIN));
531
        c.observer += runTierLabeled("observer(maint-pub)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
532
                GEN.OBSERVER_ROLE, publisherIsTieredRole(GEN.MAINTAINER_ROLE)));
×
533
        c.observer += runTierLabeled("observer(member-pub)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
534
                GEN.OBSERVER_ROLE, publisherIsTieredRole(GEN.MEMBER_ROLE)));
×
535
        c.observer += runTierLabeled("observer(self)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
536
                GEN.OBSERVER_ROLE, PUBLISHER_IS_SELF));
537
        return c;
×
538
    }
539

540
    /**
541
     * Builds a publisher constraint requiring the publisher to be a validated holder
542
     * of the given tier's role (maintainer or member) in the target space.
543
     * Owns its own AccountState resolution so ?publisher is bound through the
544
     * targeted (pkh → agent) lookup rather than enumerated.
545
     */
546
    private static String publisherIsTieredRole(IRI tierClass) {
547
        return """
×
548
                ?acct a npa:AccountState ;
549
                      npa:pubkey ?pkh ;
550
                      npa:agent  ?publisher .
551
                ?tierRI a gen:RoleInstantiation ;
552
                        npa:forSpace ?space ;
553
                        npa:forAgent ?publisher .
554
                ?rdT a npa:RoleDeclaration ;
555
                     npa:hasRoleType <%1$s> .
556
                { ?tierRI npa:regularProperty ?predT . ?rdT gen:hasRegularProperty ?predT . }
557
                UNION
558
                { ?tierRI npa:inverseProperty ?predT . ?rdT gen:hasInverseProperty ?predT . }
559
                """.formatted(tierClass);
×
560
    }
561

562
    /** Wraps {@link #runTierLoop} with tier-name context for logs/exceptions. */
563
    private int runTierLabeled(String tier, IRI graph, String sparqlUpdate) {
564
        try {
565
            return runTierLoop(graph, sparqlUpdate);
×
566
        } catch (RuntimeException ex) {
×
567
            log.error("AuthorityResolver: tier={} failed with SPARQL UPDATE:\n{}\n", tier, sparqlUpdate, ex);
×
568
            throw ex;
×
569
        }
570
    }
571

572
    /**
573
     * Runs a single tier's INSERT to fixed point. Counts rows by probing
574
     * graph size before/after each INSERT; stops when the size doesn't change.
575
     *
576
     * @return total number of triples inserted by this tier across all iterations
577
     */
578
    int runTierLoop(IRI graph, String sparqlUpdate) {
579
        int total = 0;
×
580
        long before = graphSize(graph);
×
581
        while (true) {
582
            // Note: no explicit transaction wrapping here. In tests we observed that
583
            // HTTPRepository's RDF4J-transaction protocol silently no-op'd cross-graph
584
            // SPARQL UPDATEs with UNION sub-patterns inside conn.begin()/commit(),
585
            // while the same UPDATE POSTed directly to /statements applied correctly.
586
            // A bare prepareUpdate().execute() takes the direct /statements path and
587
            // runs the UPDATE atomically per SPARQL 1.1 semantics — which is all we
588
            // need; there's nothing else to commit atomically alongside the UPDATE.
589
            try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
590
                conn.prepareUpdate(QueryLanguage.SPARQL, sparqlUpdate).execute();
×
591
            }
592
            long after = graphSize(graph);
×
593
            long added = after - before;
×
594
            if (added <= 0) break;
×
595
            total += added;
×
596
            before = after;
×
597
        }
×
598
        return total;
×
599
    }
600

601
    private long graphSize(IRI graph) {
602
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
603
            return conn.size(graph);
×
604
        }
605
    }
606

607
    /**
608
     * Distinct-subject totals in the given space-state graph, broken down by
609
     * RoleInstantiation kind (admin-pinned vs not) and RoleAssignment.
610
     * Three SELECT-COUNT queries — cheap, called once per build/cycle for
611
     * the user-facing log line. Returns zeros on failure (logged) so a flaky
612
     * count read can't wedge the cycle.
613
     */
614
    TierSubjectTotals computeTierSubjectTotals(IRI graph) {
615
        long adminRIs       = countDistinctSubjects(graph, """
×
616
                ?ri a gen:RoleInstantiation ; npa:inverseProperty gen:hasAdmin .
617
                """, "ri");
618
        long attachmentRAs  = countDistinctSubjects(graph, """
×
619
                ?ra a gen:RoleAssignment .
620
                """, "ra");
621
        long nonAdminRIs    = countDistinctSubjects(graph, """
×
622
                ?ri a gen:RoleInstantiation .
623
                FILTER NOT EXISTS { ?ri npa:inverseProperty gen:hasAdmin }
624
                """, "ri");
625
        return new TierSubjectTotals(adminRIs, attachmentRAs, nonAdminRIs);
×
626
    }
627

628
    private long countDistinctSubjects(IRI graph, String wherePattern, String varName) {
629
        String query = String.format("""
×
630
                PREFIX npa: <%1$s>
631
                PREFIX gen: <%2$s>
632
                SELECT (COUNT(DISTINCT ?%3$s) AS ?n) WHERE {
633
                  GRAPH <%4$s> {
634
                    %5$s
635
                  }
636
                }
637
                """, NPA.NAMESPACE, GEN.NAMESPACE, varName, graph, wherePattern);
638
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO);
×
639
             TupleQueryResult r = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) {
×
640
            if (!r.hasNext()) return 0;
×
641
            return Long.parseLong(r.next().getBinding("n").getValue().stringValue());
×
642
        } catch (Exception ex) {
×
643
            log.warn("AuthorityResolver: countDistinctSubjects on {} failed: {}",
×
644
                    graph, ex.toString());
×
645
            return 0;
×
646
        }
647
    }
648

649
    // ---------------- SPARQL templates ----------------
650

651
    /**
652
     * Reusable invalidation filter on a bound nanopub-IRI variable. Pass the bare
653
     * variable name (no leading {@code ?}); e.g. {@code invalidationFilter("np")}
654
     * produces an outer-scoped {@code FILTER NOT EXISTS { GRAPH npa:graph
655
     * { ?_inv_np npx:invalidates ?np . } }}.
656
     *
657
     * <p>Joins on the raw {@code npx:invalidates} triple in {@code npa:graph},
658
     * which {@link com.knowledgepixels.query.NanopubLoader} writes into the
659
     * spaces repo from two complementary directions, making the filter symmetric
660
     * in load order:
661
     * <ul>
662
     *   <li>At the invalidator's own load: the loader's space-repo trigger fires
663
     *       whenever the nanopub has either its own space-relevant extractions
664
     *       OR an {@code npx:invalidates}/{@code npx:retracts}/{@code npx:supersedes}
665
     *       triple, so a pure-retraction nanopub still lands its raw triple plus
666
     *       {@code npa:hasLoadNumber} stamp in {@code npa:graph}.</li>
667
     *   <li>At the invalidated target's load (when the invalidator landed
668
     *       earlier): {@code NanopubLoader.getInvalidatingStatements} reads the
669
     *       triple back from the meta repo and mirrors it into the target's own
670
     *       write to the spaces repo.</li>
671
     * </ul>
672
     *
673
     * <p>The earlier shape joined on a structured {@code npa:Invalidation} entry
674
     * in {@code npa:spacesGraph} that was only emitted on the invalidator's side
675
     * AND only when the invalidated target's meta had already loaded, leaving a
676
     * window where a superseding nanopub loaded before its target produced no
677
     * entry and the stale row was never filtered out (see also the matching
678
     * change in the tier-specific {@code *InvalidationCheckWhere}/{@code
679
     * *InvalidationDelete} templates below).
680
     *
681
     * <p>Important: this filter must be placed OUTSIDE the surrounding
682
     * {@code GRAPH npa:spacesGraph { ... }} block, not nested inside it. When
683
     * nested, RDF4J's planner couples the FILTER NOT EXISTS evaluation into the
684
     * join order (per-row scan multiplied by the candidate set), which we
685
     * measured turning a 39ms query into a 60s+ timeout on the live observer-tier
686
     * data. Outside the GRAPH block, the planner defers the filter until
687
     * {@code ?np}/{@code ?rdNp} are bound and does a targeted index lookup.
688
     *
689
     * <p>Variable names must match {@code [A-Za-z0-9_]+} per SPARQL grammar —
690
     * embedding a {@code ?} inside {@code ?_inv_?np} would yield a parse error.
691
     */
692
    private static String invalidationFilter(String bareVarName) {
693
        return "FILTER NOT EXISTS { GRAPH <" + NPA.GRAPH + "> {"
24✔
694
                + " ?_inv_" + bareVarName
695
                + " <" + NPX.INVALIDATES + "> ?" + bareVarName + " . } }";
696
    }
697

698
    /**
699
     * Admin tier: seed from {@code npadef:...hasRootAdmin} (trusted by construction)
700
     * plus closed-over admin grants; insert any {@code gen:RoleInstantiation} with
701
     * {@code npa:inverseProperty gen:hasAdmin} whose publisher (resolved via mirrored
702
     * trust-approved AccountState) is already in the admin set.
703
     */
704
    static String adminTierUpdate(IRI graph, long lastProcessed) {
705
        // Order tuned for RDF4J's evaluator:
706
        //   1. Anchor on the small (seed UNION closed-over) set to bind ?publisher
707
        //      and ?space cheaply.
708
        //   2. Resolve ?pkh from the mirrored AccountState row (?publisher bound).
709
        //   3. Probe instantiations using the now-bound (?space, ?pkh) — targeted
710
        //      lookup, not a full RoleInstantiation scan.
711
        //   4. Load-number filter on bound ?np.
712
        //   5. Dedup at the end.
713
        return """
69✔
714
                PREFIX npa:  <%1$s>
715
                PREFIX gen:  <%2$s>
716
                INSERT { GRAPH <%3$s> {
717
                  ?ri a gen:RoleInstantiation ;
718
                      npa:forSpace ?space ;
719
                      npa:inverseProperty gen:hasAdmin ;
720
                      npa:forAgent ?agent ;
721
                      npa:viaNanopub ?np .
722
                } }
723
                WHERE {
724
                  # 1. Anchor: who is already an admin of which space?
725
                  {
726
                    # Seed branch: root-admin in a non-invalidated SpaceDefinition.
727
                    GRAPH <%4$s> {
728
                      ?def a npa:SpaceDefinition ;
729
                           npa:forSpaceRef  ?spaceRef ;
730
                           npa:hasRootAdmin ?publisher ;
731
                           npa:viaNanopub   ?defNp .
732
                      ?spaceRef npa:spaceIri ?space .
733
                    }
734
                    %7$s
735
                  }
736
                  UNION
737
                  {
738
                    # Closed-over branch: an existing admin in this space-state graph.
739
                    GRAPH <%3$s> {
740
                      ?prev a gen:RoleInstantiation ;
741
                            npa:forSpace        ?space ;
742
                            npa:inverseProperty gen:hasAdmin ;
743
                            npa:forAgent        ?publisher .
744
                    }
745
                  }
746
                  # 2. Mirror: resolve ?publisher → ?pkh via the trust-approved row.
747
                  GRAPH <%3$s> {
748
                    ?acct a npa:AccountState ;
749
                          npa:agent  ?publisher ;
750
                          npa:pubkey ?pkh .
751
                  }
752
                  # 3. Targeted instantiation lookup by space + pubkey.
753
                  GRAPH <%4$s> {
754
                    ?ri a gen:RoleInstantiation ;
755
                        npa:forSpace        ?space ;
756
                        npa:inverseProperty gen:hasAdmin ;
757
                        npa:forAgent        ?agent ;
758
                        npa:pubkeyHash      ?pkh ;
759
                        npa:viaNanopub      ?np .
760
                  }
761
                  %6$s
762
                  # 4. Load-number filter on bound ?np.
763
                  GRAPH <%8$s> {
764
                    ?np npa:hasLoadNumber ?ln .
765
                    FILTER (?ln > %5$d)
766
                  }
767
                  # 5. Dedup last.
768
                  FILTER NOT EXISTS { GRAPH <%3$s> {
769
                    ?existing a gen:RoleInstantiation ;
770
                              npa:forSpace ?space ;
771
                              npa:forAgent ?agent ;
772
                              npa:inverseProperty gen:hasAdmin .
773
                  } }
774
                }
775
                """.formatted(
3✔
776
                NPA.NAMESPACE,
777
                GEN.NAMESPACE,
778
                graph,
779
                SpacesVocab.SPACES_GRAPH,
780
                lastProcessed,
15✔
781
                invalidationFilter("np"),
15✔
782
                invalidationFilter("defNp"),
18✔
783
                NPA.GRAPH);
784
    }
785

786
    /**
787
     * {@code gen:hasRole} attachment validation: an attachment is validated iff its
788
     * publisher is already a validated admin of the target space. Adds
789
     * {@code gen:RoleAssignment} rows to the space-state graph.
790
     */
791
    static String attachmentValidationUpdate(IRI graph, long lastProcessed) {
792
        return """
69✔
793
                PREFIX npa:  <%1$s>
794
                PREFIX gen:  <%2$s>
795
                INSERT { GRAPH <%3$s> {
796
                  ?ra a gen:RoleAssignment ;
797
                      npa:forSpace ?space ;
798
                      gen:hasRole  ?role ;
799
                      npa:viaNanopub ?np .
800
                } }
801
                WHERE {
802
                  GRAPH <%4$s> {
803
                    ?ra a gen:RoleAssignment ;
804
                        npa:forSpace ?space ;
805
                        gen:hasRole  ?role ;
806
                        npa:pubkeyHash ?pkh ;
807
                        npa:viaNanopub ?np .
808
                  }
809
                  GRAPH <%7$s> {
810
                    ?np npa:hasLoadNumber ?ln .
811
                    FILTER (?ln > %5$d)
812
                  }
813
                  GRAPH <%3$s> {
814
                    ?acct a npa:AccountState ;
815
                          npa:agent  ?publisher ;
816
                          npa:pubkey ?pkh .
817
                    ?adminRI a gen:RoleInstantiation ;
818
                             npa:forSpace ?space ;
819
                             npa:inverseProperty gen:hasAdmin ;
820
                             npa:forAgent ?publisher .
821
                  }
822
                  %6$s
823
                  FILTER NOT EXISTS { GRAPH <%3$s> {
824
                    ?existing a gen:RoleAssignment ;
825
                              npa:forSpace ?space ;
826
                              gen:hasRole  ?role .
827
                  } }
828
                }
829
                """.formatted(
3✔
830
                NPA.NAMESPACE,
831
                GEN.NAMESPACE,
832
                graph,
833
                SpacesVocab.SPACES_GRAPH,
834
                lastProcessed,
15✔
835
                invalidationFilter("np"),
18✔
836
                NPA.GRAPH);
837
    }
838

839
    /**
840
     * Non-admin tier publisher constraints (inserted as a SPARQL sub-pattern).
841
     * Each constraint owns the AccountState (pkh → agent) lookup so the join
842
     * variable is bound through a targeted pattern. The observer-self variant
843
     * binds {@code npa:agent ?agent} directly — no separate {@code ?publisher}
844
     * variable, no post-join equality filter — which lets the planner anchor
845
     * the AccountState lookup on the already-bound {@code ?agent} instead of
846
     * enumerating all approved publishers and filtering at the end.
847
     */
848
    static final String PUBLISHER_IS_ADMIN = """
849
            ?acct a npa:AccountState ;
850
                  npa:pubkey ?pkh ;
851
                  npa:agent  ?publisher .
852
            ?adminRI a gen:RoleInstantiation ;
853
                     npa:forSpace ?space ;
854
                     npa:inverseProperty gen:hasAdmin ;
855
                     npa:forAgent ?publisher .
856
            """;
857

858
    /** Observer self-evidence: the assignee's own pubkey signed the instantiation. */
859
    static final String PUBLISHER_IS_SELF = """
860
            ?acct a npa:AccountState ;
861
                  npa:pubkey ?pkh ;
862
                  npa:agent  ?agent .
863
            """;
864

865
    /**
866
     * Maintainer / Member / Observer tier INSERT. Same shape: find an instantiation
867
     * whose predicate matches a RoleDeclaration of the given tier attached to the
868
     * target space, and whose publisher passes the tier-specific constraint.
869
     */
870
    static String nonAdminTierUpdate(IRI graph, long lastProcessed,
871
                                     IRI tierClass, String publisherConstraint) {
872
        // Order tuned for RDF4J's evaluator (which executes BGPs roughly in order).
873
        // The crucial choice is the *anchor*: instantiation-first plans send the
874
        // planner exploring the full ~thousands of candidate RIs and only filter
875
        // by tier at the very end. Attachment-first anchors on the small set of
876
        // gen:RoleAssignment rows already validated in this space-state graph
877
        // (~hundreds, often zero) and walks outward by bound (?role, ?space).
878
        //
879
        //   1. Anchor on RoleAssignments in this space-state graph (small).
880
        //   2. Match the tier-pinned RoleDeclaration by ?role.
881
        //   3. Pair role-decl direction to instantiation direction in one UNION
882
        //      so only (reg, reg)/(inv, inv) combos are explored.
883
        //   4. Targeted instantiation lookup — (?space, ?pred) are bound.
884
        //   5. Publisher constraint (incl. AccountState resolution).
885
        //   6. Load-number filter on bound ?np.
886
        //   7. Dedup at the end.
887
        return """
69✔
888
                PREFIX npa:  <%1$s>
889
                PREFIX gen:  <%2$s>
890
                INSERT { GRAPH <%3$s> {
891
                  ?ri a gen:RoleInstantiation ;
892
                      npa:forSpace ?space ;
893
                      npa:forAgent ?agent ;
894
                      npa:viaNanopub ?np .
895
                } }
896
                WHERE {
897
                  # 1. Anchor: validated attachments in this space-state graph.
898
                  GRAPH <%3$s> {
899
                    ?ra a gen:RoleAssignment ;
900
                        gen:hasRole  ?role ;
901
                        npa:forSpace ?space .
902
                  }
903
                  # 2. Tier-pinned RoleDeclaration (?role bound from the attachment).
904
                  GRAPH <%4$s> {
905
                    ?rd a npa:RoleDeclaration ;
906
                        npa:hasRoleType <%7$s> ;
907
                        npa:role        ?role ;
908
                        npa:viaNanopub  ?rdNp .
909
                    # 3. Pair direction so only matching combos are explored.
910
                    {
911
                      ?rd gen:hasRegularProperty ?pred .
912
                      ?ri npa:regularProperty    ?pred .
913
                    }
914
                    UNION
915
                    {
916
                      ?rd gen:hasInverseProperty ?pred .
917
                      ?ri npa:inverseProperty    ?pred .
918
                    }
919
                    # 4. Targeted instantiation lookup — (?space, ?pred) bound.
920
                    ?ri a gen:RoleInstantiation ;
921
                        npa:forSpace   ?space ;
922
                        npa:forAgent   ?agent ;
923
                        npa:pubkeyHash ?pkh ;
924
                        npa:viaNanopub ?np .
925
                  }
926
                  # 5. Publisher constraint (incl. AccountState resolution).
927
                  GRAPH <%3$s> {
928
                    %9$s
929
                  }
930
                  # 6. Load-number filter on bound ?np.
931
                  GRAPH <%10$s> {
932
                    ?np npa:hasLoadNumber ?ln .
933
                    FILTER (?ln > %5$d)
934
                  }
935
                  # 7. Invalidation filters — outside the GRAPH block so the
936
                  #    planner defers them until ?rdNp/?np are bound.
937
                  %8$s
938
                  %6$s
939
                  # 8. Dedup last.
940
                  FILTER NOT EXISTS { GRAPH <%3$s> {
941
                    ?existing a gen:RoleInstantiation ;
942
                              npa:forSpace ?space ;
943
                              npa:forAgent ?agent ;
944
                              npa:viaNanopub ?np .
945
                  } }
946
                }
947
                """.formatted(
3✔
948
                NPA.NAMESPACE,
949
                GEN.NAMESPACE,
950
                graph,
951
                SpacesVocab.SPACES_GRAPH,
952
                lastProcessed,
15✔
953
                invalidationFilter("np"),
27✔
954
                tierClass,
955
                invalidationFilter("rdNp"),
30✔
956
                publisherConstraint,
957
                NPA.GRAPH);
958
    }
959

960
    /**
961
     * Sub-space admit pass. Copies validated {@code npa:SubSpaceDeclaration}
962
     * extraction rows into the space-state graph (preserving the {@code npasub:}
963
     * subject) and emits convenience {@code <child> npa:isSubSpaceOf <parent>} and
964
     * {@code <parent> npa:hasSubSpace <child>} direct triples. Two satisfaction
965
     * modes joined by UNION:
966
     * <ul>
967
     *   <li>Mode A — the declaration's publisher is a validated admin of both the
968
     *       child and the parent space.</li>
969
     *   <li>Mode B — a different non-invalidated declaration for the same
970
     *       {@code (child, parent)} pair exists, and the two publishers between
971
     *       them cover both admin sides (i.e. one of them is admin of the child,
972
     *       one of them is admin of the parent — possibly the same one twice if
973
     *       both happen to be admin of both).</li>
974
     * </ul>
975
     *
976
     * <p>Mode-B late-arrival: when only the partner declaration is new in this
977
     * cycle (the primary is older than {@code lastProcessed}), the load-number
978
     * filter on {@code ?np} excludes the candidate. The late-arrival sweep
979
     * ({@link #runDownstreamWithoutLoadFilter}) re-runs this pass without the
980
     * load filter and catches it.
981
     */
982
    static String subSpaceAdmitUpdate(IRI graph, long lastProcessed) {
983
        return """
69✔
984
                PREFIX npa: <%1$s>
985
                PREFIX gen: <%2$s>
986
                INSERT { GRAPH <%3$s> {
987
                  ?d a npa:SubSpaceDeclaration ;
988
                     npa:childSpace  ?child ;
989
                     npa:parentSpace ?parent ;
990
                     npa:viaNanopub  ?np .
991
                  ?child  npa:isSubSpaceOf ?parent .
992
                  ?parent npa:hasSubSpace  ?child  .
993
                } }
994
                WHERE {
995
                  # 1. Anchor: candidate declarations from the extraction graph.
996
                  GRAPH <%4$s> {
997
                    ?d a npa:SubSpaceDeclaration ;
998
                       npa:childSpace  ?child ;
999
                       npa:parentSpace ?parent ;
1000
                       npa:pubkeyHash  ?pkh ;
1001
                       npa:viaNanopub  ?np .
1002
                  }
1003
                  # 2. Mirror: resolve ?pkh → ?publisher via the trust-approved row.
1004
                  GRAPH <%3$s> {
1005
                    ?acct a npa:AccountState ;
1006
                          npa:pubkey ?pkh ;
1007
                          npa:agent  ?publisher .
1008
                  }
1009
                  # 3. Authority gate.
1010
                  {
1011
                    # Mode A — publisher is admin of BOTH child and parent.
1012
                    FILTER EXISTS { GRAPH <%3$s> {
1013
                      ?riC a gen:RoleInstantiation ;
1014
                           npa:inverseProperty gen:hasAdmin ;
1015
                           npa:forSpace ?child ;
1016
                           npa:forAgent ?publisher .
1017
                    } }
1018
                    FILTER EXISTS { GRAPH <%3$s> {
1019
                      ?riP a gen:RoleInstantiation ;
1020
                           npa:inverseProperty gen:hasAdmin ;
1021
                           npa:forSpace ?parent ;
1022
                           npa:forAgent ?publisher .
1023
                    } }
1024
                  }
1025
                  UNION
1026
                  {
1027
                    # Mode B — co-declaration whose publisher covers the side this
1028
                    # one's publisher doesn't. Between {publisher, publisher2},
1029
                    # both admin sides must be covered.
1030
                    GRAPH <%4$s> {
1031
                      ?d2 a npa:SubSpaceDeclaration ;
1032
                          npa:childSpace  ?child ;
1033
                          npa:parentSpace ?parent ;
1034
                          npa:pubkeyHash  ?pkh2 ;
1035
                          npa:viaNanopub  ?np2 .
1036
                      FILTER (?np2 != ?np)
1037
                    }
1038
                    %8$s
1039
                    GRAPH <%3$s> {
1040
                      ?acct2 a npa:AccountState ;
1041
                             npa:pubkey ?pkh2 ;
1042
                             npa:agent  ?publisher2 .
1043
                    }
1044
                    FILTER EXISTS { GRAPH <%3$s> {
1045
                      ?riA a gen:RoleInstantiation ;
1046
                           npa:inverseProperty gen:hasAdmin ;
1047
                           npa:forSpace ?child .
1048
                      { ?riA npa:forAgent ?publisher } UNION { ?riA npa:forAgent ?publisher2 }
1049
                    } }
1050
                    FILTER EXISTS { GRAPH <%3$s> {
1051
                      ?riB a gen:RoleInstantiation ;
1052
                           npa:inverseProperty gen:hasAdmin ;
1053
                           npa:forSpace ?parent .
1054
                      { ?riB npa:forAgent ?publisher } UNION { ?riB npa:forAgent ?publisher2 }
1055
                    } }
1056
                  }
1057
                  # 4. Invalidation filter on the primary declaration's nanopub.
1058
                  %6$s
1059
                  # 5. Load-number filter on bound ?np.
1060
                  GRAPH <%7$s> {
1061
                    ?np npa:hasLoadNumber ?ln .
1062
                    FILTER (?ln > %5$d)
1063
                  }
1064
                  # 6. Dedup last.
1065
                  FILTER NOT EXISTS { GRAPH <%3$s> {
1066
                    ?d a npa:SubSpaceDeclaration .
1067
                  } }
1068
                }
1069
                """.formatted(
3✔
1070
                NPA.NAMESPACE,
1071
                GEN.NAMESPACE,
1072
                graph,
1073
                SpacesVocab.SPACES_GRAPH,
1074
                lastProcessed,
15✔
1075
                invalidationFilter("np"),
27✔
1076
                NPA.GRAPH,
1077
                invalidationFilter("np2"));
6✔
1078
    }
1079

1080
    /**
1081
     * Maintained-resource admit pass. Copies validated
1082
     * {@code npa:MaintainedResourceDeclaration} extraction rows into the space-state
1083
     * graph (preserving the {@code npamrd:} subject) and emits convenience
1084
     * {@code <r> npa:isMaintainedBy <s>} and {@code <s> npa:hasMaintainedResource <r>}
1085
     * direct triples. Single satisfaction mode:
1086
     * <ul>
1087
     *   <li>Mode A — the declaration's publisher is a validated admin of the
1088
     *       maintaining space.</li>
1089
     * </ul>
1090
     *
1091
     * <p>No Mode B because only one space is involved; the two-sides-must-be-covered
1092
     * concern that drives sub-space Mode B doesn't apply. Late-arrival is still
1093
     * possible (declaration lands before the publisher's admin grant becomes valid):
1094
     * the load-number filter on {@code ?np} excludes the candidate, and the
1095
     * late-arrival sweep ({@link #runDownstreamWithoutLoadFilter}) re-runs this pass
1096
     * without the load filter and catches it.
1097
     */
1098
    static String maintainedResourceAdmitUpdate(IRI graph, long lastProcessed) {
1099
        return """
69✔
1100
                PREFIX npa: <%1$s>
1101
                PREFIX gen: <%2$s>
1102
                INSERT { GRAPH <%3$s> {
1103
                  ?d a npa:MaintainedResourceDeclaration ;
1104
                     npa:resourceIri     ?r ;
1105
                     npa:maintainerSpace ?s ;
1106
                     npa:viaNanopub      ?np .
1107
                  ?r npa:isMaintainedBy        ?s .
1108
                  ?s npa:hasMaintainedResource ?r .
1109
                } }
1110
                WHERE {
1111
                  # 1. Anchor: candidate declarations from the extraction graph.
1112
                  GRAPH <%4$s> {
1113
                    ?d a npa:MaintainedResourceDeclaration ;
1114
                       npa:resourceIri     ?r ;
1115
                       npa:maintainerSpace ?s ;
1116
                       npa:pubkeyHash      ?pkh ;
1117
                       npa:viaNanopub      ?np .
1118
                  }
1119
                  # 2. Mirror: resolve ?pkh → ?publisher via the trust-approved row.
1120
                  GRAPH <%3$s> {
1121
                    ?acct a npa:AccountState ;
1122
                          npa:pubkey ?pkh ;
1123
                          npa:agent  ?publisher .
1124
                    # 3. Authority gate (Mode A only): publisher is admin of the
1125
                    #    maintaining space.
1126
                    ?riA a gen:RoleInstantiation ;
1127
                         npa:inverseProperty gen:hasAdmin ;
1128
                         npa:forSpace ?s ;
1129
                         npa:forAgent ?publisher .
1130
                  }
1131
                  # 4. Invalidation filter on the declaration's nanopub.
1132
                  %6$s
1133
                  # 5. Load-number filter on bound ?np.
1134
                  GRAPH <%7$s> {
1135
                    ?np npa:hasLoadNumber ?ln .
1136
                    FILTER (?ln > %5$d)
1137
                  }
1138
                  # 6. Dedup last.
1139
                  FILTER NOT EXISTS { GRAPH <%3$s> {
1140
                    ?d a npa:MaintainedResourceDeclaration .
1141
                  } }
1142
                }
1143
                """.formatted(
3✔
1144
                NPA.NAMESPACE,
1145
                GEN.NAMESPACE,
1146
                graph,
1147
                SpacesVocab.SPACES_GRAPH,
1148
                lastProcessed,
15✔
1149
                invalidationFilter("np"),
18✔
1150
                NPA.GRAPH);
1151
    }
1152

1153
    /**
1154
     * URL-prefix sub-space fallback admit pass. For every pair of {@code SpaceRef}
1155
     * aggregates where the child's {@code npa:hasIdPrefix} matches the parent's
1156
     * {@code npa:spaceIri}, emits convenience {@code <child> npa:isSubSpaceOf <parent>}
1157
     * and {@code <parent> npa:hasSubSpace <child>} direct triples plus a reified
1158
     * {@code npa:DerivedSubSpaceLink} tag carrying {@code npa:derivationKind
1159
     * npa:byUrlPrefix} so consumers can hide derived edges.
1160
     *
1161
     * <p>Per-child suppression: any validated {@code npa:SubSpaceDeclaration} on the
1162
     * child in {@code npass:<…>} suppresses every fallback edge for that child.
1163
     * Suppression checks the validated set (not raw extraction-graph declarations)
1164
     * so an unapproved or in-flight Mode B declaration doesn't silently hide both
1165
     * the URL-prefix fallback and the (still-invalid) explicit relation.
1166
     *
1167
     * <p>Run order: must run after {@link #subSpaceAdmitUpdate} commits in the
1168
     * same cycle so the suppression check sees this cycle's freshly-validated
1169
     * declarations.
1170
     *
1171
     * <p>No load-number filter: the fallback depends on which Spaces exist (parent
1172
     * + child {@code SpaceRef}s), not on which were just added. Always full-scan;
1173
     * the dedup {@code FILTER NOT EXISTS} on the tag IRI prevents re-insertion.
1174
     *
1175
     * <p>No invalidation handling: derived edges have no source nanopub. Two
1176
     * staleness modes: (a) child later gets first validated declaration → old
1177
     * derived edges stay sticky until the next periodic rebuild (same policy as
1178
     * admin-RI invalidation); (b) child loses last validated declaration → the
1179
     * regular fallback pass on the next cycle re-engages, adds derived edges
1180
     * incrementally, no rebuild needed.
1181
     */
1182
    static String subSpacePrefixFallbackUpdate(IRI graph) {
1183
        return """
48✔
1184
                PREFIX npa: <%1$s>
1185
                INSERT { GRAPH <%2$s> {
1186
                  ?child  npa:isSubSpaceOf ?parent .
1187
                  ?parent npa:hasSubSpace  ?child  .
1188
                  ?tagIri a npa:DerivedSubSpaceLink ;
1189
                          npa:childSpace     ?child ;
1190
                          npa:parentSpace    ?parent ;
1191
                          npa:derivationKind npa:byUrlPrefix .
1192
                } }
1193
                WHERE {
1194
                  # 1. Anchor: child SpaceRef → its path-prefixes (extracted at load
1195
                  #    time from the Space IRI; see SpacesExtractor.enumerateIdPrefixes).
1196
                  GRAPH <%3$s> {
1197
                    ?childRef  npa:spaceIri    ?child ;
1198
                               npa:hasIdPrefix ?parent .
1199
                    # 2. Parent SpaceRef must exist for the same IRI as the prefix.
1200
                    ?parentRef npa:spaceIri    ?parent .
1201
                  }
1202
                  # 3. Suppress fallback for any child that has a validated declaration
1203
                  #    in this state graph. Per-child, all-or-nothing.
1204
                  FILTER NOT EXISTS {
1205
                    GRAPH <%2$s> {
1206
                      ?d a npa:SubSpaceDeclaration ;
1207
                         npa:childSpace ?child .
1208
                    }
1209
                  }
1210
                  # 4. Mint a deterministic tag IRI per (child, parent).
1211
                  BIND(IRI(CONCAT("http://purl.org/nanopub/admin/derivedlink/",
1212
                                  MD5(CONCAT(STR(?child), "|", STR(?parent))))) AS ?tagIri)
1213
                  # 5. Dedup: don't re-insert if this tag is already present.
1214
                  FILTER NOT EXISTS {
1215
                    GRAPH <%2$s> {
1216
                      ?tagIri a npa:DerivedSubSpaceLink .
1217
                    }
1218
                  }
1219
                }
1220
                """.formatted(
3✔
1221
                NPA.NAMESPACE,
1222
                graph,
1223
                SpacesVocab.SPACES_GRAPH);
1224
    }
1225

1226
    // ---------------- Invalidation templates (incremental cycle) ----------------
1227

1228
    /**
1229
     * WHERE clause shared by the admin-RI invalidation ASK precheck and the
1230
     * matching DELETE. Identifies admin-tier {@code gen:RoleInstantiation} rows
1231
     * in the space-state graph whose {@code npa:viaNanopub} is the target of an
1232
     * {@code npx:invalidates} triple in {@code npa:graph} whose subject nanopub
1233
     * has a load number in {@code (lastProcessed, ∞)}.
1234
     */
1235
    static String adminInvalidationCheckWhere(IRI graph, long lastProcessed) {
1236
        return String.format("""
60✔
1237
                  GRAPH <%1$s> {
1238
                    ?ri a gen:RoleInstantiation ;
1239
                        npa:inverseProperty gen:hasAdmin ;
1240
                        npa:viaNanopub ?np .
1241
                  }
1242
                  GRAPH <%2$s> {
1243
                    ?invNp <%3$s> ?np ;
1244
                           npa:hasLoadNumber ?ln .
1245
                    FILTER (?ln > %4$d)
1246
                  }
1247
                """, graph, NPA.GRAPH, NPX.INVALIDATES, lastProcessed);
6✔
1248
    }
1249

1250
    /** DELETE template for admin-tier RoleInstantiations whose source nanopub was invalidated. */
1251
    static String adminInvalidationDelete(IRI graph, long lastProcessed) {
1252
        return String.format("""
63✔
1253
                PREFIX npa: <%1$s>
1254
                PREFIX gen: <%2$s>
1255
                DELETE { GRAPH <%3$s> {
1256
                  ?ri ?p ?o .
1257
                } }
1258
                WHERE {
1259
                  GRAPH <%3$s> { ?ri ?p ?o . }
1260
                %4$s
1261
                }
1262
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
1263
                adminInvalidationCheckWhere(graph, lastProcessed));
6✔
1264
    }
1265

1266
    /** WHERE clause for RoleAssignment invalidation. */
1267
    static String roleAssignmentInvalidationCheckWhere(IRI graph, long lastProcessed) {
1268
        return String.format("""
60✔
1269
                  GRAPH <%1$s> {
1270
                    ?ra a gen:RoleAssignment ;
1271
                        npa:viaNanopub ?np .
1272
                  }
1273
                  GRAPH <%2$s> {
1274
                    ?invNp <%3$s> ?np ;
1275
                           npa:hasLoadNumber ?ln .
1276
                    FILTER (?ln > %4$d)
1277
                  }
1278
                """, graph, NPA.GRAPH, NPX.INVALIDATES, lastProcessed);
6✔
1279
    }
1280

1281
    /** DELETE template for RoleAssignments whose source nanopub was invalidated. */
1282
    static String roleAssignmentInvalidationDelete(IRI graph, long lastProcessed) {
1283
        return String.format("""
63✔
1284
                PREFIX npa: <%1$s>
1285
                PREFIX gen: <%2$s>
1286
                DELETE { GRAPH <%3$s> {
1287
                  ?ra ?p ?o .
1288
                } }
1289
                WHERE {
1290
                  GRAPH <%3$s> { ?ra ?p ?o . }
1291
                %4$s
1292
                }
1293
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
1294
                roleAssignmentInvalidationCheckWhere(graph, lastProcessed));
6✔
1295
    }
1296

1297
    /**
1298
     * WHERE clause for RoleDeclaration invalidation. ASK-only (no DELETE):
1299
     * RoleDeclarations live in {@code npa:spacesGraph} and aren't materialized
1300
     * into the space-state graph, so there's nothing to remove from the
1301
     * space-state. The ASK still flips {@code npa:needsFullRebuild} because
1302
     * sticky downstream RIs that were derived under the now-invalidated RD
1303
     * need a from-scratch recompute.
1304
     */
1305
    static String roleDeclarationInvalidationCheckWhere(long lastProcessed) {
1306
        return String.format("""
60✔
1307
                  GRAPH <%1$s> {
1308
                    ?rd a npa:RoleDeclaration ;
1309
                        npa:viaNanopub ?np .
1310
                  }
1311
                  GRAPH <%2$s> {
1312
                    ?invNp <%3$s> ?np ;
1313
                           npa:hasLoadNumber ?ln .
1314
                    FILTER (?ln > %4$d)
1315
                  }
1316
                """, SpacesVocab.SPACES_GRAPH, NPA.GRAPH, NPX.INVALIDATES, lastProcessed);
6✔
1317
    }
1318

1319
    /**
1320
     * DELETE template for non-admin (leaf-tier) RoleInstantiations whose source
1321
     * nanopub was invalidated. Identified as {@code gen:RoleInstantiation} rows
1322
     * lacking the admin-pinning {@code npa:inverseProperty gen:hasAdmin} triple.
1323
     * No flag is set; leaf-tier removals are recoverable on the next cycle.
1324
     */
1325
    static String leafTierInvalidationDelete(IRI graph, long lastProcessed) {
1326
        return String.format("""
84✔
1327
                PREFIX npa: <%1$s>
1328
                PREFIX gen: <%2$s>
1329
                DELETE { GRAPH <%3$s> {
1330
                  ?ri ?p ?o .
1331
                } }
1332
                WHERE {
1333
                  GRAPH <%3$s> {
1334
                    ?ri a gen:RoleInstantiation ;
1335
                        npa:viaNanopub ?np .
1336
                    FILTER NOT EXISTS { ?ri npa:inverseProperty gen:hasAdmin }
1337
                    ?ri ?p ?o .
1338
                  }
1339
                  GRAPH <%4$s> {
1340
                    ?invNp <%5$s> ?np ;
1341
                           npa:hasLoadNumber ?ln .
1342
                    FILTER (?ln > %6$d)
1343
                  }
1344
                }
1345
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
1346
                NPA.GRAPH, NPX.INVALIDATES, lastProcessed);
6✔
1347
    }
1348

1349
    /**
1350
     * WHERE clause shared by the sub-space invalidation ASK precheck and the
1351
     * matching DELETE. Identifies validated {@code npa:SubSpaceDeclaration} rows
1352
     * in the space-state graph whose {@code npa:viaNanopub} is the target of an
1353
     * {@code npx:invalidates} triple in {@code npa:graph} whose subject nanopub
1354
     * has a load number in {@code (lastProcessed, ∞)}.
1355
     */
1356
    static String subSpaceInvalidationCheckWhere(IRI graph, long lastProcessed) {
1357
        return String.format("""
60✔
1358
                  GRAPH <%1$s> {
1359
                    ?d a npa:SubSpaceDeclaration ;
1360
                       npa:viaNanopub ?np .
1361
                  }
1362
                  GRAPH <%2$s> {
1363
                    ?invNp <%3$s> ?np ;
1364
                           npa:hasLoadNumber ?ln .
1365
                    FILTER (?ln > %4$d)
1366
                  }
1367
                """, graph, NPA.GRAPH, NPX.INVALIDATES, lastProcessed);
6✔
1368
    }
1369

1370
    /**
1371
     * DELETE template for validated {@code npa:SubSpaceDeclaration} rows whose
1372
     * source nanopub was invalidated. Removes the per-declaration row by subject;
1373
     * the convenience direct triples ({@code <child> npa:isSubSpaceOf <parent>}
1374
     * and inverse) are left sticky and cleaned by the next periodic full rebuild
1375
     * (same staleness policy as admin-RI invalidation — see {@code
1376
     * doc/design-space-repositories.md} on the structural-rebuild flag).
1377
     */
1378
    static String subSpaceInvalidationDelete(IRI graph, long lastProcessed) {
1379
        return String.format("""
63✔
1380
                PREFIX npa: <%1$s>
1381
                PREFIX gen: <%2$s>
1382
                DELETE { GRAPH <%3$s> {
1383
                  ?d ?p ?o .
1384
                } }
1385
                WHERE {
1386
                  GRAPH <%3$s> { ?d ?p ?o . }
1387
                %4$s
1388
                }
1389
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
1390
                subSpaceInvalidationCheckWhere(graph, lastProcessed));
6✔
1391
    }
1392

1393
    /**
1394
     * DELETE template for validated {@code npa:MaintainedResourceDeclaration} rows
1395
     * whose source nanopub was invalidated. Removes the per-declaration row by
1396
     * subject; the convenience direct triples ({@code <r> npa:isMaintainedBy <s>}
1397
     * and inverse) are left sticky and cleaned by the next periodic full rebuild
1398
     * (same staleness policy as sub-space declaration invalidation, but without
1399
     * the structural-rebuild flag — maintained-resource is a leaf relation, no
1400
     * downstream consumers depend on its closure).
1401
     */
1402
    static String maintainedResourceInvalidationDelete(IRI graph, long lastProcessed) {
1403
        return String.format("""
84✔
1404
                PREFIX npa: <%1$s>
1405
                PREFIX gen: <%2$s>
1406
                DELETE { GRAPH <%3$s> {
1407
                  ?d ?p ?o .
1408
                } }
1409
                WHERE {
1410
                  GRAPH <%3$s> {
1411
                    ?d a npa:MaintainedResourceDeclaration ;
1412
                       npa:viaNanopub ?np .
1413
                    ?d ?p ?o .
1414
                  }
1415
                  GRAPH <%4$s> {
1416
                    ?invNp <%5$s> ?np ;
1417
                           npa:hasLoadNumber ?ln .
1418
                    FILTER (?ln > %6$d)
1419
                  }
1420
                }
1421
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
1422
                NPA.GRAPH, NPX.INVALIDATES, lastProcessed);
6✔
1423
    }
1424

1425
    /** Wraps an ASK by joining the shared prefixes. */
1426
    private boolean wouldInvalidate(IRI graph, long lastProcessed,
1427
                                    boolean adminPinned, String whereClause) {
1428
        // adminPinned is informational only — kept to make call sites read clearly;
1429
        // the WHERE clause already encodes the kind via its own type predicates.
1430
        String ask = String.format("""
×
1431
                PREFIX npa: <%1$s>
1432
                PREFIX gen: <%2$s>
1433
                ASK { %3$s }
1434
                """, NPA.NAMESPACE, GEN.NAMESPACE, whereClause);
1435
        return runAsk(ask);
×
1436
    }
1437

1438
    private boolean runAsk(String sparql) {
1439
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1440
            return conn.prepareBooleanQuery(QueryLanguage.SPARQL, sparql).evaluate();
×
1441
        }
1442
    }
1443

1444
    private void executeUpdate(String sparqlUpdate) {
1445
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1446
            conn.prepareUpdate(QueryLanguage.SPARQL, sparqlUpdate).execute();
×
1447
        }
1448
    }
×
1449

1450
    // ---------------- Mirror step ----------------
1451

1452
    /**
1453
     * Copies trust-approved {@code npa:AccountState} rows from {@code npat:<T>}
1454
     * in the {@code trust} repo into {@code newGraph} in the {@code spaces} repo,
1455
     * inside one spaces-side serializable transaction.
1456
     *
1457
     * @return number of rows mirrored (useful for metrics / logging)
1458
     */
1459
    int mirrorTrustState(String trustStateHash, IRI newGraph) {
1460
        IRI trustStateIri = NPAT.forHash(trustStateHash);
×
1461
        int count = 0;
×
1462
        try (RepositoryConnection trustConn = TripleStore.get().getRepoConnection(TRUST_REPO);
×
1463
             RepositoryConnection spacesConn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1464
            trustConn.begin(IsolationLevels.READ_COMMITTED);
×
1465
            spacesConn.begin(IsolationLevels.SERIALIZABLE);
×
1466
            // Walk rdf:type triples in the trust state's graph; for each AccountState,
1467
            // check status and copy the approved ones verbatim (minus status-specific
1468
            // detail triples, which we don't need for validation).
1469
            try (RepositoryResult<Statement> typeRows = trustConn.getStatements(
×
1470
                    null, RDF.TYPE, NPA_ACCOUNT_STATE, trustStateIri)) {
1471
                while (typeRows.hasNext()) {
×
1472
                    Statement st = typeRows.next();
×
1473
                    if (!(st.getSubject() instanceof IRI accountStateIri)) continue;
×
1474
                    Value status = trustConn.getStatements(accountStateIri, NPA_TRUST_STATUS, null, trustStateIri)
×
1475
                            .stream().findFirst().map(Statement::getObject).orElse(null);
×
1476
                    if (!(status instanceof IRI statusIri) || !APPROVED_SET.contains(statusIri)) continue;
×
1477
                    Value agent = trustConn.getStatements(accountStateIri, NPA_AGENT, null, trustStateIri)
×
1478
                            .stream().findFirst().map(Statement::getObject).orElse(null);
×
1479
                    Value pubkey = trustConn.getStatements(accountStateIri, NPA_PUBKEY, null, trustStateIri)
×
1480
                            .stream().findFirst().map(Statement::getObject).orElse(null);
×
1481
                    if (agent == null || pubkey == null) {
×
1482
                        log.warn("AuthorityResolver.mirror: account {} missing agent or pubkey; skipping",
×
1483
                                accountStateIri);
1484
                        continue;
×
1485
                    }
1486
                    spacesConn.add(accountStateIri, RDF.TYPE, NPA_ACCOUNT_STATE, newGraph);
×
1487
                    spacesConn.add(accountStateIri, NPA_AGENT, agent, newGraph);
×
1488
                    spacesConn.add(accountStateIri, NPA_PUBKEY, pubkey, newGraph);
×
1489
                    spacesConn.add(accountStateIri, NPA_TRUST_STATUS, statusIri, newGraph);
×
1490
                    count++;
×
1491
                }
×
1492
            }
1493
            // Mirror canonical foaf:name triples for approved agents. The trust
1494
            // loader emits one per agent (across approved keys, MAX(ratio) wins).
1495
            // Copying them into the space-state graph means consumers reading
1496
            // ?agent foaf:name ?n inside the state graph hit local data, with no
1497
            // cross-repo SERVICE.
1498
            try (RepositoryResult<Statement> nameRows = trustConn.getStatements(
×
1499
                    null, FOAF.NAME, null, trustStateIri)) {
1500
                while (nameRows.hasNext()) {
×
1501
                    Statement st = nameRows.next();
×
1502
                    spacesConn.add(st.getSubject(), st.getPredicate(), st.getObject(), newGraph);
×
1503
                }
×
1504
            }
1505
            spacesConn.commit();
×
1506
            trustConn.commit();
×
1507
        }
1508
        return count;
×
1509
    }
1510

1511
    // ---------------- Pointer + counter helpers ----------------
1512

1513
    /**
1514
     * Reads the current {@code npa:hasCurrentSpaceState} pointer from the
1515
     * {@code npa:graph} admin graph of the {@code spaces} repo. Returns
1516
     * {@code null} if no pointer exists yet.
1517
     */
1518
    IRI getCurrentSpaceStateGraph() {
1519
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1520
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
1521
                    SpacesVocab.HAS_CURRENT_SPACE_STATE);
1522
            return (v instanceof IRI iri) ? iri : null;
×
1523
        } catch (Exception ex) {
×
1524
            log.warn("AuthorityResolver: failed to read hasCurrentSpaceState pointer: {}", ex.toString());
×
1525
            return null;
×
1526
        }
1527
    }
1528

1529
    long getCurrentLoadCounter() {
1530
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1531
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
1532
                    SpacesVocab.CURRENT_LOAD_COUNTER);
1533
            if (v == null) return 0;
×
1534
            try {
1535
                return Long.parseLong(v.stringValue());
×
1536
            } catch (NumberFormatException ex) {
×
1537
                log.warn("AuthorityResolver: non-numeric currentLoadCounter: {}", v);
×
1538
                return 0;
×
1539
            }
1540
        } catch (Exception ex) {
×
1541
            log.warn("AuthorityResolver: failed to read currentLoadCounter: {}", ex.toString());
×
1542
            return 0;
×
1543
        }
1544
    }
1545

1546
    /**
1547
     * Atomic pointer flip: a single SPARQL {@code DELETE … INSERT … WHERE}
1548
     * replaces the old pointer with the new one in one statement, so readers
1549
     * never see a zero-pointer window.
1550
     */
1551
    void flipPointer(IRI newGraph) {
1552
        String update = String.format("""
×
1553
                DELETE { GRAPH <%s> { <%s> <%s> ?old } }
1554
                INSERT { GRAPH <%s> { <%s> <%s> <%s> } }
1555
                WHERE  { OPTIONAL { GRAPH <%s> { <%s> <%s> ?old } } }
1556
                """,
1557
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.HAS_CURRENT_SPACE_STATE,
1558
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.HAS_CURRENT_SPACE_STATE, newGraph,
1559
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.HAS_CURRENT_SPACE_STATE);
1560
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1561
            conn.begin(IsolationLevels.SERIALIZABLE);
×
1562
            conn.prepareUpdate(QueryLanguage.SPARQL, update).execute();
×
1563
            conn.commit();
×
1564
        }
1565
    }
×
1566

1567
    void writeProcessedUpTo(IRI graph, long loadCounter) {
1568
        String update = String.format("""
×
1569
                DELETE { GRAPH <%s> { <%s> <%s> ?old } }
1570
                INSERT { GRAPH <%s> { <%s> <%s> "%d"^^<http://www.w3.org/2001/XMLSchema#long> } }
1571
                WHERE  { OPTIONAL { GRAPH <%s> { <%s> <%s> ?old } } }
1572
                """,
1573
                graph, graph, SpacesVocab.PROCESSED_UP_TO,
1574
                graph, graph, SpacesVocab.PROCESSED_UP_TO, loadCounter,
×
1575
                graph, graph, SpacesVocab.PROCESSED_UP_TO);
1576
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1577
            conn.begin(IsolationLevels.SERIALIZABLE);
×
1578
            conn.prepareUpdate(QueryLanguage.SPARQL, update).execute();
×
1579
            conn.commit();
×
1580
        }
1581
    }
×
1582

1583
    /**
1584
     * Reads {@code processedUpTo} from the given space-state graph.
1585
     * Returns {@code -1} if absent (graph not fully built yet).
1586
     */
1587
    long readProcessedUpTo(IRI graph) {
1588
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1589
            String query = String.format(
×
1590
                    "SELECT ?n WHERE { GRAPH <%s> { <%s> <%s> ?n } }",
1591
                    graph, graph, SpacesVocab.PROCESSED_UP_TO);
1592
            try (TupleQueryResult r = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) {
×
1593
                if (!r.hasNext()) return -1;
×
1594
                BindingSet b = r.next();
×
1595
                return Long.parseLong(b.getBinding("n").getValue().stringValue());
×
1596
            }
×
1597
        } catch (Exception ex) {
×
1598
            log.warn("AuthorityResolver: failed to read processedUpTo for {}: {}", graph, ex.toString());
×
1599
            return -1;
×
1600
        }
1601
    }
1602

1603
    /**
1604
     * Reads the {@code npa:needsFullRebuild} flag (boolean literal) from
1605
     * {@code npa:graph} in the {@code spaces} repo. Defaults to {@code false}
1606
     * when the triple is absent.
1607
     */
1608
    boolean readNeedsFullRebuild() {
1609
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1610
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
1611
                    SpacesVocab.NEEDS_FULL_REBUILD);
1612
            return v != null && Boolean.parseBoolean(v.stringValue());
×
1613
        } catch (Exception ex) {
×
1614
            log.warn("AuthorityResolver: failed to read needsFullRebuild: {}", ex.toString());
×
1615
            return false;
×
1616
        }
1617
    }
1618

1619
    void setNeedsFullRebuild() {
1620
        writeNeedsFullRebuild(true);
×
1621
    }
×
1622

1623
    void clearNeedsFullRebuild() {
1624
        writeNeedsFullRebuild(false);
×
1625
    }
×
1626

1627
    private void writeNeedsFullRebuild(boolean value) {
1628
        String update = String.format("""
×
1629
                DELETE { GRAPH <%s> { <%s> <%s> ?old } }
1630
                INSERT { GRAPH <%s> { <%s> <%s> "%s"^^<http://www.w3.org/2001/XMLSchema#boolean> } }
1631
                WHERE  { OPTIONAL { GRAPH <%s> { <%s> <%s> ?old } } }
1632
                """,
1633
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.NEEDS_FULL_REBUILD,
1634
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.NEEDS_FULL_REBUILD, value,
×
1635
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.NEEDS_FULL_REBUILD);
1636
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1637
            conn.begin(IsolationLevels.SERIALIZABLE);
×
1638
            conn.prepareUpdate(QueryLanguage.SPARQL, update).execute();
×
1639
            conn.commit();
×
1640
        }
1641
    }
×
1642

1643
    void dropGraph(IRI graph) {
1644
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1645
            conn.begin(IsolationLevels.SERIALIZABLE);
×
1646
            conn.clear(graph);
×
1647
            conn.commit();
×
1648
            log.info("AuthorityResolver: dropped old space-state graph {}", graph);
×
1649
        }
1650
    }
×
1651

1652
    // ---------------- Trust-repo pointer lookup (used by TrustStateRegistry's bootstrap) ----------------
1653

1654
    /**
1655
     * Queries the {@code trust} repo directly for the current trust-state hash.
1656
     * Prefer {@link TrustStateRegistry#getCurrentHash()} in normal operation —
1657
     * this helper exists for tests and diagnostics.
1658
     *
1659
     * @return the current trust-state hash, or empty if none is set
1660
     */
1661
    Optional<String> readTrustRepoCurrentHash() {
1662
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(TRUST_REPO)) {
×
1663
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
1664
                    NPA_HAS_CURRENT_TRUST_STATE);
1665
            if (!(v instanceof IRI iri)) return Optional.empty();
×
1666
            String s = iri.stringValue();
×
1667
            if (!s.startsWith(NPAT.NAMESPACE)) return Optional.empty();
×
1668
            return Optional.of(s.substring(NPAT.NAMESPACE.length()));
×
1669
        } catch (Exception ex) {
×
1670
            log.warn("AuthorityResolver: failed to read trust-repo current pointer: {}", ex.toString());
×
1671
            return Optional.empty();
×
1672
        }
1673
    }
1674

1675
    private static String abbrev(String hash) {
1676
        return hash.length() > 12 ? hash.substring(0, 12) + "…" : hash;
×
1677
    }
1678

1679
}
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