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

knowledgepixels / nanopub-query / 24909650255

24 Apr 2026 08:10PM UTC coverage: 58.974% (-0.5%) from 59.461%
24909650255

Pull #81

github

web-flow
Merge 918ab1868 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 1717 relevant lines covered (61.97%)

9.41 hits per line

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

14.02
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
            try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
239
                conn.begin(IsolationLevels.SERIALIZABLE);
×
240
                conn.prepareUpdate(QueryLanguage.SPARQL, sparqlUpdate).execute();
×
241
                conn.commit();
×
242
            }
243
            long after = graphSize(graph);
×
244
            long added = after - before;
×
245
            if (added <= 0) break;
×
246
            total += added;
×
247
            before = after;
×
248
        }
×
249
        return total;
×
250
    }
251

252
    private long graphSize(IRI graph) {
253
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
254
            return conn.size(graph);
×
255
        }
256
    }
257

258
    // ---------------- SPARQL templates ----------------
259

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

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

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

405
    /** Non-admin tier publisher constraints (inserted as a SPARQL sub-pattern). */
406
    static final String PUBLISHER_IS_ADMIN = """
407
            ?adminRI a gen:RoleInstantiation ;
408
                     npa:forSpace ?space ;
409
                     npa:regularProperty gen:hasAdmin ;
410
                     npa:forAgent ?publisher .
411
            """;
412

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

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

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

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

593
    // ---------------- Pointer + counter helpers ----------------
594

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

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

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

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

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

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

694
    void dropGraph(IRI graph) {
695
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
696
            conn.begin(IsolationLevels.SERIALIZABLE);
×
697
            conn.clear(graph);
×
698
            conn.commit();
×
699
            log.info("AuthorityResolver: dropped old space-state graph {}", graph);
×
700
        }
701
    }
×
702

703
    // ---------------- Trust-repo pointer lookup (used by TrustStateRegistry's bootstrap) ----------------
704

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

726
    private static String abbrev(String hash) {
727
        return hash.length() > 12 ? hash.substring(0, 12) + "…" : hash;
×
728
    }
729

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