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

knowledgepixels / nanopub-query / 24978467419

27 Apr 2026 05:39AM UTC coverage: 55.994% (-0.9%) from 56.939%
24978467419

push

github

web-flow
Merge pull request #84 from knowledgepixels/feature/62-counter-semantics-cleanup

refactor: report distinct-subject totals in space-state build/cycle logs (#62)

385 of 774 branches covered (49.74%)

Branch coverage included in aggregate %.

1077 of 1837 relevant lines covered (58.63%)

9.03 hits per line

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

11.79
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() {
93
    }
94

95
    // ---------------- Public entry points ----------------
96

97
    /**
98
     * Poll entry point. Behaviour:
99
     * <ul>
100
     *   <li>If no current space-state graph or the trust state has flipped → full build.</li>
101
     *   <li>Otherwise → {@link #runIncrementalCycle incremental cycle} on the load-number
102
     *       delta {@code (processedUpTo, currentLoadCounter]}. No-op if {@code
103
     *       processedUpTo == currentLoadCounter}.</li>
104
     * </ul>
105
     * Safe to call repeatedly on a schedule. Gated by {@link FeatureFlags#spacesEnabled()}.
106
     */
107
    public void tick() {
108
        if (!FeatureFlags.spacesEnabled()) return;
6!
109
        String trustStateHash = TrustStateRegistry.get().getCurrentHash().orElse(null);
18✔
110
        if (trustStateHash == null) {
6!
111
            log.debug("AuthorityResolver.tick: no current trust state yet — skipping");
9✔
112
            return;
3✔
113
        }
114
        IRI currentGraph = getCurrentSpaceStateGraph();
×
115
        String currentGraphName = (currentGraph == null) ? null
×
116
                : currentGraph.stringValue().substring(SpacesVocab.NPASS_NAMESPACE.length());
×
117
        if (currentGraphName == null || !currentGraphName.startsWith(trustStateHash + "_")) {
×
118
            log.info("AuthorityResolver.tick: trust-state flip detected (now {}); running full build",
×
119
                    abbrev(trustStateHash));
×
120
            runFullBuild(trustStateHash);
×
121
            return;
×
122
        }
123
        runIncrementalCycle(currentGraph);
×
124
    }
×
125

126
    /**
127
     * Periodic worker. If {@code npa:needsFullRebuild} was raised by an
128
     * incremental cycle's structural DELETE, runs a from-scratch rebuild into
129
     * a fresh space-state graph (using the current trust-state hash and load
130
     * counter) and clears the flag. No-op when the flag is not set. Safe to
131
     * call concurrently with {@link #tick()} when both are scheduled on the
132
     * same single-threaded executor.
133
     */
134
    public void periodicRebuildTick() {
135
        if (!FeatureFlags.spacesEnabled()) return;
×
136
        if (!readNeedsFullRebuild()) return;
×
137
        String trustStateHash = TrustStateRegistry.get().getCurrentHash().orElse(null);
×
138
        if (trustStateHash == null) {
×
139
            log.debug("AuthorityResolver.periodicRebuildTick: no current trust state — deferring");
×
140
            return;
×
141
        }
142
        log.info("AuthorityResolver.periodicRebuildTick: needsFullRebuild flag set; rebuilding");
×
143
        runFullBuild(trustStateHash);
×
144
        clearNeedsFullRebuild();
×
145
    }
×
146

147
    /**
148
     * Startup cleanup: drop any {@code npass:*} graph that the
149
     * {@code npa:hasCurrentSpaceState} pointer isn't pointing at. Orphans come
150
     * from crashes mid-build. Safe to call at any time; idempotent.
151
     */
152
    public void cleanOrphans() {
153
        if (!FeatureFlags.spacesEnabled()) return;
×
154
        IRI current = getCurrentSpaceStateGraph();
×
155
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
156
            int dropped = 0;
×
157
            try (RepositoryResult<org.eclipse.rdf4j.model.Resource> ctxs = conn.getContextIDs()) {
×
158
                List<IRI> toDrop = new ArrayList<>();
×
159
                while (ctxs.hasNext()) {
×
160
                    org.eclipse.rdf4j.model.Resource ctx = ctxs.next();
×
161
                    if (!(ctx instanceof IRI iri)) continue;
×
162
                    if (!iri.stringValue().startsWith(SpacesVocab.NPASS_NAMESPACE)) continue;
×
163
                    if (iri.equals(current)) continue;
×
164
                    toDrop.add(iri);
×
165
                }
×
166
                for (IRI iri : toDrop) {
×
167
                    conn.begin(IsolationLevels.SERIALIZABLE);
×
168
                    conn.clear(iri);
×
169
                    conn.commit();
×
170
                    dropped++;
×
171
                    log.info("AuthorityResolver.cleanOrphans: dropped orphan graph {}", iri);
×
172
                }
×
173
            }
174
            if (dropped == 0) {
×
175
                log.debug("AuthorityResolver.cleanOrphans: no orphan space-state graphs");
×
176
            }
177
        } catch (Exception ex) {
×
178
            log.info("AuthorityResolver.cleanOrphans: failed: {}", ex.toString());
×
179
        }
×
180
    }
×
181

182
    // ---------------- Full build ----------------
183

184
    /**
185
     * Mutex-protected full build of the space-state graph for the given trust
186
     * state. Captures {@code M = currentLoadCounter}, mirrors trust-approved
187
     * rows, (PR 2b: runs per-tier UPDATE loops from scratch), stamps
188
     * {@code processedUpTo = M}, flips the pointer, drops the previous graph.
189
     */
190
    synchronized void runFullBuild(String trustStateHash) {
191
        long loadCounter = getCurrentLoadCounter();
×
192
        IRI newGraph = SpacesVocab.forSpaceState(trustStateHash, loadCounter);
×
193
        IRI oldGraph = getCurrentSpaceStateGraph();
×
194
        if (newGraph.equals(oldGraph)) {
×
195
            log.debug("AuthorityResolver.runFullBuild: already current at {}", newGraph);
×
196
            return;
×
197
        }
198

199
        // 1. Mirror trust-approved rows into the new graph.
200
        int mirrored = mirrorTrustState(trustStateHash, newGraph);
×
201

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

206
        // 3. Stamp processedUpTo inside the new graph.
207
        writeProcessedUpTo(newGraph, loadCounter);
×
208

209
        // 4. Flip the current-space-state pointer.
210
        flipPointer(newGraph);
×
211

212
        // 5. Drop the old graph if one existed.
213
        if (oldGraph != null) {
×
214
            dropGraph(oldGraph);
×
215
        }
216

217
        TierSubjectTotals totals = computeTierSubjectTotals(newGraph);
×
218
        log.info("AuthorityResolver: full build complete — graph={} mirrored={} rows loadCounter={} "
×
219
                        + "subjects: adminRIs={} attachmentRAs={} nonAdminRIs={} "
220
                        + "(inserted-triples: admin={} attachment={} maintainer={} member={} observer={})",
221
                newGraph, mirrored, loadCounter,
×
222
                totals.adminRIs(), totals.attachmentRAs(), totals.nonAdminRIs(),
×
223
                counts.admin, counts.attachment, counts.maintainer, counts.member, counts.observer);
×
224
    }
×
225

226
    // ---------------- Incremental cycle ----------------
227

228
    /**
229
     * Single delta cycle on the current space-state graph. Bounded by
230
     * {@code (processedUpTo, currentLoadCounter]}; no-op if the range is empty.
231
     *
232
     * <p>Order:
233
     * <ol>
234
     *   <li>Apply invalidation DELETEs (admin RI, RoleAssignment, non-admin RI)
235
     *       and the RoleDeclaration ASK. Any DELETE on a structural kind sets
236
     *       {@code npa:needsFullRebuild} to bound the staleness from sticky
237
     *       downstream entries; the periodic worker turns that into a from-scratch
238
     *       rebuild on its next pass.</li>
239
     *   <li>Run per-tier INSERTs in the same order as the full build.</li>
240
     *   <li>Late-arrival sweep: if any structural row was added, re-run downstream
241
     *       tier INSERTs with {@code lastProcessed = -1} to catch candidates whose
242
     *       enabling event landed in this same cycle. Dedup filters protect
243
     *       against double-insert.</li>
244
     *   <li>Bump {@code processedUpTo} to {@code currentLoadCounter}.</li>
245
     * </ol>
246
     */
247
    synchronized void runIncrementalCycle(IRI graph) {
248
        long currentLoadCounter = getCurrentLoadCounter();
×
249
        long lastProcessed = readProcessedUpTo(graph);
×
250
        if (lastProcessed < 0) {
×
251
            log.warn("AuthorityResolver.runIncrementalCycle: missing processedUpTo on {}; skipping",
×
252
                    graph);
253
            return;
×
254
        }
255
        if (currentLoadCounter <= lastProcessed) {
×
256
            log.debug("AuthorityResolver.runIncrementalCycle: caught up at load {} on {}",
×
257
                    currentLoadCounter, graph);
×
258
            return;
×
259
        }
260

261
        boolean structuralInvalidation = applyInvalidations(graph, lastProcessed);
×
262
        TierInsertedTriples counts = runAllTierLoops(graph, lastProcessed);
×
263
        boolean structuralAdds = (counts.admin > 0)
×
264
                || (counts.attachment > 0)
265
                || newRoleDeclarationsArrived(lastProcessed);
×
266
        if (structuralAdds) {
×
267
            // Late-arrival sweep: only the leaf tiers (attachment/maintainer/member/observer)
268
            // can promote candidates whose enabling event arrived in this same cycle. Skip
269
            // the admin tier — its only enabling event is the admin grant itself, already
270
            // handled by the regular pass.
271
            TierInsertedTriples lateCounts = runDownstreamWithoutLoadFilter(graph);
×
272
            counts.attachment += lateCounts.attachment;
×
273
            counts.maintainer += lateCounts.maintainer;
×
274
            counts.member     += lateCounts.member;
×
275
            counts.observer   += lateCounts.observer;
×
276
        }
277

278
        writeProcessedUpTo(graph, currentLoadCounter);
×
279

280
        TierSubjectTotals totals = computeTierSubjectTotals(graph);
×
281
        log.info("AuthorityResolver: incremental cycle complete — graph={} delta=({}, {}] "
×
282
                        + "subjects: adminRIs={} attachmentRAs={} nonAdminRIs={} "
283
                        + "(inserted-triples: admin={} attachment={} maintainer={} member={} observer={}) "
284
                        + "structuralInvalidation={} structuralAdds={}",
285
                graph, lastProcessed, currentLoadCounter,
×
286
                totals.adminRIs(), totals.attachmentRAs(), totals.nonAdminRIs(),
×
287
                counts.admin, counts.attachment, counts.maintainer, counts.member, counts.observer,
×
288
                structuralInvalidation, structuralAdds);
×
289
    }
×
290

291
    /**
292
     * Runs the four invalidation-DELETE / ASK steps. Sets {@code npa:needsFullRebuild}
293
     * when admin-RI, RoleAssignment, or RoleDeclaration invalidations matched (the
294
     * three structural kinds). Leaf-tier RI deletes don't set the flag.
295
     *
296
     * @return true iff at least one structural kind was invalidated
297
     */
298
    boolean applyInvalidations(IRI graph, long lastProcessed) {
299
        boolean structural = false;
×
300
        if (wouldInvalidate(graph, lastProcessed, /*adminPinned=*/ true,
×
301
                            adminInvalidationCheckWhere(graph, lastProcessed))) {
×
302
            executeUpdate(adminInvalidationDelete(graph, lastProcessed));
×
303
            structural = true;
×
304
        }
305
        if (wouldInvalidate(graph, lastProcessed, /*adminPinned=*/ false,
×
306
                            roleAssignmentInvalidationCheckWhere(graph, lastProcessed))) {
×
307
            executeUpdate(roleAssignmentInvalidationDelete(graph, lastProcessed));
×
308
            structural = true;
×
309
        }
310
        // RoleDeclaration ASK only — RDs aren't materialized into the space-state
311
        // graph, so there's nothing to DELETE here. The flag still flips because
312
        // sticky downstream RIs derived from the now-invalidated RD need a
313
        // from-scratch recompute.
314
        if (wouldInvalidate(graph, lastProcessed, /*adminPinned=*/ false,
×
315
                            roleDeclarationInvalidationCheckWhere(lastProcessed))) {
×
316
            structural = true;
×
317
        }
318
        // Leaf-tier RI deletes — no flag.
319
        executeUpdate(leafTierInvalidationDelete(graph, lastProcessed));
×
320
        if (structural) setNeedsFullRebuild();
×
321
        return structural;
×
322
    }
323

324
    /**
325
     * Runs the four leaf tiers (attachment/maintainer/member/observer) with
326
     * {@code lastProcessed = -1} so the load-number filter on the candidate
327
     * side admits everything. Dedup filters in the tier templates prevent
328
     * double-insert. Used by the late-arrival sweep.
329
     */
330
    TierInsertedTriples runDownstreamWithoutLoadFilter(IRI graph) {
331
        TierInsertedTriples c = new TierInsertedTriples();
×
332
        c.attachment = runTierLabeled("attachment(late)", graph,
×
333
                attachmentValidationUpdate(graph, -1));
×
334
        c.maintainer = runTierLabeled("maintainer(late)", graph,
×
335
                nonAdminTierUpdate(graph, -1, GEN.MAINTAINER_ROLE, PUBLISHER_IS_ADMIN));
×
336
        c.member = runTierLabeled("member(admin-pub,late)", graph,
×
337
                nonAdminTierUpdate(graph, -1, GEN.MEMBER_ROLE, PUBLISHER_IS_ADMIN));
×
338
        c.member += runTierLabeled("member(maint-pub,late)", graph,
×
339
                nonAdminTierUpdate(graph, -1,
×
340
                        GEN.MEMBER_ROLE, publisherIsTieredRole(GEN.MAINTAINER_ROLE)));
×
341
        c.observer = runTierLabeled("observer(self,late)", graph,
×
342
                nonAdminTierUpdate(graph, -1, GEN.OBSERVER_ROLE, PUBLISHER_IS_SELF));
×
343
        return c;
×
344
    }
345

346
    /**
347
     * Cheap ASK: did any new {@code npa:RoleDeclaration} extraction land in the
348
     * load-number delta {@code (lastProcessed, ∞)}? Used by the late-arrival
349
     * trigger so an RD that arrives in the same cycle as a matching candidate
350
     * still gets validated.
351
     */
352
    boolean newRoleDeclarationsArrived(long lastProcessed) {
353
        String ask = String.format("""
×
354
                PREFIX npa: <%1$s>
355
                ASK {
356
                  GRAPH <%2$s> {
357
                    ?rd a npa:RoleDeclaration ;
358
                        npa:viaNanopub ?np .
359
                  }
360
                  GRAPH <%3$s> {
361
                    ?np npa:hasLoadNumber ?ln .
362
                    FILTER (?ln > %4$d)
363
                  }
364
                }
365
                """, NPA.NAMESPACE, SpacesVocab.SPACES_GRAPH, NPA.GRAPH, lastProcessed);
×
366
        return runAsk(ask);
×
367
    }
368

369
    // ---------------- Tier UPDATE loops ----------------
370

371
    /**
372
     * Per-tier inserted-triple tallies for one build or cycle. Counts the sum
373
     * of {@code (graphSize_after - graphSize_before)} across all iterations of
374
     * each tier's fixed-point INSERT loop — i.e. inserted *triples*, not
375
     * distinct subjects (a single RoleInstantiation insert writes 4–5 triples).
376
     *
377
     * <p>Used internally by the {@link #runIncrementalCycle structuralAdds}
378
     * boolean check (we only care whether any tier inserted at all).
379
     * Not what the log lines report: see {@link TierSubjectTotals} +
380
     * {@link #computeTierSubjectTotals} for the distinct-subject totals
381
     * surfaced to operators.
382
     */
383
    static final class TierInsertedTriples {
×
384
        int admin;
385
        int attachment;
386
        int maintainer;
387
        int member;
388
        int observer;
389
    }
390

391
    /**
392
     * Snapshot of distinct-subject totals in a space-state graph at a moment
393
     * in time. Independent of which tier-loop added each subject.
394
     */
395
    record TierSubjectTotals(long adminRIs, long attachmentRAs, long nonAdminRIs) {}
×
396

397
    /**
398
     * Runs the five tier loops in order: admin → {@code gen:hasRole} attachment
399
     * validation → maintainer → member → observer. Each loop iterates a SPARQL
400
     * INSERT to fixed point (no new triples added). Returns per-tier counts.
401
     *
402
     * @param graph         target space-state graph
403
     * @param lastProcessed load-number horizon; use {@code -1} for full build
404
     */
405
    TierInsertedTriples runAllTierLoops(IRI graph, long lastProcessed) {
406
        TierInsertedTriples c = new TierInsertedTriples();
×
407
        c.admin = runTierLabeled("admin", graph, adminTierUpdate(graph, lastProcessed));
×
408
        c.attachment = runTierLabeled("attachment", graph,
×
409
                attachmentValidationUpdate(graph, lastProcessed));
×
410
        c.maintainer = runTierLabeled("maintainer", graph, nonAdminTierUpdate(graph, lastProcessed,
×
411
                GEN.MAINTAINER_ROLE, PUBLISHER_IS_ADMIN));
412
        // Member tier: admin OR maintainer publisher — split into two simpler updates
413
        // so the query planner doesn't struggle with the UNION.
414
        c.member = runTierLabeled("member(admin-pub)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
415
                GEN.MEMBER_ROLE, PUBLISHER_IS_ADMIN));
416
        c.member += runTierLabeled("member(maint-pub)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
417
                GEN.MEMBER_ROLE, publisherIsTieredRole(GEN.MAINTAINER_ROLE)));
×
418
        // Observer tier: self-evidence only per the plan's policy table
419
        // (gen:ObserverRole = self). Authority-publisher sub-tiers were overreach;
420
        // the three of them have been removed, so an observer instantiation is
421
        // validated iff the assignee's own pubkey signed it.
422
        c.observer = runTierLabeled("observer(self)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
423
                GEN.OBSERVER_ROLE, PUBLISHER_IS_SELF));
424
        return c;
×
425
    }
426

427
    /**
428
     * Builds a publisher constraint requiring the publisher to be a validated holder
429
     * of the given tier's role (maintainer or member) in the target space.
430
     * Owns its own AccountState resolution so ?publisher is bound through the
431
     * targeted (pkh → agent) lookup rather than enumerated.
432
     */
433
    private static String publisherIsTieredRole(IRI tierClass) {
434
        return """
×
435
                ?acct a npa:AccountState ;
436
                      npa:pubkey ?pkh ;
437
                      npa:agent  ?publisher .
438
                ?tierRI a gen:RoleInstantiation ;
439
                        npa:forSpace ?space ;
440
                        npa:forAgent ?publisher .
441
                ?rdT a npa:RoleDeclaration ;
442
                     npa:hasRoleType <%1$s> .
443
                { ?tierRI npa:regularProperty ?predT . ?rdT gen:hasRegularProperty ?predT . }
444
                UNION
445
                { ?tierRI npa:inverseProperty ?predT . ?rdT gen:hasInverseProperty ?predT . }
446
                """.formatted(tierClass);
×
447
    }
448

449
    /** Wraps {@link #runTierLoop} with tier-name context for logs/exceptions. */
450
    private int runTierLabeled(String tier, IRI graph, String sparqlUpdate) {
451
        try {
452
            return runTierLoop(graph, sparqlUpdate);
×
453
        } catch (RuntimeException ex) {
×
454
            log.error("AuthorityResolver: tier={} failed with SPARQL UPDATE:\n{}\n", tier, sparqlUpdate, ex);
×
455
            throw ex;
×
456
        }
457
    }
458

459
    /**
460
     * Runs a single tier's INSERT to fixed point. Counts rows by probing
461
     * graph size before/after each INSERT; stops when the size doesn't change.
462
     *
463
     * @return total number of triples inserted by this tier across all iterations
464
     */
465
    int runTierLoop(IRI graph, String sparqlUpdate) {
466
        int total = 0;
×
467
        long before = graphSize(graph);
×
468
        while (true) {
469
            // Note: no explicit transaction wrapping here. In tests we observed that
470
            // HTTPRepository's RDF4J-transaction protocol silently no-op'd cross-graph
471
            // SPARQL UPDATEs with UNION sub-patterns inside conn.begin()/commit(),
472
            // while the same UPDATE POSTed directly to /statements applied correctly.
473
            // A bare prepareUpdate().execute() takes the direct /statements path and
474
            // runs the UPDATE atomically per SPARQL 1.1 semantics — which is all we
475
            // need; there's nothing else to commit atomically alongside the UPDATE.
476
            try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
477
                conn.prepareUpdate(QueryLanguage.SPARQL, sparqlUpdate).execute();
×
478
            }
479
            long after = graphSize(graph);
×
480
            long added = after - before;
×
481
            if (added <= 0) break;
×
482
            total += added;
×
483
            before = after;
×
484
        }
×
485
        return total;
×
486
    }
487

488
    private long graphSize(IRI graph) {
489
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
490
            return conn.size(graph);
×
491
        }
492
    }
493

494
    /**
495
     * Distinct-subject totals in the given space-state graph, broken down by
496
     * RoleInstantiation kind (admin-pinned vs not) and RoleAssignment.
497
     * Three SELECT-COUNT queries — cheap, called once per build/cycle for
498
     * the user-facing log line. Returns zeros on failure (logged) so a flaky
499
     * count read can't wedge the cycle.
500
     */
501
    TierSubjectTotals computeTierSubjectTotals(IRI graph) {
502
        long adminRIs       = countDistinctSubjects(graph, """
×
503
                ?ri a gen:RoleInstantiation ; npa:inverseProperty gen:hasAdmin .
504
                """, "ri");
505
        long attachmentRAs  = countDistinctSubjects(graph, """
×
506
                ?ra a gen:RoleAssignment .
507
                """, "ra");
508
        long nonAdminRIs    = countDistinctSubjects(graph, """
×
509
                ?ri a gen:RoleInstantiation .
510
                FILTER NOT EXISTS { ?ri npa:inverseProperty gen:hasAdmin }
511
                """, "ri");
512
        return new TierSubjectTotals(adminRIs, attachmentRAs, nonAdminRIs);
×
513
    }
514

515
    private long countDistinctSubjects(IRI graph, String wherePattern, String varName) {
516
        String query = String.format("""
×
517
                PREFIX npa: <%1$s>
518
                PREFIX gen: <%2$s>
519
                SELECT (COUNT(DISTINCT ?%3$s) AS ?n) WHERE {
520
                  GRAPH <%4$s> {
521
                    %5$s
522
                  }
523
                }
524
                """, NPA.NAMESPACE, GEN.NAMESPACE, varName, graph, wherePattern);
525
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO);
×
526
             TupleQueryResult r = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) {
×
527
            if (!r.hasNext()) return 0;
×
528
            return Long.parseLong(r.next().getBinding("n").getValue().stringValue());
×
529
        } catch (Exception ex) {
×
530
            log.warn("AuthorityResolver: countDistinctSubjects on {} failed: {}",
×
531
                    graph, ex.toString());
×
532
            return 0;
×
533
        }
534
    }
535

536
    // ---------------- SPARQL templates ----------------
537

538
    /**
539
     * Reusable invalidation filter on a bound nanopub-IRI variable. Pass the bare
540
     * variable name (no leading {@code ?}); e.g. {@code invalidationFilter("np")}
541
     * produces an outer-scoped {@code FILTER NOT EXISTS { GRAPH npa:spacesGraph
542
     * { ?_inv_np a npa:Invalidation ; npa:invalidates ?np . } }}.
543
     *
544
     * <p>Important: this filter must be placed OUTSIDE the surrounding
545
     * {@code GRAPH npa:spacesGraph { ... }} block, not nested inside it. When
546
     * nested, RDF4J's planner couples the FILTER NOT EXISTS evaluation into the
547
     * join order (per-row scan of {@code ?_inv a npa:Invalidation} multiplied by
548
     * the candidate set), which we measured turning a 39ms query into a 60s+
549
     * timeout on the live observer-tier data. Outside the GRAPH block, the
550
     * planner defers the filter until {@code ?np}/{@code ?rdNp} are bound and
551
     * does a targeted index lookup.
552
     *
553
     * <p>Variable names must match {@code [A-Za-z0-9_]+} per SPARQL grammar —
554
     * embedding a {@code ?} inside {@code ?_inv_?np} would yield a parse error.
555
     */
556
    private static String invalidationFilter(String bareVarName) {
557
        return "FILTER NOT EXISTS { GRAPH <" + SpacesVocab.SPACES_GRAPH + "> {"
30✔
558
                + " ?_inv_" + bareVarName
559
                + " a <" + SpacesVocab.INVALIDATION + "> ; "
560
                + "<" + SpacesVocab.INVALIDATES + "> ?" + bareVarName + " . } }";
561
    }
562

563
    /**
564
     * Admin tier: seed from {@code npadef:...hasRootAdmin} (trusted by construction)
565
     * plus closed-over admin grants; insert any {@code gen:RoleInstantiation} with
566
     * {@code npa:inverseProperty gen:hasAdmin} whose publisher (resolved via mirrored
567
     * trust-approved AccountState) is already in the admin set.
568
     */
569
    static String adminTierUpdate(IRI graph, long lastProcessed) {
570
        // Order tuned for RDF4J's evaluator:
571
        //   1. Anchor on the small (seed UNION closed-over) set to bind ?publisher
572
        //      and ?space cheaply.
573
        //   2. Resolve ?pkh from the mirrored AccountState row (?publisher bound).
574
        //   3. Probe instantiations using the now-bound (?space, ?pkh) — targeted
575
        //      lookup, not a full RoleInstantiation scan.
576
        //   4. Load-number filter on bound ?np.
577
        //   5. Dedup at the end.
578
        return """
69✔
579
                PREFIX npa:  <%1$s>
580
                PREFIX gen:  <%2$s>
581
                INSERT { GRAPH <%3$s> {
582
                  ?ri a gen:RoleInstantiation ;
583
                      npa:forSpace ?space ;
584
                      npa:inverseProperty gen:hasAdmin ;
585
                      npa:forAgent ?agent ;
586
                      npa:viaNanopub ?np .
587
                } }
588
                WHERE {
589
                  # 1. Anchor: who is already an admin of which space?
590
                  {
591
                    # Seed branch: root-admin in a non-invalidated SpaceDefinition.
592
                    GRAPH <%4$s> {
593
                      ?def a npa:SpaceDefinition ;
594
                           npa:forSpaceRef  ?spaceRef ;
595
                           npa:hasRootAdmin ?publisher ;
596
                           npa:viaNanopub   ?defNp .
597
                      ?spaceRef npa:spaceIri ?space .
598
                    }
599
                    %7$s
600
                  }
601
                  UNION
602
                  {
603
                    # Closed-over branch: an existing admin in this space-state graph.
604
                    GRAPH <%3$s> {
605
                      ?prev a gen:RoleInstantiation ;
606
                            npa:forSpace        ?space ;
607
                            npa:inverseProperty gen:hasAdmin ;
608
                            npa:forAgent        ?publisher .
609
                    }
610
                  }
611
                  # 2. Mirror: resolve ?publisher → ?pkh via the trust-approved row.
612
                  GRAPH <%3$s> {
613
                    ?acct a npa:AccountState ;
614
                          npa:agent  ?publisher ;
615
                          npa:pubkey ?pkh .
616
                  }
617
                  # 3. Targeted instantiation lookup by space + pubkey.
618
                  GRAPH <%4$s> {
619
                    ?ri a gen:RoleInstantiation ;
620
                        npa:forSpace        ?space ;
621
                        npa:inverseProperty gen:hasAdmin ;
622
                        npa:forAgent        ?agent ;
623
                        npa:pubkeyHash      ?pkh ;
624
                        npa:viaNanopub      ?np .
625
                  }
626
                  %6$s
627
                  # 4. Load-number filter on bound ?np.
628
                  GRAPH <%8$s> {
629
                    ?np npa:hasLoadNumber ?ln .
630
                    FILTER (?ln > %5$d)
631
                  }
632
                  # 5. Dedup last.
633
                  FILTER NOT EXISTS { GRAPH <%3$s> {
634
                    ?existing a gen:RoleInstantiation ;
635
                              npa:forSpace ?space ;
636
                              npa:forAgent ?agent ;
637
                              npa:inverseProperty gen:hasAdmin .
638
                  } }
639
                }
640
                """.formatted(
3✔
641
                NPA.NAMESPACE,
642
                GEN.NAMESPACE,
643
                graph,
644
                SpacesVocab.SPACES_GRAPH,
645
                lastProcessed,
15✔
646
                invalidationFilter("np"),
15✔
647
                invalidationFilter("defNp"),
18✔
648
                NPA.GRAPH);
649
    }
650

651
    /**
652
     * {@code gen:hasRole} attachment validation: an attachment is validated iff its
653
     * publisher is already a validated admin of the target space. Adds
654
     * {@code gen:RoleAssignment} rows to the space-state graph.
655
     */
656
    static String attachmentValidationUpdate(IRI graph, long lastProcessed) {
657
        return """
69✔
658
                PREFIX npa:  <%1$s>
659
                PREFIX gen:  <%2$s>
660
                INSERT { GRAPH <%3$s> {
661
                  ?ra a gen:RoleAssignment ;
662
                      npa:forSpace ?space ;
663
                      gen:hasRole  ?role ;
664
                      npa:viaNanopub ?np .
665
                } }
666
                WHERE {
667
                  GRAPH <%4$s> {
668
                    ?ra a gen:RoleAssignment ;
669
                        npa:forSpace ?space ;
670
                        gen:hasRole  ?role ;
671
                        npa:pubkeyHash ?pkh ;
672
                        npa:viaNanopub ?np .
673
                  }
674
                  GRAPH <%7$s> {
675
                    ?np npa:hasLoadNumber ?ln .
676
                    FILTER (?ln > %5$d)
677
                  }
678
                  GRAPH <%3$s> {
679
                    ?acct a npa:AccountState ;
680
                          npa:agent  ?publisher ;
681
                          npa:pubkey ?pkh .
682
                    ?adminRI a gen:RoleInstantiation ;
683
                             npa:forSpace ?space ;
684
                             npa:inverseProperty gen:hasAdmin ;
685
                             npa:forAgent ?publisher .
686
                  }
687
                  %6$s
688
                  FILTER NOT EXISTS { GRAPH <%3$s> {
689
                    ?existing a gen:RoleAssignment ;
690
                              npa:forSpace ?space ;
691
                              gen:hasRole  ?role .
692
                  } }
693
                }
694
                """.formatted(
3✔
695
                NPA.NAMESPACE,
696
                GEN.NAMESPACE,
697
                graph,
698
                SpacesVocab.SPACES_GRAPH,
699
                lastProcessed,
15✔
700
                invalidationFilter("np"),
18✔
701
                NPA.GRAPH);
702
    }
703

704
    /**
705
     * Non-admin tier publisher constraints (inserted as a SPARQL sub-pattern).
706
     * Each constraint owns the AccountState (pkh → agent) lookup so the join
707
     * variable is bound through a targeted pattern. The observer-self variant
708
     * binds {@code npa:agent ?agent} directly — no separate {@code ?publisher}
709
     * variable, no post-join equality filter — which lets the planner anchor
710
     * the AccountState lookup on the already-bound {@code ?agent} instead of
711
     * enumerating all approved publishers and filtering at the end.
712
     */
713
    static final String PUBLISHER_IS_ADMIN = """
714
            ?acct a npa:AccountState ;
715
                  npa:pubkey ?pkh ;
716
                  npa:agent  ?publisher .
717
            ?adminRI a gen:RoleInstantiation ;
718
                     npa:forSpace ?space ;
719
                     npa:inverseProperty gen:hasAdmin ;
720
                     npa:forAgent ?publisher .
721
            """;
722

723
    /** Observer self-evidence: the assignee's own pubkey signed the instantiation. */
724
    static final String PUBLISHER_IS_SELF = """
725
            ?acct a npa:AccountState ;
726
                  npa:pubkey ?pkh ;
727
                  npa:agent  ?agent .
728
            """;
729

730
    /**
731
     * Maintainer / Member / Observer tier INSERT. Same shape: find an instantiation
732
     * whose predicate matches a RoleDeclaration of the given tier attached to the
733
     * target space, and whose publisher passes the tier-specific constraint.
734
     */
735
    static String nonAdminTierUpdate(IRI graph, long lastProcessed,
736
                                     IRI tierClass, String publisherConstraint) {
737
        // Order tuned for RDF4J's evaluator (which executes BGPs roughly in order).
738
        // The crucial choice is the *anchor*: instantiation-first plans send the
739
        // planner exploring the full ~thousands of candidate RIs and only filter
740
        // by tier at the very end. Attachment-first anchors on the small set of
741
        // gen:RoleAssignment rows already validated in this space-state graph
742
        // (~hundreds, often zero) and walks outward by bound (?role, ?space).
743
        //
744
        //   1. Anchor on RoleAssignments in this space-state graph (small).
745
        //   2. Match the tier-pinned RoleDeclaration by ?role.
746
        //   3. Pair role-decl direction to instantiation direction in one UNION
747
        //      so only (reg, reg)/(inv, inv) combos are explored.
748
        //   4. Targeted instantiation lookup — (?space, ?pred) are bound.
749
        //   5. Publisher constraint (incl. AccountState resolution).
750
        //   6. Load-number filter on bound ?np.
751
        //   7. Dedup at the end.
752
        return """
69✔
753
                PREFIX npa:  <%1$s>
754
                PREFIX gen:  <%2$s>
755
                INSERT { GRAPH <%3$s> {
756
                  ?ri a gen:RoleInstantiation ;
757
                      npa:forSpace ?space ;
758
                      npa:forAgent ?agent ;
759
                      npa:viaNanopub ?np .
760
                } }
761
                WHERE {
762
                  # 1. Anchor: validated attachments in this space-state graph.
763
                  GRAPH <%3$s> {
764
                    ?ra a gen:RoleAssignment ;
765
                        gen:hasRole  ?role ;
766
                        npa:forSpace ?space .
767
                  }
768
                  # 2. Tier-pinned RoleDeclaration (?role bound from the attachment).
769
                  GRAPH <%4$s> {
770
                    ?rd a npa:RoleDeclaration ;
771
                        npa:hasRoleType <%7$s> ;
772
                        npa:role        ?role ;
773
                        npa:viaNanopub  ?rdNp .
774
                    # 3. Pair direction so only matching combos are explored.
775
                    {
776
                      ?rd gen:hasRegularProperty ?pred .
777
                      ?ri npa:regularProperty    ?pred .
778
                    }
779
                    UNION
780
                    {
781
                      ?rd gen:hasInverseProperty ?pred .
782
                      ?ri npa:inverseProperty    ?pred .
783
                    }
784
                    # 4. Targeted instantiation lookup — (?space, ?pred) bound.
785
                    ?ri a gen:RoleInstantiation ;
786
                        npa:forSpace   ?space ;
787
                        npa:forAgent   ?agent ;
788
                        npa:pubkeyHash ?pkh ;
789
                        npa:viaNanopub ?np .
790
                  }
791
                  # 5. Publisher constraint (incl. AccountState resolution).
792
                  GRAPH <%3$s> {
793
                    %9$s
794
                  }
795
                  # 6. Load-number filter on bound ?np.
796
                  GRAPH <%10$s> {
797
                    ?np npa:hasLoadNumber ?ln .
798
                    FILTER (?ln > %5$d)
799
                  }
800
                  # 7. Invalidation filters — outside the GRAPH block so the
801
                  #    planner defers them until ?rdNp/?np are bound.
802
                  %8$s
803
                  %6$s
804
                  # 8. Dedup last.
805
                  FILTER NOT EXISTS { GRAPH <%3$s> {
806
                    ?existing a gen:RoleInstantiation ;
807
                              npa:forSpace ?space ;
808
                              npa:forAgent ?agent ;
809
                              npa:viaNanopub ?np .
810
                  } }
811
                }
812
                """.formatted(
3✔
813
                NPA.NAMESPACE,
814
                GEN.NAMESPACE,
815
                graph,
816
                SpacesVocab.SPACES_GRAPH,
817
                lastProcessed,
15✔
818
                invalidationFilter("np"),
27✔
819
                tierClass,
820
                invalidationFilter("rdNp"),
30✔
821
                publisherConstraint,
822
                NPA.GRAPH);
823
    }
824

825
    // ---------------- Invalidation templates (incremental cycle) ----------------
826

827
    /**
828
     * WHERE clause shared by the admin-RI invalidation ASK precheck and the
829
     * matching DELETE. Identifies admin-tier {@code gen:RoleInstantiation} rows
830
     * in the space-state graph whose {@code npa:viaNanopub} equals the target
831
     * of an {@code npa:Invalidation} that landed in {@code (lastProcessed, ∞)}.
832
     */
833
    static String adminInvalidationCheckWhere(IRI graph, long lastProcessed) {
834
        return String.format("""
60✔
835
                  GRAPH <%1$s> {
836
                    ?ri a gen:RoleInstantiation ;
837
                        npa:inverseProperty gen:hasAdmin ;
838
                        npa:viaNanopub ?np .
839
                  }
840
                  GRAPH <%2$s> {
841
                    ?inv a npa:Invalidation ;
842
                         npa:invalidates ?np ;
843
                         npa:viaNanopub  ?invNp .
844
                  }
845
                  GRAPH <%3$s> {
846
                    ?invNp npa:hasLoadNumber ?ln .
847
                    FILTER (?ln > %4$d)
848
                  }
849
                """, graph, SpacesVocab.SPACES_GRAPH, NPA.GRAPH, lastProcessed);
6✔
850
    }
851

852
    /** DELETE template for admin-tier RoleInstantiations whose source nanopub was invalidated. */
853
    static String adminInvalidationDelete(IRI graph, long lastProcessed) {
854
        return String.format("""
63✔
855
                PREFIX npa: <%1$s>
856
                PREFIX gen: <%2$s>
857
                DELETE { GRAPH <%3$s> {
858
                  ?ri ?p ?o .
859
                } }
860
                WHERE {
861
                  GRAPH <%3$s> { ?ri ?p ?o . }
862
                %4$s
863
                }
864
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
865
                adminInvalidationCheckWhere(graph, lastProcessed));
6✔
866
    }
867

868
    /** WHERE clause for RoleAssignment invalidation. */
869
    static String roleAssignmentInvalidationCheckWhere(IRI graph, long lastProcessed) {
870
        return String.format("""
60✔
871
                  GRAPH <%1$s> {
872
                    ?ra a gen:RoleAssignment ;
873
                        npa:viaNanopub ?np .
874
                  }
875
                  GRAPH <%2$s> {
876
                    ?inv a npa:Invalidation ;
877
                         npa:invalidates ?np ;
878
                         npa:viaNanopub  ?invNp .
879
                  }
880
                  GRAPH <%3$s> {
881
                    ?invNp npa:hasLoadNumber ?ln .
882
                    FILTER (?ln > %4$d)
883
                  }
884
                """, graph, SpacesVocab.SPACES_GRAPH, NPA.GRAPH, lastProcessed);
6✔
885
    }
886

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

903
    /**
904
     * WHERE clause for RoleDeclaration invalidation. ASK-only (no DELETE):
905
     * RoleDeclarations live in {@code npa:spacesGraph} and aren't materialized
906
     * into the space-state graph, so there's nothing to remove from the
907
     * space-state. The ASK still flips {@code npa:needsFullRebuild} because
908
     * sticky downstream RIs that were derived under the now-invalidated RD
909
     * need a from-scratch recompute.
910
     */
911
    static String roleDeclarationInvalidationCheckWhere(long lastProcessed) {
912
        return String.format("""
48✔
913
                  GRAPH <%1$s> {
914
                    ?rd a npa:RoleDeclaration ;
915
                        npa:viaNanopub ?np .
916
                    ?inv a npa:Invalidation ;
917
                         npa:invalidates ?np ;
918
                         npa:viaNanopub  ?invNp .
919
                  }
920
                  GRAPH <%2$s> {
921
                    ?invNp npa:hasLoadNumber ?ln .
922
                    FILTER (?ln > %3$d)
923
                  }
924
                """, SpacesVocab.SPACES_GRAPH, NPA.GRAPH, lastProcessed);
6✔
925
    }
926

927
    /**
928
     * DELETE template for non-admin (leaf-tier) RoleInstantiations whose source
929
     * nanopub was invalidated. Identified as {@code gen:RoleInstantiation} rows
930
     * lacking the admin-pinning {@code npa:inverseProperty gen:hasAdmin} triple.
931
     * No flag is set; leaf-tier removals are recoverable on the next cycle.
932
     */
933
    static String leafTierInvalidationDelete(IRI graph, long lastProcessed) {
934
        return String.format("""
84✔
935
                PREFIX npa: <%1$s>
936
                PREFIX gen: <%2$s>
937
                DELETE { GRAPH <%3$s> {
938
                  ?ri ?p ?o .
939
                } }
940
                WHERE {
941
                  GRAPH <%3$s> {
942
                    ?ri a gen:RoleInstantiation ;
943
                        npa:viaNanopub ?np .
944
                    FILTER NOT EXISTS { ?ri npa:inverseProperty gen:hasAdmin }
945
                    ?ri ?p ?o .
946
                  }
947
                  GRAPH <%4$s> {
948
                    ?inv a npa:Invalidation ;
949
                         npa:invalidates ?np ;
950
                         npa:viaNanopub  ?invNp .
951
                  }
952
                  GRAPH <%5$s> {
953
                    ?invNp npa:hasLoadNumber ?ln .
954
                    FILTER (?ln > %6$d)
955
                  }
956
                }
957
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
958
                SpacesVocab.SPACES_GRAPH, NPA.GRAPH, lastProcessed);
6✔
959
    }
960

961
    /** Wraps an ASK by joining the shared prefixes. */
962
    private boolean wouldInvalidate(IRI graph, long lastProcessed,
963
                                    boolean adminPinned, String whereClause) {
964
        // adminPinned is informational only — kept to make call sites read clearly;
965
        // the WHERE clause already encodes the kind via its own type predicates.
966
        String ask = String.format("""
×
967
                PREFIX npa: <%1$s>
968
                PREFIX gen: <%2$s>
969
                ASK { %3$s }
970
                """, NPA.NAMESPACE, GEN.NAMESPACE, whereClause);
971
        return runAsk(ask);
×
972
    }
973

974
    private boolean runAsk(String sparql) {
975
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
976
            return conn.prepareBooleanQuery(QueryLanguage.SPARQL, sparql).evaluate();
×
977
        }
978
    }
979

980
    private void executeUpdate(String sparqlUpdate) {
981
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
982
            conn.prepareUpdate(QueryLanguage.SPARQL, sparqlUpdate).execute();
×
983
        }
984
    }
×
985

986
    // ---------------- Mirror step ----------------
987

988
    /**
989
     * Copies trust-approved {@code npa:AccountState} rows from {@code npat:<T>}
990
     * in the {@code trust} repo into {@code newGraph} in the {@code spaces} repo,
991
     * inside one spaces-side serializable transaction.
992
     *
993
     * @return number of rows mirrored (useful for metrics / logging)
994
     */
995
    int mirrorTrustState(String trustStateHash, IRI newGraph) {
996
        IRI trustStateIri = NPAT.forHash(trustStateHash);
×
997
        int count = 0;
×
998
        try (RepositoryConnection trustConn = TripleStore.get().getRepoConnection(TRUST_REPO);
×
999
             RepositoryConnection spacesConn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1000
            trustConn.begin(IsolationLevels.READ_COMMITTED);
×
1001
            spacesConn.begin(IsolationLevels.SERIALIZABLE);
×
1002
            // Walk rdf:type triples in the trust state's graph; for each AccountState,
1003
            // check status and copy the approved ones verbatim (minus status-specific
1004
            // detail triples, which we don't need for validation).
1005
            try (RepositoryResult<Statement> typeRows = trustConn.getStatements(
×
1006
                    null, RDF.TYPE, NPA_ACCOUNT_STATE, trustStateIri)) {
1007
                while (typeRows.hasNext()) {
×
1008
                    Statement st = typeRows.next();
×
1009
                    if (!(st.getSubject() instanceof IRI accountStateIri)) continue;
×
1010
                    Value status = trustConn.getStatements(accountStateIri, NPA_TRUST_STATUS, null, trustStateIri)
×
1011
                            .stream().findFirst().map(Statement::getObject).orElse(null);
×
1012
                    if (!(status instanceof IRI statusIri) || !APPROVED_SET.contains(statusIri)) continue;
×
1013
                    Value agent = trustConn.getStatements(accountStateIri, NPA_AGENT, null, trustStateIri)
×
1014
                            .stream().findFirst().map(Statement::getObject).orElse(null);
×
1015
                    Value pubkey = trustConn.getStatements(accountStateIri, NPA_PUBKEY, null, trustStateIri)
×
1016
                            .stream().findFirst().map(Statement::getObject).orElse(null);
×
1017
                    if (agent == null || pubkey == null) {
×
1018
                        log.warn("AuthorityResolver.mirror: account {} missing agent or pubkey; skipping",
×
1019
                                accountStateIri);
1020
                        continue;
×
1021
                    }
1022
                    spacesConn.add(accountStateIri, RDF.TYPE, NPA_ACCOUNT_STATE, newGraph);
×
1023
                    spacesConn.add(accountStateIri, NPA_AGENT, agent, newGraph);
×
1024
                    spacesConn.add(accountStateIri, NPA_PUBKEY, pubkey, newGraph);
×
1025
                    spacesConn.add(accountStateIri, NPA_TRUST_STATUS, statusIri, newGraph);
×
1026
                    count++;
×
1027
                }
×
1028
            }
1029
            spacesConn.commit();
×
1030
            trustConn.commit();
×
1031
        }
1032
        return count;
×
1033
    }
1034

1035
    // ---------------- Pointer + counter helpers ----------------
1036

1037
    /**
1038
     * Reads the current {@code npa:hasCurrentSpaceState} pointer from the
1039
     * {@code npa:graph} admin graph of the {@code spaces} repo. Returns
1040
     * {@code null} if no pointer exists yet.
1041
     */
1042
    IRI getCurrentSpaceStateGraph() {
1043
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1044
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
1045
                    SpacesVocab.HAS_CURRENT_SPACE_STATE);
1046
            return (v instanceof IRI iri) ? iri : null;
×
1047
        } catch (Exception ex) {
×
1048
            log.warn("AuthorityResolver: failed to read hasCurrentSpaceState pointer: {}", ex.toString());
×
1049
            return null;
×
1050
        }
1051
    }
1052

1053
    long getCurrentLoadCounter() {
1054
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1055
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
1056
                    SpacesVocab.CURRENT_LOAD_COUNTER);
1057
            if (v == null) return 0;
×
1058
            try {
1059
                return Long.parseLong(v.stringValue());
×
1060
            } catch (NumberFormatException ex) {
×
1061
                log.warn("AuthorityResolver: non-numeric currentLoadCounter: {}", v);
×
1062
                return 0;
×
1063
            }
1064
        } catch (Exception ex) {
×
1065
            log.warn("AuthorityResolver: failed to read currentLoadCounter: {}", ex.toString());
×
1066
            return 0;
×
1067
        }
1068
    }
1069

1070
    /**
1071
     * Atomic pointer flip: a single SPARQL {@code DELETE … INSERT … WHERE}
1072
     * replaces the old pointer with the new one in one statement, so readers
1073
     * never see a zero-pointer window.
1074
     */
1075
    void flipPointer(IRI newGraph) {
1076
        String update = String.format("""
×
1077
                DELETE { GRAPH <%s> { <%s> <%s> ?old } }
1078
                INSERT { GRAPH <%s> { <%s> <%s> <%s> } }
1079
                WHERE  { OPTIONAL { GRAPH <%s> { <%s> <%s> ?old } } }
1080
                """,
1081
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.HAS_CURRENT_SPACE_STATE,
1082
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.HAS_CURRENT_SPACE_STATE, newGraph,
1083
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.HAS_CURRENT_SPACE_STATE);
1084
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1085
            conn.begin(IsolationLevels.SERIALIZABLE);
×
1086
            conn.prepareUpdate(QueryLanguage.SPARQL, update).execute();
×
1087
            conn.commit();
×
1088
        }
1089
    }
×
1090

1091
    void writeProcessedUpTo(IRI graph, long loadCounter) {
1092
        String update = String.format("""
×
1093
                DELETE { GRAPH <%s> { <%s> <%s> ?old } }
1094
                INSERT { GRAPH <%s> { <%s> <%s> "%d"^^<http://www.w3.org/2001/XMLSchema#long> } }
1095
                WHERE  { OPTIONAL { GRAPH <%s> { <%s> <%s> ?old } } }
1096
                """,
1097
                graph, graph, SpacesVocab.PROCESSED_UP_TO,
1098
                graph, graph, SpacesVocab.PROCESSED_UP_TO, loadCounter,
×
1099
                graph, graph, SpacesVocab.PROCESSED_UP_TO);
1100
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1101
            conn.begin(IsolationLevels.SERIALIZABLE);
×
1102
            conn.prepareUpdate(QueryLanguage.SPARQL, update).execute();
×
1103
            conn.commit();
×
1104
        }
1105
    }
×
1106

1107
    /**
1108
     * Reads {@code processedUpTo} from the given space-state graph.
1109
     * Returns {@code -1} if absent (graph not fully built yet).
1110
     */
1111
    long readProcessedUpTo(IRI graph) {
1112
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1113
            String query = String.format(
×
1114
                    "SELECT ?n WHERE { GRAPH <%s> { <%s> <%s> ?n } }",
1115
                    graph, graph, SpacesVocab.PROCESSED_UP_TO);
1116
            try (TupleQueryResult r = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) {
×
1117
                if (!r.hasNext()) return -1;
×
1118
                BindingSet b = r.next();
×
1119
                return Long.parseLong(b.getBinding("n").getValue().stringValue());
×
1120
            }
×
1121
        } catch (Exception ex) {
×
1122
            log.warn("AuthorityResolver: failed to read processedUpTo for {}: {}", graph, ex.toString());
×
1123
            return -1;
×
1124
        }
1125
    }
1126

1127
    /**
1128
     * Reads the {@code npa:needsFullRebuild} flag (boolean literal) from
1129
     * {@code npa:graph} in the {@code spaces} repo. Defaults to {@code false}
1130
     * when the triple is absent.
1131
     */
1132
    boolean readNeedsFullRebuild() {
1133
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1134
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
1135
                    SpacesVocab.NEEDS_FULL_REBUILD);
1136
            return v != null && Boolean.parseBoolean(v.stringValue());
×
1137
        } catch (Exception ex) {
×
1138
            log.warn("AuthorityResolver: failed to read needsFullRebuild: {}", ex.toString());
×
1139
            return false;
×
1140
        }
1141
    }
1142

1143
    void setNeedsFullRebuild() {
1144
        writeNeedsFullRebuild(true);
×
1145
    }
×
1146

1147
    void clearNeedsFullRebuild() {
1148
        writeNeedsFullRebuild(false);
×
1149
    }
×
1150

1151
    private void writeNeedsFullRebuild(boolean value) {
1152
        String update = String.format("""
×
1153
                DELETE { GRAPH <%s> { <%s> <%s> ?old } }
1154
                INSERT { GRAPH <%s> { <%s> <%s> "%s"^^<http://www.w3.org/2001/XMLSchema#boolean> } }
1155
                WHERE  { OPTIONAL { GRAPH <%s> { <%s> <%s> ?old } } }
1156
                """,
1157
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.NEEDS_FULL_REBUILD,
1158
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.NEEDS_FULL_REBUILD, value,
×
1159
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.NEEDS_FULL_REBUILD);
1160
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1161
            conn.begin(IsolationLevels.SERIALIZABLE);
×
1162
            conn.prepareUpdate(QueryLanguage.SPARQL, update).execute();
×
1163
            conn.commit();
×
1164
        }
1165
    }
×
1166

1167
    void dropGraph(IRI graph) {
1168
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1169
            conn.begin(IsolationLevels.SERIALIZABLE);
×
1170
            conn.clear(graph);
×
1171
            conn.commit();
×
1172
            log.info("AuthorityResolver: dropped old space-state graph {}", graph);
×
1173
        }
1174
    }
×
1175

1176
    // ---------------- Trust-repo pointer lookup (used by TrustStateRegistry's bootstrap) ----------------
1177

1178
    /**
1179
     * Queries the {@code trust} repo directly for the current trust-state hash.
1180
     * Prefer {@link TrustStateRegistry#getCurrentHash()} in normal operation —
1181
     * this helper exists for tests and diagnostics.
1182
     *
1183
     * @return the current trust-state hash, or empty if none is set
1184
     */
1185
    Optional<String> readTrustRepoCurrentHash() {
1186
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(TRUST_REPO)) {
×
1187
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
1188
                    NPA_HAS_CURRENT_TRUST_STATE);
1189
            if (!(v instanceof IRI iri)) return Optional.empty();
×
1190
            String s = iri.stringValue();
×
1191
            if (!s.startsWith(NPAT.NAMESPACE)) return Optional.empty();
×
1192
            return Optional.of(s.substring(NPAT.NAMESPACE.length()));
×
1193
        } catch (Exception ex) {
×
1194
            log.warn("AuthorityResolver: failed to read trust-repo current pointer: {}", ex.toString());
×
1195
            return Optional.empty();
×
1196
        }
1197
    }
1198

1199
    private static String abbrev(String hash) {
1200
        return hash.length() > 12 ? hash.substring(0, 12) + "…" : hash;
×
1201
    }
1202

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