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

knowledgepixels / nanopub-query / 24911158762

24 Apr 2026 08:48PM UTC coverage: 58.807% (-0.7%) from 59.461%
24911158762

Pull #81

github

web-flow
Merge 131c7103a 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 1724 relevant lines covered (61.72%)

9.37 hits per line

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

13.67
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: admin OR maintainer OR member publisher OR self-evidence — four
218
        // simple updates instead of one 4-branch UNION, which HTTP-timed out in practice.
219
        c.observer = runTierLabeled("observer(admin-pub)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
220
                GEN.OBSERVER_ROLE, PUBLISHER_IS_ADMIN));
221
        c.observer += runTierLabeled("observer(maint-pub)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
222
                GEN.OBSERVER_ROLE, publisherIsTieredRole(GEN.MAINTAINER_ROLE)));
×
223
        c.observer += runTierLabeled("observer(member-pub)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
224
                GEN.OBSERVER_ROLE, publisherIsTieredRole(GEN.MEMBER_ROLE)));
×
225
        c.observer += runTierLabeled("observer(self)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
226
                GEN.OBSERVER_ROLE, PUBLISHER_IS_SELF));
227
        return c;
×
228
    }
229

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

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

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

286
    private long graphSize(IRI graph) {
287
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
288
            return conn.size(graph);
×
289
        }
290
    }
291

292
    // ---------------- SPARQL templates ----------------
293

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

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

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

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

447
    /** Observer self-evidence: the assignee is the publisher. */
448
    static final String PUBLISHER_IS_SELF = """
449
            FILTER (?publisher = ?agent)
450
            """;
451

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

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

571
    // ---------------- Pointer + counter helpers ----------------
572

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

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

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

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

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

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

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

681
    // ---------------- Trust-repo pointer lookup (used by TrustStateRegistry's bootstrap) ----------------
682

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

704
    private static String abbrev(String hash) {
705
        return hash.length() > 12 ? hash.substring(0, 12) + "…" : hash;
×
706
    }
707

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