@dads-framework/postgres-access 0.0.0-stage → 0.1.0

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.
Files changed (105) hide show
  1. package/BENCHMARK.md +275 -0
  2. package/LICENSE.md +21 -0
  3. package/README.md +212 -2
  4. package/dist/compile-access-policy.d.ts +9 -0
  5. package/dist/compile-access-policy.d.ts.map +1 -0
  6. package/dist/compile-access-policy.js +77 -0
  7. package/dist/compile-access-policy.js.map +1 -0
  8. package/dist/drizzle-executor.d.ts +5 -0
  9. package/dist/drizzle-executor.d.ts.map +1 -0
  10. package/dist/drizzle-executor.js +25 -0
  11. package/dist/drizzle-executor.js.map +1 -0
  12. package/dist/index.d.ts +8 -0
  13. package/dist/index.d.ts.map +1 -0
  14. package/dist/index.js +8 -0
  15. package/dist/index.js.map +1 -0
  16. package/dist/lookup-primary-pool.d.ts +5 -0
  17. package/dist/lookup-primary-pool.d.ts.map +1 -0
  18. package/dist/lookup-primary-pool.js +24 -0
  19. package/dist/lookup-primary-pool.js.map +1 -0
  20. package/dist/lookup-revision-query.d.ts +7 -0
  21. package/dist/lookup-revision-query.d.ts.map +1 -0
  22. package/dist/lookup-revision-query.js +73 -0
  23. package/dist/lookup-revision-query.js.map +1 -0
  24. package/dist/lookup-revision-schema.d.ts +10 -0
  25. package/dist/lookup-revision-schema.d.ts.map +1 -0
  26. package/dist/lookup-revision-schema.js +75 -0
  27. package/dist/lookup-revision-schema.js.map +1 -0
  28. package/dist/lower-permissions.d.ts +8 -0
  29. package/dist/lower-permissions.d.ts.map +1 -0
  30. package/dist/lower-permissions.js +76 -0
  31. package/dist/lower-permissions.js.map +1 -0
  32. package/dist/policy/compile-linear-batch.d.ts +15 -0
  33. package/dist/policy/compile-linear-batch.d.ts.map +1 -0
  34. package/dist/policy/compile-linear-batch.js +34 -0
  35. package/dist/policy/compile-linear-batch.js.map +1 -0
  36. package/dist/policy/compile-linear-check.d.ts +5 -0
  37. package/dist/policy/compile-linear-check.d.ts.map +1 -0
  38. package/dist/policy/compile-linear-check.js +71 -0
  39. package/dist/policy/compile-linear-check.js.map +1 -0
  40. package/dist/policy/compile-postgres-policy.d.ts +28 -0
  41. package/dist/policy/compile-postgres-policy.d.ts.map +1 -0
  42. package/dist/policy/compile-postgres-policy.js +189 -0
  43. package/dist/policy/compile-postgres-policy.js.map +1 -0
  44. package/dist/policy/compile-reverse-policy.d.ts +5 -0
  45. package/dist/policy/compile-reverse-policy.d.ts.map +1 -0
  46. package/dist/policy/compile-reverse-policy.js +60 -0
  47. package/dist/policy/compile-reverse-policy.js.map +1 -0
  48. package/dist/policy/compile-shared-point-check.d.ts +18 -0
  49. package/dist/policy/compile-shared-point-check.d.ts.map +1 -0
  50. package/dist/policy/compile-shared-point-check.js +126 -0
  51. package/dist/policy/compile-shared-point-check.js.map +1 -0
  52. package/dist/policy/policy-model.d.ts +86 -0
  53. package/dist/policy/policy-model.d.ts.map +1 -0
  54. package/dist/policy/policy-model.js +2 -0
  55. package/dist/policy/policy-model.js.map +1 -0
  56. package/dist/policy/policy-sql.d.ts +20 -0
  57. package/dist/policy/policy-sql.d.ts.map +1 -0
  58. package/dist/policy/policy-sql.js +59 -0
  59. package/dist/policy/policy-sql.js.map +1 -0
  60. package/dist/postgres-access.tsbuildinfo +1 -0
  61. package/dist/postgres-authorization.d.ts +35 -0
  62. package/dist/postgres-authorization.d.ts.map +1 -0
  63. package/dist/postgres-authorization.js +170 -0
  64. package/dist/postgres-authorization.js.map +1 -0
  65. package/dist/postgres-response.d.ts +4 -0
  66. package/dist/postgres-response.d.ts.map +1 -0
  67. package/dist/postgres-response.js +13 -0
  68. package/dist/postgres-response.js.map +1 -0
  69. package/dist/postgres-serialization-conflict.d.ts +11 -0
  70. package/dist/postgres-serialization-conflict.d.ts.map +1 -0
  71. package/dist/postgres-serialization-conflict.js +29 -0
  72. package/dist/postgres-serialization-conflict.js.map +1 -0
  73. package/dist/postgres-tuples.d.ts +19 -0
  74. package/dist/postgres-tuples.d.ts.map +1 -0
  75. package/dist/postgres-tuples.js +135 -0
  76. package/dist/postgres-tuples.js.map +1 -0
  77. package/dist/postgres-types.d.ts +17 -0
  78. package/dist/postgres-types.d.ts.map +1 -0
  79. package/dist/postgres-types.js +10 -0
  80. package/dist/postgres-types.js.map +1 -0
  81. package/dist/prepared-check-executor.d.ts +12 -0
  82. package/dist/prepared-check-executor.d.ts.map +1 -0
  83. package/dist/prepared-check-executor.js +39 -0
  84. package/dist/prepared-check-executor.js.map +1 -0
  85. package/dist/protected-authorization-scope.d.ts +10 -0
  86. package/dist/protected-authorization-scope.d.ts.map +1 -0
  87. package/dist/protected-authorization-scope.js +41 -0
  88. package/dist/protected-authorization-scope.js.map +1 -0
  89. package/dist/relationship-schema.d.ts +11 -0
  90. package/dist/relationship-schema.d.ts.map +1 -0
  91. package/dist/relationship-schema.js +36 -0
  92. package/dist/relationship-schema.js.map +1 -0
  93. package/dist/revisioned-lookup.d.ts +13 -0
  94. package/dist/revisioned-lookup.d.ts.map +1 -0
  95. package/dist/revisioned-lookup.js +129 -0
  96. package/dist/revisioned-lookup.js.map +1 -0
  97. package/dist/transactional-access-changes.d.ts +19 -0
  98. package/dist/transactional-access-changes.d.ts.map +1 -0
  99. package/dist/transactional-access-changes.js +35 -0
  100. package/dist/transactional-access-changes.js.map +1 -0
  101. package/dist/with-protected-postgres-transaction.d.ts +22 -0
  102. package/dist/with-protected-postgres-transaction.d.ts.map +1 -0
  103. package/dist/with-protected-postgres-transaction.js +47 -0
  104. package/dist/with-protected-postgres-transaction.js.map +1 -0
  105. package/package.json +41 -4
package/BENCHMARK.md ADDED
@@ -0,0 +1,275 @@
1
+ # Experimental authorization benchmark
2
+
3
+ Measure the operation your application depends on. Point checks, fresh
4
+ resource discovery, revision-validated lookup reuse, and protected
5
+ transactions have different costs.
6
+
7
+ These are Linux development VM measurements with both engines accessed
8
+ locally. The SpiceDB comparison used the fully consistent in-memory
9
+ datastore. The figures apply to the listed fixtures and configurations.
10
+ They do not set a production latency target or compare persistent
11
+ SpiceDB deployments. The benchmarks do not include HTTP, application
12
+ writes, or serializable transaction overhead.
13
+
14
+ ## Matched point checks against SpiceDB
15
+
16
+ ```sh
17
+ CONTAINER_PER_FILE=1 npm run benchmark -w @dads-framework/postgres-access -- src/point-check-comparison.benchmark.test.ts
18
+ ```
19
+
20
+ The harness uses the same 5,000-leaf graph for each depth and engine. Both
21
+ use the public Node authorization adapters over local TCP, with the opt-in prepared-check path against PostgreSQL 16.16 and fully consistent gRPC
22
+ against the SpiceDB 1.57.0 in-memory testing datastore. It includes transport,
23
+ encoding, SQL compilation, and decoding in the timed calls. The Linux VM
24
+ has 32 vCPUs on an i9-13900KF and runs Node 24.20.0.
25
+
26
+ Each engine takes three rounds of 1,280 checks per depth and worker count,
27
+ after 30 warmups per worker. Engine order alternates and each worker checks
28
+ both granted and denied subjects. The measured mix is 75% granted, with
29
+ distinct leaf IDs and distinct denied subject IDs within each round. After
30
+ timing, an independent writer revokes and restores the membership while the
31
+ same reader must observe both changes.
32
+
33
+ The columns are the medians of the three round summaries. Latency is in
34
+ milliseconds, and throughput is completed checks per second at that worker
35
+ count.
36
+
37
+ | Arrows | Workers | Engine | p50 | p95 | p99 | Checks/s |
38
+ | -----: | ------: | :--------- | ----: | ----: | ----: | -------: |
39
+ | 2 | 1 | PostgreSQL | 0.275 | 0.702 | 1.192 | 3,054 |
40
+ | 2 | 1 | SpiceDB | 0.620 | 0.996 | 2.086 | 1,509 |
41
+ | 2 | 8 | PostgreSQL | 0.440 | 0.951 | 1.843 | 14,044 |
42
+ | 2 | 8 | SpiceDB | 1.369 | 2.269 | 3.342 | 5,678 |
43
+ | 8 | 1 | PostgreSQL | 0.184 | 0.472 | 0.873 | 4,118 |
44
+ | 8 | 1 | SpiceDB | 0.633 | 1.020 | 1.838 | 1,441 |
45
+ | 8 | 8 | PostgreSQL | 0.224 | 0.481 | 0.561 | 25,178 |
46
+ | 8 | 8 | SpiceDB | 0.814 | 1.654 | 2.116 | 8,446 |
47
+ | 16 | 1 | PostgreSQL | 0.187 | 0.362 | 0.419 | 4,476 |
48
+ | 16 | 1 | SpiceDB | 0.859 | 1.286 | 1.833 | 1,150 |
49
+ | 16 | 8 | PostgreSQL | 0.381 | 0.491 | 0.544 | 19,146 |
50
+ | 16 | 8 | SpiceDB | 1.268 | 1.986 | 2.885 | 5,925 |
51
+
52
+ At 16 arrows and eight workers, PostgreSQL's per-round p95 was 0.490,
53
+ 0.491, and 0.500 ms. An earlier implementation used the ordinary named
54
+ query and measured 0.877, 0.878, and 1.003 ms on the same fixture.
55
+ One first check per depth after seeding, using a fresh adapter, took
56
+ 6.73–8.98 ms with PostgreSQL and 2.26–4.86 ms with SpiceDB. These first
57
+ calls include any connection setup deferred until the first request and
58
+ start with the server already running.
59
+
60
+ The graph has a shared chain and one grant. The 8- and 16-arrow cases use
61
+ the bounded indexed traversal, while the 2-arrow case uses the shallow
62
+ prepared path. It exercises neither production
63
+ network hops nor all policy shapes, datastore configurations, or vendor
64
+ features. A warm point check can still exceed 1 ms, especially for wide
65
+ graphs that need the full traversal.
66
+
67
+ A separate 5,001-way branch at 16 arrows tested the exact fallback with
68
+ eight checks per mode in each of two alternating rounds. The observed
69
+ maximums were 486 and 281 ms for the ordinary prepared query, and 332 and
70
+ 281 ms with the bounded traversal plus fallback. The small fanout sample
71
+ illustrates how wide data can dominate absolute latency.
72
+
73
+ ## Opt-in lookup reuse
74
+
75
+ This run measured the public `lookupResources` call on PostgreSQL 16.16 after analyzing
76
+ the fixture tables. The application alternated between two users with distinct
77
+ authorized sets of 5,000 IDs reached over eight hops. The driver was on the
78
+ same Linux VM. The caller verified the complete ordered answers outside the
79
+ elapsed interval. Each row has 40 to 100 timed iterations after warm-up.
80
+ Batch rows measure completion of all eight operations.
81
+
82
+ | Public operation or workload | p95, ms |
83
+ | ----------------------------------------------------------------------- | -----------: |
84
+ | Fresh lookup, reuse disabled | 9.31 |
85
+ | Reuse enabled, forced miss on every call | 11.93 |
86
+ | Reuse enabled, both answers retained | 0.97 |
87
+ | Eight concurrent retained lookups | 1.05 |
88
+ | Retained lookups with an unrelated write every ten calls | 0.85 |
89
+ | Lookups with a same-namespace write every ten calls | 10.83 |
90
+ | Eight concurrent inserts to one namespace, migration absent / installed | 4.14 / 35.26 |
91
+
92
+ The recorded run had one-minute VM load 6.25. An earlier run saw a retained
93
+ lookup p95 of 0.43 ms and eight-write batch p95 of 0.88 / 2.96 ms. The revision
94
+ row is a contention point for writers. A lookup miss still evaluates the
95
+ graph, and throughput and tail latency depend on how often its namespace
96
+ changes. These retained-result timings include a primary PostgreSQL revision
97
+ read. They apply only after a successful fill for the same lookup. Fresh or
98
+ invalidated lookups still read the graph and return every requested ID.
99
+
100
+ ## Recursive userset traversal
101
+
102
+ PostgreSQL 16.16 on the same Linux VM. Baseline and candidate alternated on
103
+ the same tuple table. Each result was verified; reported p95 is the upper
104
+ sample of eight calls. Before an explicit `ANALYZE`, the baseline recursive
105
+ step for 1,024 memberships revisited about 1,050,000 tuples. The same step
106
+ with indexed frontier probes visited 1,025 frontier rows. Both arms used the same test deadline.
107
+
108
+ | Nested memberships | Point check p95 before / after | Lookup p95 before / after |
109
+ | -----------------: | -----------------------------: | ------------------------: |
110
+ | 32 | 1.42 / 0.81 ms | 0.99 / 0.63 ms |
111
+ | 1,024 | 219.14 / 3.40 ms | 206.14 / 3.00 ms |
112
+ | 10,000 | timeout / 26.34 ms | timeout / 24.36 ms |
113
+
114
+ After explicit `ANALYZE`, the baseline and candidate 10,000-edge checks
115
+ both measured about 26 ms p95, and lookups about 23 ms p95. These chains
116
+ exercise nested subject sets, separate from the permission-arrow graph
117
+ above. Each test also checked denial, batched decisions, rollback and
118
+ revocation of a middle relationship, and regrant.
119
+
120
+ Ordinary permission-arrow fixtures remained comparable. At two hops and
121
+ 500 IDs, allowed lookup p95 was 1.93 / 1.90 ms before explicit analyze.
122
+ At eight hops, 500 parent branches and 5,000 IDs it was 16.40 / 15.71 ms
123
+ before analyze. After analyze the broad fixture had similar medians
124
+ (14.98 / 15.11 ms) and more variable tails (16.40 / 19.50 ms). Each fixture
125
+ checked ordered result equality and post-commit revocation.
126
+
127
+ ## Recursive group membership soak
128
+
129
+ From a built checkout with Docker available:
130
+
131
+ ```sh
132
+ CONTAINER_PER_FILE=1 POSTGRES_ACCESS_DEEP_SOAK=1 npm run test:integration -w @dads-framework/postgres-access -- recursive-subject-set.integration.test.ts
133
+ ```
134
+
135
+ The soak traverses 32, 128, 1,024, and 10,000 group-to-group subject-set
136
+ links. Each case adds one root user membership and one terminal document
137
+ grant, for 10,002 tuples in the deepest case. These hops follow data across
138
+ instances of the same group relation. The arrow benchmarks above follow
139
+ permission references declared in the schema.
140
+
141
+ At each depth, the soak checks a point allow, ordered bulk allow and deny
142
+ decisions, and a singleton lookup. Removing a midpoint membership denies the
143
+ previously allowed point and bulk checks and empties the lookup. Restoring the
144
+ membership restores access and discovery.
145
+
146
+ The test uses isolated databases and sets `statement_timeout` to 4.9 seconds
147
+ for its fixture. This is a test setting.
148
+ The test disables autovacuum for its fixture table to control when statistics
149
+ are collected. One run leaves the freshly seeded table unanalyzed, and the
150
+ other runs `ANALYZE` after each seed. In a development VM run before the
151
+ indexed recursive traversal change, the first 10,000-hop point check hit the
152
+ 4.9-second deadline without `ANALYZE`. With indexed traversal, all four depths
153
+ passed before and after `ANALYZE` on the same VM.
154
+
155
+ ## Historical compiler measurements
156
+
157
+ These tables document changes to the benchmark fixtures over time. The
158
+ current code and benchmark commands can produce different timings.
159
+
160
+ ### Original forward and reverse baseline
161
+
162
+ This early baseline was measured on 2026-11-19 Mountain Time. Both backends ran in containers on the same Linux development VM with a 32-vCPU Intel Core i9-13900KF and 25 GiB RAM. Postgres used the `postgres:16-alpine` image. SpiceDB v1.57.0 used its in-memory datastore and fully consistent reads. Node was v24.20.0.
163
+
164
+ The fixture grants one actor access through a chain of parent relationships. A single check targets one leaf. A lookup returns every leaf the actor can see. The benchmark validates each answer and takes 15 sequential samples after one warm-up call. Timings include application-side query compilation, transport, and reading the response. They exclude schema installation and seeding. This run used a 4.9-second PostgreSQL statement deadline and a 5-second client deadline.
165
+
166
+ All figures are milliseconds, shown as median / p95.
167
+
168
+ | Arrow depth | Visible IDs | Postgres check | SpiceDB check | Postgres lookup | SpiceDB lookup |
169
+ | ----------: | ----------: | -------------: | ------------: | --------------: | --------------: |
170
+ | 2 | 500 | 1.43 / 1.67 | 1.00 / 1.33 | 1.69 / 2.97 | 4.97 / 10.70 |
171
+ | 8 | 5,000 | Timeout | 0.74 / 1.74 | 48.06 / 53.23 | 59.57 / 87.73 |
172
+ | 16 | 5,000 | Timeout | 2.35 / 3.04 | 109.85 / 128.91 | 156.05 / 215.70 |
173
+
174
+ The original forward SQL check timed out at eight and sixteen arrows while reverse resource discovery completed. Keep the backend experimental and measure check latency on the application's real policy graph before rollout. These samples do not establish production throughput, concurrent behavior, or performance with a persistent SpiceDB datastore.
175
+
176
+ To run the same fixture against the current implementation:
177
+
178
+ ```sh
179
+ CONTAINER_PER_FILE=1 npm run benchmark -w @dads-framework/postgres-access
180
+ ```
181
+
182
+ ### Forward-check follow-up
183
+
184
+ On Postgres 16.16, the original depth-8 and depth-16 statements planned in
185
+ 2.40 ms and 5.01 ms, then timed out during execution at 4.9 seconds. The
186
+ original plans pulled the arrow predicates up into nested semijoins. Disabling
187
+ JIT and setting `join_collapse_limit = 1` did not stop the timeouts. Keeping
188
+ each arrow as a correlated subplan with `OFFSET 0` left the predicates and
189
+ deadline intact. The resulting EXPLAIN ANALYZE reported 0.59 ms planning and
190
+ 0.25 ms execution at depth 8, and 1.54 ms planning and 0.56 ms execution at
191
+ depth 16.
192
+
193
+ The same application benchmark also passed under concurrent VM load. The
194
+ one-minute load rose from 36.54 to 43.62 on 32 vCPUs. The kernel's ten-second
195
+ CPU pressure was 36.47% at the start and 27.64% at the end. These are measured
196
+ contention conditions. They differ from the earlier baseline.
197
+
198
+ | Arrow depth | Visible IDs | Postgres check | SpiceDB check | Postgres lookup | SpiceDB lookup |
199
+ | ----------: | ----------: | -------------: | ------------: | --------------: | --------------: |
200
+ | 2 | 500 | 1.87 / 3.22 | 1.94 / 5.28 | 4.04 / 22.94 | 15.23 / 35.90 |
201
+ | 8 | 5,000 | 2.31 / 6.73 | 2.43 / 5.83 | 86.43 / 94.09 | 123.45 / 148.72 |
202
+ | 16 | 5,000 | 5.63 / 6.56 | 3.20 / 3.78 | 146.43 / 193.42 | 105.89 / 133.29 |
203
+
204
+ In a second run with lower CPU pressure (10.94% to 4.65%), the depth-8
205
+ Postgres check measured 2.76 / 4.40 ms and depth 16 measured 2.10 / 2.73 ms.
206
+ Lookup medians were 80.26 ms and 117.57 ms respectively.
207
+
208
+ This historical comparison changed the forward SQL only. The adapter
209
+ remains experimental. This fixture measures one chain with a shared parent
210
+ and sequential requests. Production policies may have branching relationships,
211
+ more tuples, and concurrent reads and writes.
212
+
213
+ ### Reverse-lookup follow-up
214
+
215
+ This historical change made reverse lookup drive each relationship hop from the resource IDs already
216
+ reached. A correlated lateral subquery keeps PostgreSQL from moving a broad
217
+ tuple scan ahead of the reached IDs. Each hop still returns distinct IDs and
218
+ the final result remains sorted. This comparison kept the forward compiler unchanged.
219
+
220
+ PostgreSQL 16.16 on the same 32-vCPU Linux VM. Baseline and candidate alternated
221
+ on the same database, with four warm-up and 20 timed calls per operation. Each
222
+ call checked the complete ordered ID result. Values below are p95 milliseconds.
223
+
224
+ | Shape, visible IDs | Table statistics | Allowed before / after | Denied before / after |
225
+ | -------------------------------------- | ----------------------- | ---------------------: | --------------------: |
226
+ | 8 hops, one parent branch, 5,000 IDs | Before explicit analyze | 63.77 / 6.62 | 58.14 / 3.20 |
227
+ | 16 hops, one parent branch, 5,000 IDs | Before explicit analyze | 123.65 / 8.58 | 108.98 / 3.06 |
228
+ | 8 hops, 500 parent branches, 5,000 IDs | Before explicit analyze | 4.9 s timeout / 18.32 | — / 2.28 |
229
+ | 8 hops, 500 parent branches, 5,000 IDs | After analyze | 20.02 / 15.88 | 1.20 / 1.09 |
230
+
231
+ With the broad graph the baseline timed out during its allowed warm-up before
232
+ the denied samples ran. The narrower, analyzed graphs already used efficient
233
+ plans and showed similar medians. Tail timings varied across repeats. Before
234
+ explicit analyze, the depth-16 baseline plan ran the inner chain 5,000 times.
235
+ The measured execution time fell from 150.995 ms to 3.730 ms when the query
236
+ drove the walk from the reached parent. These are synthetic planner tests,
237
+ with no throughput measurement.
238
+
239
+ ### Earlier prepared single checks
240
+
241
+ This historical comparison predates bounded linear checks and the current
242
+ limits on named ordinary statements. To run the fixture on the current checkout:
243
+
244
+ ```sh
245
+ CONTAINER_PER_FILE=1 npm run benchmark -w @dads-framework/postgres-access -- src/prepared-single-check.benchmark.test.ts
246
+ ```
247
+
248
+ This exercises public `PostgresAuthorization.check()` over local TCP against
249
+ Postgres 16.16 with an eight-connection node-postgres pool. It interleaves
250
+ unnamed and named statements across three runs of 1,280 measured checks per
251
+ mode and worker count. Each worker warms up with 30 checks before sampling.
252
+ The fixture has one shared chain per namespace, 5,000 leaves for each positive
253
+ depth, varied resource and subject IDs, and 25% denials. It proves that
254
+ revocations, re-grants, a different subject kind, and an isolated namespace
255
+ change the answer after warm-up. Timings include SQL compilation, the pool,
256
+ the round trip, and decision decoding. They exclude HTTP and cold pool
257
+ startup.
258
+
259
+ Each cell lists the p95 in milliseconds from the three runs on the Linux VM.
260
+
261
+ | Arrows | Workers | Unnamed p95 | Named p95 |
262
+ | -----: | ------: | ---------------: | ---------------: |
263
+ | 0 | 1 | 0.47, 0.40, 0.45 | 0.29, 0.31, 0.30 |
264
+ | 0 | 8 | 0.69, 0.77, 0.72 | 0.68, 0.63, 0.59 |
265
+ | 2 | 1 | 0.62, 0.63, 0.69 | 0.17, 0.16, 0.27 |
266
+ | 2 | 8 | 1.11, 1.10, 1.14 | 0.55, 0.48, 0.58 |
267
+ | 8 | 1 | 1.15, 1.15, 1.15 | 0.40, 0.29, 0.51 |
268
+ | 8 | 8 | 2.23, 2.34, 2.37 | 0.57, 0.58, 0.73 |
269
+ | 16 | 1 | 1.94, 1.96, 1.94 | 0.41, 0.42, 0.43 |
270
+ | 16 | 8 | 4.23, 4.28, 4.30 | 0.92, 0.88, 0.89 |
271
+
272
+ An earlier matching fixture on the VM gave 1.03, 1.03, and 0.98 ms named
273
+ at 16 arrows with eight workers. The recorded tail crossed 1 ms in other runs of the same fixture. New or replaced connections still incur
274
+ parse and planning costs. PostgreSQL can retain custom plans for some
275
+ queries, and production policies, tuple distributions, and transport differ.
package/LICENSE.md ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Bryton Cooper
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,213 @@
1
- # Temporary Holding Version
1
+ # `@dads-framework/postgres-access`
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Check permissions, list the resources a user can access, and commit relationship
4
+ changes alongside business data in the application's Postgres database.
5
+
6
+ ## Trusted experimental
7
+
8
+ We recommend this adapter when your app keeps its records and permission
9
+ relationships in the same Postgres database and your policy fits the
10
+ [supported model](#what-it-refuses-to-do). For example, removing a workspace
11
+ member can delete their membership row and revoke their access in one
12
+ transaction. Both changes commit together or both roll back. A check using
13
+ a fresh snapshot on the primary sees the revocation as soon as it commits. That
14
+ removes the authorization outbox, its delivery worker, and the interval
15
+ during which a committed revoke would still be waiting for delivery.
16
+
17
+ Its access decisions and visible resource lists have been checked against
18
+ SpiceDB. The [live transaction tests](./src/protected-transaction.integration.test.ts)
19
+ cover revocation and rollback. The [graph tests](./src/recursive-subject-set.integration.test.ts)
20
+ also exercise nested memberships up to 10,000 links.
21
+
22
+ Start with one protected operation and test a grant, a denial and a
23
+ revocation with your own policy. Measure checks and lists while permissions
24
+ are changing. Sustained production performance under that mix is still open.
25
+ See the [benchmark results](./BENCHMARK.md) for measured workloads.
26
+
27
+ ## Protected writes
28
+
29
+ Use `withProtectedPostgresTransaction({ database, authorization }, work)`
30
+ when a decision protects a write. The helper opens a serializable Drizzle
31
+ transaction and passes `{ tx, authorization }` to the callback. Check access
32
+ again inside the callback, even if the route already authorized the request.
33
+ Use these same handles for the application writes and relationship changes. Await all work before leaving the callback.
34
+ The authorization handle expires on return or error.
35
+
36
+ To join an existing transaction, pass `{ transaction: tx, authorization }`.
37
+ The helper verifies that it is already serializable and uses the same
38
+ transaction. The caller still owns commit and rollback. Propagate failures so
39
+ the outer transaction can roll back. The helper does not create a savepoint.
40
+
41
+ A PostgreSQL serialization failure surfaces as `PostgresSerializationConflict`
42
+ with code `POSTGRES_CONFLICT` and `retryable: true`. A caller that owns the
43
+ outer commit can use `readPostgresSerializationConflict(error)` to classify
44
+ a failure raised there. Retry the entire application transaction if retrying
45
+ is appropriate. The helper invokes the callback at most once per call.
46
+
47
+ Serializable isolation makes the commit consistent with a serial ordering of
48
+ transactions. A revoke committed before the permission check's transaction
49
+ snapshot is visible to that check. An overlapping revoke may serialize after
50
+ the protected write. If an operation requires revocation to take precedence
51
+ over an overlapping write, coordinate both operations through an application
52
+ lock or equivalent ordering mechanism. For reads and explicit tuple changes
53
+ in an existing transaction, use `inTransaction` or `inDrizzleTransaction`.
54
+
55
+ ## Try it
56
+
57
+ ```ts
58
+ import {
59
+ AlreadyAppliedAccessChanges,
60
+ PostgresAuthorization,
61
+ TransactionalAccessChanges,
62
+ relationshipSchemaMigration,
63
+ } from "@dads-framework/postgres-access";
64
+ import {
65
+ authorizationKinds,
66
+ DEFAULT_AUTHORIZATION_GUARD_MARKS,
67
+ GuardedAuthorization,
68
+ } from "@dads-framework/authorization";
69
+
70
+ // Install relationshipSchemaMigration.sql through the application's migration runner.
71
+ // connection and model come from the application composition root.
72
+ const backend = new PostgresAuthorization({
73
+ model,
74
+ namespace: "app",
75
+ executor: connection.pool,
76
+ });
77
+ const authorization = new GuardedAuthorization(
78
+ backend,
79
+ DEFAULT_AUTHORIZATION_GUARD_MARKS,
80
+ authorizationKinds(model),
81
+ );
82
+ const changes = new TransactionalAccessChanges(backend, connection.drizzle);
83
+ const afterCommit = new AlreadyAppliedAccessChanges();
84
+ ```
85
+
86
+ Bind `authorization` as the authorization port, `changes` as the enqueue port, and `afterCommit` as the after-commit dispatcher. Writers keep calling `enqueue(entries, tx)`; the tuples and the business row commit or roll back together. Use `backend.inTransaction(client)` for a read or explicit tuple operation that must see the caller's pending writes. Use `backend.inDrizzleTransaction(tx)` when the application owns a Drizzle transaction.
87
+
88
+ ## Use it
89
+
90
+ Choose Postgres for an app that already uses Postgres and can keep relationship facts beside its data. Install the relationship schema through the app's migration runner. Configure a stable namespace for this model, and select the backend at application composition. Use the same model for Postgres policy compilation and HTTP scope planning.
91
+
92
+ In Postgres mode, start neither the access-change projector nor the SpiceDB migration runner. Successful writes return an empty consistency token. Data visibility follows the caller's Postgres transaction. The after-commit dispatcher is a no-op because committed facts are already visible. Keep any application locks that coordinate work beyond projecting authorization facts.
93
+
94
+ Choose the backend based on the model features the application needs, its
95
+ transaction requirements, and measurements with its own data and traffic.
96
+ The [SpiceDB adapter](../authorization/README.md) provides a separate graph
97
+ store, with a Postgres outbox for writes.
98
+
99
+ ## What it refuses to do
100
+
101
+ Compilation rejects missing relation or permission targets, empty expressions, and local permission cycles. Cross-entity permission cycles are unsupported by the SQL engine. Each arrow needs one direct target entity type. Permission checks require a concrete subject; relationship writes can contain wildcard and subject-set tuples.
102
+
103
+ The enqueue port rejects a database handle in place of an application transaction. Its transaction-bound changes are exact tuple writes or deletes. A broad revocation sweep needs its filters passed to a transaction-bound adapter if it must commit with the business update.
104
+
105
+ ## Contract
106
+
107
+ `PostgresAuthorization` implements the authorization port's checks, ordered bulk checks, discovery, relationship writes and filtered deletes, direct-subject listing, and relationship existence reads. Unknown permission names give denied checks and empty lookup results. Invalid tuple writes and failed storage operations reject.
108
+
109
+ For operations on a root adapter, `queryTimeoutMs` defaults to 5,000 ms. It
110
+ is a client deadline for executors that honor node-postgres query options.
111
+ Configure a server-side `statement_timeout` in the application as needed.
112
+ Drizzle transaction operations use the application's database settings.
113
+ Connection management and schema migration remain application-owned.
114
+
115
+ With Docker available, run the integration suite from a built checkout:
116
+
117
+ ```sh
118
+ CONTAINER_PER_FILE=1 npm run test:integration -w @dads-framework/postgres-access
119
+ ```
120
+
121
+ The [benchmark notes](./BENCHMARK.md) explain which read paths were measured.
122
+
123
+ ### Optimize point checks
124
+
125
+ For a direct node-postgres pool, opt in by passing
126
+ `executor: preparePostgresChecks(connection.pool)`. Share the wrapper across
127
+ authorization namespaces. The wrapper can admit up to 64 distinct SQL shapes
128
+ of at most 4 KiB each and 32 KiB total per pool lifetime. Other shapes execute
129
+ unnamed, as do bulk checks, lookups, and writes. PostgreSQL decides when each
130
+ connection can reuse a generic plan. New connections and the first checks on
131
+ each connection still pay planning costs.
132
+
133
+ Checks always read the facts visible to the executing transaction. The wrapper
134
+ stores statement names and SQL shapes, and PostgreSQL stores plans per
135
+ connection. Use the ordinary executor for connections through poolers that do
136
+ not support protocol-level named statements. Drizzle-bound transactions
137
+ continue using their own execution path.
138
+
139
+ Prepared single checks can fuse a chain of four to 32 arrows ending in one
140
+ relation into an indexed recursive query. The query preserves wildcard grants
141
+ and recursive subject sets. If the bounded traversal completes without a
142
+ match, it denies. If the traversal reaches its bound without deciding, the
143
+ adapter runs the full check unnamed with the remaining query deadline.
144
+ Small ordinary point checks may also use named statements when their policy
145
+ has at most two arrows and four total relation or arrow references.
146
+ Larger point checks, bulk checks, and Drizzle transactions run unnamed.
147
+ A bulk branch with four to 32 linear arrows evaluates the complete
148
+ permission once per distinct subject and joins the results to the original
149
+ request ordinals. Mixed permissions, denials, and duplicate request rows
150
+ keep their order in the same SQL statement.
151
+ If a point policy expands beyond 64 KiB of forward SQL, the adapter compiles
152
+ a single Boolean query that shares repeated permission expressions and matches
153
+ the requested resource in PostgreSQL. It reads current relationship facts
154
+ under the configured query deadline.
155
+
156
+ ### Reuse large lookup results
157
+
158
+ By default, `lookupResources` evaluates the current relationship graph on
159
+ every call. For repeated lookups in a read-mostly service, an application can
160
+ opt in to reusing immutable ID lists. A reused list still makes a fresh
161
+ database round trip for every call. Transaction-bound adapters always
162
+ evaluate within their transaction.
163
+
164
+ Install `lookupRevisionSchemaMigration` after `relationshipSchemaMigration`
165
+ in the application's normal migration runner. Apply the optional migration
166
+ in one transaction as the migration owner. Existing v1 installations can
167
+ continue without it. This mode requires the durable, unpartitioned
168
+ `public.dad_authorization_relationship` table without row-level security.
169
+
170
+ Use a direct node-postgres 8.21+ pool connected to one primary. Configure its
171
+ role and search path once and keep the pool out of session-routing middleware.
172
+ The runtime role may use the tuple table and read revision metadata. Do not
173
+ grant runtime roles owner membership, schema DDL, revision writes, sequence
174
+ usage, or trigger privileges. For example, grant an existing runtime role:
175
+
176
+ ```sql
177
+ GRANT SELECT, INSERT, UPDATE, DELETE
178
+ ON public.dad_authorization_relationship TO app_runtime;
179
+ GRANT USAGE ON SCHEMA dad_lookup_revision TO app_runtime;
180
+ GRANT SELECT ON dad_lookup_revision.epoch, dad_lookup_revision.namespace
181
+ TO app_runtime;
182
+ ```
183
+
184
+ ```ts
185
+ const authorization = new PostgresAuthorization({
186
+ model,
187
+ namespace: "workspace",
188
+ executor: connection.pool,
189
+ reuseLookupResultsOn: connection.pool,
190
+ });
191
+ ```
192
+
193
+ You can pass `preparePostgresChecks(connection.pool)` as the executor with the
194
+ same pool. Write and read-only transaction clients do not qualify. Remove the
195
+ option before rolling the optional migration back. Failed validation rejects
196
+ the operation and clears retained answers. Table-wide tuple `SELECT` is checked
197
+ for every reuse, so revoking it prevents reuse even if revision metadata is
198
+ still readable.
199
+
200
+ The migration marks each touched namespace in the same transaction as
201
+ INSERT, DELETE, or UPDATE. Moving a tuple marks both namespaces, and
202
+ TRUNCATE changes a shared epoch. A miss reads the ID list and its revision in
203
+ one statement. Each reuse, including coalesced empty lists, validates its
204
+ revision against the primary after the call begins. Calls that overlap a
205
+ commit may observe the snapshot before or after it.
206
+
207
+ The application still owns database administration. Keep the triggers
208
+ installed for all writers, including direct SQL. Stop reuse while privileged
209
+ maintenance could bypass them. Reapply the migration to rotate the
210
+ installation revision before resuming. Recreate the authorization instances
211
+ if their pool changes authority or is restored. The cache retains a bounded
212
+ number of lists and IDs. Same-namespace writers share a revision row, so
213
+ concurrent writes may slow down. See the [benchmark](./BENCHMARK.md).
@@ -0,0 +1,9 @@
1
+ import { type AccessModel } from "@dads-framework/access";
2
+ import type { AuthorizationModelDefinition } from "./policy/policy-model.js";
3
+ export type CompiledAccessPolicy = {
4
+ readonly model: AuthorizationModelDefinition;
5
+ /** The engine's permission name for an authored permission or direct relation. */
6
+ permissionName(entity: string, name: string): string | undefined;
7
+ };
8
+ export declare function compileAccessPolicy(access: AccessModel): CompiledAccessPolicy;
9
+ //# sourceMappingURL=compile-access-policy.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"compile-access-policy.d.ts","sourceRoot":"","sources":["../src/compile-access-policy.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,KAAK,WAAW,EACjB,MAAM,wBAAwB,CAAC;AAChC,OAAO,KAAK,EACV,4BAA4B,EAG7B,MAAM,0BAA0B,CAAC;AAOlC,MAAM,MAAM,oBAAoB,GAAG;IACjC,QAAQ,CAAC,KAAK,EAAE,4BAA4B,CAAC;IAC7C,kFAAkF;IAClF,cAAc,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAAC;CAClE,CAAC;AAEF,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,WAAW,GAAG,oBAAoB,CA0B7E"}
@@ -0,0 +1,77 @@
1
+ import { emitAccessIr, } from "@dads-framework/access";
2
+ import { lowerPermissions, } from "./lower-permissions.js";
3
+ export function compileAccessPolicy(access) {
4
+ const definitions = emitAccessIr(access);
5
+ const byName = new Map(definitions.map((entry) => [entry.wireName, entry]));
6
+ const generated = new Map(definitions.map((entry) => [entry.wireName, rolePermissions(entry)]));
7
+ const model = {
8
+ entities: definitions.map((entry, index) => ({
9
+ wireName: entry.wireName,
10
+ sourceName: `entity_${index}`,
11
+ })),
12
+ relations: definitions.flatMap(lowerRelations),
13
+ permissions: definitions.flatMap((entry) => compiledPermissions(entry, { byName, generated })),
14
+ lifecycle: [],
15
+ };
16
+ return {
17
+ model,
18
+ permissionName: (entity, name) => {
19
+ const definition = byName.get(entity);
20
+ if (definition?.permissions.some((entry) => entry.name === name))
21
+ return name;
22
+ return generated.get(entity)?.get(name);
23
+ },
24
+ };
25
+ }
26
+ function lowerRelations(definition) {
27
+ return definition.roles.map((role, index) => ({
28
+ authority: "system",
29
+ entity: definition.wireName,
30
+ sourceName: `relation_${index}`,
31
+ wireName: role.name,
32
+ targets: role.subjects.map((subject) => {
33
+ if (subject.kind === "userset") {
34
+ return {
35
+ kind: "subject-set",
36
+ entity: subject.wireName,
37
+ relation: subject.relation,
38
+ };
39
+ }
40
+ return {
41
+ kind: subject.kind === "type" ? "entity" : "wildcard",
42
+ entity: subject.wireName,
43
+ };
44
+ }),
45
+ }));
46
+ }
47
+ function compiledPermissions(definition, context) {
48
+ const authored = lowerPermissions(definition, context);
49
+ const wrappers = context.generated.get(definition.wireName) ?? new Map();
50
+ return [
51
+ ...authored,
52
+ ...[...wrappers].map(([relation, wireName], index) => ({
53
+ entity: definition.wireName,
54
+ sourceName: `relation_permission_${index}`,
55
+ wireName,
56
+ expression: { kind: "relation", relation },
57
+ })),
58
+ ];
59
+ }
60
+ function rolePermissions(definition) {
61
+ const names = new Set([
62
+ ...definition.roles.map((entry) => entry.name),
63
+ ...definition.permissions.map((entry) => entry.name),
64
+ ]);
65
+ const wrappers = new Map();
66
+ let suffix = 0;
67
+ for (const role of definition.roles) {
68
+ let generated;
69
+ do {
70
+ generated = `dads_relation_${suffix}`;
71
+ suffix += 1;
72
+ } while (names.has(generated));
73
+ wrappers.set(role.name, generated);
74
+ }
75
+ return wrappers;
76
+ }
77
+ //# sourceMappingURL=compile-access-policy.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"compile-access-policy.js","sourceRoot":"","sources":["../src/compile-access-policy.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,YAAY,GAGb,MAAM,wBAAwB,CAAC;AAOhC,OAAO,EACL,gBAAgB,GAEjB,MAAM,wBAAwB,CAAC;AAQhC,MAAM,UAAU,mBAAmB,CAAC,MAAmB;IACrD,MAAM,WAAW,GAAG,YAAY,CAAC,MAAM,CAAC,CAAC;IACzC,MAAM,MAAM,GAAG,IAAI,GAAG,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC;IAC5E,MAAM,SAAS,GAAG,IAAI,GAAG,CACvB,WAAW,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,QAAQ,EAAE,eAAe,CAAC,KAAK,CAAC,CAAC,CAAC,CACrE,CAAC;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C;KACrD,CAAC,CAAC;IACH,MAAM,QAAQ,GAAG,IAAI,GAAG,EAAkB,CAAC;IAC3C,IAAI,MAAM,GAAG,CAAC,CAAC;IACf,KAAK,MAAM,IAAI,IAAI,UAAU,CAAC,KAAK,EAAE,CAAC;QACpC,IAAI,SAAiB,CAAC;QACtB,GAAG,CAAC;YACF,SAAS,GAAG,iBAAiB,MAAM,EAAE,CAAC;YACtC,MAAM,IAAI,CAAC,CAAC;QACd,CAAC,QAAQ,KAAK,CAAC,GAAG,CAAC,SAAS,CAAC,EAAE;QAC/B,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC;IACrC,CAAC;IACD,OAAO,QAAQ,CAAC;AAClB,CAAC"}
@@ -0,0 +1,5 @@
1
+ import type { DrizzleHandle } from "@dads-framework/postgres";
2
+ import type { PostgresAccessExecutor } from "./postgres-authorization.js";
3
+ /** Bridge compiled, numbered placeholders to the transaction's bound Drizzle parameters. */
4
+ export declare function transactionExecutor(transaction: Pick<DrizzleHandle, "execute">): PostgresAccessExecutor;
5
+ //# sourceMappingURL=drizzle-executor.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"drizzle-executor.d.ts","sourceRoot":"","sources":["../src/drizzle-executor.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AAE9D,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAC;AAE1E,4FAA4F;AAC5F,wBAAgB,mBAAmB,CACjC,WAAW,EAAE,IAAI,CAAC,aAAa,EAAE,SAAS,CAAC,GAC1C,sBAAsB,CAMxB"}
@@ -0,0 +1,25 @@
1
+ import { sql } from "drizzle-orm";
2
+ /** Bridge compiled, numbered placeholders to the transaction's bound Drizzle parameters. */
3
+ export function transactionExecutor(transaction) {
4
+ return {
5
+ query(query) {
6
+ return transaction.execute(parameterized(query));
7
+ },
8
+ };
9
+ }
10
+ function parameterized(query) {
11
+ const parts = [];
12
+ let start = 0;
13
+ for (const match of query.text.matchAll(/\$(\d+)/g)) {
14
+ const ordinal = Number(match[1]);
15
+ if (ordinal < 1 || ordinal > (query.values?.length ?? 0)) {
16
+ throw new Error("Postgres authorization SQL references a missing parameter");
17
+ }
18
+ parts.push(sql.raw(query.text.slice(start, match.index)));
19
+ parts.push(sql `${sql.param(query.values?.[ordinal - 1])}`);
20
+ start = match.index + match[0].length;
21
+ }
22
+ parts.push(sql.raw(query.text.slice(start)));
23
+ return sql.join(parts);
24
+ }
25
+ //# sourceMappingURL=drizzle-executor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"drizzle-executor.js","sourceRoot":"","sources":["../src/drizzle-executor.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,GAAG,EAAY,MAAM,aAAa,CAAC;AAG5C,4FAA4F;AAC5F,MAAM,UAAU,mBAAmB,CACjC,WAA2C;IAE3C,OAAO;QACL,KAAK,CAAC,KAAoB;YACxB,OAAO,WAAW,CAAC,OAAO,CAAc,aAAa,CAAC,KAAK,CAAC,CAAC,CAAC;QAChE,CAAC;KACF,CAAC;AACJ,CAAC;AAED,SAAS,aAAa,CAAC,KAAoB;IACzC,MAAM,KAAK,GAAU,EAAE,CAAC;IACxB,IAAI,KAAK,GAAG,CAAC,CAAC;IACd,KAAK,MAAM,KAAK,IAAI,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,UAAU,CAAC,EAAE,CAAC;QACpD,MAAM,OAAO,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;QACjC,IAAI,OAAO,GAAG,CAAC,IAAI,OAAO,GAAG,CAAC,KAAK,CAAC,MAAM,EAAE,MAAM,IAAI,CAAC,CAAC,EAAE,CAAC;YACzD,MAAM,IAAI,KAAK,CACb,2DAA2D,CAC5D,CAAC;QACJ,CAAC;QACD,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAA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