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

knowledgepixels / nanopub-query / 26449409375

26 May 2026 12:59PM UTC coverage: 59.244% (+0.03%) from 59.217%
26449409375

Pull #111

github

web-flow
Merge 76590179a into f752b8680
Pull Request #111: Keep admin seed alive across root-definition supersession (#110)

470 of 880 branches covered (53.41%)

Branch coverage included in aggregate %.

1347 of 2187 relevant lines covered (61.59%)

9.36 hits per line

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

15.32
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
     * <p>The seed is gated by {@link #spaceRefAliveFilter} (not the per-nanopub
705
     * {@code invalidationFilter("defNp")}): the {@code hasRootAdmin} seed is anchored
706
     * to the root NPID, which is the immutable space-ref identity, so superseding the
707
     * root <em>nanopub</em> with a continuation revision must not strip the seed —
708
     * only retracting every definition of the ref removes it. See issue #110.
709
     */
710
    static String adminTierUpdate(IRI graph, long lastProcessed) {
711
        // Order tuned for RDF4J's evaluator:
712
        //   1. Anchor on the small (seed UNION closed-over) set to bind ?publisher
713
        //      and ?space cheaply.
714
        //   2. Resolve ?pkh from the mirrored AccountState row (?publisher bound).
715
        //   3. Probe instantiations using the now-bound (?space, ?pkh) — targeted
716
        //      lookup, not a full RoleInstantiation scan.
717
        //   4. Load-number filter on bound ?np.
718
        //   5. Dedup at the end.
719
        return """
69✔
720
                PREFIX npa:  <%1$s>
721
                PREFIX gen:  <%2$s>
722
                INSERT { GRAPH <%3$s> {
723
                  ?ri a gen:RoleInstantiation ;
724
                      npa:forSpace ?space ;
725
                      npa:inverseProperty gen:hasAdmin ;
726
                      npa:forAgent ?agent ;
727
                      npa:viaNanopub ?np .
728
                } }
729
                WHERE {
730
                  # 1. Anchor: who is already an admin of which space?
731
                  {
732
                    # Seed branch: root-admin of a space ref that is still alive
733
                    # (has at least one non-invalidated definition). NOT filtered on
734
                    # ?def's own invalidation — superseding the root nanopub with a
735
                    # continuation revision must keep the seed; only a fully-retracted
736
                    # ref drops it (issue #110).
737
                    GRAPH <%4$s> {
738
                      ?def a npa:SpaceDefinition ;
739
                           npa:forSpaceRef  ?spaceRef ;
740
                           npa:hasRootAdmin ?publisher .
741
                      ?spaceRef npa:spaceIri ?space .
742
                    }
743
                    %7$s
744
                  }
745
                  UNION
746
                  {
747
                    # Closed-over branch: an existing admin in this space-state graph.
748
                    GRAPH <%3$s> {
749
                      ?prev a gen:RoleInstantiation ;
750
                            npa:forSpace        ?space ;
751
                            npa:inverseProperty gen:hasAdmin ;
752
                            npa:forAgent        ?publisher .
753
                    }
754
                  }
755
                  # 2. Mirror: resolve ?publisher → ?pkh via the trust-approved row.
756
                  GRAPH <%3$s> {
757
                    ?acct a npa:AccountState ;
758
                          npa:agent  ?publisher ;
759
                          npa:pubkey ?pkh .
760
                  }
761
                  # 3. Targeted instantiation lookup by space + pubkey.
762
                  GRAPH <%4$s> {
763
                    ?ri a gen:RoleInstantiation ;
764
                        npa:forSpace        ?space ;
765
                        npa:inverseProperty gen:hasAdmin ;
766
                        npa:forAgent        ?agent ;
767
                        npa:pubkeyHash      ?pkh ;
768
                        npa:viaNanopub      ?np .
769
                  }
770
                  %6$s
771
                  # 4. Load-number filter on bound ?np.
772
                  GRAPH <%8$s> {
773
                    ?np npa:hasLoadNumber ?ln .
774
                    FILTER (?ln > %5$d)
775
                  }
776
                  # 5. Dedup last.
777
                  FILTER NOT EXISTS { GRAPH <%3$s> {
778
                    ?existing a gen:RoleInstantiation ;
779
                              npa:forSpace ?space ;
780
                              npa:forAgent ?agent ;
781
                              npa:inverseProperty gen:hasAdmin .
782
                  } }
783
                }
784
                """.formatted(
3✔
785
                NPA.NAMESPACE,
786
                GEN.NAMESPACE,
787
                graph,
788
                SpacesVocab.SPACES_GRAPH,
789
                lastProcessed,
15✔
790
                invalidationFilter("np"),
12✔
791
                spaceRefAliveFilter(),
18✔
792
                NPA.GRAPH);
793
    }
794

795
    /**
796
     * Seed-survival filter for the admin tier (issue #110). The {@code hasRootAdmin}
797
     * seed is anchored to the root NPID, which is the immutable space-ref identity, so
798
     * it must survive supersession of the root <em>nanopub</em> by a continuation
799
     * revision (a later definition re-roots to the same ref via
800
     * {@code gen:hasRootDefinition} and so carries no {@code hasRootAdmin} of its own).
801
     * The previous {@code invalidationFilter("defNp")} dropped the seed the moment the
802
     * root revision was superseded, leaving the whole admin closure — and everything
803
     * cascading from it — unmaterialized for any space whose definition had ever been
804
     * updated.
805
     *
806
     * <p>Expressed positively: the seed survives iff the space ref still has at least
807
     * one non-invalidated {@link SpacesVocab#SPACE_DEFINITION}. A fully-retracted ref
808
     * (every definition invalidated) has no live definition, so the {@code FILTER
809
     * EXISTS} fails and the seed correctly disappears. Anchored on the already-bound
810
     * {@code ?spaceRef}, so it's a targeted lookup over that ref's (few) definitions.
811
     */
812
    private static String spaceRefAliveFilter() {
813
        return """
33✔
814
                FILTER EXISTS {
815
                  GRAPH <%1$s> {
816
                    ?liveDef a npa:SpaceDefinition ;
817
                             npa:forSpaceRef ?spaceRef ;
818
                             npa:viaNanopub  ?liveNp .
819
                  }
820
                  %2$s
821
                }
822
                """.formatted(SpacesVocab.SPACES_GRAPH, invalidationFilter("liveNp"));
9✔
823
    }
824

825
    /**
826
     * {@code gen:hasRole} attachment validation: an attachment is validated iff its
827
     * publisher is already a validated admin of the target space. Adds
828
     * {@code gen:RoleAssignment} rows to the space-state graph.
829
     */
830
    static String attachmentValidationUpdate(IRI graph, long lastProcessed) {
831
        return """
69✔
832
                PREFIX npa:  <%1$s>
833
                PREFIX gen:  <%2$s>
834
                INSERT { GRAPH <%3$s> {
835
                  ?ra a gen:RoleAssignment ;
836
                      npa:forSpace ?space ;
837
                      gen:hasRole  ?role ;
838
                      npa:viaNanopub ?np .
839
                } }
840
                WHERE {
841
                  GRAPH <%4$s> {
842
                    ?ra a gen:RoleAssignment ;
843
                        npa:forSpace ?space ;
844
                        gen:hasRole  ?role ;
845
                        npa:pubkeyHash ?pkh ;
846
                        npa:viaNanopub ?np .
847
                  }
848
                  GRAPH <%7$s> {
849
                    ?np npa:hasLoadNumber ?ln .
850
                    FILTER (?ln > %5$d)
851
                  }
852
                  GRAPH <%3$s> {
853
                    ?acct a npa:AccountState ;
854
                          npa:agent  ?publisher ;
855
                          npa:pubkey ?pkh .
856
                    ?adminRI a gen:RoleInstantiation ;
857
                             npa:forSpace ?space ;
858
                             npa:inverseProperty gen:hasAdmin ;
859
                             npa:forAgent ?publisher .
860
                  }
861
                  %6$s
862
                  FILTER NOT EXISTS { GRAPH <%3$s> {
863
                    ?existing a gen:RoleAssignment ;
864
                              npa:forSpace ?space ;
865
                              gen:hasRole  ?role .
866
                  } }
867
                }
868
                """.formatted(
3✔
869
                NPA.NAMESPACE,
870
                GEN.NAMESPACE,
871
                graph,
872
                SpacesVocab.SPACES_GRAPH,
873
                lastProcessed,
15✔
874
                invalidationFilter("np"),
18✔
875
                NPA.GRAPH);
876
    }
877

878
    /**
879
     * Non-admin tier publisher constraints (inserted as a SPARQL sub-pattern).
880
     * Each constraint owns the AccountState (pkh → agent) lookup so the join
881
     * variable is bound through a targeted pattern. The observer-self variant
882
     * binds {@code npa:agent ?agent} directly — no separate {@code ?publisher}
883
     * variable, no post-join equality filter — which lets the planner anchor
884
     * the AccountState lookup on the already-bound {@code ?agent} instead of
885
     * enumerating all approved publishers and filtering at the end.
886
     */
887
    static final String PUBLISHER_IS_ADMIN = """
888
            ?acct a npa:AccountState ;
889
                  npa:pubkey ?pkh ;
890
                  npa:agent  ?publisher .
891
            ?adminRI a gen:RoleInstantiation ;
892
                     npa:forSpace ?space ;
893
                     npa:inverseProperty gen:hasAdmin ;
894
                     npa:forAgent ?publisher .
895
            """;
896

897
    /** Observer self-evidence: the assignee's own pubkey signed the instantiation. */
898
    static final String PUBLISHER_IS_SELF = """
899
            ?acct a npa:AccountState ;
900
                  npa:pubkey ?pkh ;
901
                  npa:agent  ?agent .
902
            """;
903

904
    /**
905
     * Maintainer / Member / Observer tier INSERT. Same shape: find an instantiation
906
     * whose predicate matches a RoleDeclaration of the given tier attached to the
907
     * target space, and whose publisher passes the tier-specific constraint.
908
     */
909
    static String nonAdminTierUpdate(IRI graph, long lastProcessed,
910
                                     IRI tierClass, String publisherConstraint) {
911
        // Order tuned for RDF4J's evaluator (which executes BGPs roughly in order).
912
        // The crucial choice is the *anchor*: instantiation-first plans send the
913
        // planner exploring the full ~thousands of candidate RIs and only filter
914
        // by tier at the very end. Attachment-first anchors on the small set of
915
        // gen:RoleAssignment rows already validated in this space-state graph
916
        // (~hundreds, often zero) and walks outward by bound (?role, ?space).
917
        //
918
        //   1. Anchor on RoleAssignments in this space-state graph (small).
919
        //   2. Match the tier-pinned RoleDeclaration by ?role.
920
        //   3. Pair role-decl direction to instantiation direction in one UNION
921
        //      so only (reg, reg)/(inv, inv) combos are explored.
922
        //   4. Targeted instantiation lookup — (?space, ?pred) are bound.
923
        //   5. Publisher constraint (incl. AccountState resolution).
924
        //   6. Load-number filter on bound ?np.
925
        //   7. Dedup at the end.
926
        return """
69✔
927
                PREFIX npa:  <%1$s>
928
                PREFIX gen:  <%2$s>
929
                INSERT { GRAPH <%3$s> {
930
                  ?ri a gen:RoleInstantiation ;
931
                      npa:forSpace ?space ;
932
                      npa:forAgent ?agent ;
933
                      npa:viaNanopub ?np .
934
                } }
935
                WHERE {
936
                  # 1. Anchor: validated attachments in this space-state graph.
937
                  GRAPH <%3$s> {
938
                    ?ra a gen:RoleAssignment ;
939
                        gen:hasRole  ?role ;
940
                        npa:forSpace ?space .
941
                  }
942
                  # 2. Tier-pinned RoleDeclaration (?role bound from the attachment).
943
                  GRAPH <%4$s> {
944
                    ?rd a npa:RoleDeclaration ;
945
                        npa:hasRoleType <%7$s> ;
946
                        npa:role        ?role ;
947
                        npa:viaNanopub  ?rdNp .
948
                    # 3. Pair direction so only matching combos are explored.
949
                    {
950
                      ?rd gen:hasRegularProperty ?pred .
951
                      ?ri npa:regularProperty    ?pred .
952
                    }
953
                    UNION
954
                    {
955
                      ?rd gen:hasInverseProperty ?pred .
956
                      ?ri npa:inverseProperty    ?pred .
957
                    }
958
                    # 4. Targeted instantiation lookup — (?space, ?pred) bound.
959
                    ?ri a gen:RoleInstantiation ;
960
                        npa:forSpace   ?space ;
961
                        npa:forAgent   ?agent ;
962
                        npa:pubkeyHash ?pkh ;
963
                        npa:viaNanopub ?np .
964
                  }
965
                  # 5. Publisher constraint (incl. AccountState resolution).
966
                  GRAPH <%3$s> {
967
                    %9$s
968
                  }
969
                  # 6. Load-number filter on bound ?np.
970
                  GRAPH <%10$s> {
971
                    ?np npa:hasLoadNumber ?ln .
972
                    FILTER (?ln > %5$d)
973
                  }
974
                  # 7. Invalidation filters — outside the GRAPH block so the
975
                  #    planner defers them until ?rdNp/?np are bound.
976
                  %8$s
977
                  %6$s
978
                  # 8. Dedup last.
979
                  FILTER NOT EXISTS { GRAPH <%3$s> {
980
                    ?existing a gen:RoleInstantiation ;
981
                              npa:forSpace ?space ;
982
                              npa:forAgent ?agent ;
983
                              npa:viaNanopub ?np .
984
                  } }
985
                }
986
                """.formatted(
3✔
987
                NPA.NAMESPACE,
988
                GEN.NAMESPACE,
989
                graph,
990
                SpacesVocab.SPACES_GRAPH,
991
                lastProcessed,
15✔
992
                invalidationFilter("np"),
27✔
993
                tierClass,
994
                invalidationFilter("rdNp"),
30✔
995
                publisherConstraint,
996
                NPA.GRAPH);
997
    }
998

999
    /**
1000
     * Sub-space admit pass. Copies validated {@code npa:SubSpaceDeclaration}
1001
     * extraction rows into the space-state graph (preserving the {@code npasub:}
1002
     * subject) and emits convenience {@code <child> npa:isSubSpaceOf <parent>} and
1003
     * {@code <parent> npa:hasSubSpace <child>} direct triples. Two satisfaction
1004
     * modes joined by UNION:
1005
     * <ul>
1006
     *   <li>Mode A — the declaration's publisher is a validated admin of both the
1007
     *       child and the parent space.</li>
1008
     *   <li>Mode B — a different non-invalidated declaration for the same
1009
     *       {@code (child, parent)} pair exists, and the two publishers between
1010
     *       them cover both admin sides (i.e. one of them is admin of the child,
1011
     *       one of them is admin of the parent — possibly the same one twice if
1012
     *       both happen to be admin of both).</li>
1013
     * </ul>
1014
     *
1015
     * <p>Mode-B late-arrival: when only the partner declaration is new in this
1016
     * cycle (the primary is older than {@code lastProcessed}), the load-number
1017
     * filter on {@code ?np} excludes the candidate. The late-arrival sweep
1018
     * ({@link #runDownstreamWithoutLoadFilter}) re-runs this pass without the
1019
     * load filter and catches it.
1020
     */
1021
    static String subSpaceAdmitUpdate(IRI graph, long lastProcessed) {
1022
        return """
69✔
1023
                PREFIX npa: <%1$s>
1024
                PREFIX gen: <%2$s>
1025
                INSERT { GRAPH <%3$s> {
1026
                  ?d a npa:SubSpaceDeclaration ;
1027
                     npa:childSpace  ?child ;
1028
                     npa:parentSpace ?parent ;
1029
                     npa:viaNanopub  ?np .
1030
                  ?child  npa:isSubSpaceOf ?parent .
1031
                  ?parent npa:hasSubSpace  ?child  .
1032
                } }
1033
                WHERE {
1034
                  # 1. Anchor: candidate declarations from the extraction graph.
1035
                  GRAPH <%4$s> {
1036
                    ?d a npa:SubSpaceDeclaration ;
1037
                       npa:childSpace  ?child ;
1038
                       npa:parentSpace ?parent ;
1039
                       npa:pubkeyHash  ?pkh ;
1040
                       npa:viaNanopub  ?np .
1041
                  }
1042
                  # 2. Mirror: resolve ?pkh → ?publisher via the trust-approved row.
1043
                  GRAPH <%3$s> {
1044
                    ?acct a npa:AccountState ;
1045
                          npa:pubkey ?pkh ;
1046
                          npa:agent  ?publisher .
1047
                  }
1048
                  # 3. Authority gate.
1049
                  {
1050
                    # Mode A — publisher is admin of BOTH child and parent.
1051
                    FILTER EXISTS { GRAPH <%3$s> {
1052
                      ?riC a gen:RoleInstantiation ;
1053
                           npa:inverseProperty gen:hasAdmin ;
1054
                           npa:forSpace ?child ;
1055
                           npa:forAgent ?publisher .
1056
                    } }
1057
                    FILTER EXISTS { GRAPH <%3$s> {
1058
                      ?riP a gen:RoleInstantiation ;
1059
                           npa:inverseProperty gen:hasAdmin ;
1060
                           npa:forSpace ?parent ;
1061
                           npa:forAgent ?publisher .
1062
                    } }
1063
                  }
1064
                  UNION
1065
                  {
1066
                    # Mode B — co-declaration whose publisher covers the side this
1067
                    # one's publisher doesn't. Between {publisher, publisher2},
1068
                    # both admin sides must be covered.
1069
                    GRAPH <%4$s> {
1070
                      ?d2 a npa:SubSpaceDeclaration ;
1071
                          npa:childSpace  ?child ;
1072
                          npa:parentSpace ?parent ;
1073
                          npa:pubkeyHash  ?pkh2 ;
1074
                          npa:viaNanopub  ?np2 .
1075
                      FILTER (?np2 != ?np)
1076
                    }
1077
                    %8$s
1078
                    GRAPH <%3$s> {
1079
                      ?acct2 a npa:AccountState ;
1080
                             npa:pubkey ?pkh2 ;
1081
                             npa:agent  ?publisher2 .
1082
                    }
1083
                    FILTER EXISTS { GRAPH <%3$s> {
1084
                      ?riA a gen:RoleInstantiation ;
1085
                           npa:inverseProperty gen:hasAdmin ;
1086
                           npa:forSpace ?child .
1087
                      { ?riA npa:forAgent ?publisher } UNION { ?riA npa:forAgent ?publisher2 }
1088
                    } }
1089
                    FILTER EXISTS { GRAPH <%3$s> {
1090
                      ?riB a gen:RoleInstantiation ;
1091
                           npa:inverseProperty gen:hasAdmin ;
1092
                           npa:forSpace ?parent .
1093
                      { ?riB npa:forAgent ?publisher } UNION { ?riB npa:forAgent ?publisher2 }
1094
                    } }
1095
                  }
1096
                  # 4. Invalidation filter on the primary declaration's nanopub.
1097
                  %6$s
1098
                  # 5. Load-number filter on bound ?np.
1099
                  GRAPH <%7$s> {
1100
                    ?np npa:hasLoadNumber ?ln .
1101
                    FILTER (?ln > %5$d)
1102
                  }
1103
                  # 6. Dedup last.
1104
                  FILTER NOT EXISTS { GRAPH <%3$s> {
1105
                    ?d a npa:SubSpaceDeclaration .
1106
                  } }
1107
                }
1108
                """.formatted(
3✔
1109
                NPA.NAMESPACE,
1110
                GEN.NAMESPACE,
1111
                graph,
1112
                SpacesVocab.SPACES_GRAPH,
1113
                lastProcessed,
15✔
1114
                invalidationFilter("np"),
27✔
1115
                NPA.GRAPH,
1116
                invalidationFilter("np2"));
6✔
1117
    }
1118

1119
    /**
1120
     * Maintained-resource admit pass. Copies validated
1121
     * {@code npa:MaintainedResourceDeclaration} extraction rows into the space-state
1122
     * graph (preserving the {@code npamrd:} subject) and emits convenience
1123
     * {@code <r> npa:isMaintainedBy <s>} and {@code <s> npa:hasMaintainedResource <r>}
1124
     * direct triples. Single satisfaction mode:
1125
     * <ul>
1126
     *   <li>Mode A — the declaration's publisher is a validated admin of the
1127
     *       maintaining space.</li>
1128
     * </ul>
1129
     *
1130
     * <p>No Mode B because only one space is involved; the two-sides-must-be-covered
1131
     * concern that drives sub-space Mode B doesn't apply. Late-arrival is still
1132
     * possible (declaration lands before the publisher's admin grant becomes valid):
1133
     * the load-number filter on {@code ?np} excludes the candidate, and the
1134
     * late-arrival sweep ({@link #runDownstreamWithoutLoadFilter}) re-runs this pass
1135
     * without the load filter and catches it.
1136
     */
1137
    static String maintainedResourceAdmitUpdate(IRI graph, long lastProcessed) {
1138
        return """
69✔
1139
                PREFIX npa: <%1$s>
1140
                PREFIX gen: <%2$s>
1141
                INSERT { GRAPH <%3$s> {
1142
                  ?d a npa:MaintainedResourceDeclaration ;
1143
                     npa:resourceIri     ?r ;
1144
                     npa:maintainerSpace ?s ;
1145
                     npa:viaNanopub      ?np .
1146
                  ?r npa:isMaintainedBy        ?s .
1147
                  ?s npa:hasMaintainedResource ?r .
1148
                } }
1149
                WHERE {
1150
                  # 1. Anchor: candidate declarations from the extraction graph.
1151
                  GRAPH <%4$s> {
1152
                    ?d a npa:MaintainedResourceDeclaration ;
1153
                       npa:resourceIri     ?r ;
1154
                       npa:maintainerSpace ?s ;
1155
                       npa:pubkeyHash      ?pkh ;
1156
                       npa:viaNanopub      ?np .
1157
                  }
1158
                  # 2. Mirror: resolve ?pkh → ?publisher via the trust-approved row.
1159
                  GRAPH <%3$s> {
1160
                    ?acct a npa:AccountState ;
1161
                          npa:pubkey ?pkh ;
1162
                          npa:agent  ?publisher .
1163
                    # 3. Authority gate (Mode A only): publisher is admin of the
1164
                    #    maintaining space.
1165
                    ?riA a gen:RoleInstantiation ;
1166
                         npa:inverseProperty gen:hasAdmin ;
1167
                         npa:forSpace ?s ;
1168
                         npa:forAgent ?publisher .
1169
                  }
1170
                  # 4. Invalidation filter on the declaration's nanopub.
1171
                  %6$s
1172
                  # 5. Load-number filter on bound ?np.
1173
                  GRAPH <%7$s> {
1174
                    ?np npa:hasLoadNumber ?ln .
1175
                    FILTER (?ln > %5$d)
1176
                  }
1177
                  # 6. Dedup last.
1178
                  FILTER NOT EXISTS { GRAPH <%3$s> {
1179
                    ?d a npa:MaintainedResourceDeclaration .
1180
                  } }
1181
                }
1182
                """.formatted(
3✔
1183
                NPA.NAMESPACE,
1184
                GEN.NAMESPACE,
1185
                graph,
1186
                SpacesVocab.SPACES_GRAPH,
1187
                lastProcessed,
15✔
1188
                invalidationFilter("np"),
18✔
1189
                NPA.GRAPH);
1190
    }
1191

1192
    /**
1193
     * URL-prefix sub-space fallback admit pass. For every pair of {@code SpaceRef}
1194
     * aggregates where the child's {@code npa:hasIdPrefix} matches the parent's
1195
     * {@code npa:spaceIri}, emits convenience {@code <child> npa:isSubSpaceOf <parent>}
1196
     * and {@code <parent> npa:hasSubSpace <child>} direct triples plus a reified
1197
     * {@code npa:DerivedSubSpaceLink} tag carrying {@code npa:derivationKind
1198
     * npa:byUrlPrefix} so consumers can hide derived edges.
1199
     *
1200
     * <p>Per-child suppression: any validated {@code npa:SubSpaceDeclaration} on the
1201
     * child in {@code npass:<…>} suppresses every fallback edge for that child.
1202
     * Suppression checks the validated set (not raw extraction-graph declarations)
1203
     * so an unapproved or in-flight Mode B declaration doesn't silently hide both
1204
     * the URL-prefix fallback and the (still-invalid) explicit relation.
1205
     *
1206
     * <p>Run order: must run after {@link #subSpaceAdmitUpdate} commits in the
1207
     * same cycle so the suppression check sees this cycle's freshly-validated
1208
     * declarations.
1209
     *
1210
     * <p>No load-number filter: the fallback depends on which Spaces exist (parent
1211
     * + child {@code SpaceRef}s), not on which were just added. Always full-scan;
1212
     * the dedup {@code FILTER NOT EXISTS} on the tag IRI prevents re-insertion.
1213
     *
1214
     * <p>No invalidation handling: derived edges have no source nanopub. Two
1215
     * staleness modes: (a) child later gets first validated declaration → old
1216
     * derived edges stay sticky until the next periodic rebuild (same policy as
1217
     * admin-RI invalidation); (b) child loses last validated declaration → the
1218
     * regular fallback pass on the next cycle re-engages, adds derived edges
1219
     * incrementally, no rebuild needed.
1220
     */
1221
    static String subSpacePrefixFallbackUpdate(IRI graph) {
1222
        return """
48✔
1223
                PREFIX npa: <%1$s>
1224
                INSERT { GRAPH <%2$s> {
1225
                  ?child  npa:isSubSpaceOf ?parent .
1226
                  ?parent npa:hasSubSpace  ?child  .
1227
                  ?tagIri a npa:DerivedSubSpaceLink ;
1228
                          npa:childSpace     ?child ;
1229
                          npa:parentSpace    ?parent ;
1230
                          npa:derivationKind npa:byUrlPrefix .
1231
                } }
1232
                WHERE {
1233
                  # 1. Anchor: child SpaceRef → its path-prefixes (extracted at load
1234
                  #    time from the Space IRI; see SpacesExtractor.enumerateIdPrefixes).
1235
                  GRAPH <%3$s> {
1236
                    ?childRef  npa:spaceIri    ?child ;
1237
                               npa:hasIdPrefix ?parent .
1238
                    # 2. Parent SpaceRef must exist for the same IRI as the prefix.
1239
                    ?parentRef npa:spaceIri    ?parent .
1240
                  }
1241
                  # 3. Suppress fallback for any child that has a validated declaration
1242
                  #    in this state graph. Per-child, all-or-nothing.
1243
                  FILTER NOT EXISTS {
1244
                    GRAPH <%2$s> {
1245
                      ?d a npa:SubSpaceDeclaration ;
1246
                         npa:childSpace ?child .
1247
                    }
1248
                  }
1249
                  # 4. Mint a deterministic tag IRI per (child, parent).
1250
                  BIND(IRI(CONCAT("http://purl.org/nanopub/admin/derivedlink/",
1251
                                  MD5(CONCAT(STR(?child), "|", STR(?parent))))) AS ?tagIri)
1252
                  # 5. Dedup: don't re-insert if this tag is already present.
1253
                  FILTER NOT EXISTS {
1254
                    GRAPH <%2$s> {
1255
                      ?tagIri a npa:DerivedSubSpaceLink .
1256
                    }
1257
                  }
1258
                }
1259
                """.formatted(
3✔
1260
                NPA.NAMESPACE,
1261
                graph,
1262
                SpacesVocab.SPACES_GRAPH);
1263
    }
1264

1265
    // ---------------- Invalidation templates (incremental cycle) ----------------
1266

1267
    /**
1268
     * WHERE clause shared by the admin-RI invalidation ASK precheck and the
1269
     * matching DELETE. Identifies admin-tier {@code gen:RoleInstantiation} rows
1270
     * in the space-state graph whose {@code npa:viaNanopub} is the target of an
1271
     * {@code npx:invalidates} triple in {@code npa:graph} whose subject nanopub
1272
     * has a load number in {@code (lastProcessed, ∞)}.
1273
     */
1274
    static String adminInvalidationCheckWhere(IRI graph, long lastProcessed) {
1275
        return String.format("""
60✔
1276
                  GRAPH <%1$s> {
1277
                    ?ri a gen:RoleInstantiation ;
1278
                        npa:inverseProperty gen:hasAdmin ;
1279
                        npa:viaNanopub ?np .
1280
                  }
1281
                  GRAPH <%2$s> {
1282
                    ?invNp <%3$s> ?np ;
1283
                           npa:hasLoadNumber ?ln .
1284
                    FILTER (?ln > %4$d)
1285
                  }
1286
                """, graph, NPA.GRAPH, NPX.INVALIDATES, lastProcessed);
6✔
1287
    }
1288

1289
    /** DELETE template for admin-tier RoleInstantiations whose source nanopub was invalidated. */
1290
    static String adminInvalidationDelete(IRI graph, long lastProcessed) {
1291
        return String.format("""
63✔
1292
                PREFIX npa: <%1$s>
1293
                PREFIX gen: <%2$s>
1294
                DELETE { GRAPH <%3$s> {
1295
                  ?ri ?p ?o .
1296
                } }
1297
                WHERE {
1298
                  GRAPH <%3$s> { ?ri ?p ?o . }
1299
                %4$s
1300
                }
1301
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
1302
                adminInvalidationCheckWhere(graph, lastProcessed));
6✔
1303
    }
1304

1305
    /** WHERE clause for RoleAssignment invalidation. */
1306
    static String roleAssignmentInvalidationCheckWhere(IRI graph, long lastProcessed) {
1307
        return String.format("""
60✔
1308
                  GRAPH <%1$s> {
1309
                    ?ra a gen:RoleAssignment ;
1310
                        npa:viaNanopub ?np .
1311
                  }
1312
                  GRAPH <%2$s> {
1313
                    ?invNp <%3$s> ?np ;
1314
                           npa:hasLoadNumber ?ln .
1315
                    FILTER (?ln > %4$d)
1316
                  }
1317
                """, graph, NPA.GRAPH, NPX.INVALIDATES, lastProcessed);
6✔
1318
    }
1319

1320
    /** DELETE template for RoleAssignments whose source nanopub was invalidated. */
1321
    static String roleAssignmentInvalidationDelete(IRI graph, long lastProcessed) {
1322
        return String.format("""
63✔
1323
                PREFIX npa: <%1$s>
1324
                PREFIX gen: <%2$s>
1325
                DELETE { GRAPH <%3$s> {
1326
                  ?ra ?p ?o .
1327
                } }
1328
                WHERE {
1329
                  GRAPH <%3$s> { ?ra ?p ?o . }
1330
                %4$s
1331
                }
1332
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
1333
                roleAssignmentInvalidationCheckWhere(graph, lastProcessed));
6✔
1334
    }
1335

1336
    /**
1337
     * WHERE clause for RoleDeclaration invalidation. ASK-only (no DELETE):
1338
     * RoleDeclarations live in {@code npa:spacesGraph} and aren't materialized
1339
     * into the space-state graph, so there's nothing to remove from the
1340
     * space-state. The ASK still flips {@code npa:needsFullRebuild} because
1341
     * sticky downstream RIs that were derived under the now-invalidated RD
1342
     * need a from-scratch recompute.
1343
     */
1344
    static String roleDeclarationInvalidationCheckWhere(long lastProcessed) {
1345
        return String.format("""
60✔
1346
                  GRAPH <%1$s> {
1347
                    ?rd a npa:RoleDeclaration ;
1348
                        npa:viaNanopub ?np .
1349
                  }
1350
                  GRAPH <%2$s> {
1351
                    ?invNp <%3$s> ?np ;
1352
                           npa:hasLoadNumber ?ln .
1353
                    FILTER (?ln > %4$d)
1354
                  }
1355
                """, SpacesVocab.SPACES_GRAPH, NPA.GRAPH, NPX.INVALIDATES, lastProcessed);
6✔
1356
    }
1357

1358
    /**
1359
     * DELETE template for non-admin (leaf-tier) RoleInstantiations whose source
1360
     * nanopub was invalidated. Identified as {@code gen:RoleInstantiation} rows
1361
     * lacking the admin-pinning {@code npa:inverseProperty gen:hasAdmin} triple.
1362
     * No flag is set; leaf-tier removals are recoverable on the next cycle.
1363
     */
1364
    static String leafTierInvalidationDelete(IRI graph, long lastProcessed) {
1365
        return String.format("""
84✔
1366
                PREFIX npa: <%1$s>
1367
                PREFIX gen: <%2$s>
1368
                DELETE { GRAPH <%3$s> {
1369
                  ?ri ?p ?o .
1370
                } }
1371
                WHERE {
1372
                  GRAPH <%3$s> {
1373
                    ?ri a gen:RoleInstantiation ;
1374
                        npa:viaNanopub ?np .
1375
                    FILTER NOT EXISTS { ?ri npa:inverseProperty gen:hasAdmin }
1376
                    ?ri ?p ?o .
1377
                  }
1378
                  GRAPH <%4$s> {
1379
                    ?invNp <%5$s> ?np ;
1380
                           npa:hasLoadNumber ?ln .
1381
                    FILTER (?ln > %6$d)
1382
                  }
1383
                }
1384
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
1385
                NPA.GRAPH, NPX.INVALIDATES, lastProcessed);
6✔
1386
    }
1387

1388
    /**
1389
     * WHERE clause shared by the sub-space invalidation ASK precheck and the
1390
     * matching DELETE. Identifies validated {@code npa:SubSpaceDeclaration} rows
1391
     * in the space-state graph whose {@code npa:viaNanopub} is the target of an
1392
     * {@code npx:invalidates} triple in {@code npa:graph} whose subject nanopub
1393
     * has a load number in {@code (lastProcessed, ∞)}.
1394
     */
1395
    static String subSpaceInvalidationCheckWhere(IRI graph, long lastProcessed) {
1396
        return String.format("""
60✔
1397
                  GRAPH <%1$s> {
1398
                    ?d a npa:SubSpaceDeclaration ;
1399
                       npa:viaNanopub ?np .
1400
                  }
1401
                  GRAPH <%2$s> {
1402
                    ?invNp <%3$s> ?np ;
1403
                           npa:hasLoadNumber ?ln .
1404
                    FILTER (?ln > %4$d)
1405
                  }
1406
                """, graph, NPA.GRAPH, NPX.INVALIDATES, lastProcessed);
6✔
1407
    }
1408

1409
    /**
1410
     * DELETE template for validated {@code npa:SubSpaceDeclaration} rows whose
1411
     * source nanopub was invalidated. Removes the per-declaration row by subject;
1412
     * the convenience direct triples ({@code <child> npa:isSubSpaceOf <parent>}
1413
     * and inverse) are left sticky and cleaned by the next periodic full rebuild
1414
     * (same staleness policy as admin-RI invalidation — see {@code
1415
     * doc/design-space-repositories.md} on the structural-rebuild flag).
1416
     */
1417
    static String subSpaceInvalidationDelete(IRI graph, long lastProcessed) {
1418
        return String.format("""
63✔
1419
                PREFIX npa: <%1$s>
1420
                PREFIX gen: <%2$s>
1421
                DELETE { GRAPH <%3$s> {
1422
                  ?d ?p ?o .
1423
                } }
1424
                WHERE {
1425
                  GRAPH <%3$s> { ?d ?p ?o . }
1426
                %4$s
1427
                }
1428
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
1429
                subSpaceInvalidationCheckWhere(graph, lastProcessed));
6✔
1430
    }
1431

1432
    /**
1433
     * DELETE template for validated {@code npa:MaintainedResourceDeclaration} rows
1434
     * whose source nanopub was invalidated. Removes the per-declaration row by
1435
     * subject; the convenience direct triples ({@code <r> npa:isMaintainedBy <s>}
1436
     * and inverse) are left sticky and cleaned by the next periodic full rebuild
1437
     * (same staleness policy as sub-space declaration invalidation, but without
1438
     * the structural-rebuild flag — maintained-resource is a leaf relation, no
1439
     * downstream consumers depend on its closure).
1440
     */
1441
    static String maintainedResourceInvalidationDelete(IRI graph, long lastProcessed) {
1442
        return String.format("""
84✔
1443
                PREFIX npa: <%1$s>
1444
                PREFIX gen: <%2$s>
1445
                DELETE { GRAPH <%3$s> {
1446
                  ?d ?p ?o .
1447
                } }
1448
                WHERE {
1449
                  GRAPH <%3$s> {
1450
                    ?d a npa:MaintainedResourceDeclaration ;
1451
                       npa:viaNanopub ?np .
1452
                    ?d ?p ?o .
1453
                  }
1454
                  GRAPH <%4$s> {
1455
                    ?invNp <%5$s> ?np ;
1456
                           npa:hasLoadNumber ?ln .
1457
                    FILTER (?ln > %6$d)
1458
                  }
1459
                }
1460
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
1461
                NPA.GRAPH, NPX.INVALIDATES, lastProcessed);
6✔
1462
    }
1463

1464
    /** Wraps an ASK by joining the shared prefixes. */
1465
    private boolean wouldInvalidate(IRI graph, long lastProcessed,
1466
                                    boolean adminPinned, String whereClause) {
1467
        // adminPinned is informational only — kept to make call sites read clearly;
1468
        // the WHERE clause already encodes the kind via its own type predicates.
1469
        String ask = String.format("""
×
1470
                PREFIX npa: <%1$s>
1471
                PREFIX gen: <%2$s>
1472
                ASK { %3$s }
1473
                """, NPA.NAMESPACE, GEN.NAMESPACE, whereClause);
1474
        return runAsk(ask);
×
1475
    }
1476

1477
    private boolean runAsk(String sparql) {
1478
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1479
            return conn.prepareBooleanQuery(QueryLanguage.SPARQL, sparql).evaluate();
×
1480
        }
1481
    }
1482

1483
    private void executeUpdate(String sparqlUpdate) {
1484
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1485
            conn.prepareUpdate(QueryLanguage.SPARQL, sparqlUpdate).execute();
×
1486
        }
1487
    }
×
1488

1489
    // ---------------- Mirror step ----------------
1490

1491
    /**
1492
     * Copies trust-approved {@code npa:AccountState} rows from {@code npat:<T>}
1493
     * in the {@code trust} repo into {@code newGraph} in the {@code spaces} repo,
1494
     * inside one spaces-side serializable transaction.
1495
     *
1496
     * @return number of rows mirrored (useful for metrics / logging)
1497
     */
1498
    int mirrorTrustState(String trustStateHash, IRI newGraph) {
1499
        IRI trustStateIri = NPAT.forHash(trustStateHash);
×
1500
        int count = 0;
×
1501
        try (RepositoryConnection trustConn = TripleStore.get().getRepoConnection(TRUST_REPO);
×
1502
             RepositoryConnection spacesConn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1503
            trustConn.begin(IsolationLevels.READ_COMMITTED);
×
1504
            spacesConn.begin(IsolationLevels.SERIALIZABLE);
×
1505
            // Walk rdf:type triples in the trust state's graph; for each AccountState,
1506
            // check status and copy the approved ones verbatim (minus status-specific
1507
            // detail triples, which we don't need for validation).
1508
            try (RepositoryResult<Statement> typeRows = trustConn.getStatements(
×
1509
                    null, RDF.TYPE, NPA_ACCOUNT_STATE, trustStateIri)) {
1510
                while (typeRows.hasNext()) {
×
1511
                    Statement st = typeRows.next();
×
1512
                    if (!(st.getSubject() instanceof IRI accountStateIri)) continue;
×
1513
                    Value status = trustConn.getStatements(accountStateIri, NPA_TRUST_STATUS, null, trustStateIri)
×
1514
                            .stream().findFirst().map(Statement::getObject).orElse(null);
×
1515
                    if (!(status instanceof IRI statusIri) || !APPROVED_SET.contains(statusIri)) continue;
×
1516
                    Value agent = trustConn.getStatements(accountStateIri, NPA_AGENT, null, trustStateIri)
×
1517
                            .stream().findFirst().map(Statement::getObject).orElse(null);
×
1518
                    Value pubkey = trustConn.getStatements(accountStateIri, NPA_PUBKEY, null, trustStateIri)
×
1519
                            .stream().findFirst().map(Statement::getObject).orElse(null);
×
1520
                    if (agent == null || pubkey == null) {
×
1521
                        log.warn("AuthorityResolver.mirror: account {} missing agent or pubkey; skipping",
×
1522
                                accountStateIri);
1523
                        continue;
×
1524
                    }
1525
                    spacesConn.add(accountStateIri, RDF.TYPE, NPA_ACCOUNT_STATE, newGraph);
×
1526
                    spacesConn.add(accountStateIri, NPA_AGENT, agent, newGraph);
×
1527
                    spacesConn.add(accountStateIri, NPA_PUBKEY, pubkey, newGraph);
×
1528
                    spacesConn.add(accountStateIri, NPA_TRUST_STATUS, statusIri, newGraph);
×
1529
                    count++;
×
1530
                }
×
1531
            }
1532
            // Mirror canonical foaf:name triples for approved agents. The trust
1533
            // loader emits one per agent (across approved keys, MAX(ratio) wins).
1534
            // Copying them into the space-state graph means consumers reading
1535
            // ?agent foaf:name ?n inside the state graph hit local data, with no
1536
            // cross-repo SERVICE.
1537
            try (RepositoryResult<Statement> nameRows = trustConn.getStatements(
×
1538
                    null, FOAF.NAME, null, trustStateIri)) {
1539
                while (nameRows.hasNext()) {
×
1540
                    Statement st = nameRows.next();
×
1541
                    spacesConn.add(st.getSubject(), st.getPredicate(), st.getObject(), newGraph);
×
1542
                }
×
1543
            }
1544
            spacesConn.commit();
×
1545
            trustConn.commit();
×
1546
        }
1547
        return count;
×
1548
    }
1549

1550
    // ---------------- Pointer + counter helpers ----------------
1551

1552
    /**
1553
     * Reads the current {@code npa:hasCurrentSpaceState} pointer from the
1554
     * {@code npa:graph} admin graph of the {@code spaces} repo. Returns
1555
     * {@code null} if no pointer exists yet.
1556
     */
1557
    IRI getCurrentSpaceStateGraph() {
1558
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1559
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
1560
                    SpacesVocab.HAS_CURRENT_SPACE_STATE);
1561
            return (v instanceof IRI iri) ? iri : null;
×
1562
        } catch (Exception ex) {
×
1563
            log.warn("AuthorityResolver: failed to read hasCurrentSpaceState pointer: {}", ex.toString());
×
1564
            return null;
×
1565
        }
1566
    }
1567

1568
    long getCurrentLoadCounter() {
1569
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1570
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
1571
                    SpacesVocab.CURRENT_LOAD_COUNTER);
1572
            if (v == null) return 0;
×
1573
            try {
1574
                return Long.parseLong(v.stringValue());
×
1575
            } catch (NumberFormatException ex) {
×
1576
                log.warn("AuthorityResolver: non-numeric currentLoadCounter: {}", v);
×
1577
                return 0;
×
1578
            }
1579
        } catch (Exception ex) {
×
1580
            log.warn("AuthorityResolver: failed to read currentLoadCounter: {}", ex.toString());
×
1581
            return 0;
×
1582
        }
1583
    }
1584

1585
    /**
1586
     * Atomic pointer flip: a single SPARQL {@code DELETE … INSERT … WHERE}
1587
     * replaces the old pointer with the new one in one statement, so readers
1588
     * never see a zero-pointer window.
1589
     */
1590
    void flipPointer(IRI newGraph) {
1591
        String update = String.format("""
×
1592
                DELETE { GRAPH <%s> { <%s> <%s> ?old } }
1593
                INSERT { GRAPH <%s> { <%s> <%s> <%s> } }
1594
                WHERE  { OPTIONAL { GRAPH <%s> { <%s> <%s> ?old } } }
1595
                """,
1596
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.HAS_CURRENT_SPACE_STATE,
1597
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.HAS_CURRENT_SPACE_STATE, newGraph,
1598
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.HAS_CURRENT_SPACE_STATE);
1599
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1600
            conn.begin(IsolationLevels.SERIALIZABLE);
×
1601
            conn.prepareUpdate(QueryLanguage.SPARQL, update).execute();
×
1602
            conn.commit();
×
1603
        }
1604
    }
×
1605

1606
    void writeProcessedUpTo(IRI graph, long loadCounter) {
1607
        String update = String.format("""
×
1608
                DELETE { GRAPH <%s> { <%s> <%s> ?old } }
1609
                INSERT { GRAPH <%s> { <%s> <%s> "%d"^^<http://www.w3.org/2001/XMLSchema#long> } }
1610
                WHERE  { OPTIONAL { GRAPH <%s> { <%s> <%s> ?old } } }
1611
                """,
1612
                graph, graph, SpacesVocab.PROCESSED_UP_TO,
1613
                graph, graph, SpacesVocab.PROCESSED_UP_TO, loadCounter,
×
1614
                graph, graph, SpacesVocab.PROCESSED_UP_TO);
1615
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1616
            conn.begin(IsolationLevels.SERIALIZABLE);
×
1617
            conn.prepareUpdate(QueryLanguage.SPARQL, update).execute();
×
1618
            conn.commit();
×
1619
        }
1620
    }
×
1621

1622
    /**
1623
     * Reads {@code processedUpTo} from the given space-state graph.
1624
     * Returns {@code -1} if absent (graph not fully built yet).
1625
     */
1626
    long readProcessedUpTo(IRI graph) {
1627
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1628
            String query = String.format(
×
1629
                    "SELECT ?n WHERE { GRAPH <%s> { <%s> <%s> ?n } }",
1630
                    graph, graph, SpacesVocab.PROCESSED_UP_TO);
1631
            try (TupleQueryResult r = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) {
×
1632
                if (!r.hasNext()) return -1;
×
1633
                BindingSet b = r.next();
×
1634
                return Long.parseLong(b.getBinding("n").getValue().stringValue());
×
1635
            }
×
1636
        } catch (Exception ex) {
×
1637
            log.warn("AuthorityResolver: failed to read processedUpTo for {}: {}", graph, ex.toString());
×
1638
            return -1;
×
1639
        }
1640
    }
1641

1642
    /**
1643
     * Reads the {@code npa:needsFullRebuild} flag (boolean literal) from
1644
     * {@code npa:graph} in the {@code spaces} repo. Defaults to {@code false}
1645
     * when the triple is absent.
1646
     */
1647
    boolean readNeedsFullRebuild() {
1648
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1649
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
1650
                    SpacesVocab.NEEDS_FULL_REBUILD);
1651
            return v != null && Boolean.parseBoolean(v.stringValue());
×
1652
        } catch (Exception ex) {
×
1653
            log.warn("AuthorityResolver: failed to read needsFullRebuild: {}", ex.toString());
×
1654
            return false;
×
1655
        }
1656
    }
1657

1658
    void setNeedsFullRebuild() {
1659
        writeNeedsFullRebuild(true);
×
1660
    }
×
1661

1662
    void clearNeedsFullRebuild() {
1663
        writeNeedsFullRebuild(false);
×
1664
    }
×
1665

1666
    private void writeNeedsFullRebuild(boolean value) {
1667
        String update = String.format("""
×
1668
                DELETE { GRAPH <%s> { <%s> <%s> ?old } }
1669
                INSERT { GRAPH <%s> { <%s> <%s> "%s"^^<http://www.w3.org/2001/XMLSchema#boolean> } }
1670
                WHERE  { OPTIONAL { GRAPH <%s> { <%s> <%s> ?old } } }
1671
                """,
1672
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.NEEDS_FULL_REBUILD,
1673
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.NEEDS_FULL_REBUILD, value,
×
1674
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.NEEDS_FULL_REBUILD);
1675
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1676
            conn.begin(IsolationLevels.SERIALIZABLE);
×
1677
            conn.prepareUpdate(QueryLanguage.SPARQL, update).execute();
×
1678
            conn.commit();
×
1679
        }
1680
    }
×
1681

1682
    void dropGraph(IRI graph) {
1683
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1684
            conn.begin(IsolationLevels.SERIALIZABLE);
×
1685
            conn.clear(graph);
×
1686
            conn.commit();
×
1687
            log.info("AuthorityResolver: dropped old space-state graph {}", graph);
×
1688
        }
1689
    }
×
1690

1691
    // ---------------- Trust-repo pointer lookup (used by TrustStateRegistry's bootstrap) ----------------
1692

1693
    /**
1694
     * Queries the {@code trust} repo directly for the current trust-state hash.
1695
     * Prefer {@link TrustStateRegistry#getCurrentHash()} in normal operation —
1696
     * this helper exists for tests and diagnostics.
1697
     *
1698
     * @return the current trust-state hash, or empty if none is set
1699
     */
1700
    Optional<String> readTrustRepoCurrentHash() {
1701
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(TRUST_REPO)) {
×
1702
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
1703
                    NPA_HAS_CURRENT_TRUST_STATE);
1704
            if (!(v instanceof IRI iri)) return Optional.empty();
×
1705
            String s = iri.stringValue();
×
1706
            if (!s.startsWith(NPAT.NAMESPACE)) return Optional.empty();
×
1707
            return Optional.of(s.substring(NPAT.NAMESPACE.length()));
×
1708
        } catch (Exception ex) {
×
1709
            log.warn("AuthorityResolver: failed to read trust-repo current pointer: {}", ex.toString());
×
1710
            return Optional.empty();
×
1711
        }
1712
    }
1713

1714
    private static String abbrev(String hash) {
1715
        return hash.length() > 12 ? hash.substring(0, 12) + "…" : hash;
×
1716
    }
1717

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