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

knowledgepixels / nanopub-query / 27477022075

13 Jun 2026 07:39PM UTC coverage: 59.887%. Remained the same
27477022075

push

github

web-flow
Merge pull request #120 from knowledgepixels/feat/spaceref-phase1.5-structural-dualemit

fix(spaces): Phase 1.5 — IRI-valued dual-emit on structural-edge tiers

480 of 896 branches covered (53.57%)

Branch coverage included in aggregate %.

1425 of 2285 relevant lines covered (62.36%)

9.2 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-DUAL-EMIT (Phase 4: remove):
754
        // forSpace is still emitted alongside forSpaceRef so the not-yet-migrated
755
        // downstream tiers / pre-ref read queries keep functioning on a mixed-version
756
        // fleet; it is dropped once everything keys on forSpaceRef.
757
        return """
69✔
758
                PREFIX npa:  <%1$s>
759
                PREFIX gen:  <%2$s>
760
                INSERT { GRAPH <%3$s> {
761
                  ?sri a gen:RoleInstantiation ;
762
                       npa:forSpaceRef ?spaceRef ;
763
                       npa:forSpace ?space ;
764
                       npa:inverseProperty gen:hasAdmin ;
765
                       npa:forAgent ?agent ;
766
                       npa:viaNanopub ?np .
767
                } }
768
                WHERE {
769
                  # 1. Anchor: who is already an admin of which space ref?
770
                  {
771
                    # Seed branch: root-admin of a space ref that is still alive
772
                    # (has at least one non-invalidated definition). NOT filtered on
773
                    # ?def's own invalidation — superseding the root nanopub with a
774
                    # continuation revision must keep the seed; only a fully-retracted
775
                    # ref drops it (issue #110).
776
                    GRAPH <%4$s> {
777
                      ?def a npa:SpaceDefinition ;
778
                           npa:forSpaceRef  ?spaceRef ;
779
                           npa:hasRootAdmin ?publisher .
780
                      ?spaceRef npa:spaceIri ?space .
781
                    }
782
                    %7$s
783
                  }
784
                  UNION
785
                  {
786
                    # Closed-over branch: an existing admin of this ref. Recurse on the
787
                    # ref, then resolve its bare IRI to probe the IRI-keyed instantiation.
788
                    GRAPH <%3$s> {
789
                      ?prev a gen:RoleInstantiation ;
790
                            npa:forSpaceRef     ?spaceRef ;
791
                            npa:inverseProperty gen:hasAdmin ;
792
                            npa:forAgent        ?publisher .
793
                    }
794
                    GRAPH <%4$s> {
795
                      ?spaceRef npa:spaceIri ?space .
796
                    }
797
                  }
798
                  # 2. Mirror: resolve ?publisher → ?pkh via the trust-approved row.
799
                  GRAPH <%3$s> {
800
                    ?acct a npa:AccountState ;
801
                          npa:agent  ?publisher ;
802
                          npa:pubkey ?pkh .
803
                  }
804
                  # 3. Targeted instantiation lookup by space + pubkey (IRI-keyed).
805
                  GRAPH <%4$s> {
806
                    ?ri a gen:RoleInstantiation ;
807
                        npa:forSpace        ?space ;
808
                        npa:inverseProperty gen:hasAdmin ;
809
                        npa:forAgent        ?agent ;
810
                        npa:pubkeyHash      ?pkh ;
811
                        npa:viaNanopub      ?np .
812
                  }
813
                  # 3a. Mint the per-ref state subject: (?ri, ?spaceRef) → ?sri.
814
                  BIND(IRI(CONCAT(STR(?ri), "__", ENCODE_FOR_URI(STR(?spaceRef)))) AS ?sri)
815
                  %6$s
816
                  # 4. Load-number filter on bound ?np.
817
                  GRAPH <%8$s> {
818
                    ?np npa:hasLoadNumber ?ln .
819
                    FILTER (?ln > %5$d)
820
                  }
821
                  # 5. Dedup last — keyed on (ref, agent).
822
                  FILTER NOT EXISTS { GRAPH <%3$s> {
823
                    ?existing a gen:RoleInstantiation ;
824
                              npa:forSpaceRef ?spaceRef ;
825
                              npa:forAgent ?agent ;
826
                              npa:inverseProperty gen:hasAdmin .
827
                  } }
828
                }
829
                """.formatted(
3✔
830
                NPA.NAMESPACE,
831
                GEN.NAMESPACE,
832
                graph,
833
                SpacesVocab.SPACES_GRAPH,
834
                lastProcessed,
15✔
835
                invalidationFilter("np"),
12✔
836
                spaceRefAliveFilter(),
18✔
837
                NPA.GRAPH);
838
    }
839

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

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

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

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

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

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

1214
    /**
1215
     * Maintained-resource admit pass. Copies validated
1216
     * {@code npa:MaintainedResourceDeclaration} extraction rows into the space-state
1217
     * graph (preserving the {@code npamrd:} subject) and emits convenience
1218
     * {@code <r> npa:isMaintainedBy <s>} and {@code <s> npa:hasMaintainedResource <r>}
1219
     * direct triples. Single satisfaction mode:
1220
     * <ul>
1221
     *   <li>Mode A — the declaration's publisher is a validated admin of the
1222
     *       maintaining space.</li>
1223
     * </ul>
1224
     *
1225
     * <p>No Mode B because only one space is involved; the two-sides-must-be-covered
1226
     * concern that drives sub-space Mode B doesn't apply. Late-arrival is still
1227
     * possible (declaration lands before the publisher's admin grant becomes valid):
1228
     * the load-number filter on {@code ?np} excludes the candidate, and the
1229
     * late-arrival sweep ({@link #runDownstreamWithoutLoadFilter}) re-runs this pass
1230
     * without the load filter and catches it.
1231
     */
1232
    static String maintainedResourceAdmitUpdate(IRI graph, long lastProcessed) {
1233
        return """
69✔
1234
                PREFIX npa: <%1$s>
1235
                PREFIX gen: <%2$s>
1236
                INSERT { GRAPH <%3$s> {
1237
                  ?d a npa:MaintainedResourceDeclaration ;
1238
                     npa:resourceIri     ?r ;
1239
                     npa:maintainerSpace ?s ;
1240
                     npa:viaNanopub      ?np .
1241
                  ?r npa:isMaintainedBy        ?sRef .
1242
                  ?sRef npa:hasMaintainedResource ?r .
1243
                  # TRANSITIONAL-DUAL-EMIT (Phase 1.5; remove in Phase 4): IRI-valued
1244
                  # maintained-resource edge alongside the resource→ref one, so pre-ref
1245
                  # published queries (e.g. get-view-displays' maintained hop) keep binding
1246
                  # on a mixed-version fleet. This is the edge whose absence broke 1.15.0 —
1247
                  # see doc/report-2026-06-12-mixed-fleet-spaceref-breakage.md.
1248
                  ?r npa:isMaintainedBy        ?s .
1249
                  ?s npa:hasMaintainedResource ?r .
1250
                } }
1251
                WHERE {
1252
                  # 1. Anchor: candidate declarations from the extraction graph.
1253
                  GRAPH <%4$s> {
1254
                    ?d a npa:MaintainedResourceDeclaration ;
1255
                       npa:resourceIri     ?r ;
1256
                       npa:maintainerSpace ?s ;
1257
                       npa:pubkeyHash      ?pkh ;
1258
                       npa:viaNanopub      ?np .
1259
                  }
1260
                  # 2. Mirror: resolve ?pkh → ?publisher via the trust-approved row.
1261
                  GRAPH <%3$s> {
1262
                    ?acct a npa:AccountState ;
1263
                          npa:pubkey ?pkh ;
1264
                          npa:agent  ?publisher .
1265
                    # 3. Authority gate (Mode A only): publisher is admin of a ref of the
1266
                    #    maintaining space. ?sRef = that ref (resource → ref edge).
1267
                    ?riA a gen:RoleInstantiation ;
1268
                         npa:inverseProperty gen:hasAdmin ;
1269
                         npa:forSpace ?s ;
1270
                         npa:forSpaceRef ?sRef ;
1271
                         npa:forAgent ?publisher .
1272
                  }
1273
                  # 4. Invalidation filter on the declaration's nanopub.
1274
                  %6$s
1275
                  # 5. Load-number filter on bound ?np.
1276
                  GRAPH <%7$s> {
1277
                    ?np npa:hasLoadNumber ?ln .
1278
                    FILTER (?ln > %5$d)
1279
                  }
1280
                  # 6. Dedup last — on the emitted resource → ref edge.
1281
                  FILTER NOT EXISTS { GRAPH <%3$s> {
1282
                    ?r npa:isMaintainedBy ?sRef .
1283
                  } }
1284
                }
1285
                """.formatted(
3✔
1286
                NPA.NAMESPACE,
1287
                GEN.NAMESPACE,
1288
                graph,
1289
                SpacesVocab.SPACES_GRAPH,
1290
                lastProcessed,
15✔
1291
                invalidationFilter("np"),
18✔
1292
                NPA.GRAPH);
1293
    }
1294

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

1412
    /**
1413
     * URL-prefix sub-space fallback admit pass. For every pair of {@code SpaceRef}
1414
     * aggregates where the child's {@code npa:hasIdPrefix} matches the parent's
1415
     * {@code npa:spaceIri}, emits convenience {@code <child> npa:isSubSpaceOf <parent>}
1416
     * and {@code <parent> npa:hasSubSpace <child>} direct triples plus a reified
1417
     * {@code npa:DerivedSubSpaceLink} tag carrying {@code npa:derivationKind
1418
     * npa:byUrlPrefix} so consumers can hide derived edges.
1419
     *
1420
     * <p>Per-child suppression: any validated {@code npa:SubSpaceDeclaration} on the
1421
     * child in {@code npass:<…>} suppresses every fallback edge for that child.
1422
     * Suppression checks the validated set (not raw extraction-graph declarations)
1423
     * so an unapproved or in-flight Mode B declaration doesn't silently hide both
1424
     * the URL-prefix fallback and the (still-invalid) explicit relation.
1425
     *
1426
     * <p>Run order: must run after {@link #subSpaceAdmitUpdate} commits in the
1427
     * same cycle so the suppression check sees this cycle's freshly-validated
1428
     * declarations.
1429
     *
1430
     * <p>No load-number filter: the fallback depends on which Spaces exist (parent
1431
     * + child {@code SpaceRef}s), not on which were just added. Always full-scan;
1432
     * the dedup {@code FILTER NOT EXISTS} on the tag IRI prevents re-insertion.
1433
     *
1434
     * <p>No invalidation handling: derived edges have no source nanopub. Two
1435
     * staleness modes: (a) child later gets first validated declaration → old
1436
     * derived edges stay sticky until the next periodic rebuild (same policy as
1437
     * admin-RI invalidation); (b) child loses last validated declaration → the
1438
     * regular fallback pass on the next cycle re-engages, adds derived edges
1439
     * incrementally, no rebuild needed.
1440
     */
1441
    static String subSpacePrefixFallbackUpdate(IRI graph) {
1442
        return """
48✔
1443
                PREFIX npa: <%1$s>
1444
                INSERT { GRAPH <%2$s> {
1445
                  ?childRef  npa:isSubSpaceOf ?parentRef .
1446
                  ?parentRef npa:hasSubSpace  ?childRef  .
1447
                  # TRANSITIONAL-DUAL-EMIT (Phase 1.5; remove in Phase 4): IRI-valued
1448
                  # derived sub-space edge alongside the ref-to-ref one, mirroring the
1449
                  # explicit sub-space pass, so pre-ref published queries keep binding on a
1450
                  # mixed-version fleet. See doc/report-2026-06-12-mixed-fleet-spaceref-breakage.md.
1451
                  ?child  npa:isSubSpaceOf ?parent .
1452
                  ?parent npa:hasSubSpace  ?child  .
1453
                  ?tagIri a npa:DerivedSubSpaceLink ;
1454
                          npa:childSpace     ?child ;
1455
                          npa:parentSpace    ?parent ;
1456
                          npa:derivationKind npa:byUrlPrefix .
1457
                } }
1458
                WHERE {
1459
                  # 1. Anchor: child SpaceRef → its path-prefixes (extracted at load
1460
                  #    time from the Space IRI; see SpacesExtractor.enumerateIdPrefixes).
1461
                  GRAPH <%3$s> {
1462
                    ?childRef  npa:spaceIri    ?child ;
1463
                               npa:hasIdPrefix ?parent .
1464
                    # 2. Parent SpaceRef must exist for the same IRI as the prefix.
1465
                    ?parentRef npa:spaceIri    ?parent .
1466
                  }
1467
                  # 3. Suppress fallback for any child that has a validated declaration
1468
                  #    in this state graph. Per-child IRI, all-or-nothing.
1469
                  FILTER NOT EXISTS {
1470
                    GRAPH <%2$s> {
1471
                      ?d a npa:SubSpaceDeclaration ;
1472
                         npa:childSpace ?child .
1473
                    }
1474
                  }
1475
                  # 4. Mint a deterministic tag IRI per (child ref, parent ref) — the edge
1476
                  #    is emitted ref-to-ref, so the tag and dedup are per ref-pair.
1477
                  BIND(IRI(CONCAT("http://purl.org/nanopub/admin/derivedlink/",
1478
                                  MD5(CONCAT(STR(?childRef), "|", STR(?parentRef))))) AS ?tagIri)
1479
                  # 5. Dedup: don't re-insert if this tag is already present.
1480
                  FILTER NOT EXISTS {
1481
                    GRAPH <%2$s> {
1482
                      ?tagIri a npa:DerivedSubSpaceLink .
1483
                    }
1484
                  }
1485
                }
1486
                """.formatted(
3✔
1487
                NPA.NAMESPACE,
1488
                graph,
1489
                SpacesVocab.SPACES_GRAPH);
1490
    }
1491

1492
    // ---------------- Invalidation templates (incremental cycle) ----------------
1493

1494
    /**
1495
     * WHERE clause shared by the admin-RI invalidation ASK precheck and the
1496
     * matching DELETE. Identifies admin-tier {@code gen:RoleInstantiation} rows
1497
     * in the space-state graph whose {@code npa:viaNanopub} is the target of an
1498
     * {@code npx:invalidates} triple in {@code npa:graph} whose subject nanopub
1499
     * has a load number in {@code (lastProcessed, ∞)}.
1500
     */
1501
    static String adminInvalidationCheckWhere(IRI graph, long lastProcessed) {
1502
        return String.format("""
60✔
1503
                  GRAPH <%1$s> {
1504
                    ?ri a gen:RoleInstantiation ;
1505
                        npa:inverseProperty gen:hasAdmin ;
1506
                        npa:viaNanopub ?np .
1507
                  }
1508
                  GRAPH <%2$s> {
1509
                    ?invNp <%3$s> ?np ;
1510
                           npa:hasLoadNumber ?ln .
1511
                    FILTER (?ln > %4$d)
1512
                  }
1513
                """, graph, NPA.GRAPH, NPX.INVALIDATES, lastProcessed);
6✔
1514
    }
1515

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

1532
    /** WHERE clause for RoleAssignment invalidation. */
1533
    static String roleAssignmentInvalidationCheckWhere(IRI graph, long lastProcessed) {
1534
        return String.format("""
60✔
1535
                  GRAPH <%1$s> {
1536
                    ?ra a gen:RoleAssignment ;
1537
                        npa:viaNanopub ?np .
1538
                  }
1539
                  GRAPH <%2$s> {
1540
                    ?invNp <%3$s> ?np ;
1541
                           npa:hasLoadNumber ?ln .
1542
                    FILTER (?ln > %4$d)
1543
                  }
1544
                """, graph, NPA.GRAPH, NPX.INVALIDATES, lastProcessed);
6✔
1545
    }
1546

1547
    /** DELETE template for RoleAssignments whose source nanopub was invalidated. */
1548
    static String roleAssignmentInvalidationDelete(IRI graph, long lastProcessed) {
1549
        return String.format("""
63✔
1550
                PREFIX npa: <%1$s>
1551
                PREFIX gen: <%2$s>
1552
                DELETE { GRAPH <%3$s> {
1553
                  ?ra ?p ?o .
1554
                } }
1555
                WHERE {
1556
                  GRAPH <%3$s> { ?ra ?p ?o . }
1557
                %4$s
1558
                }
1559
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
1560
                roleAssignmentInvalidationCheckWhere(graph, lastProcessed));
6✔
1561
    }
1562

1563
    /**
1564
     * WHERE clause for RoleDeclaration invalidation. ASK-only (no DELETE):
1565
     * RoleDeclarations live in {@code npa:spacesGraph} and aren't materialized
1566
     * into the space-state graph, so there's nothing to remove from the
1567
     * space-state. The ASK still flips {@code npa:needsFullRebuild} because
1568
     * sticky downstream RIs that were derived under the now-invalidated RD
1569
     * need a from-scratch recompute.
1570
     */
1571
    static String roleDeclarationInvalidationCheckWhere(long lastProcessed) {
1572
        return String.format("""
60✔
1573
                  GRAPH <%1$s> {
1574
                    ?rd a npa:RoleDeclaration ;
1575
                        npa:viaNanopub ?np .
1576
                  }
1577
                  GRAPH <%2$s> {
1578
                    ?invNp <%3$s> ?np ;
1579
                           npa:hasLoadNumber ?ln .
1580
                    FILTER (?ln > %4$d)
1581
                  }
1582
                """, SpacesVocab.SPACES_GRAPH, NPA.GRAPH, NPX.INVALIDATES, lastProcessed);
6✔
1583
    }
1584

1585
    /**
1586
     * DELETE template for non-admin (leaf-tier) RoleInstantiations whose source
1587
     * nanopub was invalidated. Identified as {@code gen:RoleInstantiation} rows
1588
     * lacking the admin-pinning {@code npa:inverseProperty gen:hasAdmin} triple.
1589
     * No flag is set; leaf-tier removals are recoverable on the next cycle.
1590
     */
1591
    static String leafTierInvalidationDelete(IRI graph, long lastProcessed) {
1592
        return String.format("""
84✔
1593
                PREFIX npa: <%1$s>
1594
                PREFIX gen: <%2$s>
1595
                DELETE { GRAPH <%3$s> {
1596
                  ?ri ?p ?o .
1597
                } }
1598
                WHERE {
1599
                  GRAPH <%3$s> {
1600
                    ?ri a gen:RoleInstantiation ;
1601
                        npa:viaNanopub ?np .
1602
                    FILTER NOT EXISTS { ?ri npa:inverseProperty gen:hasAdmin }
1603
                    ?ri ?p ?o .
1604
                  }
1605
                  GRAPH <%4$s> {
1606
                    ?invNp <%5$s> ?np ;
1607
                           npa:hasLoadNumber ?ln .
1608
                    FILTER (?ln > %6$d)
1609
                  }
1610
                }
1611
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
1612
                NPA.GRAPH, NPX.INVALIDATES, lastProcessed);
6✔
1613
    }
1614

1615
    /**
1616
     * WHERE clause shared by the sub-space invalidation ASK precheck and the
1617
     * matching DELETE. Identifies validated {@code npa:SubSpaceDeclaration} rows
1618
     * in the space-state graph whose {@code npa:viaNanopub} is the target of an
1619
     * {@code npx:invalidates} triple in {@code npa:graph} whose subject nanopub
1620
     * has a load number in {@code (lastProcessed, ∞)}.
1621
     */
1622
    static String subSpaceInvalidationCheckWhere(IRI graph, long lastProcessed) {
1623
        return String.format("""
60✔
1624
                  GRAPH <%1$s> {
1625
                    ?d a npa:SubSpaceDeclaration ;
1626
                       npa:viaNanopub ?np .
1627
                  }
1628
                  GRAPH <%2$s> {
1629
                    ?invNp <%3$s> ?np ;
1630
                           npa:hasLoadNumber ?ln .
1631
                    FILTER (?ln > %4$d)
1632
                  }
1633
                """, graph, NPA.GRAPH, NPX.INVALIDATES, lastProcessed);
6✔
1634
    }
1635

1636
    /**
1637
     * DELETE template for validated {@code npa:SubSpaceDeclaration} rows whose
1638
     * source nanopub was invalidated. Removes the per-declaration row by subject;
1639
     * the convenience direct triples ({@code <child> npa:isSubSpaceOf <parent>}
1640
     * and inverse) are left sticky and cleaned by the next periodic full rebuild
1641
     * (same staleness policy as admin-RI invalidation — see {@code
1642
     * doc/design-space-repositories.md} on the structural-rebuild flag).
1643
     */
1644
    static String subSpaceInvalidationDelete(IRI graph, long lastProcessed) {
1645
        return String.format("""
63✔
1646
                PREFIX npa: <%1$s>
1647
                PREFIX gen: <%2$s>
1648
                DELETE { GRAPH <%3$s> {
1649
                  ?d ?p ?o .
1650
                } }
1651
                WHERE {
1652
                  GRAPH <%3$s> { ?d ?p ?o . }
1653
                %4$s
1654
                }
1655
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
1656
                subSpaceInvalidationCheckWhere(graph, lastProcessed));
6✔
1657
    }
1658

1659
    /**
1660
     * DELETE template for validated {@code npa:MaintainedResourceDeclaration} rows
1661
     * whose source nanopub was invalidated. Removes the per-declaration row by
1662
     * subject; the convenience direct triples ({@code <r> npa:isMaintainedBy <s>}
1663
     * and inverse) are left sticky and cleaned by the next periodic full rebuild
1664
     * (same staleness policy as sub-space declaration invalidation, but without
1665
     * the structural-rebuild flag — maintained-resource is a leaf relation, no
1666
     * downstream consumers depend on its closure).
1667
     */
1668
    static String maintainedResourceInvalidationDelete(IRI graph, long lastProcessed) {
1669
        return String.format("""
84✔
1670
                PREFIX npa: <%1$s>
1671
                PREFIX gen: <%2$s>
1672
                DELETE { GRAPH <%3$s> {
1673
                  ?d ?p ?o .
1674
                } }
1675
                WHERE {
1676
                  GRAPH <%3$s> {
1677
                    ?d a npa:MaintainedResourceDeclaration ;
1678
                       npa:viaNanopub ?np .
1679
                    ?d ?p ?o .
1680
                  }
1681
                  GRAPH <%4$s> {
1682
                    ?invNp <%5$s> ?np ;
1683
                           npa:hasLoadNumber ?ln .
1684
                    FILTER (?ln > %6$d)
1685
                  }
1686
                }
1687
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
1688
                NPA.GRAPH, NPX.INVALIDATES, lastProcessed);
6✔
1689
    }
1690

1691
    /**
1692
     * WHERE clause shared by the alias invalidation ASK precheck and the matching
1693
     * DELETE. Identifies validated {@code npa:SpaceAliasDeclaration} rows in the
1694
     * space-state graph whose {@code npa:viaNanopub} is the target of an
1695
     * {@code npx:invalidates} triple in {@code npa:graph} whose subject nanopub has a
1696
     * load number in {@code (lastProcessed, ∞)}.
1697
     */
1698
    static String aliasInvalidationCheckWhere(IRI graph, long lastProcessed) {
1699
        return String.format("""
60✔
1700
                  GRAPH <%1$s> {
1701
                    ?d a npa:SpaceAliasDeclaration ;
1702
                       npa:viaNanopub ?np .
1703
                  }
1704
                  GRAPH <%2$s> {
1705
                    ?invNp <%3$s> ?np ;
1706
                           npa:hasLoadNumber ?ln .
1707
                    FILTER (?ln > %4$d)
1708
                  }
1709
                """, graph, NPA.GRAPH, NPX.INVALIDATES, lastProcessed);
6✔
1710
    }
1711

1712
    /**
1713
     * DELETE template for validated {@code npa:SpaceAliasDeclaration} rows whose
1714
     * source nanopub was invalidated. Removes the per-declaration row by subject; the
1715
     * convenience {@code <alias> npa:sameAsSpace <canonical>} edge is left sticky and
1716
     * cleaned by the next periodic full rebuild (same staleness policy as sub-space
1717
     * declaration invalidation — the alias feeds the authority closure, so this kind
1718
     * is structural and flips {@code npa:needsFullRebuild}).
1719
     */
1720
    static String aliasInvalidationDelete(IRI graph, long lastProcessed) {
1721
        return String.format("""
63✔
1722
                PREFIX npa: <%1$s>
1723
                PREFIX gen: <%2$s>
1724
                DELETE { GRAPH <%3$s> {
1725
                  ?d ?p ?o .
1726
                } }
1727
                WHERE {
1728
                  GRAPH <%3$s> { ?d ?p ?o . }
1729
                %4$s
1730
                }
1731
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
1732
                aliasInvalidationCheckWhere(graph, lastProcessed));
6✔
1733
    }
1734

1735
    /** Wraps an ASK by joining the shared prefixes. */
1736
    private boolean wouldInvalidate(IRI graph, long lastProcessed,
1737
                                    boolean adminPinned, String whereClause) {
1738
        // adminPinned is informational only — kept to make call sites read clearly;
1739
        // the WHERE clause already encodes the kind via its own type predicates.
1740
        String ask = String.format("""
×
1741
                PREFIX npa: <%1$s>
1742
                PREFIX gen: <%2$s>
1743
                ASK { %3$s }
1744
                """, NPA.NAMESPACE, GEN.NAMESPACE, whereClause);
1745
        return runAsk(ask);
×
1746
    }
1747

1748
    private boolean runAsk(String sparql) {
1749
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1750
            return conn.prepareBooleanQuery(QueryLanguage.SPARQL, sparql).evaluate();
×
1751
        }
1752
    }
1753

1754
    private void executeUpdate(String sparqlUpdate) {
1755
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1756
            conn.prepareUpdate(QueryLanguage.SPARQL, sparqlUpdate).execute();
×
1757
        }
1758
    }
×
1759

1760
    // ---------------- Mirror step ----------------
1761

1762
    /**
1763
     * Copies trust-approved {@code npa:AccountState} rows from {@code npat:<T>}
1764
     * in the {@code trust} repo into {@code newGraph} in the {@code spaces} repo,
1765
     * inside one spaces-side serializable transaction.
1766
     *
1767
     * @return number of rows mirrored (useful for metrics / logging)
1768
     */
1769
    int mirrorTrustState(String trustStateHash, IRI newGraph) {
1770
        IRI trustStateIri = NPAT.forHash(trustStateHash);
×
1771
        int count = 0;
×
1772
        try (RepositoryConnection trustConn = TripleStore.get().getRepoConnection(TRUST_REPO);
×
1773
             RepositoryConnection spacesConn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1774
            trustConn.begin(IsolationLevels.READ_COMMITTED);
×
1775
            spacesConn.begin(IsolationLevels.SERIALIZABLE);
×
1776
            // Walk rdf:type triples in the trust state's graph; for each AccountState,
1777
            // check status and copy the approved ones verbatim (minus status-specific
1778
            // detail triples, which we don't need for validation).
1779
            try (RepositoryResult<Statement> typeRows = trustConn.getStatements(
×
1780
                    null, RDF.TYPE, NPA_ACCOUNT_STATE, trustStateIri)) {
1781
                while (typeRows.hasNext()) {
×
1782
                    Statement st = typeRows.next();
×
1783
                    if (!(st.getSubject() instanceof IRI accountStateIri)) continue;
×
1784
                    Value status = trustConn.getStatements(accountStateIri, NPA_TRUST_STATUS, null, trustStateIri)
×
1785
                            .stream().findFirst().map(Statement::getObject).orElse(null);
×
1786
                    if (!(status instanceof IRI statusIri) || !APPROVED_SET.contains(statusIri)) continue;
×
1787
                    Value agent = trustConn.getStatements(accountStateIri, NPA_AGENT, null, trustStateIri)
×
1788
                            .stream().findFirst().map(Statement::getObject).orElse(null);
×
1789
                    Value pubkey = trustConn.getStatements(accountStateIri, NPA_PUBKEY, null, trustStateIri)
×
1790
                            .stream().findFirst().map(Statement::getObject).orElse(null);
×
1791
                    if (agent == null || pubkey == null) {
×
1792
                        logger.warn("AuthorityResolver.mirror: account {} missing agent or pubkey; skipping",
×
1793
                                accountStateIri);
1794
                        continue;
×
1795
                    }
1796
                    spacesConn.add(accountStateIri, RDF.TYPE, NPA_ACCOUNT_STATE, newGraph);
×
1797
                    spacesConn.add(accountStateIri, NPA_AGENT, agent, newGraph);
×
1798
                    spacesConn.add(accountStateIri, NPA_PUBKEY, pubkey, newGraph);
×
1799
                    spacesConn.add(accountStateIri, NPA_TRUST_STATUS, statusIri, newGraph);
×
1800
                    count++;
×
1801
                }
×
1802
            }
1803
            // Mirror canonical foaf:name triples for approved agents. The trust
1804
            // loader emits one per agent (across approved keys, MAX(ratio) wins).
1805
            // Copying them into the space-state graph means consumers reading
1806
            // ?agent foaf:name ?n inside the state graph hit local data, with no
1807
            // cross-repo SERVICE.
1808
            try (RepositoryResult<Statement> nameRows = trustConn.getStatements(
×
1809
                    null, FOAF.NAME, null, trustStateIri)) {
1810
                while (nameRows.hasNext()) {
×
1811
                    Statement st = nameRows.next();
×
1812
                    spacesConn.add(st.getSubject(), st.getPredicate(), st.getObject(), newGraph);
×
1813
                }
×
1814
            }
1815
            spacesConn.commit();
×
1816
            trustConn.commit();
×
1817
        }
1818
        return count;
×
1819
    }
1820

1821
    // ---------------- Pointer + counter helpers ----------------
1822

1823
    /**
1824
     * Reads the current {@code npa:hasCurrentSpaceState} pointer from the
1825
     * {@code npa:graph} admin graph of the {@code spaces} repo. Returns
1826
     * {@code null} if no pointer exists yet.
1827
     */
1828
    IRI getCurrentSpaceStateGraph() {
1829
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1830
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
1831
                    SpacesVocab.HAS_CURRENT_SPACE_STATE);
1832
            return (v instanceof IRI iri) ? iri : null;
×
1833
        } catch (Exception ex) {
×
1834
            logger.warn("AuthorityResolver: failed to read hasCurrentSpaceState pointer: {}", ex.toString());
×
1835
            return null;
×
1836
        }
1837
    }
1838

1839
    long getCurrentLoadCounter() {
1840
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1841
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
1842
                    SpacesVocab.CURRENT_LOAD_COUNTER);
1843
            if (v == null) return 0;
×
1844
            try {
1845
                return Long.parseLong(v.stringValue());
×
1846
            } catch (NumberFormatException ex) {
×
1847
                logger.warn("AuthorityResolver: non-numeric currentLoadCounter: {}", v);
×
1848
                return 0;
×
1849
            }
1850
        } catch (Exception ex) {
×
1851
            logger.warn("AuthorityResolver: failed to read currentLoadCounter: {}", ex.toString());
×
1852
            return 0;
×
1853
        }
1854
    }
1855

1856
    /**
1857
     * Atomic pointer flip: a single SPARQL {@code DELETE … INSERT … WHERE}
1858
     * replaces the old pointer with the new one in one statement, so readers
1859
     * never see a zero-pointer window.
1860
     */
1861
    void flipPointer(IRI newGraph) {
1862
        String update = String.format("""
×
1863
                DELETE { GRAPH <%s> { <%s> <%s> ?old } }
1864
                INSERT { GRAPH <%s> { <%s> <%s> <%s> } }
1865
                WHERE  { OPTIONAL { GRAPH <%s> { <%s> <%s> ?old } } }
1866
                """,
1867
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.HAS_CURRENT_SPACE_STATE,
1868
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.HAS_CURRENT_SPACE_STATE, newGraph,
1869
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.HAS_CURRENT_SPACE_STATE);
1870
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1871
            conn.begin(IsolationLevels.SERIALIZABLE);
×
1872
            conn.prepareUpdate(QueryLanguage.SPARQL, update).execute();
×
1873
            conn.commit();
×
1874
        }
1875
    }
×
1876

1877
    void writeProcessedUpTo(IRI graph, long loadCounter) {
1878
        String update = String.format("""
×
1879
                DELETE { GRAPH <%s> { <%s> <%s> ?old } }
1880
                INSERT { GRAPH <%s> { <%s> <%s> "%d"^^<http://www.w3.org/2001/XMLSchema#long> } }
1881
                WHERE  { OPTIONAL { GRAPH <%s> { <%s> <%s> ?old } } }
1882
                """,
1883
                graph, graph, SpacesVocab.PROCESSED_UP_TO,
1884
                graph, graph, SpacesVocab.PROCESSED_UP_TO, loadCounter,
×
1885
                graph, graph, SpacesVocab.PROCESSED_UP_TO);
1886
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1887
            conn.begin(IsolationLevels.SERIALIZABLE);
×
1888
            conn.prepareUpdate(QueryLanguage.SPARQL, update).execute();
×
1889
            conn.commit();
×
1890
        }
1891
    }
×
1892

1893
    /**
1894
     * Reads {@code processedUpTo} from the given space-state graph.
1895
     * Returns {@code -1} if absent (graph not fully built yet).
1896
     */
1897
    long readProcessedUpTo(IRI graph) {
1898
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1899
            String query = String.format(
×
1900
                    "SELECT ?n WHERE { GRAPH <%s> { <%s> <%s> ?n } }",
1901
                    graph, graph, SpacesVocab.PROCESSED_UP_TO);
1902
            try (TupleQueryResult r = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) {
×
1903
                if (!r.hasNext()) return -1;
×
1904
                BindingSet b = r.next();
×
1905
                return Long.parseLong(b.getBinding("n").getValue().stringValue());
×
1906
            }
×
1907
        } catch (Exception ex) {
×
1908
            logger.warn("AuthorityResolver: failed to read processedUpTo for {}: {}", graph, ex.toString());
×
1909
            return -1;
×
1910
        }
1911
    }
1912

1913
    /**
1914
     * Reads the {@code npa:needsFullRebuild} flag (boolean literal) from
1915
     * {@code npa:graph} in the {@code spaces} repo. Defaults to {@code false}
1916
     * when the triple is absent.
1917
     */
1918
    boolean readNeedsFullRebuild() {
1919
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1920
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
1921
                    SpacesVocab.NEEDS_FULL_REBUILD);
1922
            return v != null && Boolean.parseBoolean(v.stringValue());
×
1923
        } catch (Exception ex) {
×
1924
            logger.warn("AuthorityResolver: failed to read needsFullRebuild: {}", ex.toString());
×
1925
            return false;
×
1926
        }
1927
    }
1928

1929
    void setNeedsFullRebuild() {
1930
        writeNeedsFullRebuild(true);
×
1931
    }
×
1932

1933
    void clearNeedsFullRebuild() {
1934
        writeNeedsFullRebuild(false);
×
1935
    }
×
1936

1937
    private void writeNeedsFullRebuild(boolean value) {
1938
        String update = String.format("""
×
1939
                DELETE { GRAPH <%s> { <%s> <%s> ?old } }
1940
                INSERT { GRAPH <%s> { <%s> <%s> "%s"^^<http://www.w3.org/2001/XMLSchema#boolean> } }
1941
                WHERE  { OPTIONAL { GRAPH <%s> { <%s> <%s> ?old } } }
1942
                """,
1943
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.NEEDS_FULL_REBUILD,
1944
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.NEEDS_FULL_REBUILD, value,
×
1945
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.NEEDS_FULL_REBUILD);
1946
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1947
            conn.begin(IsolationLevels.SERIALIZABLE);
×
1948
            conn.prepareUpdate(QueryLanguage.SPARQL, update).execute();
×
1949
            conn.commit();
×
1950
        }
1951
    }
×
1952

1953
    void dropGraph(IRI graph) {
1954
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
1955
            conn.begin(IsolationLevels.SERIALIZABLE);
×
1956
            conn.clear(graph);
×
1957
            conn.commit();
×
1958
            logger.info("AuthorityResolver: dropped old space-state graph {}", graph);
×
1959
        }
1960
    }
×
1961

1962
    // ---------------- Trust-repo pointer lookup (used by TrustStateRegistry's bootstrap) ----------------
1963

1964
    /**
1965
     * Queries the {@code trust} repo directly for the current trust-state hash.
1966
     * Prefer {@link TrustStateRegistry#getCurrentHash()} in normal operation —
1967
     * this helper exists for tests and diagnostics.
1968
     *
1969
     * @return the current trust-state hash, or empty if none is set
1970
     */
1971
    Optional<String> readTrustRepoCurrentHash() {
1972
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(TRUST_REPO)) {
×
1973
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
1974
                    NPA_HAS_CURRENT_TRUST_STATE);
1975
            if (!(v instanceof IRI iri)) return Optional.empty();
×
1976
            String s = iri.stringValue();
×
1977
            if (!s.startsWith(NPAT.NAMESPACE)) return Optional.empty();
×
1978
            return Optional.of(s.substring(NPAT.NAMESPACE.length()));
×
1979
        } catch (Exception ex) {
×
1980
            logger.warn("AuthorityResolver: failed to read trust-repo current pointer: {}", ex.toString());
×
1981
            return Optional.empty();
×
1982
        }
1983
    }
1984

1985
    private static String abbrev(String hash) {
1986
        return hash.length() > 12 ? hash.substring(0, 12) + "…" : hash;
×
1987
    }
1988

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