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

knowledgepixels / nanopub-query / 28017810007

23 Jun 2026 09:53AM UTC coverage: 61.38% (+0.3%) from 61.075%
28017810007

push

github

web-flow
Merge pull request #124 from knowledgepixels/fix/custom-role-predicate-resolution

fix(spaces): resolve custom role-predicate direction+tier from the role declaration

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
                       npa:forAgent ?agent ;
866
                       npa:viaNanopub ?np .
867
                } }
868
                WHERE {
869
                  # 1. Anchor: who is already an admin of which space ref?
870
                  {
871
                    # Seed branch: root-admin of a space ref that is still alive
872
                    # (has at least one non-invalidated definition). NOT filtered on
873
                    # ?def's own invalidation — superseding the root nanopub with a
874
                    # continuation revision must keep the seed; only a fully-retracted
875
                    # ref drops it (issue #110).
876
                    GRAPH <%4$s> {
877
                      ?def a npa:SpaceDefinition ;
878
                           npa:forSpaceRef  ?spaceRef ;
879
                           npa:hasRootAdmin ?publisher .
880
                      ?spaceRef npa:spaceIri ?space .
881
                    }
882
                    %7$s
883
                  }
884
                  UNION
885
                  {
886
                    # Closed-over branch: an existing admin of this ref. Recurse on the
887
                    # ref, then resolve its bare IRI to probe the IRI-keyed instantiation.
888
                    GRAPH <%3$s> {
889
                      ?prev a gen:RoleInstantiation ;
890
                            npa:forSpaceRef     ?spaceRef ;
891
                            npa:inverseProperty gen:hasAdmin ;
892
                            npa:forAgent        ?publisher .
893
                    }
894
                    GRAPH <%4$s> {
895
                      ?spaceRef npa:spaceIri ?space .
896
                    }
897
                  }
898
                  # 2. Mirror: resolve ?publisher → ?pkh via the trust-approved row.
899
                  GRAPH <%3$s> {
900
                    ?acct a npa:AccountState ;
901
                          npa:agent  ?publisher ;
902
                          npa:pubkey ?pkh .
903
                  }
904
                  # 3. Targeted instantiation lookup by space + pubkey (IRI-keyed).
905
                  GRAPH <%4$s> {
906
                    ?ri a gen:RoleInstantiation ;
907
                        npa:forSpace        ?space ;
908
                        npa:inverseProperty gen:hasAdmin ;
909
                        npa:forAgent        ?agent ;
910
                        npa:pubkeyHash      ?pkh ;
911
                        npa:viaNanopub      ?np .
912
                  }
913
                  # 3a. Mint the per-ref state subject: (?ri, ?spaceRef) → ?sri.
914
                  BIND(IRI(CONCAT(STR(?ri), "__", ENCODE_FOR_URI(STR(?spaceRef)))) AS ?sri)
915
                  %6$s
916
                  # 4. Load-number filter on bound ?np.
917
                  GRAPH <%8$s> {
918
                    ?np npa:hasLoadNumber ?ln .
919
                    FILTER (?ln > %5$d)
920
                  }
921
                  # 5. Dedup last — keyed on (ref, agent).
922
                  FILTER NOT EXISTS { GRAPH <%3$s> {
923
                    ?existing a gen:RoleInstantiation ;
924
                              npa:forSpaceRef ?spaceRef ;
925
                              npa:forAgent ?agent ;
926
                              npa:inverseProperty gen:hasAdmin .
927
                  } }
928
                }
929
                """.formatted(
3✔
930
                NPA.NAMESPACE,
931
                GEN.NAMESPACE,
932
                graph,
933
                SpacesVocab.SPACES_GRAPH,
934
                lastProcessed,
15✔
935
                invalidationFilter("np"),
12✔
936
                spaceRefAliveFilter(),
18✔
937
                NPA.GRAPH);
938
    }
939

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

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

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

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

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

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

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

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

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

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

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

1924
    // ---------------- Invalidation templates (incremental cycle) ----------------
1925

1926
    /**
1927
     * WHERE clause shared by the admin-RI invalidation ASK precheck and the
1928
     * matching DELETE. Identifies admin-tier {@code gen:RoleInstantiation} rows
1929
     * in the space-state graph whose {@code npa:viaNanopub} is the target of an
1930
     * {@code npx:invalidates} triple in {@code npa:graph} whose subject nanopub
1931
     * has a load number in {@code (lastProcessed, ∞)}.
1932
     */
1933
    static String adminInvalidationCheckWhere(IRI graph, long lastProcessed) {
1934
        return String.format("""
60✔
1935
                  GRAPH <%1$s> {
1936
                    ?ri a gen:RoleInstantiation ;
1937
                        npa:inverseProperty gen:hasAdmin ;
1938
                        npa:viaNanopub ?np .
1939
                  }
1940
                  GRAPH <%2$s> {
1941
                    ?invNp <%3$s> ?np ;
1942
                           npa:hasLoadNumber ?ln .
1943
                    FILTER (?ln > %4$d)
1944
                    %5$s
1945
                  }
1946
                """, graph, NPA.GRAPH, NPX.INVALIDATES, lastProcessed,
18✔
1947
                samePublisherClause("invNp", "np"));
6✔
1948
    }
1949

1950
    /** DELETE template for admin-tier RoleInstantiations whose source nanopub was invalidated. */
1951
    static String adminInvalidationDelete(IRI graph, long lastProcessed) {
1952
        return String.format("""
63✔
1953
                PREFIX npa: <%1$s>
1954
                PREFIX gen: <%2$s>
1955
                DELETE { GRAPH <%3$s> {
1956
                  ?ri ?p ?o .
1957
                } }
1958
                WHERE {
1959
                  GRAPH <%3$s> { ?ri ?p ?o . }
1960
                %4$s
1961
                }
1962
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
1963
                adminInvalidationCheckWhere(graph, lastProcessed));
6✔
1964
    }
1965

1966
    /** WHERE clause for RoleAssignment invalidation. */
1967
    static String roleAssignmentInvalidationCheckWhere(IRI graph, long lastProcessed) {
1968
        return String.format("""
60✔
1969
                  GRAPH <%1$s> {
1970
                    ?ra a gen:RoleAssignment ;
1971
                        npa:viaNanopub ?np .
1972
                  }
1973
                  GRAPH <%2$s> {
1974
                    ?invNp <%3$s> ?np ;
1975
                           npa:hasLoadNumber ?ln .
1976
                    FILTER (?ln > %4$d)
1977
                    %5$s
1978
                  }
1979
                """, graph, NPA.GRAPH, NPX.INVALIDATES, lastProcessed,
18✔
1980
                samePublisherClause("invNp", "np"));
6✔
1981
    }
1982

1983
    /** DELETE template for RoleAssignments whose source nanopub was invalidated. */
1984
    static String roleAssignmentInvalidationDelete(IRI graph, long lastProcessed) {
1985
        return String.format("""
63✔
1986
                PREFIX npa: <%1$s>
1987
                PREFIX gen: <%2$s>
1988
                DELETE { GRAPH <%3$s> {
1989
                  ?ra ?p ?o .
1990
                } }
1991
                WHERE {
1992
                  GRAPH <%3$s> { ?ra ?p ?o . }
1993
                %4$s
1994
                }
1995
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
1996
                roleAssignmentInvalidationCheckWhere(graph, lastProcessed));
6✔
1997
    }
1998

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

2031
    /**
2032
     * WHERE clause shared by the sub-space invalidation ASK precheck and the
2033
     * matching DELETE. Identifies validated {@code npa:SubSpaceDeclaration} rows
2034
     * in the space-state graph whose {@code npa:viaNanopub} is the target of an
2035
     * {@code npx:invalidates} triple in {@code npa:graph} whose subject nanopub
2036
     * has a load number in {@code (lastProcessed, ∞)}.
2037
     */
2038
    static String subSpaceInvalidationCheckWhere(IRI graph, long lastProcessed) {
2039
        return String.format("""
60✔
2040
                  GRAPH <%1$s> {
2041
                    ?d a npa:SubSpaceDeclaration ;
2042
                       npa:viaNanopub ?np .
2043
                  }
2044
                  GRAPH <%2$s> {
2045
                    ?invNp <%3$s> ?np ;
2046
                           npa:hasLoadNumber ?ln .
2047
                    FILTER (?ln > %4$d)
2048
                    %5$s
2049
                  }
2050
                """, graph, NPA.GRAPH, NPX.INVALIDATES, lastProcessed,
18✔
2051
                samePublisherClause("invNp", "np"));
6✔
2052
    }
2053

2054
    /**
2055
     * DELETE template for validated {@code npa:SubSpaceDeclaration} rows whose
2056
     * source nanopub was invalidated. Removes the per-declaration row by subject;
2057
     * the convenience direct triples ({@code <child> npa:isSubSpaceOf <parent>}
2058
     * and inverse) are left sticky and cleaned by the next periodic full rebuild
2059
     * (same staleness policy as admin-RI invalidation — see {@code
2060
     * doc/design-space-repositories.md} on the structural-rebuild flag).
2061
     */
2062
    static String subSpaceInvalidationDelete(IRI graph, long lastProcessed) {
2063
        return String.format("""
63✔
2064
                PREFIX npa: <%1$s>
2065
                PREFIX gen: <%2$s>
2066
                DELETE { GRAPH <%3$s> {
2067
                  ?d ?p ?o .
2068
                } }
2069
                WHERE {
2070
                  GRAPH <%3$s> { ?d ?p ?o . }
2071
                %4$s
2072
                }
2073
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
2074
                subSpaceInvalidationCheckWhere(graph, lastProcessed));
6✔
2075
    }
2076

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

2111
    /**
2112
     * WHERE clause shared by the alias invalidation ASK precheck and the matching
2113
     * DELETE. Identifies validated {@code npa:SpaceAliasDeclaration} rows in the
2114
     * space-state graph whose {@code npa:viaNanopub} is the target of an
2115
     * {@code npx:invalidates} triple in {@code npa:graph} whose subject nanopub has a
2116
     * load number in {@code (lastProcessed, ∞)}.
2117
     */
2118
    static String aliasInvalidationCheckWhere(IRI graph, long lastProcessed) {
2119
        return String.format("""
60✔
2120
                  GRAPH <%1$s> {
2121
                    ?d a npa:SpaceAliasDeclaration ;
2122
                       npa:viaNanopub ?np .
2123
                  }
2124
                  GRAPH <%2$s> {
2125
                    ?invNp <%3$s> ?np ;
2126
                           npa:hasLoadNumber ?ln .
2127
                    FILTER (?ln > %4$d)
2128
                    %5$s
2129
                  }
2130
                """, graph, NPA.GRAPH, NPX.INVALIDATES, lastProcessed,
18✔
2131
                samePublisherClause("invNp", "np"));
6✔
2132
    }
2133

2134
    /**
2135
     * DELETE template for validated {@code npa:SpaceAliasDeclaration} rows whose
2136
     * source nanopub was invalidated. Removes the per-declaration row by subject; the
2137
     * convenience {@code <alias> npa:sameAsSpace <canonical>} edge is left sticky and
2138
     * cleaned by the next periodic full rebuild (same staleness policy as sub-space
2139
     * declaration invalidation — the alias feeds the authority closure, so this kind
2140
     * is structural and flips {@code npa:needsFullRebuild}).
2141
     */
2142
    static String aliasInvalidationDelete(IRI graph, long lastProcessed) {
2143
        return String.format("""
63✔
2144
                PREFIX npa: <%1$s>
2145
                PREFIX gen: <%2$s>
2146
                DELETE { GRAPH <%3$s> {
2147
                  ?d ?p ?o .
2148
                } }
2149
                WHERE {
2150
                  GRAPH <%3$s> { ?d ?p ?o . }
2151
                %4$s
2152
                }
2153
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
2154
                aliasInvalidationCheckWhere(graph, lastProcessed));
6✔
2155
    }
2156

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

2210
    /**
2211
     * DELETE template for preset-derived {@code gen:RoleAssignment} rows superseded by a
2212
     * newer admin-authored same-pair assignment (issue #302). Removes the whole row by
2213
     * subject; scoped via {@code npa:derivedFromPreset} so directly-published attachments
2214
     * are never touched. The {@link #presetAttachmentValidationUpdate} re-INSERT in the
2215
     * same cycle re-materializes the pair iff the newest assignment is still active.
2216
     */
2217
    static String presetDeactivationDelete(IRI graph, long lastProcessed) {
2218
        return String.format("""
63✔
2219
                PREFIX npa: <%1$s>
2220
                PREFIX gen: <%2$s>
2221
                DELETE { GRAPH <%3$s> {
2222
                  ?ra ?p ?o .
2223
                } }
2224
                WHERE {
2225
                  GRAPH <%3$s> { ?ra ?p ?o . }
2226
                %4$s
2227
                }
2228
                """, NPA.NAMESPACE, GEN.NAMESPACE, graph,
2229
                presetDeactivationCheckWhere(graph, lastProcessed));
6✔
2230
    }
2231

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

2273
    /** Wraps an ASK by joining the shared prefixes. */
2274
    private boolean wouldInvalidate(IRI graph, long lastProcessed,
2275
                                    boolean adminPinned, String whereClause) {
2276
        // adminPinned is informational only — kept to make call sites read clearly;
2277
        // the WHERE clause already encodes the kind via its own type predicates.
2278
        String ask = String.format("""
×
2279
                PREFIX npa: <%1$s>
2280
                PREFIX gen: <%2$s>
2281
                ASK { %3$s }
2282
                """, NPA.NAMESPACE, GEN.NAMESPACE, whereClause);
2283
        return runAsk(ask);
×
2284
    }
2285

2286
    private boolean runAsk(String sparql) {
2287
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
2288
            return conn.prepareBooleanQuery(QueryLanguage.SPARQL, sparql).evaluate();
×
2289
        }
2290
    }
2291

2292
    private void executeUpdate(String sparqlUpdate) {
2293
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
2294
            conn.prepareUpdate(QueryLanguage.SPARQL, sparqlUpdate).execute();
×
2295
        }
2296
    }
×
2297

2298
    // ---------------- Mirror step ----------------
2299

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

2359
    // ---------------- Pointer + counter helpers ----------------
2360

2361
    /**
2362
     * Reads the current {@code npa:hasCurrentSpaceState} pointer from the
2363
     * {@code npa:graph} admin graph of the {@code spaces} repo. Returns
2364
     * {@code null} if no pointer exists yet.
2365
     */
2366
    IRI getCurrentSpaceStateGraph() {
2367
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
2368
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
2369
                    SpacesVocab.HAS_CURRENT_SPACE_STATE);
2370
            return (v instanceof IRI iri) ? iri : null;
×
2371
        } catch (Exception ex) {
×
2372
            logger.warn("AuthorityResolver: failed to read hasCurrentSpaceState pointer: {}", ex.toString());
×
2373
            return null;
×
2374
        }
2375
    }
2376

2377
    long getCurrentLoadCounter() {
2378
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
2379
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
2380
                    SpacesVocab.CURRENT_LOAD_COUNTER);
2381
            if (v == null) return 0;
×
2382
            try {
2383
                return Long.parseLong(v.stringValue());
×
2384
            } catch (NumberFormatException ex) {
×
2385
                logger.warn("AuthorityResolver: non-numeric currentLoadCounter: {}", v);
×
2386
                return 0;
×
2387
            }
2388
        } catch (Exception ex) {
×
2389
            logger.warn("AuthorityResolver: failed to read currentLoadCounter: {}", ex.toString());
×
2390
            return 0;
×
2391
        }
2392
    }
2393

2394
    /**
2395
     * Atomic pointer flip: a single SPARQL {@code DELETE … INSERT … WHERE}
2396
     * replaces the old pointer with the new one in one statement, so readers
2397
     * never see a zero-pointer window.
2398
     */
2399
    void flipPointer(IRI newGraph) {
2400
        String update = String.format("""
×
2401
                DELETE { GRAPH <%s> { <%s> <%s> ?old } }
2402
                INSERT { GRAPH <%s> { <%s> <%s> <%s> } }
2403
                WHERE  { OPTIONAL { GRAPH <%s> { <%s> <%s> ?old } } }
2404
                """,
2405
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.HAS_CURRENT_SPACE_STATE,
2406
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.HAS_CURRENT_SPACE_STATE, newGraph,
2407
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.HAS_CURRENT_SPACE_STATE);
2408
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
2409
            conn.begin(IsolationLevels.SERIALIZABLE);
×
2410
            conn.prepareUpdate(QueryLanguage.SPARQL, update).execute();
×
2411
            conn.commit();
×
2412
        }
2413
    }
×
2414

2415
    void writeProcessedUpTo(IRI graph, long loadCounter) {
2416
        String update = String.format("""
×
2417
                DELETE { GRAPH <%s> { <%s> <%s> ?old } }
2418
                INSERT { GRAPH <%s> { <%s> <%s> "%d"^^<http://www.w3.org/2001/XMLSchema#long> } }
2419
                WHERE  { OPTIONAL { GRAPH <%s> { <%s> <%s> ?old } } }
2420
                """,
2421
                graph, graph, SpacesVocab.PROCESSED_UP_TO,
2422
                graph, graph, SpacesVocab.PROCESSED_UP_TO, loadCounter,
×
2423
                graph, graph, SpacesVocab.PROCESSED_UP_TO);
2424
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
2425
            conn.begin(IsolationLevels.SERIALIZABLE);
×
2426
            conn.prepareUpdate(QueryLanguage.SPARQL, update).execute();
×
2427
            conn.commit();
×
2428
        }
2429
    }
×
2430

2431
    /**
2432
     * Reads {@code processedUpTo} from the given space-state graph.
2433
     * Returns {@code -1} if absent (graph not fully built yet).
2434
     */
2435
    long readProcessedUpTo(IRI graph) {
2436
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
2437
            String query = String.format(
×
2438
                    "SELECT ?n WHERE { GRAPH <%s> { <%s> <%s> ?n } }",
2439
                    graph, graph, SpacesVocab.PROCESSED_UP_TO);
2440
            try (TupleQueryResult r = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate()) {
×
2441
                if (!r.hasNext()) return -1;
×
2442
                BindingSet b = r.next();
×
2443
                return Long.parseLong(b.getBinding("n").getValue().stringValue());
×
2444
            }
×
2445
        } catch (Exception ex) {
×
2446
            logger.warn("AuthorityResolver: failed to read processedUpTo for {}: {}", graph, ex.toString());
×
2447
            return -1;
×
2448
        }
2449
    }
2450

2451
    /**
2452
     * Reads the {@code npa:needsFullRebuild} flag (boolean literal) from
2453
     * {@code npa:graph} in the {@code spaces} repo. Defaults to {@code false}
2454
     * when the triple is absent.
2455
     */
2456
    boolean readNeedsFullRebuild() {
2457
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
2458
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
2459
                    SpacesVocab.NEEDS_FULL_REBUILD);
2460
            return v != null && Boolean.parseBoolean(v.stringValue());
×
2461
        } catch (Exception ex) {
×
2462
            logger.warn("AuthorityResolver: failed to read needsFullRebuild: {}", ex.toString());
×
2463
            return false;
×
2464
        }
2465
    }
2466

2467
    void setNeedsFullRebuild() {
2468
        writeNeedsFullRebuild(true);
×
2469
    }
×
2470

2471
    void clearNeedsFullRebuild() {
2472
        writeNeedsFullRebuild(false);
×
2473
    }
×
2474

2475
    private void writeNeedsFullRebuild(boolean value) {
2476
        String update = String.format("""
×
2477
                DELETE { GRAPH <%s> { <%s> <%s> ?old } }
2478
                INSERT { GRAPH <%s> { <%s> <%s> "%s"^^<http://www.w3.org/2001/XMLSchema#boolean> } }
2479
                WHERE  { OPTIONAL { GRAPH <%s> { <%s> <%s> ?old } } }
2480
                """,
2481
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.NEEDS_FULL_REBUILD,
2482
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.NEEDS_FULL_REBUILD, value,
×
2483
                NPA.GRAPH, NPA.THIS_REPO, SpacesVocab.NEEDS_FULL_REBUILD);
2484
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
2485
            conn.begin(IsolationLevels.SERIALIZABLE);
×
2486
            conn.prepareUpdate(QueryLanguage.SPARQL, update).execute();
×
2487
            conn.commit();
×
2488
        }
2489
    }
×
2490

2491
    void dropGraph(IRI graph) {
2492
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(SPACES_REPO)) {
×
2493
            conn.begin(IsolationLevels.SERIALIZABLE);
×
2494
            conn.clear(graph);
×
2495
            conn.commit();
×
2496
            logger.info("AuthorityResolver: dropped old space-state graph {}", graph);
×
2497
        }
2498
    }
×
2499

2500
    // ---------------- Trust-repo pointer lookup (used by TrustStateRegistry's bootstrap) ----------------
2501

2502
    /**
2503
     * Queries the {@code trust} repo directly for the current trust-state hash.
2504
     * Prefer {@link TrustStateRegistry#getCurrentHash()} in normal operation —
2505
     * this helper exists for tests and diagnostics.
2506
     *
2507
     * @return the current trust-state hash, or empty if none is set
2508
     */
2509
    Optional<String> readTrustRepoCurrentHash() {
2510
        try (RepositoryConnection conn = TripleStore.get().getRepoConnection(TRUST_REPO)) {
×
2511
            Value v = Utils.getObjectForPattern(conn, NPA.GRAPH, NPA.THIS_REPO,
×
2512
                    NPA_HAS_CURRENT_TRUST_STATE);
2513
            if (!(v instanceof IRI iri)) return Optional.empty();
×
2514
            String s = iri.stringValue();
×
2515
            if (!s.startsWith(NPAT.NAMESPACE)) return Optional.empty();
×
2516
            return Optional.of(s.substring(NPAT.NAMESPACE.length()));
×
2517
        } catch (Exception ex) {
×
2518
            logger.warn("AuthorityResolver: failed to read trust-repo current pointer: {}", ex.toString());
×
2519
            return Optional.empty();
×
2520
        }
2521
    }
2522

2523
    private static String abbrev(String hash) {
2524
        return hash.length() > 12 ? hash.substring(0, 12) + "…" : hash;
×
2525
    }
2526

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