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

knowledgepixels / nanopub-query / 24979573170

27 Apr 2026 06:16AM UTC coverage: 56.165% (+0.2%) from 55.994%
24979573170

push

github

web-flow
Merge pull request #85 from knowledgepixels/feature/62-phase-3a-metrics

feat: expose spaces build/cycle metrics as Prometheus gauges (#62)

385 of 774 branches covered (49.74%)

Branch coverage included in aggregate %.

1109 of 1886 relevant lines covered (58.8%)

8.96 hits per line

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

13.26
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.RDF;
15
import org.eclipse.rdf4j.query.BindingSet;
16
import org.eclipse.rdf4j.query.QueryLanguage;
17
import org.eclipse.rdf4j.query.TupleQueryResult;
18
import org.eclipse.rdf4j.repository.RepositoryConnection;
19
import org.eclipse.rdf4j.repository.RepositoryResult;
20
import org.nanopub.vocabulary.NPA;
21
import org.slf4j.Logger;
22
import org.slf4j.LoggerFactory;
23

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

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

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

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

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

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

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

82
    private static AuthorityResolver instance;
83

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

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

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

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

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

116
    // ---------------- Public entry points ----------------
117

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

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

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

203
    // ---------------- Full build ----------------
204

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

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

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

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

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

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

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

256
    // ---------------- Incremental cycle ----------------
257

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

293
        boolean structuralInvalidation = applyInvalidations(graph, lastProcessed);
×
294
        TierInsertedTriples counts = runAllTierLoops(graph, lastProcessed);
×
295
        boolean structuralAdds = (counts.admin > 0)
×
296
                || (counts.attachment > 0)
297
                || newRoleDeclarationsArrived(lastProcessed);
×
298
        if (structuralAdds) {
×
299
            // Late-arrival sweep: only the leaf tiers (attachment/maintainer/member/observer)
300
            // can promote candidates whose enabling event arrived in this same cycle. Skip
301
            // the admin tier — its only enabling event is the admin grant itself, already
302
            // handled by the regular pass.
303
            TierInsertedTriples lateCounts = runDownstreamWithoutLoadFilter(graph);
×
304
            counts.attachment += lateCounts.attachment;
×
305
            counts.maintainer += lateCounts.maintainer;
×
306
            counts.member     += lateCounts.member;
×
307
            counts.observer   += lateCounts.observer;
×
308
        }
309

310
        writeProcessedUpTo(graph, currentLoadCounter);
×
311

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

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

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

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

406
    // ---------------- Tier UPDATE loops ----------------
407

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

428
    /**
429
     * Snapshot of distinct-subject totals in a space-state graph at a moment
430
     * in time. Independent of which tier-loop added each subject.
431
     */
432
    record TierSubjectTotals(long adminRIs, long attachmentRAs, long nonAdminRIs) {}
36✔
433

434
    /**
435
     * Runs the five tier loops in order: admin → {@code gen:hasRole} attachment
436
     * validation → maintainer → member → observer. Each loop iterates a SPARQL
437
     * INSERT to fixed point (no new triples added). Returns per-tier counts.
438
     *
439
     * @param graph         target space-state graph
440
     * @param lastProcessed load-number horizon; use {@code -1} for full build
441
     */
442
    TierInsertedTriples runAllTierLoops(IRI graph, long lastProcessed) {
443
        TierInsertedTriples c = new TierInsertedTriples();
×
444
        c.admin = runTierLabeled("admin", graph, adminTierUpdate(graph, lastProcessed));
×
445
        c.attachment = runTierLabeled("attachment", graph,
×
446
                attachmentValidationUpdate(graph, lastProcessed));
×
447
        c.maintainer = runTierLabeled("maintainer", graph, nonAdminTierUpdate(graph, lastProcessed,
×
448
                GEN.MAINTAINER_ROLE, PUBLISHER_IS_ADMIN));
449
        // Member tier: admin OR maintainer publisher — split into two simpler updates
450
        // so the query planner doesn't struggle with the UNION.
451
        c.member = runTierLabeled("member(admin-pub)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
452
                GEN.MEMBER_ROLE, PUBLISHER_IS_ADMIN));
453
        c.member += runTierLabeled("member(maint-pub)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
454
                GEN.MEMBER_ROLE, publisherIsTieredRole(GEN.MAINTAINER_ROLE)));
×
455
        // Observer tier: self-evidence only per the plan's policy table
456
        // (gen:ObserverRole = self). Authority-publisher sub-tiers were overreach;
457
        // the three of them have been removed, so an observer instantiation is
458
        // validated iff the assignee's own pubkey signed it.
459
        c.observer = runTierLabeled("observer(self)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
460
                GEN.OBSERVER_ROLE, PUBLISHER_IS_SELF));
461
        return c;
×
462
    }
463

464
    /**
465
     * Builds a publisher constraint requiring the publisher to be a validated holder
466
     * of the given tier's role (maintainer or member) in the target space.
467
     * Owns its own AccountState resolution so ?publisher is bound through the
468
     * targeted (pkh → agent) lookup rather than enumerated.
469
     */
470
    private static String publisherIsTieredRole(IRI tierClass) {
471
        return """
×
472
                ?acct a npa:AccountState ;
473
                      npa:pubkey ?pkh ;
474
                      npa:agent  ?publisher .
475
                ?tierRI a gen:RoleInstantiation ;
476
                        npa:forSpace ?space ;
477
                        npa:forAgent ?publisher .
478
                ?rdT a npa:RoleDeclaration ;
479
                     npa:hasRoleType <%1$s> .
480
                { ?tierRI npa:regularProperty ?predT . ?rdT gen:hasRegularProperty ?predT . }
481
                UNION
482
                { ?tierRI npa:inverseProperty ?predT . ?rdT gen:hasInverseProperty ?predT . }
483
                """.formatted(tierClass);
×
484
    }
485

486
    /** Wraps {@link #runTierLoop} with tier-name context for logs/exceptions. */
487
    private int runTierLabeled(String tier, IRI graph, String sparqlUpdate) {
488
        try {
489
            return runTierLoop(graph, sparqlUpdate);
×
490
        } catch (RuntimeException ex) {
×
491
            log.error("AuthorityResolver: tier={} failed with SPARQL UPDATE:\n{}\n", tier, sparqlUpdate, ex);
×
492
            throw ex;
×
493
        }
494
    }
495

496
    /**
497
     * Runs a single tier's INSERT to fixed point. Counts rows by probing
498
     * graph size before/after each INSERT; stops when the size doesn't change.
499
     *
500
     * @return total number of triples inserted by this tier across all iterations
501
     */
502
    int runTierLoop(IRI graph, String sparqlUpdate) {
503
        int total = 0;
×
504
        long before = graphSize(graph);
×
505
        while (true) {
506
            // Note: no explicit transaction wrapping here. In tests we observed that
507
            // HTTPRepository's RDF4J-transaction protocol silently no-op'd cross-graph
508
            // SPARQL UPDATEs with UNION sub-patterns inside conn.begin()/commit(),
509
            // while the same UPDATE POSTed directly to /statements applied correctly.
510
            // A bare prepareUpdate().execute() takes the direct /statements path and
511
            // runs the UPDATE atomically per SPARQL 1.1 semantics — which is all we
512
            // need; there's nothing else to commit atomically alongside the UPDATE.
513
            try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
514
                conn.prepareUpdate(QueryLanguage.SPARQL, sparqlUpdate).execute();
×
515
            }
516
            long after = graphSize(graph);
×
517
            long added = after - before;
×
518
            if (added <= 0) break;
×
519
            total += added;
×
520
            before = after;
×
521
        }
×
522
        return total;
×
523
    }
524

525
    private long graphSize(IRI graph) {
526
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
527
            return conn.size(graph);
×
528
        }
529
    }
530

531
    /**
532
     * Distinct-subject totals in the given space-state graph, broken down by
533
     * RoleInstantiation kind (admin-pinned vs not) and RoleAssignment.
534
     * Three SELECT-COUNT queries — cheap, called once per build/cycle for
535
     * the user-facing log line. Returns zeros on failure (logged) so a flaky
536
     * count read can't wedge the cycle.
537
     */
538
    TierSubjectTotals computeTierSubjectTotals(IRI graph) {
539
        long adminRIs       = countDistinctSubjects(graph, """
×
540
                ?ri a gen:RoleInstantiation ; npa:inverseProperty gen:hasAdmin .
541
                """, "ri");
542
        long attachmentRAs  = countDistinctSubjects(graph, """
×
543
                ?ra a gen:RoleAssignment .
544
                """, "ra");
545
        long nonAdminRIs    = countDistinctSubjects(graph, """
×
546
                ?ri a gen:RoleInstantiation .
547
                FILTER NOT EXISTS { ?ri npa:inverseProperty gen:hasAdmin }
548
                """, "ri");
549
        return new TierSubjectTotals(adminRIs, attachmentRAs, nonAdminRIs);
×
550
    }
551

552
    private long countDistinctSubjects(IRI graph, String wherePattern, String varName) {
553
        String query = String.format("""
×
554
                PREFIX npa: <%1$s>
555
                PREFIX gen: <%2$s>
556
                SELECT (COUNT(DISTINCT ?%3$s) AS ?n) WHERE {
557
                  GRAPH <%4$s> {
558
                    %5$s
559
                  }
560
                }
561
                """, NPA.NAMESPACE, GEN.NAMESPACE, varName, graph, wherePattern);
562
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO);
×
563
             TupleQueryResult r = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) {
×
564
            if (!r.hasNext()) return 0;
×
565
            return Long.parseLong(r.next().getBinding("n").getValue().stringValue());
×
566
        } catch (Exception ex) {
×
567
            log.warn("AuthorityResolver: countDistinctSubjects on {} failed: {}",
×
568
                    graph, ex.toString());
×
569
            return 0;
×
570
        }
571
    }
572

573
    // ---------------- SPARQL templates ----------------
574

575
    /**
576
     * Reusable invalidation filter on a bound nanopub-IRI variable. Pass the bare
577
     * variable name (no leading {@code ?}); e.g. {@code invalidationFilter("np")}
578
     * produces an outer-scoped {@code FILTER NOT EXISTS { GRAPH npa:spacesGraph
579
     * { ?_inv_np a npa:Invalidation ; npa:invalidates ?np . } }}.
580
     *
581
     * <p>Important: this filter must be placed OUTSIDE the surrounding
582
     * {@code GRAPH npa:spacesGraph { ... }} block, not nested inside it. When
583
     * nested, RDF4J's planner couples the FILTER NOT EXISTS evaluation into the
584
     * join order (per-row scan of {@code ?_inv a npa:Invalidation} multiplied by
585
     * the candidate set), which we measured turning a 39ms query into a 60s+
586
     * timeout on the live observer-tier data. Outside the GRAPH block, the
587
     * planner defers the filter until {@code ?np}/{@code ?rdNp} are bound and
588
     * does a targeted index lookup.
589
     *
590
     * <p>Variable names must match {@code [A-Za-z0-9_]+} per SPARQL grammar —
591
     * embedding a {@code ?} inside {@code ?_inv_?np} would yield a parse error.
592
     */
593
    private static String invalidationFilter(String bareVarName) {
594
        return "FILTER NOT EXISTS { GRAPH <" + SpacesVocab.SPACES_GRAPH + "> {"
30✔
595
                + " ?_inv_" + bareVarName
596
                + " a <" + SpacesVocab.INVALIDATION + "> ; "
597
                + "<" + SpacesVocab.INVALIDATES + "> ?" + bareVarName + " . } }";
598
    }
599

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

688
    /**
689
     * {@code gen:hasRole} attachment validation: an attachment is validated iff its
690
     * publisher is already a validated admin of the target space. Adds
691
     * {@code gen:RoleAssignment} rows to the space-state graph.
692
     */
693
    static String attachmentValidationUpdate(IRI graph, long lastProcessed) {
694
        return """
69✔
695
                PREFIX npa:  <%1$s>
696
                PREFIX gen:  <%2$s>
697
                INSERT { GRAPH <%3$s> {
698
                  ?ra a gen:RoleAssignment ;
699
                      npa:forSpace ?space ;
700
                      gen:hasRole  ?role ;
701
                      npa:viaNanopub ?np .
702
                } }
703
                WHERE {
704
                  GRAPH <%4$s> {
705
                    ?ra a gen:RoleAssignment ;
706
                        npa:forSpace ?space ;
707
                        gen:hasRole  ?role ;
708
                        npa:pubkeyHash ?pkh ;
709
                        npa:viaNanopub ?np .
710
                  }
711
                  GRAPH <%7$s> {
712
                    ?np npa:hasLoadNumber ?ln .
713
                    FILTER (?ln > %5$d)
714
                  }
715
                  GRAPH <%3$s> {
716
                    ?acct a npa:AccountState ;
717
                          npa:agent  ?publisher ;
718
                          npa:pubkey ?pkh .
719
                    ?adminRI a gen:RoleInstantiation ;
720
                             npa:forSpace ?space ;
721
                             npa:inverseProperty gen:hasAdmin ;
722
                             npa:forAgent ?publisher .
723
                  }
724
                  %6$s
725
                  FILTER NOT EXISTS { GRAPH <%3$s> {
726
                    ?existing a gen:RoleAssignment ;
727
                              npa:forSpace ?space ;
728
                              gen:hasRole  ?role .
729
                  } }
730
                }
731
                """.formatted(
3✔
732
                NPA.NAMESPACE,
733
                GEN.NAMESPACE,
734
                graph,
735
                SpacesVocab.SPACES_GRAPH,
736
                lastProcessed,
15✔
737
                invalidationFilter("np"),
18✔
738
                NPA.GRAPH);
739
    }
740

741
    /**
742
     * Non-admin tier publisher constraints (inserted as a SPARQL sub-pattern).
743
     * Each constraint owns the AccountState (pkh → agent) lookup so the join
744
     * variable is bound through a targeted pattern. The observer-self variant
745
     * binds {@code npa:agent ?agent} directly — no separate {@code ?publisher}
746
     * variable, no post-join equality filter — which lets the planner anchor
747
     * the AccountState lookup on the already-bound {@code ?agent} instead of
748
     * enumerating all approved publishers and filtering at the end.
749
     */
750
    static final String PUBLISHER_IS_ADMIN = """
751
            ?acct a npa:AccountState ;
752
                  npa:pubkey ?pkh ;
753
                  npa:agent  ?publisher .
754
            ?adminRI a gen:RoleInstantiation ;
755
                     npa:forSpace ?space ;
756
                     npa:inverseProperty gen:hasAdmin ;
757
                     npa:forAgent ?publisher .
758
            """;
759

760
    /** Observer self-evidence: the assignee's own pubkey signed the instantiation. */
761
    static final String PUBLISHER_IS_SELF = """
762
            ?acct a npa:AccountState ;
763
                  npa:pubkey ?pkh ;
764
                  npa:agent  ?agent .
765
            """;
766

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

862
    // ---------------- Invalidation templates (incremental cycle) ----------------
863

864
    /**
865
     * WHERE clause shared by the admin-RI invalidation ASK precheck and the
866
     * matching DELETE. Identifies admin-tier {@code gen:RoleInstantiation} rows
867
     * in the space-state graph whose {@code npa:viaNanopub} equals the target
868
     * of an {@code npa:Invalidation} that landed in {@code (lastProcessed, ∞)}.
869
     */
870
    static String adminInvalidationCheckWhere(IRI graph, long lastProcessed) {
871
        return String.format("""
60✔
872
                  GRAPH <%1$s> {
873
                    ?ri a gen:RoleInstantiation ;
874
                        npa:inverseProperty gen:hasAdmin ;
875
                        npa:viaNanopub ?np .
876
                  }
877
                  GRAPH <%2$s> {
878
                    ?inv a npa:Invalidation ;
879
                         npa:invalidates ?np ;
880
                         npa:viaNanopub  ?invNp .
881
                  }
882
                  GRAPH <%3$s> {
883
                    ?invNp npa:hasLoadNumber ?ln .
884
                    FILTER (?ln > %4$d)
885
                  }
886
                """, graph, SpacesVocab.SPACES_GRAPH, NPA.GRAPH, lastProcessed);
6✔
887
    }
888

889
    /** DELETE template for admin-tier RoleInstantiations whose source nanopub was invalidated. */
890
    static String adminInvalidationDelete(IRI graph, long lastProcessed) {
891
        return String.format("""
63✔
892
                PREFIX npa: <%1$s>
893
                PREFIX gen: <%2$s>
894
                DELETE { GRAPH <%3$s> {
895
                  ?ri ?p ?o .
896
                } }
897
                WHERE {
898
                  GRAPH <%3$s> { ?ri ?p ?o . }
899
                %4$s
900
                }
901
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
902
                adminInvalidationCheckWhere(graph, lastProcessed));
6✔
903
    }
904

905
    /** WHERE clause for RoleAssignment invalidation. */
906
    static String roleAssignmentInvalidationCheckWhere(IRI graph, long lastProcessed) {
907
        return String.format("""
60✔
908
                  GRAPH <%1$s> {
909
                    ?ra a gen:RoleAssignment ;
910
                        npa:viaNanopub ?np .
911
                  }
912
                  GRAPH <%2$s> {
913
                    ?inv a npa:Invalidation ;
914
                         npa:invalidates ?np ;
915
                         npa:viaNanopub  ?invNp .
916
                  }
917
                  GRAPH <%3$s> {
918
                    ?invNp npa:hasLoadNumber ?ln .
919
                    FILTER (?ln > %4$d)
920
                  }
921
                """, graph, SpacesVocab.SPACES_GRAPH, NPA.GRAPH, lastProcessed);
6✔
922
    }
923

924
    /** DELETE template for RoleAssignments whose source nanopub was invalidated. */
925
    static String roleAssignmentInvalidationDelete(IRI graph, long lastProcessed) {
926
        return String.format("""
63✔
927
                PREFIX npa: <%1$s>
928
                PREFIX gen: <%2$s>
929
                DELETE { GRAPH <%3$s> {
930
                  ?ra ?p ?o .
931
                } }
932
                WHERE {
933
                  GRAPH <%3$s> { ?ra ?p ?o . }
934
                %4$s
935
                }
936
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
937
                roleAssignmentInvalidationCheckWhere(graph, lastProcessed));
6✔
938
    }
939

940
    /**
941
     * WHERE clause for RoleDeclaration invalidation. ASK-only (no DELETE):
942
     * RoleDeclarations live in {@code npa:spacesGraph} and aren't materialized
943
     * into the space-state graph, so there's nothing to remove from the
944
     * space-state. The ASK still flips {@code npa:needsFullRebuild} because
945
     * sticky downstream RIs that were derived under the now-invalidated RD
946
     * need a from-scratch recompute.
947
     */
948
    static String roleDeclarationInvalidationCheckWhere(long lastProcessed) {
949
        return String.format("""
48✔
950
                  GRAPH <%1$s> {
951
                    ?rd a npa:RoleDeclaration ;
952
                        npa:viaNanopub ?np .
953
                    ?inv a npa:Invalidation ;
954
                         npa:invalidates ?np ;
955
                         npa:viaNanopub  ?invNp .
956
                  }
957
                  GRAPH <%2$s> {
958
                    ?invNp npa:hasLoadNumber ?ln .
959
                    FILTER (?ln > %3$d)
960
                  }
961
                """, SpacesVocab.SPACES_GRAPH, NPA.GRAPH, lastProcessed);
6✔
962
    }
963

964
    /**
965
     * DELETE template for non-admin (leaf-tier) RoleInstantiations whose source
966
     * nanopub was invalidated. Identified as {@code gen:RoleInstantiation} rows
967
     * lacking the admin-pinning {@code npa:inverseProperty gen:hasAdmin} triple.
968
     * No flag is set; leaf-tier removals are recoverable on the next cycle.
969
     */
970
    static String leafTierInvalidationDelete(IRI graph, long lastProcessed) {
971
        return String.format("""
84✔
972
                PREFIX npa: <%1$s>
973
                PREFIX gen: <%2$s>
974
                DELETE { GRAPH <%3$s> {
975
                  ?ri ?p ?o .
976
                } }
977
                WHERE {
978
                  GRAPH <%3$s> {
979
                    ?ri a gen:RoleInstantiation ;
980
                        npa:viaNanopub ?np .
981
                    FILTER NOT EXISTS { ?ri npa:inverseProperty gen:hasAdmin }
982
                    ?ri ?p ?o .
983
                  }
984
                  GRAPH <%4$s> {
985
                    ?inv a npa:Invalidation ;
986
                         npa:invalidates ?np ;
987
                         npa:viaNanopub  ?invNp .
988
                  }
989
                  GRAPH <%5$s> {
990
                    ?invNp npa:hasLoadNumber ?ln .
991
                    FILTER (?ln > %6$d)
992
                  }
993
                }
994
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
995
                SpacesVocab.SPACES_GRAPH, NPA.GRAPH, lastProcessed);
6✔
996
    }
997

998
    /** Wraps an ASK by joining the shared prefixes. */
999
    private boolean wouldInvalidate(IRI graph, long lastProcessed,
1000
                                    boolean adminPinned, String whereClause) {
1001
        // adminPinned is informational only — kept to make call sites read clearly;
1002
        // the WHERE clause already encodes the kind via its own type predicates.
1003
        String ask = String.format("""
×
1004
                PREFIX npa: <%1$s>
1005
                PREFIX gen: <%2$s>
1006
                ASK { %3$s }
1007
                """, NPA.NAMESPACE, GEN.NAMESPACE, whereClause);
1008
        return runAsk(ask);
×
1009
    }
1010

1011
    private boolean runAsk(String sparql) {
1012
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1013
            return conn.prepareBooleanQuery(QueryLanguage.SPARQL, sparql).evaluate();
×
1014
        }
1015
    }
1016

1017
    private void executeUpdate(String sparqlUpdate) {
1018
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1019
            conn.prepareUpdate(QueryLanguage.SPARQL, sparqlUpdate).execute();
×
1020
        }
1021
    }
×
1022

1023
    // ---------------- Mirror step ----------------
1024

1025
    /**
1026
     * Copies trust-approved {@code npa:AccountState} rows from {@code npat:<T>}
1027
     * in the {@code trust} repo into {@code newGraph} in the {@code spaces} repo,
1028
     * inside one spaces-side serializable transaction.
1029
     *
1030
     * @return number of rows mirrored (useful for metrics / logging)
1031
     */
1032
    int mirrorTrustState(String trustStateHash, IRI newGraph) {
1033
        IRI trustStateIri = NPAT.forHash(trustStateHash);
×
1034
        int count = 0;
×
1035
        try (RepositoryConnection trustConn = TripleStore.get().getRepoConnection(TRUST_REPO);
×
1036
             RepositoryConnection spacesConn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1037
            trustConn.begin(IsolationLevels.READ_COMMITTED);
×
1038
            spacesConn.begin(IsolationLevels.SERIALIZABLE);
×
1039
            // Walk rdf:type triples in the trust state's graph; for each AccountState,
1040
            // check status and copy the approved ones verbatim (minus status-specific
1041
            // detail triples, which we don't need for validation).
1042
            try (RepositoryResult<Statement> typeRows = trustConn.getStatements(
×
1043
                    null, RDF.TYPE, NPA_ACCOUNT_STATE, trustStateIri)) {
1044
                while (typeRows.hasNext()) {
×
1045
                    Statement st = typeRows.next();
×
1046
                    if (!(st.getSubject() instanceof IRI accountStateIri)) continue;
×
1047
                    Value status = trustConn.getStatements(accountStateIri, NPA_TRUST_STATUS, null, trustStateIri)
×
1048
                            .stream().findFirst().map(Statement::getObject).orElse(null);
×
1049
                    if (!(status instanceof IRI statusIri) || !APPROVED_SET.contains(statusIri)) continue;
×
1050
                    Value agent = trustConn.getStatements(accountStateIri, NPA_AGENT, null, trustStateIri)
×
1051
                            .stream().findFirst().map(Statement::getObject).orElse(null);
×
1052
                    Value pubkey = trustConn.getStatements(accountStateIri, NPA_PUBKEY, null, trustStateIri)
×
1053
                            .stream().findFirst().map(Statement::getObject).orElse(null);
×
1054
                    if (agent == null || pubkey == null) {
×
1055
                        log.warn("AuthorityResolver.mirror: account {} missing agent or pubkey; skipping",
×
1056
                                accountStateIri);
1057
                        continue;
×
1058
                    }
1059
                    spacesConn.add(accountStateIri, RDF.TYPE, NPA_ACCOUNT_STATE, newGraph);
×
1060
                    spacesConn.add(accountStateIri, NPA_AGENT, agent, newGraph);
×
1061
                    spacesConn.add(accountStateIri, NPA_PUBKEY, pubkey, newGraph);
×
1062
                    spacesConn.add(accountStateIri, NPA_TRUST_STATUS, statusIri, newGraph);
×
1063
                    count++;
×
1064
                }
×
1065
            }
1066
            spacesConn.commit();
×
1067
            trustConn.commit();
×
1068
        }
1069
        return count;
×
1070
    }
1071

1072
    // ---------------- Pointer + counter helpers ----------------
1073

1074
    /**
1075
     * Reads the current {@code npa:hasCurrentSpaceState} pointer from the
1076
     * {@code npa:graph} admin graph of the {@code spaces} repo. Returns
1077
     * {@code null} if no pointer exists yet.
1078
     */
1079
    IRI getCurrentSpaceStateGraph() {
1080
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1081
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
1082
                    SpacesVocab.HAS_CURRENT_SPACE_STATE);
1083
            return (v instanceof IRI iri) ? iri : null;
×
1084
        } catch (Exception ex) {
×
1085
            log.warn("AuthorityResolver: failed to read hasCurrentSpaceState pointer: {}", ex.toString());
×
1086
            return null;
×
1087
        }
1088
    }
1089

1090
    long getCurrentLoadCounter() {
1091
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1092
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
1093
                    SpacesVocab.CURRENT_LOAD_COUNTER);
1094
            if (v == null) return 0;
×
1095
            try {
1096
                return Long.parseLong(v.stringValue());
×
1097
            } catch (NumberFormatException ex) {
×
1098
                log.warn("AuthorityResolver: non-numeric currentLoadCounter: {}", v);
×
1099
                return 0;
×
1100
            }
1101
        } catch (Exception ex) {
×
1102
            log.warn("AuthorityResolver: failed to read currentLoadCounter: {}", ex.toString());
×
1103
            return 0;
×
1104
        }
1105
    }
1106

1107
    /**
1108
     * Atomic pointer flip: a single SPARQL {@code DELETE … INSERT … WHERE}
1109
     * replaces the old pointer with the new one in one statement, so readers
1110
     * never see a zero-pointer window.
1111
     */
1112
    void flipPointer(IRI newGraph) {
1113
        String update = String.format("""
×
1114
                DELETE { GRAPH <%s> { <%s> <%s> ?old } }
1115
                INSERT { GRAPH <%s> { <%s> <%s> <%s> } }
1116
                WHERE  { OPTIONAL { GRAPH <%s> { <%s> <%s> ?old } } }
1117
                """,
1118
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.HAS_CURRENT_SPACE_STATE,
1119
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.HAS_CURRENT_SPACE_STATE, newGraph,
1120
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.HAS_CURRENT_SPACE_STATE);
1121
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1122
            conn.begin(IsolationLevels.SERIALIZABLE);
×
1123
            conn.prepareUpdate(QueryLanguage.SPARQL, update).execute();
×
1124
            conn.commit();
×
1125
        }
1126
    }
×
1127

1128
    void writeProcessedUpTo(IRI graph, long loadCounter) {
1129
        String update = String.format("""
×
1130
                DELETE { GRAPH <%s> { <%s> <%s> ?old } }
1131
                INSERT { GRAPH <%s> { <%s> <%s> "%d"^^<http://www.w3.org/2001/XMLSchema#long> } }
1132
                WHERE  { OPTIONAL { GRAPH <%s> { <%s> <%s> ?old } } }
1133
                """,
1134
                graph, graph, SpacesVocab.PROCESSED_UP_TO,
1135
                graph, graph, SpacesVocab.PROCESSED_UP_TO, loadCounter,
×
1136
                graph, graph, SpacesVocab.PROCESSED_UP_TO);
1137
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1138
            conn.begin(IsolationLevels.SERIALIZABLE);
×
1139
            conn.prepareUpdate(QueryLanguage.SPARQL, update).execute();
×
1140
            conn.commit();
×
1141
        }
1142
    }
×
1143

1144
    /**
1145
     * Reads {@code processedUpTo} from the given space-state graph.
1146
     * Returns {@code -1} if absent (graph not fully built yet).
1147
     */
1148
    long readProcessedUpTo(IRI graph) {
1149
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1150
            String query = String.format(
×
1151
                    "SELECT ?n WHERE { GRAPH <%s> { <%s> <%s> ?n } }",
1152
                    graph, graph, SpacesVocab.PROCESSED_UP_TO);
1153
            try (TupleQueryResult r = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) {
×
1154
                if (!r.hasNext()) return -1;
×
1155
                BindingSet b = r.next();
×
1156
                return Long.parseLong(b.getBinding("n").getValue().stringValue());
×
1157
            }
×
1158
        } catch (Exception ex) {
×
1159
            log.warn("AuthorityResolver: failed to read processedUpTo for {}: {}", graph, ex.toString());
×
1160
            return -1;
×
1161
        }
1162
    }
1163

1164
    /**
1165
     * Reads the {@code npa:needsFullRebuild} flag (boolean literal) from
1166
     * {@code npa:graph} in the {@code spaces} repo. Defaults to {@code false}
1167
     * when the triple is absent.
1168
     */
1169
    boolean readNeedsFullRebuild() {
1170
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1171
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
1172
                    SpacesVocab.NEEDS_FULL_REBUILD);
1173
            return v != null && Boolean.parseBoolean(v.stringValue());
×
1174
        } catch (Exception ex) {
×
1175
            log.warn("AuthorityResolver: failed to read needsFullRebuild: {}", ex.toString());
×
1176
            return false;
×
1177
        }
1178
    }
1179

1180
    void setNeedsFullRebuild() {
1181
        writeNeedsFullRebuild(true);
×
1182
    }
×
1183

1184
    void clearNeedsFullRebuild() {
1185
        writeNeedsFullRebuild(false);
×
1186
    }
×
1187

1188
    private void writeNeedsFullRebuild(boolean value) {
1189
        String update = String.format("""
×
1190
                DELETE { GRAPH <%s> { <%s> <%s> ?old } }
1191
                INSERT { GRAPH <%s> { <%s> <%s> "%s"^^<http://www.w3.org/2001/XMLSchema#boolean> } }
1192
                WHERE  { OPTIONAL { GRAPH <%s> { <%s> <%s> ?old } } }
1193
                """,
1194
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.NEEDS_FULL_REBUILD,
1195
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.NEEDS_FULL_REBUILD, value,
×
1196
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.NEEDS_FULL_REBUILD);
1197
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1198
            conn.begin(IsolationLevels.SERIALIZABLE);
×
1199
            conn.prepareUpdate(QueryLanguage.SPARQL, update).execute();
×
1200
            conn.commit();
×
1201
        }
1202
    }
×
1203

1204
    void dropGraph(IRI graph) {
1205
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1206
            conn.begin(IsolationLevels.SERIALIZABLE);
×
1207
            conn.clear(graph);
×
1208
            conn.commit();
×
1209
            log.info("AuthorityResolver: dropped old space-state graph {}", graph);
×
1210
        }
1211
    }
×
1212

1213
    // ---------------- Trust-repo pointer lookup (used by TrustStateRegistry's bootstrap) ----------------
1214

1215
    /**
1216
     * Queries the {@code trust} repo directly for the current trust-state hash.
1217
     * Prefer {@link TrustStateRegistry#getCurrentHash()} in normal operation —
1218
     * this helper exists for tests and diagnostics.
1219
     *
1220
     * @return the current trust-state hash, or empty if none is set
1221
     */
1222
    Optional<String> readTrustRepoCurrentHash() {
1223
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(TRUST_REPO)) {
×
1224
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
1225
                    NPA_HAS_CURRENT_TRUST_STATE);
1226
            if (!(v instanceof IRI iri)) return Optional.empty();
×
1227
            String s = iri.stringValue();
×
1228
            if (!s.startsWith(NPAT.NAMESPACE)) return Optional.empty();
×
1229
            return Optional.of(s.substring(NPAT.NAMESPACE.length()));
×
1230
        } catch (Exception ex) {
×
1231
            log.warn("AuthorityResolver: failed to read trust-repo current pointer: {}", ex.toString());
×
1232
            return Optional.empty();
×
1233
        }
1234
    }
1235

1236
    private static String abbrev(String hash) {
1237
        return hash.length() > 12 ? hash.substring(0, 12) + "…" : hash;
×
1238
    }
1239

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