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

knowledgepixels / nanopub-query / 31587675387

12 Aug 2026 10:29AM UTC coverage: 76.024% (+0.05%) from 75.976%
31587675387

push

github

web-flow
Merge pull request #183 from knowledgepixels/fix/drop-serializable-rdf4j6

Drop SERIALIZABLE isolation + upgrade RDF4J server to 6.0.0

818 of 1222 branches covered (66.94%)

Branch coverage included in aggregate %.

2413 of 3028 relevant lines covered (79.69%)

12.46 hits per line

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

87.72
src/main/java/com/knowledgepixels/query/StatusController.java
1
package com.knowledgepixels.query;
2

3
import org.eclipse.rdf4j.common.transaction.IsolationLevels;
4
import org.eclipse.rdf4j.model.IRI;
5
import org.eclipse.rdf4j.model.Literal;
6
import org.eclipse.rdf4j.model.ValueFactory;
7
import org.eclipse.rdf4j.model.impl.SimpleValueFactory;
8
import org.eclipse.rdf4j.repository.RepositoryConnection;
9
import org.nanopub.vocabulary.NPA;
10

11
import java.util.Objects;
12

13
/**
14
 * Class to control the load status of the database.
15
 */
16
public class StatusController {
6 ✔
17

18
    /**
19
     * The load states in which the database can be.
20
     */
21
    public enum State {
9 ✔
22
        /**
23
         * The service is launching.
24
         */
25
        LAUNCHING,
18 ✔
26
        /**
27
         * The service is loading.
28
         */
29
        LOADING_INITIAL,
18 ✔
30
        /**
31
         * The service is loading updates.
32
         */
33
        LOADING_UPDATES,
18 ✔
34
        /**
35
         * The service is ready to serve requests.
36
         */
37
        READY,
18 ✔
38
        /**
39
         * The service detected a registry reset and is about to resync.
40
         */
41
        RESETTING,
18 ✔
42
    }
43

44
    /**
45
     * Get the singleton instance of the StatusController.
46
     *
47
     * @return the StatusController instance
48
     */
49
    public static StatusController get() {
50
        return instance;
6 ✔
51
    }
52

53
    private final static StatusController instance = new StatusController();
12 ✔
54

55
    static final IRI HAS_REGISTRY_SETUP_ID =
56
            SimpleValueFactory.getInstance().createIRI(NPA.NAMESPACE, "hasRegistrySetupId");
15 ✔
57

58
    private static final ValueFactory vf = SimpleValueFactory.getInstance();
9 ✔
59

60
    private boolean initialized = false;
9 ✔
61
    private volatile State state = null;
9 ✔
62
    private volatile long lastCommittedCounter = -1;
9 ✔
63
    private volatile Long registrySetupId = null;
12 ✔
64

65
    /**
66
     * Opens a fresh admin-repo connection for a single transaction.
67
     *
68
     * <p>This class used to hold one connection for the lifetime of the process,
69
     * assigned once in {@link #initialize()} and never re-acquired. An RDF4J restart
70
     * — which the {@code rdf4j} healthcheck performs by design when its probes fail —
71
     * orphaned that connection permanently: every subsequent admin-repo write threw,
72
     * so {@code setLoadingUpdates} failed before {@code loadBatch} could run and the
73
     * instance ingested nothing until the query container itself was restarted.
74
     * RDF4J recovering on its own was not enough. Acquiring per transaction means a
75
     * restart costs one failed tick instead of wedging the loader (incident
76
     * 2026-07-31, query.knowledgepixels.com).
77
     *
78
     * <p>Cheap enough to do per call: {@code getConnection()} on an
79
     * {@code HTTPRepository} is local and does no HTTP, as
80
     * {@link TripleStore#getRepoConnection(String)} notes. Every other admin-repo
81
     * caller in the codebase already works this way.
82
     *
83
     * @return a new connection the caller must close
84
     */
85
    private static RepositoryConnection openAdminConnection() {
86
        return TripleStore.get().getAdminRepoConnection();
9 ✔
87
    }
88

89
    /**
90
     * Rolls back an active transaction, suppressing any failure to do so.
91
     *
92
     * <p>The transaction may no longer exist server-side (already committed, timed
93
     * out, or lost to a restart), and that secondary failure must not mask the
94
     * original one.
95
     *
96
     * @param conn the connection whose transaction should be rolled back
97
     */
98
    private static void rollbackQuietly(RepositoryConnection conn) {
99
        try {
100
            if (conn.isActive()) {
9 !
101
                conn.rollback();
×
102
            }
103
        } catch (Exception rollbackException) {
×
104
            // Deliberately ignored; the caller rethrows the original cause.
105
        }
3 ✔
106
    }
3 ✔
107

108
    /**
109
     * Represents the current status of the service, including the load counter.
110
     */
111
    public static class LoadingStatus {
112

113
        /**
114
         * The current state of the service.
115
         */
116
        public final State state;
117

118
        /**
119
         * The current load counter.
120
         */
121
        public final long loadCounter;
122

123
        private LoadingStatus(State state, long loadCounter) {
6 ✔
124
            this.state = state;
9 ✔
125
            this.loadCounter = loadCounter;
9 ✔
126
        }
3 ✔
127

128
        /**
129
         * Create a new LoadingStatus instance.
130
         *
131
         * @param state       the current state of the service
132
         * @param loadCounter the current load counter
133
         * @return a new LoadingStatus instance
134
         */
135
        public static LoadingStatus of(State state, long loadCounter) {
136
            return new LoadingStatus(state, loadCounter);
18 ✔
137
        }
138

139
        @Override
140
        public boolean equals(Object o) {
141
            if (o == null || getClass() != o.getClass()) {
21 ✔
142
                return false;
6 ✔
143
            }
144
            LoadingStatus that = (LoadingStatus) o;
9 ✔
145
            return loadCounter == that.loadCounter && state == that.state;
45 ✔
146
        }
147

148
        @Override
149
        public int hashCode() {
150
            return Objects.hash(state, loadCounter);
45 ✔
151
        }
152

153
    }
154

155
    /**
156
     * Initialize the StatusController, fetching the last known state from the DB.
157
     * This must be called right after service startup, before loading any nanopubs.
158
     *
159
     * @return the current state and the last committed counter
160
     */
161
    public LoadingStatus initialize() {
162
        synchronized (this) {
12 ✔
163
            if (initialized) {
9 ✔
164
                throw new IllegalStateException("Already initialized");
15 ✔
165
            }
166
            state = State.LAUNCHING;
9 ✔
167
            try (RepositoryConnection conn = openAdminConnection()) {
6 ✔
168
                try {
169
                    // This singleton's synchronized methods are the only writer of these
170
                    // triples, so SNAPSHOT already gives strict consistency; see
171
                    // NanopubLoader#repoWriteLocks for why SERIALIZABLE is avoided.
172
                    conn.begin(IsolationLevels.SNAPSHOT);
9 ✔
173
                    // Fetch the state from the DB
174
                    try (var statements = conn.getStatements(NPA.THIS_REPO, NPA.HAS_STATUS, null, NPA.GRAPH)) {
36 ✔
175
                        if (!statements.hasNext()) {
9 !
176
                            conn.add(NPA.THIS_REPO, NPA.HAS_STATUS, stateAsLiteral(state), NPA.GRAPH);
45 ✔
177
                        } else {
178
                            var stateStatement = statements.next();
×
179
                            state = State.valueOf(stateStatement.getObject().stringValue());
×
180
                        }
181
                    }
182
                    // Fetch the load counter from the DB
183
                    try (var statements = conn.getStatements(NPA.THIS_REPO, NPA.HAS_REGISTRY_LOAD_COUNTER, null, NPA.GRAPH)) {
36 ✔
184
                        if (!statements.hasNext()) {
9 !
185
                            conn.add(NPA.THIS_REPO, NPA.HAS_REGISTRY_LOAD_COUNTER, vf.createLiteral(-1L), NPA.GRAPH);
42 ✔
186
                        } else {
187
                            var counterStatement = statements.next();
×
188
                            var stringVal = counterStatement.getObject().stringValue();
×
189
                            lastCommittedCounter = Long.parseLong(stringVal);
×
190
                        }
191
                    }
192
                    // Fetch the registry setup ID from the DB
193
                    try (var statements = conn.getStatements(NPA.THIS_REPO, HAS_REGISTRY_SETUP_ID, null, NPA.GRAPH)) {
36 ✔
194
                        if (statements.hasNext()) {
9 !
195
                            var setupIdStatement = statements.next();
×
196
                            registrySetupId = Long.parseLong(setupIdStatement.getObject().stringValue());
×
197
                        }
198
                    }
199
                    conn.commit();
6 ✔
200
                } catch (Exception e) {
×
201
                    rollbackQuietly(conn);
×
202
                    throw new RuntimeException(e);
×
203
                }
3 ✔
204
            }
205
            initialized = true;
9 ✔
206
            return getState();
15 ✔
207
        }
208
    }
209

210
    /**
211
     * Get the current state of the service.
212
     *
213
     * @return the current state and the last committed counter
214
     */
215
    public LoadingStatus getState() {
216
        return LoadingStatus.of(state, lastCommittedCounter);
18 ✔
217
    }
218

219
    /**
220
     * Transition the service to the LOADING_INITIAL state and update the load counter.
221
     * This should be called in two situations:
222
     * - By the main loading thread (after calling initialize()) to start loading the initial nanopubs.
223
     * - By the initial nanopub loader, as it processes the initial nanopubs.
224
     *
225
     * @param loadCounter the new load counter
226
     */
227
    public void setLoadingInitial(long loadCounter) {
228
        synchronized (this) {
12 ✔
229
            if (state != State.LAUNCHING && state != State.LOADING_INITIAL && state != State.RESETTING) {
36 ✔
230
                throw new IllegalStateException("Cannot transition to LOADING_INITIAL, as the " + "current state is " + state);
24 ✔
231
            }
232
            if (state != State.RESETTING && lastCommittedCounter > loadCounter) {
27 ✔
233
                throw new IllegalStateException("Cannot update the load counter from " + lastCommittedCounter + " to " + loadCounter);
24 ✔
234
            }
235
            updateState(State.LOADING_INITIAL, loadCounter);
12 ✔
236
        }
9 ✔
237
    }
3 ✔
238

239
    /**
240
     * Transition the service to the LOADING_UPDATES state and update the load counter.
241
     * This should be called by the updates loader, when it starts processing new nanopubs, or
242
     * when it finishes processing a batch of nanopubs.
243
     *
244
     * @param loadCounter the new load counter
245
     */
246
    public void setLoadingUpdates(long loadCounter) {
247
        synchronized (this) {
12 ✔
248
            if (state != State.LAUNCHING && state != State.LOADING_UPDATES && state != State.READY) {
36 ✔
249
                throw new IllegalStateException("Cannot transition to LOADING_UPDATES, as the " + "current state is " + state);
24 ✔
250
            }
251
            if (lastCommittedCounter > loadCounter) {
15 ✔
252
                throw new IllegalStateException("Cannot update the load counter from " + lastCommittedCounter + " to " + loadCounter);
24 ✔
253
            }
254
            // Idempotence guard: skip the admin-repo rewrite if the state and counter
255
            // are already where we'd set them. A no-op loop iteration of the updates
256
            // loader otherwise re-writes the same two triples hundreds of times an
257
            // hour over a long idle tail, each write growing the admin-repo LMDB via
258
            // copy-on-write.
259
            if (state == State.LOADING_UPDATES && lastCommittedCounter == loadCounter) {
27 !
260
                return;
×
261
            }
262
            updateState(State.LOADING_UPDATES, loadCounter);
12 ✔
263
        }
9 ✔
264
    }
3 ✔
265

266
    /**
267
     * Transition the service to the READY state.
268
     * This should be called by the loaders, after they finish their work.
269
     */
270
    public void setReady() {
271
        synchronized (this) {
12 ✔
272
            if (state != State.READY) {
12 ✔
273
                updateState(State.READY, lastCommittedCounter);
15 ✔
274
            }
275
        }
9 ✔
276
    }
3 ✔
277

278
    /**
279
     * Transition the service to the RESETTING state, resetting the load counter to -1.
280
     * This is triggered when a registry reset is detected (setupId changed or counter decreased),
281
     * or when FORCE_RESYNC is set on startup. Accepts any post-initialize source state:
282
     * a reset discards prior load progress, so it's valid from LOADING_INITIAL (crashed mid-init),
283
     * LOADING_UPDATES, READY, or RESETTING (retry after a crashed prior reset).
284
     */
285
    public void setResetting() {
286
        synchronized (this) {
12 ✔
287
            if (state == State.LAUNCHING) {
12 ✔
288
                throw new IllegalStateException("Cannot transition to RESETTING, as the " + "current state is " + state);
24 ✔
289
            }
290
            updateState(State.RESETTING, -1);
12 ✔
291
        }
9 ✔
292
    }
3 ✔
293

294
    /**
295
     * Get the persisted registry setup ID.
296
     *
297
     * @return the registry setup ID, or null if not yet known
298
     */
299
    public Long getRegistrySetupId() {
300
        // Lock-free read: field is volatile, writers still hold synchronized(this)
301
        // so there are no concurrent writers. applyGlobalHeaders in MainVerticle
302
        // calls this on every inbound request on the Vert.x event loop — blocking
303
        // here behind updateState's admin-repo transaction was a BlockedThreadChecker
304
        // hazard. The DB-commit-first order in the setter (setRegistrySetupId)
305
        // means a reader can observe the previous value for the few ms between DB
306
        // commit and field assignment; no caller depends on stronger consistency.
307
        return registrySetupId;
9 ✔
308
    }
309

310
    /**
311
     * Persist a new registry setup ID to the admin repo.
312
     *
313
     * @param setupId the new setup ID
314
     */
315
    public void setRegistrySetupId(long setupId) {
316
        synchronized (this) {
12 ✔
317
            try (RepositoryConnection conn = openAdminConnection()) {
6 ✔
318
                try {
319
                    conn.begin(IsolationLevels.SNAPSHOT);
9 ✔
320
                    conn.remove(NPA.THIS_REPO, HAS_REGISTRY_SETUP_ID, null, NPA.GRAPH);
33 ✔
321
                    conn.add(NPA.THIS_REPO, HAS_REGISTRY_SETUP_ID, vf.createLiteral(setupId), NPA.GRAPH);
39 ✔
322
                    conn.commit();
6 ✔
323
                    registrySetupId = setupId;
12 ✔
324
                } catch (Exception e) {
×
325
                    rollbackQuietly(conn);
×
326
                    throw new RuntimeException(e);
×
327
                }
3 ✔
328
            }
329
        }
9 ✔
330
    }
3 ✔
331

332
    /**
333
     * Persist a state transition, then adopt it in memory.
334
     *
335
     * <p>The in-memory fields are assigned only after the admin-repo commit succeeds,
336
     * mirroring {@link #setRegistrySetupId(long)}. The earlier order (assign first,
337
     * commit second) left the two permanently divergent whenever the commit threw,
338
     * because nothing rolled the fields back: the loader would then read a
339
     * {@code lastCommittedCounter} ahead of the persisted one, conclude from
340
     * {@code lastCommittedCounter >= targetCounter} that it was caught up, and skip
341
     * those nanopubs forever while still reporting READY.
342
     *
343
     * <p>Readers may observe the previous state for the few ms of the commit — the
344
     * same window {@link #getRegistrySetupId()} already documents, and no caller
345
     * depends on stronger consistency. If a commit lands server-side but the response
346
     * is lost, the fields stay behind the DB instead of ahead of it; the next
347
     * transition re-writes the same triples (the remove/add pair is idempotent), so
348
     * that direction costs at most some re-processing rather than silent data loss.
349
     *
350
     * @param newState    the state to transition to
351
     * @param loadCounter the load counter to persist alongside it
352
     */
353
    void updateState(State newState, long loadCounter) {
354
        synchronized (this) {
12 ✔
355
            try (RepositoryConnection conn = openAdminConnection()) {
6 ✔
356
                try {
357
                    // This singleton's synchronized methods are the only writer of these
358
                    // triples, so SNAPSHOT already gives strict consistency; see
359
                    // NanopubLoader#repoWriteLocks for why SERIALIZABLE is avoided.
360
                    conn.begin(IsolationLevels.SNAPSHOT);
9 ✔
361
                    conn.remove(NPA.THIS_REPO, NPA.HAS_STATUS, null, NPA.GRAPH);
33 ✔
362
                    conn.add(NPA.THIS_REPO, NPA.HAS_STATUS, stateAsLiteral(newState), NPA.GRAPH);
39 ✔
363
                    conn.remove(NPA.THIS_REPO, NPA.HAS_REGISTRY_LOAD_COUNTER, null, NPA.GRAPH);
33 ✔
364
                    conn.add(NPA.THIS_REPO, NPA.HAS_REGISTRY_LOAD_COUNTER, vf.createLiteral(loadCounter), NPA.GRAPH);
39 ✔
365
                    conn.commit();
6 ✔
366
                    state = newState;
9 ✔
367
                    lastCommittedCounter = loadCounter;
9 ✔
368
                } catch (Exception e) {
3 ✔
369
                    rollbackQuietly(conn);
6 ✔
370
                    throw new RuntimeException(e);
15 ✔
371
                }
3 ✔
372
            }
373
        }
9 ✔
374
    }
3 ✔
375

376
    private Literal stateAsLiteral(State s) {
377
        return vf.createLiteral(s.toString());
15 ✔
378
    }
379

380
    /**
381
     * Reset the StatusController for testing purposes.
382
     * This will clear the state and allow re-initialization.
383
     */
384
    void resetForTest() {
385
        synchronized (this) {
12 ✔
386
            initialized = false;
9 ✔
387
            state = null;
9 ✔
388
            lastCommittedCounter = -1;
9 ✔
389
            registrySetupId = null;
9 ✔
390
        }
9 ✔
391
    }
3 ✔
392

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