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

knowledgepixels / nanopub-query / 24912539472

24 Apr 2026 09:23PM UTC coverage: 58.926% (-0.5%) from 59.461%
24912539472

Pull #81

github

web-flow
Merge e77dd0253 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 1719 relevant lines covered (61.9%)

9.4 hits per line

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

13.92
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
        // Member tier: admin OR maintainer publisher — split into two simpler updates
212
        // so the query planner doesn't struggle with the UNION.
213
        c.member = runTierLabeled("member(admin-pub)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
214
                GEN.MEMBER_ROLE, PUBLISHER_IS_ADMIN));
215
        c.member += runTierLabeled("member(maint-pub)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
216
                GEN.MEMBER_ROLE, publisherIsTieredRole(GEN.MAINTAINER_ROLE)));
×
217
        // Observer tier: self-evidence only per the plan's policy table
218
        // (gen:ObserverRole = self). Authority-publisher sub-tiers were overreach;
219
        // the three of them have been removed, so an observer instantiation is
220
        // validated iff the assignee's own pubkey signed it.
221
        c.observer = runTierLabeled("observer(self)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
222
                GEN.OBSERVER_ROLE, PUBLISHER_IS_SELF));
223
        return c;
×
224
    }
225

226
    /**
227
     * Builds a publisher constraint requiring the publisher to be a validated holder
228
     * of the given tier's role (maintainer or member) in the target space.
229
     */
230
    private static String publisherIsTieredRole(IRI tierClass) {
231
        return """
×
232
                ?tierRI a gen:RoleInstantiation ;
233
                        npa:forSpace ?space ;
234
                        npa:forAgent ?publisher .
235
                ?rdT a npa:RoleDeclaration ;
236
                     npa:hasRoleType <%1$s> .
237
                { ?tierRI npa:regularProperty ?predT . ?rdT gen:hasRegularProperty ?predT . }
238
                UNION
239
                { ?tierRI npa:inverseProperty ?predT . ?rdT gen:hasInverseProperty ?predT . }
240
                """.formatted(tierClass);
×
241
    }
242

243
    /** Wraps {@link #runTierLoop} with tier-name context for logs/exceptions. */
244
    private int runTierLabeled(String tier, IRI graph, String sparqlUpdate) {
245
        try {
246
            return runTierLoop(graph, sparqlUpdate);
×
247
        } catch (RuntimeException ex) {
×
248
            log.error("AuthorityResolver: tier={} failed with SPARQL UPDATE:\n{}\n", tier, sparqlUpdate, ex);
×
249
            throw ex;
×
250
        }
251
    }
252

253
    /**
254
     * Runs a single tier's INSERT to fixed point. Counts rows by probing
255
     * graph size before/after each INSERT; stops when the size doesn't change.
256
     *
257
     * @return total number of triples inserted by this tier across all iterations
258
     */
259
    int runTierLoop(IRI graph, String sparqlUpdate) {
260
        int total = 0;
×
261
        long before = graphSize(graph);
×
262
        while (true) {
263
            // Note: no explicit transaction wrapping here. In tests we observed that
264
            // HTTPRepository's RDF4J-transaction protocol silently no-op'd cross-graph
265
            // SPARQL UPDATEs with UNION sub-patterns inside conn.begin()/commit(),
266
            // while the same UPDATE POSTed directly to /statements applied correctly.
267
            // A bare prepareUpdate().execute() takes the direct /statements path and
268
            // runs the UPDATE atomically per SPARQL 1.1 semantics — which is all we
269
            // need; there's nothing else to commit atomically alongside the UPDATE.
270
            try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
271
                conn.prepareUpdate(QueryLanguage.SPARQL, sparqlUpdate).execute();
×
272
            }
273
            long after = graphSize(graph);
×
274
            long added = after - before;
×
275
            if (added <= 0) break;
×
276
            total += added;
×
277
            before = after;
×
278
        }
×
279
        return total;
×
280
    }
281

282
    private long graphSize(IRI graph) {
283
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
284
            return conn.size(graph);
×
285
        }
286
    }
287

288
    // ---------------- SPARQL templates ----------------
289

290
    /**
291
     * Reusable invalidation filter on a bound nanopub-IRI variable. Pass the bare
292
     * variable name (no leading {@code ?}); e.g. {@code invalidationFilter("np")}
293
     * produces {@code FILTER NOT EXISTS { ?_inv_np a npa:Invalidation ; npa:invalidates ?np . }}.
294
     * Variable names must match {@code [A-Za-z0-9_]+} per SPARQL grammar — embedding
295
     * a {@code ?} inside {@code ?_inv_?np} would yield a parse error.
296
     */
297
    private static String invalidationFilter(String bareVarName) {
298
        return "FILTER NOT EXISTS { ?_inv_" + bareVarName
24✔
299
                + " a <" + SpacesVocab.INVALIDATION + "> ; "
300
                + "<" + SpacesVocab.INVALIDATES + "> ?" + bareVarName + " . }";
301
    }
302

303
    /**
304
     * Admin tier: seed from {@code npadef:...hasRootAdmin} (trusted by construction)
305
     * plus closed-over admin grants; insert any {@code gen:RoleInstantiation} with
306
     * {@code npa:regularProperty gen:hasAdmin} whose publisher (resolved via mirrored
307
     * trust-approved AccountState) is already in the admin set.
308
     */
309
    static String adminTierUpdate(IRI graph, long lastProcessed) {
310
        // npa:hasLoadNumber lives in the admin graph (NPA.GRAPH), NOT in
311
        // npa:spacesGraph — NanopubLoader writes the stamp there. Every tier
312
        // template below joins the delta filter via a separate GRAPH <npa:graph>
313
        // block. Invalidation entries DO live in npa:spacesGraph.
314
        return """
69✔
315
                PREFIX npa:  <%1$s>
316
                PREFIX gen:  <%2$s>
317
                INSERT { GRAPH <%3$s> {
318
                  ?ri a gen:RoleInstantiation ;
319
                      npa:forSpace ?space ;
320
                      npa:regularProperty gen:hasAdmin ;
321
                      npa:forAgent ?agent ;
322
                      npa:viaNanopub ?np .
323
                } }
324
                WHERE {
325
                  GRAPH <%4$s> {
326
                    ?ri a gen:RoleInstantiation ;
327
                        npa:forSpace        ?space ;
328
                        npa:regularProperty gen:hasAdmin ;
329
                        npa:forAgent        ?agent ;
330
                        npa:pubkeyHash      ?pkh ;
331
                        npa:viaNanopub      ?np .
332
                    %6$s
333
                  }
334
                  GRAPH <%8$s> {
335
                    ?np npa:hasLoadNumber ?ln .
336
                    FILTER (?ln > %5$d)
337
                  }
338
                  {
339
                    # Seed branch: root-admin in a non-invalidated SpaceDefinition.
340
                    GRAPH <%4$s> {
341
                      ?def a npa:SpaceDefinition ;
342
                           npa:forSpaceRef ?spaceRef ;
343
                           npa:hasRootAdmin ?publisher ;
344
                           npa:viaNanopub   ?defNp .
345
                      ?spaceRef npa:spaceIri ?space .
346
                      %7$s
347
                    }
348
                  }
349
                  UNION
350
                  {
351
                    # Closed-over branch: an existing admin in this space-state graph.
352
                    GRAPH <%3$s> {
353
                      ?prev a gen:RoleInstantiation ;
354
                            npa:forSpace ?space ;
355
                            npa:regularProperty gen:hasAdmin ;
356
                            npa:forAgent ?publisher .
357
                    }
358
                  }
359
                  GRAPH <%3$s> {
360
                    ?acct a npa:AccountState ;
361
                          npa:agent  ?publisher ;
362
                          npa:pubkey ?pkh .
363
                  }
364
                  FILTER NOT EXISTS { GRAPH <%3$s> {
365
                    ?existing a gen:RoleInstantiation ;
366
                              npa:forSpace ?space ;
367
                              npa:forAgent ?agent ;
368
                              npa:regularProperty gen:hasAdmin .
369
                  } }
370
                }
371
                """.formatted(
3✔
372
                NPA.NAMESPACE,
373
                GEN.NAMESPACE,
374
                graph,
375
                SpacesVocab.SPACES_GRAPH,
376
                lastProcessed,
15✔
377
                invalidationFilter("np"),
15✔
378
                invalidationFilter("defNp"),
18✔
379
                NPA.GRAPH);
380
    }
381

382
    /**
383
     * {@code gen:hasRole} attachment validation: an attachment is validated iff its
384
     * publisher is already a validated admin of the target space. Adds
385
     * {@code gen:RoleAssignment} rows to the space-state graph.
386
     */
387
    static String attachmentValidationUpdate(IRI graph, long lastProcessed) {
388
        return """
69✔
389
                PREFIX npa:  <%1$s>
390
                PREFIX gen:  <%2$s>
391
                INSERT { GRAPH <%3$s> {
392
                  ?ra a gen:RoleAssignment ;
393
                      npa:forSpace ?space ;
394
                      gen:hasRole  ?role ;
395
                      npa:viaNanopub ?np .
396
                } }
397
                WHERE {
398
                  GRAPH <%4$s> {
399
                    ?ra a gen:RoleAssignment ;
400
                        npa:forSpace ?space ;
401
                        gen:hasRole  ?role ;
402
                        npa:pubkeyHash ?pkh ;
403
                        npa:viaNanopub ?np .
404
                    %6$s
405
                  }
406
                  GRAPH <%7$s> {
407
                    ?np npa:hasLoadNumber ?ln .
408
                    FILTER (?ln > %5$d)
409
                  }
410
                  GRAPH <%3$s> {
411
                    ?acct a npa:AccountState ;
412
                          npa:agent  ?publisher ;
413
                          npa:pubkey ?pkh .
414
                    ?adminRI a gen:RoleInstantiation ;
415
                             npa:forSpace ?space ;
416
                             npa:regularProperty gen:hasAdmin ;
417
                             npa:forAgent ?publisher .
418
                  }
419
                  FILTER NOT EXISTS { GRAPH <%3$s> {
420
                    ?existing a gen:RoleAssignment ;
421
                              npa:forSpace ?space ;
422
                              gen:hasRole  ?role .
423
                  } }
424
                }
425
                """.formatted(
3✔
426
                NPA.NAMESPACE,
427
                GEN.NAMESPACE,
428
                graph,
429
                SpacesVocab.SPACES_GRAPH,
430
                lastProcessed,
15✔
431
                invalidationFilter("np"),
18✔
432
                NPA.GRAPH);
433
    }
434

435
    /** Non-admin tier publisher constraints (inserted as a SPARQL sub-pattern). */
436
    static final String PUBLISHER_IS_ADMIN = """
437
            ?adminRI a gen:RoleInstantiation ;
438
                     npa:forSpace ?space ;
439
                     npa:regularProperty gen:hasAdmin ;
440
                     npa:forAgent ?publisher .
441
            """;
442

443
    /** Observer self-evidence: the assignee is the publisher. */
444
    static final String PUBLISHER_IS_SELF = """
445
            FILTER (?publisher = ?agent)
446
            """;
447

448
    /**
449
     * Maintainer / Member / Observer tier INSERT. Same shape: find an instantiation
450
     * whose predicate matches a RoleDeclaration of the given tier attached to the
451
     * target space, and whose publisher passes the tier-specific constraint.
452
     */
453
    static String nonAdminTierUpdate(IRI graph, long lastProcessed,
454
                                     IRI tierClass, String publisherConstraint) {
455
        return """
69✔
456
                PREFIX npa:  <%1$s>
457
                PREFIX gen:  <%2$s>
458
                INSERT { GRAPH <%3$s> {
459
                  ?ri a gen:RoleInstantiation ;
460
                      npa:forSpace ?space ;
461
                      npa:forAgent ?agent ;
462
                      npa:viaNanopub ?np .
463
                } }
464
                WHERE {
465
                  GRAPH <%4$s> {
466
                    ?ri a gen:RoleInstantiation ;
467
                        npa:forSpace ?space ;
468
                        npa:forAgent ?agent ;
469
                        npa:pubkeyHash ?pkh ;
470
                        npa:viaNanopub ?np .
471
                    { ?ri npa:regularProperty ?pred . }
472
                    UNION
473
                    { ?ri npa:inverseProperty ?pred . }
474
                    %6$s
475
                    # Predicate maps to a RoleDeclaration of this tier (not invalidated).
476
                    ?rd a npa:RoleDeclaration ;
477
                        npa:role ?role ;
478
                        npa:hasRoleType <%7$s> ;
479
                        npa:viaNanopub ?rdNp .
480
                    { ?rd gen:hasRegularProperty ?pred . }
481
                    UNION
482
                    { ?rd gen:hasInverseProperty ?pred . }
483
                    %8$s
484
                  }
485
                  GRAPH <%10$s> {
486
                    ?np npa:hasLoadNumber ?ln .
487
                    FILTER (?ln > %5$d)
488
                  }
489
                  GRAPH <%3$s> {
490
                    # Role must be admin-attached to the target space.
491
                    ?ra a gen:RoleAssignment ;
492
                        npa:forSpace ?space ;
493
                        gen:hasRole  ?role .
494
                    # Publisher's agent from the mirrored trust-approved set.
495
                    ?acct a npa:AccountState ;
496
                          npa:agent ?publisher ;
497
                          npa:pubkey ?pkh .
498
                    %9$s
499
                  }
500
                  FILTER NOT EXISTS { GRAPH <%3$s> {
501
                    ?existing a gen:RoleInstantiation ;
502
                              npa:forSpace ?space ;
503
                              npa:forAgent ?agent ;
504
                              npa:viaNanopub ?np .
505
                  } }
506
                }
507
                """.formatted(
3✔
508
                NPA.NAMESPACE,
509
                GEN.NAMESPACE,
510
                graph,
511
                SpacesVocab.SPACES_GRAPH,
512
                lastProcessed,
15✔
513
                invalidationFilter("np"),
27✔
514
                tierClass,
515
                invalidationFilter("rdNp"),
30✔
516
                publisherConstraint,
517
                NPA.GRAPH);
518
    }
519

520
    /**
521
     * Copies trust-approved {@code npa:AccountState} rows from {@code npat:<T>}
522
     * in the {@code trust} repo into {@code newGraph} in the {@code spaces} repo,
523
     * inside one spaces-side serializable transaction.
524
     *
525
     * @return number of rows mirrored (useful for metrics / logging)
526
     */
527
    int mirrorTrustState(String trustStateHash, IRI newGraph) {
528
        IRI trustStateIri = NPAT.forHash(trustStateHash);
×
529
        int count = 0;
×
530
        try (RepositoryConnection trustConn = TripleStore.get().getRepoConnection(TRUST_REPO);
×
531
             RepositoryConnection spacesConn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
532
            trustConn.begin(IsolationLevels.READ_COMMITTED);
×
533
            spacesConn.begin(IsolationLevels.SERIALIZABLE);
×
534
            // Walk rdf:type triples in the trust state's graph; for each AccountState,
535
            // check status and copy the approved ones verbatim (minus status-specific
536
            // detail triples, which we don't need for validation).
537
            try (RepositoryResult<Statement> typeRows = trustConn.getStatements(
×
538
                    null, RDF.TYPE, NPA_ACCOUNT_STATE, trustStateIri)) {
539
                while (typeRows.hasNext()) {
×
540
                    Statement st = typeRows.next();
×
541
                    if (!(st.getSubject() instanceof IRI accountStateIri)) continue;
×
542
                    Value status = trustConn.getStatements(accountStateIri, NPA_TRUST_STATUS, null, trustStateIri)
×
543
                            .stream().findFirst().map(Statement::getObject).orElse(null);
×
544
                    if (!(status instanceof IRI statusIri) || !APPROVED_SET.contains(statusIri)) continue;
×
545
                    Value agent = trustConn.getStatements(accountStateIri, NPA_AGENT, null, trustStateIri)
×
546
                            .stream().findFirst().map(Statement::getObject).orElse(null);
×
547
                    Value pubkey = trustConn.getStatements(accountStateIri, NPA_PUBKEY, null, trustStateIri)
×
548
                            .stream().findFirst().map(Statement::getObject).orElse(null);
×
549
                    if (agent == null || pubkey == null) {
×
550
                        log.warn("AuthorityResolver.mirror: account {} missing agent or pubkey; skipping",
×
551
                                accountStateIri);
552
                        continue;
×
553
                    }
554
                    spacesConn.add(accountStateIri, RDF.TYPE, NPA_ACCOUNT_STATE, newGraph);
×
555
                    spacesConn.add(accountStateIri, NPA_AGENT, agent, newGraph);
×
556
                    spacesConn.add(accountStateIri, NPA_PUBKEY, pubkey, newGraph);
×
557
                    spacesConn.add(accountStateIri, NPA_TRUST_STATUS, statusIri, newGraph);
×
558
                    count++;
×
559
                }
×
560
            }
561
            spacesConn.commit();
×
562
            trustConn.commit();
×
563
        }
564
        return count;
×
565
    }
566

567
    // ---------------- Pointer + counter helpers ----------------
568

569
    /**
570
     * Reads the current {@code npa:hasCurrentSpaceState} pointer from the
571
     * {@code npa:graph} admin graph of the {@code spaces} repo. Returns
572
     * {@code null} if no pointer exists yet.
573
     */
574
    IRI getCurrentSpaceStateGraph() {
575
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
576
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
577
                    SpacesVocab.HAS_CURRENT_SPACE_STATE);
578
            return (v instanceof IRI iri) ? iri : null;
×
579
        } catch (Exception ex) {
×
580
            log.warn("AuthorityResolver: failed to read hasCurrentSpaceState pointer: {}", ex.toString());
×
581
            return null;
×
582
        }
583
    }
584

585
    /** Convenience: local-name of the current space-state graph IRI. */
586
    private String getCurrentSpaceStateGraphLocalName() {
587
        IRI iri = getCurrentSpaceStateGraph();
×
588
        if (iri == null) return null;
×
589
        String s = iri.stringValue();
×
590
        if (!s.startsWith(SpacesVocab.NPASS_NAMESPACE)) return null;
×
591
        return s.substring(SpacesVocab.NPASS_NAMESPACE.length());
×
592
    }
593

594
    long getCurrentLoadCounter() {
595
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
596
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
597
                    SpacesVocab.CURRENT_LOAD_COUNTER);
598
            if (v == null) return 0;
×
599
            try {
600
                return Long.parseLong(v.stringValue());
×
601
            } catch (NumberFormatException ex) {
×
602
                log.warn("AuthorityResolver: non-numeric currentLoadCounter: {}", v);
×
603
                return 0;
×
604
            }
605
        } catch (Exception ex) {
×
606
            log.warn("AuthorityResolver: failed to read currentLoadCounter: {}", ex.toString());
×
607
            return 0;
×
608
        }
609
    }
610

611
    /**
612
     * Atomic pointer flip: a single SPARQL {@code DELETE … INSERT … WHERE}
613
     * replaces the old pointer with the new one in one statement, so readers
614
     * never see a zero-pointer window.
615
     */
616
    void flipPointer(IRI newGraph) {
617
        String update = String.format("""
×
618
                DELETE { GRAPH <%s> { <%s> <%s> ?old } }
619
                INSERT { GRAPH <%s> { <%s> <%s> <%s> } }
620
                WHERE  { OPTIONAL { GRAPH <%s> { <%s> <%s> ?old } } }
621
                """,
622
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.HAS_CURRENT_SPACE_STATE,
623
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.HAS_CURRENT_SPACE_STATE, newGraph,
624
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.HAS_CURRENT_SPACE_STATE);
625
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
626
            conn.begin(IsolationLevels.SERIALIZABLE);
×
627
            conn.prepareUpdate(QueryLanguage.SPARQL, update).execute();
×
628
            conn.commit();
×
629
        }
630
    }
×
631

632
    void writeProcessedUpTo(IRI graph, long loadCounter) {
633
        String update = String.format("""
×
634
                DELETE { GRAPH <%s> { <%s> <%s> ?old } }
635
                INSERT { GRAPH <%s> { <%s> <%s> "%d"^^<http://www.w3.org/2001/XMLSchema#long> } }
636
                WHERE  { OPTIONAL { GRAPH <%s> { <%s> <%s> ?old } } }
637
                """,
638
                graph, graph, SpacesVocab.PROCESSED_UP_TO,
639
                graph, graph, SpacesVocab.PROCESSED_UP_TO, loadCounter,
×
640
                graph, graph, SpacesVocab.PROCESSED_UP_TO);
641
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
642
            conn.begin(IsolationLevels.SERIALIZABLE);
×
643
            conn.prepareUpdate(QueryLanguage.SPARQL, update).execute();
×
644
            conn.commit();
×
645
        }
646
    }
×
647

648
    /**
649
     * Reads {@code processedUpTo} from the given space-state graph.
650
     * Returns {@code -1} if absent (graph not fully built yet).
651
     */
652
    long readProcessedUpTo(IRI graph) {
653
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
654
            String query = String.format(
×
655
                    "SELECT ?n WHERE { GRAPH <%s> { <%s> <%s> ?n } }",
656
                    graph, graph, SpacesVocab.PROCESSED_UP_TO);
657
            try (TupleQueryResult r = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) {
×
658
                if (!r.hasNext()) return -1;
×
659
                BindingSet b = r.next();
×
660
                return Long.parseLong(b.getBinding("n").getValue().stringValue());
×
661
            }
×
662
        } catch (Exception ex) {
×
663
            log.warn("AuthorityResolver: failed to read processedUpTo for {}: {}", graph, ex.toString());
×
664
            return -1;
×
665
        }
666
    }
667

668
    void dropGraph(IRI graph) {
669
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
670
            conn.begin(IsolationLevels.SERIALIZABLE);
×
671
            conn.clear(graph);
×
672
            conn.commit();
×
673
            log.info("AuthorityResolver: dropped old space-state graph {}", graph);
×
674
        }
675
    }
×
676

677
    // ---------------- Trust-repo pointer lookup (used by TrustStateRegistry's bootstrap) ----------------
678

679
    /**
680
     * Queries the {@code trust} repo directly for the current trust-state hash.
681
     * Prefer {@link TrustStateRegistry#getCurrentHash()} in normal operation —
682
     * this helper exists for tests and diagnostics.
683
     *
684
     * @return the current trust-state hash, or empty if none is set
685
     */
686
    Optional<String> readTrustRepoCurrentHash() {
687
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(TRUST_REPO)) {
×
688
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
689
                    NPA_HAS_CURRENT_TRUST_STATE);
690
            if (!(v instanceof IRI iri)) return Optional.empty();
×
691
            String s = iri.stringValue();
×
692
            if (!s.startsWith(NPAT.NAMESPACE)) return Optional.empty();
×
693
            return Optional.of(s.substring(NPAT.NAMESPACE.length()));
×
694
        } catch (Exception ex) {
×
695
            log.warn("AuthorityResolver: failed to read trust-repo current pointer: {}", ex.toString());
×
696
            return Optional.empty();
×
697
        }
698
    }
699

700
    private static String abbrev(String hash) {
701
        return hash.length() > 12 ? hash.substring(0, 12) + "…" : hash;
×
702
    }
703

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