@origintrail-official/dkg-storage 10.0.12 → 10.0.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE CHANGED
@@ -1,201 +1,201 @@
1
- Apache License
2
- Version 2.0, January 2004
3
- http://www.apache.org/licenses/
4
-
5
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
-
7
- 1. Definitions.
8
-
9
- "License" shall mean the terms and conditions for use, reproduction,
10
- and distribution as defined by Sections 1 through 9 of this document.
11
-
12
- "Licensor" shall mean the copyright owner or entity authorized by
13
- the copyright owner that is granting the License.
14
-
15
- "Legal Entity" shall mean the union of the acting entity and all
16
- other entities that control, are controlled by, or are under common
17
- control with that entity. For the purposes of this definition,
18
- "control" means (i) the power, direct or indirect, to cause the
19
- direction or management of such entity, whether by contract or
20
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
- outstanding shares, or (iii) beneficial ownership of such entity.
22
-
23
- "You" (or "Your") shall mean an individual or Legal Entity
24
- exercising permissions granted by this License.
25
-
26
- "Source" form shall mean the preferred form for making modifications,
27
- including but not limited to software source code, documentation
28
- source, and configuration files.
29
-
30
- "Object" form shall mean any form resulting from mechanical
31
- transformation or translation of a Source form, including but
32
- not limited to compiled object code, generated documentation,
33
- and conversions to other media types.
34
-
35
- "Work" shall mean the work of authorship, whether in Source or
36
- Object form, made available under the License, as indicated by a
37
- copyright notice that is included in or attached to the work
38
- (an example is provided in the Appendix below).
39
-
40
- "Derivative Works" shall mean any work, whether in Source or Object
41
- form, that is based on (or derived from) the Work and for which the
42
- editorial revisions, annotations, elaborations, or other modifications
43
- represent, as a whole, an original work of authorship. For the purposes
44
- of this License, Derivative Works shall not include works that remain
45
- separable from, or merely link (or bind by name) to the interfaces of,
46
- the Work and Derivative Works thereof.
47
-
48
- "Contribution" shall mean any work of authorship, including
49
- the original version of the Work and any modifications or additions
50
- to that Work or Derivative Works thereof, that is intentionally
51
- submitted to Licensor for inclusion in the Work by the copyright owner
52
- or by an individual or Legal Entity authorized to submit on behalf of
53
- the copyright owner. For the purposes of this definition, "submitted"
54
- means any form of electronic, verbal, or written communication sent
55
- to the Licensor or its representatives, including but not limited to
56
- communication on electronic mailing lists, source code control systems,
57
- and issue tracking systems that are managed by, or on behalf of, the
58
- Licensor for the purpose of discussing and improving the Work, but
59
- excluding communication that is conspicuously marked or otherwise
60
- designated in writing by the copyright owner as "Not a Contribution."
61
-
62
- "Contributor" shall mean Licensor and any individual or Legal Entity
63
- on behalf of whom a Contribution has been received by Licensor and
64
- subsequently incorporated within the Work.
65
-
66
- 2. Grant of Copyright License. Subject to the terms and conditions of
67
- this License, each Contributor hereby grants to You a perpetual,
68
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
- copyright license to reproduce, prepare Derivative Works of,
70
- publicly display, publicly perform, sublicense, and distribute the
71
- Work and such Derivative Works in Source or Object form.
72
-
73
- 3. Grant of Patent License. Subject to the terms and conditions of
74
- this License, each Contributor hereby grants to You a perpetual,
75
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
- (except as stated in this section) patent license to make, have made,
77
- use, offer to sell, sell, import, and otherwise transfer the Work,
78
- where such license applies only to those patent claims licensable
79
- by such Contributor that are necessarily infringed by their
80
- Contribution(s) alone or by combination of their Contribution(s)
81
- with the Work to which such Contribution(s) was submitted. If You
82
- institute patent litigation against any entity (including a
83
- cross-claim or counterclaim in a lawsuit) alleging that the Work
84
- or a Contribution incorporated within the Work constitutes direct
85
- or contributory patent infringement, then any patent licenses
86
- granted to You under this License for that Work shall terminate
87
- as of the date such litigation is filed.
88
-
89
- 4. Redistribution. You may reproduce and distribute copies of the
90
- Work or Derivative Works thereof in any medium, with or without
91
- modifications, and in Source or Object form, provided that You
92
- meet the following conditions:
93
-
94
- (a) You must give any other recipients of the Work or
95
- Derivative Works a copy of this License; and
96
-
97
- (b) You must cause any modified files to carry prominent notices
98
- stating that You changed the files; and
99
-
100
- (c) You must retain, in the Source form of any Derivative Works
101
- that You distribute, all copyright, patent, trademark, and
102
- attribution notices from the Source form of the Work,
103
- excluding those notices that do not pertain to any part of
104
- the Derivative Works; and
105
-
106
- (d) If the Work includes a "NOTICE" text file as part of its
107
- distribution, then any Derivative Works that You distribute must
108
- include a readable copy of the attribution notices contained
109
- within such NOTICE file, excluding those notices that do not
110
- pertain to any part of the Derivative Works, in at least one
111
- of the following places: within a NOTICE text file distributed
112
- as part of the Derivative Works; within the Source form or
113
- documentation, if provided along with the Derivative Works; or,
114
- within a display generated by the Derivative Works, if and
115
- wherever such third-party notices normally appear. The contents
116
- of the NOTICE file are for informational purposes only and
117
- do not modify the License. You may add Your own attribution
118
- notices within Derivative Works that You distribute, alongside
119
- or as an addendum to the NOTICE text from the Work, provided
120
- that such additional attribution notices cannot be construed
121
- as modifying the License.
122
-
123
- You may add Your own copyright statement to Your modifications and
124
- may provide additional or different license terms and conditions
125
- for use, reproduction, or distribution of Your modifications, or
126
- for any such Derivative Works as a whole, provided Your use,
127
- reproduction, and distribution of the Work otherwise complies with
128
- the conditions stated in this License.
129
-
130
- 5. Submission of Contributions. Unless You explicitly state otherwise,
131
- any Contribution intentionally submitted for inclusion in the Work
132
- by You to the Licensor shall be under the terms and conditions of
133
- this License, without any additional terms or conditions.
134
- Notwithstanding the above, nothing herein shall supersede or modify
135
- the terms of any separate license agreement you may have executed
136
- with Licensor regarding such Contributions.
137
-
138
- 6. Trademarks. This License does not grant permission to use the trade
139
- names, trademarks, service marks, or product names of the Licensor,
140
- except as required for reasonable and customary use in describing the
141
- origin of the Work and reproducing the content of the NOTICE file.
142
-
143
- 7. Disclaimer of Warranty. Unless required by applicable law or
144
- agreed to in writing, Licensor provides the Work (and each
145
- Contributor provides its Contributions) on an "AS IS" BASIS,
146
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
- implied, including, without limitation, any warranties or conditions
148
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
- PARTICULAR PURPOSE. You are solely responsible for determining the
150
- appropriateness of using or redistributing the Work and assume any
151
- risks associated with Your exercise of permissions under this License.
152
-
153
- 8. Limitation of Liability. In no event and under no legal theory,
154
- whether in tort (including negligence), contract, or otherwise,
155
- unless required by applicable law (such as deliberate and grossly
156
- negligent acts) or agreed to in writing, shall any Contributor be
157
- liable to You for damages, including any direct, indirect, special,
158
- incidental, or consequential damages of any character arising as a
159
- result of this License or out of the use or inability to use the
160
- Work (including but not limited to damages for loss of goodwill,
161
- work stoppage, computer failure or malfunction, or any and all
162
- other commercial damages or losses), even if such Contributor
163
- has been advised of the possibility of such damages.
164
-
165
- 9. Accepting Warranty or Additional Liability. While redistributing
166
- the Work or Derivative Works thereof, You may choose to offer,
167
- and charge a fee for, acceptance of support, warranty, indemnity,
168
- or other liability obligations and/or rights consistent with this
169
- License. However, in accepting such obligations, You may act only
170
- on Your own behalf and on Your sole responsibility, not on behalf
171
- of any other Contributor, and only if You agree to indemnify,
172
- defend, and hold each Contributor harmless for any liability
173
- incurred by, or claims asserted against, such Contributor by reason
174
- of your accepting any such warranty or additional liability.
175
-
176
- END OF TERMS AND CONDITIONS
177
-
178
- APPENDIX: How to apply the Apache License to your work.
179
-
180
- To apply the Apache License to your work, attach the following
181
- boilerplate notice, with the fields enclosed by brackets "[]"
182
- replaced with your own identifying information. (Don't include
183
- the brackets!) The text should be enclosed in the appropriate
184
- comment syntax for the file format. We also recommend that a
185
- file or class name and description of purpose be included on the
186
- same "printed page" as the copyright notice for easier
187
- identification within third-party archives.
188
-
189
- Copyright 2018 OriginTrail
190
-
191
- Licensed under the Apache License, Version 2.0 (the "License");
192
- you may not use this file except in compliance with the License.
193
- You may obtain a copy of the License at
194
-
195
- http://www.apache.org/licenses/LICENSE-2.0
196
-
197
- Unless required by applicable law or agreed to in writing, software
198
- distributed under the License is distributed on an "AS IS" BASIS,
199
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
- See the License for the specific language governing permissions and
201
- limitations under the License.
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2018 OriginTrail
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,112 +1,112 @@
1
- # @origintrail-official/dkg-storage
2
-
3
- Triple store abstraction layer for DKG V10. Provides a unified API over multiple RDF storage backends with named graph management and private content storage.
4
-
5
- ## Features
6
-
7
- - **Backend adapters** — pluggable triple store implementations:
8
- - `OxigraphStore` — embedded WASM/native store, no external dependencies
9
- - `OxigraphWorkerStore` — worker-thread variant; keeps the daemon event loop free, with a per-read-operation timeout (see below)
10
- - `BlazegraphStore` — connects to a running Blazegraph SPARQL endpoint
11
- - `SparqlHttpStore` — generic adapter for any SPARQL 1.1 compliant endpoint
12
- - **Graph manager** — named graph lifecycle (create, drop, list) with contextGraph-scoped data and metadata graphs
13
- - **Private content store** — encrypted triple storage for private KA triples, separate from the public graph
14
- - **Custom adapters** — `registerTripleStoreAdapter()` to plug in any storage backend
15
-
16
- ## Usage
17
-
18
- ```typescript
19
- import { createTripleStore, GraphManager } from '@origintrail-official/dkg-storage';
20
-
21
- // In-memory store
22
- const memStore = await createTripleStore({ backend: 'oxigraph' });
23
-
24
- // Persistent store (requires a path)
25
- const store = await createTripleStore({
26
- backend: 'oxigraph-persistent',
27
- options: { path: './data' },
28
- });
29
-
30
- const graphs = new GraphManager(store);
31
-
32
- await store.insert(quads);
33
- const result = await store.query('SELECT * WHERE { ?s ?p ?o } LIMIT 10');
34
- ```
35
-
36
- ## Embedded worker store (`oxigraph-worker`) tuning
37
-
38
- The embedded worker runs **all** store operations on a single worker thread, so
39
- a long-running or stuck op (a huge import, an expensive query) blocks every
40
- other store-backed request behind it. Under real load this surfaces as the
41
- daemon's `/api/status` staying green while `/api/query`,
42
- `/api/context-graph/list`, and `/api/assertion/create` hang. A `store.options`
43
- knob bounds that blast radius:
44
-
45
- | Option | Default | Purpose |
46
- |---|---|---|
47
- | `operationTimeoutMs` | `120000` | Reject a **read-only** op (`query`, `hasGraph`, `listGraphs`, `countQuads`) that exceeds this instead of hanging forever — that's where the user-visible hang shows up. `0` disables (restores unbounded behaviour). `close` is exempt — its final flush always runs to completion so shutdown can't drop pending writes. |
48
-
49
- Mutations (`insert`, `delete`, …) are intentionally **not** bounded by this
50
- timeout. The bound only drops the *caller's* promise — the single worker thread
51
- keeps running the op — so a "timed-out" write could still commit afterwards,
52
- and the rest of the codebase treats a rejected `insert`/`delete` as a clean
53
- failure. Bounding only reads surfaces a wedged worker on the paths that hang
54
- without inventing an indeterminate write outcome. `insert()` therefore stays
55
- strictly atomic (all quads commit or the call fails), which callers rely on.
56
-
57
- ```jsonc
58
- // ~/.dkg/config.json
59
- "store": {
60
- "backend": "oxigraph-worker",
61
- "options": { "operationTimeoutMs": 120000 }
62
- }
63
- ```
64
-
65
- For heavy / production workloads, prefer an out-of-process SPARQL server
66
- (`sparql-http` or `blazegraph`), which handles reads and writes concurrently
67
- and keeps the daemon responsive under load.
68
-
69
- ## External-store admission and deadlines
70
-
71
- All external adapters share a process-wide priority scheduler. Waiting work is
72
- bounded independently for `ack`, `normal`, and `background` traffic, and an
73
- operation rejected before dispatch receives `StoreSchedulerBusyError` with
74
- `code: STORE_SCHEDULER_BUSY`, `retryable: true`, and a reason of either
75
- `queue_full` or `queue_wait_timeout`. Because this error is only created before
76
- the operation closure starts, retrying it cannot duplicate a write that might
77
- already have reached the store.
78
-
79
- | Environment variable | Default | Purpose |
80
- |---|---:|---|
81
- | `DKG_STORE_MAX_CONCURRENT` | `8` | Maximum external-store operations in flight. |
82
- | `DKG_STORE_ACK_RESERVED_SLOTS` | `1` | In-flight capacity reserved for ACK work. |
83
- | `DKG_STORE_NORMAL_RESERVED_SLOTS` | `1` | Non-ACK capacity kept available for normal work while background operations are in flight. |
84
- | `DKG_STORE_BACKGROUND_RESERVED_SLOTS` | `1` | Non-ACK capacity reserved for background progress. |
85
- | `DKG_STORE_QUEUE_LIMIT` | `64` | Maximum waiting operations in each priority queue. |
86
- | `DKG_STORE_ACK_QUEUE_LIMIT` | common limit | Optional ACK queue override. |
87
- | `DKG_STORE_NORMAL_QUEUE_LIMIT` | common limit | Optional normal queue override. |
88
- | `DKG_STORE_BACKGROUND_QUEUE_LIMIT` | common limit | Optional background queue override. |
89
- | `DKG_STORE_QUEUE_WAIT_TIMEOUT_MS` | `10000` | Maximum pre-dispatch wait before a retryable busy rejection. |
90
- | `DKG_BLAZEGRAPH_OPERATION_TIMEOUT_MS` | `30000` | Blazegraph end-to-end operation deadline, including scheduler wait, HTTP, response decoding, and mapping. |
91
-
92
- Normal and background reserves are normalized against the available non-ACK
93
- capacity. At least one background slot remains available, and the background
94
- progress floor is capped to its admission ceiling so conflicting custom values
95
- cannot leave usable capacity idle.
96
-
97
- Blazegraph's deadline can also be set per store, which takes precedence over
98
- the environment default:
99
-
100
- ```jsonc
101
- "store": {
102
- "backend": "blazegraph",
103
- "options": {
104
- "url": "http://127.0.0.1:9999/blazegraph/namespace/dkg/sparql",
105
- "timeout": 30000
106
- }
107
- }
108
- ```
109
-
110
- ## Internal Dependencies
111
-
112
- - `@origintrail-official/dkg-core` — configuration types, logging, constants
1
+ # @origintrail-official/dkg-storage
2
+
3
+ Triple store abstraction layer for DKG V10. Provides a unified API over multiple RDF storage backends with named graph management and private content storage.
4
+
5
+ ## Features
6
+
7
+ - **Backend adapters** — pluggable triple store implementations:
8
+ - `OxigraphStore` — embedded WASM/native store, no external dependencies
9
+ - `OxigraphWorkerStore` — worker-thread variant; keeps the daemon event loop free, with a per-read-operation timeout (see below)
10
+ - `BlazegraphStore` — connects to a running Blazegraph SPARQL endpoint
11
+ - `SparqlHttpStore` — generic adapter for any SPARQL 1.1 compliant endpoint
12
+ - **Graph manager** — named graph lifecycle (create, drop, list) with contextGraph-scoped data and metadata graphs
13
+ - **Private content store** — encrypted triple storage for private KA triples, separate from the public graph
14
+ - **Custom adapters** — `registerTripleStoreAdapter()` to plug in any storage backend
15
+
16
+ ## Usage
17
+
18
+ ```typescript
19
+ import { createTripleStore, GraphManager } from '@origintrail-official/dkg-storage';
20
+
21
+ // In-memory store
22
+ const memStore = await createTripleStore({ backend: 'oxigraph' });
23
+
24
+ // Persistent store (requires a path)
25
+ const store = await createTripleStore({
26
+ backend: 'oxigraph-persistent',
27
+ options: { path: './data' },
28
+ });
29
+
30
+ const graphs = new GraphManager(store);
31
+
32
+ await store.insert(quads);
33
+ const result = await store.query('SELECT * WHERE { ?s ?p ?o } LIMIT 10');
34
+ ```
35
+
36
+ ## Embedded worker store (`oxigraph-worker`) tuning
37
+
38
+ The embedded worker runs **all** store operations on a single worker thread, so
39
+ a long-running or stuck op (a huge import, an expensive query) blocks every
40
+ other store-backed request behind it. Under real load this surfaces as the
41
+ daemon's `/api/status` staying green while `/api/query`,
42
+ `/api/context-graph/list`, and `/api/assertion/create` hang. A `store.options`
43
+ knob bounds that blast radius:
44
+
45
+ | Option | Default | Purpose |
46
+ |---|---|---|
47
+ | `operationTimeoutMs` | `120000` | Reject a **read-only** op (`query`, `hasGraph`, `listGraphs`, `countQuads`) that exceeds this instead of hanging forever — that's where the user-visible hang shows up. `0` disables (restores unbounded behaviour). `close` is exempt — its final flush always runs to completion so shutdown can't drop pending writes. |
48
+
49
+ Mutations (`insert`, `delete`, …) are intentionally **not** bounded by this
50
+ timeout. The bound only drops the *caller's* promise — the single worker thread
51
+ keeps running the op — so a "timed-out" write could still commit afterwards,
52
+ and the rest of the codebase treats a rejected `insert`/`delete` as a clean
53
+ failure. Bounding only reads surfaces a wedged worker on the paths that hang
54
+ without inventing an indeterminate write outcome. `insert()` therefore stays
55
+ strictly atomic (all quads commit or the call fails), which callers rely on.
56
+
57
+ ```jsonc
58
+ // ~/.dkg/config.json
59
+ "store": {
60
+ "backend": "oxigraph-worker",
61
+ "options": { "operationTimeoutMs": 120000 }
62
+ }
63
+ ```
64
+
65
+ For heavy / production workloads, prefer an out-of-process SPARQL server
66
+ (`sparql-http` or `blazegraph`), which handles reads and writes concurrently
67
+ and keeps the daemon responsive under load.
68
+
69
+ ## External-store admission and deadlines
70
+
71
+ All external adapters share a process-wide priority scheduler. Waiting work is
72
+ bounded independently for `ack`, `normal`, and `background` traffic, and an
73
+ operation rejected before dispatch receives `StoreSchedulerBusyError` with
74
+ `code: STORE_SCHEDULER_BUSY`, `retryable: true`, and a reason of either
75
+ `queue_full` or `queue_wait_timeout`. Because this error is only created before
76
+ the operation closure starts, retrying it cannot duplicate a write that might
77
+ already have reached the store.
78
+
79
+ | Environment variable | Default | Purpose |
80
+ |---|---:|---|
81
+ | `DKG_STORE_MAX_CONCURRENT` | `8` | Maximum external-store operations in flight. |
82
+ | `DKG_STORE_ACK_RESERVED_SLOTS` | `1` | In-flight capacity reserved for ACK work. |
83
+ | `DKG_STORE_NORMAL_RESERVED_SLOTS` | `1` | Non-ACK capacity kept available for normal work while background operations are in flight. |
84
+ | `DKG_STORE_BACKGROUND_RESERVED_SLOTS` | `1` | Non-ACK capacity reserved for background progress. |
85
+ | `DKG_STORE_QUEUE_LIMIT` | `64` | Maximum waiting operations in each priority queue. |
86
+ | `DKG_STORE_ACK_QUEUE_LIMIT` | common limit | Optional ACK queue override. |
87
+ | `DKG_STORE_NORMAL_QUEUE_LIMIT` | common limit | Optional normal queue override. |
88
+ | `DKG_STORE_BACKGROUND_QUEUE_LIMIT` | common limit | Optional background queue override. |
89
+ | `DKG_STORE_QUEUE_WAIT_TIMEOUT_MS` | `10000` | Maximum pre-dispatch wait before a retryable busy rejection. |
90
+ | `DKG_BLAZEGRAPH_OPERATION_TIMEOUT_MS` | `30000` | Blazegraph end-to-end operation deadline, including scheduler wait, HTTP, response decoding, and mapping. |
91
+
92
+ Normal and background reserves are normalized against the available non-ACK
93
+ capacity. At least one background slot remains available, and the background
94
+ progress floor is capped to its admission ceiling so conflicting custom values
95
+ cannot leave usable capacity idle.
96
+
97
+ Blazegraph's deadline can also be set per store, which takes precedence over
98
+ the environment default:
99
+
100
+ ```jsonc
101
+ "store": {
102
+ "backend": "blazegraph",
103
+ "options": {
104
+ "url": "http://127.0.0.1:9999/blazegraph/namespace/dkg/sparql",
105
+ "timeout": 30000
106
+ }
107
+ }
108
+ ```
109
+
110
+ ## Internal Dependencies
111
+
112
+ - `@origintrail-official/dkg-core` — configuration types, logging, constants
@@ -128,9 +128,9 @@ async function readExactGraphPagedInternal(store, graphIri, options) {
128
128
  quads.length = 0;
129
129
  seenNQuadLines.clear();
130
130
  nquadsBytes = 0;
131
- const result = await store.query(`CONSTRUCT { ?s ?p ?o } WHERE {
132
- GRAPH <${graph}> { ?s ?p ?o }
133
- }
131
+ const result = await store.query(`CONSTRUCT { ?s ?p ?o } WHERE {
132
+ GRAPH <${graph}> { ?s ?p ?o }
133
+ }
134
134
  LIMIT ${expectedQuadCount + 1}`, boundedQueryOptions);
135
135
  if (result.type !== 'quads' || !Array.isArray(result.quads)) {
136
136
  throw invalidQueryResult(graph, 'Exact blank-node graph read expected CONSTRUCT quads');
@@ -160,11 +160,11 @@ async function readExactGraphPagedInternal(store, graphIri, options) {
160
160
  for (;;) {
161
161
  const remainingWithOverflowSentinel = expectedQuadCount - quads.length + 1;
162
162
  const pageLimit = Math.min(pageSize, remainingWithOverflowSentinel);
163
- const result = await store.query(`SELECT ?s ?p ?o WHERE {
164
- GRAPH <${graph}> { ?s ?p ?o }
165
- }
166
- ORDER BY ?s ?p ?o
167
- LIMIT ${pageLimit}
163
+ const result = await store.query(`SELECT ?s ?p ?o WHERE {
164
+ GRAPH <${graph}> { ?s ?p ?o }
165
+ }
166
+ ORDER BY ?s ?p ?o
167
+ LIMIT ${pageLimit}
168
168
  OFFSET ${offset}`, boundedQueryOptions);
169
169
  if (result.type !== 'bindings') {
170
170
  throw invalidQueryResult(graph, 'Exact graph read expected SELECT bindings');
@@ -253,8 +253,8 @@ function invalidQueryResult(graphIri, message) {
253
253
  });
254
254
  }
255
255
  async function queryExactGraphCount(store, graphIri, maxQuadCount, queryOptions) {
256
- const result = await store.query(`SELECT (COUNT(*) AS ?count) WHERE {
257
- GRAPH <${graphIri}> { ?s ?p ?o }
256
+ const result = await store.query(`SELECT (COUNT(*) AS ?count) WHERE {
257
+ GRAPH <${graphIri}> { ?s ?p ?o }
258
258
  }`, queryOptions);
259
259
  if (result.type !== 'bindings'
260
260
  || !Array.isArray(result.bindings)
@@ -410,11 +410,11 @@ export class ChangelogStore {
410
410
  async readChanges(sinceSeq, limit, options) {
411
411
  const since = Number.isFinite(sinceSeq) ? Math.max(0, Math.floor(sinceSeq)) : 0;
412
412
  const cap = Number.isFinite(limit) ? Math.max(1, Math.floor(limit)) : 1;
413
- const res = await this.inner.query(`SELECT ?seq ?graph ?op WHERE {
414
- GRAPH <${CHANGELOG_GRAPH}> {
415
- ?e <${P_SEQ}> ?seq ; <${P_GRAPH}> ?graph ; <${P_OP}> ?op .
416
- FILTER(?seq > ${since})
417
- }
413
+ const res = await this.inner.query(`SELECT ?seq ?graph ?op WHERE {
414
+ GRAPH <${CHANGELOG_GRAPH}> {
415
+ ?e <${P_SEQ}> ?seq ; <${P_GRAPH}> ?graph ; <${P_OP}> ?op .
416
+ FILTER(?seq > ${since})
417
+ }
418
418
  } ORDER BY ?seq LIMIT ${cap}`, { ...options, source: options?.source ?? 'changelog.readChanges' });
419
419
  if (res.type !== 'bindings')
420
420
  return [];
@@ -304,11 +304,11 @@ function sharedMemorySelectionGraphPattern(selection, options) {
304
304
  throw new Error(message);
305
305
  }
306
306
  const values = roots.map((r) => `<${r}>`).join(' ');
307
- return `VALUES ?root { ${values} }
308
- ?s ?p ?o .
309
- FILTER(
310
- ?s = ?root
311
- || STRSTARTS(STR(?s), CONCAT(STR(?root), "/.well-known/genid/"))
307
+ return `VALUES ?root { ${values} }
308
+ ?s ?p ?o .
309
+ FILTER(
310
+ ?s = ?root
311
+ || STRSTARTS(STR(?s), CONCAT(STR(?root), "/.well-known/genid/"))
312
312
  )`;
313
313
  }
314
314
  async function loadSharedMemoryQuadsInternal(store, bucketGraph, selection, options, graphScope) {
@@ -325,9 +325,9 @@ async function loadSharedMemoryQuadsInternal(store, bucketGraph, selection, opti
325
325
  if (options.resultBudget) {
326
326
  return loadSharedMemoryQuadsPaged(store, graphValues, innerGraphPattern, queryOptions, options);
327
327
  }
328
- const result = await store.query(`CONSTRUCT { ?s ?p ?o } WHERE {
329
- VALUES ?g { ${graphValues} }
330
- GRAPH ?g { ${innerGraphPattern} }
328
+ const result = await store.query(`CONSTRUCT { ?s ?p ?o } WHERE {
329
+ VALUES ?g { ${graphValues} }
330
+ GRAPH ?g { ${innerGraphPattern} }
331
331
  }`, queryOptions);
332
332
  if (result.type !== 'quads')
333
333
  return [];
@@ -356,12 +356,12 @@ async function loadSharedMemoryQuadsPaged(store, graphValues, innerGraphPattern,
356
356
  getMetrics().storeQueryResultBytesEstimate.record(bytesEstimate, { source });
357
357
  };
358
358
  for (let offset = 0;; offset += pageRows) {
359
- const result = await store.query(`SELECT DISTINCT ?s ?p ?o WHERE {
360
- VALUES ?g { ${graphValues} }
361
- GRAPH ?g { ${innerGraphPattern} }
362
- }
363
- ORDER BY ?s ?p ?o
364
- OFFSET ${offset}
359
+ const result = await store.query(`SELECT DISTINCT ?s ?p ?o WHERE {
360
+ VALUES ?g { ${graphValues} }
361
+ GRAPH ?g { ${innerGraphPattern} }
362
+ }
363
+ ORDER BY ?s ?p ?o
364
+ OFFSET ${offset}
365
365
  LIMIT ${pageRows}`, queryOptions);
366
366
  if (result.type !== 'bindings' || result.bindings.length === 0)
367
367
  break;
@@ -425,18 +425,18 @@ export async function loadSelectedVerifiableMemoryQuads(store, dataGraph, rootEn
425
425
  const vmGraphs = await resolveVerifiableMemoryReadGraphs(store, dataGraph, queryOptions);
426
426
  const graphValues = vmGraphs.map((g) => `<${g}>`).join(' ');
427
427
  const rootValues = roots.map((root) => sparqlString(root)).join(' ');
428
- const result = await store.query(`CONSTRUCT {
429
- ?s ?p ?o
430
- } WHERE {
431
- VALUES ?g { ${graphValues} }
432
- GRAPH ?g {
433
- VALUES ?rootValue { ${rootValues} }
434
- ?s ?p ?o .
435
- FILTER(
436
- STR(?s) = ?rootValue
437
- || STRSTARTS(STR(?s), CONCAT(?rootValue, "/.well-known/genid/"))
438
- )
439
- }
428
+ const result = await store.query(`CONSTRUCT {
429
+ ?s ?p ?o
430
+ } WHERE {
431
+ VALUES ?g { ${graphValues} }
432
+ GRAPH ?g {
433
+ VALUES ?rootValue { ${rootValues} }
434
+ ?s ?p ?o .
435
+ FILTER(
436
+ STR(?s) = ?rootValue
437
+ || STRSTARTS(STR(?s), CONCAT(?rootValue, "/.well-known/genid/"))
438
+ )
439
+ }
440
440
  }`, queryOptions);
441
441
  return result.type === 'quads' ? result.quads : [];
442
442
  }
package/dist/index.d.ts CHANGED
@@ -16,6 +16,7 @@ export { SparqlHttpStore, type SparqlHttpStoreOptions, type SparqlHttpQueryOptio
16
16
  export { ContextGraphManager, GraphManager, loadSelectedSharedMemoryQuads, loadSharedMemoryQuadsForScope, loadSharedMemorySliceWithKaBoundFallback, canonicalSharedMemoryScopeWriteGraph, resolveSharedMemoryScopeGraphs, resolveSharedMemoryScopeWriteGraph, loadSelectedVerifiableMemoryQuads, resolveSharedMemoryReadGraphs, resolveVerifiableMemoryReadGraphs, type LoadSelectedSharedMemoryQuadsOptions, type SharedMemoryResultBudget, SharedMemoryResultBudgetError, type LoadSelectedVerifiableMemoryQuadsOptions, type NonEmptyGraphList, type NamedKnowledgeAssetGraphIdentity, type SharedMemoryReadSelection, type SharedMemoryGraphScope, type SwmKaGraphBound, type SwmSliceSourceTags, type LoadSharedMemorySliceWithKaBoundFallbackOptions, } from './graph-manager.js';
17
17
  export { PrivateContentStore, type KnowledgeAssetPrivateReadOptions, } from './private-store.js';
18
18
  export { LOCAL_TRUSTED_KA_CONTROLS_GRAPH } from './local-trusted-controls.js';
19
+ export { SWM_MATERIALIZATION_WITNESS_GRAPH, swmMaterializationWitnessSubject, readSwmMaterializationWitness, writeSwmMaterializationWitness, invalidateSwmMaterializationWitness, } from './swm-materialization-witness.js';
19
20
  import './adapters/oxigraph.js';
20
21
  import './adapters/oxigraph-worker.js';
21
22
  import './adapters/blazegraph.js';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,IAAI,EACT,KAAK,WAAW,EAChB,KAAK,WAAW,EAChB,KAAK,YAAY,EACjB,KAAK,iBAAiB,EACtB,KAAK,qBAAqB,EAC1B,KAAK,YAAY,EACjB,KAAK,eAAe,EACpB,KAAK,SAAS,EACd,KAAK,iBAAiB,EACtB,KAAK,kBAAkB,EACvB,KAAK,uBAAuB,EAC5B,KAAK,aAAa,EAClB,KAAK,yBAAyB,EAC9B,0BAA0B,EAC1B,iBAAiB,EACjB,0BAA0B,EAC1B,yBAAyB,EACzB,mCAAmC,EACnC,2BAA2B,EAC3B,iBAAiB,EACjB,iBAAiB,EACjB,KAAK,cAAc,GACpB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,mCAAmC,EACnC,+BAA+B,EAC/B,uCAAuC,EACvC,6BAA6B,EAC7B,+BAA+B,EAC/B,gCAAgC,EAChC,KAAK,kCAAkC,EACvC,KAAK,wBAAwB,GAC9B,MAAM,2BAA2B,CAAC;AACnC,OAAO,EACL,qCAAqC,EACrC,yCAAyC,EACzC,+BAA+B,EAC/B,iCAAiC,EACjC,KAAK,qBAAqB,GAC3B,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EACL,sBAAsB,EACtB,uBAAuB,EACvB,8BAA8B,EAC9B,yCAAyC,EACzC,yBAAyB,EACzB,mCAAmC,EACnC,KAAK,8BAA8B,EACnC,KAAK,6BAA6B,EAClC,KAAK,wBAAwB,EAC7B,KAAK,wBAAwB,GAC9B,MAAM,+BAA+B,CAAC;AACvC,OAAO,EACL,6BAA6B,EAC7B,0BAA0B,EAC1B,qCAAqC,EACrC,4BAA4B,EAC5B,KAAK,mCAAmC,GACzC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EACL,+BAA+B,EAC/B,mDAAmD,EACnD,kBAAkB,EAClB,KAAK,yBAAy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C,OAAO,EACL,eAAe,EACf,KAAK,sBAAsB,EAC3B,KAAK,sBAAsB,EAC3B,KAAK,wBAAwB,GAC9B,MAAM,2BAA2B,CAAC;AACnC,OAAO,EACL,mBAAmB,EACnB,YAAY,EACZ,6BAA6B,EAC7B,6BAA6B,EAC7B,wCAAwC,EACxC,oCAAoC,EACpC,8BAA8B,EAC9B,kCAAkC,EAClC,iCAAiC,EACjC,6BAA6B,EAC7B,iCAAiC,EACjC,KAAK,oCAAoC,EACzC,KAAK,wBAAwB,EAC7B,6BAA6B,EAC7B,KAAK,wCAAwC,EAC7C,KAAK,iBAAiB,EACtB,KAAK,gCAAgC,EACrC,KAAK,yBAAyB,EAC9B,KAAK,sBAAsB,EAC3B,KAAK,eAAe,EACpB,KAAK,kBAAkB,EACvB,KAAK,+CAA+C,GACrD,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EACL,mBAAmB,EACnB,KAAK,gCAAgC,GACtC,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,+BAA+B,EAAE,MAAM,6BAA6B,CAAC;AAI9E,OAAO,EACL,iCAAiC,EACjC,gCAAgC,EAChC,6BAA6B,EAC7B,8BAA8B,EAC9B,mCAAmC,GACpC,MAAM,kCAAkC,CAAC;AAG1C,OAAO,wBAAwB,CAAC;AAChC,OAAO,+BAA+B,CAAC;AACvC,OAAO,0BAA0B,CAAC;AAClC,OAAO,2BAA2B,CAAC"}
package/dist/index.js CHANGED
@@ -16,6 +16,10 @@ export { SparqlHttpStore, } from './adapters/sparql-http.js';
16
16
  export { ContextGraphManager, GraphManager, loadSelectedSharedMemoryQuads, loadSharedMemoryQuadsForScope, loadSharedMemorySliceWithKaBoundFallback, canonicalSharedMemoryScopeWriteGraph, resolveSharedMemoryScopeGraphs, resolveSharedMemoryScopeWriteGraph, loadSelectedVerifiableMemoryQuads, resolveSharedMemoryReadGraphs, resolveVerifiableMemoryReadGraphs, SharedMemoryResultBudgetError, } from './graph-manager.js';
17
17
  export { PrivateContentStore, } from './private-store.js';
18
18
  export { LOCAL_TRUSTED_KA_CONTROLS_GRAPH } from './local-trusted-controls.js';
19
+ // #2079 — node-local memo of an already-verified SWM assertion graph. Read only
20
+ // AFTER a count gate has matched; see the module doc for why the count cannot
21
+ // be dropped.
22
+ export { SWM_MATERIALIZATION_WITNESS_GRAPH, swmMaterializationWitnessSubject, readSwmMaterializationWitness, writeSwmMaterializationWitness, invalidateSwmMaterializationWitness, } from './swm-materialization-witness.js';
19
23
  // Side-effect: register built-in adapters
20
24
  import './adapters/oxigraph.js';
21
25
  import './adapters/oxigraph-worker.js';
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAeL,0BAA0B,EAC1B,iBAAiB,EACjB,0BAA0B,EAC1B,yBAAyB,EACzB,mCAAmC,EACnC,2BAA2B,EAC3B,iBAAiB,EACjB,iBAAiB,GAElB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,mCAAmC,EACnC,+BAA+B,EAC/B,uCAAuC,EACvC,6BAA6B,EAC7B,+BAA+B,EAC/B,gCAAgC,GAGjC,MAAM,2BAA2B,CAAC;AACnC,OAAO,EACL,qCAAqC,EACrC,yCAAyC,EACzC,+BAA+B,EAC/B,iCAAiC,GAElC,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EACL,sBAAsB,EACtB,uBAAuB,EACvB,8BAA8B,EAC9B,yCAAyC,EACzC,yBAAyB,EACzB,mCAAmC,GAKpC,MAAM,+BAA+B,CAAC;AACvC,OAAO,EACL,6BAA6B,EAC7B,0BAA0B,EAC1B,qCAAqC,EACrC,4BAA4B,GAE7B,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EACL,+BAA+B,EAC/B,mDAAmD,EACnD,kBAAkB,GAInB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EACL,eAAe,EACf,wBAAwB,EACxB,cAAc,EACd,mBAAmB,EACnB,iBAAiB,GA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AAiC,EACjC,6BAA6B,EAC7B,iCAAiC,EAGjC,6BAA6B,GAS9B,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EACL,mBAAmB,GAEpB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,+BAA+B,EAAE,MAAM,6BAA6B,CAAC;AAC9E,gFAAgF;AAChF,8EAA8E;AAC9E,cAAc;AACd,OAAO,EACL,iCAAiC,EACjC,gCAAgC,EAChC,6BAA6B,EAC7B,8BAA8B,EAC9B,mCAAmC,GACpC,MAAM,kCAAkC,CAAC;AAE1C,0CAA0C;AAC1C,OAAO,wBAAwB,CAAC;AAChC,OAAO,+BAA+B,CAAC;AACvC,OAAO,0BAA0B,CAAC;AAClC,OAAO,2BAA2B,CAAC"}
@@ -90,24 +90,24 @@ export class PrivateContentStore {
90
90
  const subjectVals = incomingSubjects
91
91
  .map((s) => `<${assertSafeIri(s)}>`)
92
92
  .join(' ');
93
- sparql = `
94
- SELECT ?s ?p ?o WHERE {
95
- GRAPH ${escapedGraph} {
96
- VALUES ?s { ${subjectVals} }
97
- VALUES ?p { ${escapedPredicateVals} }
98
- ?s ?p ?o .
99
- }
100
- }
93
+ sparql = `
94
+ SELECT ?s ?p ?o WHERE {
95
+ GRAPH ${escapedGraph} {
96
+ VALUES ?s { ${subjectVals} }
97
+ VALUES ?p { ${escapedPredicateVals} }
98
+ ?s ?p ?o .
99
+ }
100
+ }
101
101
  `;
102
102
  }
103
103
  else {
104
- sparql = `
105
- SELECT ?s ?p ?o WHERE {
106
- GRAPH ${escapedGraph} {
107
- VALUES ?p { ${escapedPredicateVals} }
108
- ?s ?p ?o .
109
- }
110
- }
104
+ sparql = `
105
+ SELECT ?s ?p ?o WHERE {
106
+ GRAPH ${escapedGraph} {
107
+ VALUES ?p { ${escapedPredicateVals} }
108
+ ?s ?p ?o .
109
+ }
110
+ }
111
111
  `;
112
112
  }
113
113
  const keys = new Set();
@@ -329,10 +329,10 @@ export class PrivateContentStore {
329
329
  assertSafeIri(rootEntity);
330
330
  const graphUri = this.privateStagingGraph(contextGraphId, shareOperationId, subGraphName);
331
331
  const subject = privateStageSubject(contextGraphId, shareOperationId, rootEntity, subGraphName);
332
- const result = await this.store.query(`SELECT ?payload WHERE {
333
- GRAPH <${assertSafeIri(graphUri)}> {
334
- <${assertSafeIri(subject)}> <http://dkg.io/ontology/privateStagedQuads> ?payload .
335
- }
332
+ const result = await this.store.query(`SELECT ?payload WHERE {
333
+ GRAPH <${assertSafeIri(graphUri)}> {
334
+ <${assertSafeIri(subject)}> <http://dkg.io/ontology/privateStagedQuads> ?payload .
335
+ }
336
336
  } LIMIT 1`);
337
337
  if (result.type !== 'bindings' || result.bindings.length === 0)
338
338
  return [];
@@ -350,16 +350,16 @@ export class PrivateContentStore {
350
350
  }
351
351
  async getPrivateTriples(contextGraphId, rootEntity, subGraphName) {
352
352
  const graphUri = this.privateGraph(contextGraphId, subGraphName);
353
- const sparql = `
354
- SELECT ?s ?p ?o WHERE {
355
- GRAPH <${assertSafeIri(graphUri)}> {
356
- ?s ?p ?o .
357
- FILTER(
358
- ?s = <${assertSafeIri(rootEntity)}>
359
- || STRSTARTS(STR(?s), "${escapeSparqlLiteral(rootEntity)}/.well-known/genid/")
360
- )
361
- }
362
- }
353
+ const sparql = `
354
+ SELECT ?s ?p ?o WHERE {
355
+ GRAPH <${assertSafeIri(graphUri)}> {
356
+ ?s ?p ?o .
357
+ FILTER(
358
+ ?s = <${assertSafeIri(rootEntity)}>
359
+ || STRSTARTS(STR(?s), "${escapeSparqlLiteral(rootEntity)}/.well-known/genid/")
360
+ )
361
+ }
362
+ }
363
363
  `;
364
364
  const result = await this.store.query(sparql);
365
365
  if (result.type !== 'bindings')
@@ -414,10 +414,10 @@ export class PrivateContentStore {
414
414
  * stored slice.
415
415
  */
416
416
  async readPrivateCommitment(graphUri, markerSubject) {
417
- const result = await this.store.query(`SELECT ?c WHERE {
418
- GRAPH <${assertSafeIri(graphUri)}> {
419
- <${assertSafeIri(markerSubject)}> <${PRIVATE_COMMITMENT_PRED}> ?c .
420
- }
417
+ const result = await this.store.query(`SELECT ?c WHERE {
418
+ GRAPH <${assertSafeIri(graphUri)}> {
419
+ <${assertSafeIri(markerSubject)}> <${PRIVATE_COMMITMENT_PRED}> ?c .
420
+ }
421
421
  } LIMIT 1`);
422
422
  if (result.type !== 'bindings' || result.bindings.length === 0)
423
423
  return undefined;
@@ -0,0 +1,54 @@
1
+ import type { QueryOptions, TripleStore } from './triple-store.js';
2
+ export declare const SWM_MATERIALIZATION_WITNESS_GRAPH = "urn:dkg:local:swm-materialization-witness";
3
+ /**
4
+ * One subject per assertion graph — NOT per (graph, digest) pair.
5
+ *
6
+ * Keying the subject on the graph alone is what makes a new digest EVICT the
7
+ * old claim in the same atomic replace. Folding the digest into the subject IRI
8
+ * would leave the previous version's row standing, so a later return to that
9
+ * digest — or any equal-count replace — would find a standing lie.
10
+ *
11
+ * PRECONDITION: `assertionGraph` carries no `#`. Every caller passes a
12
+ * `knowledgeAssetLayerGraphUri`, which does not, but `assertSafeIri` does NOT
13
+ * reject `#` — so a fragment-bearing graph would yield a double-fragment IRI
14
+ * here. That would be a distinct, self-consistent subject rather than a
15
+ * collision (both write and read derive it the same way), but it is outside
16
+ * what this keying scheme intends.
17
+ */
18
+ export declare function swmMaterializationWitnessSubject(assertionGraph: string): string;
19
+ /**
20
+ * Has this node verified `assertionGraph` at exactly `digest`?
21
+ *
22
+ * A bound-subject ASK: O(1) regardless of graph size. Both the subject and the
23
+ * digest are bound, so a witness for a DIFFERENT digest reads as a miss rather
24
+ * than a hit — which is what makes an equal-count version change safe.
25
+ */
26
+ export declare function readSwmMaterializationWitness(store: TripleStore, assertionGraph: string, digest: string, options?: QueryOptions): Promise<boolean>;
27
+ /**
28
+ * Record that this node verified `assertionGraph` at `digest`, evicting any
29
+ * prior claim for that graph.
30
+ *
31
+ * Returns `false` when the store cannot do an atomic single-subject replace —
32
+ * in which case NOTHING is written. That is deliberate and is the one place
33
+ * this module departs from the usual `tryReplaceSubjectAtomically` idiom, which
34
+ * falls back to delete-then-insert: a missing witness is always safe (it costs
35
+ * one recomputation), whereas a non-atomic fallback could leave two digest rows
36
+ * for one graph after an interrupted write — and a stale digest row IS a
37
+ * standing lie. Never add a fallback here.
38
+ */
39
+ export declare function writeSwmMaterializationWitness(store: TripleStore, assertionGraph: string, digest: string, options?: QueryOptions): Promise<boolean>;
40
+ /**
41
+ * Drop the witness for `assertionGraph`.
42
+ *
43
+ * Call this from every path that replaces or removes the graph's content WITHIN
44
+ * a lock this module can see. The three unlockable paths named in the module
45
+ * doc are covered by the caller's count gate instead — they cannot be covered
46
+ * here, and pretending otherwise would be worse than leaving them to the count.
47
+ */
48
+ export declare function invalidateSwmMaterializationWitness(store: {
49
+ deleteByPattern(pattern: {
50
+ graph: string;
51
+ subject: string;
52
+ }, options?: QueryOptions): Promise<unknown>;
53
+ }, assertionGraph: string, options?: QueryOptions): Promise<void>;
54
+ //# sourceMappingURL=swm-materialization-witness.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"swm-materialization-witness.d.ts","sourceRoot":"","sources":["../src/swm-materialization-witness.ts"],"names":[],"mappings":"AA4GA,OAAO,KAAK,EAAE,YAAY,EAAQ,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAGzE,eAAO,MAAM,iCAAiC,8CAA8C,CAAC;AAI7F;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,gCAAgC,CAAC,cAAc,EAAE,MAAM,GAAG,MAAM,CAE/E;AAED;;;;;;GAMG;AACH,wBAAsB,6BAA6B,CACjD,KAAK,EAAE,WAAW,EAClB,cAAc,EAAE,MAAM,EACtB,MAAM,EAAE,MAAM,EACd,OAAO,GAAE,YAAiB,GACzB,OAAO,CAAC,OAAO,CAAC,CAclB;AAED;;;;;;;;;;;GAWG;AACH,wBAAsB,8BAA8B,CAClD,KAAK,EAAE,WAAW,EAClB,cAAc,EAAE,MAAM,EACtB,MAAM,EAAE,MAAM,EACd,OAAO,GAAE,YAAiB,GACzB,OAAO,CAAC,OAAO,CAAC,CAqBlB;AAED;;;;;;;GAOG;AACH,wBAAsB,mCAAmC,CAMvD,KAAK,EAAE;IAAE,eAAe,CAAC,OAAO,EAAE;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,EAAE,OAAO,CAAC,EAAE,YAAY,GAAG,OAAO,CAAC,OAAO,CAAC,CAAA;CAAE,EACjH,cAAc,EAAE,MAAM,EACtB,OAAO,GAAE,YAAiB,GACzB,OAAO,CAAC,IAAI,CAAC,CAQf"}
@@ -0,0 +1,197 @@
1
+ /**
2
+ * A node-local memo recording that THIS node verified a graph-scoped SWM
3
+ * assertion graph against a specific content digest (issue #2079).
4
+ *
5
+ * Like `LOCAL_TRUSTED_KA_CONTROLS_GRAPH`, this graph deliberately lives outside
6
+ * every context-graph prefix, so durable sync neither serves nor ingests it as
7
+ * peer metadata.
8
+ *
9
+ * ## What this is, and what it is NOT
10
+ *
11
+ * It is a **memo of a measurement this node already took** — written only from
12
+ * the branch that has just computed the digest over its own store content and
13
+ * found it matching. It is never an independent claim that something is
14
+ * materialized.
15
+ *
16
+ * That distinction is the whole design. A witness derived from anything a PEER
17
+ * sent is unsound: the bulk `storeInsert(processed.verifiedMeta)` writes head
18
+ * rows for every descriptor in verified metadata with no dependency on whether
19
+ * that KA's graph was materialized, so using a head row as the witness grows
20
+ * MORE likely to wrongly report "already done" the more catch-up rounds a node
21
+ * runs. That design was proposed for #2079 and killed in review; this module
22
+ * exists to be the sound alternative, not a variation on it.
23
+ *
24
+ * ## The witness is NOT sufficient on its own — callers must keep a count gate
25
+ *
26
+ * A witness records that the content WAS correct, not that it still IS. What
27
+ * happens to the content splits into two classes, and the distinction is the
28
+ * whole safety argument — do NOT collapse them into one list of "paths that
29
+ * change the graph".
30
+ *
31
+ * **REMOVALS — covered by the caller's count gate, no invalidation needed.**
32
+ * These leave an empty or absent graph, so `COUNT` returns 0 ≠ expected and the
33
+ * witness is never consulted:
34
+ *
35
+ * - the shared-memory TTL sweep (`cleanupExpiredSharedMemory`), on a timer;
36
+ * - the chain-reset wipe, whose scoped delete filters on the context-graph,
37
+ * publisher and changelog prefixes only — so a `urn:dkg:local:*` witness
38
+ * SURVIVES a wipe that deletes every context-graph triple.
39
+ *
40
+ * **REPLACES — NOT covered by the count gate. Every one MUST invalidate.**
41
+ * A replace can leave the quad count unchanged while the content differs, which
42
+ * is exactly the case `COUNT` cannot see. Known sites, all on the byte-identical
43
+ * assertion-graph URI:
44
+ *
45
+ * 1. the sync materializer's own `replaceGraph`;
46
+ * 2. live gossip apply (`workspace-handler`);
47
+ * 3. the graph-scoped VM update path (`dkg-agent-publish`);
48
+ * 4. storage-ack persistence (`storage-ack-handler`);
49
+ * 5-6. the private SWM recovery lane (`swm-recovery`, two calls) — lane-disjoint
50
+ * in automatic operation but reachable via the `recover-shared-memory` route;
51
+ * 7. WM→SWM promotion (`dkg-publisher`);
52
+ * 8. RFC-64 public-catalog activation
53
+ * (`public-catalog-native-receiver-v1.activateExactPublicProjection`), which
54
+ * uses `tryReplaceGraphAndSubjectAtomically` — see the grep note below.
55
+ *
56
+ * Two nearby RFC-64 sites are deliberately NOT obligations: rollback restore
57
+ * puts back the exact preimage, so a standing witness becomes valid again; and
58
+ * deactivation replaces with `[]`, leaving an empty graph the count gate covers.
59
+ *
60
+ * This list is a snapshot, not a closed set. **Any new whole-graph replace of a
61
+ * SWM assertion graph is a new obligation here** — treat adding one without an
62
+ * invalidate as a defect.
63
+ *
64
+ * When you sweep for missed sites, grep the SHAPE, not one function name. The
65
+ * primitives in tree today are:
66
+ *
67
+ * - `tryReplaceGraphAtomically`
68
+ * - `tryReplaceGraphAndSubjectAtomically` ← added the 8th site below
69
+ * - `store.replaceGraph` directly (the recovery lane)
70
+ *
71
+ * An earlier revision of this comment named only the first. Four review rounds
72
+ * then greppped the token it named and kept reporting the set complete, while
73
+ * `public-catalog-native-receiver-v1`'s activation — which uses the second —
74
+ * sat unlisted and uninvalidated. **The tripwire caused the miss it existed to
75
+ * prevent.** If you add a fourth primitive, add it here in the same commit.
76
+ *
77
+ * **Callers must treat a witness hit as valid only after a count gate has
78
+ * already matched.** Do not "optimize" that count away: without it the removal
79
+ * paths above become permanent silent divergence certified as parity.
80
+ *
81
+ * The digest is part of the READ for the same reason the replace list exists: a
82
+ * standing v1 row cannot satisfy an ASK bound to v2's digest, which bounds the
83
+ * damage when an invalidate is missed or its best-effort call fails.
84
+ *
85
+ * ## Known costs — accepted deliberately, recorded so they don't read as bugs
86
+ *
87
+ * An accepted trade nobody wrote down is indistinguishable from an oversight six
88
+ * months later, so:
89
+ *
90
+ * - **No GC.** Rows are orphaned whenever content is destroyed by a path that
91
+ * cannot invalidate — the TTL sweep, VM publish, and the chain-reset wipe
92
+ * (whose scoped delete spares `urn:dkg:local:*`). Bounded at two quads per
93
+ * KA ever materialized, harmless because every read binds the digest, and
94
+ * reclaimed on the next replace of that graph. A sweep keyed on
95
+ * "assertion graph no longer exists" would close it.
96
+ * - **A changelog marker per write.** This graph is in no reserved set
97
+ * (`ChangelogStore`'s is `{CHANGELOG_GRAPH}` plus `options.reservedGraphs`,
98
+ * which has no callers), so every cold-path write appends a marker and
99
+ * advances `seq`. Local only — the delta lane filters on `isCandidateGraph`,
100
+ * so it never reaches a peer.
101
+ * - **A read is now also a write.** On a MISS the check performs an atomic
102
+ * subject replace inside the KA write lock, where before it only read. Cold
103
+ * or churning stores therefore pay slightly more than they used to; the
104
+ * memo only pays back on warm ones. `DKG_SWM_MATERIALIZATION_WITNESS=0`
105
+ * disables both the read and the write for a fleet that finds it net
106
+ * negative.
107
+ */
108
+ import { assertSafeIri, sparqlString } from '@origintrail-official/dkg-core';
109
+ import { tryReplaceSubjectAtomically } from './triple-store.js';
110
+ export const SWM_MATERIALIZATION_WITNESS_GRAPH = 'urn:dkg:local:swm-materialization-witness';
111
+ const WITNESS_DIGEST_PREDICATE = 'urn:dkg:local:swm-materialization-witness:digest';
112
+ /**
113
+ * One subject per assertion graph — NOT per (graph, digest) pair.
114
+ *
115
+ * Keying the subject on the graph alone is what makes a new digest EVICT the
116
+ * old claim in the same atomic replace. Folding the digest into the subject IRI
117
+ * would leave the previous version's row standing, so a later return to that
118
+ * digest — or any equal-count replace — would find a standing lie.
119
+ *
120
+ * PRECONDITION: `assertionGraph` carries no `#`. Every caller passes a
121
+ * `knowledgeAssetLayerGraphUri`, which does not, but `assertSafeIri` does NOT
122
+ * reject `#` — so a fragment-bearing graph would yield a double-fragment IRI
123
+ * here. That would be a distinct, self-consistent subject rather than a
124
+ * collision (both write and read derive it the same way), but it is outside
125
+ * what this keying scheme intends.
126
+ */
127
+ export function swmMaterializationWitnessSubject(assertionGraph) {
128
+ return `${assertionGraph}#dkg-swm-materialized`;
129
+ }
130
+ /**
131
+ * Has this node verified `assertionGraph` at exactly `digest`?
132
+ *
133
+ * A bound-subject ASK: O(1) regardless of graph size. Both the subject and the
134
+ * digest are bound, so a witness for a DIFFERENT digest reads as a miss rather
135
+ * than a hit — which is what makes an equal-count version change safe.
136
+ */
137
+ export async function readSwmMaterializationWitness(store, assertionGraph, digest, options = {}) {
138
+ const subject = swmMaterializationWitnessSubject(assertionGraph);
139
+ // Contained: this is a pure OPTIMISATION, so a transient store error must
140
+ // degrade to "not memoized" and let the caller do the real read-back. Letting
141
+ // it throw would make a check that used to succeed fail, which is a strictly
142
+ // worse outcome than recomputing.
143
+ const result = await store
144
+ .query(`ASK { GRAPH <${assertSafeIri(SWM_MATERIALIZATION_WITNESS_GRAPH)}> { `
145
+ + `<${assertSafeIri(subject)}> <${assertSafeIri(WITNESS_DIGEST_PREDICATE)}> ${sparqlString(digest)} } }`, options)
146
+ .catch(() => null);
147
+ return result?.type === 'boolean' && result.value === true;
148
+ }
149
+ /**
150
+ * Record that this node verified `assertionGraph` at `digest`, evicting any
151
+ * prior claim for that graph.
152
+ *
153
+ * Returns `false` when the store cannot do an atomic single-subject replace —
154
+ * in which case NOTHING is written. That is deliberate and is the one place
155
+ * this module departs from the usual `tryReplaceSubjectAtomically` idiom, which
156
+ * falls back to delete-then-insert: a missing witness is always safe (it costs
157
+ * one recomputation), whereas a non-atomic fallback could leave two digest rows
158
+ * for one graph after an interrupted write — and a stale digest row IS a
159
+ * standing lie. Never add a fallback here.
160
+ */
161
+ export async function writeSwmMaterializationWitness(store, assertionGraph, digest, options = {}) {
162
+ const subject = swmMaterializationWitnessSubject(assertionGraph);
163
+ // Exactly ONE row. An earlier revision also stored a `verified-at-ms`
164
+ // timestamp; nothing read it, and every witness write appends a changelog
165
+ // marker and advances `seq`, so a second row doubled that churn for no
166
+ // consumer. Add a row here only when something reads it.
167
+ const quads = [
168
+ {
169
+ subject,
170
+ predicate: WITNESS_DIGEST_PREDICATE,
171
+ object: sparqlString(digest),
172
+ graph: SWM_MATERIALIZATION_WITNESS_GRAPH,
173
+ },
174
+ ];
175
+ return tryReplaceSubjectAtomically(store, SWM_MATERIALIZATION_WITNESS_GRAPH, subject, quads, options);
176
+ }
177
+ /**
178
+ * Drop the witness for `assertionGraph`.
179
+ *
180
+ * Call this from every path that replaces or removes the graph's content WITHIN
181
+ * a lock this module can see. The three unlockable paths named in the module
182
+ * doc are covered by the caller's count gate instead — they cannot be covered
183
+ * here, and pretending otherwise would be worse than leaving them to the count.
184
+ */
185
+ export async function invalidateSwmMaterializationWitness(
186
+ // Narrower than `TripleStore` on purpose: invalidation needs exactly one
187
+ // capability, and every replace path that must call it is an obligation
188
+ // regardless of how rich its store handle is. The private recovery lane holds
189
+ // a `SwmRecoveryStore`, which is not a full `TripleStore` — requiring one here
190
+ // would have made that site uncallable and quietly left it out of the set.
191
+ store, assertionGraph, options = {}) {
192
+ await store.deleteByPattern({
193
+ graph: SWM_MATERIALIZATION_WITNESS_GRAPH,
194
+ subject: swmMaterializationWitnessSubject(assertionGraph),
195
+ }, options);
196
+ }
197
+ //# sourceMappingURL=swm-materialization-witness.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"swm-materialization-witness.js","source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1B,MAAM,OAAO,GAAG,gCAAgC,CAAC,cAAc,CAAC,CAAC;IACjE,sEAAsE;IACtE,0EAA0E;IAC1E,uEAAuE;IACvE,yDAAyD;IACzD,MAAM,KAAK,GAAW;QACpB;YACE,OAAO;YACP,SAAS,EAAE,wBAAwB;YACnC,MAAM,EAAE,YAAY,CAAC,MAAM,CAAC;YAC5B,KAAK,EAAE,iCAAiC;SACzC;KACF,CAAC;IACF,OAAO,2BAA2B,CAChC,KAAK,EACL,iCAAiC,EACjC,OAAO,EACP,KAAK,EACL,OAAO,CACR,CAAC;AACJ,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,CAAC,KAAK,UAAU,mCAAmC;AACvD,yEAAyE;AACzE,wEAAwE;AACxE,8EAA8E;AAC9E,+EAA+E;AAC/E,2EAA2E;AAC3E,KAAiH,EACjH,cAAsB,EACtB,UAAwB,EAAE;IAE1B,MAAM,KAAK,CAAC,eAAe,CACzB;QACE,KAAK,EAAE,iCAAiC;QACxC,OAAO,EAAE,gCAAgC,CAAC,cAAc,CAAC;KAC1D,EACD,OAAO,CACR,CAAC;AACJ,CAAC"}
package/package.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "@origintrail-official/dkg-storage",
3
- "version": "10.0.12",
3
+ "version": "10.0.13",
4
4
  "type": "module",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
7
7
  "dependencies": {
8
8
  "oxigraph": "^0.5",
9
- "@origintrail-official/dkg-core": "10.0.12",
10
- "@origintrail-official/dkg-rdf-utils": "10.0.12"
9
+ "@origintrail-official/dkg-core": "10.0.13",
10
+ "@origintrail-official/dkg-rdf-utils": "10.0.13"
11
11
  },
12
12
  "devDependencies": {
13
13
  "@vitest/coverage-v8": "^4.0.18",