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

knowledgepixels / nanopub-query / 24904803690

24 Apr 2026 06:12PM UTC coverage: 59.381% (-0.08%) from 59.461%
24904803690

Pull #81

github

web-flow
Merge d363d4076 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 %.

1074 of 1717 relevant lines covered (62.55%)

9.32 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
        // The seed branch reads SpaceDefinition entries from npa:spacesGraph (that's
281
        // where they live). The closed-over branch reads existing admin instantiations
282
        // from the current space-state graph. Both branches must establish ?publisher
283
        // before joining to the mirrored AccountState row (which resolves ?pkh).
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
                    ?np npa:hasLoadNumber ?ln .
303
                    FILTER (?ln > %5$d)
304
                    %6$s
305
                  }
306
                  {
307
                    # Seed branch: root-admin in a non-invalidated SpaceDefinition.
308
                    GRAPH <%4$s> {
309
                      ?def a npa:SpaceDefinition ;
310
                           npa:forSpaceRef ?spaceRef ;
311
                           npa:hasRootAdmin ?publisher ;
312
                           npa:viaNanopub   ?defNp .
313
                      ?spaceRef npa:spaceIri ?space .
314
                      %7$s
315
                    }
316
                  }
317
                  UNION
318
                  {
319
                    # Closed-over branch: an existing admin in this space-state graph.
320
                    GRAPH <%3$s> {
321
                      ?prev a gen:RoleInstantiation ;
322
                            npa:forSpace ?space ;
323
                            npa:regularProperty gen:hasAdmin ;
324
                            npa:forAgent ?publisher .
325
                    }
326
                  }
327
                  GRAPH <%3$s> {
328
                    ?acct a npa:AccountState ;
329
                          npa:agent  ?publisher ;
330
                          npa:pubkey ?pkh .
331
                  }
332
                  FILTER NOT EXISTS { GRAPH <%3$s> {
333
                    ?existing a gen:RoleInstantiation ;
334
                              npa:forSpace ?space ;
335
                              npa:forAgent ?agent ;
336
                              npa:regularProperty gen:hasAdmin .
337
                  } }
338
                }
339
                """.formatted(
3✔
340
                NPA.NAMESPACE,
341
                GEN.NAMESPACE,
342
                graph,
343
                SpacesVocab.SPACES_GRAPH,
344
                lastProcessed,
15✔
345
                invalidationFilter("np"),
15✔
346
                invalidationFilter("defNp"));
6✔
347
    }
348

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

399
    /** Non-admin tier publisher constraints (inserted as a SPARQL sub-pattern). */
400
    static final String PUBLISHER_IS_ADMIN = """
401
            ?adminRI a gen:RoleInstantiation ;
402
                     npa:forSpace ?space ;
403
                     npa:regularProperty gen:hasAdmin ;
404
                     npa:forAgent ?publisher .
405
            """;
406

407
    static final String PUBLISHER_IS_ADMIN_OR_MAINTAINER = """
408
            {
409
              ?adminRI a gen:RoleInstantiation ;
410
                       npa:forSpace ?space ;
411
                       npa:regularProperty gen:hasAdmin ;
412
                       npa:forAgent ?publisher .
413
            }
414
            UNION
415
            {
416
              ?maintRI a gen:RoleInstantiation ;
417
                       npa:forSpace ?space ;
418
                       npa:forAgent ?publisher .
419
              ?rdM a npa:RoleDeclaration ;
420
                   npa:hasRoleType gen:MaintainerRole .
421
              { ?maintRI npa:regularProperty ?predM . ?rdM gen:hasRegularProperty ?predM . }
422
              UNION
423
              { ?maintRI npa:inverseProperty ?predM . ?rdM gen:hasInverseProperty ?predM . }
424
            }
425
            """;
426

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

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

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

584
    // ---------------- Pointer + counter helpers ----------------
585

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

602
    /** Convenience: local-name of the current space-state graph IRI. */
603
    private String getCurrentSpaceStateGraphLocalName() {
604
        IRI iri = getCurrentSpaceStateGraph();
×
605
        if (iri == null) return null;
×
606
        String s = iri.stringValue();
×
607
        if (!s.startsWith(SpacesVocab.NPASS_NAMESPACE)) return null;
×
608
        return s.substring(SpacesVocab.NPASS_NAMESPACE.length());
×
609
    }
610

611
    long getCurrentLoadCounter() {
612
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
613
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
614
                    SpacesVocab.CURRENT_LOAD_COUNTER);
615
            if (v == null) return 0;
×
616
            try {
617
                return Long.parseLong(v.stringValue());
×
618
            } catch (NumberFormatException ex) {
×
619
                log.warn("AuthorityResolver: non-numeric currentLoadCounter: {}", v);
×
620
                return 0;
×
621
            }
622
        } catch (Exception ex) {
×
623
            log.warn("AuthorityResolver: failed to read currentLoadCounter: {}", ex.toString());
×
624
            return 0;
×
625
        }
626
    }
627

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

649
    void writeProcessedUpTo(IRI graph, long loadCounter) {
650
        String update = String.format("""
×
651
                DELETE { GRAPH <%s> { <%s> <%s> ?old } }
652
                INSERT { GRAPH <%s> { <%s> <%s> "%d"^^<http://www.w3.org/2001/XMLSchema#long> } }
653
                WHERE  { OPTIONAL { GRAPH <%s> { <%s> <%s> ?old } } }
654
                """,
655
                graph, graph, SpacesVocab.PROCESSED_UP_TO,
656
                graph, graph, SpacesVocab.PROCESSED_UP_TO, loadCounter,
×
657
                graph, graph, SpacesVocab.PROCESSED_UP_TO);
658
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
659
            conn.begin(IsolationLevels.SERIALIZABLE);
×
660
            conn.prepareUpdate(QueryLanguage.SPARQL, update).execute();
×
661
            conn.commit();
×
662
        }
663
    }
×
664

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

685
    void dropGraph(IRI graph) {
686
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
687
            conn.begin(IsolationLevels.SERIALIZABLE);
×
688
            conn.clear(graph);
×
689
            conn.commit();
×
690
            log.info("AuthorityResolver: dropped old space-state graph {}", graph);
×
691
        }
692
    }
×
693

694
    // ---------------- Trust-repo pointer lookup (used by TrustStateRegistry's bootstrap) ----------------
695

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

717
    private static String abbrev(String hash) {
718
        return hash.length() > 12 ? hash.substring(0, 12) + "…" : hash;
×
719
    }
720

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