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

knowledgepixels / nanopub-query / 25598398314

09 May 2026 10:04AM UTC coverage: 58.369% (+0.7%) from 57.642%
25598398314

Pull #98

github

web-flow
Merge b82219c1c into 68e6e3645
Pull Request #98: Maintained-resource support (#97)

487 of 912 branches covered (53.4%)

Branch coverage included in aggregate %.

1295 of 2141 relevant lines covered (60.49%)

9.41 hits per line

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

14.99
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.FOAF;
15
import org.eclipse.rdf4j.model.vocabulary.RDF;
16
import org.eclipse.rdf4j.query.BindingSet;
17
import org.eclipse.rdf4j.query.QueryLanguage;
18
import org.eclipse.rdf4j.query.TupleQueryResult;
19
import org.eclipse.rdf4j.repository.RepositoryConnection;
20
import org.eclipse.rdf4j.repository.RepositoryResult;
21
import org.nanopub.vocabulary.NPA;
22
import org.slf4j.Logger;
23
import org.slf4j.LoggerFactory;
24

25
import com.knowledgepixels.query.vocabulary.GEN;
26
import com.knowledgepixels.query.vocabulary.NPAT;
27
import com.knowledgepixels.query.vocabulary.SpacesVocab;
28

29
/**
30
 * Drives the space-state materialization pipeline. Three entry points scheduled
31
 * by {@code MainVerticle}:
32
 * <ul>
33
 *   <li>{@link #tick()} — detects trust-state flips (full build) and otherwise
34
 *       advances the current space-state graph by an {@link #runIncrementalCycle
35
 *       incremental cycle} bounded by {@code (processedUpTo, currentLoadCounter]}.</li>
36
 *   <li>{@link #periodicRebuildTick()} — checks the {@code npa:needsFullRebuild}
37
 *       flag set by structural invalidations and re-runs the full build into a
38
 *       fresh graph, atomically flips the pointer, drops the old graph.</li>
39
 *   <li>{@link #cleanOrphans()} — startup cleanup of {@code npass:*} graphs the
40
 *       pointer isn't referencing.</li>
41
 * </ul>
42
 *
43
 * <p>Incremental cycle order: invalidation DELETEs (admin RI / RoleAssignment /
44
 * non-admin RI) → mirror-step delta is implicit (rebuilt only on full build) →
45
 * per-tier INSERTs (admin → attachment → maintainer → member → observer) →
46
 * late-arrival sweep (re-run downstream tiers without the load-number filter
47
 * iff this cycle added any structural rows). Sets {@code npa:needsFullRebuild}
48
 * when an admin RI / RoleAssignment / RoleDeclaration was invalidated; periodic
49
 * worker turns the flag into a from-scratch rebuild.
50
 *
51
 * <p>See {@code doc/design-space-repositories.md} — this implements the "Full
52
 * build", "Incremental cycle", and "Periodic full rebuild" procedures.
53
 */
54
public final class AuthorityResolver {
55

56
    private static final Logger log = LoggerFactory.getLogger(AuthorityResolver.class);
9✔
57

58
    private static final ValueFactory vf = SimpleValueFactory.getInstance();
6✔
59

60
    private static final String SPACES_REPO = "spaces";
61
    private static final String TRUST_REPO = "trust";
62

63
    /** NPA constants pulled in locally (trust-side). */
64
    private static final IRI NPA_HAS_CURRENT_TRUST_STATE =
9✔
65
            vf.createIRI(NPA.NAMESPACE, "hasCurrentTrustState");
6✔
66
    private static final IRI NPA_ACCOUNT_STATE = vf.createIRI(NPA.NAMESPACE, "AccountState");
15✔
67
    private static final IRI NPA_AGENT = vf.createIRI(NPA.NAMESPACE, "agent");
15✔
68
    private static final IRI NPA_PUBKEY = vf.createIRI(NPA.NAMESPACE, "pubkey");
15✔
69
    private static final IRI NPA_TRUST_STATUS = vf.createIRI(NPA.NAMESPACE, "trustStatus");
15✔
70
    private static final IRI NPA_LOADED = vf.createIRI(NPA.NAMESPACE, "loaded");
15✔
71
    private static final IRI NPA_TO_LOAD = vf.createIRI(NPA.NAMESPACE, "toLoad");
15✔
72

73
    /**
74
     * Trust-approved set: rows with one of these {@code npa:trustStatus} values
75
     * are mirrored into the space-state graph. Per
76
     * {@code doc/design-trust-state-repos.md}, these are the two "authority-
77
     * approving" statuses; {@code npa:contested}, {@code npa:skipped}, and the
78
     * transient statuses are distinct values of the same predicate and are
79
     * excluded automatically by this positive-list filter.
80
     */
81
    private static final Set<IRI> APPROVED_SET = Set.of(NPA_LOADED, NPA_TO_LOAD);
15✔
82

83
    private static AuthorityResolver instance;
84

85
    /** Returns the singleton. */
86
    public static synchronized AuthorityResolver get() {
87
        if (instance == null) {
6✔
88
            instance = new AuthorityResolver();
12✔
89
        }
90
        return instance;
6✔
91
    }
92

93
    private AuthorityResolver() {
6✔
94
    }
3✔
95

96
    // ---------------- Operational metrics snapshot ----------------
97
    //
98
    // Updated at the end of each runFullBuild / runIncrementalCycle, read by
99
    // MetricsCollector via the get*() accessors below. volatile is enough —
100
    // writers serialise via the synchronized methods, and readers (Prometheus
101
    // scrapes) only need most-recent visibility, not transactional consistency
102
    // across the snapshot. Defaults to zero values so a scrape that races a
103
    // boot before the first cycle returns 0, not NaN.
104

105
    private volatile TierSubjectTotals lastSubjectTotals = new TierSubjectTotals(0L, 0L, 0L);
24✔
106
    private volatile long lastInsertedTriplesTotal;
107
    private volatile long lastFullBuildDurationMs;
108
    private volatile long lastIncrementalCycleDurationMs;
109
    private volatile long lastProcessedUpToLag;
110

111
    public TierSubjectTotals getLastSubjectTotals() { return lastSubjectTotals; }
9✔
112
    public long getLastInsertedTriplesTotal() { return lastInsertedTriplesTotal; }
9✔
113
    public long getLastFullBuildDurationMs() { return lastFullBuildDurationMs; }
9✔
114
    public long getLastIncrementalCycleDurationMs() { return lastIncrementalCycleDurationMs; }
9✔
115
    public long getLastProcessedUpToLag() { return lastProcessedUpToLag; }
9✔
116

117
    // ---------------- Public entry points ----------------
118

119
    /**
120
     * Poll entry point. Behaviour:
121
     * <ul>
122
     *   <li>If no current space-state graph or the trust state has flipped → full build.</li>
123
     *   <li>Otherwise → {@link #runIncrementalCycle incremental cycle} on the load-number
124
     *       delta {@code (processedUpTo, currentLoadCounter]}. No-op if {@code
125
     *       processedUpTo == currentLoadCounter}.</li>
126
     * </ul>
127
     * Safe to call repeatedly on a schedule. Gated by {@link FeatureFlags#spacesEnabled()}.
128
     */
129
    public void tick() {
130
        if (!FeatureFlags.spacesEnabled()) return;
6!
131
        String trustStateHash = TrustStateRegistry.get().getCurrentHash().orElse(null);
18✔
132
        if (trustStateHash == null) {
6!
133
            log.debug("AuthorityResolver.tick: no current trust state yet — skipping");
9✔
134
            return;
3✔
135
        }
136
        IRI currentGraph = getCurrentSpaceStateGraph();
×
137
        String currentGraphName = (currentGraph == null) ? null
×
138
                : currentGraph.stringValue().substring(SpacesVocab.NPASS_NAMESPACE.length());
×
139
        if (currentGraphName == null || !currentGraphName.startsWith(trustStateHash + "_")) {
×
140
            log.info("AuthorityResolver.tick: trust-state flip detected (now {}); running full build",
×
141
                    abbrev(trustStateHash));
×
142
            runFullBuild(trustStateHash);
×
143
            return;
×
144
        }
145
        runIncrementalCycle(currentGraph);
×
146
    }
×
147

148
    /**
149
     * Periodic worker. If {@code npa:needsFullRebuild} was raised by an
150
     * incremental cycle's structural DELETE, runs a from-scratch rebuild into
151
     * a fresh space-state graph (using the current trust-state hash and load
152
     * counter) and clears the flag. No-op when the flag is not set. Safe to
153
     * call concurrently with {@link #tick()} when both are scheduled on the
154
     * same single-threaded executor.
155
     */
156
    public void periodicRebuildTick() {
157
        if (!FeatureFlags.spacesEnabled()) return;
×
158
        if (!readNeedsFullRebuild()) return;
×
159
        String trustStateHash = TrustStateRegistry.get().getCurrentHash().orElse(null);
×
160
        if (trustStateHash == null) {
×
161
            log.debug("AuthorityResolver.periodicRebuildTick: no current trust state — deferring");
×
162
            return;
×
163
        }
164
        log.info("AuthorityResolver.periodicRebuildTick: needsFullRebuild flag set; rebuilding");
×
165
        runFullBuild(trustStateHash);
×
166
        clearNeedsFullRebuild();
×
167
    }
×
168

169
    /**
170
     * Startup cleanup: drop any {@code npass:*} graph that the
171
     * {@code npa:hasCurrentSpaceState} pointer isn't pointing at. Orphans come
172
     * from crashes mid-build. Safe to call at any time; idempotent.
173
     */
174
    public void cleanOrphans() {
175
        if (!FeatureFlags.spacesEnabled()) return;
×
176
        IRI current = getCurrentSpaceStateGraph();
×
177
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
178
            int dropped = 0;
×
179
            try (RepositoryResult<org.eclipse.rdf4j.model.Resource> ctxs = conn.getContextIDs()) {
×
180
                List<IRI> toDrop = new ArrayList<>();
×
181
                while (ctxs.hasNext()) {
×
182
                    org.eclipse.rdf4j.model.Resource ctx = ctxs.next();
×
183
                    if (!(ctx instanceof IRI iri)) continue;
×
184
                    if (!iri.stringValue().startsWith(SpacesVocab.NPASS_NAMESPACE)) continue;
×
185
                    if (iri.equals(current)) continue;
×
186
                    toDrop.add(iri);
×
187
                }
×
188
                for (IRI iri : toDrop) {
×
189
                    conn.begin(IsolationLevels.SERIALIZABLE);
×
190
                    conn.clear(iri);
×
191
                    conn.commit();
×
192
                    dropped++;
×
193
                    log.info("AuthorityResolver.cleanOrphans: dropped orphan graph {}", iri);
×
194
                }
×
195
            }
196
            if (dropped == 0) {
×
197
                log.debug("AuthorityResolver.cleanOrphans: no orphan space-state graphs");
×
198
            }
199
        } catch (Exception ex) {
×
200
            log.info("AuthorityResolver.cleanOrphans: failed: {}", ex.toString());
×
201
        }
×
202
    }
×
203

204
    // ---------------- Full build ----------------
205

206
    /**
207
     * Mutex-protected full build of the space-state graph for the given trust
208
     * state. Captures {@code M = currentLoadCounter}, mirrors trust-approved
209
     * rows, (PR 2b: runs per-tier UPDATE loops from scratch), stamps
210
     * {@code processedUpTo = M}, flips the pointer, drops the previous graph.
211
     */
212
    synchronized void runFullBuild(String trustStateHash) {
213
        long startNanos = System.nanoTime();
×
214
        long loadCounter = getCurrentLoadCounter();
×
215
        IRI newGraph = SpacesVocab.forSpaceState(trustStateHash, loadCounter);
×
216
        IRI oldGraph = getCurrentSpaceStateGraph();
×
217
        if (newGraph.equals(oldGraph)) {
×
218
            log.debug("AuthorityResolver.runFullBuild: already current at {}", newGraph);
×
219
            return;
×
220
        }
221

222
        // 1. Mirror trust-approved rows into the new graph.
223
        int mirrored = mirrorTrustState(trustStateHash, newGraph);
×
224

225
        // 2. Per-tier UPDATE loops (from scratch: lastProcessed = -1 so the
226
        //    delta filter FILTER(?ln > ?lastProcessed) includes everything).
227
        TierInsertedTriples counts = runAllTierLoops(newGraph, -1);
×
228

229
        // 3. Stamp processedUpTo inside the new graph.
230
        writeProcessedUpTo(newGraph, loadCounter);
×
231

232
        // 4. Flip the current-space-state pointer.
233
        flipPointer(newGraph);
×
234

235
        // 5. Drop the old graph if one existed.
236
        if (oldGraph != null) {
×
237
            dropGraph(oldGraph);
×
238
        }
239

240
        TierSubjectTotals totals = computeTierSubjectTotals(newGraph);
×
241
        long durationMs = (System.nanoTime() - startNanos) / 1_000_000L;
×
242
        lastSubjectTotals = totals;
×
243
        lastInsertedTriplesTotal = (long) counts.admin + counts.attachment
×
244
                + counts.maintainer + counts.member + counts.observer
245
                + counts.subSpace + counts.subSpacePrefix + counts.maintainedResource;
246
        lastFullBuildDurationMs = durationMs;
×
247
        lastProcessedUpToLag = 0L;
×
248
        log.info("AuthorityResolver: full build complete — graph={} mirrored={} rows loadCounter={} "
×
249
                        + "subjects: adminRIs={} attachmentRAs={} nonAdminRIs={} "
250
                        + "(inserted-triples: admin={} attachment={} maintainer={} member={} observer={} "
251
                        + "subspace={} subspace-prefix={} maintained-resource={}) durationMs={}",
252
                newGraph, mirrored, loadCounter,
×
253
                totals.adminRIs(), totals.attachmentRAs(), totals.nonAdminRIs(),
×
254
                counts.admin, counts.attachment, counts.maintainer, counts.member, counts.observer,
×
255
                counts.subSpace, counts.subSpacePrefix, counts.maintainedResource,
×
256
                durationMs);
×
257
    }
×
258

259
    // ---------------- Incremental cycle ----------------
260

261
    /**
262
     * Single delta cycle on the current space-state graph. Bounded by
263
     * {@code (processedUpTo, currentLoadCounter]}; no-op if the range is empty.
264
     *
265
     * <p>Order:
266
     * <ol>
267
     *   <li>Apply invalidation DELETEs (admin RI, RoleAssignment, non-admin RI)
268
     *       and the RoleDeclaration ASK. Any DELETE on a structural kind sets
269
     *       {@code npa:needsFullRebuild} to bound the staleness from sticky
270
     *       downstream entries; the periodic worker turns that into a from-scratch
271
     *       rebuild on its next pass.</li>
272
     *   <li>Run per-tier INSERTs in the same order as the full build.</li>
273
     *   <li>Late-arrival sweep: if any structural row was added, re-run downstream
274
     *       tier INSERTs with {@code lastProcessed = -1} to catch candidates whose
275
     *       enabling event landed in this same cycle. Dedup filters protect
276
     *       against double-insert.</li>
277
     *   <li>Bump {@code processedUpTo} to {@code currentLoadCounter}.</li>
278
     * </ol>
279
     */
280
    synchronized void runIncrementalCycle(IRI graph) {
281
        long startNanos = System.nanoTime();
×
282
        long currentLoadCounter = getCurrentLoadCounter();
×
283
        long lastProcessed = readProcessedUpTo(graph);
×
284
        if (lastProcessed < 0) {
×
285
            log.warn("AuthorityResolver.runIncrementalCycle: missing processedUpTo on {}; skipping",
×
286
                    graph);
287
            return;
×
288
        }
289
        lastProcessedUpToLag = currentLoadCounter - lastProcessed;
×
290
        if (currentLoadCounter <= lastProcessed) {
×
291
            log.debug("AuthorityResolver.runIncrementalCycle: caught up at load {} on {}",
×
292
                    currentLoadCounter, graph);
×
293
            return;
×
294
        }
295

296
        boolean structuralInvalidation = applyInvalidations(graph, lastProcessed);
×
297
        TierInsertedTriples counts = runAllTierLoops(graph, lastProcessed);
×
298
        boolean structuralAdds = (counts.admin > 0)
×
299
                || (counts.attachment > 0)
300
                || (counts.subSpace > 0)
301
                || newRoleDeclarationsArrived(lastProcessed);
×
302
        if (structuralAdds) {
×
303
            // Late-arrival sweep: leaf tiers (attachment/maintainer/member/observer)
304
            // can promote candidates whose enabling event arrived in this same cycle.
305
            // Sub-space admit is also re-run here for Mode-B late-arrival (a new
306
            // partner declaration can validate an older primary that the regular
307
            // pass's load-number filter excluded). The URL-prefix fallback also
308
            // re-runs so newly-orphaned children pick up derived edges. Skip the
309
            // admin tier — its only enabling event is the admin grant itself,
310
            // already handled by the regular pass.
311
            TierInsertedTriples lateCounts = runDownstreamWithoutLoadFilter(graph);
×
312
            counts.attachment         += lateCounts.attachment;
×
313
            counts.maintainer         += lateCounts.maintainer;
×
314
            counts.member             += lateCounts.member;
×
315
            counts.observer           += lateCounts.observer;
×
316
            counts.subSpace           += lateCounts.subSpace;
×
317
            counts.subSpacePrefix     += lateCounts.subSpacePrefix;
×
318
            counts.maintainedResource += lateCounts.maintainedResource;
×
319
        }
320

321
        writeProcessedUpTo(graph, currentLoadCounter);
×
322

323
        TierSubjectTotals totals = computeTierSubjectTotals(graph);
×
324
        long durationMs = (System.nanoTime() - startNanos) / 1_000_000L;
×
325
        lastSubjectTotals = totals;
×
326
        lastInsertedTriplesTotal = (long) counts.admin + counts.attachment
×
327
                + counts.maintainer + counts.member + counts.observer
328
                + counts.subSpace + counts.subSpacePrefix + counts.maintainedResource;
329
        lastIncrementalCycleDurationMs = durationMs;
×
330
        log.info("AuthorityResolver: incremental cycle complete — graph={} delta=({}, {}] "
×
331
                        + "subjects: adminRIs={} attachmentRAs={} nonAdminRIs={} "
332
                        + "(inserted-triples: admin={} attachment={} maintainer={} member={} observer={} "
333
                        + "subspace={} subspace-prefix={} maintained-resource={}) "
334
                        + "structuralInvalidation={} structuralAdds={} durationMs={}",
335
                graph, lastProcessed, currentLoadCounter,
×
336
                totals.adminRIs(), totals.attachmentRAs(), totals.nonAdminRIs(),
×
337
                counts.admin, counts.attachment, counts.maintainer, counts.member, counts.observer,
×
338
                counts.subSpace, counts.subSpacePrefix, counts.maintainedResource,
×
339
                structuralInvalidation, structuralAdds, durationMs);
×
340
    }
×
341

342
    /**
343
     * Runs the four invalidation-DELETE / ASK steps. Sets {@code npa:needsFullRebuild}
344
     * when admin-RI, RoleAssignment, or RoleDeclaration invalidations matched (the
345
     * three structural kinds). Leaf-tier RI deletes don't set the flag.
346
     *
347
     * @return true iff at least one structural kind was invalidated
348
     */
349
    boolean applyInvalidations(IRI graph, long lastProcessed) {
350
        boolean structural = false;
×
351
        if (wouldInvalidate(graph, lastProcessed, /*adminPinned=*/ true,
×
352
                            adminInvalidationCheckWhere(graph, lastProcessed))) {
×
353
            executeUpdate(adminInvalidationDelete(graph, lastProcessed));
×
354
            structural = true;
×
355
        }
356
        if (wouldInvalidate(graph, lastProcessed, /*adminPinned=*/ false,
×
357
                            roleAssignmentInvalidationCheckWhere(graph, lastProcessed))) {
×
358
            executeUpdate(roleAssignmentInvalidationDelete(graph, lastProcessed));
×
359
            structural = true;
×
360
        }
361
        // RoleDeclaration ASK only — RDs aren't materialized into the space-state
362
        // graph, so there's nothing to DELETE here. The flag still flips because
363
        // sticky downstream RIs derived from the now-invalidated RD need a
364
        // from-scratch recompute.
365
        if (wouldInvalidate(graph, lastProcessed, /*adminPinned=*/ false,
×
366
                            roleDeclarationInvalidationCheckWhere(lastProcessed))) {
×
367
            structural = true;
×
368
        }
369
        // Sub-space declarations are structural — invalidating one (Mode A) or one
370
        // of two co-declarations (Mode B) changes the validated parent/child
371
        // topology. The DELETE removes the per-declaration row; the convenience
372
        // direct triples are left sticky and cleaned on the next periodic rebuild.
373
        if (wouldInvalidate(graph, lastProcessed, /*adminPinned=*/ false,
×
374
                            subSpaceInvalidationCheckWhere(graph, lastProcessed))) {
×
375
            executeUpdate(subSpaceInvalidationDelete(graph, lastProcessed));
×
376
            structural = true;
×
377
        }
378
        // Leaf-tier RI deletes — no flag.
379
        executeUpdate(leafTierInvalidationDelete(graph, lastProcessed));
×
380
        // Maintained-resource declaration deletes — no flag (leaf relation, no
381
        // downstream caches to bound).
382
        executeUpdate(maintainedResourceInvalidationDelete(graph, lastProcessed));
×
383
        if (structural) setNeedsFullRebuild();
×
384
        return structural;
×
385
    }
386

387
    /**
388
     * Runs the four leaf tiers (attachment/maintainer/member/observer) with
389
     * {@code lastProcessed = -1} so the load-number filter on the candidate
390
     * side admits everything. Dedup filters in the tier templates prevent
391
     * double-insert. Used by the late-arrival sweep.
392
     */
393
    TierInsertedTriples runDownstreamWithoutLoadFilter(IRI graph) {
394
        TierInsertedTriples c = new TierInsertedTriples();
×
395
        // Sub-space late-arrival: catches Mode-B candidates whose primary
396
        // declaration is older than lastProcessed but whose partner just landed.
397
        c.subSpace = runTierLabeled("subspace(late)", graph,
×
398
                subSpaceAdmitUpdate(graph, -1));
×
399
        // Maintained-resource late-arrival: catches declarations that landed
400
        // before the publisher's admin grant became valid in this state.
401
        c.maintainedResource = runTierLabeled("maintained-resource(late)", graph,
×
402
                maintainedResourceAdmitUpdate(graph, -1));
×
403
        // URL-prefix fallback: re-run after the late-arrival sub-space admit so
404
        // any newly-validated children get their fallback edges suppressed (for
405
        // future inserts) and any newly-orphaned children pick up fallback edges.
406
        c.subSpacePrefix = runTierLabeled("subspace-prefix(late)", graph,
×
407
                subSpacePrefixFallbackUpdate(graph));
×
408
        c.attachment = runTierLabeled("attachment(late)", graph,
×
409
                attachmentValidationUpdate(graph, -1));
×
410
        c.maintainer = runTierLabeled("maintainer(late)", graph,
×
411
                nonAdminTierUpdate(graph, -1, GEN.MAINTAINER_ROLE, PUBLISHER_IS_ADMIN));
×
412
        c.member = runTierLabeled("member(admin-pub,late)", graph,
×
413
                nonAdminTierUpdate(graph, -1, GEN.MEMBER_ROLE, PUBLISHER_IS_ADMIN));
×
414
        c.member += runTierLabeled("member(maint-pub,late)", graph,
×
415
                nonAdminTierUpdate(graph, -1,
×
416
                        GEN.MEMBER_ROLE, publisherIsTieredRole(GEN.MAINTAINER_ROLE)));
×
417
        c.observer = runTierLabeled("observer(admin-pub,late)", graph,
×
418
                nonAdminTierUpdate(graph, -1, GEN.OBSERVER_ROLE, PUBLISHER_IS_ADMIN));
×
419
        c.observer += runTierLabeled("observer(maint-pub,late)", graph,
×
420
                nonAdminTierUpdate(graph, -1,
×
421
                        GEN.OBSERVER_ROLE, publisherIsTieredRole(GEN.MAINTAINER_ROLE)));
×
422
        c.observer += runTierLabeled("observer(member-pub,late)", graph,
×
423
                nonAdminTierUpdate(graph, -1,
×
424
                        GEN.OBSERVER_ROLE, publisherIsTieredRole(GEN.MEMBER_ROLE)));
×
425
        c.observer += runTierLabeled("observer(self,late)", graph,
×
426
                nonAdminTierUpdate(graph, -1, GEN.OBSERVER_ROLE, PUBLISHER_IS_SELF));
×
427
        return c;
×
428
    }
429

430
    /**
431
     * Cheap ASK: did any new {@code npa:RoleDeclaration} extraction land in the
432
     * load-number delta {@code (lastProcessed, ∞)}? Used by the late-arrival
433
     * trigger so an RD that arrives in the same cycle as a matching candidate
434
     * still gets validated.
435
     */
436
    boolean newRoleDeclarationsArrived(long lastProcessed) {
437
        String ask = String.format("""
×
438
                PREFIX npa: <%1$s>
439
                ASK {
440
                  GRAPH <%2$s> {
441
                    ?rd a npa:RoleDeclaration ;
442
                        npa:viaNanopub ?np .
443
                  }
444
                  GRAPH <%3$s> {
445
                    ?np npa:hasLoadNumber ?ln .
446
                    FILTER (?ln > %4$d)
447
                  }
448
                }
449
                """, NPA.NAMESPACE, SpacesVocab.SPACES_GRAPH, NPA.GRAPH, lastProcessed);
×
450
        return runAsk(ask);
×
451
    }
452

453
    // ---------------- Tier UPDATE loops ----------------
454

455
    /**
456
     * Per-tier inserted-triple tallies for one build or cycle. Counts the sum
457
     * of {@code (graphSize_after - graphSize_before)} across all iterations of
458
     * each tier's fixed-point INSERT loop — i.e. inserted *triples*, not
459
     * distinct subjects (a single RoleInstantiation insert writes 4–5 triples).
460
     *
461
     * <p>Used internally by the {@link #runIncrementalCycle structuralAdds}
462
     * boolean check (we only care whether any tier inserted at all).
463
     * Not what the log lines report: see {@link TierSubjectTotals} +
464
     * {@link #computeTierSubjectTotals} for the distinct-subject totals
465
     * surfaced to operators.
466
     */
467
    static final class TierInsertedTriples {
×
468
        int admin;
469
        int attachment;
470
        int maintainer;
471
        int member;
472
        int observer;
473
        int subSpace;
474
        int subSpacePrefix;
475
        int maintainedResource;
476
    }
477

478
    /**
479
     * Snapshot of distinct-subject totals in a space-state graph at a moment
480
     * in time. Independent of which tier-loop added each subject.
481
     */
482
    record TierSubjectTotals(long adminRIs, long attachmentRAs, long nonAdminRIs) {}
36✔
483

484
    /**
485
     * Runs the five tier loops in order: admin → {@code gen:hasRole} attachment
486
     * validation → maintainer → member → observer. Each loop iterates a SPARQL
487
     * INSERT to fixed point (no new triples added). Returns per-tier counts.
488
     *
489
     * @param graph         target space-state graph
490
     * @param lastProcessed load-number horizon; use {@code -1} for full build
491
     */
492
    TierInsertedTriples runAllTierLoops(IRI graph, long lastProcessed) {
493
        TierInsertedTriples c = new TierInsertedTriples();
×
494
        c.admin = runTierLabeled("admin", graph, adminTierUpdate(graph, lastProcessed));
×
495
        // Sub-space admit runs after admin closure has settled (Mode A + Mode B both
496
        // need the admin set). Independent of role tiers — order between subspace
497
        // and attachment / maintainer / member / observer doesn't matter.
498
        c.subSpace = runTierLabeled("subspace", graph, subSpaceAdmitUpdate(graph, lastProcessed));
×
499
        // Maintained-resource admit also depends only on the admin closure. Single
500
        // Mode A: publisher must be admin of the maintaining space. No co-declaration
501
        // partner, no URL-prefix fallback.
502
        c.maintainedResource = runTierLabeled("maintained-resource", graph,
×
503
                maintainedResourceAdmitUpdate(graph, lastProcessed));
×
504
        // URL-prefix sub-space fallback runs after the explicit-declaration admit
505
        // pass commits so the per-child suppression check sees this cycle's fresh
506
        // validations. No load filter — depends on which Spaces exist, not on
507
        // delta-arrivals; the dedup FILTER NOT EXISTS prevents re-insertion.
508
        c.subSpacePrefix = runTierLabeled("subspace-prefix", graph,
×
509
                subSpacePrefixFallbackUpdate(graph));
×
510
        c.attachment = runTierLabeled("attachment", graph,
×
511
                attachmentValidationUpdate(graph, lastProcessed));
×
512
        c.maintainer = runTierLabeled("maintainer", graph, nonAdminTierUpdate(graph, lastProcessed,
×
513
                GEN.MAINTAINER_ROLE, PUBLISHER_IS_ADMIN));
514
        // Member tier: admin OR maintainer publisher — split into two simpler updates
515
        // so the query planner doesn't struggle with the UNION.
516
        c.member = runTierLabeled("member(admin-pub)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
517
                GEN.MEMBER_ROLE, PUBLISHER_IS_ADMIN));
518
        c.member += runTierLabeled("member(maint-pub)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
519
                GEN.MEMBER_ROLE, publisherIsTieredRole(GEN.MAINTAINER_ROLE)));
×
520
        // Observer tier: self-evidence OR a downward grant from any higher tier.
521
        // ObserverRole is the default tier when a role definition omits an
522
        // explicit subclass (see "Role types" in design-space-repositories.md), so
523
        // most "X assigned Y this role" nanopubs land here. Restricting the tier
524
        // to PUBLISHER_IS_SELF would silently drop those grants. The four
525
        // sub-loops mirror the trust-state's downward-only chain: admin grants
526
        // anything; maintainers and members grant observer; everyone may
527
        // self-attest.
528
        c.observer = runTierLabeled("observer(admin-pub)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
529
                GEN.OBSERVER_ROLE, PUBLISHER_IS_ADMIN));
530
        c.observer += runTierLabeled("observer(maint-pub)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
531
                GEN.OBSERVER_ROLE, publisherIsTieredRole(GEN.MAINTAINER_ROLE)));
×
532
        c.observer += runTierLabeled("observer(member-pub)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
533
                GEN.OBSERVER_ROLE, publisherIsTieredRole(GEN.MEMBER_ROLE)));
×
534
        c.observer += runTierLabeled("observer(self)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
535
                GEN.OBSERVER_ROLE, PUBLISHER_IS_SELF));
536
        return c;
×
537
    }
538

539
    /**
540
     * Builds a publisher constraint requiring the publisher to be a validated holder
541
     * of the given tier's role (maintainer or member) in the target space.
542
     * Owns its own AccountState resolution so ?publisher is bound through the
543
     * targeted (pkh → agent) lookup rather than enumerated.
544
     */
545
    private static String publisherIsTieredRole(IRI tierClass) {
546
        return """
×
547
                ?acct a npa:AccountState ;
548
                      npa:pubkey ?pkh ;
549
                      npa:agent  ?publisher .
550
                ?tierRI a gen:RoleInstantiation ;
551
                        npa:forSpace ?space ;
552
                        npa:forAgent ?publisher .
553
                ?rdT a npa:RoleDeclaration ;
554
                     npa:hasRoleType <%1$s> .
555
                { ?tierRI npa:regularProperty ?predT . ?rdT gen:hasRegularProperty ?predT . }
556
                UNION
557
                { ?tierRI npa:inverseProperty ?predT . ?rdT gen:hasInverseProperty ?predT . }
558
                """.formatted(tierClass);
×
559
    }
560

561
    /** Wraps {@link #runTierLoop} with tier-name context for logs/exceptions. */
562
    private int runTierLabeled(String tier, IRI graph, String sparqlUpdate) {
563
        try {
564
            return runTierLoop(graph, sparqlUpdate);
×
565
        } catch (RuntimeException ex) {
×
566
            log.error("AuthorityResolver: tier={} failed with SPARQL UPDATE:\n{}\n", tier, sparqlUpdate, ex);
×
567
            throw ex;
×
568
        }
569
    }
570

571
    /**
572
     * Runs a single tier's INSERT to fixed point. Counts rows by probing
573
     * graph size before/after each INSERT; stops when the size doesn't change.
574
     *
575
     * @return total number of triples inserted by this tier across all iterations
576
     */
577
    int runTierLoop(IRI graph, String sparqlUpdate) {
578
        int total = 0;
×
579
        long before = graphSize(graph);
×
580
        while (true) {
581
            // Note: no explicit transaction wrapping here. In tests we observed that
582
            // HTTPRepository's RDF4J-transaction protocol silently no-op'd cross-graph
583
            // SPARQL UPDATEs with UNION sub-patterns inside conn.begin()/commit(),
584
            // while the same UPDATE POSTed directly to /statements applied correctly.
585
            // A bare prepareUpdate().execute() takes the direct /statements path and
586
            // runs the UPDATE atomically per SPARQL 1.1 semantics — which is all we
587
            // need; there's nothing else to commit atomically alongside the UPDATE.
588
            try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
589
                conn.prepareUpdate(QueryLanguage.SPARQL, sparqlUpdate).execute();
×
590
            }
591
            long after = graphSize(graph);
×
592
            long added = after - before;
×
593
            if (added <= 0) break;
×
594
            total += added;
×
595
            before = after;
×
596
        }
×
597
        return total;
×
598
    }
599

600
    private long graphSize(IRI graph) {
601
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
602
            return conn.size(graph);
×
603
        }
604
    }
605

606
    /**
607
     * Distinct-subject totals in the given space-state graph, broken down by
608
     * RoleInstantiation kind (admin-pinned vs not) and RoleAssignment.
609
     * Three SELECT-COUNT queries — cheap, called once per build/cycle for
610
     * the user-facing log line. Returns zeros on failure (logged) so a flaky
611
     * count read can't wedge the cycle.
612
     */
613
    TierSubjectTotals computeTierSubjectTotals(IRI graph) {
614
        long adminRIs       = countDistinctSubjects(graph, """
×
615
                ?ri a gen:RoleInstantiation ; npa:inverseProperty gen:hasAdmin .
616
                """, "ri");
617
        long attachmentRAs  = countDistinctSubjects(graph, """
×
618
                ?ra a gen:RoleAssignment .
619
                """, "ra");
620
        long nonAdminRIs    = countDistinctSubjects(graph, """
×
621
                ?ri a gen:RoleInstantiation .
622
                FILTER NOT EXISTS { ?ri npa:inverseProperty gen:hasAdmin }
623
                """, "ri");
624
        return new TierSubjectTotals(adminRIs, attachmentRAs, nonAdminRIs);
×
625
    }
626

627
    private long countDistinctSubjects(IRI graph, String wherePattern, String varName) {
628
        String query = String.format("""
×
629
                PREFIX npa: <%1$s>
630
                PREFIX gen: <%2$s>
631
                SELECT (COUNT(DISTINCT ?%3$s) AS ?n) WHERE {
632
                  GRAPH <%4$s> {
633
                    %5$s
634
                  }
635
                }
636
                """, NPA.NAMESPACE, GEN.NAMESPACE, varName, graph, wherePattern);
637
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO);
×
638
             TupleQueryResult r = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) {
×
639
            if (!r.hasNext()) return 0;
×
640
            return Long.parseLong(r.next().getBinding("n").getValue().stringValue());
×
641
        } catch (Exception ex) {
×
642
            log.warn("AuthorityResolver: countDistinctSubjects on {} failed: {}",
×
643
                    graph, ex.toString());
×
644
            return 0;
×
645
        }
646
    }
647

648
    // ---------------- SPARQL templates ----------------
649

650
    /**
651
     * Reusable invalidation filter on a bound nanopub-IRI variable. Pass the bare
652
     * variable name (no leading {@code ?}); e.g. {@code invalidationFilter("np")}
653
     * produces an outer-scoped {@code FILTER NOT EXISTS { GRAPH npa:spacesGraph
654
     * { ?_inv_np a npa:Invalidation ; npa:invalidates ?np . } }}.
655
     *
656
     * <p>Important: this filter must be placed OUTSIDE the surrounding
657
     * {@code GRAPH npa:spacesGraph { ... }} block, not nested inside it. When
658
     * nested, RDF4J's planner couples the FILTER NOT EXISTS evaluation into the
659
     * join order (per-row scan of {@code ?_inv a npa:Invalidation} multiplied by
660
     * the candidate set), which we measured turning a 39ms query into a 60s+
661
     * timeout on the live observer-tier data. Outside the GRAPH block, the
662
     * planner defers the filter until {@code ?np}/{@code ?rdNp} are bound and
663
     * does a targeted index lookup.
664
     *
665
     * <p>Variable names must match {@code [A-Za-z0-9_]+} per SPARQL grammar —
666
     * embedding a {@code ?} inside {@code ?_inv_?np} would yield a parse error.
667
     */
668
    private static String invalidationFilter(String bareVarName) {
669
        return "FILTER NOT EXISTS { GRAPH <" + SpacesVocab.SPACES_GRAPH + "> {"
30✔
670
                + " ?_inv_" + bareVarName
671
                + " a <" + SpacesVocab.INVALIDATION + "> ; "
672
                + "<" + SpacesVocab.INVALIDATES + "> ?" + bareVarName + " . } }";
673
    }
674

675
    /**
676
     * Admin tier: seed from {@code npadef:...hasRootAdmin} (trusted by construction)
677
     * plus closed-over admin grants; insert any {@code gen:RoleInstantiation} with
678
     * {@code npa:inverseProperty gen:hasAdmin} whose publisher (resolved via mirrored
679
     * trust-approved AccountState) is already in the admin set.
680
     */
681
    static String adminTierUpdate(IRI graph, long lastProcessed) {
682
        // Order tuned for RDF4J's evaluator:
683
        //   1. Anchor on the small (seed UNION closed-over) set to bind ?publisher
684
        //      and ?space cheaply.
685
        //   2. Resolve ?pkh from the mirrored AccountState row (?publisher bound).
686
        //   3. Probe instantiations using the now-bound (?space, ?pkh) — targeted
687
        //      lookup, not a full RoleInstantiation scan.
688
        //   4. Load-number filter on bound ?np.
689
        //   5. Dedup at the end.
690
        return """
69✔
691
                PREFIX npa:  <%1$s>
692
                PREFIX gen:  <%2$s>
693
                INSERT { GRAPH <%3$s> {
694
                  ?ri a gen:RoleInstantiation ;
695
                      npa:forSpace ?space ;
696
                      npa:inverseProperty gen:hasAdmin ;
697
                      npa:forAgent ?agent ;
698
                      npa:viaNanopub ?np .
699
                } }
700
                WHERE {
701
                  # 1. Anchor: who is already an admin of which space?
702
                  {
703
                    # Seed branch: root-admin in a non-invalidated SpaceDefinition.
704
                    GRAPH <%4$s> {
705
                      ?def a npa:SpaceDefinition ;
706
                           npa:forSpaceRef  ?spaceRef ;
707
                           npa:hasRootAdmin ?publisher ;
708
                           npa:viaNanopub   ?defNp .
709
                      ?spaceRef npa:spaceIri ?space .
710
                    }
711
                    %7$s
712
                  }
713
                  UNION
714
                  {
715
                    # Closed-over branch: an existing admin in this space-state graph.
716
                    GRAPH <%3$s> {
717
                      ?prev a gen:RoleInstantiation ;
718
                            npa:forSpace        ?space ;
719
                            npa:inverseProperty gen:hasAdmin ;
720
                            npa:forAgent        ?publisher .
721
                    }
722
                  }
723
                  # 2. Mirror: resolve ?publisher → ?pkh via the trust-approved row.
724
                  GRAPH <%3$s> {
725
                    ?acct a npa:AccountState ;
726
                          npa:agent  ?publisher ;
727
                          npa:pubkey ?pkh .
728
                  }
729
                  # 3. Targeted instantiation lookup by space + pubkey.
730
                  GRAPH <%4$s> {
731
                    ?ri a gen:RoleInstantiation ;
732
                        npa:forSpace        ?space ;
733
                        npa:inverseProperty gen:hasAdmin ;
734
                        npa:forAgent        ?agent ;
735
                        npa:pubkeyHash      ?pkh ;
736
                        npa:viaNanopub      ?np .
737
                  }
738
                  %6$s
739
                  # 4. Load-number filter on bound ?np.
740
                  GRAPH <%8$s> {
741
                    ?np npa:hasLoadNumber ?ln .
742
                    FILTER (?ln > %5$d)
743
                  }
744
                  # 5. Dedup last.
745
                  FILTER NOT EXISTS { GRAPH <%3$s> {
746
                    ?existing a gen:RoleInstantiation ;
747
                              npa:forSpace ?space ;
748
                              npa:forAgent ?agent ;
749
                              npa:inverseProperty gen:hasAdmin .
750
                  } }
751
                }
752
                """.formatted(
3✔
753
                NPA.NAMESPACE,
754
                GEN.NAMESPACE,
755
                graph,
756
                SpacesVocab.SPACES_GRAPH,
757
                lastProcessed,
15✔
758
                invalidationFilter("np"),
15✔
759
                invalidationFilter("defNp"),
18✔
760
                NPA.GRAPH);
761
    }
762

763
    /**
764
     * {@code gen:hasRole} attachment validation: an attachment is validated iff its
765
     * publisher is already a validated admin of the target space. Adds
766
     * {@code gen:RoleAssignment} rows to the space-state graph.
767
     */
768
    static String attachmentValidationUpdate(IRI graph, long lastProcessed) {
769
        return """
69✔
770
                PREFIX npa:  <%1$s>
771
                PREFIX gen:  <%2$s>
772
                INSERT { GRAPH <%3$s> {
773
                  ?ra a gen:RoleAssignment ;
774
                      npa:forSpace ?space ;
775
                      gen:hasRole  ?role ;
776
                      npa:viaNanopub ?np .
777
                } }
778
                WHERE {
779
                  GRAPH <%4$s> {
780
                    ?ra a gen:RoleAssignment ;
781
                        npa:forSpace ?space ;
782
                        gen:hasRole  ?role ;
783
                        npa:pubkeyHash ?pkh ;
784
                        npa:viaNanopub ?np .
785
                  }
786
                  GRAPH <%7$s> {
787
                    ?np npa:hasLoadNumber ?ln .
788
                    FILTER (?ln > %5$d)
789
                  }
790
                  GRAPH <%3$s> {
791
                    ?acct a npa:AccountState ;
792
                          npa:agent  ?publisher ;
793
                          npa:pubkey ?pkh .
794
                    ?adminRI a gen:RoleInstantiation ;
795
                             npa:forSpace ?space ;
796
                             npa:inverseProperty gen:hasAdmin ;
797
                             npa:forAgent ?publisher .
798
                  }
799
                  %6$s
800
                  FILTER NOT EXISTS { GRAPH <%3$s> {
801
                    ?existing a gen:RoleAssignment ;
802
                              npa:forSpace ?space ;
803
                              gen:hasRole  ?role .
804
                  } }
805
                }
806
                """.formatted(
3✔
807
                NPA.NAMESPACE,
808
                GEN.NAMESPACE,
809
                graph,
810
                SpacesVocab.SPACES_GRAPH,
811
                lastProcessed,
15✔
812
                invalidationFilter("np"),
18✔
813
                NPA.GRAPH);
814
    }
815

816
    /**
817
     * Non-admin tier publisher constraints (inserted as a SPARQL sub-pattern).
818
     * Each constraint owns the AccountState (pkh → agent) lookup so the join
819
     * variable is bound through a targeted pattern. The observer-self variant
820
     * binds {@code npa:agent ?agent} directly — no separate {@code ?publisher}
821
     * variable, no post-join equality filter — which lets the planner anchor
822
     * the AccountState lookup on the already-bound {@code ?agent} instead of
823
     * enumerating all approved publishers and filtering at the end.
824
     */
825
    static final String PUBLISHER_IS_ADMIN = """
826
            ?acct a npa:AccountState ;
827
                  npa:pubkey ?pkh ;
828
                  npa:agent  ?publisher .
829
            ?adminRI a gen:RoleInstantiation ;
830
                     npa:forSpace ?space ;
831
                     npa:inverseProperty gen:hasAdmin ;
832
                     npa:forAgent ?publisher .
833
            """;
834

835
    /** Observer self-evidence: the assignee's own pubkey signed the instantiation. */
836
    static final String PUBLISHER_IS_SELF = """
837
            ?acct a npa:AccountState ;
838
                  npa:pubkey ?pkh ;
839
                  npa:agent  ?agent .
840
            """;
841

842
    /**
843
     * Maintainer / Member / Observer tier INSERT. Same shape: find an instantiation
844
     * whose predicate matches a RoleDeclaration of the given tier attached to the
845
     * target space, and whose publisher passes the tier-specific constraint.
846
     */
847
    static String nonAdminTierUpdate(IRI graph, long lastProcessed,
848
                                     IRI tierClass, String publisherConstraint) {
849
        // Order tuned for RDF4J's evaluator (which executes BGPs roughly in order).
850
        // The crucial choice is the *anchor*: instantiation-first plans send the
851
        // planner exploring the full ~thousands of candidate RIs and only filter
852
        // by tier at the very end. Attachment-first anchors on the small set of
853
        // gen:RoleAssignment rows already validated in this space-state graph
854
        // (~hundreds, often zero) and walks outward by bound (?role, ?space).
855
        //
856
        //   1. Anchor on RoleAssignments in this space-state graph (small).
857
        //   2. Match the tier-pinned RoleDeclaration by ?role.
858
        //   3. Pair role-decl direction to instantiation direction in one UNION
859
        //      so only (reg, reg)/(inv, inv) combos are explored.
860
        //   4. Targeted instantiation lookup — (?space, ?pred) are bound.
861
        //   5. Publisher constraint (incl. AccountState resolution).
862
        //   6. Load-number filter on bound ?np.
863
        //   7. Dedup at the end.
864
        return """
69✔
865
                PREFIX npa:  <%1$s>
866
                PREFIX gen:  <%2$s>
867
                INSERT { GRAPH <%3$s> {
868
                  ?ri a gen:RoleInstantiation ;
869
                      npa:forSpace ?space ;
870
                      npa:forAgent ?agent ;
871
                      npa:viaNanopub ?np .
872
                } }
873
                WHERE {
874
                  # 1. Anchor: validated attachments in this space-state graph.
875
                  GRAPH <%3$s> {
876
                    ?ra a gen:RoleAssignment ;
877
                        gen:hasRole  ?role ;
878
                        npa:forSpace ?space .
879
                  }
880
                  # 2. Tier-pinned RoleDeclaration (?role bound from the attachment).
881
                  GRAPH <%4$s> {
882
                    ?rd a npa:RoleDeclaration ;
883
                        npa:hasRoleType <%7$s> ;
884
                        npa:role        ?role ;
885
                        npa:viaNanopub  ?rdNp .
886
                    # 3. Pair direction so only matching combos are explored.
887
                    {
888
                      ?rd gen:hasRegularProperty ?pred .
889
                      ?ri npa:regularProperty    ?pred .
890
                    }
891
                    UNION
892
                    {
893
                      ?rd gen:hasInverseProperty ?pred .
894
                      ?ri npa:inverseProperty    ?pred .
895
                    }
896
                    # 4. Targeted instantiation lookup — (?space, ?pred) bound.
897
                    ?ri a gen:RoleInstantiation ;
898
                        npa:forSpace   ?space ;
899
                        npa:forAgent   ?agent ;
900
                        npa:pubkeyHash ?pkh ;
901
                        npa:viaNanopub ?np .
902
                  }
903
                  # 5. Publisher constraint (incl. AccountState resolution).
904
                  GRAPH <%3$s> {
905
                    %9$s
906
                  }
907
                  # 6. Load-number filter on bound ?np.
908
                  GRAPH <%10$s> {
909
                    ?np npa:hasLoadNumber ?ln .
910
                    FILTER (?ln > %5$d)
911
                  }
912
                  # 7. Invalidation filters — outside the GRAPH block so the
913
                  #    planner defers them until ?rdNp/?np are bound.
914
                  %8$s
915
                  %6$s
916
                  # 8. Dedup last.
917
                  FILTER NOT EXISTS { GRAPH <%3$s> {
918
                    ?existing a gen:RoleInstantiation ;
919
                              npa:forSpace ?space ;
920
                              npa:forAgent ?agent ;
921
                              npa:viaNanopub ?np .
922
                  } }
923
                }
924
                """.formatted(
3✔
925
                NPA.NAMESPACE,
926
                GEN.NAMESPACE,
927
                graph,
928
                SpacesVocab.SPACES_GRAPH,
929
                lastProcessed,
15✔
930
                invalidationFilter("np"),
27✔
931
                tierClass,
932
                invalidationFilter("rdNp"),
30✔
933
                publisherConstraint,
934
                NPA.GRAPH);
935
    }
936

937
    /**
938
     * Sub-space admit pass. Copies validated {@code npa:SubSpaceDeclaration}
939
     * extraction rows into the space-state graph (preserving the {@code npasub:}
940
     * subject) and emits convenience {@code <child> npa:isSubSpaceOf <parent>} and
941
     * {@code <parent> npa:hasSubSpace <child>} direct triples. Two satisfaction
942
     * modes joined by UNION:
943
     * <ul>
944
     *   <li>Mode A — the declaration's publisher is a validated admin of both the
945
     *       child and the parent space.</li>
946
     *   <li>Mode B — a different non-invalidated declaration for the same
947
     *       {@code (child, parent)} pair exists, and the two publishers between
948
     *       them cover both admin sides (i.e. one of them is admin of the child,
949
     *       one of them is admin of the parent — possibly the same one twice if
950
     *       both happen to be admin of both).</li>
951
     * </ul>
952
     *
953
     * <p>Mode-B late-arrival: when only the partner declaration is new in this
954
     * cycle (the primary is older than {@code lastProcessed}), the load-number
955
     * filter on {@code ?np} excludes the candidate. The late-arrival sweep
956
     * ({@link #runDownstreamWithoutLoadFilter}) re-runs this pass without the
957
     * load filter and catches it.
958
     */
959
    static String subSpaceAdmitUpdate(IRI graph, long lastProcessed) {
960
        return """
69✔
961
                PREFIX npa: <%1$s>
962
                PREFIX gen: <%2$s>
963
                INSERT { GRAPH <%3$s> {
964
                  ?d a npa:SubSpaceDeclaration ;
965
                     npa:childSpace  ?child ;
966
                     npa:parentSpace ?parent ;
967
                     npa:viaNanopub  ?np .
968
                  ?child  npa:isSubSpaceOf ?parent .
969
                  ?parent npa:hasSubSpace  ?child  .
970
                } }
971
                WHERE {
972
                  # 1. Anchor: candidate declarations from the extraction graph.
973
                  GRAPH <%4$s> {
974
                    ?d a npa:SubSpaceDeclaration ;
975
                       npa:childSpace  ?child ;
976
                       npa:parentSpace ?parent ;
977
                       npa:pubkeyHash  ?pkh ;
978
                       npa:viaNanopub  ?np .
979
                  }
980
                  # 2. Mirror: resolve ?pkh → ?publisher via the trust-approved row.
981
                  GRAPH <%3$s> {
982
                    ?acct a npa:AccountState ;
983
                          npa:pubkey ?pkh ;
984
                          npa:agent  ?publisher .
985
                  }
986
                  # 3. Authority gate.
987
                  {
988
                    # Mode A — publisher is admin of BOTH child and parent.
989
                    FILTER EXISTS { GRAPH <%3$s> {
990
                      ?riC a gen:RoleInstantiation ;
991
                           npa:inverseProperty gen:hasAdmin ;
992
                           npa:forSpace ?child ;
993
                           npa:forAgent ?publisher .
994
                    } }
995
                    FILTER EXISTS { GRAPH <%3$s> {
996
                      ?riP a gen:RoleInstantiation ;
997
                           npa:inverseProperty gen:hasAdmin ;
998
                           npa:forSpace ?parent ;
999
                           npa:forAgent ?publisher .
1000
                    } }
1001
                  }
1002
                  UNION
1003
                  {
1004
                    # Mode B — co-declaration whose publisher covers the side this
1005
                    # one's publisher doesn't. Between {publisher, publisher2},
1006
                    # both admin sides must be covered.
1007
                    GRAPH <%4$s> {
1008
                      ?d2 a npa:SubSpaceDeclaration ;
1009
                          npa:childSpace  ?child ;
1010
                          npa:parentSpace ?parent ;
1011
                          npa:pubkeyHash  ?pkh2 ;
1012
                          npa:viaNanopub  ?np2 .
1013
                      FILTER (?np2 != ?np)
1014
                    }
1015
                    %8$s
1016
                    GRAPH <%3$s> {
1017
                      ?acct2 a npa:AccountState ;
1018
                             npa:pubkey ?pkh2 ;
1019
                             npa:agent  ?publisher2 .
1020
                    }
1021
                    FILTER EXISTS { GRAPH <%3$s> {
1022
                      ?riA a gen:RoleInstantiation ;
1023
                           npa:inverseProperty gen:hasAdmin ;
1024
                           npa:forSpace ?child .
1025
                      { ?riA npa:forAgent ?publisher } UNION { ?riA npa:forAgent ?publisher2 }
1026
                    } }
1027
                    FILTER EXISTS { GRAPH <%3$s> {
1028
                      ?riB a gen:RoleInstantiation ;
1029
                           npa:inverseProperty gen:hasAdmin ;
1030
                           npa:forSpace ?parent .
1031
                      { ?riB npa:forAgent ?publisher } UNION { ?riB npa:forAgent ?publisher2 }
1032
                    } }
1033
                  }
1034
                  # 4. Invalidation filter on the primary declaration's nanopub.
1035
                  %6$s
1036
                  # 5. Load-number filter on bound ?np.
1037
                  GRAPH <%7$s> {
1038
                    ?np npa:hasLoadNumber ?ln .
1039
                    FILTER (?ln > %5$d)
1040
                  }
1041
                  # 6. Dedup last.
1042
                  FILTER NOT EXISTS { GRAPH <%3$s> {
1043
                    ?d a npa:SubSpaceDeclaration .
1044
                  } }
1045
                }
1046
                """.formatted(
3✔
1047
                NPA.NAMESPACE,
1048
                GEN.NAMESPACE,
1049
                graph,
1050
                SpacesVocab.SPACES_GRAPH,
1051
                lastProcessed,
15✔
1052
                invalidationFilter("np"),
27✔
1053
                NPA.GRAPH,
1054
                invalidationFilter("np2"));
6✔
1055
    }
1056

1057
    /**
1058
     * Maintained-resource admit pass. Copies validated
1059
     * {@code npa:MaintainedResourceDeclaration} extraction rows into the space-state
1060
     * graph (preserving the {@code npamrd:} subject) and emits convenience
1061
     * {@code <r> npa:isMaintainedBy <s>} and {@code <s> npa:hasMaintainedResource <r>}
1062
     * direct triples. Single satisfaction mode:
1063
     * <ul>
1064
     *   <li>Mode A — the declaration's publisher is a validated admin of the
1065
     *       maintaining space.</li>
1066
     * </ul>
1067
     *
1068
     * <p>No Mode B because only one space is involved; the two-sides-must-be-covered
1069
     * concern that drives sub-space Mode B doesn't apply. Late-arrival is still
1070
     * possible (declaration lands before the publisher's admin grant becomes valid):
1071
     * the load-number filter on {@code ?np} excludes the candidate, and the
1072
     * late-arrival sweep ({@link #runDownstreamWithoutLoadFilter}) re-runs this pass
1073
     * without the load filter and catches it.
1074
     */
1075
    static String maintainedResourceAdmitUpdate(IRI graph, long lastProcessed) {
1076
        return """
69✔
1077
                PREFIX npa: <%1$s>
1078
                PREFIX gen: <%2$s>
1079
                INSERT { GRAPH <%3$s> {
1080
                  ?d a npa:MaintainedResourceDeclaration ;
1081
                     npa:resourceIri     ?r ;
1082
                     npa:maintainerSpace ?s ;
1083
                     npa:viaNanopub      ?np .
1084
                  ?r npa:isMaintainedBy        ?s .
1085
                  ?s npa:hasMaintainedResource ?r .
1086
                } }
1087
                WHERE {
1088
                  # 1. Anchor: candidate declarations from the extraction graph.
1089
                  GRAPH <%4$s> {
1090
                    ?d a npa:MaintainedResourceDeclaration ;
1091
                       npa:resourceIri     ?r ;
1092
                       npa:maintainerSpace ?s ;
1093
                       npa:pubkeyHash      ?pkh ;
1094
                       npa:viaNanopub      ?np .
1095
                  }
1096
                  # 2. Mirror: resolve ?pkh → ?publisher via the trust-approved row.
1097
                  GRAPH <%3$s> {
1098
                    ?acct a npa:AccountState ;
1099
                          npa:pubkey ?pkh ;
1100
                          npa:agent  ?publisher .
1101
                    # 3. Authority gate (Mode A only): publisher is admin of the
1102
                    #    maintaining space.
1103
                    ?riA a gen:RoleInstantiation ;
1104
                         npa:inverseProperty gen:hasAdmin ;
1105
                         npa:forSpace ?s ;
1106
                         npa:forAgent ?publisher .
1107
                  }
1108
                  # 4. Invalidation filter on the declaration's nanopub.
1109
                  %6$s
1110
                  # 5. Load-number filter on bound ?np.
1111
                  GRAPH <%7$s> {
1112
                    ?np npa:hasLoadNumber ?ln .
1113
                    FILTER (?ln > %5$d)
1114
                  }
1115
                  # 6. Dedup last.
1116
                  FILTER NOT EXISTS { GRAPH <%3$s> {
1117
                    ?d a npa:MaintainedResourceDeclaration .
1118
                  } }
1119
                }
1120
                """.formatted(
3✔
1121
                NPA.NAMESPACE,
1122
                GEN.NAMESPACE,
1123
                graph,
1124
                SpacesVocab.SPACES_GRAPH,
1125
                lastProcessed,
15✔
1126
                invalidationFilter("np"),
18✔
1127
                NPA.GRAPH);
1128
    }
1129

1130
    /**
1131
     * URL-prefix sub-space fallback admit pass. For every pair of {@code SpaceRef}
1132
     * aggregates where the child's {@code npa:hasIdPrefix} matches the parent's
1133
     * {@code npa:spaceIri}, emits convenience {@code <child> npa:isSubSpaceOf <parent>}
1134
     * and {@code <parent> npa:hasSubSpace <child>} direct triples plus a reified
1135
     * {@code npa:DerivedSubSpaceLink} tag carrying {@code npa:derivationKind
1136
     * npa:byUrlPrefix} so consumers can hide derived edges.
1137
     *
1138
     * <p>Per-child suppression: any validated {@code npa:SubSpaceDeclaration} on the
1139
     * child in {@code npass:<…>} suppresses every fallback edge for that child.
1140
     * Suppression checks the validated set (not raw extraction-graph declarations)
1141
     * so an unapproved or in-flight Mode B declaration doesn't silently hide both
1142
     * the URL-prefix fallback and the (still-invalid) explicit relation.
1143
     *
1144
     * <p>Run order: must run after {@link #subSpaceAdmitUpdate} commits in the
1145
     * same cycle so the suppression check sees this cycle's freshly-validated
1146
     * declarations.
1147
     *
1148
     * <p>No load-number filter: the fallback depends on which Spaces exist (parent
1149
     * + child {@code SpaceRef}s), not on which were just added. Always full-scan;
1150
     * the dedup {@code FILTER NOT EXISTS} on the tag IRI prevents re-insertion.
1151
     *
1152
     * <p>No invalidation handling: derived edges have no source nanopub. Two
1153
     * staleness modes: (a) child later gets first validated declaration → old
1154
     * derived edges stay sticky until the next periodic rebuild (same policy as
1155
     * admin-RI invalidation); (b) child loses last validated declaration → the
1156
     * regular fallback pass on the next cycle re-engages, adds derived edges
1157
     * incrementally, no rebuild needed.
1158
     */
1159
    static String subSpacePrefixFallbackUpdate(IRI graph) {
1160
        return """
48✔
1161
                PREFIX npa: <%1$s>
1162
                INSERT { GRAPH <%2$s> {
1163
                  ?child  npa:isSubSpaceOf ?parent .
1164
                  ?parent npa:hasSubSpace  ?child  .
1165
                  ?tagIri a npa:DerivedSubSpaceLink ;
1166
                          npa:childSpace     ?child ;
1167
                          npa:parentSpace    ?parent ;
1168
                          npa:derivationKind npa:byUrlPrefix .
1169
                } }
1170
                WHERE {
1171
                  # 1. Anchor: child SpaceRef → its path-prefixes (extracted at load
1172
                  #    time from the Space IRI; see SpacesExtractor.enumerateIdPrefixes).
1173
                  GRAPH <%3$s> {
1174
                    ?childRef  npa:spaceIri    ?child ;
1175
                               npa:hasIdPrefix ?parent .
1176
                    # 2. Parent SpaceRef must exist for the same IRI as the prefix.
1177
                    ?parentRef npa:spaceIri    ?parent .
1178
                  }
1179
                  # 3. Suppress fallback for any child that has a validated declaration
1180
                  #    in this state graph. Per-child, all-or-nothing.
1181
                  FILTER NOT EXISTS {
1182
                    GRAPH <%2$s> {
1183
                      ?d a npa:SubSpaceDeclaration ;
1184
                         npa:childSpace ?child .
1185
                    }
1186
                  }
1187
                  # 4. Mint a deterministic tag IRI per (child, parent).
1188
                  BIND(IRI(CONCAT("http://purl.org/nanopub/admin/derivedlink/",
1189
                                  MD5(CONCAT(STR(?child), "|", STR(?parent))))) AS ?tagIri)
1190
                  # 5. Dedup: don't re-insert if this tag is already present.
1191
                  FILTER NOT EXISTS {
1192
                    GRAPH <%2$s> {
1193
                      ?tagIri a npa:DerivedSubSpaceLink .
1194
                    }
1195
                  }
1196
                }
1197
                """.formatted(
3✔
1198
                NPA.NAMESPACE,
1199
                graph,
1200
                SpacesVocab.SPACES_GRAPH);
1201
    }
1202

1203
    // ---------------- Invalidation templates (incremental cycle) ----------------
1204

1205
    /**
1206
     * WHERE clause shared by the admin-RI invalidation ASK precheck and the
1207
     * matching DELETE. Identifies admin-tier {@code gen:RoleInstantiation} rows
1208
     * in the space-state graph whose {@code npa:viaNanopub} equals the target
1209
     * of an {@code npa:Invalidation} that landed in {@code (lastProcessed, ∞)}.
1210
     */
1211
    static String adminInvalidationCheckWhere(IRI graph, long lastProcessed) {
1212
        return String.format("""
60✔
1213
                  GRAPH <%1$s> {
1214
                    ?ri a gen:RoleInstantiation ;
1215
                        npa:inverseProperty gen:hasAdmin ;
1216
                        npa:viaNanopub ?np .
1217
                  }
1218
                  GRAPH <%2$s> {
1219
                    ?inv a npa:Invalidation ;
1220
                         npa:invalidates ?np ;
1221
                         npa:viaNanopub  ?invNp .
1222
                  }
1223
                  GRAPH <%3$s> {
1224
                    ?invNp npa:hasLoadNumber ?ln .
1225
                    FILTER (?ln > %4$d)
1226
                  }
1227
                """, graph, SpacesVocab.SPACES_GRAPH, NPA.GRAPH, lastProcessed);
6✔
1228
    }
1229

1230
    /** DELETE template for admin-tier RoleInstantiations whose source nanopub was invalidated. */
1231
    static String adminInvalidationDelete(IRI graph, long lastProcessed) {
1232
        return String.format("""
63✔
1233
                PREFIX npa: <%1$s>
1234
                PREFIX gen: <%2$s>
1235
                DELETE { GRAPH <%3$s> {
1236
                  ?ri ?p ?o .
1237
                } }
1238
                WHERE {
1239
                  GRAPH <%3$s> { ?ri ?p ?o . }
1240
                %4$s
1241
                }
1242
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
1243
                adminInvalidationCheckWhere(graph, lastProcessed));
6✔
1244
    }
1245

1246
    /** WHERE clause for RoleAssignment invalidation. */
1247
    static String roleAssignmentInvalidationCheckWhere(IRI graph, long lastProcessed) {
1248
        return String.format("""
60✔
1249
                  GRAPH <%1$s> {
1250
                    ?ra a gen:RoleAssignment ;
1251
                        npa:viaNanopub ?np .
1252
                  }
1253
                  GRAPH <%2$s> {
1254
                    ?inv a npa:Invalidation ;
1255
                         npa:invalidates ?np ;
1256
                         npa:viaNanopub  ?invNp .
1257
                  }
1258
                  GRAPH <%3$s> {
1259
                    ?invNp npa:hasLoadNumber ?ln .
1260
                    FILTER (?ln > %4$d)
1261
                  }
1262
                """, graph, SpacesVocab.SPACES_GRAPH, NPA.GRAPH, lastProcessed);
6✔
1263
    }
1264

1265
    /** DELETE template for RoleAssignments whose source nanopub was invalidated. */
1266
    static String roleAssignmentInvalidationDelete(IRI graph, long lastProcessed) {
1267
        return String.format("""
63✔
1268
                PREFIX npa: <%1$s>
1269
                PREFIX gen: <%2$s>
1270
                DELETE { GRAPH <%3$s> {
1271
                  ?ra ?p ?o .
1272
                } }
1273
                WHERE {
1274
                  GRAPH <%3$s> { ?ra ?p ?o . }
1275
                %4$s
1276
                }
1277
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
1278
                roleAssignmentInvalidationCheckWhere(graph, lastProcessed));
6✔
1279
    }
1280

1281
    /**
1282
     * WHERE clause for RoleDeclaration invalidation. ASK-only (no DELETE):
1283
     * RoleDeclarations live in {@code npa:spacesGraph} and aren't materialized
1284
     * into the space-state graph, so there's nothing to remove from the
1285
     * space-state. The ASK still flips {@code npa:needsFullRebuild} because
1286
     * sticky downstream RIs that were derived under the now-invalidated RD
1287
     * need a from-scratch recompute.
1288
     */
1289
    static String roleDeclarationInvalidationCheckWhere(long lastProcessed) {
1290
        return String.format("""
48✔
1291
                  GRAPH <%1$s> {
1292
                    ?rd a npa:RoleDeclaration ;
1293
                        npa:viaNanopub ?np .
1294
                    ?inv a npa:Invalidation ;
1295
                         npa:invalidates ?np ;
1296
                         npa:viaNanopub  ?invNp .
1297
                  }
1298
                  GRAPH <%2$s> {
1299
                    ?invNp npa:hasLoadNumber ?ln .
1300
                    FILTER (?ln > %3$d)
1301
                  }
1302
                """, SpacesVocab.SPACES_GRAPH, NPA.GRAPH, lastProcessed);
6✔
1303
    }
1304

1305
    /**
1306
     * DELETE template for non-admin (leaf-tier) RoleInstantiations whose source
1307
     * nanopub was invalidated. Identified as {@code gen:RoleInstantiation} rows
1308
     * lacking the admin-pinning {@code npa:inverseProperty gen:hasAdmin} triple.
1309
     * No flag is set; leaf-tier removals are recoverable on the next cycle.
1310
     */
1311
    static String leafTierInvalidationDelete(IRI graph, long lastProcessed) {
1312
        return String.format("""
84✔
1313
                PREFIX npa: <%1$s>
1314
                PREFIX gen: <%2$s>
1315
                DELETE { GRAPH <%3$s> {
1316
                  ?ri ?p ?o .
1317
                } }
1318
                WHERE {
1319
                  GRAPH <%3$s> {
1320
                    ?ri a gen:RoleInstantiation ;
1321
                        npa:viaNanopub ?np .
1322
                    FILTER NOT EXISTS { ?ri npa:inverseProperty gen:hasAdmin }
1323
                    ?ri ?p ?o .
1324
                  }
1325
                  GRAPH <%4$s> {
1326
                    ?inv a npa:Invalidation ;
1327
                         npa:invalidates ?np ;
1328
                         npa:viaNanopub  ?invNp .
1329
                  }
1330
                  GRAPH <%5$s> {
1331
                    ?invNp npa:hasLoadNumber ?ln .
1332
                    FILTER (?ln > %6$d)
1333
                  }
1334
                }
1335
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
1336
                SpacesVocab.SPACES_GRAPH, NPA.GRAPH, lastProcessed);
6✔
1337
    }
1338

1339
    /**
1340
     * WHERE clause shared by the sub-space invalidation ASK precheck and the
1341
     * matching DELETE. Identifies validated {@code npa:SubSpaceDeclaration} rows
1342
     * in the space-state graph whose {@code npa:viaNanopub} equals the target of
1343
     * an {@code npa:Invalidation} that landed in {@code (lastProcessed, ∞)}.
1344
     */
1345
    static String subSpaceInvalidationCheckWhere(IRI graph, long lastProcessed) {
1346
        return String.format("""
60✔
1347
                  GRAPH <%1$s> {
1348
                    ?d a npa:SubSpaceDeclaration ;
1349
                       npa:viaNanopub ?np .
1350
                  }
1351
                  GRAPH <%2$s> {
1352
                    ?inv a npa:Invalidation ;
1353
                         npa:invalidates ?np ;
1354
                         npa:viaNanopub  ?invNp .
1355
                  }
1356
                  GRAPH <%3$s> {
1357
                    ?invNp npa:hasLoadNumber ?ln .
1358
                    FILTER (?ln > %4$d)
1359
                  }
1360
                """, graph, SpacesVocab.SPACES_GRAPH, NPA.GRAPH, lastProcessed);
6✔
1361
    }
1362

1363
    /**
1364
     * DELETE template for validated {@code npa:SubSpaceDeclaration} rows whose
1365
     * source nanopub was invalidated. Removes the per-declaration row by subject;
1366
     * the convenience direct triples ({@code <child> npa:isSubSpaceOf <parent>}
1367
     * and inverse) are left sticky and cleaned by the next periodic full rebuild
1368
     * (same staleness policy as admin-RI invalidation — see {@code
1369
     * doc/design-space-repositories.md} on the structural-rebuild flag).
1370
     */
1371
    static String subSpaceInvalidationDelete(IRI graph, long lastProcessed) {
1372
        return String.format("""
63✔
1373
                PREFIX npa: <%1$s>
1374
                PREFIX gen: <%2$s>
1375
                DELETE { GRAPH <%3$s> {
1376
                  ?d ?p ?o .
1377
                } }
1378
                WHERE {
1379
                  GRAPH <%3$s> { ?d ?p ?o . }
1380
                %4$s
1381
                }
1382
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
1383
                subSpaceInvalidationCheckWhere(graph, lastProcessed));
6✔
1384
    }
1385

1386
    /**
1387
     * DELETE template for validated {@code npa:MaintainedResourceDeclaration} rows
1388
     * whose source nanopub was invalidated. Removes the per-declaration row by
1389
     * subject; the convenience direct triples ({@code <r> npa:isMaintainedBy <s>}
1390
     * and inverse) are left sticky and cleaned by the next periodic full rebuild
1391
     * (same staleness policy as sub-space declaration invalidation, but without
1392
     * the structural-rebuild flag — maintained-resource is a leaf relation, no
1393
     * downstream consumers depend on its closure).
1394
     */
1395
    static String maintainedResourceInvalidationDelete(IRI graph, long lastProcessed) {
1396
        return String.format("""
84✔
1397
                PREFIX npa: <%1$s>
1398
                PREFIX gen: <%2$s>
1399
                DELETE { GRAPH <%3$s> {
1400
                  ?d ?p ?o .
1401
                } }
1402
                WHERE {
1403
                  GRAPH <%3$s> {
1404
                    ?d a npa:MaintainedResourceDeclaration ;
1405
                       npa:viaNanopub ?np .
1406
                    ?d ?p ?o .
1407
                  }
1408
                  GRAPH <%4$s> {
1409
                    ?inv a npa:Invalidation ;
1410
                         npa:invalidates ?np ;
1411
                         npa:viaNanopub  ?invNp .
1412
                  }
1413
                  GRAPH <%5$s> {
1414
                    ?invNp npa:hasLoadNumber ?ln .
1415
                    FILTER (?ln > %6$d)
1416
                  }
1417
                }
1418
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
1419
                SpacesVocab.SPACES_GRAPH, NPA.GRAPH, lastProcessed);
6✔
1420
    }
1421

1422
    /** Wraps an ASK by joining the shared prefixes. */
1423
    private boolean wouldInvalidate(IRI graph, long lastProcessed,
1424
                                    boolean adminPinned, String whereClause) {
1425
        // adminPinned is informational only — kept to make call sites read clearly;
1426
        // the WHERE clause already encodes the kind via its own type predicates.
1427
        String ask = String.format("""
×
1428
                PREFIX npa: <%1$s>
1429
                PREFIX gen: <%2$s>
1430
                ASK { %3$s }
1431
                """, NPA.NAMESPACE, GEN.NAMESPACE, whereClause);
1432
        return runAsk(ask);
×
1433
    }
1434

1435
    private boolean runAsk(String sparql) {
1436
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1437
            return conn.prepareBooleanQuery(QueryLanguage.SPARQL, sparql).evaluate();
×
1438
        }
1439
    }
1440

1441
    private void executeUpdate(String sparqlUpdate) {
1442
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1443
            conn.prepareUpdate(QueryLanguage.SPARQL, sparqlUpdate).execute();
×
1444
        }
1445
    }
×
1446

1447
    // ---------------- Mirror step ----------------
1448

1449
    /**
1450
     * Copies trust-approved {@code npa:AccountState} rows from {@code npat:<T>}
1451
     * in the {@code trust} repo into {@code newGraph} in the {@code spaces} repo,
1452
     * inside one spaces-side serializable transaction.
1453
     *
1454
     * @return number of rows mirrored (useful for metrics / logging)
1455
     */
1456
    int mirrorTrustState(String trustStateHash, IRI newGraph) {
1457
        IRI trustStateIri = NPAT.forHash(trustStateHash);
×
1458
        int count = 0;
×
1459
        try (RepositoryConnection trustConn = TripleStore.get().getRepoConnection(TRUST_REPO);
×
1460
             RepositoryConnection spacesConn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1461
            trustConn.begin(IsolationLevels.READ_COMMITTED);
×
1462
            spacesConn.begin(IsolationLevels.SERIALIZABLE);
×
1463
            // Walk rdf:type triples in the trust state's graph; for each AccountState,
1464
            // check status and copy the approved ones verbatim (minus status-specific
1465
            // detail triples, which we don't need for validation).
1466
            try (RepositoryResult<Statement> typeRows = trustConn.getStatements(
×
1467
                    null, RDF.TYPE, NPA_ACCOUNT_STATE, trustStateIri)) {
1468
                while (typeRows.hasNext()) {
×
1469
                    Statement st = typeRows.next();
×
1470
                    if (!(st.getSubject() instanceof IRI accountStateIri)) continue;
×
1471
                    Value status = trustConn.getStatements(accountStateIri, NPA_TRUST_STATUS, null, trustStateIri)
×
1472
                            .stream().findFirst().map(Statement::getObject).orElse(null);
×
1473
                    if (!(status instanceof IRI statusIri) || !APPROVED_SET.contains(statusIri)) continue;
×
1474
                    Value agent = trustConn.getStatements(accountStateIri, NPA_AGENT, null, trustStateIri)
×
1475
                            .stream().findFirst().map(Statement::getObject).orElse(null);
×
1476
                    Value pubkey = trustConn.getStatements(accountStateIri, NPA_PUBKEY, null, trustStateIri)
×
1477
                            .stream().findFirst().map(Statement::getObject).orElse(null);
×
1478
                    if (agent == null || pubkey == null) {
×
1479
                        log.warn("AuthorityResolver.mirror: account {} missing agent or pubkey; skipping",
×
1480
                                accountStateIri);
1481
                        continue;
×
1482
                    }
1483
                    spacesConn.add(accountStateIri, RDF.TYPE, NPA_ACCOUNT_STATE, newGraph);
×
1484
                    spacesConn.add(accountStateIri, NPA_AGENT, agent, newGraph);
×
1485
                    spacesConn.add(accountStateIri, NPA_PUBKEY, pubkey, newGraph);
×
1486
                    spacesConn.add(accountStateIri, NPA_TRUST_STATUS, statusIri, newGraph);
×
1487
                    count++;
×
1488
                }
×
1489
            }
1490
            // Mirror canonical foaf:name triples for approved agents. The trust
1491
            // loader emits one per agent (across approved keys, MAX(ratio) wins).
1492
            // Copying them into the space-state graph means consumers reading
1493
            // ?agent foaf:name ?n inside the state graph hit local data, with no
1494
            // cross-repo SERVICE.
1495
            try (RepositoryResult<Statement> nameRows = trustConn.getStatements(
×
1496
                    null, FOAF.NAME, null, trustStateIri)) {
1497
                while (nameRows.hasNext()) {
×
1498
                    Statement st = nameRows.next();
×
1499
                    spacesConn.add(st.getSubject(), st.getPredicate(), st.getObject(), newGraph);
×
1500
                }
×
1501
            }
1502
            spacesConn.commit();
×
1503
            trustConn.commit();
×
1504
        }
1505
        return count;
×
1506
    }
1507

1508
    // ---------------- Pointer + counter helpers ----------------
1509

1510
    /**
1511
     * Reads the current {@code npa:hasCurrentSpaceState} pointer from the
1512
     * {@code npa:graph} admin graph of the {@code spaces} repo. Returns
1513
     * {@code null} if no pointer exists yet.
1514
     */
1515
    IRI getCurrentSpaceStateGraph() {
1516
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1517
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
1518
                    SpacesVocab.HAS_CURRENT_SPACE_STATE);
1519
            return (v instanceof IRI iri) ? iri : null;
×
1520
        } catch (Exception ex) {
×
1521
            log.warn("AuthorityResolver: failed to read hasCurrentSpaceState pointer: {}", ex.toString());
×
1522
            return null;
×
1523
        }
1524
    }
1525

1526
    long getCurrentLoadCounter() {
1527
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1528
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
1529
                    SpacesVocab.CURRENT_LOAD_COUNTER);
1530
            if (v == null) return 0;
×
1531
            try {
1532
                return Long.parseLong(v.stringValue());
×
1533
            } catch (NumberFormatException ex) {
×
1534
                log.warn("AuthorityResolver: non-numeric currentLoadCounter: {}", v);
×
1535
                return 0;
×
1536
            }
1537
        } catch (Exception ex) {
×
1538
            log.warn("AuthorityResolver: failed to read currentLoadCounter: {}", ex.toString());
×
1539
            return 0;
×
1540
        }
1541
    }
1542

1543
    /**
1544
     * Atomic pointer flip: a single SPARQL {@code DELETE … INSERT … WHERE}
1545
     * replaces the old pointer with the new one in one statement, so readers
1546
     * never see a zero-pointer window.
1547
     */
1548
    void flipPointer(IRI newGraph) {
1549
        String update = String.format("""
×
1550
                DELETE { GRAPH <%s> { <%s> <%s> ?old } }
1551
                INSERT { GRAPH <%s> { <%s> <%s> <%s> } }
1552
                WHERE  { OPTIONAL { GRAPH <%s> { <%s> <%s> ?old } } }
1553
                """,
1554
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.HAS_CURRENT_SPACE_STATE,
1555
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.HAS_CURRENT_SPACE_STATE, newGraph,
1556
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.HAS_CURRENT_SPACE_STATE);
1557
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1558
            conn.begin(IsolationLevels.SERIALIZABLE);
×
1559
            conn.prepareUpdate(QueryLanguage.SPARQL, update).execute();
×
1560
            conn.commit();
×
1561
        }
1562
    }
×
1563

1564
    void writeProcessedUpTo(IRI graph, long loadCounter) {
1565
        String update = String.format("""
×
1566
                DELETE { GRAPH <%s> { <%s> <%s> ?old } }
1567
                INSERT { GRAPH <%s> { <%s> <%s> "%d"^^<http://www.w3.org/2001/XMLSchema#long> } }
1568
                WHERE  { OPTIONAL { GRAPH <%s> { <%s> <%s> ?old } } }
1569
                """,
1570
                graph, graph, SpacesVocab.PROCESSED_UP_TO,
1571
                graph, graph, SpacesVocab.PROCESSED_UP_TO, loadCounter,
×
1572
                graph, graph, SpacesVocab.PROCESSED_UP_TO);
1573
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1574
            conn.begin(IsolationLevels.SERIALIZABLE);
×
1575
            conn.prepareUpdate(QueryLanguage.SPARQL, update).execute();
×
1576
            conn.commit();
×
1577
        }
1578
    }
×
1579

1580
    /**
1581
     * Reads {@code processedUpTo} from the given space-state graph.
1582
     * Returns {@code -1} if absent (graph not fully built yet).
1583
     */
1584
    long readProcessedUpTo(IRI graph) {
1585
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1586
            String query = String.format(
×
1587
                    "SELECT ?n WHERE { GRAPH <%s> { <%s> <%s> ?n } }",
1588
                    graph, graph, SpacesVocab.PROCESSED_UP_TO);
1589
            try (TupleQueryResult r = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) {
×
1590
                if (!r.hasNext()) return -1;
×
1591
                BindingSet b = r.next();
×
1592
                return Long.parseLong(b.getBinding("n").getValue().stringValue());
×
1593
            }
×
1594
        } catch (Exception ex) {
×
1595
            log.warn("AuthorityResolver: failed to read processedUpTo for {}: {}", graph, ex.toString());
×
1596
            return -1;
×
1597
        }
1598
    }
1599

1600
    /**
1601
     * Reads the {@code npa:needsFullRebuild} flag (boolean literal) from
1602
     * {@code npa:graph} in the {@code spaces} repo. Defaults to {@code false}
1603
     * when the triple is absent.
1604
     */
1605
    boolean readNeedsFullRebuild() {
1606
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1607
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
1608
                    SpacesVocab.NEEDS_FULL_REBUILD);
1609
            return v != null && Boolean.parseBoolean(v.stringValue());
×
1610
        } catch (Exception ex) {
×
1611
            log.warn("AuthorityResolver: failed to read needsFullRebuild: {}", ex.toString());
×
1612
            return false;
×
1613
        }
1614
    }
1615

1616
    void setNeedsFullRebuild() {
1617
        writeNeedsFullRebuild(true);
×
1618
    }
×
1619

1620
    void clearNeedsFullRebuild() {
1621
        writeNeedsFullRebuild(false);
×
1622
    }
×
1623

1624
    private void writeNeedsFullRebuild(boolean value) {
1625
        String update = String.format("""
×
1626
                DELETE { GRAPH <%s> { <%s> <%s> ?old } }
1627
                INSERT { GRAPH <%s> { <%s> <%s> "%s"^^<http://www.w3.org/2001/XMLSchema#boolean> } }
1628
                WHERE  { OPTIONAL { GRAPH <%s> { <%s> <%s> ?old } } }
1629
                """,
1630
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.NEEDS_FULL_REBUILD,
1631
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.NEEDS_FULL_REBUILD, value,
×
1632
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.NEEDS_FULL_REBUILD);
1633
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1634
            conn.begin(IsolationLevels.SERIALIZABLE);
×
1635
            conn.prepareUpdate(QueryLanguage.SPARQL, update).execute();
×
1636
            conn.commit();
×
1637
        }
1638
    }
×
1639

1640
    void dropGraph(IRI graph) {
1641
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1642
            conn.begin(IsolationLevels.SERIALIZABLE);
×
1643
            conn.clear(graph);
×
1644
            conn.commit();
×
1645
            log.info("AuthorityResolver: dropped old space-state graph {}", graph);
×
1646
        }
1647
    }
×
1648

1649
    // ---------------- Trust-repo pointer lookup (used by TrustStateRegistry's bootstrap) ----------------
1650

1651
    /**
1652
     * Queries the {@code trust} repo directly for the current trust-state hash.
1653
     * Prefer {@link TrustStateRegistry#getCurrentHash()} in normal operation —
1654
     * this helper exists for tests and diagnostics.
1655
     *
1656
     * @return the current trust-state hash, or empty if none is set
1657
     */
1658
    Optional<String> readTrustRepoCurrentHash() {
1659
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(TRUST_REPO)) {
×
1660
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
1661
                    NPA_HAS_CURRENT_TRUST_STATE);
1662
            if (!(v instanceof IRI iri)) return Optional.empty();
×
1663
            String s = iri.stringValue();
×
1664
            if (!s.startsWith(NPAT.NAMESPACE)) return Optional.empty();
×
1665
            return Optional.of(s.substring(NPAT.NAMESPACE.length()));
×
1666
        } catch (Exception ex) {
×
1667
            log.warn("AuthorityResolver: failed to read trust-repo current pointer: {}", ex.toString());
×
1668
            return Optional.empty();
×
1669
        }
1670
    }
1671

1672
    private static String abbrev(String hash) {
1673
        return hash.length() > 12 ? hash.substring(0, 12) + "…" : hash;
×
1674
    }
1675

1676
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc