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

knowledgepixels / nanopub-query / 28037224309

23 Jun 2026 03:31PM UTC coverage: 61.38%. Remained the same
28037224309

push

github

web-flow
Merge pull request #128 from knowledgepixels/fix/issue-127-stamp-admin-role-tier

fix(spaces): stamp npa:hasRoleType gen:AdminRole on admin RoleInstantiations (#127)

541 of 974 branches covered (55.54%)

Branch coverage included in aggregate %.

1568 of 2462 relevant lines covered (63.69%)

9.6 hits per line

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

19.09
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.presetAttachment
×
245
                + counts.presetAssignmentRef
246
                + counts.attachment + counts.maintainer + counts.member + counts.observer
247
                + counts.subSpace + counts.subSpacePrefix + counts.maintainedResource;
248
        lastFullBuildDurationMs = durationMs;
×
249
        lastProcessedUpToLag = 0L;
×
250
        logger.info("AuthorityResolver: full build complete — graph={} mirrored={} rows loadCounter={} "
×
251
                        + "subjects: adminRIs={} attachmentRAs={} nonAdminRIs={} "
252
                        + "(inserted-triples: admin={} alias={} preset-attachment={} preset-assignment-ref={} attachment={} maintainer={} member={} observer={} "
253
                        + "subspace={} subspace-prefix={} maintained-resource={}) durationMs={}",
254
                newGraph, mirrored, loadCounter,
×
255
                totals.adminRIs(), totals.attachmentRAs(), totals.nonAdminRIs(),
×
256
                counts.admin, counts.alias, counts.presetAttachment, counts.presetAssignmentRef, counts.attachment, counts.maintainer, counts.member, counts.observer,
×
257
                counts.subSpace, counts.subSpacePrefix, counts.maintainedResource,
×
258
                durationMs);
×
259
    }
×
260

261
    // ---------------- Incremental cycle ----------------
262

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

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

329
        writeProcessedUpTo(graph, currentLoadCounter);
×
330

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

351
    /**
352
     * Runs the four invalidation-DELETE / ASK steps. Sets {@code npa:needsFullRebuild}
353
     * when admin-RI, RoleAssignment, or RoleDeclaration invalidations matched (the
354
     * three structural kinds). Leaf-tier RI deletes don't set the flag.
355
     *
356
     * @return true iff at least one structural kind was invalidated
357
     */
358
    boolean applyInvalidations(IRI graph, long lastProcessed) {
359
        boolean structural = false;
×
360
        if (wouldInvalidate(graph, lastProcessed, /*adminPinned=*/ true,
×
361
                            adminInvalidationCheckWhere(graph, lastProcessed))) {
×
362
            executeUpdate(adminInvalidationDelete(graph, lastProcessed));
×
363
            structural = true;
×
364
        }
365
        if (wouldInvalidate(graph, lastProcessed, /*adminPinned=*/ false,
×
366
                            roleAssignmentInvalidationCheckWhere(graph, lastProcessed))) {
×
367
            executeUpdate(roleAssignmentInvalidationDelete(graph, lastProcessed));
×
368
            structural = true;
×
369
        }
370
        // Role-declaration invalidation is deliberately NOT acted on (see
371
        // nonAdminTierUpdate): a role assignment is governed by the admin-validated
372
        // attachment, not by the declaration author's later supersession/retraction, so
373
        // an invalidated RD neither deletes rows nor triggers a rebuild.
374
        // Sub-space declarations are structural — invalidating one (Mode A) or one
375
        // of two co-declarations (Mode B) changes the validated parent/child
376
        // topology. The DELETE removes the per-declaration row; the convenience
377
        // direct triples are left sticky and cleaned on the next periodic rebuild.
378
        if (wouldInvalidate(graph, lastProcessed, /*adminPinned=*/ false,
×
379
                            subSpaceInvalidationCheckWhere(graph, lastProcessed))) {
×
380
            executeUpdate(subSpaceInvalidationDelete(graph, lastProcessed));
×
381
            structural = true;
×
382
        }
383
        // Space-alias declarations are structural — invalidating one removes an
384
        // owl:sameAs edge that feeds the admin-authority closure (issue #113). The
385
        // DELETE removes the per-declaration row; the convenience npa:sameAsSpace edge
386
        // is left sticky and cleaned on the next periodic rebuild (same policy as
387
        // sub-space declarations).
388
        if (wouldInvalidate(graph, lastProcessed, /*adminPinned=*/ false,
×
389
                            aliasInvalidationCheckWhere(graph, lastProcessed))) {
×
390
            executeUpdate(aliasInvalidationDelete(graph, lastProcessed));
×
391
            structural = true;
×
392
        }
393
        // Preset-derived RoleAssignment removal (issue #302). NOT npx:invalidates: a newer
394
        // admin-authored same-(preset,resource) assignment supersedes by dct:created (a
395
        // gen:DeactivatedPresetAssignment, or any newer assignment that is no longer active).
396
        // Structural — sticky downstream non-admin RIs derived through a removed attachment
397
        // are bounded by the periodic full rebuild. The DELETE is scoped by
398
        // npa:derivedFromPreset so directly-published gen:hasRole attachments are never
399
        // touched; the §4.3 re-INSERT re-materializes only currently-active pairs in the same
400
        // cycle. See doc/design-preset-role-materialization.md §4.4.
401
        if (wouldInvalidate(graph, lastProcessed, /*adminPinned=*/ false,
×
402
                            presetDeactivationCheckWhere(graph, lastProcessed))) {
×
403
            executeUpdate(presetDeactivationDelete(graph, lastProcessed));
×
404
            structural = true;
×
405
        }
406
        // Leaf-tier RI deletes — no flag.
407
        executeUpdate(leafTierInvalidationDelete(graph, lastProcessed));
×
408
        // Ref-scoped preset-assignment listing stamps whose assignment nanopub was
409
        // hard-retracted (issue #122) — no flag (display leaf, nothing downstream).
410
        executeUpdate(presetAssignmentRefInvalidationDelete(graph, lastProcessed));
×
411
        // Maintained-resource declaration deletes — no flag (leaf relation, no
412
        // downstream caches to bound).
413
        executeUpdate(maintainedResourceInvalidationDelete(graph, lastProcessed));
×
414
        if (structural) setNeedsFullRebuild();
×
415
        return structural;
×
416
    }
417

418
    /**
419
     * Runs the four leaf tiers (attachment/maintainer/member/observer) with
420
     * {@code lastProcessed = -1} so the load-number filter on the candidate
421
     * side admits everything. Dedup filters in the tier templates prevent
422
     * double-insert. Used by the late-arrival sweep.
423
     */
424
    TierInsertedTriples runDownstreamWithoutLoadFilter(IRI graph) {
425
        TierInsertedTriples c = new TierInsertedTriples();
×
426
        // Alias late-arrival: catches alias declarations whose canonical admin grant
427
        // became valid only in this same cycle (the load-number filter on the
428
        // declaration's nanopub would otherwise exclude it). Runs first so the
429
        // attachment / role tiers below see this cycle's fresh npa:sameAsSpace edges.
430
        c.alias = runTierLabeled("alias(late)", graph, aliasAdmitUpdate(graph, -1));
×
431
        // Sub-space late-arrival: catches Mode-B candidates whose primary
432
        // declaration is older than lastProcessed but whose partner just landed.
433
        c.subSpace = runTierLabeled("subspace(late)", graph,
×
434
                subSpaceAdmitUpdate(graph, -1));
×
435
        // Maintained-resource late-arrival: catches declarations that landed
436
        // before the publisher's admin grant became valid in this state.
437
        c.maintainedResource = runTierLabeled("maintained-resource(late)", graph,
×
438
                maintainedResourceAdmitUpdate(graph, -1));
×
439
        // URL-prefix fallback: re-run after the late-arrival sub-space admit so
440
        // any newly-validated children get their fallback edges suppressed (for
441
        // future inserts) and any newly-orphaned children pick up fallback edges.
442
        c.subSpacePrefix = runTierLabeled("subspace-prefix(late)", graph,
×
443
                subSpacePrefixFallbackUpdate(graph));
×
444
        // Preset-attachment late-arrival: catches assignments whose preset declaration or
445
        // admin grant only became valid in this same cycle. Runs before attachment(late)
446
        // so the non-admin late tiers below see this cycle's fresh preset-derived RAs.
447
        c.presetAttachment = runTierLabeled("preset-attachment(late)", graph,
×
448
                presetAttachmentValidationUpdate(graph, -1));
×
449
        // Ref-scoped preset-assignment late stamp: catches assignments whose authorizing
450
        // admin grant only became valid this cycle (the load filter would skip the older
451
        // assignment nanopub). Mirrors the preset-attachment late sweep above.
452
        c.presetAssignmentRef = runTierLabeled("preset-assignment-ref(late)", graph,
×
453
                presetAssignmentRefStampUpdate(graph, -1));
×
454
        c.attachment = runTierLabeled("attachment(late)", graph,
×
455
                attachmentValidationUpdate(graph, -1));
×
456
        c.maintainer = runTierLabeled("maintainer(late)", graph,
×
457
                nonAdminTierUpdate(graph, -1, GEN.MAINTAINER_ROLE, PUBLISHER_IS_ADMIN));
×
458
        c.member = runTierLabeled("member(admin-pub,late)", graph,
×
459
                nonAdminTierUpdate(graph, -1, GEN.MEMBER_ROLE, PUBLISHER_IS_ADMIN));
×
460
        c.member += runTierLabeled("member(maint-pub,late)", graph,
×
461
                nonAdminTierUpdate(graph, -1,
×
462
                        GEN.MEMBER_ROLE, publisherIsTieredRole(GEN.MAINTAINER_ROLE)));
×
463
        c.observer = runTierLabeled("observer(admin-pub,late)", graph,
×
464
                nonAdminTierUpdate(graph, -1, GEN.OBSERVER_ROLE, PUBLISHER_IS_ADMIN));
×
465
        c.observer += runTierLabeled("observer(maint-pub,late)", graph,
×
466
                nonAdminTierUpdate(graph, -1,
×
467
                        GEN.OBSERVER_ROLE, publisherIsTieredRole(GEN.MAINTAINER_ROLE)));
×
468
        c.observer += runTierLabeled("observer(member-pub,late)", graph,
×
469
                nonAdminTierUpdate(graph, -1,
×
470
                        GEN.OBSERVER_ROLE, publisherIsTieredRole(GEN.MEMBER_ROLE)));
×
471
        c.observer += runTierLabeled("observer(self,late)", graph,
×
472
                nonAdminTierUpdate(graph, -1, GEN.OBSERVER_ROLE, PUBLISHER_IS_SELF));
×
473
        return c;
×
474
    }
475

476
    /**
477
     * Cheap ASK: did any new {@code npa:RoleDeclaration} extraction land in the
478
     * load-number delta {@code (lastProcessed, ∞)}? Used by the late-arrival
479
     * trigger so an RD that arrives in the same cycle as a matching candidate
480
     * still gets validated.
481
     */
482
    boolean newRoleDeclarationsArrived(long lastProcessed) {
483
        String ask = String.format("""
×
484
                PREFIX npa: <%1$s>
485
                ASK {
486
                  GRAPH <%2$s> {
487
                    ?rd a npa:RoleDeclaration ;
488
                        npa:viaNanopub ?np .
489
                  }
490
                  GRAPH <%3$s> {
491
                    ?np npa:hasLoadNumber ?ln .
492
                    FILTER (?ln > %4$d)
493
                  }
494
                }
495
                """, NPA.NAMESPACE, SpacesVocab.SPACES_GRAPH, NPA.GRAPH, lastProcessed);
×
496
        return runAsk(ask);
×
497
    }
498

499
    /**
500
     * Cheap ASK: did any new {@code npa:PresetAssignment} or {@code npa:PresetDeclaration}
501
     * extraction land in the load-number delta {@code (lastProcessed, ∞)}? Drives the
502
     * late-arrival re-run so a preset assignment that arrives in the same cycle as its
503
     * declaration (or admin grant) still materializes, and so an arriving newer assignment
504
     * triggers the deactivation/latest-wins re-evaluation.
505
     */
506
    boolean newPresetAssignmentsArrived(long lastProcessed) {
507
        String ask = String.format("""
×
508
                PREFIX npa: <%1$s>
509
                ASK {
510
                  GRAPH <%2$s> {
511
                    ?x a ?t ;
512
                       npa:viaNanopub ?np .
513
                    FILTER (?t = npa:PresetAssignment || ?t = npa:PresetDeclaration)
514
                  }
515
                  GRAPH <%3$s> {
516
                    ?np npa:hasLoadNumber ?ln .
517
                    FILTER (?ln > %4$d)
518
                  }
519
                }
520
                """, NPA.NAMESPACE, SpacesVocab.SPACES_GRAPH, NPA.GRAPH, lastProcessed);
×
521
        return runAsk(ask);
×
522
    }
523

524
    // ---------------- Tier UPDATE loops ----------------
525

526
    /**
527
     * Per-tier inserted-triple tallies for one build or cycle. Counts the sum
528
     * of {@code (graphSize_after - graphSize_before)} across all iterations of
529
     * each tier's fixed-point INSERT loop — i.e. inserted *triples*, not
530
     * distinct subjects (a single RoleInstantiation insert writes 4–5 triples).
531
     *
532
     * <p>Used internally by the {@link #runIncrementalCycle structuralAdds}
533
     * boolean check (we only care whether any tier inserted at all).
534
     * Not what the log lines report: see {@link TierSubjectTotals} +
535
     * {@link #computeTierSubjectTotals} for the distinct-subject totals
536
     * surfaced to operators.
537
     */
538
    static final class TierInsertedTriples {
×
539
        int admin;
540
        int alias;
541
        int presetAttachment;
542
        int presetAssignmentRef;
543
        int attachment;
544
        int maintainer;
545
        int member;
546
        int observer;
547
        int subSpace;
548
        int subSpacePrefix;
549
        int maintainedResource;
550
    }
551

552
    /**
553
     * Snapshot of distinct-subject totals in a space-state graph at a moment
554
     * in time. Independent of which tier-loop added each subject.
555
     */
556
    record TierSubjectTotals(long adminRIs, long attachmentRAs, long nonAdminRIs) {}
36✔
557

558
    /**
559
     * Runs the five tier loops in order: admin → {@code gen:hasRole} attachment
560
     * validation → maintainer → member → observer. Each loop iterates a SPARQL
561
     * INSERT to fixed point (no new triples added). Returns per-tier counts.
562
     *
563
     * @param graph         target space-state graph
564
     * @param lastProcessed load-number horizon; use {@code -1} for full build
565
     */
566
    TierInsertedTriples runAllTierLoops(IRI graph, long lastProcessed) {
567
        TierInsertedTriples c = new TierInsertedTriples();
×
568
        c.admin = runTierLabeled("admin", graph, adminTierUpdate(graph, lastProcessed));
×
569
        // Alias admit runs after the admin closure has settled (both the authority
570
        // gate and the anti-hijack check read the admin set) and before attachment /
571
        // role tiers (their alias-aware admin lookups consume the npa:sameAsSpace edge
572
        // this pass emits). See issue #113.
573
        c.alias = runTierLabeled("alias", graph, aliasAdmitUpdate(graph, lastProcessed));
×
574
        // Sub-space admit runs after admin closure has settled (Mode A + Mode B both
575
        // need the admin set). Independent of role tiers — order between subspace
576
        // and attachment / maintainer / member / observer doesn't matter.
577
        c.subSpace = runTierLabeled("subspace", graph, subSpaceAdmitUpdate(graph, lastProcessed));
×
578
        // Maintained-resource admit also depends only on the admin closure. Single
579
        // Mode A: publisher must be admin of the maintaining space. No co-declaration
580
        // partner, no URL-prefix fallback.
581
        c.maintainedResource = runTierLabeled("maintained-resource", graph,
×
582
                maintainedResourceAdmitUpdate(graph, lastProcessed));
×
583
        // URL-prefix sub-space fallback runs after the explicit-declaration admit
584
        // pass commits so the per-child suppression check sees this cycle's fresh
585
        // validations. No load filter — depends on which Spaces exist, not on
586
        // delta-arrivals; the dedup FILTER NOT EXISTS prevents re-insertion.
587
        c.subSpacePrefix = runTierLabeled("subspace-prefix", graph,
×
588
                subSpacePrefixFallbackUpdate(graph));
×
589
        // Preset-attachment runs immediately before the regular attachment tier so the
590
        // gen:RoleAssignment rows it materializes (from active, admin-authored preset
591
        // assignments) are picked up by the downstream non-admin tiers in the same pass,
592
        // exactly like directly-published attachments. See
593
        // doc/design-preset-role-materialization.md.
594
        c.presetAttachment = runTierLabeled("preset-attachment", graph,
×
595
                presetAttachmentValidationUpdate(graph, lastProcessed));
×
596
        // Ref-scoped preset-assignment listing stamp (issue #122). Display-only leaf —
597
        // independent of the role tiers and of structuralAdds; order doesn't matter.
598
        c.presetAssignmentRef = runTierLabeled("preset-assignment-ref", graph,
×
599
                presetAssignmentRefStampUpdate(graph, lastProcessed));
×
600
        c.attachment = runTierLabeled("attachment", graph,
×
601
                attachmentValidationUpdate(graph, lastProcessed));
×
602
        c.maintainer = runTierLabeled("maintainer", graph, nonAdminTierUpdate(graph, lastProcessed,
×
603
                GEN.MAINTAINER_ROLE, PUBLISHER_IS_ADMIN));
604
        // Member tier: admin OR maintainer publisher — split into two simpler updates
605
        // so the query planner doesn't struggle with the UNION.
606
        c.member = runTierLabeled("member(admin-pub)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
607
                GEN.MEMBER_ROLE, PUBLISHER_IS_ADMIN));
608
        c.member += runTierLabeled("member(maint-pub)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
609
                GEN.MEMBER_ROLE, publisherIsTieredRole(GEN.MAINTAINER_ROLE)));
×
610
        // Observer tier: self-evidence OR a downward grant from any higher tier.
611
        // ObserverRole is the default tier when a role definition omits an
612
        // explicit subclass (see "Role types" in design-space-repositories.md), so
613
        // most "X assigned Y this role" nanopubs land here. Restricting the tier
614
        // to PUBLISHER_IS_SELF would silently drop those grants. The four
615
        // sub-loops mirror the trust-state's downward-only chain: admin grants
616
        // anything; maintainers and members grant observer; everyone may
617
        // self-attest.
618
        c.observer = runTierLabeled("observer(admin-pub)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
619
                GEN.OBSERVER_ROLE, PUBLISHER_IS_ADMIN));
620
        c.observer += runTierLabeled("observer(maint-pub)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
621
                GEN.OBSERVER_ROLE, publisherIsTieredRole(GEN.MAINTAINER_ROLE)));
×
622
        c.observer += runTierLabeled("observer(member-pub)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
623
                GEN.OBSERVER_ROLE, publisherIsTieredRole(GEN.MEMBER_ROLE)));
×
624
        c.observer += runTierLabeled("observer(self)", graph, nonAdminTierUpdate(graph, lastProcessed,
×
625
                GEN.OBSERVER_ROLE, PUBLISHER_IS_SELF));
626
        return c;
×
627
    }
628

629
    /**
630
     * Builds a publisher constraint requiring the publisher to be a validated holder
631
     * of the given tier's role (maintainer or member) in the target space.
632
     * Owns its own AccountState resolution so ?publisher is bound through the
633
     * targeted (pkh → agent) lookup rather than enumerated.
634
     */
635
    private static String publisherIsTieredRole(IRI tierClass) {
636
        // Re-keyed on the assignment's ref (alias → canonical already resolved by the
637
        // attachment tier). Relies on materialized non-admin RIs carrying their role
638
        // property (npa:regularProperty / npa:inverseProperty) — supplied by the
639
        // enrichment in nonAdminTierUpdate; without it this constraint matched nothing.
640
        return """
×
641
                ?acct a npa:AccountState ;
642
                      npa:pubkey ?pkh ;
643
                      npa:agent  ?publisher .
644
                ?tierRI a gen:RoleInstantiation ;
645
                        npa:forSpaceRef ?spaceRef ;
646
                        npa:forAgent ?publisher .
647
                ?rdT a npa:RoleDeclaration ;
648
                     npa:hasRoleType <%1$s> .
649
                { ?tierRI npa:regularProperty ?predT . ?rdT gen:hasRegularProperty ?predT . }
650
                UNION
651
                { ?tierRI npa:inverseProperty ?predT . ?rdT gen:hasInverseProperty ?predT . }
652
                """.formatted(tierClass);
×
653
    }
654

655
    /** Wraps {@link #runTierLoop} with tier-name context for logs/exceptions. */
656
    private int runTierLabeled(String tier, IRI graph, String sparqlUpdate) {
657
        try {
658
            return runTierLoop(graph, sparqlUpdate);
×
659
        } catch (RuntimeException ex) {
×
660
            logger.error("AuthorityResolver: tier={} failed with SPARQL UPDATE:\n{}\n", tier, sparqlUpdate, ex);
×
661
            throw ex;
×
662
        }
663
    }
664

665
    /**
666
     * Runs a single tier's INSERT to fixed point. Counts rows by probing
667
     * graph size before/after each INSERT; stops when the size doesn't change.
668
     *
669
     * @return total number of triples inserted by this tier across all iterations
670
     */
671
    int runTierLoop(IRI graph, String sparqlUpdate) {
672
        int total = 0;
×
673
        long before = graphSize(graph);
×
674
        while (true) {
675
            // Note: no explicit transaction wrapping here. In tests we observed that
676
            // HTTPRepository's RDF4J-transaction protocol silently no-op'd cross-graph
677
            // SPARQL UPDATEs with UNION sub-patterns inside conn.begin()/commit(),
678
            // while the same UPDATE POSTed directly to /statements applied correctly.
679
            // A bare prepareUpdate().execute() takes the direct /statements path and
680
            // runs the UPDATE atomically per SPARQL 1.1 semantics — which is all we
681
            // need; there's nothing else to commit atomically alongside the UPDATE.
682
            try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
683
                conn.prepareUpdate(QueryLanguage.SPARQL, sparqlUpdate).execute();
×
684
            }
685
            long after = graphSize(graph);
×
686
            long added = after - before;
×
687
            if (added <= 0) break;
×
688
            total += added;
×
689
            before = after;
×
690
        }
×
691
        return total;
×
692
    }
693

694
    private long graphSize(IRI graph) {
695
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
696
            return conn.size(graph);
×
697
        }
698
    }
699

700
    /**
701
     * Distinct-subject totals in the given space-state graph, broken down by
702
     * RoleInstantiation kind (admin-pinned vs not) and RoleAssignment.
703
     * Three SELECT-COUNT queries — cheap, called once per build/cycle for
704
     * the user-facing log line. Returns zeros on failure (logged) so a flaky
705
     * count read can't wedge the cycle.
706
     */
707
    TierSubjectTotals computeTierSubjectTotals(IRI graph) {
708
        long adminRIs       = countDistinctSubjects(graph, """
×
709
                ?ri a gen:RoleInstantiation ; npa:inverseProperty gen:hasAdmin .
710
                """, "ri");
711
        long attachmentRAs  = countDistinctSubjects(graph, """
×
712
                ?ra a gen:RoleAssignment .
713
                """, "ra");
714
        long nonAdminRIs    = countDistinctSubjects(graph, """
×
715
                ?ri a gen:RoleInstantiation .
716
                FILTER NOT EXISTS { ?ri npa:inverseProperty gen:hasAdmin }
717
                """, "ri");
718
        return new TierSubjectTotals(adminRIs, attachmentRAs, nonAdminRIs);
×
719
    }
720

721
    private long countDistinctSubjects(IRI graph, String wherePattern, String varName) {
722
        String query = String.format("""
×
723
                PREFIX npa: <%1$s>
724
                PREFIX gen: <%2$s>
725
                SELECT (COUNT(DISTINCT ?%3$s) AS ?n) WHERE {
726
                  GRAPH <%4$s> {
727
                    %5$s
728
                  }
729
                }
730
                """, NPA.NAMESPACE, GEN.NAMESPACE, varName, graph, wherePattern);
731
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO);
×
732
             TupleQueryResult r = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) {
×
733
            if (!r.hasNext()) return 0;
×
734
            return Long.parseLong(r.next().getBinding("n").getValue().stringValue());
×
735
        } catch (Exception ex) {
×
736
            logger.warn("AuthorityResolver: countDistinctSubjects on {} failed: {}",
×
737
                    graph, ex.toString());
×
738
            return 0;
×
739
        }
740
    }
741

742
    // ---------------- SPARQL templates ----------------
743

744
    /**
745
     * Reusable invalidation filter on a bound nanopub-IRI variable. Pass the bare
746
     * variable name (no leading {@code ?}); e.g. {@code invalidationFilter("np")}
747
     * produces an outer-scoped {@code FILTER NOT EXISTS { GRAPH npa:graph
748
     * { ?_inv_np npx:invalidates ?np . } }}.
749
     *
750
     * <p>Joins on the raw {@code npx:invalidates} triple in {@code npa:graph},
751
     * which {@link com.knowledgepixels.query.NanopubLoader} writes into the
752
     * spaces repo from two complementary directions, making the filter symmetric
753
     * in load order:
754
     * <ul>
755
     *   <li>At the invalidator's own load: the loader's space-repo trigger fires
756
     *       whenever the nanopub has either its own space-relevant extractions
757
     *       OR an {@code npx:invalidates}/{@code npx:retracts}/{@code npx:supersedes}
758
     *       triple, so a pure-retraction nanopub still lands its raw triple plus
759
     *       {@code npa:hasLoadNumber} stamp in {@code npa:graph}.</li>
760
     *   <li>At the invalidated target's load (when the invalidator landed
761
     *       earlier): {@code NanopubLoader.getInvalidatingStatements} reads the
762
     *       triple back from the meta repo and mirrors it into the target's own
763
     *       write to the spaces repo.</li>
764
     * </ul>
765
     *
766
     * <p>The earlier shape joined on a structured {@code npa:Invalidation} entry
767
     * in {@code npa:spacesGraph} that was only emitted on the invalidator's side
768
     * AND only when the invalidated target's meta had already loaded, leaving a
769
     * window where a superseding nanopub loaded before its target produced no
770
     * entry and the stale row was never filtered out (see also the matching
771
     * change in the tier-specific {@code *InvalidationCheckWhere}/{@code
772
     * *InvalidationDelete} templates below).
773
     *
774
     * <p>Important: this filter must be placed OUTSIDE the surrounding
775
     * {@code GRAPH npa:spacesGraph { ... }} block, not nested inside it. When
776
     * nested, RDF4J's planner couples the FILTER NOT EXISTS evaluation into the
777
     * join order (per-row scan multiplied by the candidate set), which we
778
     * measured turning a 39ms query into a 60s+ timeout on the live observer-tier
779
     * data. Outside the GRAPH block, the planner defers the filter until
780
     * {@code ?np}/{@code ?rdNp} are bound and does a targeted index lookup.
781
     *
782
     * <p>Variable names must match {@code [A-Za-z0-9_]+} per SPARQL grammar —
783
     * embedding a {@code ?} inside {@code ?_inv_?np} would yield a parse error.
784
     */
785
    private static String invalidationFilter(String bareVarName) {
786
        return "FILTER NOT EXISTS { GRAPH <" + NPA.GRAPH + "> {"
30✔
787
                + " ?_inv_" + bareVarName
788
                + " <" + NPX.INVALIDATES + "> ?" + bareVarName + " . "
789
                + samePublisherClause("_inv_" + bareVarName, bareVarName)
6✔
790
                + " } }";
791
    }
792

793
    /**
794
     * SPARQL triple pair (placed inside a {@code GRAPH npa:graph { ... }} block)
795
     * requiring the invalidating nanopub and its target to share a signing public
796
     * key — the self-retraction authority gate for issue #112. Without it, the
797
     * materializer honors {@code npx:invalidates}/{@code retracts}/{@code supersedes}
798
     * from <em>any</em> validly-signed nanopub, so any agent can erase another
799
     * space's materialized state (griefing/DoS of the view — fail-closed, no
800
     * privilege escalation, but real). Additions are already admin-gated; this is
801
     * the symmetric gate on removals.
802
     *
803
     * <p>Both {@code npa:hasValidSignatureForPublicKeyHash} triples live in
804
     * {@code npa:graph} of the spaces repo: the target via its own space-load, the
805
     * invalidator via the symmetric retractor propagation in
806
     * {@link com.knowledgepixels.query.NanopubLoader} (forward {@code
807
     * loadInvalidateStatements} + reverse {@code loadInvalidatorIntoSpacesRepo}),
808
     * so the join is populated regardless of load order.
809
     *
810
     * <p>"Same pubkey" is intentionally stricter than "same agent": a retraction
811
     * signed by a different key the author owns (key rotation) is not honored, and
812
     * cross-admin supersession is out of scope here (would need an admin-authority
813
     * arm). The pubkey-bridge variable is suffixed with {@code targetVar} so two
814
     * filters in one query (e.g. on {@code ?np} and {@code ?rdNp}) don't collide.
815
     *
816
     * @param invVar    invalidator nanopub variable name (no leading {@code ?})
817
     * @param targetVar invalidated-target nanopub variable name (no leading {@code ?})
818
     */
819
    private static String samePublisherClause(String invVar, String targetVar) {
820
        String pk = "?_invpk_" + targetVar;
9✔
821
        return "?" + invVar + " <" + NPA.HAS_VALID_SIGNATURE_FOR_PUBLIC_KEY_HASH + "> " + pk + " . "
30✔
822
                + "?" + targetVar + " <" + NPA.HAS_VALID_SIGNATURE_FOR_PUBLIC_KEY_HASH + "> " + pk + " .";
823
    }
824

825
    /**
826
     * Admin tier: seed from {@code npadef:...hasRootAdmin} (trusted by construction)
827
     * plus closed-over admin grants; insert any {@code gen:RoleInstantiation} with
828
     * {@code npa:inverseProperty gen:hasAdmin} whose publisher (resolved via mirrored
829
     * trust-approved AccountState) is already in the admin set.
830
     *
831
     * <p>The seed is gated by {@link #spaceRefAliveFilter} (not the per-nanopub
832
     * {@code invalidationFilter("defNp")}): the {@code hasRootAdmin} seed is anchored
833
     * to the root NPID, which is the immutable space-ref identity, so superseding the
834
     * root <em>nanopub</em> with a continuation revision must not strip the seed —
835
     * only retracting every definition of the ref removes it. See issue #110.
836
     */
837
    static String adminTierUpdate(IRI graph, long lastProcessed) {
838
        // Order tuned for RDF4J's evaluator:
839
        //   1. Anchor on the small (seed UNION closed-over) set to bind ?publisher
840
        //      and ?space cheaply.
841
        //   2. Resolve ?pkh from the mirrored AccountState row (?publisher bound).
842
        //   3. Probe instantiations using the now-bound (?space, ?pkh) — targeted
843
        //      lookup, not a full RoleInstantiation scan.
844
        //   4. Load-number filter on bound ?np.
845
        //   5. Dedup at the end.
846
        // Authority is keyed on the space *ref* (npa:forSpaceRef), not the bare Space
847
        // IRI: two refs that share an IRI but have different roots are independent
848
        // domains (see doc/design-spaceref-isolation.md). The instantiation evidence in
849
        // the extraction graph is IRI-keyed (a gen:hasAdmin nanopub names the bare IRI),
850
        // so we project it per-ref by joining each instantiation naming ?space to the
851
        // admin rows of every ref of ?space whose admin set contains the publisher. The
852
        // inserted subject is minted per (?ri, ?spaceRef) so one instantiation validating
853
        // into N refs yields N distinct rows. TRANSITIONAL-DUAL-EMIT (Phase 4: remove):
854
        // forSpace is still emitted alongside forSpaceRef so the not-yet-migrated
855
        // downstream tiers / pre-ref read queries keep functioning on a mixed-version
856
        // fleet; it is dropped once everything keys on forSpaceRef.
857
        return """
69✔
858
                PREFIX npa:  <%1$s>
859
                PREFIX gen:  <%2$s>
860
                INSERT { GRAPH <%3$s> {
861
                  ?sri a gen:RoleInstantiation ;
862
                       npa:forSpaceRef ?spaceRef ;
863
                       npa:forSpace ?space ;
864
                       npa:inverseProperty gen:hasAdmin ;
865
                       # Stamp the admin tier so consumers read tier uniformly across all
866
                       # RoleInstantiations (?ri npa:hasRoleType ?tier) with no admin
867
                       # special-case — matching the non-admin path (issue #125, #127).
868
                       npa:hasRoleType gen:AdminRole ;
869
                       npa:forAgent ?agent ;
870
                       npa:viaNanopub ?np .
871
                } }
872
                WHERE {
873
                  # 1. Anchor: who is already an admin of which space ref?
874
                  {
875
                    # Seed branch: root-admin of a space ref that is still alive
876
                    # (has at least one non-invalidated definition). NOT filtered on
877
                    # ?def's own invalidation — superseding the root nanopub with a
878
                    # continuation revision must keep the seed; only a fully-retracted
879
                    # ref drops it (issue #110).
880
                    GRAPH <%4$s> {
881
                      ?def a npa:SpaceDefinition ;
882
                           npa:forSpaceRef  ?spaceRef ;
883
                           npa:hasRootAdmin ?publisher .
884
                      ?spaceRef npa:spaceIri ?space .
885
                    }
886
                    %7$s
887
                  }
888
                  UNION
889
                  {
890
                    # Closed-over branch: an existing admin of this ref. Recurse on the
891
                    # ref, then resolve its bare IRI to probe the IRI-keyed instantiation.
892
                    GRAPH <%3$s> {
893
                      ?prev a gen:RoleInstantiation ;
894
                            npa:forSpaceRef     ?spaceRef ;
895
                            npa:inverseProperty gen:hasAdmin ;
896
                            npa:forAgent        ?publisher .
897
                    }
898
                    GRAPH <%4$s> {
899
                      ?spaceRef npa:spaceIri ?space .
900
                    }
901
                  }
902
                  # 2. Mirror: resolve ?publisher → ?pkh via the trust-approved row.
903
                  GRAPH <%3$s> {
904
                    ?acct a npa:AccountState ;
905
                          npa:agent  ?publisher ;
906
                          npa:pubkey ?pkh .
907
                  }
908
                  # 3. Targeted instantiation lookup by space + pubkey (IRI-keyed).
909
                  GRAPH <%4$s> {
910
                    ?ri a gen:RoleInstantiation ;
911
                        npa:forSpace        ?space ;
912
                        npa:inverseProperty gen:hasAdmin ;
913
                        npa:forAgent        ?agent ;
914
                        npa:pubkeyHash      ?pkh ;
915
                        npa:viaNanopub      ?np .
916
                  }
917
                  # 3a. Mint the per-ref state subject: (?ri, ?spaceRef) → ?sri.
918
                  BIND(IRI(CONCAT(STR(?ri), "__", ENCODE_FOR_URI(STR(?spaceRef)))) AS ?sri)
919
                  %6$s
920
                  # 4. Load-number filter on bound ?np.
921
                  GRAPH <%8$s> {
922
                    ?np npa:hasLoadNumber ?ln .
923
                    FILTER (?ln > %5$d)
924
                  }
925
                  # 5. Dedup last — keyed on (ref, agent).
926
                  FILTER NOT EXISTS { GRAPH <%3$s> {
927
                    ?existing a gen:RoleInstantiation ;
928
                              npa:forSpaceRef ?spaceRef ;
929
                              npa:forAgent ?agent ;
930
                              npa:inverseProperty gen:hasAdmin .
931
                  } }
932
                }
933
                """.formatted(
3✔
934
                NPA.NAMESPACE,
935
                GEN.NAMESPACE,
936
                graph,
937
                SpacesVocab.SPACES_GRAPH,
938
                lastProcessed,
15✔
939
                invalidationFilter("np"),
12✔
940
                spaceRefAliveFilter(),
18✔
941
                NPA.GRAPH);
942
    }
943

944
    /**
945
     * Seed-survival filter for the admin tier (issue #110). The {@code hasRootAdmin}
946
     * seed is anchored to the root NPID, which is the immutable space-ref identity, so
947
     * it must survive supersession of the root <em>nanopub</em> by a continuation
948
     * revision (a later definition re-roots to the same ref via
949
     * {@code gen:hasRootDefinition} and so carries no {@code hasRootAdmin} of its own).
950
     * The previous {@code invalidationFilter("defNp")} dropped the seed the moment the
951
     * root revision was superseded, leaving the whole admin closure — and everything
952
     * cascading from it — unmaterialized for any space whose definition had ever been
953
     * updated.
954
     *
955
     * <p>Expressed positively: the seed survives iff the space ref still has at least
956
     * one non-invalidated {@link SpacesVocab#SPACE_DEFINITION}. A fully-retracted ref
957
     * (every definition invalidated) has no live definition, so the {@code FILTER
958
     * EXISTS} fails and the seed correctly disappears. Anchored on the already-bound
959
     * {@code ?spaceRef}, so it's a targeted lookup over that ref's (few) definitions.
960
     */
961
    private static String spaceRefAliveFilter() {
962
        return """
33✔
963
                FILTER EXISTS {
964
                  GRAPH <%1$s> {
965
                    ?liveDef a npa:SpaceDefinition ;
966
                             npa:forSpaceRef ?spaceRef ;
967
                             npa:viaNanopub  ?liveNp .
968
                  }
969
                  %2$s
970
                }
971
                """.formatted(SpacesVocab.SPACES_GRAPH, invalidationFilter("liveNp"));
9✔
972
    }
973

974
    /**
975
     * {@code gen:hasRole} attachment validation: an attachment is validated iff its
976
     * publisher is already a validated admin of the target space. Adds
977
     * {@code gen:RoleAssignment} rows to the space-state graph.
978
     */
979
    static String attachmentValidationUpdate(IRI graph, long lastProcessed) {
980
        // Ref-keyed (see doc/design-spaceref-isolation.md). The attachment names a bare
981
        // Space IRI; it is validated per-ref for every ref of that IRI whose admin set
982
        // contains the publisher (direct), or — when the named IRI is an owl:sameAs alias
983
        // — for the canonical ref it maps to (issue #113). ?targetRef is the ref the
984
        // RoleAssignment attaches to; the inserted subject is minted per (?ra, ?targetRef)
985
        // so one attachment validating into N refs yields N distinct rows.
986
        // TRANSITIONAL-DUAL-EMIT (Phase 4: remove): forSpace (the attached IRI, possibly an
987
        // alias) is kept so the non-admin tier can probe the IRI-keyed instantiations
988
        // naming it, and so pre-ref read queries keep functioning on a mixed-version fleet.
989
        return """
69✔
990
                PREFIX npa:  <%1$s>
991
                PREFIX gen:  <%2$s>
992
                INSERT { GRAPH <%3$s> {
993
                  ?ra2 a gen:RoleAssignment ;
994
                       npa:forSpaceRef ?targetRef ;
995
                       npa:forSpace ?space ;
996
                       gen:hasRole  ?role ;
997
                       npa:viaNanopub ?np .
998
                } }
999
                WHERE {
1000
                  GRAPH <%4$s> {
1001
                    ?ra a gen:RoleAssignment ;
1002
                        npa:forSpace ?space ;
1003
                        gen:hasRole  ?role ;
1004
                        npa:pubkeyHash ?pkh ;
1005
                        npa:viaNanopub ?np .
1006
                  }
1007
                  GRAPH <%7$s> {
1008
                    ?np npa:hasLoadNumber ?ln .
1009
                    FILTER (?ln > %5$d)
1010
                  }
1011
                  GRAPH <%3$s> {
1012
                    ?acct a npa:AccountState ;
1013
                          npa:agent  ?publisher ;
1014
                          npa:pubkey ?pkh .
1015
                  }
1016
                  # Per-ref admin gate. ?targetRef = a ref of ?space the publisher admins
1017
                  # (direct), or the canonical ref ?space is an owl:sameAs alias of.
1018
                  {
1019
                    GRAPH <%4$s> { ?targetRef npa:spaceIri ?space . }
1020
                    GRAPH <%3$s> {
1021
                      ?adminRI a gen:RoleInstantiation ;
1022
                               npa:forSpaceRef ?targetRef ;
1023
                               npa:inverseProperty gen:hasAdmin ;
1024
                               npa:forAgent ?publisher .
1025
                    }
1026
                  }
1027
                  UNION
1028
                  {
1029
                    GRAPH <%3$s> {
1030
                      ?space npa:sameAsSpace ?targetRef .
1031
                      ?adminRI a gen:RoleInstantiation ;
1032
                               npa:forSpaceRef ?targetRef ;
1033
                               npa:inverseProperty gen:hasAdmin ;
1034
                               npa:forAgent ?publisher .
1035
                    }
1036
                  }
1037
                  BIND(IRI(CONCAT(STR(?ra), "__", ENCODE_FOR_URI(STR(?targetRef)))) AS ?ra2)
1038
                  %6$s
1039
                  FILTER NOT EXISTS { GRAPH <%3$s> {
1040
                    ?existing a gen:RoleAssignment ;
1041
                              npa:forSpaceRef ?targetRef ;
1042
                              gen:hasRole  ?role .
1043
                  } }
1044
                }
1045
                """.formatted(
3✔
1046
                NPA.NAMESPACE,
1047
                GEN.NAMESPACE,
1048
                graph,
1049
                SpacesVocab.SPACES_GRAPH,
1050
                lastProcessed,
15✔
1051
                invalidationFilter("np"),
18✔
1052
                NPA.GRAPH);
1053
    }
1054

1055
    /**
1056
     * Preset-bundled role materialization (Nanodash issue #302). For each active,
1057
     * admin-authored {@code gen:PresetAssignment} targeting a {@code gen:Space}, inserts
1058
     * one {@code gen:RoleAssignment} per role the preset bundles — exactly as if
1059
     * {@code <space> gen:hasRole <role>} had been published by the assignment's publisher.
1060
     * The materialized rows carry {@code npa:derivedFromPreset} (the assignment nanopub)
1061
     * so the deactivation delete and read-side marking can scope to them without touching
1062
     * directly-published attachments. See {@code doc/design-preset-role-materialization.md}.
1063
     *
1064
     * <p>Activation is resolved by an <b>authorization-scoped latest-wins</b> over the
1065
     * {@code (preset, resource)} pair, NOT {@code npx:invalidates} (§3): the candidate set
1066
     * for the {@code MAX(dct:created)} comparison is restricted to assignments whose
1067
     * publisher is also a validated admin of the target ref, so an unauthorized key's newer
1068
     * assignment cannot shadow an admin's activation (the #113-class anti-hijack rule).
1069
     */
1070
    static String presetAttachmentValidationUpdate(IRI graph, long lastProcessed) {
1071
        // Ref-keyed like attachmentValidationUpdate: the assignment names a bare resource
1072
        // IRI; it is validated per-ref for every Space ref of that IRI whose admin set
1073
        // contains the publisher. The inserted subject is minted per (assignment, ref, role)
1074
        // — one assignment fans out to N roles and N refs. Non-Space targets resolve no
1075
        // ?targetRef and so insert nothing (correct no-op; maintained-resource / individual
1076
        // targets are future work, see design doc §2). TRANSITIONAL-DUAL-EMIT (Phase 4:
1077
        // remove): forSpace kept alongside forSpaceRef so the non-admin tiers can probe the
1078
        // IRI-keyed instantiations and pre-ref read queries keep functioning.
1079
        return """
69✔
1080
                PREFIX npa:  <%1$s>
1081
                PREFIX gen:  <%2$s>
1082
                INSERT { GRAPH <%3$s> {
1083
                  ?ra2 a gen:RoleAssignment ;
1084
                       npa:forSpaceRef ?targetRef ;
1085
                       npa:forSpace    ?resource ;
1086
                       gen:hasRole     ?role ;
1087
                       npa:viaNanopub  ?assignNp ;
1088
                       npa:derivedFromPreset ?assignNp .
1089
                } }
1090
                WHERE {
1091
                  # 1. Anchor: active preset assignments in the extraction graph.
1092
                  GRAPH <%4$s> {
1093
                    ?pa a npa:PresetAssignment ;
1094
                        npa:ofPreset    ?preset ;
1095
                        npa:forResource ?resource ;
1096
                        npa:isActivated true ;
1097
                        npa:pubkeyHash  ?pkh ;
1098
                        npa:viaNanopub  ?assignNp ;
1099
                        <http://purl.org/dc/terms/created> ?created .
1100
                  }
1101
                  # 2. Load-number filter on the assignment nanopub.
1102
                  GRAPH <%7$s> {
1103
                    ?assignNp npa:hasLoadNumber ?ln .
1104
                    FILTER (?ln > %5$d)
1105
                  }
1106
                  # 3. Resolve publisher pkh -> agent via the mirrored trust-approved row.
1107
                  GRAPH <%3$s> {
1108
                    ?acct a npa:AccountState ;
1109
                          npa:agent  ?publisher ;
1110
                          npa:pubkey ?pkh .
1111
                  }
1112
                  # 4. Target must be a Space ref the publisher admins — direct, or the
1113
                  #    canonical ref ?resource is an owl:sameAs alias of (issue #113 parity
1114
                  #    with attachmentValidationUpdate, so a preset assigned against an alias
1115
                  #    IRI still materializes against the canonical ref).
1116
                  {
1117
                    GRAPH <%4$s> { ?targetRef npa:spaceIri ?resource . }
1118
                    GRAPH <%3$s> {
1119
                      ?adminRI a gen:RoleInstantiation ;
1120
                               npa:forSpaceRef ?targetRef ;
1121
                               npa:inverseProperty gen:hasAdmin ;
1122
                               npa:forAgent ?publisher .
1123
                    }
1124
                  }
1125
                  UNION
1126
                  {
1127
                    GRAPH <%3$s> {
1128
                      ?resource npa:sameAsSpace ?targetRef .
1129
                      ?adminRI a gen:RoleInstantiation ;
1130
                               npa:forSpaceRef ?targetRef ;
1131
                               npa:inverseProperty gen:hasAdmin ;
1132
                               npa:forAgent ?publisher .
1133
                    }
1134
                  }
1135
                  # 5. Resolve the assignment's referenced preset IRI (node or kind) to its
1136
                  #    canonical kind, mirroring how Nanodash views key on dct:isVersionOf
1137
                  #    (ViewDisplay.getViewKindIri). Every declaration carries npa:ofPreset for
1138
                  #    both its node IRI and kind, so either reference maps to the same ?kind.
1139
                  GRAPH <%4$s> {
1140
                    ?pdMap a npa:PresetDeclaration ;
1141
                           npa:ofPreset   ?preset ;
1142
                           npa:presetKind ?kind .
1143
                  }
1144
                  # 5a. Roles come from the LATEST live declaration of that kind, restricted to
1145
                  #     Space-targeted presets — so a superseded preset version's roles never leak
1146
                  #     (the per-view-kind latest-wins, ported to materialization).
1147
                  GRAPH <%4$s> {
1148
                    ?pd a npa:PresetDeclaration ;
1149
                        npa:presetKind           ?kind ;
1150
                        npa:presetRole           ?role ;
1151
                        npa:appliesToInstancesOf gen:Space ;
1152
                        npa:viaNanopub           ?pdNp ;
1153
                        <http://purl.org/dc/terms/created> ?pdCreated .
1154
                  }
1155
                  # 5b. Latest-declaration-per-kind: reject if a newer LIVE declaration of the
1156
                  #     same kind exists (tiebreak on subject IRI for equal timestamps).
1157
                  FILTER NOT EXISTS {
1158
                    GRAPH <%4$s> {
1159
                      ?pdNewer a npa:PresetDeclaration ;
1160
                               npa:presetKind ?kind ;
1161
                               npa:viaNanopub ?pdNpNewer ;
1162
                               <http://purl.org/dc/terms/created> ?pdCreatedNewer .
1163
                      FILTER (?pdCreatedNewer > ?pdCreated
1164
                              || (?pdCreatedNewer = ?pdCreated && STR(?pdNewer) > STR(?pd)))
1165
                    }
1166
                    %8$s
1167
                  }
1168
                  # 5c. The chosen declaration must itself be live (not superseded/retracted).
1169
                  %9$s
1170
                  # 6. Mint the per (assignment, ref, role) subject.
1171
                  BIND(IRI(CONCAT(STR(?pa), "__", ENCODE_FOR_URI(STR(?targetRef)),
1172
                                  "__", ENCODE_FOR_URI(STR(?role)))) AS ?ra2)
1173
                  # 7. Authorization-scoped latest-wins (anti-hijack, design doc §3): reject
1174
                  #    if a newer same-(preset,resource) assignment exists whose publisher is
1175
                  #    ALSO a validated admin of ?targetRef. Filtering the shadowing candidate
1176
                  #    to admin-authored rows BEFORE taking the latest is what stops an
1177
                  #    unauthorized key from suppressing an admin's activation. Placed after
1178
                  #    the main vars are bound so the planner defers it (RDF4J quirk).
1179
                  FILTER NOT EXISTS {
1180
                    GRAPH <%4$s> {
1181
                      ?paNewer a npa:PresetAssignment ;
1182
                               npa:ofPreset    ?preset ;
1183
                               npa:forResource ?resource ;
1184
                               npa:pubkeyHash  ?pkhNewer ;
1185
                               <http://purl.org/dc/terms/created> ?createdNewer .
1186
                      FILTER (?createdNewer > ?created
1187
                              || (?createdNewer = ?created && STR(?paNewer) > STR(?pa)))
1188
                    }
1189
                    GRAPH <%3$s> {
1190
                      ?acctNewer a npa:AccountState ;
1191
                                 npa:agent  ?publisherNewer ;
1192
                                 npa:pubkey ?pkhNewer .
1193
                      ?adminRINewer a gen:RoleInstantiation ;
1194
                                    npa:forSpaceRef ?targetRef ;
1195
                                    npa:inverseProperty gen:hasAdmin ;
1196
                                    npa:forAgent ?publisherNewer .
1197
                    }
1198
                  }
1199
                  # 8. Defensive: drop if the assignment nanopub itself was hard-retracted.
1200
                  %6$s
1201
                  # 9. Dedup last — keyed on (ref, role).
1202
                  FILTER NOT EXISTS { GRAPH <%3$s> {
1203
                    ?existing a gen:RoleAssignment ;
1204
                              npa:forSpaceRef ?targetRef ;
1205
                              gen:hasRole ?role .
1206
                  } }
1207
                }
1208
                """.formatted(
3✔
1209
                NPA.NAMESPACE,
1210
                GEN.NAMESPACE,
1211
                graph,
1212
                SpacesVocab.SPACES_GRAPH,
1213
                lastProcessed,
15✔
1214
                invalidationFilter("assignNp"),
27✔
1215
                NPA.GRAPH,
1216
                invalidationFilter("pdNpNewer"),
15✔
1217
                invalidationFilter("pdNp"));
6✔
1218
    }
1219

1220
    /**
1221
     * Stamps a ref-scoped, admin-validated mirror of each {@code npa:PresetAssignment}
1222
     * into the state graph (issue #122). The publisher-agnostic extraction row
1223
     * ({@link SpacesExtractor#extractPresetAssignment}) is keyed only by
1224
     * {@code npa:forResource}, so a consumer listing a space's preset assignments by IRI
1225
     * sees the union across <em>all</em> refs claiming that IRI. This stamp adds
1226
     * {@code npa:forSpaceRef ?targetRef} so the "Assigned presets" listing is no longer
1227
     * merged across refs of the same IRI — the one remaining About-tab listing that still
1228
     * merged across refs (every other ref-scoped listing already has a {@code forSpaceRef}
1229
     * companion).
1230
     *
1231
     * <p>Faithful per-assignment mirror — deliberately <em>not</em> role-gated and
1232
     * <em>not</em> latest-wins-resolved, unlike {@link #presetAttachmentValidationUpdate}:
1233
     * <ul>
1234
     *   <li>No {@code npa:PresetDeclaration}/role join, so a preset that bundles only
1235
     *       <em>views</em> (no roles) is still listed.</li>
1236
     *   <li>Emits active <em>and</em> deactivated rows (carries {@code npa:isActivated})
1237
     *       so the listing can show state; a deactivation is just a newer admin-authored
1238
     *       row, so no {@code dct:created}-driven removal is needed here (contrast §4.4).</li>
1239
     *   <li>Latest-wins is deferred to the consumer query, which ranges only over these
1240
     *       admin-authored rows — so it is authorization-scoped for free (design §3): a
1241
     *       non-admin of the ref can never get a row stamped, so it cannot enter the
1242
     *       latest-wins race.</li>
1243
     * </ul>
1244
     *
1245
     * <p>Display-only leaf: nothing downstream derives from these rows (contrast the
1246
     * preset-derived {@code gen:RoleAssignment}), so the caller must <em>not</em> feed this
1247
     * tier's count into {@code structuralAdds}. The {@code npa:forSpaceRef} predicate also
1248
     * distinguishes a stamped row from the IRI-keyed extraction row (which never carries it),
1249
     * so {@link #presetAssignmentRefInvalidationDelete} can target exactly these rows.
1250
     * Reuses steps 1–4 of {@link #presetAttachmentValidationUpdate}; see
1251
     * doc/design-preset-role-materialization.md §3 and issue #122.
1252
     */
1253
    static String presetAssignmentRefStampUpdate(IRI graph, long lastProcessed) {
1254
        return """
69✔
1255
                PREFIX npa:  <%1$s>
1256
                PREFIX gen:  <%2$s>
1257
                INSERT { GRAPH <%3$s> {
1258
                  ?paRef a npa:PresetAssignment ;
1259
                         npa:ofPreset    ?preset ;
1260
                         npa:forResource ?resource ;
1261
                         npa:forSpaceRef ?targetRef ;
1262
                         npa:isActivated ?activated ;
1263
                         npa:viaNanopub  ?assignNp ;
1264
                         <http://purl.org/dc/terms/created> ?created .
1265
                } }
1266
                WHERE {
1267
                  # 1. Anchor: every assignment row (active or not) in the extraction graph.
1268
                  GRAPH <%4$s> {
1269
                    ?pa a npa:PresetAssignment ;
1270
                        npa:ofPreset    ?preset ;
1271
                        npa:forResource ?resource ;
1272
                        npa:isActivated ?activated ;
1273
                        npa:pubkeyHash  ?pkh ;
1274
                        npa:viaNanopub  ?assignNp ;
1275
                        <http://purl.org/dc/terms/created> ?created .
1276
                  }
1277
                  # 2. Load-number filter on the assignment nanopub (delta window).
1278
                  GRAPH <%6$s> {
1279
                    ?assignNp npa:hasLoadNumber ?ln .
1280
                    FILTER (?ln > %5$d)
1281
                  }
1282
                  # 3. Resolve publisher pkh -> agent via the mirrored trust-approved row.
1283
                  GRAPH <%3$s> {
1284
                    ?acct a npa:AccountState ;
1285
                          npa:agent  ?publisher ;
1286
                          npa:pubkey ?pkh .
1287
                  }
1288
                  # 4. Target must be a Space ref the publisher admins. ?targetRef = that ref;
1289
                  #    fan-out to N refs the publisher admins (per-ref isolation, consistent
1290
                  #    with the role materializer and design-spaceref-isolation.md). Direct,
1291
                  #    or the canonical ref ?resource is an owl:sameAs alias of (issue #113),
1292
                  #    so an assignment naming an alias is still listed under the canonical ref.
1293
                  {
1294
                    GRAPH <%4$s> { ?targetRef npa:spaceIri ?resource . }
1295
                    GRAPH <%3$s> {
1296
                      ?adminRI a gen:RoleInstantiation ;
1297
                               npa:forSpaceRef ?targetRef ;
1298
                               npa:inverseProperty gen:hasAdmin ;
1299
                               npa:forAgent ?publisher .
1300
                    }
1301
                  }
1302
                  UNION
1303
                  {
1304
                    GRAPH <%3$s> {
1305
                      ?resource npa:sameAsSpace ?targetRef .
1306
                      ?adminRI a gen:RoleInstantiation ;
1307
                               npa:forSpaceRef ?targetRef ;
1308
                               npa:inverseProperty gen:hasAdmin ;
1309
                               npa:forAgent ?publisher .
1310
                    }
1311
                  }
1312
                  # 5. Defensive: drop if the assignment nanopub itself was hard-retracted.
1313
                  %7$s
1314
                  # 6. Mint per (assignment, ref); dedup on the bound subject. No latest-wins
1315
                  #    here — a deactivation is just a newer admin-authored row, and the
1316
                  #    consumer resolves latest dct:created per (preset,resource) over these
1317
                  #    admin-authored rows (so the resolution is authorization-scoped).
1318
                  BIND(IRI(CONCAT(STR(?pa), "__", ENCODE_FOR_URI(STR(?targetRef)))) AS ?paRef)
1319
                  FILTER NOT EXISTS { GRAPH <%3$s> { ?paRef a npa:PresetAssignment . } }
1320
                }
1321
                """.formatted(
3✔
1322
                NPA.NAMESPACE,
1323
                GEN.NAMESPACE,
1324
                graph,
1325
                SpacesVocab.SPACES_GRAPH,
1326
                lastProcessed,
27✔
1327
                NPA.GRAPH,
1328
                invalidationFilter("assignNp"));
6✔
1329
    }
1330

1331
    /**
1332
     * Non-admin tier publisher constraints (inserted as a SPARQL sub-pattern).
1333
     * Each constraint owns the AccountState (pkh → agent) lookup so the join
1334
     * variable is bound through a targeted pattern. The observer-self variant
1335
     * binds {@code npa:agent ?agent} directly — no separate {@code ?publisher}
1336
     * variable, no post-join equality filter — which lets the planner anchor
1337
     * the AccountState lookup on the already-bound {@code ?agent} instead of
1338
     * enumerating all approved publishers and filtering at the end.
1339
     */
1340
    static final String PUBLISHER_IS_ADMIN = """
1341
            ?acct a npa:AccountState ;
1342
                  npa:pubkey ?pkh ;
1343
                  npa:agent  ?publisher .
1344
            # Admin of the assignment's ref. The ref already resolves alias →
1345
            # canonical (the attachment tier bound ?spaceRef through the owl:sameAs
1346
            # alias edge for aliased IRIs, issue #113), so no alias arm is needed here.
1347
            ?adminRI a gen:RoleInstantiation ;
1348
                     npa:forSpaceRef ?spaceRef ;
1349
                     npa:inverseProperty gen:hasAdmin ;
1350
                     npa:forAgent ?publisher .
1351
            """;
1352

1353
    /** Observer self-evidence: the assignee's own pubkey signed the instantiation. */
1354
    static final String PUBLISHER_IS_SELF = """
1355
            ?acct a npa:AccountState ;
1356
                  npa:pubkey ?pkh ;
1357
                  npa:agent  ?agent .
1358
            """;
1359

1360
    /**
1361
     * Maintainer / Member / Observer tier INSERT. Same shape: find an instantiation
1362
     * whose predicate matches a RoleDeclaration of the given tier attached to the
1363
     * target space, and whose publisher passes the tier-specific constraint.
1364
     */
1365
    static String nonAdminTierUpdate(IRI graph, long lastProcessed,
1366
                                     IRI tierClass, String publisherConstraint) {
1367
        // Order tuned for RDF4J's evaluator (which executes BGPs roughly in order).
1368
        // The crucial choice is the *anchor*: instantiation-first plans send the
1369
        // planner exploring the full ~thousands of candidate RIs and only filter
1370
        // by tier at the very end. Attachment-first anchors on the small set of
1371
        // gen:RoleAssignment rows already validated in this space-state graph
1372
        // (~hundreds, often zero) and walks outward by bound (?role, ?space).
1373
        //
1374
        //   1. Anchor on RoleAssignments in this space-state graph (small).
1375
        //   1a. Resolve the IRIs that denote the assignment's ref — its canonical
1376
        //      IRI plus any validated owl:sameAs aliases — so an instantiation that
1377
        //      names an alias of the space still matches (issue #113). Bound here so
1378
        //      the instantiation lookup below stays anchored by ?instSpace.
1379
        //   2. Match the tier-pinned RoleDeclaration by ?role.
1380
        //   3. Pair role-decl direction to instantiation direction in one UNION
1381
        //      so only (reg, reg)/(inv, inv) combos are explored.
1382
        //   4. Targeted instantiation lookup — (?instSpace, ?pred) are bound.
1383
        //   5. Publisher constraint (incl. AccountState resolution).
1384
        //   6. Load-number filter on bound ?np.
1385
        //   7. Dedup at the end.
1386
        return """
69✔
1387
                PREFIX npa:  <%1$s>
1388
                PREFIX gen:  <%2$s>
1389
                INSERT { GRAPH <%3$s> {
1390
                  ?ri2 a gen:RoleInstantiation ;
1391
                       npa:forSpaceRef ?spaceRef ;
1392
                       # TRANSITIONAL-DUAL-EMIT (Phase 4: remove): forSpace alongside
1393
                       # forSpaceRef so pre-ref read queries (e.g. get-space-members) keep
1394
                       # functioning on a mixed-version fleet; downstream tiers key on the ref.
1395
                       npa:forSpace ?space ;
1396
                       npa:forAgent ?agent ;
1397
                       ?dirPred ?pred ;
1398
                       # Persist the tier and role IRI that are already bound at this point —
1399
                       # the loop's tierClass arg (%7$s) and the anchoring attachment's ?role
1400
                       # (step 1) — so ref-scoped consumers key on identity rather than
1401
                       # re-deriving the tier from the bare predicate against GLOBAL
1402
                       # RoleDeclarations. The bare-predicate re-derivation bleeds tiers
1403
                       # across spaces that declare the same predicate at different tiers
1404
                       # (issue #125): consumers should match ?ri2 npa:hasRoleType <tier>
1405
                       # / gen:hasRole ?role, exactly as the *-roles-ref queries do.
1406
                       npa:hasRoleType <%7$s> ;
1407
                       gen:hasRole ?role ;
1408
                       npa:viaNanopub ?np .
1409
                } }
1410
                WHERE {
1411
                  # 1. Anchor: validated attachments in this space-state graph (ref-keyed).
1412
                  GRAPH <%3$s> {
1413
                    ?ra a gen:RoleAssignment ;
1414
                        gen:hasRole     ?role ;
1415
                        npa:forSpaceRef ?spaceRef ;
1416
                        npa:forSpace    ?space .
1417
                  }
1418
                  # 1a. The IRIs that denote this ref: its canonical IRI, plus any validated
1419
                  #     owl:sameAs aliases of it (issue #113) — so an instantiation naming an
1420
                  #     alias of the space still materializes here. Bound BEFORE the
1421
                  #     instantiation BGP so that lookup stays anchored by ?instSpace (planner
1422
                  #     note above); ?spaceRef is already bound, so each arm is a targeted
1423
                  #     lookup yielding a tiny IRI set. The alias arm only follows admin-
1424
                  #     validated npa:sameAsSpace edges, so it grants no authority the admin
1425
                  #     tier would not (anti-hijack is enforced upstream, not relaxed here).
1426
                  {
1427
                    GRAPH <%4$s> { ?spaceRef npa:spaceIri ?instSpace . }
1428
                  }
1429
                  UNION
1430
                  {
1431
                    GRAPH <%3$s> { ?instSpace npa:sameAsSpace ?spaceRef . }
1432
                  }
1433
                  # 2. Tier-pinned RoleDeclaration (?role bound from the attachment). Its
1434
                  #    nanopub's invalidation is intentionally NOT consulted (see step 7), so
1435
                  #    no ?rdNp binding is needed.
1436
                  GRAPH <%4$s> {
1437
                    ?rd a npa:RoleDeclaration ;
1438
                        npa:hasRoleType <%7$s> ;
1439
                        npa:role        ?role .
1440
                    # 3. Pair role-decl direction to the instantiation in one UNION so only
1441
                    #    matching combos are explored, binding (?instSpace, ?agent) per arm.
1442
                    #    ?dirPred carries the resolved direction so the materialized row
1443
                    #    records the role property (read by get-space-members and
1444
                    #    publisherIsTieredRole) — identical shape whichever arm matched.
1445
                    #
1446
                    #    The first two arms handle instantiations the extractor already
1447
                    #    classified (npa:regularProperty / npa:inverseProperty). The last two
1448
                    #    resolve a custom predicate the extractor left neutral (npa:rolePredicate
1449
                    #    with raw npa:bindingSubject / npa:bindingObject): the role declaration
1450
                    #    supplies the direction, which fixes which raw endpoint is the space vs
1451
                    #    the agent. INVERSE = <space> pred <agent>; REGULAR = <agent> pred <space>.
1452
                    {
1453
                      ?rd gen:hasRegularProperty ?pred .
1454
                      ?ri npa:regularProperty ?pred ;
1455
                          npa:forSpace ?instSpace ;
1456
                          npa:forAgent ?agent .
1457
                      BIND(npa:regularProperty AS ?dirPred)
1458
                    }
1459
                    UNION
1460
                    {
1461
                      ?rd gen:hasInverseProperty ?pred .
1462
                      ?ri npa:inverseProperty ?pred ;
1463
                          npa:forSpace ?instSpace ;
1464
                          npa:forAgent ?agent .
1465
                      BIND(npa:inverseProperty AS ?dirPred)
1466
                    }
1467
                    UNION
1468
                    {
1469
                      ?rd gen:hasInverseProperty ?pred .
1470
                      ?ri npa:rolePredicate   ?pred ;
1471
                          npa:bindingSubject  ?instSpace ;
1472
                          npa:bindingObject   ?agent .
1473
                      BIND(npa:inverseProperty AS ?dirPred)
1474
                    }
1475
                    UNION
1476
                    {
1477
                      ?rd gen:hasRegularProperty ?pred .
1478
                      ?ri npa:rolePredicate   ?pred ;
1479
                          npa:bindingObject   ?instSpace ;
1480
                          npa:bindingSubject  ?agent .
1481
                      BIND(npa:regularProperty AS ?dirPred)
1482
                    }
1483
                    # 4. Common instantiation columns. ?instSpace was resolved to this ref
1484
                    #    above (canonical or owl:sameAs alias), so an alias-named instantiation
1485
                    #    joins the same ?spaceRef as a canonical one. The materialized row still
1486
                    #    carries npa:forSpace ?space (the attachment's IRI) for the transitional
1487
                    #    dual-emit, so pre-ref reads see the member under the space's primary IRI.
1488
                    ?ri a gen:RoleInstantiation ;
1489
                        npa:pubkeyHash ?pkh ;
1490
                        npa:viaNanopub ?np .
1491
                  }
1492
                  # 5. Publisher constraint (incl. AccountState resolution).
1493
                  GRAPH <%3$s> {
1494
                    %8$s
1495
                  }
1496
                  # 5a. Mint the per-ref state subject: (?ri, ?spaceRef) → ?ri2.
1497
                  BIND(IRI(CONCAT(STR(?ri), "__", ENCODE_FOR_URI(STR(?spaceRef)))) AS ?ri2)
1498
                  # 6. Load-number filter on bound ?np.
1499
                  GRAPH <%9$s> {
1500
                    ?np npa:hasLoadNumber ?ln .
1501
                    FILTER (?ln > %5$d)
1502
                  }
1503
                  # 7. Instantiation invalidation filter — outside the GRAPH block so the
1504
                  #    planner defers it until ?np is bound. Role-DECLARATION invalidation is
1505
                  #    deliberately NOT consulted: the tier already anchors on the admin-
1506
                  #    validated attachment (?ra), which is removed when an admin retracts it,
1507
                  #    so admin control is fully enforced there. Letting the declaration's
1508
                  #    author (usually not the space admin) supersede/retract their declaration
1509
                  #    strip a space's members is the same cross-author-strip anti-pattern as
1510
                  #    issue #112. Role IRIs are version-pinned, so the attached definition is
1511
                  #    immutable regardless of the declaration nanopub's later lifecycle.
1512
                  %6$s
1513
                  # 8. Dedup last — keyed on (ref, agent, nanopub).
1514
                  FILTER NOT EXISTS { GRAPH <%3$s> {
1515
                    ?existing a gen:RoleInstantiation ;
1516
                              npa:forSpaceRef ?spaceRef ;
1517
                              npa:forAgent ?agent ;
1518
                              npa:viaNanopub ?np .
1519
                  } }
1520
                }
1521
                """.formatted(
3✔
1522
                NPA.NAMESPACE,
1523
                GEN.NAMESPACE,
1524
                graph,
1525
                SpacesVocab.SPACES_GRAPH,
1526
                lastProcessed,
15✔
1527
                invalidationFilter("np"),
42✔
1528
                tierClass,
1529
                publisherConstraint,
1530
                NPA.GRAPH);
1531
    }
1532

1533
    /**
1534
     * Sub-space admit pass. Copies validated {@code npa:SubSpaceDeclaration}
1535
     * extraction rows into the space-state graph (preserving the {@code npasub:}
1536
     * subject) and emits convenience {@code <child> npa:isSubSpaceOf <parent>} and
1537
     * {@code <parent> npa:hasSubSpace <child>} direct triples. Two satisfaction
1538
     * modes joined by UNION:
1539
     * <ul>
1540
     *   <li>Mode A — the declaration's publisher is a validated admin of both the
1541
     *       child and the parent space.</li>
1542
     *   <li>Mode B — a different non-invalidated declaration for the same
1543
     *       {@code (child, parent)} pair exists, and the two publishers between
1544
     *       them cover both admin sides (i.e. one of them is admin of the child,
1545
     *       one of them is admin of the parent — possibly the same one twice if
1546
     *       both happen to be admin of both).</li>
1547
     * </ul>
1548
     *
1549
     * <p>Mode-B late-arrival: when only the partner declaration is new in this
1550
     * cycle (the primary is older than {@code lastProcessed}), the load-number
1551
     * filter on {@code ?np} excludes the candidate. The late-arrival sweep
1552
     * ({@link #runDownstreamWithoutLoadFilter}) re-runs this pass without the
1553
     * load filter and catches it.
1554
     */
1555
    static String subSpaceAdmitUpdate(IRI graph, long lastProcessed) {
1556
        return """
69✔
1557
                PREFIX npa: <%1$s>
1558
                PREFIX gen: <%2$s>
1559
                INSERT { GRAPH <%3$s> {
1560
                  ?d a npa:SubSpaceDeclaration ;
1561
                     npa:childSpace  ?child ;
1562
                     npa:parentSpace ?parent ;
1563
                     npa:viaNanopub  ?np .
1564
                  ?childRef  npa:isSubSpaceOf ?parentRef .
1565
                  ?parentRef npa:hasSubSpace  ?childRef  .
1566
                  # TRANSITIONAL-DUAL-EMIT (Phase 1.5; remove in Phase 4): IRI-valued
1567
                  # sub-space edge alongside the ref-to-ref one, so pre-ref published
1568
                  # queries that key on the bare Space IRI keep binding on a mixed-version
1569
                  # fleet. See doc/report-2026-06-12-mixed-fleet-spaceref-breakage.md.
1570
                  ?child  npa:isSubSpaceOf ?parent .
1571
                  ?parent npa:hasSubSpace  ?child  .
1572
                } }
1573
                WHERE {
1574
                  # 1. Anchor: candidate declarations from the extraction graph.
1575
                  GRAPH <%4$s> {
1576
                    ?d a npa:SubSpaceDeclaration ;
1577
                       npa:childSpace  ?child ;
1578
                       npa:parentSpace ?parent ;
1579
                       npa:pubkeyHash  ?pkh ;
1580
                       npa:viaNanopub  ?np .
1581
                  }
1582
                  # 2. Mirror: resolve ?pkh → ?publisher via the trust-approved row.
1583
                  GRAPH <%3$s> {
1584
                    ?acct a npa:AccountState ;
1585
                          npa:pubkey ?pkh ;
1586
                          npa:agent  ?publisher .
1587
                  }
1588
                  # 3. Authority gate, ref-keyed. The edge is emitted ref-to-ref between
1589
                  #    the child ref and parent ref the authorizing admin governs; the
1590
                  #    admin rows' dual-emitted npa:forSpace binds the refs to the child /
1591
                  #    parent IRIs (cross-product when an IRI has several governed refs).
1592
                  {
1593
                    # Mode A — publisher is admin of BOTH a child ref and a parent ref.
1594
                    GRAPH <%3$s> {
1595
                      ?riC a gen:RoleInstantiation ;
1596
                           npa:inverseProperty gen:hasAdmin ;
1597
                           npa:forSpace ?child ;
1598
                           npa:forSpaceRef ?childRef ;
1599
                           npa:forAgent ?publisher .
1600
                      ?riP a gen:RoleInstantiation ;
1601
                           npa:inverseProperty gen:hasAdmin ;
1602
                           npa:forSpace ?parent ;
1603
                           npa:forSpaceRef ?parentRef ;
1604
                           npa:forAgent ?publisher .
1605
                    }
1606
                  }
1607
                  UNION
1608
                  {
1609
                    # Mode B — co-declaration whose publisher covers the side this
1610
                    # one's publisher doesn't. Between {publisher, publisher2},
1611
                    # both admin sides must be covered.
1612
                    GRAPH <%4$s> {
1613
                      ?d2 a npa:SubSpaceDeclaration ;
1614
                          npa:childSpace  ?child ;
1615
                          npa:parentSpace ?parent ;
1616
                          npa:pubkeyHash  ?pkh2 ;
1617
                          npa:viaNanopub  ?np2 .
1618
                      FILTER (?np2 != ?np)
1619
                    }
1620
                    %8$s
1621
                    GRAPH <%3$s> {
1622
                      ?acct2 a npa:AccountState ;
1623
                             npa:pubkey ?pkh2 ;
1624
                             npa:agent  ?publisher2 .
1625
                      ?riA a gen:RoleInstantiation ;
1626
                           npa:inverseProperty gen:hasAdmin ;
1627
                           npa:forSpace ?child ;
1628
                           npa:forSpaceRef ?childRef .
1629
                      { ?riA npa:forAgent ?publisher } UNION { ?riA npa:forAgent ?publisher2 }
1630
                      ?riB a gen:RoleInstantiation ;
1631
                           npa:inverseProperty gen:hasAdmin ;
1632
                           npa:forSpace ?parent ;
1633
                           npa:forSpaceRef ?parentRef .
1634
                      { ?riB npa:forAgent ?publisher } UNION { ?riB npa:forAgent ?publisher2 }
1635
                    }
1636
                  }
1637
                  # 4. Invalidation filter on the primary declaration's nanopub.
1638
                  %6$s
1639
                  # 5. Load-number filter on bound ?np.
1640
                  GRAPH <%7$s> {
1641
                    ?np npa:hasLoadNumber ?ln .
1642
                    FILTER (?ln > %5$d)
1643
                  }
1644
                  # 6. Dedup last — on the emitted ref-to-ref edge.
1645
                  FILTER NOT EXISTS { GRAPH <%3$s> {
1646
                    ?childRef npa:isSubSpaceOf ?parentRef .
1647
                  } }
1648
                }
1649
                """.formatted(
3✔
1650
                NPA.NAMESPACE,
1651
                GEN.NAMESPACE,
1652
                graph,
1653
                SpacesVocab.SPACES_GRAPH,
1654
                lastProcessed,
15✔
1655
                invalidationFilter("np"),
27✔
1656
                NPA.GRAPH,
1657
                invalidationFilter("np2"));
6✔
1658
    }
1659

1660
    /**
1661
     * Maintained-resource admit pass. Copies validated
1662
     * {@code npa:MaintainedResourceDeclaration} extraction rows into the space-state
1663
     * graph (preserving the {@code npamrd:} subject) and emits convenience
1664
     * {@code <r> npa:isMaintainedBy <s>} and {@code <s> npa:hasMaintainedResource <r>}
1665
     * direct triples. Single satisfaction mode:
1666
     * <ul>
1667
     *   <li>Mode A — the declaration's publisher is a validated admin of the
1668
     *       maintaining space.</li>
1669
     * </ul>
1670
     *
1671
     * <p>No Mode B because only one space is involved; the two-sides-must-be-covered
1672
     * concern that drives sub-space Mode B doesn't apply. Late-arrival is still
1673
     * possible (declaration lands before the publisher's admin grant becomes valid):
1674
     * the load-number filter on {@code ?np} excludes the candidate, and the
1675
     * late-arrival sweep ({@link #runDownstreamWithoutLoadFilter}) re-runs this pass
1676
     * without the load filter and catches it.
1677
     */
1678
    static String maintainedResourceAdmitUpdate(IRI graph, long lastProcessed) {
1679
        return """
69✔
1680
                PREFIX npa: <%1$s>
1681
                PREFIX gen: <%2$s>
1682
                INSERT { GRAPH <%3$s> {
1683
                  ?d a npa:MaintainedResourceDeclaration ;
1684
                     npa:resourceIri     ?r ;
1685
                     npa:maintainerSpace ?s ;
1686
                     npa:viaNanopub      ?np .
1687
                  ?r npa:isMaintainedBy        ?sRef .
1688
                  ?sRef npa:hasMaintainedResource ?r .
1689
                  # TRANSITIONAL-DUAL-EMIT (Phase 1.5; remove in Phase 4): IRI-valued
1690
                  # maintained-resource edge alongside the resource→ref one, so pre-ref
1691
                  # published queries (e.g. get-view-displays' maintained hop) keep binding
1692
                  # on a mixed-version fleet. This is the edge whose absence broke 1.15.0 —
1693
                  # see doc/report-2026-06-12-mixed-fleet-spaceref-breakage.md.
1694
                  ?r npa:isMaintainedBy        ?s .
1695
                  ?s npa:hasMaintainedResource ?r .
1696
                } }
1697
                WHERE {
1698
                  # 1. Anchor: candidate declarations from the extraction graph.
1699
                  GRAPH <%4$s> {
1700
                    ?d a npa:MaintainedResourceDeclaration ;
1701
                       npa:resourceIri     ?r ;
1702
                       npa:maintainerSpace ?s ;
1703
                       npa:pubkeyHash      ?pkh ;
1704
                       npa:viaNanopub      ?np .
1705
                  }
1706
                  # 2. Mirror: resolve ?pkh → ?publisher via the trust-approved row.
1707
                  GRAPH <%3$s> {
1708
                    ?acct a npa:AccountState ;
1709
                          npa:pubkey ?pkh ;
1710
                          npa:agent  ?publisher .
1711
                    # 3. Authority gate (Mode A only): publisher is admin of a ref of the
1712
                    #    maintaining space. ?sRef = that ref (resource → ref edge).
1713
                    ?riA a gen:RoleInstantiation ;
1714
                         npa:inverseProperty gen:hasAdmin ;
1715
                         npa:forSpace ?s ;
1716
                         npa:forSpaceRef ?sRef ;
1717
                         npa:forAgent ?publisher .
1718
                  }
1719
                  # 4. Invalidation filter on the declaration's nanopub.
1720
                  %6$s
1721
                  # 5. Load-number filter on bound ?np.
1722
                  GRAPH <%7$s> {
1723
                    ?np npa:hasLoadNumber ?ln .
1724
                    FILTER (?ln > %5$d)
1725
                  }
1726
                  # 6. Dedup last — on the emitted resource → ref edge.
1727
                  FILTER NOT EXISTS { GRAPH <%3$s> {
1728
                    ?r npa:isMaintainedBy ?sRef .
1729
                  } }
1730
                }
1731
                """.formatted(
3✔
1732
                NPA.NAMESPACE,
1733
                GEN.NAMESPACE,
1734
                graph,
1735
                SpacesVocab.SPACES_GRAPH,
1736
                lastProcessed,
15✔
1737
                invalidationFilter("np"),
18✔
1738
                NPA.GRAPH);
1739
    }
1740

1741
    /**
1742
     * Space-alias admit pass (issue #113). Copies validated
1743
     * {@code npa:SpaceAliasDeclaration} extraction rows into the space-state graph
1744
     * (preserving the {@code npaalias:} subject) and emits the directional
1745
     * {@code <alias> npa:sameAsSpace <canonical>} edge consumed by the alias-aware
1746
     * admin-authority lookups in {@link #attachmentValidationUpdate},
1747
     * {@link #PUBLISHER_IS_ADMIN}, and {@link #publisherIsTieredRole}.
1748
     *
1749
     * <p>Two gates, both read against the (already-settled) admin closure in the
1750
     * space-state graph:
1751
     * <ul>
1752
     *   <li><b>Authority</b> — the declaration's publisher (resolved via the mirrored
1753
     *       trust-approved {@code AccountState}) is a validated admin of the
1754
     *       <em>canonical</em> space. The alias is declared inside the canonical
1755
     *       space's own {@code gen:Space} nanopub, so this is the same evidence rule
1756
     *       as a {@code gen:hasRole} attachment.</li>
1757
     *   <li><b>Anti-hijack</b> — the alias must not be an independently-governed live
1758
     *       space: it must have no admin who is not also an admin of the canonical
1759
     *       space ({@code admins(alias) ⊆ admins(canonical)}). The common rename case
1760
     *       (the alias's own definition was superseded, so it has no live admin
1761
     *       closure) passes trivially; an attacker publishing
1762
     *       {@code <evil> owl:sameAs <activeSpace>} is rejected because the active
1763
     *       space has admins not in evil's set.</li>
1764
     * </ul>
1765
     *
1766
     * <p>Late-arrival: when the canonical admin grant only becomes valid in the same
1767
     * cycle as the declaration, the load-number filter on {@code ?np} excludes the
1768
     * candidate; the late-arrival sweep ({@link #runDownstreamWithoutLoadFilter})
1769
     * re-runs this pass without the load filter and catches it.
1770
     */
1771
    static String aliasAdmitUpdate(IRI graph, long lastProcessed) {
1772
        // Ref-keyed (see doc/design-spaceref-isolation.md). The declaration names bare
1773
        // canonical/alias IRIs. It is admitted per canonical *ref* whose admin set
1774
        // contains the publisher; the emitted edge is ref-valued on the canonical side
1775
        // (<alias> npa:sameAsSpace <canonicalRef>), which is what the alias-aware admin
1776
        // lookups in the attachment tier consume. Anti-hijack compares the alias IRI's
1777
        // admins against that specific canonical ref's admins — strictly tighter than the
1778
        // old bare-IRI form.
1779
        return """
69✔
1780
                PREFIX npa: <%1$s>
1781
                PREFIX gen: <%2$s>
1782
                INSERT { GRAPH <%3$s> {
1783
                  ?d a npa:SpaceAliasDeclaration ;
1784
                     npa:canonicalSpace ?canonical ;
1785
                     npa:aliasSpace     ?alias ;
1786
                     npa:viaNanopub     ?np .
1787
                  ?alias npa:sameAsSpace ?canonRef .
1788
                  # TRANSITIONAL-DUAL-EMIT (Phase 1.5; remove in Phase 4): IRI-valued
1789
                  # alias edge alongside the ref-valued one, so pre-ref published queries
1790
                  # that resolve owl:sameAs by bare canonical IRI keep binding on a
1791
                  # mixed-version fleet. Internal alias-aware lookups (attachment tier)
1792
                  # join through npa:forSpaceRef, which is ref-valued, so this IRI-valued
1793
                  # object never satisfies them — it is inert internally, read-only for
1794
                  # legacy consumers. See doc/report-2026-06-12-mixed-fleet-spaceref-breakage.md.
1795
                  ?alias npa:sameAsSpace ?canonical .
1796
                } }
1797
                WHERE {
1798
                  # 1. Anchor: candidate alias declarations from the extraction graph.
1799
                  GRAPH <%4$s> {
1800
                    ?d a npa:SpaceAliasDeclaration ;
1801
                       npa:canonicalSpace ?canonical ;
1802
                       npa:aliasSpace     ?alias ;
1803
                       npa:pubkeyHash     ?pkh ;
1804
                       npa:viaNanopub     ?np .
1805
                  }
1806
                  # 2. Authority gate per canonical ref: ?canonRef is a ref of ?canonical
1807
                  #    whose admin set contains the declaration's publisher.
1808
                  GRAPH <%4$s> { ?canonRef npa:spaceIri ?canonical . }
1809
                  GRAPH <%3$s> {
1810
                    ?acct a npa:AccountState ;
1811
                          npa:pubkey ?pkh ;
1812
                          npa:agent  ?publisher .
1813
                    ?adminRI a gen:RoleInstantiation ;
1814
                             npa:inverseProperty gen:hasAdmin ;
1815
                             npa:forSpaceRef ?canonRef ;
1816
                             npa:forAgent ?publisher .
1817
                  }
1818
                  # 3. Anti-hijack: the alias IRI must have no admin who is not also an
1819
                  #    admin of this canonical ref (admins(alias) ⊆ admins(canonRef)).
1820
                  FILTER NOT EXISTS {
1821
                    GRAPH <%3$s> {
1822
                      ?aliasAdmin a gen:RoleInstantiation ;
1823
                                  npa:inverseProperty gen:hasAdmin ;
1824
                                  npa:forSpace ?alias ;
1825
                                  npa:forAgent ?otherAgent .
1826
                    }
1827
                    FILTER NOT EXISTS {
1828
                      GRAPH <%3$s> {
1829
                        ?canonAdmin a gen:RoleInstantiation ;
1830
                                    npa:inverseProperty gen:hasAdmin ;
1831
                                    npa:forSpaceRef ?canonRef ;
1832
                                    npa:forAgent ?otherAgent .
1833
                      }
1834
                    }
1835
                  }
1836
                  # 4. Invalidation filter on the declaration's nanopub.
1837
                  %6$s
1838
                  # 5. Load-number filter on bound ?np.
1839
                  GRAPH <%7$s> {
1840
                    ?np npa:hasLoadNumber ?ln .
1841
                    FILTER (?ln > %5$d)
1842
                  }
1843
                  # 6. Dedup last — on the emitted (alias, canonical ref) edge.
1844
                  FILTER NOT EXISTS { GRAPH <%3$s> {
1845
                    ?alias npa:sameAsSpace ?canonRef .
1846
                  } }
1847
                }
1848
                """.formatted(
3✔
1849
                NPA.NAMESPACE,
1850
                GEN.NAMESPACE,
1851
                graph,
1852
                SpacesVocab.SPACES_GRAPH,
1853
                lastProcessed,
15✔
1854
                invalidationFilter("np"),
18✔
1855
                NPA.GRAPH);
1856
    }
1857

1858
    /**
1859
     * URL-prefix sub-space fallback admit pass. For every pair of {@code SpaceRef}
1860
     * aggregates where the child's {@code npa:hasIdPrefix} matches the parent's
1861
     * {@code npa:spaceIri}, emits convenience {@code <child> npa:isSubSpaceOf <parent>}
1862
     * and {@code <parent> npa:hasSubSpace <child>} direct triples plus a reified
1863
     * {@code npa:DerivedSubSpaceLink} tag carrying {@code npa:derivationKind
1864
     * npa:byUrlPrefix} so consumers can hide derived edges.
1865
     *
1866
     * <p>Per-child suppression: any validated {@code npa:SubSpaceDeclaration} on the
1867
     * child in {@code npass:<…>} suppresses every fallback edge for that child.
1868
     * Suppression checks the validated set (not raw extraction-graph declarations)
1869
     * so an unapproved or in-flight Mode B declaration doesn't silently hide both
1870
     * the URL-prefix fallback and the (still-invalid) explicit relation.
1871
     *
1872
     * <p>Run order: must run after {@link #subSpaceAdmitUpdate} commits in the
1873
     * same cycle so the suppression check sees this cycle's freshly-validated
1874
     * declarations.
1875
     *
1876
     * <p>No load-number filter: the fallback depends on which Spaces exist (parent
1877
     * + child {@code SpaceRef}s), not on which were just added. Always full-scan;
1878
     * the dedup {@code FILTER NOT EXISTS} on the tag IRI prevents re-insertion.
1879
     *
1880
     * <p>No invalidation handling: derived edges have no source nanopub. Two
1881
     * staleness modes: (a) child later gets first validated declaration → old
1882
     * derived edges stay sticky until the next periodic rebuild (same policy as
1883
     * admin-RI invalidation); (b) child loses last validated declaration → the
1884
     * regular fallback pass on the next cycle re-engages, adds derived edges
1885
     * incrementally, no rebuild needed.
1886
     */
1887
    static String subSpacePrefixFallbackUpdate(IRI graph) {
1888
        return """
48✔
1889
                PREFIX npa: <%1$s>
1890
                INSERT { GRAPH <%2$s> {
1891
                  ?childRef  npa:isSubSpaceOf ?parentRef .
1892
                  ?parentRef npa:hasSubSpace  ?childRef  .
1893
                  # TRANSITIONAL-DUAL-EMIT (Phase 1.5; remove in Phase 4): IRI-valued
1894
                  # derived sub-space edge alongside the ref-to-ref one, mirroring the
1895
                  # explicit sub-space pass, so pre-ref published queries keep binding on a
1896
                  # mixed-version fleet. See doc/report-2026-06-12-mixed-fleet-spaceref-breakage.md.
1897
                  ?child  npa:isSubSpaceOf ?parent .
1898
                  ?parent npa:hasSubSpace  ?child  .
1899
                  ?tagIri a npa:DerivedSubSpaceLink ;
1900
                          npa:childSpace     ?child ;
1901
                          npa:parentSpace    ?parent ;
1902
                          npa:derivationKind npa:byUrlPrefix .
1903
                } }
1904
                WHERE {
1905
                  # 1. Anchor: child SpaceRef → its path-prefixes (extracted at load
1906
                  #    time from the Space IRI; see SpacesExtractor.enumerateIdPrefixes).
1907
                  GRAPH <%3$s> {
1908
                    ?childRef  npa:spaceIri    ?child ;
1909
                               npa:hasIdPrefix ?parent .
1910
                    # 2. Parent SpaceRef must exist for the same IRI as the prefix.
1911
                    ?parentRef npa:spaceIri    ?parent .
1912
                  }
1913
                  # 3. Suppress fallback for any child that has a validated declaration
1914
                  #    in this state graph. Per-child IRI, all-or-nothing.
1915
                  FILTER NOT EXISTS {
1916
                    GRAPH <%2$s> {
1917
                      ?d a npa:SubSpaceDeclaration ;
1918
                         npa:childSpace ?child .
1919
                    }
1920
                  }
1921
                  # 4. Mint a deterministic tag IRI per (child ref, parent ref) — the edge
1922
                  #    is emitted ref-to-ref, so the tag and dedup are per ref-pair.
1923
                  BIND(IRI(CONCAT("http://purl.org/nanopub/admin/derivedlink/",
1924
                                  MD5(CONCAT(STR(?childRef), "|", STR(?parentRef))))) AS ?tagIri)
1925
                  # 5. Dedup: don't re-insert if this tag is already present.
1926
                  FILTER NOT EXISTS {
1927
                    GRAPH <%2$s> {
1928
                      ?tagIri a npa:DerivedSubSpaceLink .
1929
                    }
1930
                  }
1931
                }
1932
                """.formatted(
3✔
1933
                NPA.NAMESPACE,
1934
                graph,
1935
                SpacesVocab.SPACES_GRAPH);
1936
    }
1937

1938
    // ---------------- Invalidation templates (incremental cycle) ----------------
1939

1940
    /**
1941
     * WHERE clause shared by the admin-RI invalidation ASK precheck and the
1942
     * matching DELETE. Identifies admin-tier {@code gen:RoleInstantiation} rows
1943
     * in the space-state graph whose {@code npa:viaNanopub} is the target of an
1944
     * {@code npx:invalidates} triple in {@code npa:graph} whose subject nanopub
1945
     * has a load number in {@code (lastProcessed, ∞)}.
1946
     */
1947
    static String adminInvalidationCheckWhere(IRI graph, long lastProcessed) {
1948
        return String.format("""
60✔
1949
                  GRAPH <%1$s> {
1950
                    ?ri a gen:RoleInstantiation ;
1951
                        npa:inverseProperty gen:hasAdmin ;
1952
                        npa:viaNanopub ?np .
1953
                  }
1954
                  GRAPH <%2$s> {
1955
                    ?invNp <%3$s> ?np ;
1956
                           npa:hasLoadNumber ?ln .
1957
                    FILTER (?ln > %4$d)
1958
                    %5$s
1959
                  }
1960
                """, graph, NPA.GRAPH, NPX.INVALIDATES, lastProcessed,
18✔
1961
                samePublisherClause("invNp", "np"));
6✔
1962
    }
1963

1964
    /** DELETE template for admin-tier RoleInstantiations whose source nanopub was invalidated. */
1965
    static String adminInvalidationDelete(IRI graph, long lastProcessed) {
1966
        return String.format("""
63✔
1967
                PREFIX npa: <%1$s>
1968
                PREFIX gen: <%2$s>
1969
                DELETE { GRAPH <%3$s> {
1970
                  ?ri ?p ?o .
1971
                } }
1972
                WHERE {
1973
                  GRAPH <%3$s> { ?ri ?p ?o . }
1974
                %4$s
1975
                }
1976
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
1977
                adminInvalidationCheckWhere(graph, lastProcessed));
6✔
1978
    }
1979

1980
    /** WHERE clause for RoleAssignment invalidation. */
1981
    static String roleAssignmentInvalidationCheckWhere(IRI graph, long lastProcessed) {
1982
        return String.format("""
60✔
1983
                  GRAPH <%1$s> {
1984
                    ?ra a gen:RoleAssignment ;
1985
                        npa:viaNanopub ?np .
1986
                  }
1987
                  GRAPH <%2$s> {
1988
                    ?invNp <%3$s> ?np ;
1989
                           npa:hasLoadNumber ?ln .
1990
                    FILTER (?ln > %4$d)
1991
                    %5$s
1992
                  }
1993
                """, graph, NPA.GRAPH, NPX.INVALIDATES, lastProcessed,
18✔
1994
                samePublisherClause("invNp", "np"));
6✔
1995
    }
1996

1997
    /** DELETE template for RoleAssignments whose source nanopub was invalidated. */
1998
    static String roleAssignmentInvalidationDelete(IRI graph, long lastProcessed) {
1999
        return String.format("""
63✔
2000
                PREFIX npa: <%1$s>
2001
                PREFIX gen: <%2$s>
2002
                DELETE { GRAPH <%3$s> {
2003
                  ?ra ?p ?o .
2004
                } }
2005
                WHERE {
2006
                  GRAPH <%3$s> { ?ra ?p ?o . }
2007
                %4$s
2008
                }
2009
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
2010
                roleAssignmentInvalidationCheckWhere(graph, lastProcessed));
6✔
2011
    }
2012

2013
    /**
2014
     * DELETE template for non-admin (leaf-tier) RoleInstantiations whose source
2015
     * nanopub was invalidated. Identified as {@code gen:RoleInstantiation} rows
2016
     * lacking the admin-pinning {@code npa:inverseProperty gen:hasAdmin} triple.
2017
     * No flag is set; leaf-tier removals are recoverable on the next cycle.
2018
     */
2019
    static String leafTierInvalidationDelete(IRI graph, long lastProcessed) {
2020
        return String.format("""
84✔
2021
                PREFIX npa: <%1$s>
2022
                PREFIX gen: <%2$s>
2023
                DELETE { GRAPH <%3$s> {
2024
                  ?ri ?p ?o .
2025
                } }
2026
                WHERE {
2027
                  GRAPH <%3$s> {
2028
                    ?ri a gen:RoleInstantiation ;
2029
                        npa:viaNanopub ?np .
2030
                    FILTER NOT EXISTS { ?ri npa:inverseProperty gen:hasAdmin }
2031
                    ?ri ?p ?o .
2032
                  }
2033
                  GRAPH <%4$s> {
2034
                    ?invNp <%5$s> ?np ;
2035
                           npa:hasLoadNumber ?ln .
2036
                    FILTER (?ln > %6$d)
2037
                    %7$s
2038
                  }
2039
                }
2040
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
2041
                NPA.GRAPH, NPX.INVALIDATES, lastProcessed,
18✔
2042
                samePublisherClause("invNp", "np"));
6✔
2043
    }
2044

2045
    /**
2046
     * WHERE clause shared by the sub-space invalidation ASK precheck and the
2047
     * matching DELETE. Identifies validated {@code npa:SubSpaceDeclaration} rows
2048
     * in the space-state graph whose {@code npa:viaNanopub} is the target of an
2049
     * {@code npx:invalidates} triple in {@code npa:graph} whose subject nanopub
2050
     * has a load number in {@code (lastProcessed, ∞)}.
2051
     */
2052
    static String subSpaceInvalidationCheckWhere(IRI graph, long lastProcessed) {
2053
        return String.format("""
60✔
2054
                  GRAPH <%1$s> {
2055
                    ?d a npa:SubSpaceDeclaration ;
2056
                       npa:viaNanopub ?np .
2057
                  }
2058
                  GRAPH <%2$s> {
2059
                    ?invNp <%3$s> ?np ;
2060
                           npa:hasLoadNumber ?ln .
2061
                    FILTER (?ln > %4$d)
2062
                    %5$s
2063
                  }
2064
                """, graph, NPA.GRAPH, NPX.INVALIDATES, lastProcessed,
18✔
2065
                samePublisherClause("invNp", "np"));
6✔
2066
    }
2067

2068
    /**
2069
     * DELETE template for validated {@code npa:SubSpaceDeclaration} rows whose
2070
     * source nanopub was invalidated. Removes the per-declaration row by subject;
2071
     * the convenience direct triples ({@code <child> npa:isSubSpaceOf <parent>}
2072
     * and inverse) are left sticky and cleaned by the next periodic full rebuild
2073
     * (same staleness policy as admin-RI invalidation — see {@code
2074
     * doc/design-space-repositories.md} on the structural-rebuild flag).
2075
     */
2076
    static String subSpaceInvalidationDelete(IRI graph, long lastProcessed) {
2077
        return String.format("""
63✔
2078
                PREFIX npa: <%1$s>
2079
                PREFIX gen: <%2$s>
2080
                DELETE { GRAPH <%3$s> {
2081
                  ?d ?p ?o .
2082
                } }
2083
                WHERE {
2084
                  GRAPH <%3$s> { ?d ?p ?o . }
2085
                %4$s
2086
                }
2087
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
2088
                subSpaceInvalidationCheckWhere(graph, lastProcessed));
6✔
2089
    }
2090

2091
    /**
2092
     * DELETE template for validated {@code npa:MaintainedResourceDeclaration} rows
2093
     * whose source nanopub was invalidated. Removes the per-declaration row by
2094
     * subject; the convenience direct triples ({@code <r> npa:isMaintainedBy <s>}
2095
     * and inverse) are left sticky and cleaned by the next periodic full rebuild
2096
     * (same staleness policy as sub-space declaration invalidation, but without
2097
     * the structural-rebuild flag — maintained-resource is a leaf relation, no
2098
     * downstream consumers depend on its closure).
2099
     */
2100
    static String maintainedResourceInvalidationDelete(IRI graph, long lastProcessed) {
2101
        return String.format("""
84✔
2102
                PREFIX npa: <%1$s>
2103
                PREFIX gen: <%2$s>
2104
                DELETE { GRAPH <%3$s> {
2105
                  ?d ?p ?o .
2106
                } }
2107
                WHERE {
2108
                  GRAPH <%3$s> {
2109
                    ?d a npa:MaintainedResourceDeclaration ;
2110
                       npa:viaNanopub ?np .
2111
                    ?d ?p ?o .
2112
                  }
2113
                  GRAPH <%4$s> {
2114
                    ?invNp <%5$s> ?np ;
2115
                           npa:hasLoadNumber ?ln .
2116
                    FILTER (?ln > %6$d)
2117
                    %7$s
2118
                  }
2119
                }
2120
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
2121
                NPA.GRAPH, NPX.INVALIDATES, lastProcessed,
18✔
2122
                samePublisherClause("invNp", "np"));
6✔
2123
    }
2124

2125
    /**
2126
     * WHERE clause shared by the alias invalidation ASK precheck and the matching
2127
     * DELETE. Identifies validated {@code npa:SpaceAliasDeclaration} rows in the
2128
     * space-state graph whose {@code npa:viaNanopub} is the target of an
2129
     * {@code npx:invalidates} triple in {@code npa:graph} whose subject nanopub has a
2130
     * load number in {@code (lastProcessed, ∞)}.
2131
     */
2132
    static String aliasInvalidationCheckWhere(IRI graph, long lastProcessed) {
2133
        return String.format("""
60✔
2134
                  GRAPH <%1$s> {
2135
                    ?d a npa:SpaceAliasDeclaration ;
2136
                       npa:viaNanopub ?np .
2137
                  }
2138
                  GRAPH <%2$s> {
2139
                    ?invNp <%3$s> ?np ;
2140
                           npa:hasLoadNumber ?ln .
2141
                    FILTER (?ln > %4$d)
2142
                    %5$s
2143
                  }
2144
                """, graph, NPA.GRAPH, NPX.INVALIDATES, lastProcessed,
18✔
2145
                samePublisherClause("invNp", "np"));
6✔
2146
    }
2147

2148
    /**
2149
     * DELETE template for validated {@code npa:SpaceAliasDeclaration} rows whose
2150
     * source nanopub was invalidated. Removes the per-declaration row by subject; the
2151
     * convenience {@code <alias> npa:sameAsSpace <canonical>} edge is left sticky and
2152
     * cleaned by the next periodic full rebuild (same staleness policy as sub-space
2153
     * declaration invalidation — the alias feeds the authority closure, so this kind
2154
     * is structural and flips {@code npa:needsFullRebuild}).
2155
     */
2156
    static String aliasInvalidationDelete(IRI graph, long lastProcessed) {
2157
        return String.format("""
63✔
2158
                PREFIX npa: <%1$s>
2159
                PREFIX gen: <%2$s>
2160
                DELETE { GRAPH <%3$s> {
2161
                  ?d ?p ?o .
2162
                } }
2163
                WHERE {
2164
                  GRAPH <%3$s> { ?d ?p ?o . }
2165
                %4$s
2166
                }
2167
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
2168
                aliasInvalidationCheckWhere(graph, lastProcessed));
6✔
2169
    }
2170

2171
    /**
2172
     * WHERE clause shared by the preset-deactivation ASK precheck and the matching DELETE
2173
     * (Nanodash issue #302). Binds {@code ?ra} = a materialized preset-derived
2174
     * {@code gen:RoleAssignment} ({@code npa:derivedFromPreset}) for which a <em>newer,
2175
     * admin-authored</em> same-{@code (preset, resource)} assignment exists by
2176
     * {@code dct:created} (load number in {@code (lastProcessed, ∞)}). This is NOT an
2177
     * {@code npx:invalidates} check — preset activation is latest-wins by timestamp.
2178
     *
2179
     * <p>Authorization-scoped (anti-hijack, design doc §3/§4.4): the newer assignment's
2180
     * publisher must itself be a validated admin of the row's {@code npa:forSpaceRef}, so an
2181
     * unauthorized key's newer assignment can neither delete nor shadow an admin's
2182
     * materialized role. {@code dct:created} is written as a full IRI (not a {@code dct:}
2183
     * prefix) because {@link #wouldInvalidate}'s ASK wrapper only declares {@code npa:} /
2184
     * {@code gen:}.
2185
     */
2186
    static String presetDeactivationCheckWhere(IRI graph, long lastProcessed) {
2187
        return String.format("""
60✔
2188
                  GRAPH <%1$s> {
2189
                    ?ra a gen:RoleAssignment ;
2190
                        npa:derivedFromPreset ?assignNp ;
2191
                        npa:forSpaceRef ?targetRef .
2192
                  }
2193
                  GRAPH <%2$s> {
2194
                    ?pa a npa:PresetAssignment ;
2195
                        npa:viaNanopub  ?assignNp ;
2196
                        npa:ofPreset    ?preset ;
2197
                        npa:forResource ?resource ;
2198
                        <http://purl.org/dc/terms/created> ?created .
2199
                    ?paNewer a npa:PresetAssignment ;
2200
                             npa:ofPreset    ?preset ;
2201
                             npa:forResource ?resource ;
2202
                             npa:pubkeyHash  ?pkhNewer ;
2203
                             npa:viaNanopub  ?assignNpNewer ;
2204
                             <http://purl.org/dc/terms/created> ?createdNewer .
2205
                    FILTER (?createdNewer > ?created
2206
                            || (?createdNewer = ?created && STR(?paNewer) > STR(?pa)))
2207
                  }
2208
                  GRAPH <%3$s> {
2209
                    ?assignNpNewer npa:hasLoadNumber ?lnNewer .
2210
                    FILTER (?lnNewer > %4$d)
2211
                  }
2212
                  GRAPH <%1$s> {
2213
                    ?acctNewer a npa:AccountState ;
2214
                               npa:agent  ?publisherNewer ;
2215
                               npa:pubkey ?pkhNewer .
2216
                    ?adminRINewer a gen:RoleInstantiation ;
2217
                                  npa:forSpaceRef ?targetRef ;
2218
                                  npa:inverseProperty gen:hasAdmin ;
2219
                                  npa:forAgent ?publisherNewer .
2220
                  }
2221
                """, graph, SpacesVocab.SPACES_GRAPH, NPA.GRAPH, lastProcessed);
6✔
2222
    }
2223

2224
    /**
2225
     * DELETE template for preset-derived {@code gen:RoleAssignment} rows superseded by a
2226
     * newer admin-authored same-pair assignment (issue #302). Removes the whole row by
2227
     * subject; scoped via {@code npa:derivedFromPreset} so directly-published attachments
2228
     * are never touched. The {@link #presetAttachmentValidationUpdate} re-INSERT in the
2229
     * same cycle re-materializes the pair iff the newest assignment is still active.
2230
     */
2231
    static String presetDeactivationDelete(IRI graph, long lastProcessed) {
2232
        return String.format("""
63✔
2233
                PREFIX npa: <%1$s>
2234
                PREFIX gen: <%2$s>
2235
                DELETE { GRAPH <%3$s> {
2236
                  ?ra ?p ?o .
2237
                } }
2238
                WHERE {
2239
                  GRAPH <%3$s> { ?ra ?p ?o . }
2240
                %4$s
2241
                }
2242
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
2243
                presetDeactivationCheckWhere(graph, lastProcessed));
6✔
2244
    }
2245

2246
    /**
2247
     * DELETE template for ref-scoped preset-assignment stamps ({@link
2248
     * #presetAssignmentRefStampUpdate}) whose underlying assignment nanopub was
2249
     * hard-retracted (issue #122). Removes the whole row by subject; scoped to
2250
     * state-graph {@code npa:PresetAssignment} rows that carry {@code npa:forSpaceRef}
2251
     * (the IRI-keyed extraction rows never do), so it can never touch them.
2252
     *
2253
     * <p>Leaf delete — no structural flag: nothing downstream derives from a listing
2254
     * stamp, so a stale row only mis-displays a retracted assignment until this cycle's
2255
     * delete runs. Admin-grant revocation is bounded by the periodic full rebuild (same
2256
     * sticky-convenience policy as the alias / sub-space declaration edges). A
2257
     * <em>deactivation</em> needs no delete here: it is represented as a newer
2258
     * admin-authored stamp with {@code npa:isActivated false}, resolved by the consumer's
2259
     * latest-wins.
2260
     */
2261
    static String presetAssignmentRefInvalidationDelete(IRI graph, long lastProcessed) {
2262
        return String.format("""
84✔
2263
                PREFIX npa: <%1$s>
2264
                PREFIX gen: <%2$s>
2265
                DELETE { GRAPH <%3$s> {
2266
                  ?paRef ?p ?o .
2267
                } }
2268
                WHERE {
2269
                  GRAPH <%3$s> {
2270
                    ?paRef a npa:PresetAssignment ;
2271
                           npa:forSpaceRef ?targetRef ;
2272
                           npa:viaNanopub  ?assignNp .
2273
                    ?paRef ?p ?o .
2274
                  }
2275
                  GRAPH <%4$s> {
2276
                    ?invNp <%5$s> ?assignNp ;
2277
                           npa:hasLoadNumber ?ln .
2278
                    FILTER (?ln > %6$d)
2279
                    %7$s
2280
                  }
2281
                }
2282
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
2283
                NPA.GRAPH, NPX.INVALIDATES, lastProcessed,
18✔
2284
                samePublisherClause("invNp", "assignNp"));
6✔
2285
    }
2286

2287
    /** Wraps an ASK by joining the shared prefixes. */
2288
    private boolean wouldInvalidate(IRI graph, long lastProcessed,
2289
                                    boolean adminPinned, String whereClause) {
2290
        // adminPinned is informational only — kept to make call sites read clearly;
2291
        // the WHERE clause already encodes the kind via its own type predicates.
2292
        String ask = String.format("""
×
2293
                PREFIX npa: <%1$s>
2294
                PREFIX gen: <%2$s>
2295
                ASK { %3$s }
2296
                """, NPA.NAMESPACE, GEN.NAMESPACE, whereClause);
2297
        return runAsk(ask);
×
2298
    }
2299

2300
    private boolean runAsk(String sparql) {
2301
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
2302
            return conn.prepareBooleanQuery(QueryLanguage.SPARQL, sparql).evaluate();
×
2303
        }
2304
    }
2305

2306
    private void executeUpdate(String sparqlUpdate) {
2307
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
2308
            conn.prepareUpdate(QueryLanguage.SPARQL, sparqlUpdate).execute();
×
2309
        }
2310
    }
×
2311

2312
    // ---------------- Mirror step ----------------
2313

2314
    /**
2315
     * Copies trust-approved {@code npa:AccountState} rows from {@code npat:<T>}
2316
     * in the {@code trust} repo into {@code newGraph} in the {@code spaces} repo,
2317
     * inside one spaces-side serializable transaction.
2318
     *
2319
     * @return number of rows mirrored (useful for metrics / logging)
2320
     */
2321
    int mirrorTrustState(String trustStateHash, IRI newGraph) {
2322
        IRI trustStateIri = NPAT.forHash(trustStateHash);
×
2323
        int count = 0;
×
2324
        try (RepositoryConnection trustConn = TripleStore.get().getRepoConnection(TRUST_REPO);
×
2325
             RepositoryConnection spacesConn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
2326
            trustConn.begin(IsolationLevels.READ_COMMITTED);
×
2327
            spacesConn.begin(IsolationLevels.SERIALIZABLE);
×
2328
            // Walk rdf:type triples in the trust state's graph; for each AccountState,
2329
            // check status and copy the approved ones verbatim (minus status-specific
2330
            // detail triples, which we don't need for validation).
2331
            try (RepositoryResult<Statement> typeRows = trustConn.getStatements(
×
2332
                    null, RDF.TYPE, NPA_ACCOUNT_STATE, trustStateIri)) {
2333
                while (typeRows.hasNext()) {
×
2334
                    Statement st = typeRows.next();
×
2335
                    if (!(st.getSubject() instanceof IRI accountStateIri)) continue;
×
2336
                    Value status = trustConn.getStatements(accountStateIri, NPA_TRUST_STATUS, null, trustStateIri)
×
2337
                            .stream().findFirst().map(Statement::getObject).orElse(null);
×
2338
                    if (!(status instanceof IRI statusIri) || !APPROVED_SET.contains(statusIri)) continue;
×
2339
                    Value agent = trustConn.getStatements(accountStateIri, NPA_AGENT, null, trustStateIri)
×
2340
                            .stream().findFirst().map(Statement::getObject).orElse(null);
×
2341
                    Value pubkey = trustConn.getStatements(accountStateIri, NPA_PUBKEY, null, trustStateIri)
×
2342
                            .stream().findFirst().map(Statement::getObject).orElse(null);
×
2343
                    if (agent == null || pubkey == null) {
×
2344
                        logger.warn("AuthorityResolver.mirror: account {} missing agent or pubkey; skipping",
×
2345
                                accountStateIri);
2346
                        continue;
×
2347
                    }
2348
                    spacesConn.add(accountStateIri, RDF.TYPE, NPA_ACCOUNT_STATE, newGraph);
×
2349
                    spacesConn.add(accountStateIri, NPA_AGENT, agent, newGraph);
×
2350
                    spacesConn.add(accountStateIri, NPA_PUBKEY, pubkey, newGraph);
×
2351
                    spacesConn.add(accountStateIri, NPA_TRUST_STATUS, statusIri, newGraph);
×
2352
                    count++;
×
2353
                }
×
2354
            }
2355
            // Mirror canonical foaf:name triples for approved agents. The trust
2356
            // loader emits one per agent (across approved keys, MAX(ratio) wins).
2357
            // Copying them into the space-state graph means consumers reading
2358
            // ?agent foaf:name ?n inside the state graph hit local data, with no
2359
            // cross-repo SERVICE.
2360
            try (RepositoryResult<Statement> nameRows = trustConn.getStatements(
×
2361
                    null, FOAF.NAME, null, trustStateIri)) {
2362
                while (nameRows.hasNext()) {
×
2363
                    Statement st = nameRows.next();
×
2364
                    spacesConn.add(st.getSubject(), st.getPredicate(), st.getObject(), newGraph);
×
2365
                }
×
2366
            }
2367
            spacesConn.commit();
×
2368
            trustConn.commit();
×
2369
        }
2370
        return count;
×
2371
    }
2372

2373
    // ---------------- Pointer + counter helpers ----------------
2374

2375
    /**
2376
     * Reads the current {@code npa:hasCurrentSpaceState} pointer from the
2377
     * {@code npa:graph} admin graph of the {@code spaces} repo. Returns
2378
     * {@code null} if no pointer exists yet.
2379
     */
2380
    IRI getCurrentSpaceStateGraph() {
2381
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
2382
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
2383
                    SpacesVocab.HAS_CURRENT_SPACE_STATE);
2384
            return (v instanceof IRI iri) ? iri : null;
×
2385
        } catch (Exception ex) {
×
2386
            logger.warn("AuthorityResolver: failed to read hasCurrentSpaceState pointer: {}", ex.toString());
×
2387
            return null;
×
2388
        }
2389
    }
2390

2391
    long getCurrentLoadCounter() {
2392
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
2393
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
2394
                    SpacesVocab.CURRENT_LOAD_COUNTER);
2395
            if (v == null) return 0;
×
2396
            try {
2397
                return Long.parseLong(v.stringValue());
×
2398
            } catch (NumberFormatException ex) {
×
2399
                logger.warn("AuthorityResolver: non-numeric currentLoadCounter: {}", v);
×
2400
                return 0;
×
2401
            }
2402
        } catch (Exception ex) {
×
2403
            logger.warn("AuthorityResolver: failed to read currentLoadCounter: {}", ex.toString());
×
2404
            return 0;
×
2405
        }
2406
    }
2407

2408
    /**
2409
     * Atomic pointer flip: a single SPARQL {@code DELETE … INSERT … WHERE}
2410
     * replaces the old pointer with the new one in one statement, so readers
2411
     * never see a zero-pointer window.
2412
     */
2413
    void flipPointer(IRI newGraph) {
2414
        String update = String.format("""
×
2415
                DELETE { GRAPH <%s> { <%s> <%s> ?old } }
2416
                INSERT { GRAPH <%s> { <%s> <%s> <%s> } }
2417
                WHERE  { OPTIONAL { GRAPH <%s> { <%s> <%s> ?old } } }
2418
                """,
2419
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.HAS_CURRENT_SPACE_STATE,
2420
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.HAS_CURRENT_SPACE_STATE, newGraph,
2421
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.HAS_CURRENT_SPACE_STATE);
2422
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
2423
            conn.begin(IsolationLevels.SERIALIZABLE);
×
2424
            conn.prepareUpdate(QueryLanguage.SPARQL, update).execute();
×
2425
            conn.commit();
×
2426
        }
2427
    }
×
2428

2429
    void writeProcessedUpTo(IRI graph, long loadCounter) {
2430
        String update = String.format("""
×
2431
                DELETE { GRAPH <%s> { <%s> <%s> ?old } }
2432
                INSERT { GRAPH <%s> { <%s> <%s> "%d"^^<http://www.w3.org/2001/XMLSchema#long> } }
2433
                WHERE  { OPTIONAL { GRAPH <%s> { <%s> <%s> ?old } } }
2434
                """,
2435
                graph, graph, SpacesVocab.PROCESSED_UP_TO,
2436
                graph, graph, SpacesVocab.PROCESSED_UP_TO, loadCounter,
×
2437
                graph, graph, SpacesVocab.PROCESSED_UP_TO);
2438
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
2439
            conn.begin(IsolationLevels.SERIALIZABLE);
×
2440
            conn.prepareUpdate(QueryLanguage.SPARQL, update).execute();
×
2441
            conn.commit();
×
2442
        }
2443
    }
×
2444

2445
    /**
2446
     * Reads {@code processedUpTo} from the given space-state graph.
2447
     * Returns {@code -1} if absent (graph not fully built yet).
2448
     */
2449
    long readProcessedUpTo(IRI graph) {
2450
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
2451
            String query = String.format(
×
2452
                    "SELECT ?n WHERE { GRAPH <%s> { <%s> <%s> ?n } }",
2453
                    graph, graph, SpacesVocab.PROCESSED_UP_TO);
2454
            try (TupleQueryResult r = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) {
×
2455
                if (!r.hasNext()) return -1;
×
2456
                BindingSet b = r.next();
×
2457
                return Long.parseLong(b.getBinding("n").getValue().stringValue());
×
2458
            }
×
2459
        } catch (Exception ex) {
×
2460
            logger.warn("AuthorityResolver: failed to read processedUpTo for {}: {}", graph, ex.toString());
×
2461
            return -1;
×
2462
        }
2463
    }
2464

2465
    /**
2466
     * Reads the {@code npa:needsFullRebuild} flag (boolean literal) from
2467
     * {@code npa:graph} in the {@code spaces} repo. Defaults to {@code false}
2468
     * when the triple is absent.
2469
     */
2470
    boolean readNeedsFullRebuild() {
2471
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
2472
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
2473
                    SpacesVocab.NEEDS_FULL_REBUILD);
2474
            return v != null && Boolean.parseBoolean(v.stringValue());
×
2475
        } catch (Exception ex) {
×
2476
            logger.warn("AuthorityResolver: failed to read needsFullRebuild: {}", ex.toString());
×
2477
            return false;
×
2478
        }
2479
    }
2480

2481
    void setNeedsFullRebuild() {
2482
        writeNeedsFullRebuild(true);
×
2483
    }
×
2484

2485
    void clearNeedsFullRebuild() {
2486
        writeNeedsFullRebuild(false);
×
2487
    }
×
2488

2489
    private void writeNeedsFullRebuild(boolean value) {
2490
        String update = String.format("""
×
2491
                DELETE { GRAPH <%s> { <%s> <%s> ?old } }
2492
                INSERT { GRAPH <%s> { <%s> <%s> "%s"^^<http://www.w3.org/2001/XMLSchema#boolean> } }
2493
                WHERE  { OPTIONAL { GRAPH <%s> { <%s> <%s> ?old } } }
2494
                """,
2495
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.NEEDS_FULL_REBUILD,
2496
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.NEEDS_FULL_REBUILD, value,
×
2497
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.NEEDS_FULL_REBUILD);
2498
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
2499
            conn.begin(IsolationLevels.SERIALIZABLE);
×
2500
            conn.prepareUpdate(QueryLanguage.SPARQL, update).execute();
×
2501
            conn.commit();
×
2502
        }
2503
    }
×
2504

2505
    void dropGraph(IRI graph) {
2506
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
2507
            conn.begin(IsolationLevels.SERIALIZABLE);
×
2508
            conn.clear(graph);
×
2509
            conn.commit();
×
2510
            logger.info("AuthorityResolver: dropped old space-state graph {}", graph);
×
2511
        }
2512
    }
×
2513

2514
    // ---------------- Trust-repo pointer lookup (used by TrustStateRegistry's bootstrap) ----------------
2515

2516
    /**
2517
     * Queries the {@code trust} repo directly for the current trust-state hash.
2518
     * Prefer {@link TrustStateRegistry#getCurrentHash()} in normal operation —
2519
     * this helper exists for tests and diagnostics.
2520
     *
2521
     * @return the current trust-state hash, or empty if none is set
2522
     */
2523
    Optional<String> readTrustRepoCurrentHash() {
2524
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(TRUST_REPO)) {
×
2525
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
2526
                    NPA_HAS_CURRENT_TRUST_STATE);
2527
            if (!(v instanceof IRI iri)) return Optional.empty();
×
2528
            String s = iri.stringValue();
×
2529
            if (!s.startsWith(NPAT.NAMESPACE)) return Optional.empty();
×
2530
            return Optional.of(s.substring(NPAT.NAMESPACE.length()));
×
2531
        } catch (Exception ex) {
×
2532
            logger.warn("AuthorityResolver: failed to read trust-repo current pointer: {}", ex.toString());
×
2533
            return Optional.empty();
×
2534
        }
2535
    }
2536

2537
    private static String abbrev(String hash) {
2538
        return hash.length() > 12 ? hash.substring(0, 12) + "…" : hash;
×
2539
    }
2540

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