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

knowledgepixels / nanopub-registry / 31489094351

11 Aug 2026 11:59AM UTC coverage: 35.596% (+2.1%) from 33.463%
31489094351

push

github

web-flow
Merge pull request #130 from knowledgepixels/fix/128-task-transactions

fix: make task transactions real, and split the tasks that cannot use them

365 of 1158 branches covered (31.52%)

Branch coverage included in aggregate %.

1208 of 3261 relevant lines covered (37.04%)

6.1 hits per line

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

23.77
src/main/java/com/knowledgepixels/registry/Task.java
1
package com.knowledgepixels.registry;
2

3
import com.knowledgepixels.registry.db.IndexInitializer;
4
import com.mongodb.client.ClientSession;
5
import com.mongodb.client.FindIterable;
6
import com.mongodb.client.MongoCollection;
7
import com.mongodb.client.MongoCursor;
8
import com.mongodb.client.model.ReplaceOptions;
9
import net.trustyuri.TrustyUriUtils;
10
import org.apache.commons.lang.Validate;
11
import org.bson.Document;
12
import org.eclipse.rdf4j.model.IRI;
13
import org.eclipse.rdf4j.model.Statement;
14
import org.nanopub.Nanopub;
15
import org.nanopub.SimpleTimestampPattern;
16
import org.nanopub.extra.index.IndexUtils;
17
import org.nanopub.extra.index.NanopubIndex;
18
import org.nanopub.extra.security.KeyDeclaration;
19
import org.nanopub.extra.setting.IntroNanopub;
20
import org.nanopub.extra.setting.NanopubSetting;
21
import org.slf4j.Logger;
22
import org.slf4j.LoggerFactory;
23

24
import java.io.Serializable;
25
import java.time.ZonedDateTime;
26
import java.util.*;
27
import java.util.concurrent.atomic.AtomicLong;
28

29
import static com.knowledgepixels.registry.EntryStatus.*;
30
import static com.knowledgepixels.registry.NanopubLoader.*;
31
import static com.knowledgepixels.registry.RegistryDB.*;
32
import static com.knowledgepixels.registry.ServerStatus.*;
33
import static com.mongodb.client.model.Filters.eq;
34
import static com.mongodb.client.model.Filters.in;
35
import static com.mongodb.client.model.Sorts.*;
36

37
public enum Task implements Serializable {
6 ✔
38

39
    INIT_DB {
33 ✔
40
        public void run(ClientSession s, Document taskDoc) {
41
            logger.info("Running INIT_DB task: initializing a fresh database");
9 ✔
42
            setServerStatus(s, launching);
9 ✔
43

44
            increaseStateCounter(s);
6 ✔
45
            if (RegistryDB.isInitialized(s)) {
9 !
46
                logger.error("INIT_DB aborted: database is already initialized");
×
47
                throw new RuntimeException("DB already initialized");
×
48
            }
49

50
            long setupId = Math.abs(Utils.getRandom().nextLong());
12 ✔
51
            boolean testInstance = "true".equals(System.getenv("REGISTRY_TEST_INSTANCE"));
15 ✔
52
            logger.info("Initializing new database with setupId={} (testInstance={})", setupId, testInstance);
21 ✔
53

54
            setValue(s, Collection.SERVER_INFO.toString(), "setupId", setupId);
21 ✔
55
            setValue(s, Collection.SERVER_INFO.toString(), "testInstance", testInstance);
21 ✔
56

57
            logger.debug("INIT_DB complete; scheduling LOAD_CONFIG task");
9 ✔
58
            schedule(s, LOAD_CONFIG);
9 ✔
59
        }
3 ✔
60

61
    },
62

63
    LOAD_CONFIG {
33 ✔
64
        public void run(ClientSession s, Document taskDoc) {
65
            logger.info("Running LOAD_CONFIG task");
9 ✔
66
            ServerStatus status = getServerStatus(s);
9 ✔
67
            if (status != launching) {
9 !
68
                logger.error("LOAD_CONFIG aborted: expected server status '{}' but found '{}'", launching, status);
×
69
                throw new IllegalTaskStatusException("Illegal status for this task: " + status);
×
70
            }
71

72
            String coverageTypes = System.getenv("REGISTRY_COVERAGE_TYPES");
9 ✔
73
            if (coverageTypes != null) {
6 !
74
                logger.info("Setting coverageTypes from REGISTRY_COVERAGE_TYPES: {}", coverageTypes);
×
75
                setValue(s, Collection.SERVER_INFO.toString(), "coverageTypes", coverageTypes);
×
76
            } else {
77
                logger.debug("REGISTRY_COVERAGE_TYPES not set; leaving coverageTypes unset");
9 ✔
78
            }
79

80
            String coverageAgents = System.getenv("REGISTRY_COVERAGE_AGENTS");
9 ✔
81
            if (coverageAgents != null) {
6 !
82
                logger.info("Setting coverageAgents from REGISTRY_COVERAGE_AGENTS: {}", coverageAgents);
×
83
                setValue(s, Collection.SERVER_INFO.toString(), "coverageAgents", coverageAgents);
×
84
            } else {
85
                logger.debug("REGISTRY_COVERAGE_AGENTS not set; leaving coverageAgents unset");
9 ✔
86
            }
87

88
            logger.debug("LOAD_CONFIG complete; scheduling LOAD_SETTING task");
9 ✔
89
            schedule(s, LOAD_SETTING);
9 ✔
90
        }
3 ✔
91

92
    },
93

94
    LOAD_SETTING {
33 ✔
95
        public void run(ClientSession s, Document taskDoc) throws Exception {
96
            logger.info("Running LOAD_SETTING task");
9 ✔
97
            ServerStatus status = getServerStatus(s);
9 ✔
98
            if (status != launching) {
9 !
99
                logger.error("LOAD_SETTING aborted: expected server status '{}' but found '{}'", launching, status);
×
100
                throw new IllegalTaskStatusException("Illegal status for this task: " + status);
×
101
            }
102

103
            NanopubSetting settingNp = Utils.getSetting();
6 ✔
104
            String settingId = TrustyUriUtils.getArtifactCode(settingNp.getNanopub().getUri().stringValue());
18 ✔
105
            logger.info("Loading setting nanopub {}", settingId);
12 ✔
106
            setValue(s, Collection.SETTING.toString(), "original", settingId);
18 ✔
107
            setValue(s, Collection.SETTING.toString(), "current", settingId);
18 ✔
108
            loadNanopub(s, settingNp.getNanopub());
15 ✔
109

110
            List<Document> bootstrapServices = new ArrayList<>();
12 ✔
111
            for (IRI i : settingNp.getBootstrapServices()) {
33 ✔
112
                bootstrapServices.add(new Document("_id", i.stringValue()));
27 ✔
113
            }
3 ✔
114
            logger.info("Setting {} bootstrap service(s) from the setting nanopub: {}", bootstrapServices.size(), bootstrapServices);
21 ✔
115
            // potentially currently hardcoded in the nanopub lib
116
            setValue(s, Collection.SETTING.toString(), "bootstrap-services", bootstrapServices);
18 ✔
117

118
            boolean performFullLoad = !"false".equals(Utils.getEnv("REGISTRY_PERFORM_FULL_LOAD", null));
27 !
119
            if (performFullLoad) {
6 !
120
                logger.debug("REGISTRY_PERFORM_FULL_LOAD not disabled; scheduling LOAD_FULL task");
9 ✔
121
                schedule(s, LOAD_FULL);
12 ✔
122
            } else {
123
                logger.info("REGISTRY_PERFORM_FULL_LOAD=false; skipping LOAD_FULL task");
×
124
            }
125

126
            logger.debug("LOAD_SETTING complete; transitioning server status to '{}' and scheduling INIT_COLLECTIONS", coreLoading);
12 ✔
127
            setServerStatus(s, coreLoading);
9 ✔
128
            schedule(s, INIT_COLLECTIONS);
9 ✔
129
        }
3 ✔
130
    },
131

132
    INIT_COLLECTIONS {
33 ✔
133

134
        // DB read from: setting
135
        // DB write to:  nanopubs
136
        // This state is periodically executed
137

138
        /**
139
         * Prepares the ground for a trust state cycle: resets the loading collections, creates
140
         * their indexes, and fetches the agent intro collection into the local nanopub store.
141
         *
142
         * <p>Everything here is either a catalog operation or network I/O, so this task cannot be
143
         * transactional. It deliberately holds no derived writes: those live in
144
         * {@link #SEED_TRUST_STATE}, which runs afterwards and, because the intro collection is
145
         * local by then, needs neither (issue #128).
146
         */
147
        public void run(ClientSession s, Document taskDoc) throws Exception {
148
            logger.info("Running INIT_COLLECTIONS task");
9 ✔
149
            ServerStatus status = getServerStatus(s);
9 ✔
150
            if (status != coreLoading && status != updating) {
9 !
151
                logger.error("INIT_COLLECTIONS aborted: expected server status 'coreLoading' or 'updating' but found '{}'", status);
×
152
                throw new IllegalTaskStatusException("Illegal status for this task: " + status);
×
153
            }
154

155
            // A cycle always builds its staging collections from scratch, so anything still there
156
            // is a half-built cycle left by an interrupted run and has to go before SEED_TRUST_STATE
157
            // starts inserting (issue #50). Done outside the transaction, as dropping a collection
158
            // is a DDL operation; it is idempotent, so a retry of this task is unaffected, and it
159
            // is what keeps such a retry from colliding with the fixed keys that task seeds under.
160
            dropLoadingCollections();
3 ✔
161

162
            IndexInitializer.initLoadingCollections(s);
6 ✔
163

164
            // Read through Utils rather than System.getenv so tests can reach this branch; the two
165
            // are equivalent in production, where the env reader delegates to System::getenv.
166
            boolean trustCalculation = !"false".equals(Utils.getEnv("REGISTRY_ENABLE_TRUST_CALCULATION", null));
24 !
167
            if (trustCalculation) {
6 !
168
                // Pull the agent intro collection into the nanopub store now, so that the seeding
169
                // below it resolves the index locally and stays off the network.
170
                String agentIntroCollectionUri = Utils.getSetting().getAgentIntroCollection().stringValue();
×
171
                logger.info("Retrieving base agent intro collection: {}", agentIntroCollectionUri);
×
172
                loadNanopub(s, NanopubLoader.retrieveNanopub(s, agentIntroCollectionUri));
×
173
                if (NanopubLoader.retrieveLocalNanopub(s, agentIntroCollectionUri) == null) {
×
174
                    // retrieveNanopub returns the nanopub even when loadNanopub declined to store
175
                    // it (size or triple count limits), which would send SEED_TRUST_STATE to the
176
                    // network from inside its transaction. Fail here instead, where retrying is free.
177
                    throw new RuntimeException("Agent intro collection could not be stored locally: " + agentIntroCollectionUri);
×
178
                }
179
            } else {
×
180
                logger.info("Trust calculation disabled (REGISTRY_ENABLE_TRUST_CALCULATION=false); not retrieving the agent intro collection");
9 ✔
181
            }
182

183
            // Pass the decision on rather than re-reading the environment, so that both halves of
184
            // the cycle are seeded from one observation of the flag.
185
            schedule(s, SEED_TRUST_STATE.with("trustCalculation", trustCalculation));
21 ✔
186
        }
3 ✔
187

188
        @Override
189
        public boolean runAsTransaction() {
190
            // Drops and indexes the _loading collections, which is DDL, and fetches the agent
191
            // intro collection over the network. Neither is permitted or bounded inside a
192
            // transaction; the writes that follow from them are in SEED_TRUST_STATE. See #128.
193
            return false;
×
194
        }
195

196
    },
197

198
    SEED_TRUST_STATE {
33 ✔
199

200
        // DB read from: nanopubs, setting
201
        // DB write to:  trustPaths, endorsements, accounts
202

203
        /**
204
         * Seeds the loading collections for a fresh cycle, from data that
205
         * {@link #INIT_COLLECTIONS} has already made local. Transactional: on a crash the whole
206
         * seeding is rolled back and re-run, rather than half-applied (issue #128).
207
         */
208
        public void run(ClientSession s, Document taskDoc) throws Exception {
209
            logger.info("Running SEED_TRUST_STATE task");
×
210

211
            if (!taskDoc.getBoolean("trustCalculation", true)) {
×
212
                logger.info("Trust calculation disabled; seeding explicit pubkeys and skipping to FINALIZE_TRUST_STATE");
×
213
                for (Map.Entry<String, Integer> entry : AgentFilter.getExplicitPubkeys().entrySet()) {
×
214
                    String pubkeyHash = entry.getKey();
×
215
                    int quota = entry.getValue();
×
216
                    Document account = new Document("agent", "")
×
217
                            .append("pubkey", pubkeyHash)
×
218
                            .append("status", toLoad.getValue())
×
219
                            .append("depth", 0)
×
220
                            .append("quota", quota);
×
221
                    if (!has(s, "accounts_loading", new Document("pubkey", pubkeyHash))) {
×
222
                        insert(s, "accounts_loading", account);
×
223
                        logger.debug("Seeded explicit pubkey as account: {} (quota={})", pubkeyHash, quota);
×
224
                    }
225
                }
×
226
                schedule(s, FINALIZE_TRUST_STATE);
×
227
                return;
×
228
            }
229

230
            logger.debug("Inserting root trust path entry for base agent");
×
231
            // since this may take long, we start with postfix "_loading"
232
            // and only at completion it's changed to trustPath, endorsements, accounts
233
            insert(s, "trustPaths_loading",
×
234
                    new Document("_id", "$")
235
                            .append("sorthash", "")
×
236
                            .append("agent", "$")
×
237
                            .append("pubkey", "$")
×
238
                            .append("depth", 0)
×
239
                            .append("ratio", 1.0d)
×
240
                            .append("type", "extended")
×
241
            );
242

243
            String agentIntroCollectionUri = Utils.getSetting().getAgentIntroCollection().stringValue();
×
244
            // Strictly local: INIT_COLLECTIONS has already stored this and verified it is here, so
245
            // this must not fall back to the network the way retrieveNanopub would.
246
            Nanopub agentIndexNp = NanopubLoader.retrieveLocalNanopub(s, agentIntroCollectionUri);
×
247
            if (agentIndexNp == null) {
×
248
                throw new RuntimeException("Agent intro collection is not available locally: " + agentIntroCollectionUri);
×
249
            }
250
            NanopubIndex agentIndex = IndexUtils.castToIndex(agentIndexNp);
×
251
            String currentSetting = getValue(s, Collection.SETTING.toString(), "current").toString();
×
252
            for (IRI el : agentIndex.getElements()) {
×
253
                String declarationAc = TrustyUriUtils.getArtifactCode(el.stringValue());
×
254
                Validate.notNull(declarationAc);
×
255

256
                insert(s, "endorsements_loading",
×
257
                        new Document("agent", "$")
258
                                .append("pubkey", "$")
×
259
                                .append("endorsedNanopub", declarationAc)
×
260
                                .append("source", currentSetting)
×
261
                                .append("status", toRetrieve.getValue())
×
262

263
                );
264

265
            }
×
266
            insert(s, "accounts_loading",
×
267
                    new Document("agent", "$")
268
                            .append("pubkey", "$")
×
269
                            .append("status", visited.getValue())
×
270
                            .append("depth", 0)
×
271
            );
272

273
            logger.info("Starting iteration at depth 0");
×
274
            schedule(s, LOAD_DECLARATIONS.with("depth", 1));
×
275
        }
×
276

277
        // At the end of this task, the base agent is initialized:
278
        // ------------------------------------------------------------
279
        //
280
        //              $$$$ ----endorses----> [intro]
281
        //              base                (to-retrieve)
282
        //              $$$$
283
        //            (visited)
284
        //
285
        //              [0] trust path
286
        //
287
        // ------------------------------------------------------------
288
        // Only one endorses-link to an introduction is shown here,
289
        // but there are typically several.
290

291
    },
292

293
    LOAD_DECLARATIONS {
33 ✔
294

295
        // In general, we have at this point accounts with
296
        // endorsement links to unvisited agent introductions:
297
        // ------------------------------------------------------------
298
        //
299
        //         o      ----endorses----> [intro]
300
        //    --> /#\  /o\___            (to-retrieve)
301
        //        / \  \_/^^^
302
        //         (visited)
303
        //
304
        //    ========[X] trust path
305
        //
306
        // ------------------------------------------------------------
307

308
        // DB read from: endorsements, trustEdges, accounts
309
        // DB write to:  endorsements, trustEdges, accounts
310

311
        public void run(ClientSession s, Document taskDoc) {
312

313
            int depth = taskDoc.getInteger("depth");
×
314
            logger.info("Running LOAD_DECLARATIONS task at depth {}", depth);
×
315

316
            while (true) {
317
                Document d = getOne(s, "endorsements_loading",
×
318
                        new DbEntryWrapper(toRetrieve).getDocument());
×
319
                if (d == null) {
×
320
                    break;
×
321
                }
322

323
                IntroNanopub agentIntro = getAgentIntro(s, d.getString("endorsedNanopub"));
×
324
                if (agentIntro != null) {
×
325
                    String agentId = agentIntro.getUser().stringValue();
×
326
                    // foaf:name + dct:created of the intro nanopub. Same name applies to every
327
                    // KeyDeclaration in the intro, so resolve once outside the inner loop.
328
                    String introName = Utils.extractIntroName(agentIntro);
×
329
                    Calendar introCreatedCal = SimpleTimestampPattern.getCreationTime(agentIntro.getNanopub());
×
330
                    Date introCreatedAt = (introCreatedCal == null) ? null : introCreatedCal.getTime();
×
331
                    // The authorizing introduction for this (agent, pubkey): it carries the
332
                    // KeyDeclaration for the pubkey. Recorded alongside the name and kept in sync
333
                    // with it (latest-dct:created wins), so it reflects one authorizing intro —
334
                    // the name-winning one — not the complete set of intros for this account.
335
                    String introNp = agentIntro.getNanopub().getUri().stringValue();
×
336

337
                    for (KeyDeclaration kd : agentIntro.getKeyDeclarations()) {
×
338
                        String sourceAgent = d.getString("agent");
×
339
                        Validate.notNull(sourceAgent);
×
340
                        String sourcePubkey = d.getString("pubkey");
×
341
                        Validate.notNull(sourcePubkey);
×
342
                        String sourceAc = d.getString("source");
×
343
                        Validate.notNull(sourceAc);
×
344
                        String agentPubkey = Utils.getHash(kd.getPublicKeyString());
×
345
                        Validate.notNull(agentPubkey);
×
346
                        Document trustEdge = new Document("fromAgent", sourceAgent)
×
347
                                .append("fromPubkey", sourcePubkey)
×
348
                                .append("toAgent", agentId)
×
349
                                .append("toPubkey", agentPubkey)
×
350
                                .append("source", sourceAc);
×
351
                        if (!has(s, "trustEdges", trustEdge)) {
×
352
                            boolean invalidated = has(s, "invalidations", new Document("invalidatedNp", sourceAc).append("invalidatingPubkey", sourcePubkey));
×
353
                            if (invalidated) {
×
354
                                logger.info("Trust edge from {}/{} to {}/{} is invalidated by source {}", sourceAgent, sourcePubkey, agentId, agentPubkey, sourceAc);
×
355
                            }
356
                            insert(s, "trustEdges", trustEdge.append("invalidated", invalidated));
×
357
                        }
358

359
                        Document agent = new Document("agent", agentId).append("pubkey", agentPubkey);
×
360
                        Document existing = collection("accounts_loading").find(s, agent).first();
×
361
                        if (existing == null) {
×
362
                            insert(s, "accounts_loading", agent
×
363
                                    .append("status", seen.getValue())
×
364
                                    .append("depth", depth)
×
365
                                    .append("name", introName)
×
366
                                    .append("nameCreatedAt", introCreatedAt)
×
367
                                    .append("introNanopub", introNp));
×
368
                        } else if (introName != null) {
×
369
                            // Per-(agent, pubkey) name policy: keep the name from the intro
370
                            // with the latest dct:created. First write wins when no current
371
                            // timestamp exists; otherwise compare and replace iff strictly newer.
372
                            Date currentCreatedAt = existing.getDate("nameCreatedAt");
×
373
                            if (currentCreatedAt == null
×
374
                                || (introCreatedAt != null && introCreatedAt.after(currentCreatedAt))) {
×
375
                                set(s, "accounts_loading", existing
×
376
                                        .append("name", introName)
×
377
                                        .append("nameCreatedAt", introCreatedAt)
×
378
                                        .append("introNanopub", introNp));
×
379
                            }
380
                        }
381
                    }
×
382

383
                    set(s, "endorsements_loading", d.append("status", retrieved.getValue()));
×
384
                } else {
×
385
                    logger.debug("Discarding endorsement {}: referenced nanopub {} is not a valid agent intro", d.get("_id"), d.getString("endorsedNanopub"));
×
386
                    set(s, "endorsements_loading", d.append("status", discarded.getValue()));
×
387
                }
388
            }
×
389
            logger.info("LOAD_DECLARATIONS at depth {} complete.", depth);
×
390
            schedule(s, EXPAND_TRUST_PATHS.with("depth", depth));
×
391
        }
×
392

393
        // At the end of this step, the key declarations in the agent
394
        // introductions are loaded and the corresponding trust edges
395
        // established:
396
        // ------------------------------------------------------------
397
        //
398
        //        o      ----endorses----> [intro]
399
        //   --> /#\  /o\___                o
400
        //       / \  \_/^^^ ---trusts---> /#\  /o\___
401
        //        (visited)                / \  \_/^^^
402
        //                                   (seen)
403
        //
404
        //   ========[X] trust path
405
        //
406
        // ------------------------------------------------------------
407
        // Only one trust edge per introduction is shown here, but
408
        // there can be several.
409

410
        @Override
411
        public boolean runAsTransaction() {
412
            // Retrieves an agent intro over the network for every pending endorsement, each with
413
            // up to ten retries, which would exceed MongoDB's transaction timeout. See #128.
414
            return false;
×
415
        }
416

417
    },
418

419
    EXPAND_TRUST_PATHS {
33 ✔
420

421
        // DB read from: accounts, trustPaths, trustEdges
422
        // DB write to:  accounts, trustPaths
423

424
        public void run(ClientSession s, Document taskDoc) {
425

426
            int depth = taskDoc.getInteger("depth");
×
427
            logger.info("Running EXPAND_TRUST_PATHS task at depth {}", depth);
×
428

429
            while (true) {
430
                Document d = getOne(s, "accounts_loading",
×
431
                        new Document("status", visited.getValue())
×
432
                                .append("depth", depth - 1)
×
433
                );
434
                if (d == null) {
×
435
                    break;
×
436
                }
437

438
                String agentId = d.getString("agent");
×
439
                Validate.notNull(agentId);
×
440
                String pubkeyHash = d.getString("pubkey");
×
441
                Validate.notNull(pubkeyHash);
×
442

443
                Document trustPath = collection("trustPaths_loading").find(s,
×
444
                        new Document("agent", agentId).append("pubkey", pubkeyHash).append("type", "extended").append("depth", depth - 1)
×
445
                ).sort(orderBy(descending("ratio"), ascending("sorthash"))).first();
×
446

447
                if (trustPath == null) {
×
448
                    // Check it again in next iteration:
449
                    set(s, "accounts_loading", d.append("depth", depth));
×
450
                } else {
451
                    // Only first matching trust path is considered
452

453
                    Map<String, Document> newPaths = new HashMap<>();
×
454
                    Map<String, Set<String>> pubkeySets = new HashMap<>();
×
455
                    String currentSetting = getValue(s, Collection.SETTING.toString(), "current").toString();
×
456

457
                    try (MongoCursor<Document> edgeCursor = get(s, "trustEdges",
×
458
                            trustEdgeFilter(agentId, pubkeyHash, getBootstrapSettingAcs(s))
×
459
                    )) {
460
                        while (edgeCursor.hasNext()) {
×
461
                            Document e = edgeCursor.next();
×
462

463
                            String agent = e.getString("toAgent");
×
464
                            Validate.notNull(agent);
×
465
                            String pubkey = e.getString("toPubkey");
×
466
                            Validate.notNull(pubkey);
×
467
                            String pathId = trustPath.getString("_id") + " " + agent + "|" + pubkey;
×
468
                            newPaths.put(pathId,
×
469
                                    new Document("_id", pathId)
470
                                            .append("sorthash", Utils.getHash(currentSetting + " " + pathId))
×
471
                                            .append("agent", agent)
×
472
                                            .append("pubkey", pubkey)
×
473
                                            .append("depth", depth)
×
474
                                            .append("type", "extended")
×
475
                            );
476
                            if (!pubkeySets.containsKey(agent)) {
×
477
                                pubkeySets.put(agent, new HashSet<>());
×
478
                            }
479
                            pubkeySets.get(agent).add(pubkey);
×
480
                        }
×
481
                    }
482
                    for (String pathId : newPaths.keySet()) {
×
483
                        Document pd = newPaths.get(pathId);
×
484
                        // first divide by agents; then for each agent, divide by number of pubkeys:
485
                        double newRatio = (trustPath.getDouble("ratio") * 0.9) / pubkeySets.size() / pubkeySets.get(pd.getString("agent")).size();
×
486
                        insert(s, "trustPaths_loading", pd.append("ratio", newRatio));
×
487
                    }
×
488
                    // Retain only 10% of the ratio — the other 90% was distributed to children
489
                    double retainedRatio = trustPath.getDouble("ratio") * 0.1;
×
490
                    set(s, "trustPaths_loading", trustPath.append("type", "primary").append("ratio", retainedRatio));
×
491
                    set(s, "accounts_loading", d.append("status", expanded.getValue()));
×
492
                }
493
            }
×
494
            logger.info("EXPAND_TRUST_PATHS at depth {} complete.", depth);
×
495
            schedule(s, LOAD_CORE.with("depth", depth).append("load-count", 0));
×
496
        }
×
497

498
        // At the end of this step, trust paths are updated to include
499
        // the new accounts:
500
        // ------------------------------------------------------------
501
        //
502
        //         o      ----endorses----> [intro]
503
        //    --> /#\  /o\___                o
504
        //        / \  \_/^^^ ---trusts---> /#\  /o\___
505
        //        (expanded)                / \  \_/^^^
506
        //                                    (seen)
507
        //
508
        //    ========[X]=====================[X+1] trust path
509
        //
510
        // ------------------------------------------------------------
511
        // Only one trust path is shown here, but they branch out if
512
        // several trust edges are present.
513

514
    },
515

516
    LOAD_CORE {
33 ✔
517

518
        // From here on, we refocus on the head of the trust paths:
519
        // ------------------------------------------------------------
520
        //
521
        //         o
522
        //    --> /#\  /o\___
523
        //        / \  \_/^^^
524
        //          (seen)
525
        //
526
        //    ========[X] trust path
527
        //
528
        // ------------------------------------------------------------
529

530
        // DB read from: accounts, trustPaths, endorsements, lists
531
        // DB write to:  accounts, endorsements, lists
532

533
        public void run(ClientSession s, Document taskDoc) {
534

535
            int depth = taskDoc.getInteger("depth");
×
536
            int loadCount = taskDoc.getInteger("load-count");
×
537

538
            Document agentAccount = getOne(s, "accounts_loading",
×
539
                    new Document("depth", depth).append("status", seen.getValue()));
×
540
            final String agentId;
541
            final String pubkeyHash;
542
            final Document trustPath;
543
            if (agentAccount != null) {
×
544
                agentId = agentAccount.getString("agent");
×
545
                Validate.notNull(agentId);
×
546
                pubkeyHash = agentAccount.getString("pubkey");
×
547
                Validate.notNull(pubkeyHash);
×
548
                trustPath = getOne(s, "trustPaths_loading",
×
549
                        new Document("depth", depth)
×
550
                                .append("agent", agentId)
×
551
                                .append("pubkey", pubkeyHash)
×
552
                );
553
            } else {
554
                agentId = null;
×
555
                pubkeyHash = null;
×
556
                trustPath = null;
×
557
            }
558

559
            if (agentAccount == null) {
×
560
                logger.info("LOAD_CORE at depth {} complete: {} account(s) processed", depth, loadCount);
×
561
                schedule(s, FINISH_ITERATION.with("depth", depth).append("load-count", loadCount));
×
562
            } else if (trustPath == null) {
×
563
                logger.debug("Account {}/{} has no trust path at depth {}; marking skipped", agentId, pubkeyHash, depth);
×
564
                // Account was seen but has no trust path at this depth; skip it
565
                set(s, "accounts_loading", agentAccount.append("status", skipped.getValue()));
×
566
                schedule(s, LOAD_CORE.with("depth", depth).append("load-count", loadCount));
×
567
            } else if (trustPath.getDouble("ratio") < MIN_TRUST_PATH_RATIO) {
×
568
                logger.debug("Pubkey {}: trust path ratio {} below minimum {}; skipping core load, marking encountered", pubkeyHash, trustPath.getDouble("ratio"), MIN_TRUST_PATH_RATIO);
×
569
                set(s, "accounts_loading", agentAccount.append("status", skipped.getValue()));
×
570
                Document d = new Document("pubkey", pubkeyHash).append("type", INTRO_TYPE_HASH);
×
571
                if (!has(s, "lists", d)) {
×
572
                    insert(s, "lists", d.append("status", encountered.getValue()));
×
573
                }
574
                schedule(s, LOAD_CORE.with("depth", depth).append("load-count", loadCount + 1));
×
575
            } else {
×
576
                logger.info("Pubkey {}: loading core (intro + endorsements) at depth {}", pubkeyHash, depth);
×
577
                // TODO check intro limit
578
                Document introList = new Document()
×
579
                        .append("pubkey", pubkeyHash)
×
580
                        .append("type", INTRO_TYPE_HASH)
×
581
                        .append("status", loading.getValue());
×
582
                if (!has(s, "lists", new Document("pubkey", pubkeyHash).append("type", INTRO_TYPE_HASH))) {
×
583
                    insert(s, "lists", introList);
×
584
                }
585

586
                // No checksum skip in LOAD_CORE: the endorsement extraction logic (below) needs to
587
                // see every nanopub to populate endorsements_loading, which is rebuilt from scratch each UPDATE.
588
                try (var stream = NanopubLoader.retrieveNanopubsFromPeers(INTRO_TYPE_HASH, pubkeyHash)) {
×
589
                    NanopubLoader.loadStreamInParallel(stream, np -> {
×
590
                        try (ClientSession ws = RegistryDB.getClient().startSession()) {
×
591
                            loadNanopub(ws, np, pubkeyHash, INTRO_TYPE);
×
592
                        }
593
                    });
×
594
                }
595

596
                set(s, "lists", introList.append("status", loaded.getValue()));
×
597
                logger.debug("Pubkey {}: intro list loaded", pubkeyHash);
×
598

599
                // TODO check endorsement limit
600
                Document endorseList = new Document()
×
601
                        .append("pubkey", pubkeyHash)
×
602
                        .append("type", ENDORSE_TYPE_HASH)
×
603
                        .append("status", loading.getValue());
×
604
                if (!has(s, "lists", new Document("pubkey", pubkeyHash).append("type", ENDORSE_TYPE_HASH))) {
×
605
                    insert(s, "lists", endorseList);
×
606
                }
607

608
                try (var stream = NanopubLoader.retrieveNanopubsFromPeers(ENDORSE_TYPE_HASH, pubkeyHash)) {
×
609
                    stream.forEach(m -> {
×
610
                        if (!m.isSuccess()) {
×
611
                            logger.error("Pubkey {}: failed to download an endorsement nanopub; aborting LOAD_CORE task", pubkeyHash);
×
612
                            throw new AbortingTaskException("Failed to download nanopub; aborting task...");
×
613
                        }
614
                        Nanopub nanopub = m.getNanopub();
×
615
                        loadNanopub(s, nanopub, pubkeyHash, ENDORSE_TYPE);
×
616
                        String sourceNpId = TrustyUriUtils.getArtifactCode(nanopub.getUri().stringValue());
×
617
                        Validate.notNull(sourceNpId);
×
618
                        for (Statement st : nanopub.getAssertion()) {
×
619
                            if (!st.getPredicate().equals(Utils.APPROVES_OF)) {
×
620
                                continue;
×
621
                            }
622
                            if (!(st.getObject() instanceof IRI)) {
×
623
                                continue;
×
624
                            }
625
                            if (!agentId.equals(st.getSubject().stringValue())) {
×
626
                                continue;
×
627
                            }
628
                            String objStr = st.getObject().stringValue();
×
629
                            if (!TrustyUriUtils.isPotentialTrustyUri(objStr)) {
×
630
                                continue;
×
631
                            }
632
                            String endorsedNpId = TrustyUriUtils.getArtifactCode(objStr);
×
633
                            Validate.notNull(endorsedNpId);
×
634
                            Document endorsement = new Document("agent", agentId)
×
635
                                    .append("pubkey", pubkeyHash)
×
636
                                    .append("endorsedNanopub", endorsedNpId)
×
637
                                    .append("source", sourceNpId);
×
638
                            if (!has(s, "endorsements_loading", endorsement)) {
×
639
                                insert(s, "endorsements_loading",
×
640
                                        endorsement.append("status", toRetrieve.getValue()));
×
641
                            }
642
                        }
×
643
                    });
×
644
                }
645
                logger.debug("Pubkey {}: endorsement list loaded", pubkeyHash);
×
646

647
                set(s, "lists", endorseList.append("status", loaded.getValue()));
×
648

649
                Document df = new Document("pubkey", pubkeyHash).append("type", "$");
×
650
                if (!has(s, "lists", df)) {
×
651
                    insert(s, "lists",
×
652
                            df.append("status", encountered.getValue()));
×
653
                }
654

655
                set(s, "accounts_loading", agentAccount.append("status", visited.getValue()));
×
656

657
                schedule(s, LOAD_CORE.with("depth", depth).append("load-count", loadCount + 1));
×
658
            }
659

660
        }
×
661

662
        // At the end of this step, we have added new endorsement
663
        // links to yet-to-retrieve agent introductions:
664
        // ------------------------------------------------------------
665
        //
666
        //         o      ----endorses----> [intro]
667
        //    --> /#\  /o\___            (to-retrieve)
668
        //        / \  \_/^^^
669
        //         (visited)
670
        //
671
        //    ========[X] trust path
672
        //
673
        // ------------------------------------------------------------
674
        // Only one endorsement is shown here, but there are typically
675
        // several.
676

677
        @Override
678
        public boolean runAsTransaction() {
679
            // Streams intros and endorsements from peers, and loads them through worker threads
680
            // that each open their own session. Neither can join a transaction. See #128.
681
            return false;
×
682
        }
683

684
    },
685

686
    FINISH_ITERATION {
33 ✔
687
        public void run(ClientSession s, Document taskDoc) {
688

689
            int depth = taskDoc.getInteger("depth");
×
690
            int loadCount = taskDoc.getInteger("load-count");
×
691

692
            if (loadCount == 0) {
×
693
                logger.info("No new cores loaded; finishing iteration");
×
694
                schedule(s, CALCULATE_TRUST_SCORES);
×
695
            } else if (depth == MAX_TRUST_PATH_DEPTH) {
×
696
                logger.info("Maximum depth reached: {}", depth);
×
697
                schedule(s, CALCULATE_TRUST_SCORES);
×
698
            } else {
699
                logger.info("Progressing iteration at depth {}", depth + 1);
×
700
                schedule(s, LOAD_DECLARATIONS.with("depth", depth + 1));
×
701
            }
702

703
        }
×
704

705
    },
706

707
    CALCULATE_TRUST_SCORES {
33 ✔
708

709
        // DB read from: accounts, trustPaths
710
        // DB write to:  accounts
711

712
        public void run(ClientSession s, Document taskDoc) {
713
            logger.info("Running CALCULATE_TRUST_SCORES task");
×
714

715
            while (true) {
716
                Document d = getOne(s, "accounts_loading", new Document("status", expanded.getValue()));
×
717
                if (d == null) {
×
718
                    break;
×
719
                }
720

721
                double ratio = 0.0;
×
722
                Map<String, Boolean> seenPathElements = new HashMap<>();
×
723
                int pathCount = 0;
×
724
                try (MongoCursor<Document> trustPaths = collection("trustPaths_loading").find(s,
×
725
                        new Document("agent", d.get("agent").toString()).append("pubkey", d.get("pubkey").toString())
×
726
                ).sort(orderBy(ascending("depth"), descending("ratio"), ascending("sorthash"))).cursor()) {
×
727
                    while (trustPaths.hasNext()) {
×
728
                        Document trustPath = trustPaths.next();
×
729
                        ratio += trustPath.getDouble("ratio");
×
730
                        boolean independentPath = true;
×
731
                        String[] pathElements = trustPath.getString("_id").split(" ");
×
732
                        // Iterate over path elements, ignoring first (root) and last (this agent/pubkey):
733
                        for (int i = 1; i < pathElements.length - 1; i++) {
×
734
                            String p = pathElements[i];
×
735
                            if (seenPathElements.containsKey(p)) {
×
736
                                independentPath = false;
×
737
                                break;
×
738
                            }
739
                            seenPathElements.put(p, true);
×
740
                        }
741
                        if (independentPath) {
×
742
                            pathCount += 1;
×
743
                        }
744
                    }
×
745
                }
746
                double rawQuota = GLOBAL_QUOTA * ratio;
×
747
                int quota = (int) rawQuota;
×
748
                if (rawQuota < MIN_USER_QUOTA) {
×
749
                    quota = MIN_USER_QUOTA;
×
750
                } else if (rawQuota > MAX_USER_QUOTA) {
×
751
                    quota = MAX_USER_QUOTA;
×
752
                }
753
                set(s, "accounts_loading",
×
754
                        d.append("status", processed.getValue())
×
755
                                .append("ratio", ratio)
×
756
                                .append("pathCount", pathCount)
×
757
                                .append("quota", quota)
×
758
                );
759
            }
×
760
            logger.info("CALCULATE_TRUST_SCORES complete");
×
761
            schedule(s, AGGREGATE_AGENTS);
×
762
        }
×
763

764
    },
765

766
    AGGREGATE_AGENTS {
33 ✔
767

768
        // DB read from: accounts, agents
769
        // DB write to:  accounts, agents
770

771
        public void run(ClientSession s, Document taskDoc) {
772
            logger.info("Running AGGREGATE_AGENTS task");
×
773

774
            while (true) {
775
                Document a = getOne(s, "accounts_loading", new Document("status", processed.getValue()));
×
776
                if (a == null) {
×
777
                    break;
×
778
                }
779

780
                Document agentId = new Document("agent", a.get("agent").toString()).append("status", processed.getValue());
×
781
                int count = 0;
×
782
                int pathCountSum = 0;
×
783
                double totalRatio = 0.0d;
×
784
                // Canonical-name resolution across the agent's approved keys: pick the
785
                // row with MAX(ratio); ties broken on lex-min name for determinism.
786
                // Per-(agent, pubkey) name was already chosen by LOAD_ENDORSEMENTS as
787
                // "latest declaring intro wins"; this layer just folds across keys.
788
                String chosenName = null;
×
789
                double chosenRatio = Double.NEGATIVE_INFINITY;
×
790
                try (MongoCursor<Document> agentAccounts = collection("accounts_loading").find(s, agentId).cursor()) {
×
791
                    while (agentAccounts.hasNext()) {
×
792
                        Document d = agentAccounts.next();
×
793
                        count++;
×
794
                        pathCountSum += d.getInteger("pathCount");
×
795
                        double r = d.getDouble("ratio");
×
796
                        totalRatio += r;
×
797
                        String n = d.getString("name");
×
798
                        if (n != null && (r > chosenRatio
×
799
                                          || (r == chosenRatio && (chosenName == null || n.compareTo(chosenName) < 0)))) {
×
800
                            chosenName = n;
×
801
                            chosenRatio = r;
×
802
                        }
803
                    }
×
804
                }
805
                collection("accounts_loading").updateMany(s, agentId, new Document("$set",
×
806
                        new DbEntryWrapper(aggregated).getDocument()));
×
807
                insert(s, "agents_loading",
×
808
                        agentId.append("accountCount", count)
×
809
                                .append("avgPathCount", (double) pathCountSum / count)
×
810
                                .append("totalRatio", totalRatio)
×
811
                                .append("name", chosenName)
×
812
                );
813
            }
×
814
            logger.info("AGGREGATE_AGENTS complete");
×
815
            schedule(s, ASSIGN_PUBKEYS);
×
816

817
        }
×
818

819
    },
820

821
    ASSIGN_PUBKEYS {
33 ✔
822

823
        // DB read from: accounts
824
        // DB write to:  accounts
825

826
        public void run(ClientSession s, Document taskDoc) {
827
            logger.info("Running ASSIGN_PUBKEYS task");
×
828
            int approvedCount = 0;
×
829
            int contestedCount = 0;
×
830

831
            while (true) {
832
                Document a = getOne(s, "accounts_loading", new DbEntryWrapper(aggregated).getDocument());
×
833
                if (a == null) {
×
834
                    break;
×
835
                }
836

837
                Document pubkeyId = new Document("pubkey", a.get("pubkey").toString());
×
838
                if (collection("accounts_loading").countDocuments(s, pubkeyId) == 1) {
×
839
                    collection("accounts_loading").updateMany(s, pubkeyId,
×
840
                            new Document("$set", new DbEntryWrapper(approved).getDocument()));
×
841
                    approvedCount++;
×
842
                } else {
843
                    // TODO At the moment all get marked as 'contested'; implement more nuanced algorithm
844
                    logger.debug("Pubkey {} is claimed by multiple accounts; marking contested", pubkeyId.getString("pubkey"));
×
845
                    collection("accounts_loading").updateMany(s, pubkeyId, new Document("$set",
×
846
                            new DbEntryWrapper(contested).getDocument()));
×
847
                    contestedCount++;
×
848
                }
849
            }
×
850
            logger.info("ASSIGN_PUBKEYS complete: {} approved, {} contested", approvedCount, contestedCount);
×
851
            schedule(s, DETERMINE_UPDATES);
×
852

853
        }
×
854

855
    },
856

857
    DETERMINE_UPDATES {
33 ✔
858

859
        // DB read from: accounts
860
        // DB write to:  accounts
861

862
        public void run(ClientSession s, Document taskDoc) {
863
            logger.info("Running DETERMINE_UPDATES task");
×
864

865
            // TODO Handle contested accounts properly:
866
            for (Document d : collection("accounts_loading").find(s,
×
867
                    new DbEntryWrapper(approved).getDocument())) {
×
868
                // TODO Consider quota too:
869
                Document accountId = new Document("agent", d.get("agent").toString()).append("pubkey", d.get("pubkey").toString());
×
870
                if (collection(Collection.ACCOUNTS.toString()) == null || !has(s, Collection.ACCOUNTS.toString(),
×
871
                        accountId.append("status", loaded.getValue()))) {
×
872
                    set(s, "accounts_loading", d.append("status", toLoad.getValue()));
×
873
                } else {
874
                    set(s, "accounts_loading", d.append("status", loaded.getValue()));
×
875
                }
876
            }
×
877
            logger.info("DETERMINE_UPDATES complete");
×
878
            schedule(s, FINALIZE_TRUST_STATE);
×
879

880
        }
×
881

882
    },
883

884
    FINALIZE_TRUST_STATE {
33 ✔
885
        // We do this is a separate task/transaction, because if we do it at the beginning of RELEASE_DATA, that task hangs and cannot
886
        // properly re-run (as some renaming outside of transactions will have taken place).
887
        public void run(ClientSession s, Document taskDoc) {
888
            logger.info("Running FINALIZE_TRUST_STATE task");
×
889
            String newTrustStateHash = RegistryDB.calculateTrustStateHash(s);
×
890
            String previousTrustStateHash = (String) getValue(s, Collection.SERVER_INFO.toString(), "trustStateHash");  // may be null
×
891
            logger.info("Computed new trust state hash {} (previous: {})", newTrustStateHash, previousTrustStateHash);
×
892
            setValue(s, Collection.SERVER_INFO.toString(), "lastTrustStateUpdate", ZonedDateTime.now().toString());
×
893

894
            schedule(s, RELEASE_DATA.with("newTrustStateHash", newTrustStateHash).append("previousTrustStateHash", previousTrustStateHash));
×
895
        }
×
896

897
    },
898

899
    RELEASE_DATA {
33 ✔
900

901
        /**
902
         * Publishes the cycle's results by renaming the loading collections over the live ones.
903
         *
904
         * <p>Renaming is a catalog operation and cannot run inside a transaction, which is the
905
         * whole reason this task is separate: everything derived from the renamed collections —
906
         * the counter, the snapshot, the status transition — is in {@link #PUBLISH_TRUST_STATE},
907
         * which runs afterwards and so reads them through a snapshot that already includes them
908
         * (issue #128).
909
         */
910
        public void run(ClientSession s, Document taskDoc) {
911
            logger.info("Running RELEASE_DATA task (current status: {})", getServerStatus(s));
15 ✔
912

913
            String newTrustStateHash = taskDoc.get("newTrustStateHash").toString();
15 ✔
914
            String previousTrustStateHash = taskDoc.getString("previousTrustStateHash");  // may be null
12 ✔
915

916
            // Renaming collections is run outside of a transaction, but is idempotent operation, so can safely be retried if task fails:
917
            logger.debug("Renaming loading collections into live collections");
9 ✔
918
            promoteLoadingCollections();
3 ✔
919

920
            schedule(s, PUBLISH_TRUST_STATE
15 ✔
921
                    .with("newTrustStateHash", newTrustStateHash)
9 ✔
922
                    .append("previousTrustStateHash", previousTrustStateHash));
3 ✔
923
        }
3 ✔
924

925
        @Override
926
        public boolean runAsTransaction() {
927
            // Renames the _loading collections into the live ones, which is DDL and cannot run
928
            // inside a transaction. See #128. Both the renames and the rescheduling below them are
929
            // idempotent, which is what PUBLISH_TRUST_STATE's own guard relies on: an interrupted
930
            // run of this task is re-executed and enqueues that successor a second time.
931
            return false;
×
932
        }
933

934
    },
935

936
    PUBLISH_TRUST_STATE {
33 ✔
937

938
        private static final int TRUST_STATE_SNAPSHOT_RETENTION = 100;
939

940
        /**
941
         * Records the newly released trust state: the counter, the debug row, the hash-keyed
942
         * snapshot, the retention pruning and the server status transition. Transactional — every
943
         * write here is an ordinary document write on collections {@link #RELEASE_DATA} has
944
         * already renamed into place.
945
         *
946
         * <p>The very first state of a fresh registry is held back: nothing is recorded until a
947
         * cycle finds the initial full load complete, so consumers never see the near-empty
948
         * bootstrap state (see below).
949
         */
950
        public void run(ClientSession s, Document taskDoc) {
951
            ServerStatus status = getServerStatus(s);
9 ✔
952
            logger.info("Running PUBLISH_TRUST_STATE task (current status: {})", status);
12 ✔
953

954
            String newTrustStateHash = taskDoc.get("newTrustStateHash").toString();
15 ✔
955
            String previousTrustStateHash = taskDoc.getString("previousTrustStateHash");  // may be null
12 ✔
956
            String storedTrustStateHash = (String) getValue(s, Collection.SERVER_INFO.toString(), "trustStateHash");  // null until the first publication
21 ✔
957

958
            if (storedTrustStateHash == null
15 ✔
959
                    && !"false".equals(Utils.getEnv("REGISTRY_PERFORM_FULL_LOAD", null))
15 !
960
                    && has(s, Collection.ACCOUNTS.toString(), new DbEntryWrapper(toLoad).getDocument())) {
24 ✔
961
                // Bootstrap: nothing has ever been published and the just-released accounts are
962
                // still waiting for their initial full load, so the computed state is the
963
                // near-empty bootstrap one — every account still 'toLoad' is excluded from the
964
                // hash and the snapshot (issue #119, calculateTrustStateHash). Publishing it would
965
                // hand consumers a trust state containing essentially nobody, replaced as soon as
966
                // loading finishes without any change in the network. Hold off instead until a
967
                // cycle finds the initial load complete. Checked against the database rather than
968
                // the server status because the initial load can span several update cycles, and
969
                // because a re-run of the non-transactional RELEASE_DATA enqueues this task twice.
970
                // Once something has been published, 'toLoad' accounts are normal between-cycles
971
                // state (#119) and must not suppress publication.
972
                logger.info("Initial full load not complete yet; not publishing bootstrap trust state {}", newTrustStateHash);
15 ✔
973
            } else if (previousTrustStateHash == null || !previousTrustStateHash.equals(newTrustStateHash)) {
6 !
974
                logger.info("Trust state changed ({} -> {}); recording new state and snapshot", previousTrustStateHash, newTrustStateHash);
15 ✔
975
                // Bump the counter and record the hash only once per distinct trust state. This
976
                // task is transactional, so it cannot half-apply — but RELEASE_DATA is not, and an
977
                // interrupted run of it enqueues this task a second time with the same hashes. The
978
                // check has to be against the stored hash rather than against
979
                // previousTrustStateHash from the task document, which still holds the value from
980
                // before the first run and would let the counter drift on every duplicate.
981
                if (newTrustStateHash.equals(storedTrustStateHash)) {
12 ✔
982
                    logger.info("Trust state {} was already recorded by an earlier run of this task; not bumping the counter again", newTrustStateHash);
15 ✔
983
                } else {
984
                    increaseStateCounter(s);
6 ✔
985
                    setValue(s, Collection.SERVER_INFO.toString(), "trustStateHash", newTrustStateHash);
18 ✔
986
                }
987
                Object trustStateCounter = getValue(s, Collection.SERVER_INFO.toString(), "trustStateCounter");
18 ✔
988
                // Keyed on the counter, which is stable across retries thanks to the guard above,
989
                // so a retry replaces this row instead of appending a duplicate. The
990
                // trustStateCounter field is kept because DebugPage queries on it.
991
                collection("debug_trustPaths").replaceOne(s,
51 ✔
992
                        new Document("_id", trustStateCounter),
993
                        new Document("_id", trustStateCounter)
994
                                .append("trustStateTxt", DebugPage.getTrustPathsTxt(s))
12 ✔
995
                                .append("trustStateHash", newTrustStateHash)
9 ✔
996
                                .append("trustStateCounter", trustStateCounter),
15 ✔
997
                        new ReplaceOptions().upsert(true));
3 ✔
998

999
                // Structured hash-keyed snapshot for consumer mirroring (#107).
1000
                // Reads the accounts collection just renamed from accounts_loading above (:697).
1001
                List<Document> snapshotAccounts = new ArrayList<>();
12 ✔
1002
                for (Document a : collection(Collection.ACCOUNTS.toString()).find(s)) {
42 ✔
1003
                    String pubkey = a.getString("pubkey");
12 ✔
1004
                    if ("$".equals(pubkey)) {
12 !
1005
                        continue;
×
1006
                    }
1007
                    // 'toLoad' is an internal-only staging status (not yet servable). Excluding it here
1008
                    // — together with the matching exclusion in calculateTrustStateHash — keeps transient
1009
                    // 'toLoad' accounts out of the published snapshot, so an account enters the public
1010
                    // trust state exactly when it becomes loaded, never stuck at 'toLoad' (issue #119).
1011
                    if (toLoad.getValue().equals(a.getString("status"))) {
21 !
1012
                        continue;
×
1013
                    }
1014
                    snapshotAccounts.add(new Document()
24 ✔
1015
                            .append("pubkey", pubkey)
12 ✔
1016
                            .append("agent", a.getString("agent"))
15 ✔
1017
                            .append("name", a.getString("name"))
15 ✔
1018
                            .append("nameCreatedAt", a.get("nameCreatedAt"))
15 ✔
1019
                            .append("introNanopub", a.getString("introNanopub"))
15 ✔
1020
                            .append("status", a.getString("status"))
15 ✔
1021
                            .append("depth", a.get("depth"))
15 ✔
1022
                            .append("pathCount", a.get("pathCount"))
15 ✔
1023
                            .append("ratio", a.get("ratio"))
15 ✔
1024
                            .append("quota", a.get("quota")));
6 ✔
1025
                }
3 ✔
1026
                Document snapshot = new Document()
15 ✔
1027
                        .append("_id", newTrustStateHash)
9 ✔
1028
                        .append("trustStateCounter", trustStateCounter)
6 ✔
1029
                        .append("createdAt", ZonedDateTime.now().toString())
15 ✔
1030
                        .append("accounts", snapshotAccounts);
6 ✔
1031
                collection(Collection.TRUST_STATE_SNAPSHOTS.toString()).replaceOne(
48 ✔
1032
                        s,
1033
                        new Document("_id", newTrustStateHash),
1034
                        snapshot,
1035
                        new ReplaceOptions().upsert(true));
3 ✔
1036
                logger.debug("Saved trust state snapshot {} with {} account(s)", newTrustStateHash, snapshotAccounts.size());
21 ✔
1037

1038
                // Prune beyond retention: collect _ids of snapshots past the Nth most recent, delete them.
1039
                // trustStateCounter is monotonically increasing (see increaseStateCounter above), so ordering is well-defined.
1040
                List<Object> toPrune = new ArrayList<>();
12 ✔
1041
                try (MongoCursor<Document> stale = collection(Collection.TRUST_STATE_SNAPSHOTS.toString())
12 ✔
1042
                        .find(s)
21 ✔
1043
                        .sort(descending("trustStateCounter"))
9 ✔
1044
                        .skip(TRUST_STATE_SNAPSHOT_RETENTION)
15 ✔
1045
                        .projection(new Document("_id", 1))
9 ✔
1046
                        .cursor()) {
6 ✔
1047
                    while (stale.hasNext()) {
9 !
1048
                        toPrune.add(stale.next().get("_id"));
×
1049
                    }
1050
                }
1051
                if (!toPrune.isEmpty()) {
9 !
1052
                    logger.info("Pruning {} trust state snapshot(s) beyond retention limit of {}", toPrune.size(), TRUST_STATE_SNAPSHOT_RETENTION);
×
1053
                    collection(Collection.TRUST_STATE_SNAPSHOTS.toString()).deleteMany(
×
1054
                            s, new Document("_id", new Document("$in", toPrune)));
1055
                }
1056
            } else {
3 ✔
1057
                logger.info("Trust state unchanged ({}); skipping snapshot and pruning", newTrustStateHash);
×
1058
            }
1059

1060
            if (status == coreLoading) {
9 ✔
1061
                logger.info("Server status transitioning coreLoading -> coreReady");
9 ✔
1062
                setServerStatus(s, coreReady);
12 ✔
1063
            } else {
1064
                logger.info("Server status transitioning {} -> ready", status);
12 ✔
1065
                setServerStatus(s, ready);
9 ✔
1066
            }
1067

1068
            // Run update 10min after this cycle finishes (the delay is measured from the end of the
1069
            // recompute, since this is the last task in the chain):
1070
            logger.debug("PUBLISH_TRUST_STATE complete; scheduling next UPDATE in 10min");
9 ✔
1071
            schedule(s, UPDATE.withDelay(10 * 60 * 1000));
15 ✔
1072
        }
3 ✔
1073

1074
    },
1075

1076
    UPDATE {
33 ✔
1077
        public void run(ClientSession s, Document taskDoc) {
1078
            ServerStatus status = getServerStatus(s);
×
1079
            if (status == ready || status == coreReady) {
×
1080
                logger.info("Server status {} eligible for update; transitioning to updating and scheduling INIT_COLLECTIONS", status);
×
1081
                setServerStatus(s, updating);
×
1082
                schedule(s, INIT_COLLECTIONS);
×
1083
            } else {
1084
                logger.info("Postponing update; currently in status {}", status);
×
1085
                schedule(s, UPDATE.withDelay(10 * 60 * 1000));
×
1086
            }
1087

1088
        }
×
1089

1090
    },
1091

1092
    LOAD_FULL {
33 ✔
1093
        public void run(ClientSession s, Document taskDoc) {
1094
            logger.debug("LOAD_FULL invoked; taskDoc={}", taskDoc);
12 ✔
1095

1096
            if ("false".equals(Utils.getEnv("REGISTRY_PERFORM_FULL_LOAD", null))) {
18 !
1097
                logger.info("REGISTRY_PERFORM_FULL_LOAD=false; skipping full load");
×
1098
                return;
×
1099
            }
1100

1101
            ServerStatus status = getServerStatus(s);
9 ✔
1102
            logger.debug("Server status check for LOAD_FULL: status={}", status);
12 ✔
1103
            if (status != coreReady && status != ready && status != updating) {
27 !
1104
                long delay = 1000;
6 ✔
1105
                logger.info("Server status={} is not eligible for full load (expected coreReady/ready/updating); deferring and retrying in {}ms", status, delay);
18 ✔
1106
                schedule(s, LOAD_FULL.withDelay(delay));
15 ✔
1107
                return;
3 ✔
1108
            }
1109

1110
            Document a = getOne(s, Collection.ACCOUNTS.toString(), new DbEntryWrapper(toLoad).getDocument());
×
1111
            if (a == null) {
×
1112
                logger.info("No accounts left with status={}; full load pass complete", toLoad);
×
1113
                if (status == coreReady) {
×
1114
                    logger.info("Server status transitioning coreReady -> ready; full load finished");
×
1115
                    setServerStatus(s, ready);
×
1116
                }
1117
                long delay = 100;
×
1118
                logger.info("Scheduling optional loading checks (RUN_OPTIONAL_LOAD) in {}ms", delay);
×
1119
                schedule(s, RUN_OPTIONAL_LOAD.withDelay(delay));
×
1120
            } else {
×
1121
                final String ph = a.getString("pubkey");
×
1122
                boolean quotaReached = false;
×
1123
                if (!ph.equals("$")) {
×
1124
                    if (!AgentFilter.isAllowed(s, ph)) {
×
1125
                        logger.info("Pubkey {} is not covered by the agent filter; marking account as skipped", ph);
×
1126
                        set(s, Collection.ACCOUNTS.toString(), a.append("status", skipped.getValue()));
×
1127
                        schedule(s, LOAD_FULL.withDelay(100));
×
1128
                        return;
×
1129
                    }
1130
                    if (AgentFilter.isOverQuota(s, ph)) {
×
1131
                        logger.info("Pubkey {} is already over quota; skipping load, marking account as capped", ph);
×
1132
                        quotaReached = true;
×
1133
                    } else {
1134
                        long startTime = System.nanoTime();
×
1135
                        AtomicLong totalLoaded = new AtomicLong(0);
×
1136

1137
                        // Load per covered type (or "$" if no restriction) with checksum skip-ahead
1138
                        for (String typeHash : getLoadTypeHashes(s, ph)) {
×
1139
                            logger.debug("Pubkey {}: starting load for typeHash={}", ph, typeHash);
×
1140
                            String checksums = buildChecksumFallbacks(s, ph, typeHash);
×
1141
                            logger.debug("Pubkey {}, typeHash={}: checksum fallbacks={}", ph, typeHash, checksums);
×
1142
                            try (var stream = NanopubLoader.retrieveNanopubsFromPeers(typeHash, ph, checksums)) {
×
1143
                                NanopubLoader.loadStreamInParallel(stream, np -> {
×
1144
                                    if (!CoverageFilter.isCovered(np)) {
×
1145
                                        logger.debug("Pubkey {}: nanopub {} not covered; skipping", ph, np);
×
1146
                                        return;
×
1147
                                    }
1148
                                    try (ClientSession ws = RegistryDB.getClient().startSession()) {
×
1149
                                        if (!AgentFilter.isOverQuota(ws, ph)) {
×
1150
                                            loadNanopub(ws, np, ph, "$");
×
1151
                                            totalLoaded.incrementAndGet();
×
1152
                                        } else {
1153
                                            logger.debug("Pubkey {} hit quota mid-stream; skipping nanopub {}", ph, np);
×
1154
                                        }
1155
                                    }
1156
                                });
×
1157
                            }
1158
                            logger.debug("Pubkey {}: finished load for typeHash={}", ph, typeHash);
×
1159
                        }
×
1160

1161
                        double timeSeconds = (System.nanoTime() - startTime) * 1e-9;
×
1162
                        logger.info("Pubkey {}: loaded {} nanopubs in {}s ({} np/s)",
×
1163
                                ph, totalLoaded.get(), String.format("%.2f", timeSeconds),
×
1164
                                String.format("%.2f", totalLoaded.get() / timeSeconds));
×
1165

1166
                        if (AgentFilter.isOverQuota(s, ph)) {
×
1167
                            logger.info("Pubkey {} reached quota during this load; marking account as capped", ph);
×
1168
                            quotaReached = true;
×
1169
                        }
1170
                    }
×
1171
                } else {
1172
                    logger.debug("Account pubkey is '$' (unrestricted); no per-pubkey quota/filter checks applied");
×
1173
                }
1174

1175
                Document l = getOne(s, "lists", new Document().append("pubkey", ph).append("type", "$"));
×
1176
                if (l != null) {
×
1177
                    logger.debug("Pubkey {}: marking matching list entry as loaded", ph);
×
1178
                    set(s, "lists", l.append("status", loaded.getValue()));
×
1179
                }
1180
                EntryStatus accountStatus = quotaReached ? capped : loaded;
×
1181
                int effectiveQuota = AgentFilter.getQuota(s, ph);
×
1182
                if (effectiveQuota >= 0) {
×
1183
                    logger.debug("Pubkey {}: recording effective quota={}", ph, effectiveQuota);
×
1184
                    a.append("quota", effectiveQuota);
×
1185
                }
1186
                logger.info("Pubkey {}: account load complete, status={}", ph, accountStatus);
×
1187
                set(s, Collection.ACCOUNTS.toString(), a.append("status", accountStatus.getValue()));
×
1188

1189
                schedule(s, LOAD_FULL.withDelay(100));
×
1190
            }
1191
        }
×
1192

1193
        @Override
1194
        public boolean runAsTransaction() {
1195
            // TODO Make this a transaction once we connect to other Nanopub Registry instances:
1196
            return false;
×
1197
        }
1198

1199
    },
1200

1201
    RUN_OPTIONAL_LOAD {
33 ✔
1202

1203
        private static final int BATCH_SIZE = Integer.parseInt(
15 ✔
1204
                Utils.getEnv("REGISTRY_OPTIONAL_LOAD_BATCH_SIZE", "100"));
3 ✔
1205

1206
        public void run(ClientSession s, Document taskDoc) {
1207
            if ("false".equals(System.getenv("REGISTRY_ENABLE_OPTIONAL_LOAD"))) {
×
1208
                schedule(s, CHECK_NEW.withDelay(500));
×
1209
                return;
×
1210
            }
1211

1212
            AtomicLong totalLoaded = new AtomicLong(0);
×
1213

1214
            // Phase 1: Process encountered intro lists (core loading)
1215
            while (totalLoaded.get() < BATCH_SIZE) {
×
1216
                Document di = getOne(s, "lists", new Document("type", INTRO_TYPE_HASH).append("status", encountered.getValue()));
×
1217
                if (di == null) {
×
1218
                    break;
×
1219
                }
1220

1221
                final String pubkeyHash = di.getString("pubkey");
×
1222
                Validate.notNull(pubkeyHash);
×
1223
                logger.info("Optional core loading: {}", pubkeyHash);
×
1224

1225
                String introChecksums = buildChecksumFallbacks(s, pubkeyHash, INTRO_TYPE_HASH);
×
1226
                try (var stream = NanopubLoader.retrieveNanopubsFromPeers(INTRO_TYPE_HASH, pubkeyHash, introChecksums)) {
×
1227
                    NanopubLoader.loadStreamInParallel(stream, np -> {
×
1228
                        try (ClientSession ws = RegistryDB.getClient().startSession()) {
×
1229
                            loadNanopub(ws, np, pubkeyHash, INTRO_TYPE);
×
1230
                            totalLoaded.incrementAndGet();
×
1231
                        }
1232
                    });
×
1233
                }
1234
                set(s, "lists", di.append("status", loaded.getValue()));
×
1235

1236
                String endorseChecksums = buildChecksumFallbacks(s, pubkeyHash, ENDORSE_TYPE_HASH);
×
1237
                try (var stream = NanopubLoader.retrieveNanopubsFromPeers(ENDORSE_TYPE_HASH, pubkeyHash, endorseChecksums)) {
×
1238
                    NanopubLoader.loadStreamInParallel(stream, np -> {
×
1239
                        try (ClientSession ws = RegistryDB.getClient().startSession()) {
×
1240
                            loadNanopub(ws, np, pubkeyHash, ENDORSE_TYPE);
×
1241
                            totalLoaded.incrementAndGet();
×
1242
                        }
1243
                    });
×
1244
                }
1245

1246
                Document de = new Document("pubkey", pubkeyHash).append("type", ENDORSE_TYPE_HASH);
×
1247
                if (has(s, "lists", de)) {
×
1248
                    set(s, "lists", de.append("status", loaded.getValue()));
×
1249
                } else {
1250
                    insert(s, "lists", de.append("status", loaded.getValue()));
×
1251
                }
1252

1253
                Document df = new Document("pubkey", pubkeyHash).append("type", "$");
×
1254
                if (!has(s, "lists", df)) {
×
1255
                    insert(s, "lists", df.append("status", encountered.getValue()));
×
1256
                }
1257
            }
×
1258

1259
            // Phase 2: Process encountered full lists (if budget remains)
1260
            while (totalLoaded.get() < BATCH_SIZE) {
×
1261
                Document df = getOne(s, "lists", new Document("type", "$").append("status", encountered.getValue()));
×
1262
                if (df == null) {
×
1263
                    break;
×
1264
                }
1265

1266
                final String pubkeyHash = df.getString("pubkey");
×
1267
                logger.info("Optional full loading: {}", pubkeyHash);
×
1268

1269
                // Load per covered type (or "$" if no restriction) with checksum skip-ahead
1270
                for (String typeHash : getLoadTypeHashes(s, pubkeyHash)) {
×
1271
                    String checksums = buildChecksumFallbacks(s, pubkeyHash, typeHash);
×
1272
                    try (var stream = NanopubLoader.retrieveNanopubsFromPeers(typeHash, pubkeyHash, checksums)) {
×
1273
                        NanopubLoader.loadStreamInParallel(stream, np -> {
×
1274
                            if (!CoverageFilter.isCovered(np)) {
×
1275
                                return;
×
1276
                            }
1277
                            try (ClientSession ws = RegistryDB.getClient().startSession()) {
×
1278
                                loadNanopub(ws, np, pubkeyHash, "$");
×
1279
                                totalLoaded.incrementAndGet();
×
1280
                            }
1281
                        });
×
1282
                    }
1283
                }
×
1284

1285
                set(s, "lists", df.append("status", loaded.getValue()));
×
1286

1287
                // Backfill nanopubs stored locally during the transitional period (i.e. before
1288
                // the $ list was loaded). Such nanopubs were stored in the nanopubs collection by
1289
                // simpleLoad() but never added to listEntries; add them to the $ list now.
1290
                logger.info("Backfilling locally stored nanopubs for pubkey: {}", pubkeyHash);
×
1291
                try (MongoCursor<Document> npCursor = collection(Collection.NANOPUBS.toString())
×
1292
                        .find(s, new Document("pubkey", pubkeyHash)).cursor()) {
×
1293
                    while (npCursor.hasNext()) {
×
1294
                        String fullId = npCursor.next().getString("fullId");
×
1295
                        if (fullId == null) {
×
1296
                            continue;
×
1297
                        }
1298
                        try (ClientSession ws = RegistryDB.getClient().startSession()) {
×
1299
                            Nanopub np = NanopubLoader.retrieveLocalNanopub(ws, fullId);
×
1300
                            if (np != null && CoverageFilter.isCovered(np)) {
×
1301
                                loadNanopub(ws, np, pubkeyHash, "$");
×
1302
                                totalLoaded.incrementAndGet();
×
1303
                            }
1304
                        } catch (Exception ex) {
×
1305
                            logger.info("Error backfilling nanopub {}: {}", fullId, ex.getMessage());
×
1306
                        }
×
1307
                    }
×
1308
                }
1309
            }
×
1310

1311
            if (totalLoaded.get() > 0) {
×
1312
                logger.info("Optional load batch completed: {} nanopubs across multiple pubkeys", totalLoaded.get());
×
1313
            }
1314

1315
            if (prioritizeAllPubkeys()) {
×
1316
                // Check if there are more pubkeys waiting to be processed
1317
                boolean moreWork = has(s, "lists", new Document("type", INTRO_TYPE_HASH).append("status", encountered.getValue()))
×
1318
                                   || has(s, "lists", new Document("type", "$").append("status", encountered.getValue()));
×
1319
                if (moreWork) {
×
1320
                    // Continue processing without a full CHECK_NEW cycle in between.
1321
                    // CHECK_NEW will run naturally once all encountered lists are processed.
1322
                    schedule(s, RUN_OPTIONAL_LOAD.withDelay(10));
×
1323
                } else {
1324
                    schedule(s, CHECK_NEW.withDelay(500));
×
1325
                }
1326
            } else {
×
1327
                // Throttled: yield to CHECK_NEW after each batch to prioritize approved pubkeys
1328
                schedule(s, CHECK_NEW.withDelay(500));
×
1329
            }
1330
        }
×
1331

1332
        @Override
1333
        public boolean runAsTransaction() {
1334
            // Streams up to REGISTRY_OPTIONAL_LOAD_BATCH_SIZE nanopubs from peers and loads them
1335
            // through worker threads that each open their own session. Neither can join a
1336
            // transaction. See #128.
1337
            return false;
×
1338
        }
1339

1340
    },
1341

1342
    CHECK_NEW {
33 ✔
1343
        public void run(ClientSession s, Document taskDoc) {
1344
            logger.debug("Running CHECK_NEW task: checking peers and legacy source for new nanopubs");
×
1345

1346
            logger.debug("Checking peers for new nanopubs");
×
1347
            RegistryPeerConnector.checkPeers(s);
×
1348
            // Keep legacy connection during transition period:
1349
            logger.debug("Checking legacy connector for new nanopubs");
×
1350
            LegacyConnector.checkForNewNanopubs(s);
×
1351
            // TODO Somehow throttle the loading of such potentially non-approved nanopubs
1352

1353
            long delay = 100;
×
1354
            logger.debug("CHECK_NEW complete; scheduling LOAD_FULL with {}ms delay", delay);
×
1355
            schedule(s, LOAD_FULL.withDelay(delay));
×
1356
        }
×
1357

1358
        @Override
1359
        public boolean runAsTransaction() {
1360
            // Peer sync includes long-running streaming fetches that would exceed
1361
            // MongoDB's transaction timeout; each operation is individually safe.
1362
            return false;
×
1363
        }
1364

1365
    };
1366

1367
    private static final Logger logger = LoggerFactory.getLogger(Task.class);
9 ✔
1368

1369
    public abstract void run(ClientSession s, Document taskDoc) throws Exception;
1370

1371
    /**
1372
     * Which trust edges out of {@code (agentId, pubkeyHash)} the trust calculation follows.
1373
     *
1374
     * <p>Normally: edges that are not invalidated. Plus, always: edges sourced from a setting
1375
     * nanopub this instance was bootstrapped from, <em>even when they are invalidated</em>
1376
     * (issue #60).
1377
     *
1378
     * <p>Those edges are correctly marked invalidated — a superseded setting is invalidated
1379
     * like anything else, and {@code RegistryDB} records that faithfully. But the root
1380
     * endorsements of a running instance are all sourced from its setting
1381
     * ({@link #INIT_COLLECTIONS}), so honouring that invalidation here severs every root edge
1382
     * at once and collapses the trust network to the base agent. It cannot recover either:
1383
     * {@link #LOAD_SETTING} runs only at {@code status == launching}, so the instance keeps
1384
     * using the superseded setting.
1385
     *
1386
     * <p>That happened on 2026-08-05. A setting superseding the deployed one was published,
1387
     * changing only its trust-range algorithm — a field no code reads — and the next iteration
1388
     * produced a trust state with 14 accounts instead of 777, identically on three independent
1389
     * registries. Adopting a superseding setting is a deliberate act (deploy it as
1390
     * {@code REGISTRY_SETTING_FILE} and re-bootstrap); merely publishing one must not do it.
1391
     *
1392
     * @param agentId          the source agent
1393
     * @param pubkeyHash       the source pubkey hash
1394
     * @param bootstrapSettings artifact codes from {@link RegistryDB#getBootstrapSettingAcs}
1395
     * @return the MongoDB filter for the edges to follow
1396
     */
1397
    static Document trustEdgeFilter(String agentId, String pubkeyHash, Set<String> bootstrapSettings) {
1398
        Document filter = new Document("fromAgent", agentId).append("fromPubkey", pubkeyHash);
27 ✔
1399
        if (bootstrapSettings.isEmpty()) {
9 ✔
1400
            return filter.append("invalidated", false);
18 ✔
1401
        }
1402
        return filter.append("$or", List.of(
27 ✔
1403
                new Document("invalidated", false),
42 ✔
1404
                new Document("source", new Document("$in", new ArrayList<>(bootstrapSettings)))));
1405
    }
1406

1407
    public boolean runAsTransaction() {
1408
        return true;
×
1409
    }
1410

1411
    Document asDocument() {
1412
        return withDelay(0L);
12 ✔
1413
    }
1414

1415
    private Document withDelay(long delay) {
1416
        // TODO Rename "not-before" to "notBefore" for consistency with other field names
1417
        return new Document()
15 ✔
1418
                .append("not-before", System.currentTimeMillis() + delay)
21 ✔
1419
                .append("action", name());
6 ✔
1420
    }
1421

1422
    private Document with(String key, Object value) {
1423
        return asDocument().append(key, value);
18 ✔
1424
    }
1425

1426
    private static boolean prioritizeAllPubkeys() {
1427
        return "true".equals(System.getenv("REGISTRY_PRIORITIZE_ALL_PUBKEYS"));
×
1428
    }
1429

1430
    /**
1431
     * Returns the type hashes to load for a given pubkey. When coverage is unrestricted,
1432
     * returns just "$" (all types in one request). When restricted, returns each covered
1433
     * type hash for per-type fetching with checksum skip-ahead.
1434
     * <p>
1435
     * TODO: Fetching "$" from peers with type restrictions will only return their covered
1436
     * types, not all types. To get full coverage, we'd need to fetch per-type from such peers.
1437
     * Additionally, checksum-based skip-ahead won't work correctly against such peers, because
1438
     * their "$" list has different checksums due to the differing type subset. This means full
1439
     * re-downloads on every cycle. Per-type fetching would solve both issues.
1440
     */
1441
    private static java.util.List<String> getLoadTypeHashes(ClientSession s, String pubkeyHash) {
1442
        if (CoverageFilter.coversAllTypes()) {
×
1443
            return java.util.List.of("$");
×
1444
        }
1445
        return java.util.List.copyOf(CoverageFilter.getCoveredTypeHashes());
×
1446
    }
1447

1448
    // TODO Move these to setting:
1449
    private static final int MAX_TRUST_PATH_DEPTH = 10;
1450
    private static final double MIN_TRUST_PATH_RATIO = 0.0000000001;
1451
    //private static final double MIN_TRUST_PATH_RATIO = 0.01; // For testing
1452
    private static final int GLOBAL_QUOTA = Integer.parseInt(
12 ✔
1453
            Utils.getEnv("REGISTRY_GLOBAL_QUOTA", "1000000000"));
3 ✔
1454
    private static final int MIN_USER_QUOTA = Integer.parseInt(
12 ✔
1455
            Utils.getEnv("REGISTRY_MIN_USER_QUOTA", "1000"));
3 ✔
1456
    private static final int MAX_USER_QUOTA = Integer.parseInt(
12 ✔
1457
            Utils.getEnv("REGISTRY_MAX_USER_QUOTA", "100000"));
3 ✔
1458

1459
    private static MongoCollection<Document> tasksCollection = collection(Collection.TASKS.toString());
12 ✔
1460

1461
    /**
1462
     * The tasks that make up one trust-state cycle, from building the staging collections to
1463
     * promoting them to their live names.
1464
     *
1465
     * @see #recoverInterruptedCycle
1466
     */
1467
    private static final Set<Task> TRUST_CYCLE_TASKS = EnumSet.of(
159 ✔
1468
            INIT_COLLECTIONS, SEED_TRUST_STATE, LOAD_DECLARATIONS, EXPAND_TRUST_PATHS, LOAD_CORE,
1469
            FINISH_ITERATION, CALCULATE_TRUST_SCORES, AGGREGATE_AGENTS, ASSIGN_PUBKEYS,
1470
            DETERMINE_UPDATES, FINALIZE_TRUST_STATE, RELEASE_DATA, PUBLISH_TRUST_STATE);
1471

1472
    /**
1473
     * The tail of a trust-state cycle: the computation is finished by the time these run, and both
1474
     * are idempotent, so an interrupted cycle that has reached them is left to finish rather than
1475
     * recomputed.
1476
     *
1477
     * @see #recoverInterruptedCycle
1478
     */
1479
    private static final Set<Task> TRUST_CYCLE_TAIL_TASKS = EnumSet.of(RELEASE_DATA, PUBLISH_TRUST_STATE);
15 ✔
1480

1481
    private static volatile String currentTaskName;
1482
    private static volatile long currentTaskStartTime;
1483

1484
    public static String getCurrentTaskName() {
1485
        return currentTaskName;
×
1486
    }
1487

1488
    public static long getCurrentTaskStartTime() {
1489
        return currentTaskStartTime;
×
1490
    }
1491

1492
    /**
1493
     * Restarts a trust-state cycle that a shutdown interrupted, so the registry can recover on its
1494
     * own (issue #50).
1495
     *
1496
     * <p>Task writes are not atomic with the removal of the task from the queue, so a task that was
1497
     * running when the process died is picked up again on restart and re-executes writes it already
1498
     * performed. For most of the cycle that is harmless — the tasks pick their work by entry status
1499
     * — but the unconditional inserts in {@link #INIT_COLLECTIONS} then fail on duplicate keys, and
1500
     * that task retries forever without ever getting past them. A crash can also leave both a task
1501
     * and the successor it scheduled in the queue, making the rest of the cycle run twice.
1502
     *
1503
     * <p>Rather than resuming a half-built cycle, we therefore restart it: the queued cycle tasks
1504
     * are dropped and a fresh {@link #INIT_COLLECTIONS} is scheduled, which discards the staging
1505
     * collections and rebuilds them. This costs one recomputation and nothing else — the staging
1506
     * collections only become live at the end of the cycle, so the trust state currently served
1507
     * (status {@code updating}) is untouched.
1508
     *
1509
     * <p>The exception is a queued tail task ({@link #TRUST_CYCLE_TAIL_TASKS}): the computation is
1510
     * then complete and both tail tasks are idempotent by design, so they are kept and left to
1511
     * finish rather than recomputed. Their siblings are still dropped, so a duplicate predecessor
1512
     * cannot run the cycle a second time.
1513
     *
1514
     * @param mongoSession the MongoDB client session
1515
     */
1516
    static void recoverInterruptedCycle(ClientSession mongoSession) {
1517
        Object statusValue = getValue(mongoSession, Collection.SERVER_INFO.toString(), "status");
18 ✔
1518
        if (statusValue == null) {
6 ✔
1519
            return;
3 ✔
1520
        }
1521
        ServerStatus status = ServerStatus.valueOf(statusValue.toString());
12 ✔
1522
        if (status != coreLoading && status != updating) {
18 ✔
1523
            // No cycle was in progress; if one is due, a queued UPDATE starts it from scratch.
1524
            logger.debug("Server status is {}; no interrupted trust-state cycle to recover", status);
12 ✔
1525
            return;
3 ✔
1526
        }
1527

1528
        List<String> tailNames = TRUST_CYCLE_TAIL_TASKS.stream().map(Task::name).toList();
18 ✔
1529
        boolean releasePending = tasksCollection.find(mongoSession, in("action", tailNames)).first() != null;
36 ✔
1530
        List<String> obsolete = TRUST_CYCLE_TASKS.stream()
12 ✔
1531
                .filter(task -> !releasePending || !TRUST_CYCLE_TAIL_TASKS.contains(task))
36 ✔
1532
                .map(Task::name)
3 ✔
1533
                .toList();
6 ✔
1534
        long removed = tasksCollection.deleteMany(mongoSession, in("action", obsolete)).getDeletedCount();
24 ✔
1535

1536
        if (releasePending) {
6 ✔
1537
            logger.info("Recovering trust-state cycle interrupted in status {}: dropped {} queued task(s), letting the pending tail task(s) {} finish the cycle",
39 ✔
1538
                    status, removed, tailNames);
18 ✔
1539
        } else {
1540
            logger.info("Recovering trust-state cycle interrupted in status {}: dropped {} queued task(s), restarting the cycle at {}",
36 ✔
1541
                    status, removed, INIT_COLLECTIONS.name());
21 ✔
1542
            schedule(mongoSession, INIT_COLLECTIONS);
9 ✔
1543
        }
1544
    }
3 ✔
1545

1546
    /**
1547
     * The super important base entry point!
1548
     */
1549
    static void runTasks() {
1550
        try (ClientSession s = RegistryDB.getClient().startSession()) {
×
1551
            if (!RegistryDB.isInitialized(s)) {
×
1552
                schedule(s, INIT_DB); // does not yet execute, only schedules
×
1553
            } else {
1554
                recoverInterruptedCycle(s);
×
1555
            }
1556

1557
            logger.info("Task runner started");
×
1558
            while (true) {
1559
                FindIterable<Document> taskResult = tasksCollection.find(s).sort(ascending("not-before"));
×
1560
                Document taskDoc = taskResult.first();
×
1561
                long sleepTime = 10;
×
1562
                if (taskDoc != null && taskDoc.getLong("not-before") < System.currentTimeMillis()) {
×
1563
                    Task task = valueOf(taskDoc.getString("action"));
×
1564
                    Object taskId = taskDoc.getOrDefault("_id", null);
×
1565
                    logger.info("Picked task to run: {} (docId={})", task.name(), taskId);
×
1566

1567
                    if (task.runAsTransaction()) {
×
1568
                        try {
1569
                            s.startTransaction();
×
1570
                            logger.debug("Transaction started for task {}", task.name());
×
1571
                            runTask(s, task, taskDoc);
×
1572
                            s.commitTransaction();
×
1573
                            logger.info("Transaction committed for task {}", task.name());
×
1574
                        } catch (Exception ex) {
×
1575
                            logger.warn("Transactional task {} failed, aborting: {}", task.name(), ex.getMessage(), ex);
×
1576
                            abortTransaction(s, ex.getMessage());
×
1577
                            logger.info("Transaction aborted for task {}", task.name());
×
1578
                            sleepTime = 1000;
×
1579
                        } finally {
1580
                            cleanTransactionWithRetry(s);
×
1581
                        }
×
1582
                    } else {
1583
                        try {
1584
                            runTask(s, task, taskDoc);
×
1585
                        } catch (Exception ex) {
×
1586
                            logger.warn("Non-transactional task {} failed: {}", task.name(), ex.getMessage(), ex);
×
1587
                        }
×
1588
                    }
1589
                }
1590
                try {
1591
                    Thread.sleep(sleepTime);
×
1592
                } catch (InterruptedException ex) {
×
1593
                    // ignore
1594
                    logger.debug("Task runner sleep interrupted");
×
1595
                }
×
1596
            }
×
1597
        }
1598
    }
1599

1600
    /**
1601
     * Runs a single task on the given session.
1602
     *
1603
     * <p>The session belongs to the caller and carries the transaction, if any: for a task with
1604
     * {@link #runAsTransaction()}, {@link #runTasks} has already called
1605
     * {@code startTransaction()} on it, so the task's writes and the removal of the task from the
1606
     * queue below both join that transaction and commit together. Opening a session here instead
1607
     * would silently place both outside it (issue #128).
1608
     *
1609
     * @param s       the session to run on, with an active transaction for transactional tasks
1610
     * @param task    the task to run
1611
     * @param taskDoc the queue document describing this invocation
1612
     */
1613
    static void runTask(ClientSession s, Task task, Document taskDoc) throws Exception {
1614
        currentTaskName = task.name();
9 ✔
1615
        currentTaskStartTime = System.currentTimeMillis();
6 ✔
1616
        logger.info("Starting task {} with request: {}", currentTaskName, taskDoc);
15 ✔
1617

1618
        try {
1619
            task.run(s, taskDoc);
12 ✔
1620
            long duration = System.currentTimeMillis() - currentTaskStartTime;
12 ✔
1621
            tasksCollection.deleteOne(s, eq("_id", taskDoc.get("_id")));
27 ✔
1622
            logger.info("Completed and removed from queue task {} in {} ms", currentTaskName, duration);
18 ✔
1623
        } catch (Exception ex) {
×
1624
            long duration = System.currentTimeMillis() - currentTaskStartTime;
×
1625
            logger.error("Task {} failed after {} ms: {}", currentTaskName, duration, ex.getMessage(), ex);
×
1626
            throw ex;
×
1627
        } finally {
1628
            currentTaskName = null;
6 ✔
1629
        }
1630
    }
3 ✔
1631

1632
    public static void abortTransaction(ClientSession mongoSession, String message) {
1633
        boolean successful = false;
×
1634
        while (!successful) {
×
1635
            try {
1636
                if (mongoSession.hasActiveTransaction()) {
×
1637
                    logger.info("Attempting to abort transaction: {}", message);
×
1638
                    mongoSession.abortTransaction();
×
1639
                }
1640
                successful = true;
×
1641
                logger.debug("abortTransaction succeeded");
×
1642
            } catch (Exception ex) {
×
1643
                logger.warn("abortTransaction attempt failed: {}", ex.getMessage(), ex);
×
1644
                try {
1645
                    Thread.sleep(100);
×
1646
                } catch (InterruptedException ie) {
×
1647
                    logger.debug("abortTransaction sleep interrupted");
×
1648
                }
×
1649
            }
×
1650
        }
1651
    }
×
1652

1653
    public synchronized static void cleanTransactionWithRetry(ClientSession mongoSession) {
1654
        boolean successful = false;
×
1655
        while (!successful) {
×
1656
            try {
1657
                if (mongoSession.hasActiveTransaction()) {
×
1658
                    mongoSession.abortTransaction();
×
1659
                    logger.debug("abortTransaction during cleanup succeeded");
×
1660
                }
1661
                successful = true;
×
1662
                logger.debug("Transaction cleanup completed");
×
1663
            } catch (Exception ex) {
×
1664
                logger.warn("Transaction cleanup failed: {}", ex.getMessage(), ex);
×
1665
                try {
1666
                    Thread.sleep(100);
×
1667
                } catch (InterruptedException ie) {
×
1668
                    logger.debug("cleanTransactionWithRetry sleep interrupted");
×
1669
                }
×
1670
            }
×
1671
        }
1672
    }
×
1673

1674
    private static IntroNanopub getAgentIntro(ClientSession mongoSession, String nanopubId) {
1675
        IntroNanopub agentIntro = new IntroNanopub(NanopubLoader.retrieveNanopub(mongoSession, nanopubId));
×
1676
        if (agentIntro.getUser() == null) {
×
1677
            logger.debug("Nanopub {} is not a valid agent intro (no declared user); discarding", nanopubId);
×
1678
            return null;
×
1679
        }
1680
        loadNanopub(mongoSession, agentIntro.getNanopub());
×
1681
        return agentIntro;
×
1682
    }
1683

1684

1685
    private static void setServerStatus(ClientSession mongoSession, ServerStatus status) {
1686
        setValue(mongoSession, Collection.SERVER_INFO.toString(), "status", status.toString());
21 ✔
1687
    }
3 ✔
1688

1689
    private static ServerStatus getServerStatus(ClientSession mongoSession) {
1690
        Object status = getValue(mongoSession, Collection.SERVER_INFO.toString(), "status");
18 ✔
1691
        if (status == null) {
6 !
1692
            throw new RuntimeException("Illegal DB state: serverInfo status unavailable");
×
1693
        }
1694
        return ServerStatus.valueOf(status.toString());
12 ✔
1695
    }
1696

1697
    private static void schedule(ClientSession mongoSession, Task task) {
1698
        schedule(mongoSession, task.asDocument());
12 ✔
1699
    }
3 ✔
1700

1701
    private static void schedule(ClientSession mongoSession, Document taskDoc) {
1702
        logger.info("Scheduling task: {}", taskDoc.getString("action"));
18 ✔
1703
        tasksCollection.insertOne(mongoSession, taskDoc);
12 ✔
1704
    }
3 ✔
1705

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

© 2026 Coveralls, Inc