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

knowledgepixels / nanopub-query / 27429560429

12 Jun 2026 04:42PM UTC coverage: 59.887% (+0.3%) from 59.604%
27429560429

push

github

web-flow
Merge pull request #119 from knowledgepixels/doc/spaceref-isolation

Per-space-ref authority isolation (design + Phases 0–1)

480 of 896 branches covered (53.57%)

Branch coverage included in aggregate %.

1425 of 2285 relevant lines covered (62.36%)

9.16 hits per line

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

16.29
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.nanopub.vocabulary.NPX;
23
import org.slf4j.Logger;
24
import org.slf4j.LoggerFactory;
25

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

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

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

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

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

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

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

84
    private static AuthorityResolver instance;
85

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

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

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

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

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

118
    // ---------------- Public entry points ----------------
119

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

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

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

205
    // ---------------- Full build ----------------
206

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

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

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

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

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

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

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

260
    // ---------------- Incremental cycle ----------------
261

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

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

324
        writeProcessedUpTo(graph, currentLoadCounter);
×
325

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

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

400
    /**
401
     * Runs the four leaf tiers (attachment/maintainer/member/observer) with
402
     * {@code lastProcessed = -1} so the load-number filter on the candidate
403
     * side admits everything. Dedup filters in the tier templates prevent
404
     * double-insert. Used by the late-arrival sweep.
405
     */
406
    TierInsertedTriples runDownstreamWithoutLoadFilter(IRI graph) {
407
        TierInsertedTriples c = new TierInsertedTriples();
×
408
        // Alias late-arrival: catches alias declarations whose canonical admin grant
409
        // became valid only in this same cycle (the load-number filter on the
410
        // declaration's nanopub would otherwise exclude it). Runs first so the
411
        // attachment / role tiers below see this cycle's fresh npa:sameAsSpace edges.
412
        c.alias = runTierLabeled("alias(late)", graph, aliasAdmitUpdate(graph, -1));
×
413
        // Sub-space late-arrival: catches Mode-B candidates whose primary
414
        // declaration is older than lastProcessed but whose partner just landed.
415
        c.subSpace = runTierLabeled("subspace(late)", graph,
×
416
                subSpaceAdmitUpdate(graph, -1));
×
417
        // Maintained-resource late-arrival: catches declarations that landed
418
        // before the publisher's admin grant became valid in this state.
419
        c.maintainedResource = runTierLabeled("maintained-resource(late)", graph,
×
420
                maintainedResourceAdmitUpdate(graph, -1));
×
421
        // URL-prefix fallback: re-run after the late-arrival sub-space admit so
422
        // any newly-validated children get their fallback edges suppressed (for
423
        // future inserts) and any newly-orphaned children pick up fallback edges.
424
        c.subSpacePrefix = runTierLabeled("subspace-prefix(late)", graph,
×
425
                subSpacePrefixFallbackUpdate(graph));
×
426
        c.attachment = runTierLabeled("attachment(late)", graph,
×
427
                attachmentValidationUpdate(graph, -1));
×
428
        c.maintainer = runTierLabeled("maintainer(late)", graph,
×
429
                nonAdminTierUpdate(graph, -1, GEN.MAINTAINER_ROLE, PUBLISHER_IS_ADMIN));
×
430
        c.member = runTierLabeled("member(admin-pub,late)", graph,
×
431
                nonAdminTierUpdate(graph, -1, GEN.MEMBER_ROLE, PUBLISHER_IS_ADMIN));
×
432
        c.member += runTierLabeled("member(maint-pub,late)", graph,
×
433
                nonAdminTierUpdate(graph, -1,
×
434
                        GEN.MEMBER_ROLE, publisherIsTieredRole(GEN.MAINTAINER_ROLE)));
×
435
        c.observer = runTierLabeled("observer(admin-pub,late)", graph,
×
436
                nonAdminTierUpdate(graph, -1, GEN.OBSERVER_ROLE, PUBLISHER_IS_ADMIN));
×
437
        c.observer += runTierLabeled("observer(maint-pub,late)", graph,
×
438
                nonAdminTierUpdate(graph, -1,
×
439
                        GEN.OBSERVER_ROLE, publisherIsTieredRole(GEN.MAINTAINER_ROLE)));
×
440
        c.observer += runTierLabeled("observer(member-pub,late)", graph,
×
441
                nonAdminTierUpdate(graph, -1,
×
442
                        GEN.OBSERVER_ROLE, publisherIsTieredRole(GEN.MEMBER_ROLE)));
×
443
        c.observer += runTierLabeled("observer(self,late)", graph,
×
444
                nonAdminTierUpdate(graph, -1, GEN.OBSERVER_ROLE, PUBLISHER_IS_SELF));
×
445
        return c;
×
446
    }
447

448
    /**
449
     * Cheap ASK: did any new {@code npa:RoleDeclaration} extraction land in the
450
     * load-number delta {@code (lastProcessed, ∞)}? Used by the late-arrival
451
     * trigger so an RD that arrives in the same cycle as a matching candidate
452
     * still gets validated.
453
     */
454
    boolean newRoleDeclarationsArrived(long lastProcessed) {
455
        String ask = String.format("""
×
456
                PREFIX npa: <%1$s>
457
                ASK {
458
                  GRAPH <%2$s> {
459
                    ?rd a npa:RoleDeclaration ;
460
                        npa:viaNanopub ?np .
461
                  }
462
                  GRAPH <%3$s> {
463
                    ?np npa:hasLoadNumber ?ln .
464
                    FILTER (?ln > %4$d)
465
                  }
466
                }
467
                """, NPA.NAMESPACE, SpacesVocab.SPACES_GRAPH, NPA.GRAPH, lastProcessed);
×
468
        return runAsk(ask);
×
469
    }
470

471
    // ---------------- Tier UPDATE loops ----------------
472

473
    /**
474
     * Per-tier inserted-triple tallies for one build or cycle. Counts the sum
475
     * of {@code (graphSize_after - graphSize_before)} across all iterations of
476
     * each tier's fixed-point INSERT loop — i.e. inserted *triples*, not
477
     * distinct subjects (a single RoleInstantiation insert writes 4–5 triples).
478
     *
479
     * <p>Used internally by the {@link #runIncrementalCycle structuralAdds}
480
     * boolean check (we only care whether any tier inserted at all).
481
     * Not what the log lines report: see {@link TierSubjectTotals} +
482
     * {@link #computeTierSubjectTotals} for the distinct-subject totals
483
     * surfaced to operators.
484
     */
485
    static final class TierInsertedTriples {
×
486
        int admin;
487
        int alias;
488
        int attachment;
489
        int maintainer;
490
        int member;
491
        int observer;
492
        int subSpace;
493
        int subSpacePrefix;
494
        int maintainedResource;
495
    }
496

497
    /**
498
     * Snapshot of distinct-subject totals in a space-state graph at a moment
499
     * in time. Independent of which tier-loop added each subject.
500
     */
501
    record TierSubjectTotals(long adminRIs, long attachmentRAs, long nonAdminRIs) {}
36✔
502

503
    /**
504
     * Runs the five tier loops in order: admin → {@code gen:hasRole} attachment
505
     * validation → maintainer → member → observer. Each loop iterates a SPARQL
506
     * INSERT to fixed point (no new triples added). Returns per-tier counts.
507
     *
508
     * @param graph         target space-state graph
509
     * @param lastProcessed load-number horizon; use {@code -1} for full build
510
     */
511
    TierInsertedTriples runAllTierLoops(IRI graph, long lastProcessed) {
512
        TierInsertedTriples c = new TierInsertedTriples();
×
513
        c.admin = runTierLabeled("admin", graph, adminTierUpdate(graph, lastProcessed));
×
514
        // Alias admit runs after the admin closure has settled (both the authority
515
        // gate and the anti-hijack check read the admin set) and before attachment /
516
        // role tiers (their alias-aware admin lookups consume the npa:sameAsSpace edge
517
        // this pass emits). See issue #113.
518
        c.alias = runTierLabeled("alias", graph, aliasAdmitUpdate(graph, lastProcessed));
×
519
        // Sub-space admit runs after admin closure has settled (Mode A + Mode B both
520
        // need the admin set). Independent of role tiers — order between subspace
521
        // and attachment / maintainer / member / observer doesn't matter.
522
        c.subSpace = runTierLabeled("subspace", graph, subSpaceAdmitUpdate(graph, lastProcessed));
×
523
        // Maintained-resource admit also depends only on the admin closure. Single
524
        // Mode A: publisher must be admin of the maintaining space. No co-declaration
525
        // partner, no URL-prefix fallback.
526
        c.maintainedResource = runTierLabeled("maintained-resource", graph,
×
527
                maintainedResourceAdmitUpdate(graph, lastProcessed));
×
528
        // URL-prefix sub-space fallback runs after the explicit-declaration admit
529
        // pass commits so the per-child suppression check sees this cycle's fresh
530
        // validations. No load filter — depends on which Spaces exist, not on
531
        // delta-arrivals; the dedup FILTER NOT EXISTS prevents re-insertion.
532
        c.subSpacePrefix = runTierLabeled("subspace-prefix", graph,
×
533
                subSpacePrefixFallbackUpdate(graph));
×
534
        c.attachment = runTierLabeled("attachment", graph,
×
535
                attachmentValidationUpdate(graph, lastProcessed));
×
536
        c.maintainer = runTierLabeled("maintainer", graph, nonAdminTierUpdate(graph, lastProcessed,
×
537
                GEN.MAINTAINER_ROLE, PUBLISHER_IS_ADMIN));
538
        // Member tier: admin OR maintainer publisher — split into two simpler updates
539
        // so the query planner doesn't struggle with the UNION.
540
        c.member = runTierLabeled("member(admin-pub)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
541
                GEN.MEMBER_ROLE, PUBLISHER_IS_ADMIN));
542
        c.member += runTierLabeled("member(maint-pub)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
543
                GEN.MEMBER_ROLE, publisherIsTieredRole(GEN.MAINTAINER_ROLE)));
×
544
        // Observer tier: self-evidence OR a downward grant from any higher tier.
545
        // ObserverRole is the default tier when a role definition omits an
546
        // explicit subclass (see "Role types" in design-space-repositories.md), so
547
        // most "X assigned Y this role" nanopubs land here. Restricting the tier
548
        // to PUBLISHER_IS_SELF would silently drop those grants. The four
549
        // sub-loops mirror the trust-state's downward-only chain: admin grants
550
        // anything; maintainers and members grant observer; everyone may
551
        // self-attest.
552
        c.observer = runTierLabeled("observer(admin-pub)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
553
                GEN.OBSERVER_ROLE, PUBLISHER_IS_ADMIN));
554
        c.observer += runTierLabeled("observer(maint-pub)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
555
                GEN.OBSERVER_ROLE, publisherIsTieredRole(GEN.MAINTAINER_ROLE)));
×
556
        c.observer += runTierLabeled("observer(member-pub)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
557
                GEN.OBSERVER_ROLE, publisherIsTieredRole(GEN.MEMBER_ROLE)));
×
558
        c.observer += runTierLabeled("observer(self)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
559
                GEN.OBSERVER_ROLE, PUBLISHER_IS_SELF));
560
        return c;
×
561
    }
562

563
    /**
564
     * Builds a publisher constraint requiring the publisher to be a validated holder
565
     * of the given tier's role (maintainer or member) in the target space.
566
     * Owns its own AccountState resolution so ?publisher is bound through the
567
     * targeted (pkh → agent) lookup rather than enumerated.
568
     */
569
    private static String publisherIsTieredRole(IRI tierClass) {
570
        // Re-keyed on the assignment's ref (alias → canonical already resolved by the
571
        // attachment tier). Relies on materialized non-admin RIs carrying their role
572
        // property (npa:regularProperty / npa:inverseProperty) — supplied by the
573
        // enrichment in nonAdminTierUpdate; without it this constraint matched nothing.
574
        return """
×
575
                ?acct a npa:AccountState ;
576
                      npa:pubkey ?pkh ;
577
                      npa:agent  ?publisher .
578
                ?tierRI a gen:RoleInstantiation ;
579
                        npa:forSpaceRef ?spaceRef ;
580
                        npa:forAgent ?publisher .
581
                ?rdT a npa:RoleDeclaration ;
582
                     npa:hasRoleType <%1$s> .
583
                { ?tierRI npa:regularProperty ?predT . ?rdT gen:hasRegularProperty ?predT . }
584
                UNION
585
                { ?tierRI npa:inverseProperty ?predT . ?rdT gen:hasInverseProperty ?predT . }
586
                """.formatted(tierClass);
×
587
    }
588

589
    /** Wraps {@link #runTierLoop} with tier-name context for logs/exceptions. */
590
    private int runTierLabeled(String tier, IRI graph, String sparqlUpdate) {
591
        try {
592
            return runTierLoop(graph, sparqlUpdate);
×
593
        } catch (RuntimeException ex) {
×
594
            logger.error("AuthorityResolver: tier={} failed with SPARQL UPDATE:\n{}\n", tier, sparqlUpdate, ex);
×
595
            throw ex;
×
596
        }
597
    }
598

599
    /**
600
     * Runs a single tier's INSERT to fixed point. Counts rows by probing
601
     * graph size before/after each INSERT; stops when the size doesn't change.
602
     *
603
     * @return total number of triples inserted by this tier across all iterations
604
     */
605
    int runTierLoop(IRI graph, String sparqlUpdate) {
606
        int total = 0;
×
607
        long before = graphSize(graph);
×
608
        while (true) {
609
            // Note: no explicit transaction wrapping here. In tests we observed that
610
            // HTTPRepository's RDF4J-transaction protocol silently no-op'd cross-graph
611
            // SPARQL UPDATEs with UNION sub-patterns inside conn.begin()/commit(),
612
            // while the same UPDATE POSTed directly to /statements applied correctly.
613
            // A bare prepareUpdate().execute() takes the direct /statements path and
614
            // runs the UPDATE atomically per SPARQL 1.1 semantics — which is all we
615
            // need; there's nothing else to commit atomically alongside the UPDATE.
616
            try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
617
                conn.prepareUpdate(QueryLanguage.SPARQL, sparqlUpdate).execute();
×
618
            }
619
            long after = graphSize(graph);
×
620
            long added = after - before;
×
621
            if (added <= 0) break;
×
622
            total += added;
×
623
            before = after;
×
624
        }
×
625
        return total;
×
626
    }
627

628
    private long graphSize(IRI graph) {
629
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
630
            return conn.size(graph);
×
631
        }
632
    }
633

634
    /**
635
     * Distinct-subject totals in the given space-state graph, broken down by
636
     * RoleInstantiation kind (admin-pinned vs not) and RoleAssignment.
637
     * Three SELECT-COUNT queries — cheap, called once per build/cycle for
638
     * the user-facing log line. Returns zeros on failure (logged) so a flaky
639
     * count read can't wedge the cycle.
640
     */
641
    TierSubjectTotals computeTierSubjectTotals(IRI graph) {
642
        long adminRIs       = countDistinctSubjects(graph, """
×
643
                ?ri a gen:RoleInstantiation ; npa:inverseProperty gen:hasAdmin .
644
                """, "ri");
645
        long attachmentRAs  = countDistinctSubjects(graph, """
×
646
                ?ra a gen:RoleAssignment .
647
                """, "ra");
648
        long nonAdminRIs    = countDistinctSubjects(graph, """
×
649
                ?ri a gen:RoleInstantiation .
650
                FILTER NOT EXISTS { ?ri npa:inverseProperty gen:hasAdmin }
651
                """, "ri");
652
        return new TierSubjectTotals(adminRIs, attachmentRAs, nonAdminRIs);
×
653
    }
654

655
    private long countDistinctSubjects(IRI graph, String wherePattern, String varName) {
656
        String query = String.format("""
×
657
                PREFIX npa: <%1$s>
658
                PREFIX gen: <%2$s>
659
                SELECT (COUNT(DISTINCT ?%3$s) AS ?n) WHERE {
660
                  GRAPH <%4$s> {
661
                    %5$s
662
                  }
663
                }
664
                """, NPA.NAMESPACE, GEN.NAMESPACE, varName, graph, wherePattern);
665
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO);
×
666
             TupleQueryResult r = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) {
×
667
            if (!r.hasNext()) return 0;
×
668
            return Long.parseLong(r.next().getBinding("n").getValue().stringValue());
×
669
        } catch (Exception ex) {
×
670
            logger.warn("AuthorityResolver: countDistinctSubjects on {} failed: {}",
×
671
                    graph, ex.toString());
×
672
            return 0;
×
673
        }
674
    }
675

676
    // ---------------- SPARQL templates ----------------
677

678
    /**
679
     * Reusable invalidation filter on a bound nanopub-IRI variable. Pass the bare
680
     * variable name (no leading {@code ?}); e.g. {@code invalidationFilter("np")}
681
     * produces an outer-scoped {@code FILTER NOT EXISTS { GRAPH npa:graph
682
     * { ?_inv_np npx:invalidates ?np . } }}.
683
     *
684
     * <p>Joins on the raw {@code npx:invalidates} triple in {@code npa:graph},
685
     * which {@link com.knowledgepixels.query.NanopubLoader} writes into the
686
     * spaces repo from two complementary directions, making the filter symmetric
687
     * in load order:
688
     * <ul>
689
     *   <li>At the invalidator's own load: the loader's space-repo trigger fires
690
     *       whenever the nanopub has either its own space-relevant extractions
691
     *       OR an {@code npx:invalidates}/{@code npx:retracts}/{@code npx:supersedes}
692
     *       triple, so a pure-retraction nanopub still lands its raw triple plus
693
     *       {@code npa:hasLoadNumber} stamp in {@code npa:graph}.</li>
694
     *   <li>At the invalidated target's load (when the invalidator landed
695
     *       earlier): {@code NanopubLoader.getInvalidatingStatements} reads the
696
     *       triple back from the meta repo and mirrors it into the target's own
697
     *       write to the spaces repo.</li>
698
     * </ul>
699
     *
700
     * <p>The earlier shape joined on a structured {@code npa:Invalidation} entry
701
     * in {@code npa:spacesGraph} that was only emitted on the invalidator's side
702
     * AND only when the invalidated target's meta had already loaded, leaving a
703
     * window where a superseding nanopub loaded before its target produced no
704
     * entry and the stale row was never filtered out (see also the matching
705
     * change in the tier-specific {@code *InvalidationCheckWhere}/{@code
706
     * *InvalidationDelete} templates below).
707
     *
708
     * <p>Important: this filter must be placed OUTSIDE the surrounding
709
     * {@code GRAPH npa:spacesGraph { ... }} block, not nested inside it. When
710
     * nested, RDF4J's planner couples the FILTER NOT EXISTS evaluation into the
711
     * join order (per-row scan multiplied by the candidate set), which we
712
     * measured turning a 39ms query into a 60s+ timeout on the live observer-tier
713
     * data. Outside the GRAPH block, the planner defers the filter until
714
     * {@code ?np}/{@code ?rdNp} are bound and does a targeted index lookup.
715
     *
716
     * <p>Variable names must match {@code [A-Za-z0-9_]+} per SPARQL grammar —
717
     * embedding a {@code ?} inside {@code ?_inv_?np} would yield a parse error.
718
     */
719
    private static String invalidationFilter(String bareVarName) {
720
        return "FILTER NOT EXISTS { GRAPH <" + NPA.GRAPH + "> {"
24✔
721
                + " ?_inv_" + bareVarName
722
                + " <" + NPX.INVALIDATES + "> ?" + bareVarName + " . } }";
723
    }
724

725
    /**
726
     * Admin tier: seed from {@code npadef:...hasRootAdmin} (trusted by construction)
727
     * plus closed-over admin grants; insert any {@code gen:RoleInstantiation} with
728
     * {@code npa:inverseProperty gen:hasAdmin} whose publisher (resolved via mirrored
729
     * trust-approved AccountState) is already in the admin set.
730
     *
731
     * <p>The seed is gated by {@link #spaceRefAliveFilter} (not the per-nanopub
732
     * {@code invalidationFilter("defNp")}): the {@code hasRootAdmin} seed is anchored
733
     * to the root NPID, which is the immutable space-ref identity, so superseding the
734
     * root <em>nanopub</em> with a continuation revision must not strip the seed —
735
     * only retracting every definition of the ref removes it. See issue #110.
736
     */
737
    static String adminTierUpdate(IRI graph, long lastProcessed) {
738
        // Order tuned for RDF4J's evaluator:
739
        //   1. Anchor on the small (seed UNION closed-over) set to bind ?publisher
740
        //      and ?space cheaply.
741
        //   2. Resolve ?pkh from the mirrored AccountState row (?publisher bound).
742
        //   3. Probe instantiations using the now-bound (?space, ?pkh) — targeted
743
        //      lookup, not a full RoleInstantiation scan.
744
        //   4. Load-number filter on bound ?np.
745
        //   5. Dedup at the end.
746
        // Authority is keyed on the space *ref* (npa:forSpaceRef), not the bare Space
747
        // IRI: two refs that share an IRI but have different roots are independent
748
        // domains (see doc/design-spaceref-isolation.md). The instantiation evidence in
749
        // the extraction graph is IRI-keyed (a gen:hasAdmin nanopub names the bare IRI),
750
        // so we project it per-ref by joining each instantiation naming ?space to the
751
        // admin rows of every ref of ?space whose admin set contains the publisher. The
752
        // inserted subject is minted per (?ri, ?spaceRef) so one instantiation validating
753
        // into N refs yields N distinct rows. Transitional: forSpace is still emitted
754
        // alongside forSpaceRef so the not-yet-migrated downstream tiers / read queries
755
        // keep functioning; it is dropped once everything keys on forSpaceRef.
756
        return """
69✔
757
                PREFIX npa:  <%1$s>
758
                PREFIX gen:  <%2$s>
759
                INSERT { GRAPH <%3$s> {
760
                  ?sri a gen:RoleInstantiation ;
761
                       npa:forSpaceRef ?spaceRef ;
762
                       npa:forSpace ?space ;
763
                       npa:inverseProperty gen:hasAdmin ;
764
                       npa:forAgent ?agent ;
765
                       npa:viaNanopub ?np .
766
                } }
767
                WHERE {
768
                  # 1. Anchor: who is already an admin of which space ref?
769
                  {
770
                    # Seed branch: root-admin of a space ref that is still alive
771
                    # (has at least one non-invalidated definition). NOT filtered on
772
                    # ?def's own invalidation — superseding the root nanopub with a
773
                    # continuation revision must keep the seed; only a fully-retracted
774
                    # ref drops it (issue #110).
775
                    GRAPH <%4$s> {
776
                      ?def a npa:SpaceDefinition ;
777
                           npa:forSpaceRef  ?spaceRef ;
778
                           npa:hasRootAdmin ?publisher .
779
                      ?spaceRef npa:spaceIri ?space .
780
                    }
781
                    %7$s
782
                  }
783
                  UNION
784
                  {
785
                    # Closed-over branch: an existing admin of this ref. Recurse on the
786
                    # ref, then resolve its bare IRI to probe the IRI-keyed instantiation.
787
                    GRAPH <%3$s> {
788
                      ?prev a gen:RoleInstantiation ;
789
                            npa:forSpaceRef     ?spaceRef ;
790
                            npa:inverseProperty gen:hasAdmin ;
791
                            npa:forAgent        ?publisher .
792
                    }
793
                    GRAPH <%4$s> {
794
                      ?spaceRef npa:spaceIri ?space .
795
                    }
796
                  }
797
                  # 2. Mirror: resolve ?publisher → ?pkh via the trust-approved row.
798
                  GRAPH <%3$s> {
799
                    ?acct a npa:AccountState ;
800
                          npa:agent  ?publisher ;
801
                          npa:pubkey ?pkh .
802
                  }
803
                  # 3. Targeted instantiation lookup by space + pubkey (IRI-keyed).
804
                  GRAPH <%4$s> {
805
                    ?ri a gen:RoleInstantiation ;
806
                        npa:forSpace        ?space ;
807
                        npa:inverseProperty gen:hasAdmin ;
808
                        npa:forAgent        ?agent ;
809
                        npa:pubkeyHash      ?pkh ;
810
                        npa:viaNanopub      ?np .
811
                  }
812
                  # 3a. Mint the per-ref state subject: (?ri, ?spaceRef) → ?sri.
813
                  BIND(IRI(CONCAT(STR(?ri), "__", ENCODE_FOR_URI(STR(?spaceRef)))) AS ?sri)
814
                  %6$s
815
                  # 4. Load-number filter on bound ?np.
816
                  GRAPH <%8$s> {
817
                    ?np npa:hasLoadNumber ?ln .
818
                    FILTER (?ln > %5$d)
819
                  }
820
                  # 5. Dedup last — keyed on (ref, agent).
821
                  FILTER NOT EXISTS { GRAPH <%3$s> {
822
                    ?existing a gen:RoleInstantiation ;
823
                              npa:forSpaceRef ?spaceRef ;
824
                              npa:forAgent ?agent ;
825
                              npa:inverseProperty gen:hasAdmin .
826
                  } }
827
                }
828
                """.formatted(
3✔
829
                NPA.NAMESPACE,
830
                GEN.NAMESPACE,
831
                graph,
832
                SpacesVocab.SPACES_GRAPH,
833
                lastProcessed,
15✔
834
                invalidationFilter("np"),
12✔
835
                spaceRefAliveFilter(),
18✔
836
                NPA.GRAPH);
837
    }
838

839
    /**
840
     * Seed-survival filter for the admin tier (issue #110). The {@code hasRootAdmin}
841
     * seed is anchored to the root NPID, which is the immutable space-ref identity, so
842
     * it must survive supersession of the root <em>nanopub</em> by a continuation
843
     * revision (a later definition re-roots to the same ref via
844
     * {@code gen:hasRootDefinition} and so carries no {@code hasRootAdmin} of its own).
845
     * The previous {@code invalidationFilter("defNp")} dropped the seed the moment the
846
     * root revision was superseded, leaving the whole admin closure — and everything
847
     * cascading from it — unmaterialized for any space whose definition had ever been
848
     * updated.
849
     *
850
     * <p>Expressed positively: the seed survives iff the space ref still has at least
851
     * one non-invalidated {@link SpacesVocab#SPACE_DEFINITION}. A fully-retracted ref
852
     * (every definition invalidated) has no live definition, so the {@code FILTER
853
     * EXISTS} fails and the seed correctly disappears. Anchored on the already-bound
854
     * {@code ?spaceRef}, so it's a targeted lookup over that ref's (few) definitions.
855
     */
856
    private static String spaceRefAliveFilter() {
857
        return """
33✔
858
                FILTER EXISTS {
859
                  GRAPH <%1$s> {
860
                    ?liveDef a npa:SpaceDefinition ;
861
                             npa:forSpaceRef ?spaceRef ;
862
                             npa:viaNanopub  ?liveNp .
863
                  }
864
                  %2$s
865
                }
866
                """.formatted(SpacesVocab.SPACES_GRAPH, invalidationFilter("liveNp"));
9✔
867
    }
868

869
    /**
870
     * {@code gen:hasRole} attachment validation: an attachment is validated iff its
871
     * publisher is already a validated admin of the target space. Adds
872
     * {@code gen:RoleAssignment} rows to the space-state graph.
873
     */
874
    static String attachmentValidationUpdate(IRI graph, long lastProcessed) {
875
        // Ref-keyed (see doc/design-spaceref-isolation.md). The attachment names a bare
876
        // Space IRI; it is validated per-ref for every ref of that IRI whose admin set
877
        // contains the publisher (direct), or — when the named IRI is an owl:sameAs alias
878
        // — for the canonical ref it maps to (issue #113). ?targetRef is the ref the
879
        // RoleAssignment attaches to; the inserted subject is minted per (?ra, ?targetRef)
880
        // so one attachment validating into N refs yields N distinct rows. forSpace (the
881
        // attached IRI, possibly an alias) is kept so the non-admin tier can probe the
882
        // IRI-keyed instantiations naming it.
883
        return """
69✔
884
                PREFIX npa:  <%1$s>
885
                PREFIX gen:  <%2$s>
886
                INSERT { GRAPH <%3$s> {
887
                  ?ra2 a gen:RoleAssignment ;
888
                       npa:forSpaceRef ?targetRef ;
889
                       npa:forSpace ?space ;
890
                       gen:hasRole  ?role ;
891
                       npa:viaNanopub ?np .
892
                } }
893
                WHERE {
894
                  GRAPH <%4$s> {
895
                    ?ra a gen:RoleAssignment ;
896
                        npa:forSpace ?space ;
897
                        gen:hasRole  ?role ;
898
                        npa:pubkeyHash ?pkh ;
899
                        npa:viaNanopub ?np .
900
                  }
901
                  GRAPH <%7$s> {
902
                    ?np npa:hasLoadNumber ?ln .
903
                    FILTER (?ln > %5$d)
904
                  }
905
                  GRAPH <%3$s> {
906
                    ?acct a npa:AccountState ;
907
                          npa:agent  ?publisher ;
908
                          npa:pubkey ?pkh .
909
                  }
910
                  # Per-ref admin gate. ?targetRef = a ref of ?space the publisher admins
911
                  # (direct), or the canonical ref ?space is an owl:sameAs alias of.
912
                  {
913
                    GRAPH <%4$s> { ?targetRef npa:spaceIri ?space . }
914
                    GRAPH <%3$s> {
915
                      ?adminRI a gen:RoleInstantiation ;
916
                               npa:forSpaceRef ?targetRef ;
917
                               npa:inverseProperty gen:hasAdmin ;
918
                               npa:forAgent ?publisher .
919
                    }
920
                  }
921
                  UNION
922
                  {
923
                    GRAPH <%3$s> {
924
                      ?space npa:sameAsSpace ?targetRef .
925
                      ?adminRI a gen:RoleInstantiation ;
926
                               npa:forSpaceRef ?targetRef ;
927
                               npa:inverseProperty gen:hasAdmin ;
928
                               npa:forAgent ?publisher .
929
                    }
930
                  }
931
                  BIND(IRI(CONCAT(STR(?ra), "__", ENCODE_FOR_URI(STR(?targetRef)))) AS ?ra2)
932
                  %6$s
933
                  FILTER NOT EXISTS { GRAPH <%3$s> {
934
                    ?existing a gen:RoleAssignment ;
935
                              npa:forSpaceRef ?targetRef ;
936
                              gen:hasRole  ?role .
937
                  } }
938
                }
939
                """.formatted(
3✔
940
                NPA.NAMESPACE,
941
                GEN.NAMESPACE,
942
                graph,
943
                SpacesVocab.SPACES_GRAPH,
944
                lastProcessed,
15✔
945
                invalidationFilter("np"),
18✔
946
                NPA.GRAPH);
947
    }
948

949
    /**
950
     * Non-admin tier publisher constraints (inserted as a SPARQL sub-pattern).
951
     * Each constraint owns the AccountState (pkh → agent) lookup so the join
952
     * variable is bound through a targeted pattern. The observer-self variant
953
     * binds {@code npa:agent ?agent} directly — no separate {@code ?publisher}
954
     * variable, no post-join equality filter — which lets the planner anchor
955
     * the AccountState lookup on the already-bound {@code ?agent} instead of
956
     * enumerating all approved publishers and filtering at the end.
957
     */
958
    static final String PUBLISHER_IS_ADMIN = """
959
            ?acct a npa:AccountState ;
960
                  npa:pubkey ?pkh ;
961
                  npa:agent  ?publisher .
962
            # Admin of the assignment's ref. The ref already resolves alias →
963
            # canonical (the attachment tier bound ?spaceRef through the owl:sameAs
964
            # alias edge for aliased IRIs, issue #113), so no alias arm is needed here.
965
            ?adminRI a gen:RoleInstantiation ;
966
                     npa:forSpaceRef ?spaceRef ;
967
                     npa:inverseProperty gen:hasAdmin ;
968
                     npa:forAgent ?publisher .
969
            """;
970

971
    /** Observer self-evidence: the assignee's own pubkey signed the instantiation. */
972
    static final String PUBLISHER_IS_SELF = """
973
            ?acct a npa:AccountState ;
974
                  npa:pubkey ?pkh ;
975
                  npa:agent  ?agent .
976
            """;
977

978
    /**
979
     * Maintainer / Member / Observer tier INSERT. Same shape: find an instantiation
980
     * whose predicate matches a RoleDeclaration of the given tier attached to the
981
     * target space, and whose publisher passes the tier-specific constraint.
982
     */
983
    static String nonAdminTierUpdate(IRI graph, long lastProcessed,
984
                                     IRI tierClass, String publisherConstraint) {
985
        // Order tuned for RDF4J's evaluator (which executes BGPs roughly in order).
986
        // The crucial choice is the *anchor*: instantiation-first plans send the
987
        // planner exploring the full ~thousands of candidate RIs and only filter
988
        // by tier at the very end. Attachment-first anchors on the small set of
989
        // gen:RoleAssignment rows already validated in this space-state graph
990
        // (~hundreds, often zero) and walks outward by bound (?role, ?space).
991
        //
992
        //   1. Anchor on RoleAssignments in this space-state graph (small).
993
        //   2. Match the tier-pinned RoleDeclaration by ?role.
994
        //   3. Pair role-decl direction to instantiation direction in one UNION
995
        //      so only (reg, reg)/(inv, inv) combos are explored.
996
        //   4. Targeted instantiation lookup — (?space, ?pred) are bound.
997
        //   5. Publisher constraint (incl. AccountState resolution).
998
        //   6. Load-number filter on bound ?np.
999
        //   7. Dedup at the end.
1000
        return """
69✔
1001
                PREFIX npa:  <%1$s>
1002
                PREFIX gen:  <%2$s>
1003
                INSERT { GRAPH <%3$s> {
1004
                  ?ri2 a gen:RoleInstantiation ;
1005
                       npa:forSpaceRef ?spaceRef ;
1006
                       npa:forSpace ?space ;
1007
                       npa:forAgent ?agent ;
1008
                       ?dirPred ?pred ;
1009
                       npa:viaNanopub ?np .
1010
                } }
1011
                WHERE {
1012
                  # 1. Anchor: validated attachments in this space-state graph (ref-keyed).
1013
                  GRAPH <%3$s> {
1014
                    ?ra a gen:RoleAssignment ;
1015
                        gen:hasRole     ?role ;
1016
                        npa:forSpaceRef ?spaceRef ;
1017
                        npa:forSpace    ?space .
1018
                  }
1019
                  # 2. Tier-pinned RoleDeclaration (?role bound from the attachment).
1020
                  GRAPH <%4$s> {
1021
                    ?rd a npa:RoleDeclaration ;
1022
                        npa:hasRoleType <%7$s> ;
1023
                        npa:role        ?role ;
1024
                        npa:viaNanopub  ?rdNp .
1025
                    # 3. Pair direction so only matching combos are explored. ?dirPred
1026
                    #    carries the matched direction so the materialized row records the
1027
                    #    role property (read by get-space-members and publisherIsTieredRole).
1028
                    {
1029
                      ?rd gen:hasRegularProperty ?pred .
1030
                      ?ri npa:regularProperty    ?pred .
1031
                      BIND(npa:regularProperty AS ?dirPred)
1032
                    }
1033
                    UNION
1034
                    {
1035
                      ?rd gen:hasInverseProperty ?pred .
1036
                      ?ri npa:inverseProperty    ?pred .
1037
                      BIND(npa:inverseProperty AS ?dirPred)
1038
                    }
1039
                    # 4. Targeted instantiation lookup — (?space, ?pred) bound.
1040
                    ?ri a gen:RoleInstantiation ;
1041
                        npa:forSpace   ?space ;
1042
                        npa:forAgent   ?agent ;
1043
                        npa:pubkeyHash ?pkh ;
1044
                        npa:viaNanopub ?np .
1045
                  }
1046
                  # 5. Publisher constraint (incl. AccountState resolution).
1047
                  GRAPH <%3$s> {
1048
                    %9$s
1049
                  }
1050
                  # 5a. Mint the per-ref state subject: (?ri, ?spaceRef) → ?ri2.
1051
                  BIND(IRI(CONCAT(STR(?ri), "__", ENCODE_FOR_URI(STR(?spaceRef)))) AS ?ri2)
1052
                  # 6. Load-number filter on bound ?np.
1053
                  GRAPH <%10$s> {
1054
                    ?np npa:hasLoadNumber ?ln .
1055
                    FILTER (?ln > %5$d)
1056
                  }
1057
                  # 7. Invalidation filters — outside the GRAPH block so the
1058
                  #    planner defers them until ?rdNp/?np are bound.
1059
                  %8$s
1060
                  %6$s
1061
                  # 8. Dedup last — keyed on (ref, agent, nanopub).
1062
                  FILTER NOT EXISTS { GRAPH <%3$s> {
1063
                    ?existing a gen:RoleInstantiation ;
1064
                              npa:forSpaceRef ?spaceRef ;
1065
                              npa:forAgent ?agent ;
1066
                              npa:viaNanopub ?np .
1067
                  } }
1068
                }
1069
                """.formatted(
3✔
1070
                NPA.NAMESPACE,
1071
                GEN.NAMESPACE,
1072
                graph,
1073
                SpacesVocab.SPACES_GRAPH,
1074
                lastProcessed,
15✔
1075
                invalidationFilter("np"),
27✔
1076
                tierClass,
1077
                invalidationFilter("rdNp"),
30✔
1078
                publisherConstraint,
1079
                NPA.GRAPH);
1080
    }
1081

1082
    /**
1083
     * Sub-space admit pass. Copies validated {@code npa:SubSpaceDeclaration}
1084
     * extraction rows into the space-state graph (preserving the {@code npasub:}
1085
     * subject) and emits convenience {@code <child> npa:isSubSpaceOf <parent>} and
1086
     * {@code <parent> npa:hasSubSpace <child>} direct triples. Two satisfaction
1087
     * modes joined by UNION:
1088
     * <ul>
1089
     *   <li>Mode A — the declaration's publisher is a validated admin of both the
1090
     *       child and the parent space.</li>
1091
     *   <li>Mode B — a different non-invalidated declaration for the same
1092
     *       {@code (child, parent)} pair exists, and the two publishers between
1093
     *       them cover both admin sides (i.e. one of them is admin of the child,
1094
     *       one of them is admin of the parent — possibly the same one twice if
1095
     *       both happen to be admin of both).</li>
1096
     * </ul>
1097
     *
1098
     * <p>Mode-B late-arrival: when only the partner declaration is new in this
1099
     * cycle (the primary is older than {@code lastProcessed}), the load-number
1100
     * filter on {@code ?np} excludes the candidate. The late-arrival sweep
1101
     * ({@link #runDownstreamWithoutLoadFilter}) re-runs this pass without the
1102
     * load filter and catches it.
1103
     */
1104
    static String subSpaceAdmitUpdate(IRI graph, long lastProcessed) {
1105
        return """
69✔
1106
                PREFIX npa: <%1$s>
1107
                PREFIX gen: <%2$s>
1108
                INSERT { GRAPH <%3$s> {
1109
                  ?d a npa:SubSpaceDeclaration ;
1110
                     npa:childSpace  ?child ;
1111
                     npa:parentSpace ?parent ;
1112
                     npa:viaNanopub  ?np .
1113
                  ?childRef  npa:isSubSpaceOf ?parentRef .
1114
                  ?parentRef npa:hasSubSpace  ?childRef  .
1115
                } }
1116
                WHERE {
1117
                  # 1. Anchor: candidate declarations from the extraction graph.
1118
                  GRAPH <%4$s> {
1119
                    ?d a npa:SubSpaceDeclaration ;
1120
                       npa:childSpace  ?child ;
1121
                       npa:parentSpace ?parent ;
1122
                       npa:pubkeyHash  ?pkh ;
1123
                       npa:viaNanopub  ?np .
1124
                  }
1125
                  # 2. Mirror: resolve ?pkh → ?publisher via the trust-approved row.
1126
                  GRAPH <%3$s> {
1127
                    ?acct a npa:AccountState ;
1128
                          npa:pubkey ?pkh ;
1129
                          npa:agent  ?publisher .
1130
                  }
1131
                  # 3. Authority gate, ref-keyed. The edge is emitted ref-to-ref between
1132
                  #    the child ref and parent ref the authorizing admin governs; the
1133
                  #    admin rows' dual-emitted npa:forSpace binds the refs to the child /
1134
                  #    parent IRIs (cross-product when an IRI has several governed refs).
1135
                  {
1136
                    # Mode A — publisher is admin of BOTH a child ref and a parent ref.
1137
                    GRAPH <%3$s> {
1138
                      ?riC a gen:RoleInstantiation ;
1139
                           npa:inverseProperty gen:hasAdmin ;
1140
                           npa:forSpace ?child ;
1141
                           npa:forSpaceRef ?childRef ;
1142
                           npa:forAgent ?publisher .
1143
                      ?riP a gen:RoleInstantiation ;
1144
                           npa:inverseProperty gen:hasAdmin ;
1145
                           npa:forSpace ?parent ;
1146
                           npa:forSpaceRef ?parentRef ;
1147
                           npa:forAgent ?publisher .
1148
                    }
1149
                  }
1150
                  UNION
1151
                  {
1152
                    # Mode B — co-declaration whose publisher covers the side this
1153
                    # one's publisher doesn't. Between {publisher, publisher2},
1154
                    # both admin sides must be covered.
1155
                    GRAPH <%4$s> {
1156
                      ?d2 a npa:SubSpaceDeclaration ;
1157
                          npa:childSpace  ?child ;
1158
                          npa:parentSpace ?parent ;
1159
                          npa:pubkeyHash  ?pkh2 ;
1160
                          npa:viaNanopub  ?np2 .
1161
                      FILTER (?np2 != ?np)
1162
                    }
1163
                    %8$s
1164
                    GRAPH <%3$s> {
1165
                      ?acct2 a npa:AccountState ;
1166
                             npa:pubkey ?pkh2 ;
1167
                             npa:agent  ?publisher2 .
1168
                      ?riA a gen:RoleInstantiation ;
1169
                           npa:inverseProperty gen:hasAdmin ;
1170
                           npa:forSpace ?child ;
1171
                           npa:forSpaceRef ?childRef .
1172
                      { ?riA npa:forAgent ?publisher } UNION { ?riA npa:forAgent ?publisher2 }
1173
                      ?riB a gen:RoleInstantiation ;
1174
                           npa:inverseProperty gen:hasAdmin ;
1175
                           npa:forSpace ?parent ;
1176
                           npa:forSpaceRef ?parentRef .
1177
                      { ?riB npa:forAgent ?publisher } UNION { ?riB npa:forAgent ?publisher2 }
1178
                    }
1179
                  }
1180
                  # 4. Invalidation filter on the primary declaration's nanopub.
1181
                  %6$s
1182
                  # 5. Load-number filter on bound ?np.
1183
                  GRAPH <%7$s> {
1184
                    ?np npa:hasLoadNumber ?ln .
1185
                    FILTER (?ln > %5$d)
1186
                  }
1187
                  # 6. Dedup last — on the emitted ref-to-ref edge.
1188
                  FILTER NOT EXISTS { GRAPH <%3$s> {
1189
                    ?childRef npa:isSubSpaceOf ?parentRef .
1190
                  } }
1191
                }
1192
                """.formatted(
3✔
1193
                NPA.NAMESPACE,
1194
                GEN.NAMESPACE,
1195
                graph,
1196
                SpacesVocab.SPACES_GRAPH,
1197
                lastProcessed,
15✔
1198
                invalidationFilter("np"),
27✔
1199
                NPA.GRAPH,
1200
                invalidationFilter("np2"));
6✔
1201
    }
1202

1203
    /**
1204
     * Maintained-resource admit pass. Copies validated
1205
     * {@code npa:MaintainedResourceDeclaration} extraction rows into the space-state
1206
     * graph (preserving the {@code npamrd:} subject) and emits convenience
1207
     * {@code <r> npa:isMaintainedBy <s>} and {@code <s> npa:hasMaintainedResource <r>}
1208
     * direct triples. Single satisfaction mode:
1209
     * <ul>
1210
     *   <li>Mode A — the declaration's publisher is a validated admin of the
1211
     *       maintaining space.</li>
1212
     * </ul>
1213
     *
1214
     * <p>No Mode B because only one space is involved; the two-sides-must-be-covered
1215
     * concern that drives sub-space Mode B doesn't apply. Late-arrival is still
1216
     * possible (declaration lands before the publisher's admin grant becomes valid):
1217
     * the load-number filter on {@code ?np} excludes the candidate, and the
1218
     * late-arrival sweep ({@link #runDownstreamWithoutLoadFilter}) re-runs this pass
1219
     * without the load filter and catches it.
1220
     */
1221
    static String maintainedResourceAdmitUpdate(IRI graph, long lastProcessed) {
1222
        return """
69✔
1223
                PREFIX npa: <%1$s>
1224
                PREFIX gen: <%2$s>
1225
                INSERT { GRAPH <%3$s> {
1226
                  ?d a npa:MaintainedResourceDeclaration ;
1227
                     npa:resourceIri     ?r ;
1228
                     npa:maintainerSpace ?s ;
1229
                     npa:viaNanopub      ?np .
1230
                  ?r npa:isMaintainedBy        ?sRef .
1231
                  ?sRef npa:hasMaintainedResource ?r .
1232
                } }
1233
                WHERE {
1234
                  # 1. Anchor: candidate declarations from the extraction graph.
1235
                  GRAPH <%4$s> {
1236
                    ?d a npa:MaintainedResourceDeclaration ;
1237
                       npa:resourceIri     ?r ;
1238
                       npa:maintainerSpace ?s ;
1239
                       npa:pubkeyHash      ?pkh ;
1240
                       npa:viaNanopub      ?np .
1241
                  }
1242
                  # 2. Mirror: resolve ?pkh → ?publisher via the trust-approved row.
1243
                  GRAPH <%3$s> {
1244
                    ?acct a npa:AccountState ;
1245
                          npa:pubkey ?pkh ;
1246
                          npa:agent  ?publisher .
1247
                    # 3. Authority gate (Mode A only): publisher is admin of a ref of the
1248
                    #    maintaining space. ?sRef = that ref (resource → ref edge).
1249
                    ?riA a gen:RoleInstantiation ;
1250
                         npa:inverseProperty gen:hasAdmin ;
1251
                         npa:forSpace ?s ;
1252
                         npa:forSpaceRef ?sRef ;
1253
                         npa:forAgent ?publisher .
1254
                  }
1255
                  # 4. Invalidation filter on the declaration's nanopub.
1256
                  %6$s
1257
                  # 5. Load-number filter on bound ?np.
1258
                  GRAPH <%7$s> {
1259
                    ?np npa:hasLoadNumber ?ln .
1260
                    FILTER (?ln > %5$d)
1261
                  }
1262
                  # 6. Dedup last — on the emitted resource → ref edge.
1263
                  FILTER NOT EXISTS { GRAPH <%3$s> {
1264
                    ?r npa:isMaintainedBy ?sRef .
1265
                  } }
1266
                }
1267
                """.formatted(
3✔
1268
                NPA.NAMESPACE,
1269
                GEN.NAMESPACE,
1270
                graph,
1271
                SpacesVocab.SPACES_GRAPH,
1272
                lastProcessed,
15✔
1273
                invalidationFilter("np"),
18✔
1274
                NPA.GRAPH);
1275
    }
1276

1277
    /**
1278
     * Space-alias admit pass (issue #113). Copies validated
1279
     * {@code npa:SpaceAliasDeclaration} extraction rows into the space-state graph
1280
     * (preserving the {@code npaalias:} subject) and emits the directional
1281
     * {@code <alias> npa:sameAsSpace <canonical>} edge consumed by the alias-aware
1282
     * admin-authority lookups in {@link #attachmentValidationUpdate},
1283
     * {@link #PUBLISHER_IS_ADMIN}, and {@link #publisherIsTieredRole}.
1284
     *
1285
     * <p>Two gates, both read against the (already-settled) admin closure in the
1286
     * space-state graph:
1287
     * <ul>
1288
     *   <li><b>Authority</b> — the declaration's publisher (resolved via the mirrored
1289
     *       trust-approved {@code AccountState}) is a validated admin of the
1290
     *       <em>canonical</em> space. The alias is declared inside the canonical
1291
     *       space's own {@code gen:Space} nanopub, so this is the same evidence rule
1292
     *       as a {@code gen:hasRole} attachment.</li>
1293
     *   <li><b>Anti-hijack</b> — the alias must not be an independently-governed live
1294
     *       space: it must have no admin who is not also an admin of the canonical
1295
     *       space ({@code admins(alias) ⊆ admins(canonical)}). The common rename case
1296
     *       (the alias's own definition was superseded, so it has no live admin
1297
     *       closure) passes trivially; an attacker publishing
1298
     *       {@code <evil> owl:sameAs <activeSpace>} is rejected because the active
1299
     *       space has admins not in evil's set.</li>
1300
     * </ul>
1301
     *
1302
     * <p>Late-arrival: when the canonical admin grant only becomes valid in the same
1303
     * cycle as the declaration, the load-number filter on {@code ?np} excludes the
1304
     * candidate; the late-arrival sweep ({@link #runDownstreamWithoutLoadFilter})
1305
     * re-runs this pass without the load filter and catches it.
1306
     */
1307
    static String aliasAdmitUpdate(IRI graph, long lastProcessed) {
1308
        // Ref-keyed (see doc/design-spaceref-isolation.md). The declaration names bare
1309
        // canonical/alias IRIs. It is admitted per canonical *ref* whose admin set
1310
        // contains the publisher; the emitted edge is ref-valued on the canonical side
1311
        // (<alias> npa:sameAsSpace <canonicalRef>), which is what the alias-aware admin
1312
        // lookups in the attachment tier consume. Anti-hijack compares the alias IRI's
1313
        // admins against that specific canonical ref's admins — strictly tighter than the
1314
        // old bare-IRI form.
1315
        return """
69✔
1316
                PREFIX npa: <%1$s>
1317
                PREFIX gen: <%2$s>
1318
                INSERT { GRAPH <%3$s> {
1319
                  ?d a npa:SpaceAliasDeclaration ;
1320
                     npa:canonicalSpace ?canonical ;
1321
                     npa:aliasSpace     ?alias ;
1322
                     npa:viaNanopub     ?np .
1323
                  ?alias npa:sameAsSpace ?canonRef .
1324
                } }
1325
                WHERE {
1326
                  # 1. Anchor: candidate alias declarations from the extraction graph.
1327
                  GRAPH <%4$s> {
1328
                    ?d a npa:SpaceAliasDeclaration ;
1329
                       npa:canonicalSpace ?canonical ;
1330
                       npa:aliasSpace     ?alias ;
1331
                       npa:pubkeyHash     ?pkh ;
1332
                       npa:viaNanopub     ?np .
1333
                  }
1334
                  # 2. Authority gate per canonical ref: ?canonRef is a ref of ?canonical
1335
                  #    whose admin set contains the declaration's publisher.
1336
                  GRAPH <%4$s> { ?canonRef npa:spaceIri ?canonical . }
1337
                  GRAPH <%3$s> {
1338
                    ?acct a npa:AccountState ;
1339
                          npa:pubkey ?pkh ;
1340
                          npa:agent  ?publisher .
1341
                    ?adminRI a gen:RoleInstantiation ;
1342
                             npa:inverseProperty gen:hasAdmin ;
1343
                             npa:forSpaceRef ?canonRef ;
1344
                             npa:forAgent ?publisher .
1345
                  }
1346
                  # 3. Anti-hijack: the alias IRI must have no admin who is not also an
1347
                  #    admin of this canonical ref (admins(alias) ⊆ admins(canonRef)).
1348
                  FILTER NOT EXISTS {
1349
                    GRAPH <%3$s> {
1350
                      ?aliasAdmin a gen:RoleInstantiation ;
1351
                                  npa:inverseProperty gen:hasAdmin ;
1352
                                  npa:forSpace ?alias ;
1353
                                  npa:forAgent ?otherAgent .
1354
                    }
1355
                    FILTER NOT EXISTS {
1356
                      GRAPH <%3$s> {
1357
                        ?canonAdmin a gen:RoleInstantiation ;
1358
                                    npa:inverseProperty gen:hasAdmin ;
1359
                                    npa:forSpaceRef ?canonRef ;
1360
                                    npa:forAgent ?otherAgent .
1361
                      }
1362
                    }
1363
                  }
1364
                  # 4. Invalidation filter on the declaration's nanopub.
1365
                  %6$s
1366
                  # 5. Load-number filter on bound ?np.
1367
                  GRAPH <%7$s> {
1368
                    ?np npa:hasLoadNumber ?ln .
1369
                    FILTER (?ln > %5$d)
1370
                  }
1371
                  # 6. Dedup last — on the emitted (alias, canonical ref) edge.
1372
                  FILTER NOT EXISTS { GRAPH <%3$s> {
1373
                    ?alias npa:sameAsSpace ?canonRef .
1374
                  } }
1375
                }
1376
                """.formatted(
3✔
1377
                NPA.NAMESPACE,
1378
                GEN.NAMESPACE,
1379
                graph,
1380
                SpacesVocab.SPACES_GRAPH,
1381
                lastProcessed,
15✔
1382
                invalidationFilter("np"),
18✔
1383
                NPA.GRAPH);
1384
    }
1385

1386
    /**
1387
     * URL-prefix sub-space fallback admit pass. For every pair of {@code SpaceRef}
1388
     * aggregates where the child's {@code npa:hasIdPrefix} matches the parent's
1389
     * {@code npa:spaceIri}, emits convenience {@code <child> npa:isSubSpaceOf <parent>}
1390
     * and {@code <parent> npa:hasSubSpace <child>} direct triples plus a reified
1391
     * {@code npa:DerivedSubSpaceLink} tag carrying {@code npa:derivationKind
1392
     * npa:byUrlPrefix} so consumers can hide derived edges.
1393
     *
1394
     * <p>Per-child suppression: any validated {@code npa:SubSpaceDeclaration} on the
1395
     * child in {@code npass:<…>} suppresses every fallback edge for that child.
1396
     * Suppression checks the validated set (not raw extraction-graph declarations)
1397
     * so an unapproved or in-flight Mode B declaration doesn't silently hide both
1398
     * the URL-prefix fallback and the (still-invalid) explicit relation.
1399
     *
1400
     * <p>Run order: must run after {@link #subSpaceAdmitUpdate} commits in the
1401
     * same cycle so the suppression check sees this cycle's freshly-validated
1402
     * declarations.
1403
     *
1404
     * <p>No load-number filter: the fallback depends on which Spaces exist (parent
1405
     * + child {@code SpaceRef}s), not on which were just added. Always full-scan;
1406
     * the dedup {@code FILTER NOT EXISTS} on the tag IRI prevents re-insertion.
1407
     *
1408
     * <p>No invalidation handling: derived edges have no source nanopub. Two
1409
     * staleness modes: (a) child later gets first validated declaration → old
1410
     * derived edges stay sticky until the next periodic rebuild (same policy as
1411
     * admin-RI invalidation); (b) child loses last validated declaration → the
1412
     * regular fallback pass on the next cycle re-engages, adds derived edges
1413
     * incrementally, no rebuild needed.
1414
     */
1415
    static String subSpacePrefixFallbackUpdate(IRI graph) {
1416
        return """
48✔
1417
                PREFIX npa: <%1$s>
1418
                INSERT { GRAPH <%2$s> {
1419
                  ?childRef  npa:isSubSpaceOf ?parentRef .
1420
                  ?parentRef npa:hasSubSpace  ?childRef  .
1421
                  ?tagIri a npa:DerivedSubSpaceLink ;
1422
                          npa:childSpace     ?child ;
1423
                          npa:parentSpace    ?parent ;
1424
                          npa:derivationKind npa:byUrlPrefix .
1425
                } }
1426
                WHERE {
1427
                  # 1. Anchor: child SpaceRef → its path-prefixes (extracted at load
1428
                  #    time from the Space IRI; see SpacesExtractor.enumerateIdPrefixes).
1429
                  GRAPH <%3$s> {
1430
                    ?childRef  npa:spaceIri    ?child ;
1431
                               npa:hasIdPrefix ?parent .
1432
                    # 2. Parent SpaceRef must exist for the same IRI as the prefix.
1433
                    ?parentRef npa:spaceIri    ?parent .
1434
                  }
1435
                  # 3. Suppress fallback for any child that has a validated declaration
1436
                  #    in this state graph. Per-child IRI, all-or-nothing.
1437
                  FILTER NOT EXISTS {
1438
                    GRAPH <%2$s> {
1439
                      ?d a npa:SubSpaceDeclaration ;
1440
                         npa:childSpace ?child .
1441
                    }
1442
                  }
1443
                  # 4. Mint a deterministic tag IRI per (child ref, parent ref) — the edge
1444
                  #    is emitted ref-to-ref, so the tag and dedup are per ref-pair.
1445
                  BIND(IRI(CONCAT("http://purl.org/nanopub/admin/derivedlink/",
1446
                                  MD5(CONCAT(STR(?childRef), "|", STR(?parentRef))))) AS ?tagIri)
1447
                  # 5. Dedup: don't re-insert if this tag is already present.
1448
                  FILTER NOT EXISTS {
1449
                    GRAPH <%2$s> {
1450
                      ?tagIri a npa:DerivedSubSpaceLink .
1451
                    }
1452
                  }
1453
                }
1454
                """.formatted(
3✔
1455
                NPA.NAMESPACE,
1456
                graph,
1457
                SpacesVocab.SPACES_GRAPH);
1458
    }
1459

1460
    // ---------------- Invalidation templates (incremental cycle) ----------------
1461

1462
    /**
1463
     * WHERE clause shared by the admin-RI invalidation ASK precheck and the
1464
     * matching DELETE. Identifies admin-tier {@code gen:RoleInstantiation} rows
1465
     * in the space-state graph whose {@code npa:viaNanopub} is the target of an
1466
     * {@code npx:invalidates} triple in {@code npa:graph} whose subject nanopub
1467
     * has a load number in {@code (lastProcessed, ∞)}.
1468
     */
1469
    static String adminInvalidationCheckWhere(IRI graph, long lastProcessed) {
1470
        return String.format("""
60✔
1471
                  GRAPH <%1$s> {
1472
                    ?ri a gen:RoleInstantiation ;
1473
                        npa:inverseProperty gen:hasAdmin ;
1474
                        npa:viaNanopub ?np .
1475
                  }
1476
                  GRAPH <%2$s> {
1477
                    ?invNp <%3$s> ?np ;
1478
                           npa:hasLoadNumber ?ln .
1479
                    FILTER (?ln > %4$d)
1480
                  }
1481
                """, graph, NPA.GRAPH, NPX.INVALIDATES, lastProcessed);
6✔
1482
    }
1483

1484
    /** DELETE template for admin-tier RoleInstantiations whose source nanopub was invalidated. */
1485
    static String adminInvalidationDelete(IRI graph, long lastProcessed) {
1486
        return String.format("""
63✔
1487
                PREFIX npa: <%1$s>
1488
                PREFIX gen: <%2$s>
1489
                DELETE { GRAPH <%3$s> {
1490
                  ?ri ?p ?o .
1491
                } }
1492
                WHERE {
1493
                  GRAPH <%3$s> { ?ri ?p ?o . }
1494
                %4$s
1495
                }
1496
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
1497
                adminInvalidationCheckWhere(graph, lastProcessed));
6✔
1498
    }
1499

1500
    /** WHERE clause for RoleAssignment invalidation. */
1501
    static String roleAssignmentInvalidationCheckWhere(IRI graph, long lastProcessed) {
1502
        return String.format("""
60✔
1503
                  GRAPH <%1$s> {
1504
                    ?ra a gen:RoleAssignment ;
1505
                        npa:viaNanopub ?np .
1506
                  }
1507
                  GRAPH <%2$s> {
1508
                    ?invNp <%3$s> ?np ;
1509
                           npa:hasLoadNumber ?ln .
1510
                    FILTER (?ln > %4$d)
1511
                  }
1512
                """, graph, NPA.GRAPH, NPX.INVALIDATES, lastProcessed);
6✔
1513
    }
1514

1515
    /** DELETE template for RoleAssignments whose source nanopub was invalidated. */
1516
    static String roleAssignmentInvalidationDelete(IRI graph, long lastProcessed) {
1517
        return String.format("""
63✔
1518
                PREFIX npa: <%1$s>
1519
                PREFIX gen: <%2$s>
1520
                DELETE { GRAPH <%3$s> {
1521
                  ?ra ?p ?o .
1522
                } }
1523
                WHERE {
1524
                  GRAPH <%3$s> { ?ra ?p ?o . }
1525
                %4$s
1526
                }
1527
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
1528
                roleAssignmentInvalidationCheckWhere(graph, lastProcessed));
6✔
1529
    }
1530

1531
    /**
1532
     * WHERE clause for RoleDeclaration invalidation. ASK-only (no DELETE):
1533
     * RoleDeclarations live in {@code npa:spacesGraph} and aren't materialized
1534
     * into the space-state graph, so there's nothing to remove from the
1535
     * space-state. The ASK still flips {@code npa:needsFullRebuild} because
1536
     * sticky downstream RIs that were derived under the now-invalidated RD
1537
     * need a from-scratch recompute.
1538
     */
1539
    static String roleDeclarationInvalidationCheckWhere(long lastProcessed) {
1540
        return String.format("""
60✔
1541
                  GRAPH <%1$s> {
1542
                    ?rd a npa:RoleDeclaration ;
1543
                        npa:viaNanopub ?np .
1544
                  }
1545
                  GRAPH <%2$s> {
1546
                    ?invNp <%3$s> ?np ;
1547
                           npa:hasLoadNumber ?ln .
1548
                    FILTER (?ln > %4$d)
1549
                  }
1550
                """, SpacesVocab.SPACES_GRAPH, NPA.GRAPH, NPX.INVALIDATES, lastProcessed);
6✔
1551
    }
1552

1553
    /**
1554
     * DELETE template for non-admin (leaf-tier) RoleInstantiations whose source
1555
     * nanopub was invalidated. Identified as {@code gen:RoleInstantiation} rows
1556
     * lacking the admin-pinning {@code npa:inverseProperty gen:hasAdmin} triple.
1557
     * No flag is set; leaf-tier removals are recoverable on the next cycle.
1558
     */
1559
    static String leafTierInvalidationDelete(IRI graph, long lastProcessed) {
1560
        return String.format("""
84✔
1561
                PREFIX npa: <%1$s>
1562
                PREFIX gen: <%2$s>
1563
                DELETE { GRAPH <%3$s> {
1564
                  ?ri ?p ?o .
1565
                } }
1566
                WHERE {
1567
                  GRAPH <%3$s> {
1568
                    ?ri a gen:RoleInstantiation ;
1569
                        npa:viaNanopub ?np .
1570
                    FILTER NOT EXISTS { ?ri npa:inverseProperty gen:hasAdmin }
1571
                    ?ri ?p ?o .
1572
                  }
1573
                  GRAPH <%4$s> {
1574
                    ?invNp <%5$s> ?np ;
1575
                           npa:hasLoadNumber ?ln .
1576
                    FILTER (?ln > %6$d)
1577
                  }
1578
                }
1579
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
1580
                NPA.GRAPH, NPX.INVALIDATES, lastProcessed);
6✔
1581
    }
1582

1583
    /**
1584
     * WHERE clause shared by the sub-space invalidation ASK precheck and the
1585
     * matching DELETE. Identifies validated {@code npa:SubSpaceDeclaration} rows
1586
     * in the space-state graph whose {@code npa:viaNanopub} is the target of an
1587
     * {@code npx:invalidates} triple in {@code npa:graph} whose subject nanopub
1588
     * has a load number in {@code (lastProcessed, ∞)}.
1589
     */
1590
    static String subSpaceInvalidationCheckWhere(IRI graph, long lastProcessed) {
1591
        return String.format("""
60✔
1592
                  GRAPH <%1$s> {
1593
                    ?d a npa:SubSpaceDeclaration ;
1594
                       npa:viaNanopub ?np .
1595
                  }
1596
                  GRAPH <%2$s> {
1597
                    ?invNp <%3$s> ?np ;
1598
                           npa:hasLoadNumber ?ln .
1599
                    FILTER (?ln > %4$d)
1600
                  }
1601
                """, graph, NPA.GRAPH, NPX.INVALIDATES, lastProcessed);
6✔
1602
    }
1603

1604
    /**
1605
     * DELETE template for validated {@code npa:SubSpaceDeclaration} rows whose
1606
     * source nanopub was invalidated. Removes the per-declaration row by subject;
1607
     * the convenience direct triples ({@code <child> npa:isSubSpaceOf <parent>}
1608
     * and inverse) are left sticky and cleaned by the next periodic full rebuild
1609
     * (same staleness policy as admin-RI invalidation — see {@code
1610
     * doc/design-space-repositories.md} on the structural-rebuild flag).
1611
     */
1612
    static String subSpaceInvalidationDelete(IRI graph, long lastProcessed) {
1613
        return String.format("""
63✔
1614
                PREFIX npa: <%1$s>
1615
                PREFIX gen: <%2$s>
1616
                DELETE { GRAPH <%3$s> {
1617
                  ?d ?p ?o .
1618
                } }
1619
                WHERE {
1620
                  GRAPH <%3$s> { ?d ?p ?o . }
1621
                %4$s
1622
                }
1623
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
1624
                subSpaceInvalidationCheckWhere(graph, lastProcessed));
6✔
1625
    }
1626

1627
    /**
1628
     * DELETE template for validated {@code npa:MaintainedResourceDeclaration} rows
1629
     * whose source nanopub was invalidated. Removes the per-declaration row by
1630
     * subject; the convenience direct triples ({@code <r> npa:isMaintainedBy <s>}
1631
     * and inverse) are left sticky and cleaned by the next periodic full rebuild
1632
     * (same staleness policy as sub-space declaration invalidation, but without
1633
     * the structural-rebuild flag — maintained-resource is a leaf relation, no
1634
     * downstream consumers depend on its closure).
1635
     */
1636
    static String maintainedResourceInvalidationDelete(IRI graph, long lastProcessed) {
1637
        return String.format("""
84✔
1638
                PREFIX npa: <%1$s>
1639
                PREFIX gen: <%2$s>
1640
                DELETE { GRAPH <%3$s> {
1641
                  ?d ?p ?o .
1642
                } }
1643
                WHERE {
1644
                  GRAPH <%3$s> {
1645
                    ?d a npa:MaintainedResourceDeclaration ;
1646
                       npa:viaNanopub ?np .
1647
                    ?d ?p ?o .
1648
                  }
1649
                  GRAPH <%4$s> {
1650
                    ?invNp <%5$s> ?np ;
1651
                           npa:hasLoadNumber ?ln .
1652
                    FILTER (?ln > %6$d)
1653
                  }
1654
                }
1655
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
1656
                NPA.GRAPH, NPX.INVALIDATES, lastProcessed);
6✔
1657
    }
1658

1659
    /**
1660
     * WHERE clause shared by the alias invalidation ASK precheck and the matching
1661
     * DELETE. Identifies validated {@code npa:SpaceAliasDeclaration} rows in the
1662
     * space-state graph whose {@code npa:viaNanopub} is the target of an
1663
     * {@code npx:invalidates} triple in {@code npa:graph} whose subject nanopub has a
1664
     * load number in {@code (lastProcessed, ∞)}.
1665
     */
1666
    static String aliasInvalidationCheckWhere(IRI graph, long lastProcessed) {
1667
        return String.format("""
60✔
1668
                  GRAPH <%1$s> {
1669
                    ?d a npa:SpaceAliasDeclaration ;
1670
                       npa:viaNanopub ?np .
1671
                  }
1672
                  GRAPH <%2$s> {
1673
                    ?invNp <%3$s> ?np ;
1674
                           npa:hasLoadNumber ?ln .
1675
                    FILTER (?ln > %4$d)
1676
                  }
1677
                """, graph, NPA.GRAPH, NPX.INVALIDATES, lastProcessed);
6✔
1678
    }
1679

1680
    /**
1681
     * DELETE template for validated {@code npa:SpaceAliasDeclaration} rows whose
1682
     * source nanopub was invalidated. Removes the per-declaration row by subject; the
1683
     * convenience {@code <alias> npa:sameAsSpace <canonical>} edge is left sticky and
1684
     * cleaned by the next periodic full rebuild (same staleness policy as sub-space
1685
     * declaration invalidation — the alias feeds the authority closure, so this kind
1686
     * is structural and flips {@code npa:needsFullRebuild}).
1687
     */
1688
    static String aliasInvalidationDelete(IRI graph, long lastProcessed) {
1689
        return String.format("""
63✔
1690
                PREFIX npa: <%1$s>
1691
                PREFIX gen: <%2$s>
1692
                DELETE { GRAPH <%3$s> {
1693
                  ?d ?p ?o .
1694
                } }
1695
                WHERE {
1696
                  GRAPH <%3$s> { ?d ?p ?o . }
1697
                %4$s
1698
                }
1699
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
1700
                aliasInvalidationCheckWhere(graph, lastProcessed));
6✔
1701
    }
1702

1703
    /** Wraps an ASK by joining the shared prefixes. */
1704
    private boolean wouldInvalidate(IRI graph, long lastProcessed,
1705
                                    boolean adminPinned, String whereClause) {
1706
        // adminPinned is informational only — kept to make call sites read clearly;
1707
        // the WHERE clause already encodes the kind via its own type predicates.
1708
        String ask = String.format("""
×
1709
                PREFIX npa: <%1$s>
1710
                PREFIX gen: <%2$s>
1711
                ASK { %3$s }
1712
                """, NPA.NAMESPACE, GEN.NAMESPACE, whereClause);
1713
        return runAsk(ask);
×
1714
    }
1715

1716
    private boolean runAsk(String sparql) {
1717
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1718
            return conn.prepareBooleanQuery(QueryLanguage.SPARQL, sparql).evaluate();
×
1719
        }
1720
    }
1721

1722
    private void executeUpdate(String sparqlUpdate) {
1723
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1724
            conn.prepareUpdate(QueryLanguage.SPARQL, sparqlUpdate).execute();
×
1725
        }
1726
    }
×
1727

1728
    // ---------------- Mirror step ----------------
1729

1730
    /**
1731
     * Copies trust-approved {@code npa:AccountState} rows from {@code npat:<T>}
1732
     * in the {@code trust} repo into {@code newGraph} in the {@code spaces} repo,
1733
     * inside one spaces-side serializable transaction.
1734
     *
1735
     * @return number of rows mirrored (useful for metrics / logging)
1736
     */
1737
    int mirrorTrustState(String trustStateHash, IRI newGraph) {
1738
        IRI trustStateIri = NPAT.forHash(trustStateHash);
×
1739
        int count = 0;
×
1740
        try (RepositoryConnection trustConn = TripleStore.get().getRepoConnection(TRUST_REPO);
×
1741
             RepositoryConnection spacesConn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1742
            trustConn.begin(IsolationLevels.READ_COMMITTED);
×
1743
            spacesConn.begin(IsolationLevels.SERIALIZABLE);
×
1744
            // Walk rdf:type triples in the trust state's graph; for each AccountState,
1745
            // check status and copy the approved ones verbatim (minus status-specific
1746
            // detail triples, which we don't need for validation).
1747
            try (RepositoryResult<Statement> typeRows = trustConn.getStatements(
×
1748
                    null, RDF.TYPE, NPA_ACCOUNT_STATE, trustStateIri)) {
1749
                while (typeRows.hasNext()) {
×
1750
                    Statement st = typeRows.next();
×
1751
                    if (!(st.getSubject() instanceof IRI accountStateIri)) continue;
×
1752
                    Value status = trustConn.getStatements(accountStateIri, NPA_TRUST_STATUS, null, trustStateIri)
×
1753
                            .stream().findFirst().map(Statement::getObject).orElse(null);
×
1754
                    if (!(status instanceof IRI statusIri) || !APPROVED_SET.contains(statusIri)) continue;
×
1755
                    Value agent = trustConn.getStatements(accountStateIri, NPA_AGENT, null, trustStateIri)
×
1756
                            .stream().findFirst().map(Statement::getObject).orElse(null);
×
1757
                    Value pubkey = trustConn.getStatements(accountStateIri, NPA_PUBKEY, null, trustStateIri)
×
1758
                            .stream().findFirst().map(Statement::getObject).orElse(null);
×
1759
                    if (agent == null || pubkey == null) {
×
1760
                        logger.warn("AuthorityResolver.mirror: account {} missing agent or pubkey; skipping",
×
1761
                                accountStateIri);
1762
                        continue;
×
1763
                    }
1764
                    spacesConn.add(accountStateIri, RDF.TYPE, NPA_ACCOUNT_STATE, newGraph);
×
1765
                    spacesConn.add(accountStateIri, NPA_AGENT, agent, newGraph);
×
1766
                    spacesConn.add(accountStateIri, NPA_PUBKEY, pubkey, newGraph);
×
1767
                    spacesConn.add(accountStateIri, NPA_TRUST_STATUS, statusIri, newGraph);
×
1768
                    count++;
×
1769
                }
×
1770
            }
1771
            // Mirror canonical foaf:name triples for approved agents. The trust
1772
            // loader emits one per agent (across approved keys, MAX(ratio) wins).
1773
            // Copying them into the space-state graph means consumers reading
1774
            // ?agent foaf:name ?n inside the state graph hit local data, with no
1775
            // cross-repo SERVICE.
1776
            try (RepositoryResult<Statement> nameRows = trustConn.getStatements(
×
1777
                    null, FOAF.NAME, null, trustStateIri)) {
1778
                while (nameRows.hasNext()) {
×
1779
                    Statement st = nameRows.next();
×
1780
                    spacesConn.add(st.getSubject(), st.getPredicate(), st.getObject(), newGraph);
×
1781
                }
×
1782
            }
1783
            spacesConn.commit();
×
1784
            trustConn.commit();
×
1785
        }
1786
        return count;
×
1787
    }
1788

1789
    // ---------------- Pointer + counter helpers ----------------
1790

1791
    /**
1792
     * Reads the current {@code npa:hasCurrentSpaceState} pointer from the
1793
     * {@code npa:graph} admin graph of the {@code spaces} repo. Returns
1794
     * {@code null} if no pointer exists yet.
1795
     */
1796
    IRI getCurrentSpaceStateGraph() {
1797
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1798
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
1799
                    SpacesVocab.HAS_CURRENT_SPACE_STATE);
1800
            return (v instanceof IRI iri) ? iri : null;
×
1801
        } catch (Exception ex) {
×
1802
            logger.warn("AuthorityResolver: failed to read hasCurrentSpaceState pointer: {}", ex.toString());
×
1803
            return null;
×
1804
        }
1805
    }
1806

1807
    long getCurrentLoadCounter() {
1808
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1809
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
1810
                    SpacesVocab.CURRENT_LOAD_COUNTER);
1811
            if (v == null) return 0;
×
1812
            try {
1813
                return Long.parseLong(v.stringValue());
×
1814
            } catch (NumberFormatException ex) {
×
1815
                logger.warn("AuthorityResolver: non-numeric currentLoadCounter: {}", v);
×
1816
                return 0;
×
1817
            }
1818
        } catch (Exception ex) {
×
1819
            logger.warn("AuthorityResolver: failed to read currentLoadCounter: {}", ex.toString());
×
1820
            return 0;
×
1821
        }
1822
    }
1823

1824
    /**
1825
     * Atomic pointer flip: a single SPARQL {@code DELETE … INSERT … WHERE}
1826
     * replaces the old pointer with the new one in one statement, so readers
1827
     * never see a zero-pointer window.
1828
     */
1829
    void flipPointer(IRI newGraph) {
1830
        String update = String.format("""
×
1831
                DELETE { GRAPH <%s> { <%s> <%s> ?old } }
1832
                INSERT { GRAPH <%s> { <%s> <%s> <%s> } }
1833
                WHERE  { OPTIONAL { GRAPH <%s> { <%s> <%s> ?old } } }
1834
                """,
1835
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.HAS_CURRENT_SPACE_STATE,
1836
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.HAS_CURRENT_SPACE_STATE, newGraph,
1837
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.HAS_CURRENT_SPACE_STATE);
1838
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1839
            conn.begin(IsolationLevels.SERIALIZABLE);
×
1840
            conn.prepareUpdate(QueryLanguage.SPARQL, update).execute();
×
1841
            conn.commit();
×
1842
        }
1843
    }
×
1844

1845
    void writeProcessedUpTo(IRI graph, long loadCounter) {
1846
        String update = String.format("""
×
1847
                DELETE { GRAPH <%s> { <%s> <%s> ?old } }
1848
                INSERT { GRAPH <%s> { <%s> <%s> "%d"^^<http://www.w3.org/2001/XMLSchema#long> } }
1849
                WHERE  { OPTIONAL { GRAPH <%s> { <%s> <%s> ?old } } }
1850
                """,
1851
                graph, graph, SpacesVocab.PROCESSED_UP_TO,
1852
                graph, graph, SpacesVocab.PROCESSED_UP_TO, loadCounter,
×
1853
                graph, graph, SpacesVocab.PROCESSED_UP_TO);
1854
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1855
            conn.begin(IsolationLevels.SERIALIZABLE);
×
1856
            conn.prepareUpdate(QueryLanguage.SPARQL, update).execute();
×
1857
            conn.commit();
×
1858
        }
1859
    }
×
1860

1861
    /**
1862
     * Reads {@code processedUpTo} from the given space-state graph.
1863
     * Returns {@code -1} if absent (graph not fully built yet).
1864
     */
1865
    long readProcessedUpTo(IRI graph) {
1866
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1867
            String query = String.format(
×
1868
                    "SELECT ?n WHERE { GRAPH <%s> { <%s> <%s> ?n } }",
1869
                    graph, graph, SpacesVocab.PROCESSED_UP_TO);
1870
            try (TupleQueryResult r = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) {
×
1871
                if (!r.hasNext()) return -1;
×
1872
                BindingSet b = r.next();
×
1873
                return Long.parseLong(b.getBinding("n").getValue().stringValue());
×
1874
            }
×
1875
        } catch (Exception ex) {
×
1876
            logger.warn("AuthorityResolver: failed to read processedUpTo for {}: {}", graph, ex.toString());
×
1877
            return -1;
×
1878
        }
1879
    }
1880

1881
    /**
1882
     * Reads the {@code npa:needsFullRebuild} flag (boolean literal) from
1883
     * {@code npa:graph} in the {@code spaces} repo. Defaults to {@code false}
1884
     * when the triple is absent.
1885
     */
1886
    boolean readNeedsFullRebuild() {
1887
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1888
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
1889
                    SpacesVocab.NEEDS_FULL_REBUILD);
1890
            return v != null && Boolean.parseBoolean(v.stringValue());
×
1891
        } catch (Exception ex) {
×
1892
            logger.warn("AuthorityResolver: failed to read needsFullRebuild: {}", ex.toString());
×
1893
            return false;
×
1894
        }
1895
    }
1896

1897
    void setNeedsFullRebuild() {
1898
        writeNeedsFullRebuild(true);
×
1899
    }
×
1900

1901
    void clearNeedsFullRebuild() {
1902
        writeNeedsFullRebuild(false);
×
1903
    }
×
1904

1905
    private void writeNeedsFullRebuild(boolean value) {
1906
        String update = String.format("""
×
1907
                DELETE { GRAPH <%s> { <%s> <%s> ?old } }
1908
                INSERT { GRAPH <%s> { <%s> <%s> "%s"^^<http://www.w3.org/2001/XMLSchema#boolean> } }
1909
                WHERE  { OPTIONAL { GRAPH <%s> { <%s> <%s> ?old } } }
1910
                """,
1911
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.NEEDS_FULL_REBUILD,
1912
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.NEEDS_FULL_REBUILD, value,
×
1913
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.NEEDS_FULL_REBUILD);
1914
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1915
            conn.begin(IsolationLevels.SERIALIZABLE);
×
1916
            conn.prepareUpdate(QueryLanguage.SPARQL, update).execute();
×
1917
            conn.commit();
×
1918
        }
1919
    }
×
1920

1921
    void dropGraph(IRI graph) {
1922
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1923
            conn.begin(IsolationLevels.SERIALIZABLE);
×
1924
            conn.clear(graph);
×
1925
            conn.commit();
×
1926
            logger.info("AuthorityResolver: dropped old space-state graph {}", graph);
×
1927
        }
1928
    }
×
1929

1930
    // ---------------- Trust-repo pointer lookup (used by TrustStateRegistry's bootstrap) ----------------
1931

1932
    /**
1933
     * Queries the {@code trust} repo directly for the current trust-state hash.
1934
     * Prefer {@link TrustStateRegistry#getCurrentHash()} in normal operation —
1935
     * this helper exists for tests and diagnostics.
1936
     *
1937
     * @return the current trust-state hash, or empty if none is set
1938
     */
1939
    Optional<String> readTrustRepoCurrentHash() {
1940
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(TRUST_REPO)) {
×
1941
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
1942
                    NPA_HAS_CURRENT_TRUST_STATE);
1943
            if (!(v instanceof IRI iri)) return Optional.empty();
×
1944
            String s = iri.stringValue();
×
1945
            if (!s.startsWith(NPAT.NAMESPACE)) return Optional.empty();
×
1946
            return Optional.of(s.substring(NPAT.NAMESPACE.length()));
×
1947
        } catch (Exception ex) {
×
1948
            logger.warn("AuthorityResolver: failed to read trust-repo current pointer: {}", ex.toString());
×
1949
            return Optional.empty();
×
1950
        }
1951
    }
1952

1953
    private static String abbrev(String hash) {
1954
        return hash.length() > 12 ? hash.substring(0, 12) + "…" : hash;
×
1955
    }
1956

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