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

knowledgepixels / nanopub-query / 25427443331

06 May 2026 09:32AM UTC coverage: 57.877% (-0.1%) from 57.984%
25427443331

push

github

web-flow
Merge pull request #95 from knowledgepixels/feature/93-subspace-admit-pass

Validate sub-space declarations in materialiser admit pass (#93, PR 2/3)

467 of 888 branches covered (52.59%)

Branch coverage included in aggregate %.

1256 of 2089 relevant lines covered (60.12%)

9.27 hits per line

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

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

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

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

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

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

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

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

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

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

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

83
    private static AuthorityResolver instance;
84

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

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

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

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

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

117
    // ---------------- Public entry points ----------------
118

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

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

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

204
    // ---------------- Full build ----------------
205

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

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

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

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

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

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

240
        TierSubjectTotals totals = computeTierSubjectTotals(newGraph);
×
241
        long durationMs = (System.nanoTime() - startNanos) / 1_000_000L;
×
242
        lastSubjectTotals = totals;
×
243
        lastInsertedTriplesTotal = (long) counts.admin + counts.attachment
×
244
                + counts.maintainer + counts.member + counts.observer + counts.subSpace;
245
        lastFullBuildDurationMs = durationMs;
×
246
        lastProcessedUpToLag = 0L;
×
247
        log.info("AuthorityResolver: full build complete — graph={} mirrored={} rows loadCounter={} "
×
248
                        + "subjects: adminRIs={} attachmentRAs={} nonAdminRIs={} "
249
                        + "(inserted-triples: admin={} attachment={} maintainer={} member={} observer={} subspace={}) "
250
                        + "durationMs={}",
251
                newGraph, mirrored, loadCounter,
×
252
                totals.adminRIs(), totals.attachmentRAs(), totals.nonAdminRIs(),
×
253
                counts.admin, counts.attachment, counts.maintainer, counts.member, counts.observer, counts.subSpace,
×
254
                durationMs);
×
255
    }
×
256

257
    // ---------------- Incremental cycle ----------------
258

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

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

316
        writeProcessedUpTo(graph, currentLoadCounter);
×
317

318
        TierSubjectTotals totals = computeTierSubjectTotals(graph);
×
319
        long durationMs = (System.nanoTime() - startNanos) / 1_000_000L;
×
320
        lastSubjectTotals = totals;
×
321
        lastInsertedTriplesTotal = (long) counts.admin + counts.attachment
×
322
                + counts.maintainer + counts.member + counts.observer + counts.subSpace;
323
        lastIncrementalCycleDurationMs = durationMs;
×
324
        log.info("AuthorityResolver: incremental cycle complete — graph={} delta=({}, {}] "
×
325
                        + "subjects: adminRIs={} attachmentRAs={} nonAdminRIs={} "
326
                        + "(inserted-triples: admin={} attachment={} maintainer={} member={} observer={} subspace={}) "
327
                        + "structuralInvalidation={} structuralAdds={} durationMs={}",
328
                graph, lastProcessed, currentLoadCounter,
×
329
                totals.adminRIs(), totals.attachmentRAs(), totals.nonAdminRIs(),
×
330
                counts.admin, counts.attachment, counts.maintainer, counts.member, counts.observer, counts.subSpace,
×
331
                structuralInvalidation, structuralAdds, durationMs);
×
332
    }
×
333

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

376
    /**
377
     * Runs the four leaf tiers (attachment/maintainer/member/observer) with
378
     * {@code lastProcessed = -1} so the load-number filter on the candidate
379
     * side admits everything. Dedup filters in the tier templates prevent
380
     * double-insert. Used by the late-arrival sweep.
381
     */
382
    TierInsertedTriples runDownstreamWithoutLoadFilter(IRI graph) {
383
        TierInsertedTriples c = new TierInsertedTriples();
×
384
        // Sub-space late-arrival: catches Mode-B candidates whose primary
385
        // declaration is older than lastProcessed but whose partner just landed.
386
        c.subSpace = runTierLabeled("subspace(late)", graph,
×
387
                subSpaceAdmitUpdate(graph, -1));
×
388
        c.attachment = runTierLabeled("attachment(late)", graph,
×
389
                attachmentValidationUpdate(graph, -1));
×
390
        c.maintainer = runTierLabeled("maintainer(late)", graph,
×
391
                nonAdminTierUpdate(graph, -1, GEN.MAINTAINER_ROLE, PUBLISHER_IS_ADMIN));
×
392
        c.member = runTierLabeled("member(admin-pub,late)", graph,
×
393
                nonAdminTierUpdate(graph, -1, GEN.MEMBER_ROLE, PUBLISHER_IS_ADMIN));
×
394
        c.member += runTierLabeled("member(maint-pub,late)", graph,
×
395
                nonAdminTierUpdate(graph, -1,
×
396
                        GEN.MEMBER_ROLE, publisherIsTieredRole(GEN.MAINTAINER_ROLE)));
×
397
        c.observer = runTierLabeled("observer(admin-pub,late)", graph,
×
398
                nonAdminTierUpdate(graph, -1, GEN.OBSERVER_ROLE, PUBLISHER_IS_ADMIN));
×
399
        c.observer += runTierLabeled("observer(maint-pub,late)", graph,
×
400
                nonAdminTierUpdate(graph, -1,
×
401
                        GEN.OBSERVER_ROLE, publisherIsTieredRole(GEN.MAINTAINER_ROLE)));
×
402
        c.observer += runTierLabeled("observer(member-pub,late)", graph,
×
403
                nonAdminTierUpdate(graph, -1,
×
404
                        GEN.OBSERVER_ROLE, publisherIsTieredRole(GEN.MEMBER_ROLE)));
×
405
        c.observer += runTierLabeled("observer(self,late)", graph,
×
406
                nonAdminTierUpdate(graph, -1, GEN.OBSERVER_ROLE, PUBLISHER_IS_SELF));
×
407
        return c;
×
408
    }
409

410
    /**
411
     * Cheap ASK: did any new {@code npa:RoleDeclaration} extraction land in the
412
     * load-number delta {@code (lastProcessed, ∞)}? Used by the late-arrival
413
     * trigger so an RD that arrives in the same cycle as a matching candidate
414
     * still gets validated.
415
     */
416
    boolean newRoleDeclarationsArrived(long lastProcessed) {
417
        String ask = String.format("""
×
418
                PREFIX npa: <%1$s>
419
                ASK {
420
                  GRAPH <%2$s> {
421
                    ?rd a npa:RoleDeclaration ;
422
                        npa:viaNanopub ?np .
423
                  }
424
                  GRAPH <%3$s> {
425
                    ?np npa:hasLoadNumber ?ln .
426
                    FILTER (?ln > %4$d)
427
                  }
428
                }
429
                """, NPA.NAMESPACE, SpacesVocab.SPACES_GRAPH, NPA.GRAPH, lastProcessed);
×
430
        return runAsk(ask);
×
431
    }
432

433
    // ---------------- Tier UPDATE loops ----------------
434

435
    /**
436
     * Per-tier inserted-triple tallies for one build or cycle. Counts the sum
437
     * of {@code (graphSize_after - graphSize_before)} across all iterations of
438
     * each tier's fixed-point INSERT loop — i.e. inserted *triples*, not
439
     * distinct subjects (a single RoleInstantiation insert writes 4–5 triples).
440
     *
441
     * <p>Used internally by the {@link #runIncrementalCycle structuralAdds}
442
     * boolean check (we only care whether any tier inserted at all).
443
     * Not what the log lines report: see {@link TierSubjectTotals} +
444
     * {@link #computeTierSubjectTotals} for the distinct-subject totals
445
     * surfaced to operators.
446
     */
447
    static final class TierInsertedTriples {
×
448
        int admin;
449
        int attachment;
450
        int maintainer;
451
        int member;
452
        int observer;
453
        int subSpace;
454
    }
455

456
    /**
457
     * Snapshot of distinct-subject totals in a space-state graph at a moment
458
     * in time. Independent of which tier-loop added each subject.
459
     */
460
    record TierSubjectTotals(long adminRIs, long attachmentRAs, long nonAdminRIs) {}
36✔
461

462
    /**
463
     * Runs the five tier loops in order: admin → {@code gen:hasRole} attachment
464
     * validation → maintainer → member → observer. Each loop iterates a SPARQL
465
     * INSERT to fixed point (no new triples added). Returns per-tier counts.
466
     *
467
     * @param graph         target space-state graph
468
     * @param lastProcessed load-number horizon; use {@code -1} for full build
469
     */
470
    TierInsertedTriples runAllTierLoops(IRI graph, long lastProcessed) {
471
        TierInsertedTriples c = new TierInsertedTriples();
×
472
        c.admin = runTierLabeled("admin", graph, adminTierUpdate(graph, lastProcessed));
×
473
        // Sub-space admit runs after admin closure has settled (Mode A + Mode B both
474
        // need the admin set). Independent of role tiers — order between subspace
475
        // and attachment / maintainer / member / observer doesn't matter.
476
        c.subSpace = runTierLabeled("subspace", graph, subSpaceAdmitUpdate(graph, lastProcessed));
×
477
        c.attachment = runTierLabeled("attachment", graph,
×
478
                attachmentValidationUpdate(graph, lastProcessed));
×
479
        c.maintainer = runTierLabeled("maintainer", graph, nonAdminTierUpdate(graph, lastProcessed,
×
480
                GEN.MAINTAINER_ROLE, PUBLISHER_IS_ADMIN));
481
        // Member tier: admin OR maintainer publisher — split into two simpler updates
482
        // so the query planner doesn't struggle with the UNION.
483
        c.member = runTierLabeled("member(admin-pub)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
484
                GEN.MEMBER_ROLE, PUBLISHER_IS_ADMIN));
485
        c.member += runTierLabeled("member(maint-pub)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
486
                GEN.MEMBER_ROLE, publisherIsTieredRole(GEN.MAINTAINER_ROLE)));
×
487
        // Observer tier: self-evidence OR a downward grant from any higher tier.
488
        // ObserverRole is the default tier when a role definition omits an
489
        // explicit subclass (see "Role types" in design-space-repositories.md), so
490
        // most "X assigned Y this role" nanopubs land here. Restricting the tier
491
        // to PUBLISHER_IS_SELF would silently drop those grants. The four
492
        // sub-loops mirror the trust-state's downward-only chain: admin grants
493
        // anything; maintainers and members grant observer; everyone may
494
        // self-attest.
495
        c.observer = runTierLabeled("observer(admin-pub)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
496
                GEN.OBSERVER_ROLE, PUBLISHER_IS_ADMIN));
497
        c.observer += runTierLabeled("observer(maint-pub)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
498
                GEN.OBSERVER_ROLE, publisherIsTieredRole(GEN.MAINTAINER_ROLE)));
×
499
        c.observer += runTierLabeled("observer(member-pub)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
500
                GEN.OBSERVER_ROLE, publisherIsTieredRole(GEN.MEMBER_ROLE)));
×
501
        c.observer += runTierLabeled("observer(self)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
502
                GEN.OBSERVER_ROLE, PUBLISHER_IS_SELF));
503
        return c;
×
504
    }
505

506
    /**
507
     * Builds a publisher constraint requiring the publisher to be a validated holder
508
     * of the given tier's role (maintainer or member) in the target space.
509
     * Owns its own AccountState resolution so ?publisher is bound through the
510
     * targeted (pkh → agent) lookup rather than enumerated.
511
     */
512
    private static String publisherIsTieredRole(IRI tierClass) {
513
        return """
×
514
                ?acct a npa:AccountState ;
515
                      npa:pubkey ?pkh ;
516
                      npa:agent  ?publisher .
517
                ?tierRI a gen:RoleInstantiation ;
518
                        npa:forSpace ?space ;
519
                        npa:forAgent ?publisher .
520
                ?rdT a npa:RoleDeclaration ;
521
                     npa:hasRoleType <%1$s> .
522
                { ?tierRI npa:regularProperty ?predT . ?rdT gen:hasRegularProperty ?predT . }
523
                UNION
524
                { ?tierRI npa:inverseProperty ?predT . ?rdT gen:hasInverseProperty ?predT . }
525
                """.formatted(tierClass);
×
526
    }
527

528
    /** Wraps {@link #runTierLoop} with tier-name context for logs/exceptions. */
529
    private int runTierLabeled(String tier, IRI graph, String sparqlUpdate) {
530
        try {
531
            return runTierLoop(graph, sparqlUpdate);
×
532
        } catch (RuntimeException ex) {
×
533
            log.error("AuthorityResolver: tier={} failed with SPARQL UPDATE:\n{}\n", tier, sparqlUpdate, ex);
×
534
            throw ex;
×
535
        }
536
    }
537

538
    /**
539
     * Runs a single tier's INSERT to fixed point. Counts rows by probing
540
     * graph size before/after each INSERT; stops when the size doesn't change.
541
     *
542
     * @return total number of triples inserted by this tier across all iterations
543
     */
544
    int runTierLoop(IRI graph, String sparqlUpdate) {
545
        int total = 0;
×
546
        long before = graphSize(graph);
×
547
        while (true) {
548
            // Note: no explicit transaction wrapping here. In tests we observed that
549
            // HTTPRepository's RDF4J-transaction protocol silently no-op'd cross-graph
550
            // SPARQL UPDATEs with UNION sub-patterns inside conn.begin()/commit(),
551
            // while the same UPDATE POSTed directly to /statements applied correctly.
552
            // A bare prepareUpdate().execute() takes the direct /statements path and
553
            // runs the UPDATE atomically per SPARQL 1.1 semantics — which is all we
554
            // need; there's nothing else to commit atomically alongside the UPDATE.
555
            try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
556
                conn.prepareUpdate(QueryLanguage.SPARQL, sparqlUpdate).execute();
×
557
            }
558
            long after = graphSize(graph);
×
559
            long added = after - before;
×
560
            if (added <= 0) break;
×
561
            total += added;
×
562
            before = after;
×
563
        }
×
564
        return total;
×
565
    }
566

567
    private long graphSize(IRI graph) {
568
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
569
            return conn.size(graph);
×
570
        }
571
    }
572

573
    /**
574
     * Distinct-subject totals in the given space-state graph, broken down by
575
     * RoleInstantiation kind (admin-pinned vs not) and RoleAssignment.
576
     * Three SELECT-COUNT queries — cheap, called once per build/cycle for
577
     * the user-facing log line. Returns zeros on failure (logged) so a flaky
578
     * count read can't wedge the cycle.
579
     */
580
    TierSubjectTotals computeTierSubjectTotals(IRI graph) {
581
        long adminRIs       = countDistinctSubjects(graph, """
×
582
                ?ri a gen:RoleInstantiation ; npa:inverseProperty gen:hasAdmin .
583
                """, "ri");
584
        long attachmentRAs  = countDistinctSubjects(graph, """
×
585
                ?ra a gen:RoleAssignment .
586
                """, "ra");
587
        long nonAdminRIs    = countDistinctSubjects(graph, """
×
588
                ?ri a gen:RoleInstantiation .
589
                FILTER NOT EXISTS { ?ri npa:inverseProperty gen:hasAdmin }
590
                """, "ri");
591
        return new TierSubjectTotals(adminRIs, attachmentRAs, nonAdminRIs);
×
592
    }
593

594
    private long countDistinctSubjects(IRI graph, String wherePattern, String varName) {
595
        String query = String.format("""
×
596
                PREFIX npa: <%1$s>
597
                PREFIX gen: <%2$s>
598
                SELECT (COUNT(DISTINCT ?%3$s) AS ?n) WHERE {
599
                  GRAPH <%4$s> {
600
                    %5$s
601
                  }
602
                }
603
                """, NPA.NAMESPACE, GEN.NAMESPACE, varName, graph, wherePattern);
604
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO);
×
605
             TupleQueryResult r = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) {
×
606
            if (!r.hasNext()) return 0;
×
607
            return Long.parseLong(r.next().getBinding("n").getValue().stringValue());
×
608
        } catch (Exception ex) {
×
609
            log.warn("AuthorityResolver: countDistinctSubjects on {} failed: {}",
×
610
                    graph, ex.toString());
×
611
            return 0;
×
612
        }
613
    }
614

615
    // ---------------- SPARQL templates ----------------
616

617
    /**
618
     * Reusable invalidation filter on a bound nanopub-IRI variable. Pass the bare
619
     * variable name (no leading {@code ?}); e.g. {@code invalidationFilter("np")}
620
     * produces an outer-scoped {@code FILTER NOT EXISTS { GRAPH npa:spacesGraph
621
     * { ?_inv_np a npa:Invalidation ; npa:invalidates ?np . } }}.
622
     *
623
     * <p>Important: this filter must be placed OUTSIDE the surrounding
624
     * {@code GRAPH npa:spacesGraph { ... }} block, not nested inside it. When
625
     * nested, RDF4J's planner couples the FILTER NOT EXISTS evaluation into the
626
     * join order (per-row scan of {@code ?_inv a npa:Invalidation} multiplied by
627
     * the candidate set), which we measured turning a 39ms query into a 60s+
628
     * timeout on the live observer-tier data. Outside the GRAPH block, the
629
     * planner defers the filter until {@code ?np}/{@code ?rdNp} are bound and
630
     * does a targeted index lookup.
631
     *
632
     * <p>Variable names must match {@code [A-Za-z0-9_]+} per SPARQL grammar —
633
     * embedding a {@code ?} inside {@code ?_inv_?np} would yield a parse error.
634
     */
635
    private static String invalidationFilter(String bareVarName) {
636
        return "FILTER NOT EXISTS { GRAPH <" + SpacesVocab.SPACES_GRAPH + "> {"
30✔
637
                + " ?_inv_" + bareVarName
638
                + " a <" + SpacesVocab.INVALIDATION + "> ; "
639
                + "<" + SpacesVocab.INVALIDATES + "> ?" + bareVarName + " . } }";
640
    }
641

642
    /**
643
     * Admin tier: seed from {@code npadef:...hasRootAdmin} (trusted by construction)
644
     * plus closed-over admin grants; insert any {@code gen:RoleInstantiation} with
645
     * {@code npa:inverseProperty gen:hasAdmin} whose publisher (resolved via mirrored
646
     * trust-approved AccountState) is already in the admin set.
647
     */
648
    static String adminTierUpdate(IRI graph, long lastProcessed) {
649
        // Order tuned for RDF4J's evaluator:
650
        //   1. Anchor on the small (seed UNION closed-over) set to bind ?publisher
651
        //      and ?space cheaply.
652
        //   2. Resolve ?pkh from the mirrored AccountState row (?publisher bound).
653
        //   3. Probe instantiations using the now-bound (?space, ?pkh) — targeted
654
        //      lookup, not a full RoleInstantiation scan.
655
        //   4. Load-number filter on bound ?np.
656
        //   5. Dedup at the end.
657
        return """
69✔
658
                PREFIX npa:  <%1$s>
659
                PREFIX gen:  <%2$s>
660
                INSERT { GRAPH <%3$s> {
661
                  ?ri a gen:RoleInstantiation ;
662
                      npa:forSpace ?space ;
663
                      npa:inverseProperty gen:hasAdmin ;
664
                      npa:forAgent ?agent ;
665
                      npa:viaNanopub ?np .
666
                } }
667
                WHERE {
668
                  # 1. Anchor: who is already an admin of which space?
669
                  {
670
                    # Seed branch: root-admin in a non-invalidated SpaceDefinition.
671
                    GRAPH <%4$s> {
672
                      ?def a npa:SpaceDefinition ;
673
                           npa:forSpaceRef  ?spaceRef ;
674
                           npa:hasRootAdmin ?publisher ;
675
                           npa:viaNanopub   ?defNp .
676
                      ?spaceRef npa:spaceIri ?space .
677
                    }
678
                    %7$s
679
                  }
680
                  UNION
681
                  {
682
                    # Closed-over branch: an existing admin in this space-state graph.
683
                    GRAPH <%3$s> {
684
                      ?prev a gen:RoleInstantiation ;
685
                            npa:forSpace        ?space ;
686
                            npa:inverseProperty gen:hasAdmin ;
687
                            npa:forAgent        ?publisher .
688
                    }
689
                  }
690
                  # 2. Mirror: resolve ?publisher → ?pkh via the trust-approved row.
691
                  GRAPH <%3$s> {
692
                    ?acct a npa:AccountState ;
693
                          npa:agent  ?publisher ;
694
                          npa:pubkey ?pkh .
695
                  }
696
                  # 3. Targeted instantiation lookup by space + pubkey.
697
                  GRAPH <%4$s> {
698
                    ?ri a gen:RoleInstantiation ;
699
                        npa:forSpace        ?space ;
700
                        npa:inverseProperty gen:hasAdmin ;
701
                        npa:forAgent        ?agent ;
702
                        npa:pubkeyHash      ?pkh ;
703
                        npa:viaNanopub      ?np .
704
                  }
705
                  %6$s
706
                  # 4. Load-number filter on bound ?np.
707
                  GRAPH <%8$s> {
708
                    ?np npa:hasLoadNumber ?ln .
709
                    FILTER (?ln > %5$d)
710
                  }
711
                  # 5. Dedup last.
712
                  FILTER NOT EXISTS { GRAPH <%3$s> {
713
                    ?existing a gen:RoleInstantiation ;
714
                              npa:forSpace ?space ;
715
                              npa:forAgent ?agent ;
716
                              npa:inverseProperty gen:hasAdmin .
717
                  } }
718
                }
719
                """.formatted(
3✔
720
                NPA.NAMESPACE,
721
                GEN.NAMESPACE,
722
                graph,
723
                SpacesVocab.SPACES_GRAPH,
724
                lastProcessed,
15✔
725
                invalidationFilter("np"),
15✔
726
                invalidationFilter("defNp"),
18✔
727
                NPA.GRAPH);
728
    }
729

730
    /**
731
     * {@code gen:hasRole} attachment validation: an attachment is validated iff its
732
     * publisher is already a validated admin of the target space. Adds
733
     * {@code gen:RoleAssignment} rows to the space-state graph.
734
     */
735
    static String attachmentValidationUpdate(IRI graph, long lastProcessed) {
736
        return """
69✔
737
                PREFIX npa:  <%1$s>
738
                PREFIX gen:  <%2$s>
739
                INSERT { GRAPH <%3$s> {
740
                  ?ra a gen:RoleAssignment ;
741
                      npa:forSpace ?space ;
742
                      gen:hasRole  ?role ;
743
                      npa:viaNanopub ?np .
744
                } }
745
                WHERE {
746
                  GRAPH <%4$s> {
747
                    ?ra a gen:RoleAssignment ;
748
                        npa:forSpace ?space ;
749
                        gen:hasRole  ?role ;
750
                        npa:pubkeyHash ?pkh ;
751
                        npa:viaNanopub ?np .
752
                  }
753
                  GRAPH <%7$s> {
754
                    ?np npa:hasLoadNumber ?ln .
755
                    FILTER (?ln > %5$d)
756
                  }
757
                  GRAPH <%3$s> {
758
                    ?acct a npa:AccountState ;
759
                          npa:agent  ?publisher ;
760
                          npa:pubkey ?pkh .
761
                    ?adminRI a gen:RoleInstantiation ;
762
                             npa:forSpace ?space ;
763
                             npa:inverseProperty gen:hasAdmin ;
764
                             npa:forAgent ?publisher .
765
                  }
766
                  %6$s
767
                  FILTER NOT EXISTS { GRAPH <%3$s> {
768
                    ?existing a gen:RoleAssignment ;
769
                              npa:forSpace ?space ;
770
                              gen:hasRole  ?role .
771
                  } }
772
                }
773
                """.formatted(
3✔
774
                NPA.NAMESPACE,
775
                GEN.NAMESPACE,
776
                graph,
777
                SpacesVocab.SPACES_GRAPH,
778
                lastProcessed,
15✔
779
                invalidationFilter("np"),
18✔
780
                NPA.GRAPH);
781
    }
782

783
    /**
784
     * Non-admin tier publisher constraints (inserted as a SPARQL sub-pattern).
785
     * Each constraint owns the AccountState (pkh → agent) lookup so the join
786
     * variable is bound through a targeted pattern. The observer-self variant
787
     * binds {@code npa:agent ?agent} directly — no separate {@code ?publisher}
788
     * variable, no post-join equality filter — which lets the planner anchor
789
     * the AccountState lookup on the already-bound {@code ?agent} instead of
790
     * enumerating all approved publishers and filtering at the end.
791
     */
792
    static final String PUBLISHER_IS_ADMIN = """
793
            ?acct a npa:AccountState ;
794
                  npa:pubkey ?pkh ;
795
                  npa:agent  ?publisher .
796
            ?adminRI a gen:RoleInstantiation ;
797
                     npa:forSpace ?space ;
798
                     npa:inverseProperty gen:hasAdmin ;
799
                     npa:forAgent ?publisher .
800
            """;
801

802
    /** Observer self-evidence: the assignee's own pubkey signed the instantiation. */
803
    static final String PUBLISHER_IS_SELF = """
804
            ?acct a npa:AccountState ;
805
                  npa:pubkey ?pkh ;
806
                  npa:agent  ?agent .
807
            """;
808

809
    /**
810
     * Maintainer / Member / Observer tier INSERT. Same shape: find an instantiation
811
     * whose predicate matches a RoleDeclaration of the given tier attached to the
812
     * target space, and whose publisher passes the tier-specific constraint.
813
     */
814
    static String nonAdminTierUpdate(IRI graph, long lastProcessed,
815
                                     IRI tierClass, String publisherConstraint) {
816
        // Order tuned for RDF4J's evaluator (which executes BGPs roughly in order).
817
        // The crucial choice is the *anchor*: instantiation-first plans send the
818
        // planner exploring the full ~thousands of candidate RIs and only filter
819
        // by tier at the very end. Attachment-first anchors on the small set of
820
        // gen:RoleAssignment rows already validated in this space-state graph
821
        // (~hundreds, often zero) and walks outward by bound (?role, ?space).
822
        //
823
        //   1. Anchor on RoleAssignments in this space-state graph (small).
824
        //   2. Match the tier-pinned RoleDeclaration by ?role.
825
        //   3. Pair role-decl direction to instantiation direction in one UNION
826
        //      so only (reg, reg)/(inv, inv) combos are explored.
827
        //   4. Targeted instantiation lookup — (?space, ?pred) are bound.
828
        //   5. Publisher constraint (incl. AccountState resolution).
829
        //   6. Load-number filter on bound ?np.
830
        //   7. Dedup at the end.
831
        return """
69✔
832
                PREFIX npa:  <%1$s>
833
                PREFIX gen:  <%2$s>
834
                INSERT { GRAPH <%3$s> {
835
                  ?ri a gen:RoleInstantiation ;
836
                      npa:forSpace ?space ;
837
                      npa:forAgent ?agent ;
838
                      npa:viaNanopub ?np .
839
                } }
840
                WHERE {
841
                  # 1. Anchor: validated attachments in this space-state graph.
842
                  GRAPH <%3$s> {
843
                    ?ra a gen:RoleAssignment ;
844
                        gen:hasRole  ?role ;
845
                        npa:forSpace ?space .
846
                  }
847
                  # 2. Tier-pinned RoleDeclaration (?role bound from the attachment).
848
                  GRAPH <%4$s> {
849
                    ?rd a npa:RoleDeclaration ;
850
                        npa:hasRoleType <%7$s> ;
851
                        npa:role        ?role ;
852
                        npa:viaNanopub  ?rdNp .
853
                    # 3. Pair direction so only matching combos are explored.
854
                    {
855
                      ?rd gen:hasRegularProperty ?pred .
856
                      ?ri npa:regularProperty    ?pred .
857
                    }
858
                    UNION
859
                    {
860
                      ?rd gen:hasInverseProperty ?pred .
861
                      ?ri npa:inverseProperty    ?pred .
862
                    }
863
                    # 4. Targeted instantiation lookup — (?space, ?pred) bound.
864
                    ?ri a gen:RoleInstantiation ;
865
                        npa:forSpace   ?space ;
866
                        npa:forAgent   ?agent ;
867
                        npa:pubkeyHash ?pkh ;
868
                        npa:viaNanopub ?np .
869
                  }
870
                  # 5. Publisher constraint (incl. AccountState resolution).
871
                  GRAPH <%3$s> {
872
                    %9$s
873
                  }
874
                  # 6. Load-number filter on bound ?np.
875
                  GRAPH <%10$s> {
876
                    ?np npa:hasLoadNumber ?ln .
877
                    FILTER (?ln > %5$d)
878
                  }
879
                  # 7. Invalidation filters — outside the GRAPH block so the
880
                  #    planner defers them until ?rdNp/?np are bound.
881
                  %8$s
882
                  %6$s
883
                  # 8. Dedup last.
884
                  FILTER NOT EXISTS { GRAPH <%3$s> {
885
                    ?existing a gen:RoleInstantiation ;
886
                              npa:forSpace ?space ;
887
                              npa:forAgent ?agent ;
888
                              npa:viaNanopub ?np .
889
                  } }
890
                }
891
                """.formatted(
3✔
892
                NPA.NAMESPACE,
893
                GEN.NAMESPACE,
894
                graph,
895
                SpacesVocab.SPACES_GRAPH,
896
                lastProcessed,
15✔
897
                invalidationFilter("np"),
27✔
898
                tierClass,
899
                invalidationFilter("rdNp"),
30✔
900
                publisherConstraint,
901
                NPA.GRAPH);
902
    }
903

904
    /**
905
     * Sub-space admit pass. Copies validated {@code npa:SubSpaceDeclaration}
906
     * extraction rows into the space-state graph (preserving the {@code npasub:}
907
     * subject) and emits convenience {@code <child> npa:isSubSpaceOf <parent>} and
908
     * {@code <parent> npa:hasSubSpace <child>} direct triples. Two satisfaction
909
     * modes joined by UNION:
910
     * <ul>
911
     *   <li>Mode A — the declaration's publisher is a validated admin of both the
912
     *       child and the parent space.</li>
913
     *   <li>Mode B — a different non-invalidated declaration for the same
914
     *       {@code (child, parent)} pair exists, and the two publishers between
915
     *       them cover both admin sides (i.e. one of them is admin of the child,
916
     *       one of them is admin of the parent — possibly the same one twice if
917
     *       both happen to be admin of both).</li>
918
     * </ul>
919
     *
920
     * <p>Mode-B late-arrival: when only the partner declaration is new in this
921
     * cycle (the primary is older than {@code lastProcessed}), the load-number
922
     * filter on {@code ?np} excludes the candidate. The late-arrival sweep
923
     * ({@link #runDownstreamWithoutLoadFilter}) re-runs this pass without the
924
     * load filter and catches it.
925
     */
926
    static String subSpaceAdmitUpdate(IRI graph, long lastProcessed) {
927
        return """
69✔
928
                PREFIX npa: <%1$s>
929
                PREFIX gen: <%2$s>
930
                INSERT { GRAPH <%3$s> {
931
                  ?d a npa:SubSpaceDeclaration ;
932
                     npa:childSpace  ?child ;
933
                     npa:parentSpace ?parent ;
934
                     npa:viaNanopub  ?np .
935
                  ?child  npa:isSubSpaceOf ?parent .
936
                  ?parent npa:hasSubSpace  ?child  .
937
                } }
938
                WHERE {
939
                  # 1. Anchor: candidate declarations from the extraction graph.
940
                  GRAPH <%4$s> {
941
                    ?d a npa:SubSpaceDeclaration ;
942
                       npa:childSpace  ?child ;
943
                       npa:parentSpace ?parent ;
944
                       npa:pubkeyHash  ?pkh ;
945
                       npa:viaNanopub  ?np .
946
                  }
947
                  # 2. Mirror: resolve ?pkh → ?publisher via the trust-approved row.
948
                  GRAPH <%3$s> {
949
                    ?acct a npa:AccountState ;
950
                          npa:pubkey ?pkh ;
951
                          npa:agent  ?publisher .
952
                  }
953
                  # 3. Authority gate.
954
                  {
955
                    # Mode A — publisher is admin of BOTH child and parent.
956
                    FILTER EXISTS { GRAPH <%3$s> {
957
                      ?riC a gen:RoleInstantiation ;
958
                           npa:inverseProperty gen:hasAdmin ;
959
                           npa:forSpace ?child ;
960
                           npa:forAgent ?publisher .
961
                    } }
962
                    FILTER EXISTS { GRAPH <%3$s> {
963
                      ?riP a gen:RoleInstantiation ;
964
                           npa:inverseProperty gen:hasAdmin ;
965
                           npa:forSpace ?parent ;
966
                           npa:forAgent ?publisher .
967
                    } }
968
                  }
969
                  UNION
970
                  {
971
                    # Mode B — co-declaration whose publisher covers the side this
972
                    # one's publisher doesn't. Between {publisher, publisher2},
973
                    # both admin sides must be covered.
974
                    GRAPH <%4$s> {
975
                      ?d2 a npa:SubSpaceDeclaration ;
976
                          npa:childSpace  ?child ;
977
                          npa:parentSpace ?parent ;
978
                          npa:pubkeyHash  ?pkh2 ;
979
                          npa:viaNanopub  ?np2 .
980
                      FILTER (?np2 != ?np)
981
                    }
982
                    %8$s
983
                    GRAPH <%3$s> {
984
                      ?acct2 a npa:AccountState ;
985
                             npa:pubkey ?pkh2 ;
986
                             npa:agent  ?publisher2 .
987
                    }
988
                    FILTER EXISTS { GRAPH <%3$s> {
989
                      ?riA a gen:RoleInstantiation ;
990
                           npa:inverseProperty gen:hasAdmin ;
991
                           npa:forSpace ?child .
992
                      { ?riA npa:forAgent ?publisher } UNION { ?riA npa:forAgent ?publisher2 }
993
                    } }
994
                    FILTER EXISTS { GRAPH <%3$s> {
995
                      ?riB a gen:RoleInstantiation ;
996
                           npa:inverseProperty gen:hasAdmin ;
997
                           npa:forSpace ?parent .
998
                      { ?riB npa:forAgent ?publisher } UNION { ?riB npa:forAgent ?publisher2 }
999
                    } }
1000
                  }
1001
                  # 4. Invalidation filter on the primary declaration's nanopub.
1002
                  %6$s
1003
                  # 5. Load-number filter on bound ?np.
1004
                  GRAPH <%7$s> {
1005
                    ?np npa:hasLoadNumber ?ln .
1006
                    FILTER (?ln > %5$d)
1007
                  }
1008
                  # 6. Dedup last.
1009
                  FILTER NOT EXISTS { GRAPH <%3$s> {
1010
                    ?d a npa:SubSpaceDeclaration .
1011
                  } }
1012
                }
1013
                """.formatted(
3✔
1014
                NPA.NAMESPACE,
1015
                GEN.NAMESPACE,
1016
                graph,
1017
                SpacesVocab.SPACES_GRAPH,
1018
                lastProcessed,
15✔
1019
                invalidationFilter("np"),
27✔
1020
                NPA.GRAPH,
1021
                invalidationFilter("np2"));
6✔
1022
    }
1023

1024
    // ---------------- Invalidation templates (incremental cycle) ----------------
1025

1026
    /**
1027
     * WHERE clause shared by the admin-RI invalidation ASK precheck and the
1028
     * matching DELETE. Identifies admin-tier {@code gen:RoleInstantiation} rows
1029
     * in the space-state graph whose {@code npa:viaNanopub} equals the target
1030
     * of an {@code npa:Invalidation} that landed in {@code (lastProcessed, ∞)}.
1031
     */
1032
    static String adminInvalidationCheckWhere(IRI graph, long lastProcessed) {
1033
        return String.format("""
60✔
1034
                  GRAPH <%1$s> {
1035
                    ?ri a gen:RoleInstantiation ;
1036
                        npa:inverseProperty gen:hasAdmin ;
1037
                        npa:viaNanopub ?np .
1038
                  }
1039
                  GRAPH <%2$s> {
1040
                    ?inv a npa:Invalidation ;
1041
                         npa:invalidates ?np ;
1042
                         npa:viaNanopub  ?invNp .
1043
                  }
1044
                  GRAPH <%3$s> {
1045
                    ?invNp npa:hasLoadNumber ?ln .
1046
                    FILTER (?ln > %4$d)
1047
                  }
1048
                """, graph, SpacesVocab.SPACES_GRAPH, NPA.GRAPH, lastProcessed);
6✔
1049
    }
1050

1051
    /** DELETE template for admin-tier RoleInstantiations whose source nanopub was invalidated. */
1052
    static String adminInvalidationDelete(IRI graph, long lastProcessed) {
1053
        return String.format("""
63✔
1054
                PREFIX npa: <%1$s>
1055
                PREFIX gen: <%2$s>
1056
                DELETE { GRAPH <%3$s> {
1057
                  ?ri ?p ?o .
1058
                } }
1059
                WHERE {
1060
                  GRAPH <%3$s> { ?ri ?p ?o . }
1061
                %4$s
1062
                }
1063
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
1064
                adminInvalidationCheckWhere(graph, lastProcessed));
6✔
1065
    }
1066

1067
    /** WHERE clause for RoleAssignment invalidation. */
1068
    static String roleAssignmentInvalidationCheckWhere(IRI graph, long lastProcessed) {
1069
        return String.format("""
60✔
1070
                  GRAPH <%1$s> {
1071
                    ?ra a gen:RoleAssignment ;
1072
                        npa:viaNanopub ?np .
1073
                  }
1074
                  GRAPH <%2$s> {
1075
                    ?inv a npa:Invalidation ;
1076
                         npa:invalidates ?np ;
1077
                         npa:viaNanopub  ?invNp .
1078
                  }
1079
                  GRAPH <%3$s> {
1080
                    ?invNp npa:hasLoadNumber ?ln .
1081
                    FILTER (?ln > %4$d)
1082
                  }
1083
                """, graph, SpacesVocab.SPACES_GRAPH, NPA.GRAPH, lastProcessed);
6✔
1084
    }
1085

1086
    /** DELETE template for RoleAssignments whose source nanopub was invalidated. */
1087
    static String roleAssignmentInvalidationDelete(IRI graph, long lastProcessed) {
1088
        return String.format("""
63✔
1089
                PREFIX npa: <%1$s>
1090
                PREFIX gen: <%2$s>
1091
                DELETE { GRAPH <%3$s> {
1092
                  ?ra ?p ?o .
1093
                } }
1094
                WHERE {
1095
                  GRAPH <%3$s> { ?ra ?p ?o . }
1096
                %4$s
1097
                }
1098
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
1099
                roleAssignmentInvalidationCheckWhere(graph, lastProcessed));
6✔
1100
    }
1101

1102
    /**
1103
     * WHERE clause for RoleDeclaration invalidation. ASK-only (no DELETE):
1104
     * RoleDeclarations live in {@code npa:spacesGraph} and aren't materialized
1105
     * into the space-state graph, so there's nothing to remove from the
1106
     * space-state. The ASK still flips {@code npa:needsFullRebuild} because
1107
     * sticky downstream RIs that were derived under the now-invalidated RD
1108
     * need a from-scratch recompute.
1109
     */
1110
    static String roleDeclarationInvalidationCheckWhere(long lastProcessed) {
1111
        return String.format("""
48✔
1112
                  GRAPH <%1$s> {
1113
                    ?rd a npa:RoleDeclaration ;
1114
                        npa:viaNanopub ?np .
1115
                    ?inv a npa:Invalidation ;
1116
                         npa:invalidates ?np ;
1117
                         npa:viaNanopub  ?invNp .
1118
                  }
1119
                  GRAPH <%2$s> {
1120
                    ?invNp npa:hasLoadNumber ?ln .
1121
                    FILTER (?ln > %3$d)
1122
                  }
1123
                """, SpacesVocab.SPACES_GRAPH, NPA.GRAPH, lastProcessed);
6✔
1124
    }
1125

1126
    /**
1127
     * DELETE template for non-admin (leaf-tier) RoleInstantiations whose source
1128
     * nanopub was invalidated. Identified as {@code gen:RoleInstantiation} rows
1129
     * lacking the admin-pinning {@code npa:inverseProperty gen:hasAdmin} triple.
1130
     * No flag is set; leaf-tier removals are recoverable on the next cycle.
1131
     */
1132
    static String leafTierInvalidationDelete(IRI graph, long lastProcessed) {
1133
        return String.format("""
84✔
1134
                PREFIX npa: <%1$s>
1135
                PREFIX gen: <%2$s>
1136
                DELETE { GRAPH <%3$s> {
1137
                  ?ri ?p ?o .
1138
                } }
1139
                WHERE {
1140
                  GRAPH <%3$s> {
1141
                    ?ri a gen:RoleInstantiation ;
1142
                        npa:viaNanopub ?np .
1143
                    FILTER NOT EXISTS { ?ri npa:inverseProperty gen:hasAdmin }
1144
                    ?ri ?p ?o .
1145
                  }
1146
                  GRAPH <%4$s> {
1147
                    ?inv a npa:Invalidation ;
1148
                         npa:invalidates ?np ;
1149
                         npa:viaNanopub  ?invNp .
1150
                  }
1151
                  GRAPH <%5$s> {
1152
                    ?invNp npa:hasLoadNumber ?ln .
1153
                    FILTER (?ln > %6$d)
1154
                  }
1155
                }
1156
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
1157
                SpacesVocab.SPACES_GRAPH, NPA.GRAPH, lastProcessed);
6✔
1158
    }
1159

1160
    /**
1161
     * WHERE clause shared by the sub-space invalidation ASK precheck and the
1162
     * matching DELETE. Identifies validated {@code npa:SubSpaceDeclaration} rows
1163
     * in the space-state graph whose {@code npa:viaNanopub} equals the target of
1164
     * an {@code npa:Invalidation} that landed in {@code (lastProcessed, ∞)}.
1165
     */
1166
    static String subSpaceInvalidationCheckWhere(IRI graph, long lastProcessed) {
1167
        return String.format("""
60✔
1168
                  GRAPH <%1$s> {
1169
                    ?d a npa:SubSpaceDeclaration ;
1170
                       npa:viaNanopub ?np .
1171
                  }
1172
                  GRAPH <%2$s> {
1173
                    ?inv a npa:Invalidation ;
1174
                         npa:invalidates ?np ;
1175
                         npa:viaNanopub  ?invNp .
1176
                  }
1177
                  GRAPH <%3$s> {
1178
                    ?invNp npa:hasLoadNumber ?ln .
1179
                    FILTER (?ln > %4$d)
1180
                  }
1181
                """, graph, SpacesVocab.SPACES_GRAPH, NPA.GRAPH, lastProcessed);
6✔
1182
    }
1183

1184
    /**
1185
     * DELETE template for validated {@code npa:SubSpaceDeclaration} rows whose
1186
     * source nanopub was invalidated. Removes the per-declaration row by subject;
1187
     * the convenience direct triples ({@code <child> npa:isSubSpaceOf <parent>}
1188
     * and inverse) are left sticky and cleaned by the next periodic full rebuild
1189
     * (same staleness policy as admin-RI invalidation — see {@code
1190
     * doc/design-space-repositories.md} on the structural-rebuild flag).
1191
     */
1192
    static String subSpaceInvalidationDelete(IRI graph, long lastProcessed) {
1193
        return String.format("""
63✔
1194
                PREFIX npa: <%1$s>
1195
                PREFIX gen: <%2$s>
1196
                DELETE { GRAPH <%3$s> {
1197
                  ?d ?p ?o .
1198
                } }
1199
                WHERE {
1200
                  GRAPH <%3$s> { ?d ?p ?o . }
1201
                %4$s
1202
                }
1203
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
1204
                subSpaceInvalidationCheckWhere(graph, lastProcessed));
6✔
1205
    }
1206

1207
    /** Wraps an ASK by joining the shared prefixes. */
1208
    private boolean wouldInvalidate(IRI graph, long lastProcessed,
1209
                                    boolean adminPinned, String whereClause) {
1210
        // adminPinned is informational only — kept to make call sites read clearly;
1211
        // the WHERE clause already encodes the kind via its own type predicates.
1212
        String ask = String.format("""
×
1213
                PREFIX npa: <%1$s>
1214
                PREFIX gen: <%2$s>
1215
                ASK { %3$s }
1216
                """, NPA.NAMESPACE, GEN.NAMESPACE, whereClause);
1217
        return runAsk(ask);
×
1218
    }
1219

1220
    private boolean runAsk(String sparql) {
1221
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1222
            return conn.prepareBooleanQuery(QueryLanguage.SPARQL, sparql).evaluate();
×
1223
        }
1224
    }
1225

1226
    private void executeUpdate(String sparqlUpdate) {
1227
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1228
            conn.prepareUpdate(QueryLanguage.SPARQL, sparqlUpdate).execute();
×
1229
        }
1230
    }
×
1231

1232
    // ---------------- Mirror step ----------------
1233

1234
    /**
1235
     * Copies trust-approved {@code npa:AccountState} rows from {@code npat:<T>}
1236
     * in the {@code trust} repo into {@code newGraph} in the {@code spaces} repo,
1237
     * inside one spaces-side serializable transaction.
1238
     *
1239
     * @return number of rows mirrored (useful for metrics / logging)
1240
     */
1241
    int mirrorTrustState(String trustStateHash, IRI newGraph) {
1242
        IRI trustStateIri = NPAT.forHash(trustStateHash);
×
1243
        int count = 0;
×
1244
        try (RepositoryConnection trustConn = TripleStore.get().getRepoConnection(TRUST_REPO);
×
1245
             RepositoryConnection spacesConn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1246
            trustConn.begin(IsolationLevels.READ_COMMITTED);
×
1247
            spacesConn.begin(IsolationLevels.SERIALIZABLE);
×
1248
            // Walk rdf:type triples in the trust state's graph; for each AccountState,
1249
            // check status and copy the approved ones verbatim (minus status-specific
1250
            // detail triples, which we don't need for validation).
1251
            try (RepositoryResult<Statement> typeRows = trustConn.getStatements(
×
1252
                    null, RDF.TYPE, NPA_ACCOUNT_STATE, trustStateIri)) {
1253
                while (typeRows.hasNext()) {
×
1254
                    Statement st = typeRows.next();
×
1255
                    if (!(st.getSubject() instanceof IRI accountStateIri)) continue;
×
1256
                    Value status = trustConn.getStatements(accountStateIri, NPA_TRUST_STATUS, null, trustStateIri)
×
1257
                            .stream().findFirst().map(Statement::getObject).orElse(null);
×
1258
                    if (!(status instanceof IRI statusIri) || !APPROVED_SET.contains(statusIri)) continue;
×
1259
                    Value agent = trustConn.getStatements(accountStateIri, NPA_AGENT, null, trustStateIri)
×
1260
                            .stream().findFirst().map(Statement::getObject).orElse(null);
×
1261
                    Value pubkey = trustConn.getStatements(accountStateIri, NPA_PUBKEY, null, trustStateIri)
×
1262
                            .stream().findFirst().map(Statement::getObject).orElse(null);
×
1263
                    if (agent == null || pubkey == null) {
×
1264
                        log.warn("AuthorityResolver.mirror: account {} missing agent or pubkey; skipping",
×
1265
                                accountStateIri);
1266
                        continue;
×
1267
                    }
1268
                    spacesConn.add(accountStateIri, RDF.TYPE, NPA_ACCOUNT_STATE, newGraph);
×
1269
                    spacesConn.add(accountStateIri, NPA_AGENT, agent, newGraph);
×
1270
                    spacesConn.add(accountStateIri, NPA_PUBKEY, pubkey, newGraph);
×
1271
                    spacesConn.add(accountStateIri, NPA_TRUST_STATUS, statusIri, newGraph);
×
1272
                    count++;
×
1273
                }
×
1274
            }
1275
            // Mirror canonical foaf:name triples for approved agents. The trust
1276
            // loader emits one per agent (across approved keys, MAX(ratio) wins).
1277
            // Copying them into the space-state graph means consumers reading
1278
            // ?agent foaf:name ?n inside the state graph hit local data, with no
1279
            // cross-repo SERVICE.
1280
            try (RepositoryResult<Statement> nameRows = trustConn.getStatements(
×
1281
                    null, FOAF.NAME, null, trustStateIri)) {
1282
                while (nameRows.hasNext()) {
×
1283
                    Statement st = nameRows.next();
×
1284
                    spacesConn.add(st.getSubject(), st.getPredicate(), st.getObject(), newGraph);
×
1285
                }
×
1286
            }
1287
            spacesConn.commit();
×
1288
            trustConn.commit();
×
1289
        }
1290
        return count;
×
1291
    }
1292

1293
    // ---------------- Pointer + counter helpers ----------------
1294

1295
    /**
1296
     * Reads the current {@code npa:hasCurrentSpaceState} pointer from the
1297
     * {@code npa:graph} admin graph of the {@code spaces} repo. Returns
1298
     * {@code null} if no pointer exists yet.
1299
     */
1300
    IRI getCurrentSpaceStateGraph() {
1301
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1302
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
1303
                    SpacesVocab.HAS_CURRENT_SPACE_STATE);
1304
            return (v instanceof IRI iri) ? iri : null;
×
1305
        } catch (Exception ex) {
×
1306
            log.warn("AuthorityResolver: failed to read hasCurrentSpaceState pointer: {}", ex.toString());
×
1307
            return null;
×
1308
        }
1309
    }
1310

1311
    long getCurrentLoadCounter() {
1312
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1313
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
1314
                    SpacesVocab.CURRENT_LOAD_COUNTER);
1315
            if (v == null) return 0;
×
1316
            try {
1317
                return Long.parseLong(v.stringValue());
×
1318
            } catch (NumberFormatException ex) {
×
1319
                log.warn("AuthorityResolver: non-numeric currentLoadCounter: {}", v);
×
1320
                return 0;
×
1321
            }
1322
        } catch (Exception ex) {
×
1323
            log.warn("AuthorityResolver: failed to read currentLoadCounter: {}", ex.toString());
×
1324
            return 0;
×
1325
        }
1326
    }
1327

1328
    /**
1329
     * Atomic pointer flip: a single SPARQL {@code DELETE … INSERT … WHERE}
1330
     * replaces the old pointer with the new one in one statement, so readers
1331
     * never see a zero-pointer window.
1332
     */
1333
    void flipPointer(IRI newGraph) {
1334
        String update = String.format("""
×
1335
                DELETE { GRAPH <%s> { <%s> <%s> ?old } }
1336
                INSERT { GRAPH <%s> { <%s> <%s> <%s> } }
1337
                WHERE  { OPTIONAL { GRAPH <%s> { <%s> <%s> ?old } } }
1338
                """,
1339
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.HAS_CURRENT_SPACE_STATE,
1340
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.HAS_CURRENT_SPACE_STATE, newGraph,
1341
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.HAS_CURRENT_SPACE_STATE);
1342
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1343
            conn.begin(IsolationLevels.SERIALIZABLE);
×
1344
            conn.prepareUpdate(QueryLanguage.SPARQL, update).execute();
×
1345
            conn.commit();
×
1346
        }
1347
    }
×
1348

1349
    void writeProcessedUpTo(IRI graph, long loadCounter) {
1350
        String update = String.format("""
×
1351
                DELETE { GRAPH <%s> { <%s> <%s> ?old } }
1352
                INSERT { GRAPH <%s> { <%s> <%s> "%d"^^<http://www.w3.org/2001/XMLSchema#long> } }
1353
                WHERE  { OPTIONAL { GRAPH <%s> { <%s> <%s> ?old } } }
1354
                """,
1355
                graph, graph, SpacesVocab.PROCESSED_UP_TO,
1356
                graph, graph, SpacesVocab.PROCESSED_UP_TO, loadCounter,
×
1357
                graph, graph, SpacesVocab.PROCESSED_UP_TO);
1358
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1359
            conn.begin(IsolationLevels.SERIALIZABLE);
×
1360
            conn.prepareUpdate(QueryLanguage.SPARQL, update).execute();
×
1361
            conn.commit();
×
1362
        }
1363
    }
×
1364

1365
    /**
1366
     * Reads {@code processedUpTo} from the given space-state graph.
1367
     * Returns {@code -1} if absent (graph not fully built yet).
1368
     */
1369
    long readProcessedUpTo(IRI graph) {
1370
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1371
            String query = String.format(
×
1372
                    "SELECT ?n WHERE { GRAPH <%s> { <%s> <%s> ?n } }",
1373
                    graph, graph, SpacesVocab.PROCESSED_UP_TO);
1374
            try (TupleQueryResult r = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) {
×
1375
                if (!r.hasNext()) return -1;
×
1376
                BindingSet b = r.next();
×
1377
                return Long.parseLong(b.getBinding("n").getValue().stringValue());
×
1378
            }
×
1379
        } catch (Exception ex) {
×
1380
            log.warn("AuthorityResolver: failed to read processedUpTo for {}: {}", graph, ex.toString());
×
1381
            return -1;
×
1382
        }
1383
    }
1384

1385
    /**
1386
     * Reads the {@code npa:needsFullRebuild} flag (boolean literal) from
1387
     * {@code npa:graph} in the {@code spaces} repo. Defaults to {@code false}
1388
     * when the triple is absent.
1389
     */
1390
    boolean readNeedsFullRebuild() {
1391
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1392
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
1393
                    SpacesVocab.NEEDS_FULL_REBUILD);
1394
            return v != null && Boolean.parseBoolean(v.stringValue());
×
1395
        } catch (Exception ex) {
×
1396
            log.warn("AuthorityResolver: failed to read needsFullRebuild: {}", ex.toString());
×
1397
            return false;
×
1398
        }
1399
    }
1400

1401
    void setNeedsFullRebuild() {
1402
        writeNeedsFullRebuild(true);
×
1403
    }
×
1404

1405
    void clearNeedsFullRebuild() {
1406
        writeNeedsFullRebuild(false);
×
1407
    }
×
1408

1409
    private void writeNeedsFullRebuild(boolean value) {
1410
        String update = String.format("""
×
1411
                DELETE { GRAPH <%s> { <%s> <%s> ?old } }
1412
                INSERT { GRAPH <%s> { <%s> <%s> "%s"^^<http://www.w3.org/2001/XMLSchema#boolean> } }
1413
                WHERE  { OPTIONAL { GRAPH <%s> { <%s> <%s> ?old } } }
1414
                """,
1415
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.NEEDS_FULL_REBUILD,
1416
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.NEEDS_FULL_REBUILD, value,
×
1417
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.NEEDS_FULL_REBUILD);
1418
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1419
            conn.begin(IsolationLevels.SERIALIZABLE);
×
1420
            conn.prepareUpdate(QueryLanguage.SPARQL, update).execute();
×
1421
            conn.commit();
×
1422
        }
1423
    }
×
1424

1425
    void dropGraph(IRI graph) {
1426
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1427
            conn.begin(IsolationLevels.SERIALIZABLE);
×
1428
            conn.clear(graph);
×
1429
            conn.commit();
×
1430
            log.info("AuthorityResolver: dropped old space-state graph {}", graph);
×
1431
        }
1432
    }
×
1433

1434
    // ---------------- Trust-repo pointer lookup (used by TrustStateRegistry's bootstrap) ----------------
1435

1436
    /**
1437
     * Queries the {@code trust} repo directly for the current trust-state hash.
1438
     * Prefer {@link TrustStateRegistry#getCurrentHash()} in normal operation —
1439
     * this helper exists for tests and diagnostics.
1440
     *
1441
     * @return the current trust-state hash, or empty if none is set
1442
     */
1443
    Optional<String> readTrustRepoCurrentHash() {
1444
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(TRUST_REPO)) {
×
1445
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
1446
                    NPA_HAS_CURRENT_TRUST_STATE);
1447
            if (!(v instanceof IRI iri)) return Optional.empty();
×
1448
            String s = iri.stringValue();
×
1449
            if (!s.startsWith(NPAT.NAMESPACE)) return Optional.empty();
×
1450
            return Optional.of(s.substring(NPAT.NAMESPACE.length()));
×
1451
        } catch (Exception ex) {
×
1452
            log.warn("AuthorityResolver: failed to read trust-repo current pointer: {}", ex.toString());
×
1453
            return Optional.empty();
×
1454
        }
1455
    }
1456

1457
    private static String abbrev(String hash) {
1458
        return hash.length() > 12 ? hash.substring(0, 12) + "…" : hash;
×
1459
    }
1460

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