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

knowledgepixels / nanopub-query / 24924351623

25 Apr 2026 06:10AM UTC coverage: 58.926% (-0.5%) from 59.461%
24924351623

Pull #81

github

web-flow
Merge 5eac546be 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
        // Order tuned for RDF4J's evaluator:
311
        //   1. Anchor on the small (seed UNION closed-over) set to bind ?publisher
312
        //      and ?space cheaply.
313
        //   2. Resolve ?pkh from the mirrored AccountState row (?publisher bound).
314
        //   3. Probe instantiations using the now-bound (?space, ?pkh) — targeted
315
        //      lookup, not a full RoleInstantiation scan.
316
        //   4. Load-number filter on bound ?np.
317
        //   5. Dedup at the end.
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
                  # 1. Anchor: who is already an admin of which space?
330
                  {
331
                    # Seed branch: root-admin in a non-invalidated SpaceDefinition.
332
                    GRAPH <%4$s> {
333
                      ?def a npa:SpaceDefinition ;
334
                           npa:forSpaceRef  ?spaceRef ;
335
                           npa:hasRootAdmin ?publisher ;
336
                           npa:viaNanopub   ?defNp .
337
                      ?spaceRef npa:spaceIri ?space .
338
                      %7$s
339
                    }
340
                  }
341
                  UNION
342
                  {
343
                    # Closed-over branch: an existing admin in this space-state graph.
344
                    GRAPH <%3$s> {
345
                      ?prev a gen:RoleInstantiation ;
346
                            npa:forSpace        ?space ;
347
                            npa:regularProperty gen:hasAdmin ;
348
                            npa:forAgent        ?publisher .
349
                    }
350
                  }
351
                  # 2. Mirror: resolve ?publisher → ?pkh via the trust-approved row.
352
                  GRAPH <%3$s> {
353
                    ?acct a npa:AccountState ;
354
                          npa:agent  ?publisher ;
355
                          npa:pubkey ?pkh .
356
                  }
357
                  # 3. Targeted instantiation lookup by space + pubkey.
358
                  GRAPH <%4$s> {
359
                    ?ri a gen:RoleInstantiation ;
360
                        npa:forSpace        ?space ;
361
                        npa:regularProperty gen:hasAdmin ;
362
                        npa:forAgent        ?agent ;
363
                        npa:pubkeyHash      ?pkh ;
364
                        npa:viaNanopub      ?np .
365
                    %6$s
366
                  }
367
                  # 4. Load-number filter on bound ?np.
368
                  GRAPH <%8$s> {
369
                    ?np npa:hasLoadNumber ?ln .
370
                    FILTER (?ln > %5$d)
371
                  }
372
                  # 5. Dedup last.
373
                  FILTER NOT EXISTS { GRAPH <%3$s> {
374
                    ?existing a gen:RoleInstantiation ;
375
                              npa:forSpace ?space ;
376
                              npa:forAgent ?agent ;
377
                              npa:regularProperty gen:hasAdmin .
378
                  } }
379
                }
380
                """.formatted(
3✔
381
                NPA.NAMESPACE,
382
                GEN.NAMESPACE,
383
                graph,
384
                SpacesVocab.SPACES_GRAPH,
385
                lastProcessed,
15✔
386
                invalidationFilter("np"),
15✔
387
                invalidationFilter("defNp"),
18✔
388
                NPA.GRAPH);
389
    }
390

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

444
    /** Non-admin tier publisher constraints (inserted as a SPARQL sub-pattern). */
445
    static final String PUBLISHER_IS_ADMIN = """
446
            ?adminRI a gen:RoleInstantiation ;
447
                     npa:forSpace ?space ;
448
                     npa:regularProperty gen:hasAdmin ;
449
                     npa:forAgent ?publisher .
450
            """;
451

452
    /** Observer self-evidence: the assignee is the publisher. */
453
    static final String PUBLISHER_IS_SELF = """
454
            FILTER (?publisher = ?agent)
455
            """;
456

457
    /**
458
     * Maintainer / Member / Observer tier INSERT. Same shape: find an instantiation
459
     * whose predicate matches a RoleDeclaration of the given tier attached to the
460
     * target space, and whose publisher passes the tier-specific constraint.
461
     */
462
    static String nonAdminTierUpdate(IRI graph, long lastProcessed,
463
                                     IRI tierClass, String publisherConstraint) {
464
        // Order tuned for RDF4J's evaluator (which executes BGPs roughly in order):
465
        //   1. Anchor on the small, tier-pinned RoleDeclaration set (~tens of rows).
466
        //   2. Pair the role-decl direction with the instantiation direction inside
467
        //      one UNION so only valid (regular, regular)/(inverse, inverse) joins
468
        //      are explored — not the 2x2 cross-product of independent UNIONs.
469
        //   3. Match the candidate instantiation by the now-bound predicate.
470
        //   4. Resolve load-number from the admin graph (now-bound subject).
471
        //   5. Attachment + mirrored AccountState + publisher constraint, last.
472
        //   6. Dedup at the end.
473
        return """
69✔
474
                PREFIX npa:  <%1$s>
475
                PREFIX gen:  <%2$s>
476
                INSERT { GRAPH <%3$s> {
477
                  ?ri a gen:RoleInstantiation ;
478
                      npa:forSpace ?space ;
479
                      npa:forAgent ?agent ;
480
                      npa:viaNanopub ?np .
481
                } }
482
                WHERE {
483
                  # 1. Anchor: tier-pinned RoleDeclarations (small, selective).
484
                  GRAPH <%4$s> {
485
                    ?rd a npa:RoleDeclaration ;
486
                        npa:hasRoleType <%7$s> ;
487
                        npa:role        ?role ;
488
                        npa:viaNanopub  ?rdNp .
489
                    %8$s
490
                    # 2. Pair direction so the planner explores only matching combos.
491
                    {
492
                      ?rd gen:hasRegularProperty ?pred .
493
                      ?ri npa:regularProperty    ?pred .
494
                    }
495
                    UNION
496
                    {
497
                      ?rd gen:hasInverseProperty ?pred .
498
                      ?ri npa:inverseProperty    ?pred .
499
                    }
500
                    # 3. Targeted instantiation lookup — ?pred is bound.
501
                    ?ri a gen:RoleInstantiation ;
502
                        npa:forSpace   ?space ;
503
                        npa:forAgent   ?agent ;
504
                        npa:pubkeyHash ?pkh ;
505
                        npa:viaNanopub ?np .
506
                    %6$s
507
                  }
508
                  # 4. Load-number filter on bound ?np.
509
                  GRAPH <%10$s> {
510
                    ?np npa:hasLoadNumber ?ln .
511
                    FILTER (?ln > %5$d)
512
                  }
513
                  # 5. Attachment + AccountState + publisher constraint.
514
                  GRAPH <%3$s> {
515
                    ?ra a gen:RoleAssignment ;
516
                        gen:hasRole  ?role ;
517
                        npa:forSpace ?space .
518
                    ?acct a npa:AccountState ;
519
                          npa:pubkey ?pkh ;
520
                          npa:agent  ?publisher .
521
                    %9$s
522
                  }
523
                  # 6. Dedup last.
524
                  FILTER NOT EXISTS { GRAPH <%3$s> {
525
                    ?existing a gen:RoleInstantiation ;
526
                              npa:forSpace ?space ;
527
                              npa:forAgent ?agent ;
528
                              npa:viaNanopub ?np .
529
                  } }
530
                }
531
                """.formatted(
3✔
532
                NPA.NAMESPACE,
533
                GEN.NAMESPACE,
534
                graph,
535
                SpacesVocab.SPACES_GRAPH,
536
                lastProcessed,
15✔
537
                invalidationFilter("np"),
27✔
538
                tierClass,
539
                invalidationFilter("rdNp"),
30✔
540
                publisherConstraint,
541
                NPA.GRAPH);
542
    }
543

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

591
    // ---------------- Pointer + counter helpers ----------------
592

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

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

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

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

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

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

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

701
    // ---------------- Trust-repo pointer lookup (used by TrustStateRegistry's bootstrap) ----------------
702

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

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

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