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

knowledgepixels / nanopub-query / 25011631105

27 Apr 2026 06:09PM UTC coverage: 56.687% (+0.1%) from 56.559%
25011631105

Pull #89

github

web-flow
Merge 5e4e24419 into 79fe0439b
Pull Request #89: feat: validate downward observer-tier grants from admin/maintainer/member (#62)

426 of 842 branches covered (50.59%)

Branch coverage included in aggregate %.

1189 of 2007 relevant lines covered (59.24%)

8.92 hits per line

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

12.69
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;
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={}) "
250
                        + "durationMs={}",
251
                newGraph, mirrored, loadCounter,
×
252
                totals.adminRIs(), totals.attachmentRAs(), totals.nonAdminRIs(),
×
253
                counts.admin, counts.attachment, counts.maintainer, counts.member, counts.observer,
×
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
                || newRoleDeclarationsArrived(lastProcessed);
×
299
        if (structuralAdds) {
×
300
            // Late-arrival sweep: only the leaf tiers (attachment/maintainer/member/observer)
301
            // can promote candidates whose enabling event arrived in this same cycle. Skip
302
            // the admin tier — its only enabling event is the admin grant itself, already
303
            // handled by the regular pass.
304
            TierInsertedTriples lateCounts = runDownstreamWithoutLoadFilter(graph);
×
305
            counts.attachment += lateCounts.attachment;
×
306
            counts.maintainer += lateCounts.maintainer;
×
307
            counts.member     += lateCounts.member;
×
308
            counts.observer   += lateCounts.observer;
×
309
        }
310

311
        writeProcessedUpTo(graph, currentLoadCounter);
×
312

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

329
    /**
330
     * Runs the four invalidation-DELETE / ASK steps. Sets {@code npa:needsFullRebuild}
331
     * when admin-RI, RoleAssignment, or RoleDeclaration invalidations matched (the
332
     * three structural kinds). Leaf-tier RI deletes don't set the flag.
333
     *
334
     * @return true iff at least one structural kind was invalidated
335
     */
336
    boolean applyInvalidations(IRI graph, long lastProcessed) {
337
        boolean structural = false;
×
338
        if (wouldInvalidate(graph, lastProcessed, /*adminPinned=*/ true,
×
339
                            adminInvalidationCheckWhere(graph, lastProcessed))) {
×
340
            executeUpdate(adminInvalidationDelete(graph, lastProcessed));
×
341
            structural = true;
×
342
        }
343
        if (wouldInvalidate(graph, lastProcessed, /*adminPinned=*/ false,
×
344
                            roleAssignmentInvalidationCheckWhere(graph, lastProcessed))) {
×
345
            executeUpdate(roleAssignmentInvalidationDelete(graph, lastProcessed));
×
346
            structural = true;
×
347
        }
348
        // RoleDeclaration ASK only — RDs aren't materialized into the space-state
349
        // graph, so there's nothing to DELETE here. The flag still flips because
350
        // sticky downstream RIs derived from the now-invalidated RD need a
351
        // from-scratch recompute.
352
        if (wouldInvalidate(graph, lastProcessed, /*adminPinned=*/ false,
×
353
                            roleDeclarationInvalidationCheckWhere(lastProcessed))) {
×
354
            structural = true;
×
355
        }
356
        // Leaf-tier RI deletes — no flag.
357
        executeUpdate(leafTierInvalidationDelete(graph, lastProcessed));
×
358
        if (structural) setNeedsFullRebuild();
×
359
        return structural;
×
360
    }
361

362
    /**
363
     * Runs the four leaf tiers (attachment/maintainer/member/observer) with
364
     * {@code lastProcessed = -1} so the load-number filter on the candidate
365
     * side admits everything. Dedup filters in the tier templates prevent
366
     * double-insert. Used by the late-arrival sweep.
367
     */
368
    TierInsertedTriples runDownstreamWithoutLoadFilter(IRI graph) {
369
        TierInsertedTriples c = new TierInsertedTriples();
×
370
        c.attachment = runTierLabeled("attachment(late)", graph,
×
371
                attachmentValidationUpdate(graph, -1));
×
372
        c.maintainer = runTierLabeled("maintainer(late)", graph,
×
373
                nonAdminTierUpdate(graph, -1, GEN.MAINTAINER_ROLE, PUBLISHER_IS_ADMIN));
×
374
        c.member = runTierLabeled("member(admin-pub,late)", graph,
×
375
                nonAdminTierUpdate(graph, -1, GEN.MEMBER_ROLE, PUBLISHER_IS_ADMIN));
×
376
        c.member += runTierLabeled("member(maint-pub,late)", graph,
×
377
                nonAdminTierUpdate(graph, -1,
×
378
                        GEN.MEMBER_ROLE, publisherIsTieredRole(GEN.MAINTAINER_ROLE)));
×
379
        c.observer = runTierLabeled("observer(admin-pub,late)", graph,
×
380
                nonAdminTierUpdate(graph, -1, GEN.OBSERVER_ROLE, PUBLISHER_IS_ADMIN));
×
381
        c.observer += runTierLabeled("observer(maint-pub,late)", graph,
×
382
                nonAdminTierUpdate(graph, -1,
×
383
                        GEN.OBSERVER_ROLE, publisherIsTieredRole(GEN.MAINTAINER_ROLE)));
×
384
        c.observer += runTierLabeled("observer(member-pub,late)", graph,
×
385
                nonAdminTierUpdate(graph, -1,
×
386
                        GEN.OBSERVER_ROLE, publisherIsTieredRole(GEN.MEMBER_ROLE)));
×
387
        c.observer += runTierLabeled("observer(self,late)", graph,
×
388
                nonAdminTierUpdate(graph, -1, GEN.OBSERVER_ROLE, PUBLISHER_IS_SELF));
×
389
        return c;
×
390
    }
391

392
    /**
393
     * Cheap ASK: did any new {@code npa:RoleDeclaration} extraction land in the
394
     * load-number delta {@code (lastProcessed, ∞)}? Used by the late-arrival
395
     * trigger so an RD that arrives in the same cycle as a matching candidate
396
     * still gets validated.
397
     */
398
    boolean newRoleDeclarationsArrived(long lastProcessed) {
399
        String ask = String.format("""
×
400
                PREFIX npa: <%1$s>
401
                ASK {
402
                  GRAPH <%2$s> {
403
                    ?rd a npa:RoleDeclaration ;
404
                        npa:viaNanopub ?np .
405
                  }
406
                  GRAPH <%3$s> {
407
                    ?np npa:hasLoadNumber ?ln .
408
                    FILTER (?ln > %4$d)
409
                  }
410
                }
411
                """, NPA.NAMESPACE, SpacesVocab.SPACES_GRAPH, NPA.GRAPH, lastProcessed);
×
412
        return runAsk(ask);
×
413
    }
414

415
    // ---------------- Tier UPDATE loops ----------------
416

417
    /**
418
     * Per-tier inserted-triple tallies for one build or cycle. Counts the sum
419
     * of {@code (graphSize_after - graphSize_before)} across all iterations of
420
     * each tier's fixed-point INSERT loop — i.e. inserted *triples*, not
421
     * distinct subjects (a single RoleInstantiation insert writes 4–5 triples).
422
     *
423
     * <p>Used internally by the {@link #runIncrementalCycle structuralAdds}
424
     * boolean check (we only care whether any tier inserted at all).
425
     * Not what the log lines report: see {@link TierSubjectTotals} +
426
     * {@link #computeTierSubjectTotals} for the distinct-subject totals
427
     * surfaced to operators.
428
     */
429
    static final class TierInsertedTriples {
×
430
        int admin;
431
        int attachment;
432
        int maintainer;
433
        int member;
434
        int observer;
435
    }
436

437
    /**
438
     * Snapshot of distinct-subject totals in a space-state graph at a moment
439
     * in time. Independent of which tier-loop added each subject.
440
     */
441
    record TierSubjectTotals(long adminRIs, long attachmentRAs, long nonAdminRIs) {}
36✔
442

443
    /**
444
     * Runs the five tier loops in order: admin → {@code gen:hasRole} attachment
445
     * validation → maintainer → member → observer. Each loop iterates a SPARQL
446
     * INSERT to fixed point (no new triples added). Returns per-tier counts.
447
     *
448
     * @param graph         target space-state graph
449
     * @param lastProcessed load-number horizon; use {@code -1} for full build
450
     */
451
    TierInsertedTriples runAllTierLoops(IRI graph, long lastProcessed) {
452
        TierInsertedTriples c = new TierInsertedTriples();
×
453
        c.admin = runTierLabeled("admin", graph, adminTierUpdate(graph, lastProcessed));
×
454
        c.attachment = runTierLabeled("attachment", graph,
×
455
                attachmentValidationUpdate(graph, lastProcessed));
×
456
        c.maintainer = runTierLabeled("maintainer", graph, nonAdminTierUpdate(graph, lastProcessed,
×
457
                GEN.MAINTAINER_ROLE, PUBLISHER_IS_ADMIN));
458
        // Member tier: admin OR maintainer publisher — split into two simpler updates
459
        // so the query planner doesn't struggle with the UNION.
460
        c.member = runTierLabeled("member(admin-pub)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
461
                GEN.MEMBER_ROLE, PUBLISHER_IS_ADMIN));
462
        c.member += runTierLabeled("member(maint-pub)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
463
                GEN.MEMBER_ROLE, publisherIsTieredRole(GEN.MAINTAINER_ROLE)));
×
464
        // Observer tier: self-evidence OR a downward grant from any higher tier.
465
        // ObserverRole is the default tier when a role definition omits an
466
        // explicit subclass (see "Role types" in design-space-repositories.md), so
467
        // most "X assigned Y this role" nanopubs land here. Restricting the tier
468
        // to PUBLISHER_IS_SELF would silently drop those grants. The four
469
        // sub-loops mirror the trust-state's downward-only chain: admin grants
470
        // anything; maintainers and members grant observer; everyone may
471
        // self-attest.
472
        c.observer = runTierLabeled("observer(admin-pub)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
473
                GEN.OBSERVER_ROLE, PUBLISHER_IS_ADMIN));
474
        c.observer += runTierLabeled("observer(maint-pub)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
475
                GEN.OBSERVER_ROLE, publisherIsTieredRole(GEN.MAINTAINER_ROLE)));
×
476
        c.observer += runTierLabeled("observer(member-pub)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
477
                GEN.OBSERVER_ROLE, publisherIsTieredRole(GEN.MEMBER_ROLE)));
×
478
        c.observer += runTierLabeled("observer(self)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
479
                GEN.OBSERVER_ROLE, PUBLISHER_IS_SELF));
480
        return c;
×
481
    }
482

483
    /**
484
     * Builds a publisher constraint requiring the publisher to be a validated holder
485
     * of the given tier's role (maintainer or member) in the target space.
486
     * Owns its own AccountState resolution so ?publisher is bound through the
487
     * targeted (pkh → agent) lookup rather than enumerated.
488
     */
489
    private static String publisherIsTieredRole(IRI tierClass) {
490
        return """
×
491
                ?acct a npa:AccountState ;
492
                      npa:pubkey ?pkh ;
493
                      npa:agent  ?publisher .
494
                ?tierRI a gen:RoleInstantiation ;
495
                        npa:forSpace ?space ;
496
                        npa:forAgent ?publisher .
497
                ?rdT a npa:RoleDeclaration ;
498
                     npa:hasRoleType <%1$s> .
499
                { ?tierRI npa:regularProperty ?predT . ?rdT gen:hasRegularProperty ?predT . }
500
                UNION
501
                { ?tierRI npa:inverseProperty ?predT . ?rdT gen:hasInverseProperty ?predT . }
502
                """.formatted(tierClass);
×
503
    }
504

505
    /** Wraps {@link #runTierLoop} with tier-name context for logs/exceptions. */
506
    private int runTierLabeled(String tier, IRI graph, String sparqlUpdate) {
507
        try {
508
            return runTierLoop(graph, sparqlUpdate);
×
509
        } catch (RuntimeException ex) {
×
510
            log.error("AuthorityResolver: tier={} failed with SPARQL UPDATE:\n{}\n", tier, sparqlUpdate, ex);
×
511
            throw ex;
×
512
        }
513
    }
514

515
    /**
516
     * Runs a single tier's INSERT to fixed point. Counts rows by probing
517
     * graph size before/after each INSERT; stops when the size doesn't change.
518
     *
519
     * @return total number of triples inserted by this tier across all iterations
520
     */
521
    int runTierLoop(IRI graph, String sparqlUpdate) {
522
        int total = 0;
×
523
        long before = graphSize(graph);
×
524
        while (true) {
525
            // Note: no explicit transaction wrapping here. In tests we observed that
526
            // HTTPRepository's RDF4J-transaction protocol silently no-op'd cross-graph
527
            // SPARQL UPDATEs with UNION sub-patterns inside conn.begin()/commit(),
528
            // while the same UPDATE POSTed directly to /statements applied correctly.
529
            // A bare prepareUpdate().execute() takes the direct /statements path and
530
            // runs the UPDATE atomically per SPARQL 1.1 semantics — which is all we
531
            // need; there's nothing else to commit atomically alongside the UPDATE.
532
            try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
533
                conn.prepareUpdate(QueryLanguage.SPARQL, sparqlUpdate).execute();
×
534
            }
535
            long after = graphSize(graph);
×
536
            long added = after - before;
×
537
            if (added <= 0) break;
×
538
            total += added;
×
539
            before = after;
×
540
        }
×
541
        return total;
×
542
    }
543

544
    private long graphSize(IRI graph) {
545
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
546
            return conn.size(graph);
×
547
        }
548
    }
549

550
    /**
551
     * Distinct-subject totals in the given space-state graph, broken down by
552
     * RoleInstantiation kind (admin-pinned vs not) and RoleAssignment.
553
     * Three SELECT-COUNT queries — cheap, called once per build/cycle for
554
     * the user-facing log line. Returns zeros on failure (logged) so a flaky
555
     * count read can't wedge the cycle.
556
     */
557
    TierSubjectTotals computeTierSubjectTotals(IRI graph) {
558
        long adminRIs       = countDistinctSubjects(graph, """
×
559
                ?ri a gen:RoleInstantiation ; npa:inverseProperty gen:hasAdmin .
560
                """, "ri");
561
        long attachmentRAs  = countDistinctSubjects(graph, """
×
562
                ?ra a gen:RoleAssignment .
563
                """, "ra");
564
        long nonAdminRIs    = countDistinctSubjects(graph, """
×
565
                ?ri a gen:RoleInstantiation .
566
                FILTER NOT EXISTS { ?ri npa:inverseProperty gen:hasAdmin }
567
                """, "ri");
568
        return new TierSubjectTotals(adminRIs, attachmentRAs, nonAdminRIs);
×
569
    }
570

571
    private long countDistinctSubjects(IRI graph, String wherePattern, String varName) {
572
        String query = String.format("""
×
573
                PREFIX npa: <%1$s>
574
                PREFIX gen: <%2$s>
575
                SELECT (COUNT(DISTINCT ?%3$s) AS ?n) WHERE {
576
                  GRAPH <%4$s> {
577
                    %5$s
578
                  }
579
                }
580
                """, NPA.NAMESPACE, GEN.NAMESPACE, varName, graph, wherePattern);
581
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO);
×
582
             TupleQueryResult r = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) {
×
583
            if (!r.hasNext()) return 0;
×
584
            return Long.parseLong(r.next().getBinding("n").getValue().stringValue());
×
585
        } catch (Exception ex) {
×
586
            log.warn("AuthorityResolver: countDistinctSubjects on {} failed: {}",
×
587
                    graph, ex.toString());
×
588
            return 0;
×
589
        }
590
    }
591

592
    // ---------------- SPARQL templates ----------------
593

594
    /**
595
     * Reusable invalidation filter on a bound nanopub-IRI variable. Pass the bare
596
     * variable name (no leading {@code ?}); e.g. {@code invalidationFilter("np")}
597
     * produces an outer-scoped {@code FILTER NOT EXISTS { GRAPH npa:spacesGraph
598
     * { ?_inv_np a npa:Invalidation ; npa:invalidates ?np . } }}.
599
     *
600
     * <p>Important: this filter must be placed OUTSIDE the surrounding
601
     * {@code GRAPH npa:spacesGraph { ... }} block, not nested inside it. When
602
     * nested, RDF4J's planner couples the FILTER NOT EXISTS evaluation into the
603
     * join order (per-row scan of {@code ?_inv a npa:Invalidation} multiplied by
604
     * the candidate set), which we measured turning a 39ms query into a 60s+
605
     * timeout on the live observer-tier data. Outside the GRAPH block, the
606
     * planner defers the filter until {@code ?np}/{@code ?rdNp} are bound and
607
     * does a targeted index lookup.
608
     *
609
     * <p>Variable names must match {@code [A-Za-z0-9_]+} per SPARQL grammar —
610
     * embedding a {@code ?} inside {@code ?_inv_?np} would yield a parse error.
611
     */
612
    private static String invalidationFilter(String bareVarName) {
613
        return "FILTER NOT EXISTS { GRAPH <" + SpacesVocab.SPACES_GRAPH + "> {"
30✔
614
                + " ?_inv_" + bareVarName
615
                + " a <" + SpacesVocab.INVALIDATION + "> ; "
616
                + "<" + SpacesVocab.INVALIDATES + "> ?" + bareVarName + " . } }";
617
    }
618

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

707
    /**
708
     * {@code gen:hasRole} attachment validation: an attachment is validated iff its
709
     * publisher is already a validated admin of the target space. Adds
710
     * {@code gen:RoleAssignment} rows to the space-state graph.
711
     */
712
    static String attachmentValidationUpdate(IRI graph, long lastProcessed) {
713
        return """
69✔
714
                PREFIX npa:  <%1$s>
715
                PREFIX gen:  <%2$s>
716
                INSERT { GRAPH <%3$s> {
717
                  ?ra a gen:RoleAssignment ;
718
                      npa:forSpace ?space ;
719
                      gen:hasRole  ?role ;
720
                      npa:viaNanopub ?np .
721
                } }
722
                WHERE {
723
                  GRAPH <%4$s> {
724
                    ?ra a gen:RoleAssignment ;
725
                        npa:forSpace ?space ;
726
                        gen:hasRole  ?role ;
727
                        npa:pubkeyHash ?pkh ;
728
                        npa:viaNanopub ?np .
729
                  }
730
                  GRAPH <%7$s> {
731
                    ?np npa:hasLoadNumber ?ln .
732
                    FILTER (?ln > %5$d)
733
                  }
734
                  GRAPH <%3$s> {
735
                    ?acct a npa:AccountState ;
736
                          npa:agent  ?publisher ;
737
                          npa:pubkey ?pkh .
738
                    ?adminRI a gen:RoleInstantiation ;
739
                             npa:forSpace ?space ;
740
                             npa:inverseProperty gen:hasAdmin ;
741
                             npa:forAgent ?publisher .
742
                  }
743
                  %6$s
744
                  FILTER NOT EXISTS { GRAPH <%3$s> {
745
                    ?existing a gen:RoleAssignment ;
746
                              npa:forSpace ?space ;
747
                              gen:hasRole  ?role .
748
                  } }
749
                }
750
                """.formatted(
3✔
751
                NPA.NAMESPACE,
752
                GEN.NAMESPACE,
753
                graph,
754
                SpacesVocab.SPACES_GRAPH,
755
                lastProcessed,
15✔
756
                invalidationFilter("np"),
18✔
757
                NPA.GRAPH);
758
    }
759

760
    /**
761
     * Non-admin tier publisher constraints (inserted as a SPARQL sub-pattern).
762
     * Each constraint owns the AccountState (pkh → agent) lookup so the join
763
     * variable is bound through a targeted pattern. The observer-self variant
764
     * binds {@code npa:agent ?agent} directly — no separate {@code ?publisher}
765
     * variable, no post-join equality filter — which lets the planner anchor
766
     * the AccountState lookup on the already-bound {@code ?agent} instead of
767
     * enumerating all approved publishers and filtering at the end.
768
     */
769
    static final String PUBLISHER_IS_ADMIN = """
770
            ?acct a npa:AccountState ;
771
                  npa:pubkey ?pkh ;
772
                  npa:agent  ?publisher .
773
            ?adminRI a gen:RoleInstantiation ;
774
                     npa:forSpace ?space ;
775
                     npa:inverseProperty gen:hasAdmin ;
776
                     npa:forAgent ?publisher .
777
            """;
778

779
    /** Observer self-evidence: the assignee's own pubkey signed the instantiation. */
780
    static final String PUBLISHER_IS_SELF = """
781
            ?acct a npa:AccountState ;
782
                  npa:pubkey ?pkh ;
783
                  npa:agent  ?agent .
784
            """;
785

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

881
    // ---------------- Invalidation templates (incremental cycle) ----------------
882

883
    /**
884
     * WHERE clause shared by the admin-RI invalidation ASK precheck and the
885
     * matching DELETE. Identifies admin-tier {@code gen:RoleInstantiation} rows
886
     * in the space-state graph whose {@code npa:viaNanopub} equals the target
887
     * of an {@code npa:Invalidation} that landed in {@code (lastProcessed, ∞)}.
888
     */
889
    static String adminInvalidationCheckWhere(IRI graph, long lastProcessed) {
890
        return String.format("""
60✔
891
                  GRAPH <%1$s> {
892
                    ?ri a gen:RoleInstantiation ;
893
                        npa:inverseProperty gen:hasAdmin ;
894
                        npa:viaNanopub ?np .
895
                  }
896
                  GRAPH <%2$s> {
897
                    ?inv a npa:Invalidation ;
898
                         npa:invalidates ?np ;
899
                         npa:viaNanopub  ?invNp .
900
                  }
901
                  GRAPH <%3$s> {
902
                    ?invNp npa:hasLoadNumber ?ln .
903
                    FILTER (?ln > %4$d)
904
                  }
905
                """, graph, SpacesVocab.SPACES_GRAPH, NPA.GRAPH, lastProcessed);
6✔
906
    }
907

908
    /** DELETE template for admin-tier RoleInstantiations whose source nanopub was invalidated. */
909
    static String adminInvalidationDelete(IRI graph, long lastProcessed) {
910
        return String.format("""
63✔
911
                PREFIX npa: <%1$s>
912
                PREFIX gen: <%2$s>
913
                DELETE { GRAPH <%3$s> {
914
                  ?ri ?p ?o .
915
                } }
916
                WHERE {
917
                  GRAPH <%3$s> { ?ri ?p ?o . }
918
                %4$s
919
                }
920
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
921
                adminInvalidationCheckWhere(graph, lastProcessed));
6✔
922
    }
923

924
    /** WHERE clause for RoleAssignment invalidation. */
925
    static String roleAssignmentInvalidationCheckWhere(IRI graph, long lastProcessed) {
926
        return String.format("""
60✔
927
                  GRAPH <%1$s> {
928
                    ?ra a gen:RoleAssignment ;
929
                        npa:viaNanopub ?np .
930
                  }
931
                  GRAPH <%2$s> {
932
                    ?inv a npa:Invalidation ;
933
                         npa:invalidates ?np ;
934
                         npa:viaNanopub  ?invNp .
935
                  }
936
                  GRAPH <%3$s> {
937
                    ?invNp npa:hasLoadNumber ?ln .
938
                    FILTER (?ln > %4$d)
939
                  }
940
                """, graph, SpacesVocab.SPACES_GRAPH, NPA.GRAPH, lastProcessed);
6✔
941
    }
942

943
    /** DELETE template for RoleAssignments whose source nanopub was invalidated. */
944
    static String roleAssignmentInvalidationDelete(IRI graph, long lastProcessed) {
945
        return String.format("""
63✔
946
                PREFIX npa: <%1$s>
947
                PREFIX gen: <%2$s>
948
                DELETE { GRAPH <%3$s> {
949
                  ?ra ?p ?o .
950
                } }
951
                WHERE {
952
                  GRAPH <%3$s> { ?ra ?p ?o . }
953
                %4$s
954
                }
955
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
956
                roleAssignmentInvalidationCheckWhere(graph, lastProcessed));
6✔
957
    }
958

959
    /**
960
     * WHERE clause for RoleDeclaration invalidation. ASK-only (no DELETE):
961
     * RoleDeclarations live in {@code npa:spacesGraph} and aren't materialized
962
     * into the space-state graph, so there's nothing to remove from the
963
     * space-state. The ASK still flips {@code npa:needsFullRebuild} because
964
     * sticky downstream RIs that were derived under the now-invalidated RD
965
     * need a from-scratch recompute.
966
     */
967
    static String roleDeclarationInvalidationCheckWhere(long lastProcessed) {
968
        return String.format("""
48✔
969
                  GRAPH <%1$s> {
970
                    ?rd a npa:RoleDeclaration ;
971
                        npa:viaNanopub ?np .
972
                    ?inv a npa:Invalidation ;
973
                         npa:invalidates ?np ;
974
                         npa:viaNanopub  ?invNp .
975
                  }
976
                  GRAPH <%2$s> {
977
                    ?invNp npa:hasLoadNumber ?ln .
978
                    FILTER (?ln > %3$d)
979
                  }
980
                """, SpacesVocab.SPACES_GRAPH, NPA.GRAPH, lastProcessed);
6✔
981
    }
982

983
    /**
984
     * DELETE template for non-admin (leaf-tier) RoleInstantiations whose source
985
     * nanopub was invalidated. Identified as {@code gen:RoleInstantiation} rows
986
     * lacking the admin-pinning {@code npa:inverseProperty gen:hasAdmin} triple.
987
     * No flag is set; leaf-tier removals are recoverable on the next cycle.
988
     */
989
    static String leafTierInvalidationDelete(IRI graph, long lastProcessed) {
990
        return String.format("""
84✔
991
                PREFIX npa: <%1$s>
992
                PREFIX gen: <%2$s>
993
                DELETE { GRAPH <%3$s> {
994
                  ?ri ?p ?o .
995
                } }
996
                WHERE {
997
                  GRAPH <%3$s> {
998
                    ?ri a gen:RoleInstantiation ;
999
                        npa:viaNanopub ?np .
1000
                    FILTER NOT EXISTS { ?ri npa:inverseProperty gen:hasAdmin }
1001
                    ?ri ?p ?o .
1002
                  }
1003
                  GRAPH <%4$s> {
1004
                    ?inv a npa:Invalidation ;
1005
                         npa:invalidates ?np ;
1006
                         npa:viaNanopub  ?invNp .
1007
                  }
1008
                  GRAPH <%5$s> {
1009
                    ?invNp npa:hasLoadNumber ?ln .
1010
                    FILTER (?ln > %6$d)
1011
                  }
1012
                }
1013
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
1014
                SpacesVocab.SPACES_GRAPH, NPA.GRAPH, lastProcessed);
6✔
1015
    }
1016

1017
    /** Wraps an ASK by joining the shared prefixes. */
1018
    private boolean wouldInvalidate(IRI graph, long lastProcessed,
1019
                                    boolean adminPinned, String whereClause) {
1020
        // adminPinned is informational only — kept to make call sites read clearly;
1021
        // the WHERE clause already encodes the kind via its own type predicates.
1022
        String ask = String.format("""
×
1023
                PREFIX npa: <%1$s>
1024
                PREFIX gen: <%2$s>
1025
                ASK { %3$s }
1026
                """, NPA.NAMESPACE, GEN.NAMESPACE, whereClause);
1027
        return runAsk(ask);
×
1028
    }
1029

1030
    private boolean runAsk(String sparql) {
1031
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1032
            return conn.prepareBooleanQuery(QueryLanguage.SPARQL, sparql).evaluate();
×
1033
        }
1034
    }
1035

1036
    private void executeUpdate(String sparqlUpdate) {
1037
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1038
            conn.prepareUpdate(QueryLanguage.SPARQL, sparqlUpdate).execute();
×
1039
        }
1040
    }
×
1041

1042
    // ---------------- Mirror step ----------------
1043

1044
    /**
1045
     * Copies trust-approved {@code npa:AccountState} rows from {@code npat:<T>}
1046
     * in the {@code trust} repo into {@code newGraph} in the {@code spaces} repo,
1047
     * inside one spaces-side serializable transaction.
1048
     *
1049
     * @return number of rows mirrored (useful for metrics / logging)
1050
     */
1051
    int mirrorTrustState(String trustStateHash, IRI newGraph) {
1052
        IRI trustStateIri = NPAT.forHash(trustStateHash);
×
1053
        int count = 0;
×
1054
        try (RepositoryConnection trustConn = TripleStore.get().getRepoConnection(TRUST_REPO);
×
1055
             RepositoryConnection spacesConn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1056
            trustConn.begin(IsolationLevels.READ_COMMITTED);
×
1057
            spacesConn.begin(IsolationLevels.SERIALIZABLE);
×
1058
            // Walk rdf:type triples in the trust state's graph; for each AccountState,
1059
            // check status and copy the approved ones verbatim (minus status-specific
1060
            // detail triples, which we don't need for validation).
1061
            try (RepositoryResult<Statement> typeRows = trustConn.getStatements(
×
1062
                    null, RDF.TYPE, NPA_ACCOUNT_STATE, trustStateIri)) {
1063
                while (typeRows.hasNext()) {
×
1064
                    Statement st = typeRows.next();
×
1065
                    if (!(st.getSubject() instanceof IRI accountStateIri)) continue;
×
1066
                    Value status = trustConn.getStatements(accountStateIri, NPA_TRUST_STATUS, null, trustStateIri)
×
1067
                            .stream().findFirst().map(Statement::getObject).orElse(null);
×
1068
                    if (!(status instanceof IRI statusIri) || !APPROVED_SET.contains(statusIri)) continue;
×
1069
                    Value agent = trustConn.getStatements(accountStateIri, NPA_AGENT, null, trustStateIri)
×
1070
                            .stream().findFirst().map(Statement::getObject).orElse(null);
×
1071
                    Value pubkey = trustConn.getStatements(accountStateIri, NPA_PUBKEY, null, trustStateIri)
×
1072
                            .stream().findFirst().map(Statement::getObject).orElse(null);
×
1073
                    if (agent == null || pubkey == null) {
×
1074
                        log.warn("AuthorityResolver.mirror: account {} missing agent or pubkey; skipping",
×
1075
                                accountStateIri);
1076
                        continue;
×
1077
                    }
1078
                    spacesConn.add(accountStateIri, RDF.TYPE, NPA_ACCOUNT_STATE, newGraph);
×
1079
                    spacesConn.add(accountStateIri, NPA_AGENT, agent, newGraph);
×
1080
                    spacesConn.add(accountStateIri, NPA_PUBKEY, pubkey, newGraph);
×
1081
                    spacesConn.add(accountStateIri, NPA_TRUST_STATUS, statusIri, newGraph);
×
1082
                    count++;
×
1083
                }
×
1084
            }
1085
            // Mirror canonical foaf:name triples for approved agents. The trust
1086
            // loader emits one per agent (across approved keys, MAX(ratio) wins).
1087
            // Copying them into the space-state graph means consumers reading
1088
            // ?agent foaf:name ?n inside the state graph hit local data, with no
1089
            // cross-repo SERVICE.
1090
            try (RepositoryResult<Statement> nameRows = trustConn.getStatements(
×
1091
                    null, FOAF.NAME, null, trustStateIri)) {
1092
                while (nameRows.hasNext()) {
×
1093
                    Statement st = nameRows.next();
×
1094
                    spacesConn.add(st.getSubject(), st.getPredicate(), st.getObject(), newGraph);
×
1095
                }
×
1096
            }
1097
            spacesConn.commit();
×
1098
            trustConn.commit();
×
1099
        }
1100
        return count;
×
1101
    }
1102

1103
    // ---------------- Pointer + counter helpers ----------------
1104

1105
    /**
1106
     * Reads the current {@code npa:hasCurrentSpaceState} pointer from the
1107
     * {@code npa:graph} admin graph of the {@code spaces} repo. Returns
1108
     * {@code null} if no pointer exists yet.
1109
     */
1110
    IRI getCurrentSpaceStateGraph() {
1111
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1112
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
1113
                    SpacesVocab.HAS_CURRENT_SPACE_STATE);
1114
            return (v instanceof IRI iri) ? iri : null;
×
1115
        } catch (Exception ex) {
×
1116
            log.warn("AuthorityResolver: failed to read hasCurrentSpaceState pointer: {}", ex.toString());
×
1117
            return null;
×
1118
        }
1119
    }
1120

1121
    long getCurrentLoadCounter() {
1122
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1123
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
1124
                    SpacesVocab.CURRENT_LOAD_COUNTER);
1125
            if (v == null) return 0;
×
1126
            try {
1127
                return Long.parseLong(v.stringValue());
×
1128
            } catch (NumberFormatException ex) {
×
1129
                log.warn("AuthorityResolver: non-numeric currentLoadCounter: {}", v);
×
1130
                return 0;
×
1131
            }
1132
        } catch (Exception ex) {
×
1133
            log.warn("AuthorityResolver: failed to read currentLoadCounter: {}", ex.toString());
×
1134
            return 0;
×
1135
        }
1136
    }
1137

1138
    /**
1139
     * Atomic pointer flip: a single SPARQL {@code DELETE … INSERT … WHERE}
1140
     * replaces the old pointer with the new one in one statement, so readers
1141
     * never see a zero-pointer window.
1142
     */
1143
    void flipPointer(IRI newGraph) {
1144
        String update = String.format("""
×
1145
                DELETE { GRAPH <%s> { <%s> <%s> ?old } }
1146
                INSERT { GRAPH <%s> { <%s> <%s> <%s> } }
1147
                WHERE  { OPTIONAL { GRAPH <%s> { <%s> <%s> ?old } } }
1148
                """,
1149
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.HAS_CURRENT_SPACE_STATE,
1150
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.HAS_CURRENT_SPACE_STATE, newGraph,
1151
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.HAS_CURRENT_SPACE_STATE);
1152
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1153
            conn.begin(IsolationLevels.SERIALIZABLE);
×
1154
            conn.prepareUpdate(QueryLanguage.SPARQL, update).execute();
×
1155
            conn.commit();
×
1156
        }
1157
    }
×
1158

1159
    void writeProcessedUpTo(IRI graph, long loadCounter) {
1160
        String update = String.format("""
×
1161
                DELETE { GRAPH <%s> { <%s> <%s> ?old } }
1162
                INSERT { GRAPH <%s> { <%s> <%s> "%d"^^<http://www.w3.org/2001/XMLSchema#long> } }
1163
                WHERE  { OPTIONAL { GRAPH <%s> { <%s> <%s> ?old } } }
1164
                """,
1165
                graph, graph, SpacesVocab.PROCESSED_UP_TO,
1166
                graph, graph, SpacesVocab.PROCESSED_UP_TO, loadCounter,
×
1167
                graph, graph, SpacesVocab.PROCESSED_UP_TO);
1168
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1169
            conn.begin(IsolationLevels.SERIALIZABLE);
×
1170
            conn.prepareUpdate(QueryLanguage.SPARQL, update).execute();
×
1171
            conn.commit();
×
1172
        }
1173
    }
×
1174

1175
    /**
1176
     * Reads {@code processedUpTo} from the given space-state graph.
1177
     * Returns {@code -1} if absent (graph not fully built yet).
1178
     */
1179
    long readProcessedUpTo(IRI graph) {
1180
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1181
            String query = String.format(
×
1182
                    "SELECT ?n WHERE { GRAPH <%s> { <%s> <%s> ?n } }",
1183
                    graph, graph, SpacesVocab.PROCESSED_UP_TO);
1184
            try (TupleQueryResult r = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) {
×
1185
                if (!r.hasNext()) return -1;
×
1186
                BindingSet b = r.next();
×
1187
                return Long.parseLong(b.getBinding("n").getValue().stringValue());
×
1188
            }
×
1189
        } catch (Exception ex) {
×
1190
            log.warn("AuthorityResolver: failed to read processedUpTo for {}: {}", graph, ex.toString());
×
1191
            return -1;
×
1192
        }
1193
    }
1194

1195
    /**
1196
     * Reads the {@code npa:needsFullRebuild} flag (boolean literal) from
1197
     * {@code npa:graph} in the {@code spaces} repo. Defaults to {@code false}
1198
     * when the triple is absent.
1199
     */
1200
    boolean readNeedsFullRebuild() {
1201
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1202
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
1203
                    SpacesVocab.NEEDS_FULL_REBUILD);
1204
            return v != null && Boolean.parseBoolean(v.stringValue());
×
1205
        } catch (Exception ex) {
×
1206
            log.warn("AuthorityResolver: failed to read needsFullRebuild: {}", ex.toString());
×
1207
            return false;
×
1208
        }
1209
    }
1210

1211
    void setNeedsFullRebuild() {
1212
        writeNeedsFullRebuild(true);
×
1213
    }
×
1214

1215
    void clearNeedsFullRebuild() {
1216
        writeNeedsFullRebuild(false);
×
1217
    }
×
1218

1219
    private void writeNeedsFullRebuild(boolean value) {
1220
        String update = String.format("""
×
1221
                DELETE { GRAPH <%s> { <%s> <%s> ?old } }
1222
                INSERT { GRAPH <%s> { <%s> <%s> "%s"^^<http://www.w3.org/2001/XMLSchema#boolean> } }
1223
                WHERE  { OPTIONAL { GRAPH <%s> { <%s> <%s> ?old } } }
1224
                """,
1225
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.NEEDS_FULL_REBUILD,
1226
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.NEEDS_FULL_REBUILD, value,
×
1227
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.NEEDS_FULL_REBUILD);
1228
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1229
            conn.begin(IsolationLevels.SERIALIZABLE);
×
1230
            conn.prepareUpdate(QueryLanguage.SPARQL, update).execute();
×
1231
            conn.commit();
×
1232
        }
1233
    }
×
1234

1235
    void dropGraph(IRI graph) {
1236
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1237
            conn.begin(IsolationLevels.SERIALIZABLE);
×
1238
            conn.clear(graph);
×
1239
            conn.commit();
×
1240
            log.info("AuthorityResolver: dropped old space-state graph {}", graph);
×
1241
        }
1242
    }
×
1243

1244
    // ---------------- Trust-repo pointer lookup (used by TrustStateRegistry's bootstrap) ----------------
1245

1246
    /**
1247
     * Queries the {@code trust} repo directly for the current trust-state hash.
1248
     * Prefer {@link TrustStateRegistry#getCurrentHash()} in normal operation —
1249
     * this helper exists for tests and diagnostics.
1250
     *
1251
     * @return the current trust-state hash, or empty if none is set
1252
     */
1253
    Optional<String> readTrustRepoCurrentHash() {
1254
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(TRUST_REPO)) {
×
1255
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
1256
                    NPA_HAS_CURRENT_TRUST_STATE);
1257
            if (!(v instanceof IRI iri)) return Optional.empty();
×
1258
            String s = iri.stringValue();
×
1259
            if (!s.startsWith(NPAT.NAMESPACE)) return Optional.empty();
×
1260
            return Optional.of(s.substring(NPAT.NAMESPACE.length()));
×
1261
        } catch (Exception ex) {
×
1262
            log.warn("AuthorityResolver: failed to read trust-repo current pointer: {}", ex.toString());
×
1263
            return Optional.empty();
×
1264
        }
1265
    }
1266

1267
    private static String abbrev(String hash) {
1268
        return hash.length() > 12 ? hash.substring(0, 12) + "…" : hash;
×
1269
    }
1270

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