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

knowledgepixels / nanopub-query / 24910542966

24 Apr 2026 08:32PM UTC coverage: 59.022% (-0.4%) from 59.461%
24910542966

Pull #81

github

web-flow
Merge 888738e5a into 2324af847
Pull Request #81: feat: per-tier SPARQL UPDATE loops in full build (#62, PR 2b/3)

385 of 740 branches covered (52.03%)

Branch coverage included in aggregate %.

1064 of 1715 relevant lines covered (62.04%)

9.42 hits per line

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

14.13
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: detects trust-state flips,
30
 * mirrors the approved {@code (agent, pubkey)} rows from the {@code trust} repo
31
 * into a fresh {@code npass:<T>_<M>} graph in the {@code spaces} repo, runs the
32
 * per-tier validation loops (stubbed in PR 2a), flips the
33
 * {@code npa:hasCurrentSpaceState} pointer, and drops the previous graph. Also
34
 * cleans up orphan {@code npass:*} graphs on startup.
35
 *
36
 * <p>See {@code doc/plan-space-repositories.md} — this implements the "Full
37
 * build" procedure plus pointer management and the mirror step. Per-tier SPARQL
38
 * UPDATE loops, the incremental cycle, and the periodic-rebuild flag follow in
39
 * PRs 2b and 2c.
40
 */
41
public final class AuthorityResolver {
42

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

45
    private static final ValueFactory vf = SimpleValueFactory.getInstance();
6✔
46

47
    private static final String SPACES_REPO = "spaces";
48
    private static final String TRUST_REPO = "trust";
49

50
    /** NPA constants pulled in locally (trust-side). */
51
    private static final IRI NPA_HAS_CURRENT_TRUST_STATE =
9✔
52
            vf.createIRI(NPA.NAMESPACE, "hasCurrentTrustState");
6✔
53
    private static final IRI NPA_ACCOUNT_STATE = vf.createIRI(NPA.NAMESPACE, "AccountState");
15✔
54
    private static final IRI NPA_AGENT = vf.createIRI(NPA.NAMESPACE, "agent");
15✔
55
    private static final IRI NPA_PUBKEY = vf.createIRI(NPA.NAMESPACE, "pubkey");
15✔
56
    private static final IRI NPA_TRUST_STATUS = vf.createIRI(NPA.NAMESPACE, "trustStatus");
15✔
57
    private static final IRI NPA_LOADED = vf.createIRI(NPA.NAMESPACE, "loaded");
15✔
58
    private static final IRI NPA_TO_LOAD = vf.createIRI(NPA.NAMESPACE, "toLoad");
15✔
59

60
    /**
61
     * Trust-approved set: rows with one of these {@code npa:trustStatus} values
62
     * are mirrored into the space-state graph. Per
63
     * {@code doc/design-trust-state-repos.md}, these are the two "authority-
64
     * approving" statuses; {@code npa:contested}, {@code npa:skipped}, and the
65
     * transient statuses are distinct values of the same predicate and are
66
     * excluded automatically by this positive-list filter.
67
     */
68
    private static final Set<IRI> APPROVED_SET = Set.of(NPA_LOADED, NPA_TO_LOAD);
15✔
69

70
    private static AuthorityResolver instance;
71

72
    /** Returns the singleton. */
73
    public static synchronized AuthorityResolver get() {
74
        if (instance == null) {
6✔
75
            instance = new AuthorityResolver();
12✔
76
        }
77
        return instance;
6✔
78
    }
79

80
    private AuthorityResolver() {
81
    }
82

83
    // ---------------- Public entry points ----------------
84

85
    /**
86
     * Poll entry point: checks the current trust-state hash against the active
87
     * space-state graph's hash component; if they differ (or no space-state graph
88
     * exists yet), runs a full build. Safe to call repeatedly on a schedule —
89
     * when the hashes match, it's a no-op. Gated by
90
     * {@link FeatureFlags#spacesEnabled()}.
91
     */
92
    public void tick() {
93
        if (!FeatureFlags.spacesEnabled()) return;
6!
94
        String trustStateHash = TrustStateRegistry.get().getCurrentHash().orElse(null);
18✔
95
        if (trustStateHash == null) {
6!
96
            log.debug("AuthorityResolver.tick: no current trust state yet — skipping");
9✔
97
            return;
3✔
98
        }
99
        String currentGraphName = getCurrentSpaceStateGraphLocalName();
×
100
        if (currentGraphName != null && currentGraphName.startsWith(trustStateHash + "_")) {
×
101
            log.debug("AuthorityResolver.tick: already on trust state {}", abbrev(trustStateHash));
×
102
            return;
×
103
        }
104
        log.info("AuthorityResolver.tick: trust-state flip detected (now {}); running full build",
×
105
                abbrev(trustStateHash));
×
106
        runFullBuild(trustStateHash);
×
107
    }
×
108

109
    /**
110
     * Startup cleanup: drop any {@code npass:*} graph that the
111
     * {@code npa:hasCurrentSpaceState} pointer isn't pointing at. Orphans come
112
     * from crashes mid-build. Safe to call at any time; idempotent.
113
     */
114
    public void cleanOrphans() {
115
        if (!FeatureFlags.spacesEnabled()) return;
×
116
        IRI current = getCurrentSpaceStateGraph();
×
117
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
118
            int dropped = 0;
×
119
            try (RepositoryResult<org.eclipse.rdf4j.model.Resource> ctxs = conn.getContextIDs()) {
×
120
                List<IRI> toDrop = new ArrayList<>();
×
121
                while (ctxs.hasNext()) {
×
122
                    org.eclipse.rdf4j.model.Resource ctx = ctxs.next();
×
123
                    if (!(ctx instanceof IRI iri)) continue;
×
124
                    if (!iri.stringValue().startsWith(SpacesVocab.NPASS_NAMESPACE)) continue;
×
125
                    if (iri.equals(current)) continue;
×
126
                    toDrop.add(iri);
×
127
                }
×
128
                for (IRI iri : toDrop) {
×
129
                    conn.begin(IsolationLevels.SERIALIZABLE);
×
130
                    conn.clear(iri);
×
131
                    conn.commit();
×
132
                    dropped++;
×
133
                    log.info("AuthorityResolver.cleanOrphans: dropped orphan graph {}", iri);
×
134
                }
×
135
            }
136
            if (dropped == 0) {
×
137
                log.debug("AuthorityResolver.cleanOrphans: no orphan space-state graphs");
×
138
            }
139
        } catch (Exception ex) {
×
140
            log.info("AuthorityResolver.cleanOrphans: failed: {}", ex.toString());
×
141
        }
×
142
    }
×
143

144
    // ---------------- Full build ----------------
145

146
    /**
147
     * Mutex-protected full build of the space-state graph for the given trust
148
     * state. Captures {@code M = currentLoadCounter}, mirrors trust-approved
149
     * rows, (PR 2b: runs per-tier UPDATE loops from scratch), stamps
150
     * {@code processedUpTo = M}, flips the pointer, drops the previous graph.
151
     */
152
    synchronized void runFullBuild(String trustStateHash) {
153
        long loadCounter = getCurrentLoadCounter();
×
154
        IRI newGraph = SpacesVocab.forSpaceState(trustStateHash, loadCounter);
×
155
        IRI oldGraph = getCurrentSpaceStateGraph();
×
156
        if (newGraph.equals(oldGraph)) {
×
157
            log.debug("AuthorityResolver.runFullBuild: already current at {}", newGraph);
×
158
            return;
×
159
        }
160

161
        // 1. Mirror trust-approved rows into the new graph.
162
        int mirrored = mirrorTrustState(trustStateHash, newGraph);
×
163

164
        // 2. Per-tier UPDATE loops (from scratch: lastProcessed = -1 so the
165
        //    delta filter FILTER(?ln > ?lastProcessed) includes everything).
166
        TierCounts counts = runAllTierLoops(newGraph, -1);
×
167

168
        // 3. Stamp processedUpTo inside the new graph.
169
        writeProcessedUpTo(newGraph, loadCounter);
×
170

171
        // 4. Flip the current-space-state pointer.
172
        flipPointer(newGraph);
×
173

174
        // 5. Drop the old graph if one existed.
175
        if (oldGraph != null) {
×
176
            dropGraph(oldGraph);
×
177
        }
178

179
        log.info("AuthorityResolver: full build complete — graph={} mirrored={} rows loadCounter={} "
×
180
                        + "tiers: admin={} attachment={} maintainer={} member={} observer={}",
181
                newGraph, mirrored, loadCounter,
×
182
                counts.admin, counts.attachment, counts.maintainer, counts.member, counts.observer);
×
183
    }
×
184

185
    // ---------------- Tier UPDATE loops ----------------
186

187
    /** Per-tier INSERT counts (for logging/metrics). */
188
    static final class TierCounts {
×
189
        int admin;
190
        int attachment;
191
        int maintainer;
192
        int member;
193
        int observer;
194
    }
195

196
    /**
197
     * Runs the five tier loops in order: admin → {@code gen:hasRole} attachment
198
     * validation → maintainer → member → observer. Each loop iterates a SPARQL
199
     * INSERT to fixed point (no new triples added). Returns per-tier counts.
200
     *
201
     * @param graph         target space-state graph
202
     * @param lastProcessed load-number horizon; use {@code -1} for full build
203
     */
204
    TierCounts runAllTierLoops(IRI graph, long lastProcessed) {
205
        TierCounts c = new TierCounts();
×
206
        c.admin = runTierLabeled("admin", graph, adminTierUpdate(graph, lastProcessed));
×
207
        c.attachment = runTierLabeled("attachment", graph,
×
208
                attachmentValidationUpdate(graph, lastProcessed));
×
209
        c.maintainer = runTierLabeled("maintainer", graph, nonAdminTierUpdate(graph, lastProcessed,
×
210
                GEN.MAINTAINER_ROLE, PUBLISHER_IS_ADMIN));
211
        c.member = runTierLabeled("member", graph, nonAdminTierUpdate(graph, lastProcessed,
×
212
                GEN.MEMBER_ROLE, PUBLISHER_IS_ADMIN_OR_MAINTAINER));
213
        c.observer = runTierLabeled("observer", graph, nonAdminTierUpdate(graph, lastProcessed,
×
214
                GEN.OBSERVER_ROLE, PUBLISHER_IS_SELF_OR_TIERED));
215
        return c;
×
216
    }
217

218
    /** Wraps {@link #runTierLoop} with tier-name context for logs/exceptions. */
219
    private int runTierLabeled(String tier, IRI graph, String sparqlUpdate) {
220
        try {
221
            return runTierLoop(graph, sparqlUpdate);
×
222
        } catch (RuntimeException ex) {
×
223
            log.error("AuthorityResolver: tier={} failed with SPARQL UPDATE:\n{}\n", tier, sparqlUpdate, ex);
×
224
            throw ex;
×
225
        }
226
    }
227

228
    /**
229
     * Runs a single tier's INSERT to fixed point. Counts rows by probing
230
     * graph size before/after each INSERT; stops when the size doesn't change.
231
     *
232
     * @return total number of triples inserted by this tier across all iterations
233
     */
234
    int runTierLoop(IRI graph, String sparqlUpdate) {
235
        int total = 0;
×
236
        long before = graphSize(graph);
×
237
        while (true) {
238
            // Note: no explicit transaction wrapping here. In tests we observed that
239
            // HTTPRepository's RDF4J-transaction protocol silently no-op'd cross-graph
240
            // SPARQL UPDATEs with UNION sub-patterns inside conn.begin()/commit(),
241
            // while the same UPDATE POSTed directly to /statements applied correctly.
242
            // A bare prepareUpdate().execute() takes the direct /statements path and
243
            // runs the UPDATE atomically per SPARQL 1.1 semantics — which is all we
244
            // need; there's nothing else to commit atomically alongside the UPDATE.
245
            try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
246
                conn.prepareUpdate(QueryLanguage.SPARQL, sparqlUpdate).execute();
×
247
            }
248
            long after = graphSize(graph);
×
249
            long added = after - before;
×
250
            if (added <= 0) break;
×
251
            total += added;
×
252
            before = after;
×
253
        }
×
254
        return total;
×
255
    }
256

257
    private long graphSize(IRI graph) {
258
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
259
            return conn.size(graph);
×
260
        }
261
    }
262

263
    // ---------------- SPARQL templates ----------------
264

265
    /**
266
     * Reusable invalidation filter on a bound nanopub-IRI variable. Pass the bare
267
     * variable name (no leading {@code ?}); e.g. {@code invalidationFilter("np")}
268
     * produces {@code FILTER NOT EXISTS { ?_inv_np a npa:Invalidation ; npa:invalidates ?np . }}.
269
     * Variable names must match {@code [A-Za-z0-9_]+} per SPARQL grammar — embedding
270
     * a {@code ?} inside {@code ?_inv_?np} would yield a parse error.
271
     */
272
    private static String invalidationFilter(String bareVarName) {
273
        return "FILTER NOT EXISTS { ?_inv_" + bareVarName
24✔
274
                + " a <" + SpacesVocab.INVALIDATION + "> ; "
275
                + "<" + SpacesVocab.INVALIDATES + "> ?" + bareVarName + " . }";
276
    }
277

278
    /**
279
     * Admin tier: seed from {@code npadef:...hasRootAdmin} (trusted by construction)
280
     * plus closed-over admin grants; insert any {@code gen:RoleInstantiation} with
281
     * {@code npa:regularProperty gen:hasAdmin} whose publisher (resolved via mirrored
282
     * trust-approved AccountState) is already in the admin set.
283
     */
284
    static String adminTierUpdate(IRI graph, long lastProcessed) {
285
        // npa:hasLoadNumber lives in the admin graph (NPA.GRAPH), NOT in
286
        // npa:spacesGraph — NanopubLoader writes the stamp there. Every tier
287
        // template below joins the delta filter via a separate GRAPH <npa:graph>
288
        // block. Invalidation entries DO live in npa:spacesGraph.
289
        return """
69✔
290
                PREFIX npa:  <%1$s>
291
                PREFIX gen:  <%2$s>
292
                INSERT { GRAPH <%3$s> {
293
                  ?ri a gen:RoleInstantiation ;
294
                      npa:forSpace ?space ;
295
                      npa:regularProperty gen:hasAdmin ;
296
                      npa:forAgent ?agent ;
297
                      npa:viaNanopub ?np .
298
                } }
299
                WHERE {
300
                  GRAPH <%4$s> {
301
                    ?ri a gen:RoleInstantiation ;
302
                        npa:forSpace        ?space ;
303
                        npa:regularProperty gen:hasAdmin ;
304
                        npa:forAgent        ?agent ;
305
                        npa:pubkeyHash      ?pkh ;
306
                        npa:viaNanopub      ?np .
307
                    %6$s
308
                  }
309
                  GRAPH <%8$s> {
310
                    ?np npa:hasLoadNumber ?ln .
311
                    FILTER (?ln > %5$d)
312
                  }
313
                  {
314
                    # Seed branch: root-admin in a non-invalidated SpaceDefinition.
315
                    GRAPH <%4$s> {
316
                      ?def a npa:SpaceDefinition ;
317
                           npa:forSpaceRef ?spaceRef ;
318
                           npa:hasRootAdmin ?publisher ;
319
                           npa:viaNanopub   ?defNp .
320
                      ?spaceRef npa:spaceIri ?space .
321
                      %7$s
322
                    }
323
                  }
324
                  UNION
325
                  {
326
                    # Closed-over branch: an existing admin in this space-state graph.
327
                    GRAPH <%3$s> {
328
                      ?prev a gen:RoleInstantiation ;
329
                            npa:forSpace ?space ;
330
                            npa:regularProperty gen:hasAdmin ;
331
                            npa:forAgent ?publisher .
332
                    }
333
                  }
334
                  GRAPH <%3$s> {
335
                    ?acct a npa:AccountState ;
336
                          npa:agent  ?publisher ;
337
                          npa:pubkey ?pkh .
338
                  }
339
                  FILTER NOT EXISTS { GRAPH <%3$s> {
340
                    ?existing a gen:RoleInstantiation ;
341
                              npa:forSpace ?space ;
342
                              npa:forAgent ?agent ;
343
                              npa:regularProperty gen:hasAdmin .
344
                  } }
345
                }
346
                """.formatted(
3✔
347
                NPA.NAMESPACE,
348
                GEN.NAMESPACE,
349
                graph,
350
                SpacesVocab.SPACES_GRAPH,
351
                lastProcessed,
15✔
352
                invalidationFilter("np"),
15✔
353
                invalidationFilter("defNp"),
18✔
354
                NPA.GRAPH);
355
    }
356

357
    /**
358
     * {@code gen:hasRole} attachment validation: an attachment is validated iff its
359
     * publisher is already a validated admin of the target space. Adds
360
     * {@code gen:RoleAssignment} rows to the space-state graph.
361
     */
362
    static String attachmentValidationUpdate(IRI graph, long lastProcessed) {
363
        return """
69✔
364
                PREFIX npa:  <%1$s>
365
                PREFIX gen:  <%2$s>
366
                INSERT { GRAPH <%3$s> {
367
                  ?ra a gen:RoleAssignment ;
368
                      npa:forSpace ?space ;
369
                      gen:hasRole  ?role ;
370
                      npa:viaNanopub ?np .
371
                } }
372
                WHERE {
373
                  GRAPH <%4$s> {
374
                    ?ra a gen:RoleAssignment ;
375
                        npa:forSpace ?space ;
376
                        gen:hasRole  ?role ;
377
                        npa:pubkeyHash ?pkh ;
378
                        npa:viaNanopub ?np .
379
                    %6$s
380
                  }
381
                  GRAPH <%7$s> {
382
                    ?np npa:hasLoadNumber ?ln .
383
                    FILTER (?ln > %5$d)
384
                  }
385
                  GRAPH <%3$s> {
386
                    ?acct a npa:AccountState ;
387
                          npa:agent  ?publisher ;
388
                          npa:pubkey ?pkh .
389
                    ?adminRI a gen:RoleInstantiation ;
390
                             npa:forSpace ?space ;
391
                             npa:regularProperty gen:hasAdmin ;
392
                             npa:forAgent ?publisher .
393
                  }
394
                  FILTER NOT EXISTS { GRAPH <%3$s> {
395
                    ?existing a gen:RoleAssignment ;
396
                              npa:forSpace ?space ;
397
                              gen:hasRole  ?role .
398
                  } }
399
                }
400
                """.formatted(
3✔
401
                NPA.NAMESPACE,
402
                GEN.NAMESPACE,
403
                graph,
404
                SpacesVocab.SPACES_GRAPH,
405
                lastProcessed,
15✔
406
                invalidationFilter("np"),
18✔
407
                NPA.GRAPH);
408
    }
409

410
    /** Non-admin tier publisher constraints (inserted as a SPARQL sub-pattern). */
411
    static final String PUBLISHER_IS_ADMIN = """
412
            ?adminRI a gen:RoleInstantiation ;
413
                     npa:forSpace ?space ;
414
                     npa:regularProperty gen:hasAdmin ;
415
                     npa:forAgent ?publisher .
416
            """;
417

418
    static final String PUBLISHER_IS_ADMIN_OR_MAINTAINER = """
419
            {
420
              ?adminRI a gen:RoleInstantiation ;
421
                       npa:forSpace ?space ;
422
                       npa:regularProperty gen:hasAdmin ;
423
                       npa:forAgent ?publisher .
424
            }
425
            UNION
426
            {
427
              ?maintRI a gen:RoleInstantiation ;
428
                       npa:forSpace ?space ;
429
                       npa:forAgent ?publisher .
430
              ?rdM a npa:RoleDeclaration ;
431
                   npa:hasRoleType gen:MaintainerRole .
432
              { ?maintRI npa:regularProperty ?predM . ?rdM gen:hasRegularProperty ?predM . }
433
              UNION
434
              { ?maintRI npa:inverseProperty ?predM . ?rdM gen:hasInverseProperty ?predM . }
435
            }
436
            """;
437

438
    /**
439
     * Observer self-evidence: publisher is admin, maintainer, member, OR the
440
     * mirrored trust row confirms that the signing pubkey maps to the assignee
441
     * itself (i.e. the assignee is the publisher).
442
     */
443
    static final String PUBLISHER_IS_SELF_OR_TIERED = """
444
            {
445
              ?adminRI a gen:RoleInstantiation ;
446
                       npa:forSpace ?space ;
447
                       npa:regularProperty gen:hasAdmin ;
448
                       npa:forAgent ?publisher .
449
            }
450
            UNION
451
            {
452
              ?maintRI a gen:RoleInstantiation ;
453
                       npa:forSpace ?space ;
454
                       npa:forAgent ?publisher .
455
              ?rdM a npa:RoleDeclaration ;
456
                   npa:hasRoleType gen:MaintainerRole .
457
              { ?maintRI npa:regularProperty ?predM . ?rdM gen:hasRegularProperty ?predM . }
458
              UNION
459
              { ?maintRI npa:inverseProperty ?predM . ?rdM gen:hasInverseProperty ?predM . }
460
            }
461
            UNION
462
            {
463
              ?memRI a gen:RoleInstantiation ;
464
                     npa:forSpace ?space ;
465
                     npa:forAgent ?publisher .
466
              ?rdMem a npa:RoleDeclaration ;
467
                     npa:hasRoleType gen:MemberRole .
468
              { ?memRI npa:regularProperty ?predMem . ?rdMem gen:hasRegularProperty ?predMem . }
469
              UNION
470
              { ?memRI npa:inverseProperty ?predMem . ?rdMem gen:hasInverseProperty ?predMem . }
471
            }
472
            UNION
473
            {
474
              # Self-evidence: publisher pubkey maps to the assignee.
475
              FILTER (?publisher = ?agent)
476
            }
477
            """;
478

479
    /**
480
     * Maintainer / Member / Observer tier INSERT. Same shape: find an instantiation
481
     * whose predicate matches a RoleDeclaration of the given tier attached to the
482
     * target space, and whose publisher passes the tier-specific constraint.
483
     */
484
    static String nonAdminTierUpdate(IRI graph, long lastProcessed,
485
                                     IRI tierClass, String publisherConstraint) {
486
        return """
69✔
487
                PREFIX npa:  <%1$s>
488
                PREFIX gen:  <%2$s>
489
                INSERT { GRAPH <%3$s> {
490
                  ?ri a gen:RoleInstantiation ;
491
                      npa:forSpace ?space ;
492
                      npa:forAgent ?agent ;
493
                      npa:viaNanopub ?np .
494
                } }
495
                WHERE {
496
                  GRAPH <%4$s> {
497
                    ?ri a gen:RoleInstantiation ;
498
                        npa:forSpace ?space ;
499
                        npa:forAgent ?agent ;
500
                        npa:pubkeyHash ?pkh ;
501
                        npa:viaNanopub ?np .
502
                    { ?ri npa:regularProperty ?pred . }
503
                    UNION
504
                    { ?ri npa:inverseProperty ?pred . }
505
                    %6$s
506
                    # Predicate maps to a RoleDeclaration of this tier (not invalidated).
507
                    ?rd a npa:RoleDeclaration ;
508
                        npa:role ?role ;
509
                        npa:hasRoleType <%7$s> ;
510
                        npa:viaNanopub ?rdNp .
511
                    { ?rd gen:hasRegularProperty ?pred . }
512
                    UNION
513
                    { ?rd gen:hasInverseProperty ?pred . }
514
                    %8$s
515
                  }
516
                  GRAPH <%10$s> {
517
                    ?np npa:hasLoadNumber ?ln .
518
                    FILTER (?ln > %5$d)
519
                  }
520
                  GRAPH <%3$s> {
521
                    # Role must be admin-attached to the target space.
522
                    ?ra a gen:RoleAssignment ;
523
                        npa:forSpace ?space ;
524
                        gen:hasRole  ?role .
525
                    # Publisher's agent from the mirrored trust-approved set.
526
                    ?acct a npa:AccountState ;
527
                          npa:agent ?publisher ;
528
                          npa:pubkey ?pkh .
529
                    %9$s
530
                  }
531
                  FILTER NOT EXISTS { GRAPH <%3$s> {
532
                    ?existing a gen:RoleInstantiation ;
533
                              npa:forSpace ?space ;
534
                              npa:forAgent ?agent ;
535
                              npa:viaNanopub ?np .
536
                  } }
537
                }
538
                """.formatted(
3✔
539
                NPA.NAMESPACE,
540
                GEN.NAMESPACE,
541
                graph,
542
                SpacesVocab.SPACES_GRAPH,
543
                lastProcessed,
15✔
544
                invalidationFilter("np"),
27✔
545
                tierClass,
546
                invalidationFilter("rdNp"),
30✔
547
                publisherConstraint,
548
                NPA.GRAPH);
549
    }
550

551
    /**
552
     * Copies trust-approved {@code npa:AccountState} rows from {@code npat:<T>}
553
     * in the {@code trust} repo into {@code newGraph} in the {@code spaces} repo,
554
     * inside one spaces-side serializable transaction.
555
     *
556
     * @return number of rows mirrored (useful for metrics / logging)
557
     */
558
    int mirrorTrustState(String trustStateHash, IRI newGraph) {
559
        IRI trustStateIri = NPAT.forHash(trustStateHash);
×
560
        int count = 0;
×
561
        try (RepositoryConnection trustConn = TripleStore.get().getRepoConnection(TRUST_REPO);
×
562
             RepositoryConnection spacesConn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
563
            trustConn.begin(IsolationLevels.READ_COMMITTED);
×
564
            spacesConn.begin(IsolationLevels.SERIALIZABLE);
×
565
            // Walk rdf:type triples in the trust state's graph; for each AccountState,
566
            // check status and copy the approved ones verbatim (minus status-specific
567
            // detail triples, which we don't need for validation).
568
            try (RepositoryResult<Statement> typeRows = trustConn.getStatements(
×
569
                    null, RDF.TYPE, NPA_ACCOUNT_STATE, trustStateIri)) {
570
                while (typeRows.hasNext()) {
×
571
                    Statement st = typeRows.next();
×
572
                    if (!(st.getSubject() instanceof IRI accountStateIri)) continue;
×
573
                    Value status = trustConn.getStatements(accountStateIri, NPA_TRUST_STATUS, null, trustStateIri)
×
574
                            .stream().findFirst().map(Statement::getObject).orElse(null);
×
575
                    if (!(status instanceof IRI statusIri) || !APPROVED_SET.contains(statusIri)) continue;
×
576
                    Value agent = trustConn.getStatements(accountStateIri, NPA_AGENT, null, trustStateIri)
×
577
                            .stream().findFirst().map(Statement::getObject).orElse(null);
×
578
                    Value pubkey = trustConn.getStatements(accountStateIri, NPA_PUBKEY, null, trustStateIri)
×
579
                            .stream().findFirst().map(Statement::getObject).orElse(null);
×
580
                    if (agent == null || pubkey == null) {
×
581
                        log.warn("AuthorityResolver.mirror: account {} missing agent or pubkey; skipping",
×
582
                                accountStateIri);
583
                        continue;
×
584
                    }
585
                    spacesConn.add(accountStateIri, RDF.TYPE, NPA_ACCOUNT_STATE, newGraph);
×
586
                    spacesConn.add(accountStateIri, NPA_AGENT, agent, newGraph);
×
587
                    spacesConn.add(accountStateIri, NPA_PUBKEY, pubkey, newGraph);
×
588
                    spacesConn.add(accountStateIri, NPA_TRUST_STATUS, statusIri, newGraph);
×
589
                    count++;
×
590
                }
×
591
            }
592
            spacesConn.commit();
×
593
            trustConn.commit();
×
594
        }
595
        return count;
×
596
    }
597

598
    // ---------------- Pointer + counter helpers ----------------
599

600
    /**
601
     * Reads the current {@code npa:hasCurrentSpaceState} pointer from the
602
     * {@code npa:graph} admin graph of the {@code spaces} repo. Returns
603
     * {@code null} if no pointer exists yet.
604
     */
605
    IRI getCurrentSpaceStateGraph() {
606
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
607
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
608
                    SpacesVocab.HAS_CURRENT_SPACE_STATE);
609
            return (v instanceof IRI iri) ? iri : null;
×
610
        } catch (Exception ex) {
×
611
            log.warn("AuthorityResolver: failed to read hasCurrentSpaceState pointer: {}", ex.toString());
×
612
            return null;
×
613
        }
614
    }
615

616
    /** Convenience: local-name of the current space-state graph IRI. */
617
    private String getCurrentSpaceStateGraphLocalName() {
618
        IRI iri = getCurrentSpaceStateGraph();
×
619
        if (iri == null) return null;
×
620
        String s = iri.stringValue();
×
621
        if (!s.startsWith(SpacesVocab.NPASS_NAMESPACE)) return null;
×
622
        return s.substring(SpacesVocab.NPASS_NAMESPACE.length());
×
623
    }
624

625
    long getCurrentLoadCounter() {
626
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
627
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
628
                    SpacesVocab.CURRENT_LOAD_COUNTER);
629
            if (v == null) return 0;
×
630
            try {
631
                return Long.parseLong(v.stringValue());
×
632
            } catch (NumberFormatException ex) {
×
633
                log.warn("AuthorityResolver: non-numeric currentLoadCounter: {}", v);
×
634
                return 0;
×
635
            }
636
        } catch (Exception ex) {
×
637
            log.warn("AuthorityResolver: failed to read currentLoadCounter: {}", ex.toString());
×
638
            return 0;
×
639
        }
640
    }
641

642
    /**
643
     * Atomic pointer flip: a single SPARQL {@code DELETE … INSERT … WHERE}
644
     * replaces the old pointer with the new one in one statement, so readers
645
     * never see a zero-pointer window.
646
     */
647
    void flipPointer(IRI newGraph) {
648
        String update = String.format("""
×
649
                DELETE { GRAPH <%s> { <%s> <%s> ?old } }
650
                INSERT { GRAPH <%s> { <%s> <%s> <%s> } }
651
                WHERE  { OPTIONAL { GRAPH <%s> { <%s> <%s> ?old } } }
652
                """,
653
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.HAS_CURRENT_SPACE_STATE,
654
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.HAS_CURRENT_SPACE_STATE, newGraph,
655
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.HAS_CURRENT_SPACE_STATE);
656
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
657
            conn.begin(IsolationLevels.SERIALIZABLE);
×
658
            conn.prepareUpdate(QueryLanguage.SPARQL, update).execute();
×
659
            conn.commit();
×
660
        }
661
    }
×
662

663
    void writeProcessedUpTo(IRI graph, long loadCounter) {
664
        String update = String.format("""
×
665
                DELETE { GRAPH <%s> { <%s> <%s> ?old } }
666
                INSERT { GRAPH <%s> { <%s> <%s> "%d"^^<http://www.w3.org/2001/XMLSchema#long> } }
667
                WHERE  { OPTIONAL { GRAPH <%s> { <%s> <%s> ?old } } }
668
                """,
669
                graph, graph, SpacesVocab.PROCESSED_UP_TO,
670
                graph, graph, SpacesVocab.PROCESSED_UP_TO, loadCounter,
×
671
                graph, graph, SpacesVocab.PROCESSED_UP_TO);
672
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
673
            conn.begin(IsolationLevels.SERIALIZABLE);
×
674
            conn.prepareUpdate(QueryLanguage.SPARQL, update).execute();
×
675
            conn.commit();
×
676
        }
677
    }
×
678

679
    /**
680
     * Reads {@code processedUpTo} from the given space-state graph.
681
     * Returns {@code -1} if absent (graph not fully built yet).
682
     */
683
    long readProcessedUpTo(IRI graph) {
684
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
685
            String query = String.format(
×
686
                    "SELECT ?n WHERE { GRAPH <%s> { <%s> <%s> ?n } }",
687
                    graph, graph, SpacesVocab.PROCESSED_UP_TO);
688
            try (TupleQueryResult r = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) {
×
689
                if (!r.hasNext()) return -1;
×
690
                BindingSet b = r.next();
×
691
                return Long.parseLong(b.getBinding("n").getValue().stringValue());
×
692
            }
×
693
        } catch (Exception ex) {
×
694
            log.warn("AuthorityResolver: failed to read processedUpTo for {}: {}", graph, ex.toString());
×
695
            return -1;
×
696
        }
697
    }
698

699
    void dropGraph(IRI graph) {
700
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
701
            conn.begin(IsolationLevels.SERIALIZABLE);
×
702
            conn.clear(graph);
×
703
            conn.commit();
×
704
            log.info("AuthorityResolver: dropped old space-state graph {}", graph);
×
705
        }
706
    }
×
707

708
    // ---------------- Trust-repo pointer lookup (used by TrustStateRegistry's bootstrap) ----------------
709

710
    /**
711
     * Queries the {@code trust} repo directly for the current trust-state hash.
712
     * Prefer {@link TrustStateRegistry#getCurrentHash()} in normal operation —
713
     * this helper exists for tests and diagnostics.
714
     *
715
     * @return the current trust-state hash, or empty if none is set
716
     */
717
    Optional<String> readTrustRepoCurrentHash() {
718
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(TRUST_REPO)) {
×
719
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
720
                    NPA_HAS_CURRENT_TRUST_STATE);
721
            if (!(v instanceof IRI iri)) return Optional.empty();
×
722
            String s = iri.stringValue();
×
723
            if (!s.startsWith(NPAT.NAMESPACE)) return Optional.empty();
×
724
            return Optional.of(s.substring(NPAT.NAMESPACE.length()));
×
725
        } catch (Exception ex) {
×
726
            log.warn("AuthorityResolver: failed to read trust-repo current pointer: {}", ex.toString());
×
727
            return Optional.empty();
×
728
        }
729
    }
730

731
    private static String abbrev(String hash) {
732
        return hash.length() > 12 ? hash.substring(0, 12) + "…" : hash;
×
733
    }
734

735
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc