@farukada/aws-langgraph-dynamodb-ts 1.0.0-rc.1 → 1.0.0-rc.2

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 (324) hide show
  1. package/README.md +1621 -288
  2. package/dist/backfill/backfill.d.ts +168 -0
  3. package/dist/backfill/backfill.js +393 -0
  4. package/dist/checkpointer/actions/delete-thread.d.ts +44 -4
  5. package/dist/checkpointer/actions/delete-thread.js +56 -22
  6. package/dist/checkpointer/actions/get-tuple.d.ts +29 -5
  7. package/dist/checkpointer/actions/get-tuple.js +41 -13
  8. package/dist/checkpointer/actions/list.d.ts +42 -10
  9. package/dist/checkpointer/actions/list.js +86 -57
  10. package/dist/checkpointer/actions/put-writes.d.ts +41 -9
  11. package/dist/checkpointer/actions/put-writes.js +62 -48
  12. package/dist/checkpointer/actions/put.d.ts +82 -10
  13. package/dist/checkpointer/actions/put.js +166 -44
  14. package/dist/checkpointer/internal/delta-history.d.ts +112 -0
  15. package/dist/checkpointer/internal/delta-history.js +252 -0
  16. package/dist/checkpointer/internal/listing.d.ts +149 -0
  17. package/dist/checkpointer/internal/listing.js +245 -0
  18. package/dist/checkpointer/internal/parse.d.ts +262 -0
  19. package/dist/checkpointer/internal/parse.js +372 -0
  20. package/dist/checkpointer/internal/pending-writes.d.ts +275 -0
  21. package/dist/checkpointer/internal/pending-writes.js +588 -0
  22. package/dist/checkpointer/internal/read.d.ts +130 -0
  23. package/dist/checkpointer/internal/read.js +264 -0
  24. package/dist/checkpointer/internal/rows.d.ts +571 -0
  25. package/dist/checkpointer/internal/rows.js +834 -0
  26. package/dist/checkpointer/internal/setup.d.ts +42 -21
  27. package/dist/checkpointer/internal/setup.js +65 -31
  28. package/dist/checkpointer/saver.d.ts +242 -42
  29. package/dist/checkpointer/saver.js +257 -53
  30. package/dist/checkpointer/types.d.ts +37 -44
  31. package/dist/checkpointer/types.js +10 -0
  32. package/dist/factory/factory.d.ts +120 -11
  33. package/dist/factory/factory.js +195 -16
  34. package/dist/factory/types.d.ts +23 -4
  35. package/dist/factory/types.js +8 -0
  36. package/dist/history/actions/add-messages.d.ts +30 -2
  37. package/dist/history/actions/add-messages.js +37 -57
  38. package/dist/history/actions/clear.d.ts +46 -4
  39. package/dist/history/actions/clear.js +64 -15
  40. package/dist/history/actions/get-messages.d.ts +41 -0
  41. package/dist/history/actions/get-messages.js +94 -32
  42. package/dist/history/actions/list-sessions.d.ts +52 -10
  43. package/dist/history/actions/list-sessions.js +141 -38
  44. package/dist/history/actions/reconcile-count.d.ts +41 -8
  45. package/dist/history/actions/reconcile-count.js +44 -57
  46. package/dist/history/chat-message-history.d.ts +200 -38
  47. package/dist/history/chat-message-history.js +218 -51
  48. package/dist/history/internal/append.d.ts +212 -0
  49. package/dist/history/internal/append.js +500 -0
  50. package/dist/history/internal/message-read.d.ts +84 -0
  51. package/dist/history/internal/message-read.js +204 -0
  52. package/dist/history/internal/parse.d.ts +153 -0
  53. package/dist/history/internal/parse.js +252 -0
  54. package/dist/history/internal/rows.d.ts +195 -0
  55. package/dist/history/internal/rows.js +250 -0
  56. package/dist/history/internal/session.d.ts +331 -0
  57. package/dist/history/internal/session.js +628 -0
  58. package/dist/history/internal/setup.d.ts +52 -19
  59. package/dist/history/internal/setup.js +90 -27
  60. package/dist/history/session-adapter.d.ts +95 -6
  61. package/dist/history/session-adapter.js +99 -8
  62. package/dist/history/types.d.ts +61 -31
  63. package/dist/history/types.js +10 -0
  64. package/dist/index.d.ts +38 -14
  65. package/dist/index.js +31 -12
  66. package/dist/shared/adapter.d.ts +135 -0
  67. package/dist/shared/adapter.js +143 -0
  68. package/dist/shared/clock.d.ts +48 -4
  69. package/dist/shared/clock.js +51 -4
  70. package/dist/shared/codec/codec.d.ts +275 -9
  71. package/dist/shared/codec/codec.js +394 -19
  72. package/dist/shared/codec/compression.d.ts +43 -6
  73. package/dist/shared/codec/compression.js +52 -11
  74. package/dist/shared/codec/json-serde.d.ts +76 -3
  75. package/dist/shared/codec/json-serde.js +181 -7
  76. package/dist/shared/codec/s3/client-types.d.ts +20 -1
  77. package/dist/shared/codec/s3/client-types.js +20 -1
  78. package/dist/shared/codec/s3/client.d.ts +35 -8
  79. package/dist/shared/codec/s3/client.js +61 -10
  80. package/dist/shared/codec/s3/config.d.ts +226 -22
  81. package/dist/shared/codec/s3/config.js +274 -24
  82. package/dist/shared/codec/s3/lifecycle.d.ts +163 -11
  83. package/dist/shared/codec/s3/lifecycle.js +328 -36
  84. package/dist/shared/codec/s3/offloader.d.ts +390 -19
  85. package/dist/shared/codec/s3/offloader.js +590 -50
  86. package/dist/shared/concurrency.d.ts +40 -3
  87. package/dist/shared/concurrency.js +55 -7
  88. package/dist/shared/dynamodb/abort.d.ts +45 -7
  89. package/dist/shared/dynamodb/abort.js +46 -14
  90. package/dist/shared/dynamodb/batch-write.d.ts +77 -13
  91. package/dist/shared/dynamodb/batch-write.js +146 -26
  92. package/dist/shared/dynamodb/cancellation.d.ts +121 -3
  93. package/dist/shared/dynamodb/cancellation.js +147 -2
  94. package/dist/shared/dynamodb/client.d.ts +159 -12
  95. package/dist/shared/dynamodb/client.js +135 -10
  96. package/dist/shared/dynamodb/idempotent-write.d.ts +551 -0
  97. package/dist/shared/dynamodb/idempotent-write.js +593 -0
  98. package/dist/shared/dynamodb/paginate.d.ts +105 -8
  99. package/dist/shared/dynamodb/paginate.js +175 -6
  100. package/dist/shared/dynamodb/partition-delete.d.ts +181 -16
  101. package/dist/shared/dynamodb/partition-delete.js +312 -43
  102. package/dist/shared/dynamodb/recency-index.d.ts +231 -0
  103. package/dist/shared/dynamodb/recency-index.js +377 -0
  104. package/dist/shared/dynamodb/retry.d.ts +265 -10
  105. package/dist/shared/dynamodb/retry.js +426 -20
  106. package/dist/shared/dynamodb/table-schema.d.ts +190 -0
  107. package/dist/shared/dynamodb/table-schema.js +209 -0
  108. package/dist/shared/errors/base-error.d.ts +174 -8
  109. package/dist/shared/errors/base-error.js +154 -7
  110. package/dist/shared/errors/boundary.d.ts +63 -10
  111. package/dist/shared/errors/boundary.js +110 -13
  112. package/dist/shared/errors/classify.d.ts +97 -0
  113. package/dist/shared/errors/classify.js +257 -0
  114. package/dist/shared/errors/error-code.d.ts +76 -1
  115. package/dist/shared/errors/error-code.js +83 -1
  116. package/dist/shared/errors/errors.d.ts +157 -58
  117. package/dist/shared/errors/errors.js +218 -93
  118. package/dist/shared/logging/logger.d.ts +63 -1
  119. package/dist/shared/logging/logger.js +97 -2
  120. package/dist/shared/logging/redaction.d.ts +86 -6
  121. package/dist/shared/logging/redaction.js +265 -24
  122. package/dist/shared/logging/secret-patterns.d.ts +136 -24
  123. package/dist/shared/logging/secret-patterns.js +165 -30
  124. package/dist/shared/logging/truncate.d.ts +197 -0
  125. package/dist/shared/logging/truncate.js +231 -0
  126. package/dist/shared/options.d.ts +52 -5
  127. package/dist/shared/options.js +9 -0
  128. package/dist/shared/ulid.d.ts +71 -14
  129. package/dist/shared/ulid.js +77 -14
  130. package/dist/shared/validation/collaborators.d.ts +141 -0
  131. package/dist/shared/validation/collaborators.js +188 -0
  132. package/dist/shared/validation/option-shape.d.ts +89 -0
  133. package/dist/shared/validation/option-shape.js +113 -0
  134. package/dist/shared/validation/options.d.ts +142 -5
  135. package/dist/shared/validation/options.js +284 -46
  136. package/dist/shared/validation/primitives.d.ts +287 -24
  137. package/dist/shared/validation/primitives.js +347 -42
  138. package/dist/shared/validation/ttl.d.ts +61 -12
  139. package/dist/shared/validation/ttl.js +102 -22
  140. package/dist/store/actions/list-namespaces.d.ts +76 -5
  141. package/dist/store/actions/list-namespaces.js +160 -22
  142. package/dist/store/actions/put.d.ts +33 -7
  143. package/dist/store/actions/put.js +53 -71
  144. package/dist/store/actions/reconcile-vector-index.d.ts +28 -8
  145. package/dist/store/actions/reconcile-vector-index.js +33 -13
  146. package/dist/store/actions/search.d.ts +34 -5
  147. package/dist/store/actions/search.js +52 -20
  148. package/dist/store/internal/batch-plan.d.ts +24 -9
  149. package/dist/store/internal/batch-plan.js +91 -34
  150. package/dist/store/internal/filter.d.ts +36 -2
  151. package/dist/store/internal/filter.js +66 -14
  152. package/dist/store/internal/get-item.d.ts +45 -0
  153. package/dist/store/internal/get-item.js +115 -0
  154. package/dist/store/internal/item-write.d.ts +230 -0
  155. package/dist/store/internal/item-write.js +463 -0
  156. package/dist/store/internal/parse.d.ts +225 -0
  157. package/dist/store/internal/parse.js +350 -0
  158. package/dist/store/internal/rows.d.ts +355 -0
  159. package/dist/store/internal/rows.js +447 -0
  160. package/dist/store/internal/semantic-search.d.ts +146 -12
  161. package/dist/store/internal/semantic-search.js +317 -15
  162. package/dist/store/internal/setup.d.ts +86 -21
  163. package/dist/store/internal/setup.js +209 -26
  164. package/dist/store/internal/table-search.d.ts +100 -0
  165. package/dist/store/internal/table-search.js +213 -0
  166. package/dist/store/internal/vector-index.d.ts +247 -0
  167. package/dist/store/internal/vector-index.js +546 -0
  168. package/dist/store/store.d.ts +258 -33
  169. package/dist/store/store.js +309 -53
  170. package/dist/store/types.d.ts +74 -28
  171. package/dist/store/types.js +13 -0
  172. package/dist/store/vector-backend.d.ts +64 -3
  173. package/dist/store/vector-backend.js +15 -0
  174. package/package.json +41 -25
  175. package/dist/checkpointer/internal/assemble.d.ts +0 -17
  176. package/dist/checkpointer/internal/assemble.js +0 -38
  177. package/dist/checkpointer/internal/checkpoint-write-verify.d.ts +0 -24
  178. package/dist/checkpointer/internal/checkpoint-write-verify.js +0 -67
  179. package/dist/checkpointer/internal/configurable.d.ts +0 -12
  180. package/dist/checkpointer/internal/configurable.js +0 -24
  181. package/dist/checkpointer/internal/fetch.d.ts +0 -19
  182. package/dist/checkpointer/internal/fetch.js +0 -88
  183. package/dist/checkpointer/internal/filter-match.d.ts +0 -13
  184. package/dist/checkpointer/internal/filter-match.js +0 -15
  185. package/dist/checkpointer/internal/item-reader.d.ts +0 -66
  186. package/dist/checkpointer/internal/item-reader.js +0 -113
  187. package/dist/checkpointer/internal/item-writer.d.ts +0 -35
  188. package/dist/checkpointer/internal/item-writer.js +0 -107
  189. package/dist/checkpointer/internal/keys.d.ts +0 -41
  190. package/dist/checkpointer/internal/keys.js +0 -117
  191. package/dist/checkpointer/internal/list-scope.d.ts +0 -61
  192. package/dist/checkpointer/internal/list-scope.js +0 -108
  193. package/dist/checkpointer/internal/pending-sends.d.ts +0 -13
  194. package/dist/checkpointer/internal/pending-sends.js +0 -29
  195. package/dist/checkpointer/internal/query.d.ts +0 -21
  196. package/dist/checkpointer/internal/query.js +0 -42
  197. package/dist/checkpointer/internal/regular-write.d.ts +0 -28
  198. package/dist/checkpointer/internal/regular-write.js +0 -66
  199. package/dist/checkpointer/internal/special-write-cas.d.ts +0 -29
  200. package/dist/checkpointer/internal/special-write-cas.js +0 -104
  201. package/dist/checkpointer/internal/special-write-cleanup.d.ts +0 -23
  202. package/dist/checkpointer/internal/special-write-cleanup.js +0 -50
  203. package/dist/checkpointer/internal/special-write-verify.d.ts +0 -53
  204. package/dist/checkpointer/internal/special-write-verify.js +0 -80
  205. package/dist/checkpointer/internal/stored-channels.d.ts +0 -31
  206. package/dist/checkpointer/internal/stored-channels.js +0 -70
  207. package/dist/checkpointer/internal/validation.d.ts +0 -18
  208. package/dist/checkpointer/internal/validation.js +0 -40
  209. package/dist/checkpointer/internal/write-guard.d.ts +0 -20
  210. package/dist/checkpointer/internal/write-guard.js +0 -48
  211. package/dist/checkpointer/internal/write-index.d.ts +0 -36
  212. package/dist/checkpointer/internal/write-index.js +0 -41
  213. package/dist/history/internal/append-saga.d.ts +0 -25
  214. package/dist/history/internal/append-saga.js +0 -79
  215. package/dist/history/internal/compensation.d.ts +0 -25
  216. package/dist/history/internal/compensation.js +0 -92
  217. package/dist/history/internal/item-mapper.d.ts +0 -9
  218. package/dist/history/internal/item-mapper.js +0 -27
  219. package/dist/history/internal/keys.d.ts +0 -16
  220. package/dist/history/internal/keys.js +0 -48
  221. package/dist/history/internal/message-chunker.d.ts +0 -13
  222. package/dist/history/internal/message-chunker.js +0 -67
  223. package/dist/history/internal/message-transaction.d.ts +0 -25
  224. package/dist/history/internal/message-transaction.js +0 -61
  225. package/dist/history/internal/message-window.d.ts +0 -17
  226. package/dist/history/internal/message-window.js +0 -49
  227. package/dist/history/internal/query.d.ts +0 -23
  228. package/dist/history/internal/query.js +0 -39
  229. package/dist/history/internal/session-count.d.ts +0 -47
  230. package/dist/history/internal/session-count.js +0 -115
  231. package/dist/history/internal/session-title.d.ts +0 -19
  232. package/dist/history/internal/session-title.js +0 -43
  233. package/dist/history/internal/session-update.d.ts +0 -27
  234. package/dist/history/internal/session-update.js +0 -69
  235. package/dist/history/internal/title-generator.d.ts +0 -12
  236. package/dist/history/internal/title-generator.js +0 -41
  237. package/dist/history/internal/ttl-anchor.d.ts +0 -24
  238. package/dist/history/internal/ttl-anchor.js +0 -38
  239. package/dist/history/internal/validation.d.ts +0 -25
  240. package/dist/history/internal/validation.js +0 -53
  241. package/dist/shared/codec/descriptor-keys.d.ts +0 -12
  242. package/dist/shared/codec/descriptor-keys.js +0 -14
  243. package/dist/shared/codec/encode.d.ts +0 -13
  244. package/dist/shared/codec/encode.js +0 -43
  245. package/dist/shared/codec/payload-loss.d.ts +0 -12
  246. package/dist/shared/codec/payload-loss.js +0 -38
  247. package/dist/shared/codec/s3/adapter-config.d.ts +0 -13
  248. package/dist/shared/codec/s3/adapter-config.js +0 -22
  249. package/dist/shared/codec/s3/bounded-body.d.ts +0 -14
  250. package/dist/shared/codec/s3/bounded-body.js +0 -47
  251. package/dist/shared/codec/s3/delete.d.ts +0 -7
  252. package/dist/shared/codec/s3/delete.js +0 -28
  253. package/dist/shared/codec/s3/key-scope.d.ts +0 -23
  254. package/dist/shared/codec/s3/key-scope.js +0 -44
  255. package/dist/shared/codec/s3/orphans.d.ts +0 -23
  256. package/dist/shared/codec/s3/orphans.js +0 -71
  257. package/dist/shared/codec/s3/read-write.d.ts +0 -18
  258. package/dist/shared/codec/s3/read-write.js +0 -51
  259. package/dist/shared/codec/s3/retry.d.ts +0 -5
  260. package/dist/shared/codec/s3/retry.js +0 -22
  261. package/dist/shared/constants.d.ts +0 -112
  262. package/dist/shared/constants.js +0 -115
  263. package/dist/shared/dynamodb/backoff.d.ts +0 -15
  264. package/dist/shared/dynamodb/backoff.js +0 -48
  265. package/dist/shared/dynamodb/conditional-put.d.ts +0 -67
  266. package/dist/shared/dynamodb/conditional-put.js +0 -76
  267. package/dist/shared/dynamodb/drain-unprocessed.d.ts +0 -21
  268. package/dist/shared/dynamodb/drain-unprocessed.js +0 -43
  269. package/dist/shared/dynamodb/expiry.d.ts +0 -16
  270. package/dist/shared/dynamodb/expiry.js +0 -29
  271. package/dist/shared/dynamodb/paginate-core.d.ts +0 -24
  272. package/dist/shared/dynamodb/paginate-core.js +0 -82
  273. package/dist/shared/dynamodb/retry-classifier.d.ts +0 -17
  274. package/dist/shared/dynamodb/retry-classifier.js +0 -118
  275. package/dist/shared/dynamodb/retry-policy.d.ts +0 -26
  276. package/dist/shared/dynamodb/retry-policy.js +0 -22
  277. package/dist/shared/dynamodb/scan.d.ts +0 -14
  278. package/dist/shared/dynamodb/scan.js +0 -19
  279. package/dist/shared/dynamodb/types.d.ts +0 -23
  280. package/dist/shared/dynamodb/types.js +0 -2
  281. package/dist/shared/errors/upstream-error.d.ts +0 -16
  282. package/dist/shared/errors/upstream-error.js +0 -27
  283. package/dist/shared/errors/wrap-error.d.ts +0 -7
  284. package/dist/shared/errors/wrap-error.js +0 -15
  285. package/dist/shared/logging/redaction-walk.d.ts +0 -23
  286. package/dist/shared/logging/redaction-walk.js +0 -112
  287. package/dist/store/actions/get.d.ts +0 -13
  288. package/dist/store/actions/get.js +0 -73
  289. package/dist/store/internal/backend-search.d.ts +0 -4
  290. package/dist/store/internal/backend-search.js +0 -74
  291. package/dist/store/internal/candidates.d.ts +0 -23
  292. package/dist/store/internal/candidates.js +0 -94
  293. package/dist/store/internal/index-reconcile.d.ts +0 -21
  294. package/dist/store/internal/index-reconcile.js +0 -118
  295. package/dist/store/internal/index-sync.d.ts +0 -10
  296. package/dist/store/internal/index-sync.js +0 -25
  297. package/dist/store/internal/item-mapper.d.ts +0 -27
  298. package/dist/store/internal/item-mapper.js +0 -61
  299. package/dist/store/internal/keys.d.ts +0 -17
  300. package/dist/store/internal/keys.js +0 -41
  301. package/dist/store/internal/namespace-match.d.ts +0 -11
  302. package/dist/store/internal/namespace-match.js +0 -40
  303. package/dist/store/internal/option-validation.d.ts +0 -13
  304. package/dist/store/internal/option-validation.js +0 -77
  305. package/dist/store/internal/overwrite-swap.d.ts +0 -32
  306. package/dist/store/internal/overwrite-swap.js +0 -68
  307. package/dist/store/internal/persist.d.ts +0 -28
  308. package/dist/store/internal/persist.js +0 -64
  309. package/dist/store/internal/query.d.ts +0 -11
  310. package/dist/store/internal/query.js +0 -48
  311. package/dist/store/internal/ranker.d.ts +0 -18
  312. package/dist/store/internal/ranker.js +0 -39
  313. package/dist/store/internal/read-existing.d.ts +0 -23
  314. package/dist/store/internal/read-existing.js +0 -41
  315. package/dist/store/internal/score-direction.d.ts +0 -31
  316. package/dist/store/internal/score-direction.js +0 -38
  317. package/dist/store/internal/search-filter.d.ts +0 -3
  318. package/dist/store/internal/search-filter.js +0 -10
  319. package/dist/store/internal/text-path.d.ts +0 -17
  320. package/dist/store/internal/text-path.js +0 -147
  321. package/dist/store/internal/validation.d.ts +0 -18
  322. package/dist/store/internal/validation.js +0 -51
  323. package/dist/store/internal/write-verify.d.ts +0 -42
  324. package/dist/store/internal/write-verify.js +0 -71
@@ -1,3 +1,15 @@
1
+ /**
2
+ * Hides which decode failures cost one message and which fail the read.
3
+ *
4
+ * A stored message is fetched, deserialized and rebuilt in three stages, and
5
+ * the stage a failure comes from decides its fate: only a loss no reader could
6
+ * ever recover is confined to that message and handed to `onCorruptMessage`
7
+ * (record 12); a transport fault, an out-of-scope key, a newer payload or a
8
+ * serializer's refusal fails the read under either policy. A caller gets a
9
+ * conversation that is whole or, under `'skip'`, missing a lost turn
10
+ * reported at `error` — never one silently truncated without a trace —
11
+ * however many downloads run at once.
12
+ */
1
13
  import { type BaseMessage } from '@langchain/core/messages';
2
14
  import type { CancelOptions } from '../../shared/options';
3
15
  import type { HistoryContext } from '../internal/setup';
@@ -13,5 +25,34 @@ import type { MessageWindow } from '../types';
13
25
  * `onCorruptMessage`: `'throw'` fails the read with the underlying error;
14
26
  * `'skip'` (the default) reports it at `error` with its sort key and returns
15
27
  * the rest. Every other failure propagates regardless of the policy.
28
+ *
29
+ * Accepts: `options.limit` — the newest N, at least 1; absent asks for the
30
+ * whole session, and `0` is refused rather than read as an empty conversation
31
+ * (see {@link parseMessageWindow}).
32
+ * `options.before` — only messages appended before that instant.
33
+ * `options.signal` — aborts the reads.
34
+ *
35
+ * Returns: the messages in chronological order, oldest first. A session that
36
+ * does not exist and one whose messages have all expired both return nothing:
37
+ * a conversation nobody can read is a conversation that is not there.
38
+ *
39
+ * Throws: `VALIDATION` naming `sessionId`, `limit`, `before`, `signal`, or
40
+ * `options.<key>` for a key this package does not read;
41
+ * `FORMAT_UNSUPPORTED` for a row, or a payload, a newer version wrote — the
42
+ * payload half whatever the policy, because a newer reader reads it and
43
+ * dropping it would lose a turn a rollback could still serve; the decode error
44
+ * of a corrupt row under `onCorruptMessage: 'throw'`; `VALIDATION` naming
45
+ * `message` for a row in this session's message key space that this adapter
46
+ * did not write, naming
47
+ * `s3Key` for a row addressing an object outside the session's own path, and
48
+ * naming `serde` for a row whose payload the serializer refuses to
49
+ * reconstruct, all three whatever the policy; any infrastructure failure — a
50
+ * throttle, a permission, a transport error — whatever the policy, because
51
+ * dropping a message for one of those would hand back a silently truncated
52
+ * conversation that the chain then re-persists as the truth.
53
+ *
54
+ * Guarantees: strongly consistent, so the turn just appended is visible.
55
+ * Offloaded messages download several at a time, and the corruption policy is
56
+ * applied in message order however they finish.
16
57
  */
17
58
  export declare function getMessages(context: HistoryContext, sessionId: string, options?: MessageWindow & CancelOptions): Promise<BaseMessage[]>;
@@ -1,46 +1,81 @@
1
1
  "use strict";
2
+ /**
3
+ * Hides which decode failures cost one message and which fail the read.
4
+ *
5
+ * A stored message is fetched, deserialized and rebuilt in three stages, and
6
+ * the stage a failure comes from decides its fate: only a loss no reader could
7
+ * ever recover is confined to that message and handed to `onCorruptMessage`
8
+ * (record 12); a transport fault, an out-of-scope key, a newer payload or a
9
+ * serializer's refusal fails the read under either policy. A caller gets a
10
+ * conversation that is whole or, under `'skip'`, missing a lost turn
11
+ * reported at `error` — never one silently truncated without a trace —
12
+ * however many downloads run at once.
13
+ */
2
14
  Object.defineProperty(exports, "__esModule", { value: true });
3
15
  exports.getMessages = getMessages;
4
16
  const messages_1 = require("@langchain/core/messages");
5
17
  const codec_1 = require("../../shared/codec/codec");
6
- const payload_loss_1 = require("../../shared/codec/payload-loss");
7
18
  const concurrency_1 = require("../../shared/concurrency");
8
- const constants_1 = require("../../shared/constants");
9
- const wrap_error_1 = require("../../shared/errors/wrap-error");
10
- const message_window_1 = require("../internal/message-window");
11
- const validation_1 = require("../internal/validation");
19
+ const base_error_1 = require("../../shared/errors/base-error");
20
+ const truncate_1 = require("../../shared/logging/truncate");
21
+ const message_read_1 = require("../internal/message-read");
22
+ const parse_1 = require("../internal/parse");
23
+ /**
24
+ * This message's own loss, or the whole read's failure. Only what no reader
25
+ * could ever recover is confined to one message; everything else would hand
26
+ * the caller a silently truncated conversation that
27
+ * `RunnableWithMessageHistory` then re-persists as the truth.
28
+ */
29
+ function corruptOrRethrow(error) {
30
+ if ((0, codec_1.isPermanentPayloadLoss)(error))
31
+ return { kind: 'corrupt', error };
32
+ throw error;
33
+ }
12
34
  /**
13
- * Decode one item in two stages so failures are classified by what caused
35
+ * Decode one item in three stages so failures are classified by what caused
14
36
  * them. Fetching the bytes (an S3 download, decompression) is infrastructure:
15
- * a transport, throttling or permission failure there is rethrown, because
16
- * dropping the message would hand the caller a silently truncated conversation
17
- * that `RunnableWithMessageHistory` then re-persists. Only a *permanent* loss
18
- * at that stage — the object is gone, or the decompression guard tripped — is
19
- * corruption. Deserializing and rebuilding the message is pure data handling,
20
- * so any failure there (bad bytes, a type LangChain cannot rebuild such as a
21
- * `RemoveMessage`) is corruption too, and is confined to that one message.
37
+ * a transport, throttling or permission failure there is rethrown. Only a
38
+ * *permanent* loss at that stage — the object is gone, or the decompression
39
+ * guard tripped — is corruption; a row whose `s3Key` lies outside the session's
40
+ * own path is a configuration or tenancy fault, and a payload whose
41
+ * `schemaVersion` is newer than this release reads is a turn a newer reader
42
+ * still serves, so both are rethrown like any other infrastructure failure (see
43
+ * `assertKeyInScope` and `assertReadableDescriptor`).
44
+ *
45
+ * Deserializing is classified the same way, through the same predicate: bytes
46
+ * that are no longer the form the row declares are this message's own loss, but
47
+ * a serde that refuses to reconstruct what intact bytes *name* — the branded
48
+ * refusal {@link loadPayloadValue} raises for a stored `lc` record naming a
49
+ * class outside its allow-list — is a misconfigured serde or a planted row, and
50
+ * is reported for the same reason the out-of-scope key is. Bytes reached this
51
+ * stage bare before it existed, so a refusal of that kind was skipped here
52
+ * while the store and the saver raised on the identical row.
53
+ *
54
+ * Rebuilding the message from what the serde returned is pure data handling, so
55
+ * any failure there — a type LangChain cannot rebuild, such as a
56
+ * `RemoveMessage` — is corruption confined to that one message.
22
57
  */
23
- async function decodeMessage(context, item, sessionId) {
24
- const deps = {
25
- serde: context.serde,
26
- compression: context.compression,
27
- offloader: context.offloader,
28
- };
58
+ async function decodeMessage(context, item, sessionId, signal) {
59
+ const deps = (0, codec_1.codecDepsOf)(context, signal);
29
60
  let bytes;
30
61
  try {
31
62
  bytes = await (0, codec_1.readPayloadBytes)(item.message, deps, [sessionId]);
32
63
  }
33
64
  catch (error) {
34
- if ((0, payload_loss_1.isPermanentPayloadLoss)(error))
35
- return { kind: 'corrupt', error: error };
36
- throw error;
65
+ return corruptOrRethrow(error);
66
+ }
67
+ let stored;
68
+ try {
69
+ stored = await (0, codec_1.loadPayloadValue)(item.message.serdeType, bytes, deps);
70
+ }
71
+ catch (error) {
72
+ return corruptOrRethrow(error);
37
73
  }
38
74
  try {
39
- const stored = (await context.serde.loadsTyped(item.message.serdeType, bytes));
40
75
  return { kind: 'ok', message: (0, messages_1.mapStoredMessagesToChatMessages)([stored])[0] };
41
76
  }
42
77
  catch (error) {
43
- return { kind: 'corrupt', error: (0, wrap_error_1.toError)(error) };
78
+ return { kind: 'corrupt', error: (0, base_error_1.toError)(error) };
44
79
  }
45
80
  }
46
81
  /**
@@ -54,13 +89,40 @@ async function decodeMessage(context, item, sessionId) {
54
89
  * `onCorruptMessage`: `'throw'` fails the read with the underlying error;
55
90
  * `'skip'` (the default) reports it at `error` with its sort key and returns
56
91
  * the rest. Every other failure propagates regardless of the policy.
92
+ *
93
+ * Accepts: `options.limit` — the newest N, at least 1; absent asks for the
94
+ * whole session, and `0` is refused rather than read as an empty conversation
95
+ * (see {@link parseMessageWindow}).
96
+ * `options.before` — only messages appended before that instant.
97
+ * `options.signal` — aborts the reads.
98
+ *
99
+ * Returns: the messages in chronological order, oldest first. A session that
100
+ * does not exist and one whose messages have all expired both return nothing:
101
+ * a conversation nobody can read is a conversation that is not there.
102
+ *
103
+ * Throws: `VALIDATION` naming `sessionId`, `limit`, `before`, `signal`, or
104
+ * `options.<key>` for a key this package does not read;
105
+ * `FORMAT_UNSUPPORTED` for a row, or a payload, a newer version wrote — the
106
+ * payload half whatever the policy, because a newer reader reads it and
107
+ * dropping it would lose a turn a rollback could still serve; the decode error
108
+ * of a corrupt row under `onCorruptMessage: 'throw'`; `VALIDATION` naming
109
+ * `message` for a row in this session's message key space that this adapter
110
+ * did not write, naming
111
+ * `s3Key` for a row addressing an object outside the session's own path, and
112
+ * naming `serde` for a row whose payload the serializer refuses to
113
+ * reconstruct, all three whatever the policy; any infrastructure failure — a
114
+ * throttle, a permission, a transport error — whatever the policy, because
115
+ * dropping a message for one of those would hand back a silently truncated
116
+ * conversation that the chain then re-persists as the truth.
117
+ *
118
+ * Guarantees: strongly consistent, so the turn just appended is visible.
119
+ * Offloaded messages download several at a time, and the corruption policy is
120
+ * applied in message order however they finish.
57
121
  */
58
122
  async function getMessages(context, sessionId, options = {}) {
59
- (0, validation_1.validateSessionId)(sessionId);
60
- (0, validation_1.validateMessageWindow)(options);
61
- const items = await (0, message_window_1.readWindow)(context, sessionId, options);
62
- /** Offloaded rows cost one S3 GET each, so they decode several at a time; the policy is applied in order. */
63
- const decoded = await (0, concurrency_1.mapWithConcurrency)(items, constants_1.DEFAULT_READ_CONCURRENCY, (item) => decodeMessage(context, item, sessionId));
123
+ const request = (0, parse_1.parseGetMessagesRequest)(sessionId, options);
124
+ const items = await (0, message_read_1.readWindow)(context, request.sessionId, request.window, request.signal);
125
+ const decoded = await (0, concurrency_1.mapWithConcurrency)(items, context.readConcurrency ?? concurrency_1.DEFAULT_READ_CONCURRENCY, (item) => decodeMessage(context, item, request.sessionId, request.signal));
64
126
  const messages = [];
65
127
  decoded.forEach((result, index) => {
66
128
  if (result.kind === 'ok') {
@@ -70,9 +132,9 @@ async function getMessages(context, sessionId, options = {}) {
70
132
  if (context.onCorruptMessage === 'throw')
71
133
  throw result.error;
72
134
  context.logger.error('getMessages: skipped a corrupt message item', {
73
- sessionId,
74
- sortKey: items[index].SK,
75
- reason: result.error.name,
135
+ sessionId: request.sessionId,
136
+ sortKey: (0, truncate_1.truncateForLog)(items[index].SK),
137
+ reason: (0, truncate_1.truncateForLog)((0, base_error_1.failureLabel)(result.error)),
76
138
  });
77
139
  });
78
140
  return messages;
@@ -1,13 +1,55 @@
1
+ /**
2
+ * Hides whether a listing reads the recency index or scans the table.
3
+ *
4
+ * With a configured `indexName` a listing is a cursor-paged, newest-first
5
+ * merge of the index shards; without one it is a filtered scan sorted in
6
+ * memory, with no cursor (record 8). A caller passes the same options and gets
7
+ * the same `SessionPage` either way: `limit` is the newest N on both paths,
8
+ * `0` reads neither, and the same rule summarises each session and drops the
9
+ * expired, foreign and malformed ones.
10
+ */
1
11
  import type { HistoryContext } from '../internal/setup';
2
- import type { SessionMetadata } from '../types';
12
+ import type { ListSessionsOptions, SessionPage } from '../types';
3
13
  /**
4
- * List all sessions as metadata summaries, newest-updated first. The scan is
5
- * filtered to session items so the adapter works on a table shared with the
6
- * checkpointer/store; foreign rows are also skipped defensively, and rows past
7
- * their TTL are filtered out exactly as `getMessages` filters expired messages.
14
+ * List sessions as metadata summaries, most recently updated first.
15
+ *
16
+ * Accepts: `options.limit` — the package-wide page rule, an integer from 0 to
17
+ * the page ceiling; absent means one index page (100) with the index, and
18
+ * every session without it, since a scan has no cursor to fetch the rest with.
19
+ * `0` returns an empty page on either path without reading the table, which
20
+ * matters most on the scan path: a scan has to finish before the newest can be
21
+ * known, so answering `limit: 0` by scanning and then slicing to nothing would
22
+ * have paid for the whole table to return an empty page.
23
+ * `options.cursor` — from a previous page, and
24
+ * only with a configured `indexName`. `options.maxItems` and
25
+ * `maxIterations` — caps on the scan path; with the index the page size is the
26
+ * bound and they do nothing. Each must be a positive integer or `Infinity`
27
+ * (the paginator's own way to ask for no cap); absent keeps its default.
28
+ *
29
+ * Returns: the page, newest-updated first, and a `nextCursor` while rows may
30
+ * remain. A page can come back shorter than `limit` while more remain: expired
31
+ * and foreign rows are dropped after the read, and so is a row of this
32
+ * package's own whose `messageCount`, `createdAt`, `updatedAt`, `title` or
33
+ * `ttl` is not the type written there — otherwise one unreadable `ttl` would fail the
34
+ * whole call, taking every healthy session with it. The cursor is a position in
35
+ * the index rather than a count of what survived filtering. A cursor does not
36
+ * promise more rows: the page after it can come back empty (see
37
+ * `queryRecencyIndex`).
38
+ *
39
+ * Throws: `VALIDATION` naming `limit`, `cursor`, `maxItems`,
40
+ * `maxIterations`, `signal`, or `options.<key>` for a key this package does
41
+ * not read; `RESULT_TRUNCATED` past the scan path's caps, or for an
42
+ * index shard whose pages do not end within `MAX_LOOP_ITERATIONS`;
43
+ * `FORMAT_UNSUPPORTED` for a SESSION row a newer release wrote, on either
44
+ * path; `ABORTED`.
45
+ *
46
+ * Guarantees: with a configured `indexName` each index shard is read
47
+ * newest-first one DynamoDB page at a time, and its next page whenever it has
48
+ * no row buffered and the page still needs one, which can cost a query per
49
+ * shard per page whose rows the page never takes; at most `readConcurrency`
50
+ * shards are queried at once. Memory is the page being built, up to `limit`
51
+ * rows and so bounded by the page ceiling, plus at most one DynamoDB page per shard,
52
+ * whatever the table holds. Without one it is a filtered table scan that holds
53
+ * every session at once and returns no cursor, as earlier releases did.
8
54
  */
9
- export declare function listSessions(context: HistoryContext, options?: {
10
- maxIterations?: number;
11
- maxItems?: number;
12
- signal?: AbortSignal;
13
- }): Promise<SessionMetadata[]>;
55
+ export declare function listSessions(context: HistoryContext, options?: ListSessionsOptions): Promise<SessionPage>;
@@ -1,53 +1,156 @@
1
1
  "use strict";
2
+ /**
3
+ * Hides whether a listing reads the recency index or scans the table.
4
+ *
5
+ * With a configured `indexName` a listing is a cursor-paged, newest-first
6
+ * merge of the index shards; without one it is a filtered scan sorted in
7
+ * memory, with no cursor (record 8). A caller passes the same options and gets
8
+ * the same `SessionPage` either way: `limit` is the newest N on both paths,
9
+ * `0` reads neither, and the same rule summarises each session and drops the
10
+ * expired, foreign and malformed ones.
11
+ */
2
12
  Object.defineProperty(exports, "__esModule", { value: true });
3
13
  exports.listSessions = listSessions;
4
14
  const clock_1 = require("../../shared/clock");
5
- const expiry_1 = require("../../shared/dynamodb/expiry");
6
- const retry_policy_1 = require("../../shared/dynamodb/retry-policy");
7
- const scan_1 = require("../../shared/dynamodb/scan");
8
- const keys_1 = require("../internal/keys");
15
+ const concurrency_1 = require("../../shared/concurrency");
16
+ const paginate_1 = require("../../shared/dynamodb/paginate");
17
+ const recency_index_1 = require("../../shared/dynamodb/recency-index");
18
+ const retry_1 = require("../../shared/dynamodb/retry");
19
+ const table_schema_1 = require("../../shared/dynamodb/table-schema");
20
+ const primitives_1 = require("../../shared/validation/primitives");
21
+ const parse_1 = require("../internal/parse");
22
+ const rows_1 = require("../internal/rows");
23
+ const session_1 = require("../internal/session");
24
+ /** Rows per page when the caller names none. */
25
+ const DEFAULT_PAGE_SIZE = (0, primitives_1.parseLimit)(100, 0);
9
26
  /**
10
- * List all sessions as metadata summaries, newest-updated first. The scan is
11
- * filtered to session items so the adapter works on a table shared with the
12
- * checkpointer/store; foreign rows are also skipped defensively, and rows past
13
- * their TTL are filtered out exactly as `getMessages` filters expired messages.
27
+ * One page from the recency index, newest-updated first.
28
+ *
29
+ * Expired, foreign and malformed rows are dropped after the read, so a page can
30
+ * come back shorter than `limit` while more rows remain. The cursor still advances,
31
+ * because it is the position in the index rather than a count of what survived
32
+ * filtering.
14
33
  */
15
- async function listSessions(context, options) {
34
+ async function pageFromIndex(context, indexName, request) {
35
+ const atSeconds = (0, clock_1.nowSeconds)();
36
+ const page = await (0, recency_index_1.queryRecencyIndex)({
37
+ client: context.client,
38
+ tableName: context.tableName,
39
+ indexName,
40
+ tag: 'SESS',
41
+ shards: context.indexShards ?? recency_index_1.DEFAULT_INDEX_SHARDS,
42
+ concurrency: context.readConcurrency ?? concurrency_1.DEFAULT_READ_CONCURRENCY,
43
+ limit: request.limit ?? DEFAULT_PAGE_SIZE,
44
+ cursor: request.cursor,
45
+ retry: (0, retry_1.retryFor)(context, request.signal),
46
+ signal: request.signal,
47
+ });
48
+ const sessions = page.items
49
+ .map((raw) => (0, session_1.summariseSession)(raw, atSeconds))
50
+ .filter((session) => session !== undefined);
51
+ return { sessions, ...(page.nextCursor === undefined ? {} : { nextCursor: page.nextCursor }) };
52
+ }
53
+ /**
54
+ * Every session, read by scanning the table and sorted in memory.
55
+ *
56
+ * The fallback for a table without the recency index. It consumes read capacity
57
+ * for every row the scan *evaluates*, not every row it returns, and it holds
58
+ * every session at once — which is why the index exists and why this path
59
+ * offers no cursor.
60
+ *
61
+ * An explicit `limit` is honoured here as the newest N, the same thing it means
62
+ * on the index path. It cannot bound the read — a scan has to finish before the
63
+ * newest can be known — but answering a caller who asked for ten with five
64
+ * thousand sessions was a wrong answer, not a cheaper one.
65
+ *
66
+ * The filter names the partition tag before the sort key. The sort key alone
67
+ * does not identify this adapter: a store namespace element may not hold the
68
+ * separator, but the join inserts one, so the legal store key
69
+ * `sortKey(['t', 'HISTORY'], 'SESSION')` composes `SESSION_SORT_KEY` byte for
70
+ * byte. Such a row sits in a `STORE#` partition, and since a row stamped with a
71
+ * format version above this release is *reported* rather than skipped, one of
72
+ * them was enough to fail this listing on a table the three adapters share.
73
+ * `summariseSession` already requires `PK` to equal `sessionPartition(sessionId)`, so
74
+ * the tag excludes only rows it was dropping after the read. Filtering costs no
75
+ * read capacity either way: DynamoDB applies it once the scan has finished.
76
+ */
77
+ async function allByScan(context, request) {
16
78
  const sessions = [];
17
- const nowSeconds = (0, clock_1.nowSeconds)();
18
- for await (const raw of (0, scan_1.paginateScan)({
19
- retry: (0, retry_policy_1.retryFor)(context, options?.signal),
20
- signal: options?.signal,
79
+ const atSeconds = (0, clock_1.nowSeconds)();
80
+ for await (const raw of (0, paginate_1.paginateScan)({
81
+ retry: (0, retry_1.retryFor)(context, request.signal),
82
+ signal: request.signal,
21
83
  client: context.client,
22
84
  params: {
23
85
  TableName: context.tableName,
24
- FilterExpression: '#sk = :session',
25
- ExpressionAttributeNames: { '#sk': 'SK' },
26
- ExpressionAttributeValues: { ':session': keys_1.SESSION_SORT_KEY },
86
+ FilterExpression: 'begins_with(#pk, :pkp) AND #sk = :session',
87
+ ExpressionAttributeNames: { '#pk': table_schema_1.PARTITION_KEY_ATTRIBUTE, '#sk': table_schema_1.SORT_KEY_ATTRIBUTE },
88
+ ExpressionAttributeValues: {
89
+ ':pkp': (0, rows_1.historyPartitionPrefix)(),
90
+ ':session': rows_1.SESSION_SORT_KEY,
91
+ },
27
92
  },
28
- maxIterations: options?.maxIterations,
29
- maxItems: options?.maxItems,
93
+ maxIterations: request.maxIterations,
94
+ maxItems: request.maxItems,
30
95
  })) {
31
- const item = raw;
32
- if (item.SK !== keys_1.SESSION_SORT_KEY || typeof item.sessionId !== 'string')
33
- continue;
34
- if ((0, expiry_1.isExpiredRow)(item, nowSeconds))
35
- continue;
36
- sessions.push({
37
- sessionId: item.sessionId,
38
- title: item.title,
39
- messageCount: item.messageCount,
40
- createdAt: item.createdAt,
41
- updatedAt: item.updatedAt,
42
- expiresAt: item.ttl === undefined ? undefined : new Date(item.ttl * 1000).toISOString(),
43
- });
96
+ const session = (0, session_1.summariseSession)(raw, atSeconds);
97
+ if (session)
98
+ sessions.push(session);
44
99
  }
45
- /**
46
- * Ordinal, not `localeCompare`: these are ISO-8601 timestamps, whose
47
- * byte order already is their chronological order. Locale-aware collation
48
- * applies rules (case folding, punctuation weighting) that have no meaning
49
- * here and are not guaranteed to agree with it in every locale.
50
- */
100
+ // Ordinal, not `localeCompare`: these are ISO-8601 timestamps, whose byte
101
+ // order already is their chronological order. Locale-aware collation applies
102
+ // rules (case folding, punctuation weighting) that have no meaning here and
103
+ // are not guaranteed to agree with it in every locale.
51
104
  sessions.sort((a, b) => (a.updatedAt < b.updatedAt ? 1 : a.updatedAt > b.updatedAt ? -1 : 0));
52
- return sessions;
105
+ return { sessions: request.limit === undefined ? sessions : sessions.slice(0, request.limit) };
106
+ }
107
+ /**
108
+ * List sessions as metadata summaries, most recently updated first.
109
+ *
110
+ * Accepts: `options.limit` — the package-wide page rule, an integer from 0 to
111
+ * the page ceiling; absent means one index page (100) with the index, and
112
+ * every session without it, since a scan has no cursor to fetch the rest with.
113
+ * `0` returns an empty page on either path without reading the table, which
114
+ * matters most on the scan path: a scan has to finish before the newest can be
115
+ * known, so answering `limit: 0` by scanning and then slicing to nothing would
116
+ * have paid for the whole table to return an empty page.
117
+ * `options.cursor` — from a previous page, and
118
+ * only with a configured `indexName`. `options.maxItems` and
119
+ * `maxIterations` — caps on the scan path; with the index the page size is the
120
+ * bound and they do nothing. Each must be a positive integer or `Infinity`
121
+ * (the paginator's own way to ask for no cap); absent keeps its default.
122
+ *
123
+ * Returns: the page, newest-updated first, and a `nextCursor` while rows may
124
+ * remain. A page can come back shorter than `limit` while more remain: expired
125
+ * and foreign rows are dropped after the read, and so is a row of this
126
+ * package's own whose `messageCount`, `createdAt`, `updatedAt`, `title` or
127
+ * `ttl` is not the type written there — otherwise one unreadable `ttl` would fail the
128
+ * whole call, taking every healthy session with it. The cursor is a position in
129
+ * the index rather than a count of what survived filtering. A cursor does not
130
+ * promise more rows: the page after it can come back empty (see
131
+ * `queryRecencyIndex`).
132
+ *
133
+ * Throws: `VALIDATION` naming `limit`, `cursor`, `maxItems`,
134
+ * `maxIterations`, `signal`, or `options.<key>` for a key this package does
135
+ * not read; `RESULT_TRUNCATED` past the scan path's caps, or for an
136
+ * index shard whose pages do not end within `MAX_LOOP_ITERATIONS`;
137
+ * `FORMAT_UNSUPPORTED` for a SESSION row a newer release wrote, on either
138
+ * path; `ABORTED`.
139
+ *
140
+ * Guarantees: with a configured `indexName` each index shard is read
141
+ * newest-first one DynamoDB page at a time, and its next page whenever it has
142
+ * no row buffered and the page still needs one, which can cost a query per
143
+ * shard per page whose rows the page never takes; at most `readConcurrency`
144
+ * shards are queried at once. Memory is the page being built, up to `limit`
145
+ * rows and so bounded by the page ceiling, plus at most one DynamoDB page per shard,
146
+ * whatever the table holds. Without one it is a filtered table scan that holds
147
+ * every session at once and returns no cursor, as earlier releases did.
148
+ */
149
+ async function listSessions(context, options = {}) {
150
+ const request = (0, parse_1.parseListSessionsRequest)(options, context.indexName);
151
+ if (request.limit === 0)
152
+ return { sessions: [] };
153
+ return context.indexName === undefined
154
+ ? allByScan(context, request)
155
+ : pageFromIndex(context, context.indexName, request);
53
156
  }
@@ -1,12 +1,45 @@
1
+ /**
2
+ * Hides that repairing `messageCount` is the session row's own job.
3
+ *
4
+ * The public repair only parses the session id and hands it to the module
5
+ * that owns the count (record 22). The recount, the compare-and-swap on the
6
+ * value it read, and the retry when an append lands in between all live
7
+ * there, beside the append that keeps the count in step, so the repair and
8
+ * the append cannot come to disagree about what the count means.
9
+ */
1
10
  import type { HistoryContext } from '../internal/setup';
2
11
  /**
3
- * Recompute `messageCount` from the authoritative number of stored message items
4
- * and write it back, repairing any drift. A repair tool: the append path keeps
5
- * the count consistent transactionally, so this is only needed after external
6
- * corruption. Run it when the session is quiescent — it `SET`s the count, so a
7
- * concurrent append's increment could be clobbered. Requires the session to
8
- * already exist; reconciling a nonexistent session throws {@link ConflictError}
9
- * rather than creating a permanent, TTL-less metadata-only row. Returns the
10
- * reconciled count.
12
+ * Recompute `messageCount` from the number of stored message items and write it
13
+ * back, repairing drift. The append path keeps the count consistent
14
+ * transactionally, so this is only needed after external corruption.
15
+ *
16
+ * **Safe to run on a live session.** The count is written under a condition on
17
+ * the value the row held when the count was computed, so an append landing in
18
+ * between makes the write fail rather than clobber the increment; the tool then
19
+ * recounts and tries again. Writing it unconditionally — which is what this did
20
+ * — silently discarded concurrent appends on exactly the sessions an operator
21
+ * reaches for this tool to fix.
22
+ *
23
+ * Accepts: `sessionId` — validated, and an existing session: repairing one that
24
+ * does not exist would mean creating it. `signal` — aborts the reads.
25
+ *
26
+ * Returns: the count now stored, which is the number of messages a reader would
27
+ * see.
28
+ *
29
+ * Throws: `VALIDATION` naming `sessionId`; `CONDITION_CONFLICT` when the
30
+ * session does not exist — rather than creating a permanent, TTL-less
31
+ * metadata-only row — and when it stays too busy to settle within
32
+ * {@link OVERWRITE_CAS_MAX_ATTEMPTS} attempts; `FORMAT_UNSUPPORTED` for a
33
+ * message row a newer release wrote, and `VALIDATION` naming `message` for
34
+ * a row in the session's message key space that this adapter did not write,
35
+ * both of which `getMessages` refuses too — writing a count back for a session
36
+ * no read can open would repair nothing; whatever the reads and the write
37
+ * throw.
38
+ *
39
+ * Guarantees: safe on a live session. The write is pinned to the value the row
40
+ * held when the count was computed, so an append landing in between fails the
41
+ * write rather than clobbering its increment, and the tool recounts. Expired
42
+ * messages are not counted, so the repaired number agrees with what
43
+ * `getMessages` returns rather than with what the table still holds.
11
44
  */
12
45
  export declare function reconcileMessageCount(context: HistoryContext, sessionId: string, signal?: AbortSignal): Promise<number>;
@@ -1,64 +1,51 @@
1
1
  "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.reconcileMessageCount = reconcileMessageCount;
4
- const clock_1 = require("../../shared/clock");
5
- const retry_1 = require("../../shared/dynamodb/retry");
6
- const retry_policy_1 = require("../../shared/dynamodb/retry-policy");
7
- const errors_1 = require("../../shared/errors/errors");
8
- const keys_1 = require("../internal/keys");
9
- const query_1 = require("../internal/query");
10
- const validation_1 = require("../internal/validation");
11
2
  /**
12
- * Count only the rows `getMessages` would return: an expired message that
13
- * DynamoDB's TTL sweep has not yet removed is invisible to the read path, so
14
- * counting it would "repair" `messageCount` to a number no reader ever sees.
3
+ * Hides that repairing `messageCount` is the session row's own job.
4
+ *
5
+ * The public repair only parses the session id and hands it to the module
6
+ * that owns the count (record 22). The recount, the compare-and-swap on the
7
+ * value it read, and the retry when an append lands in between all live
8
+ * there, beside the append that keeps the count in step, so the repair and
9
+ * the append cannot come to disagree about what the count means.
15
10
  */
16
- async function countMessages(context, sessionId, signal) {
17
- const query = (0, query_1.messageQuery)(context.tableName, sessionId);
18
- const base = {
19
- ...query,
20
- Select: 'COUNT',
21
- FilterExpression: 'attribute_not_exists(#ttl) OR #ttl > :now',
22
- ExpressionAttributeNames: { ...query.ExpressionAttributeNames, '#ttl': 'ttl' },
23
- ExpressionAttributeValues: { ...query.ExpressionAttributeValues, ':now': (0, clock_1.nowSeconds)() },
24
- };
25
- let total = 0;
26
- let startKey;
27
- do {
28
- const page = await (0, retry_1.withDynamoDBRetry)(() => context.client.query({ ...base, ExclusiveStartKey: startKey }), (0, retry_policy_1.retryFor)(context, signal));
29
- total += page.Count ?? 0;
30
- startKey = page.LastEvaluatedKey;
31
- } while (startKey);
32
- return total;
33
- }
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.reconcileMessageCount = reconcileMessageCount;
13
+ const parse_1 = require("../internal/parse");
14
+ const session_1 = require("../internal/session");
34
15
  /**
35
- * Recompute `messageCount` from the authoritative number of stored message items
36
- * and write it back, repairing any drift. A repair tool: the append path keeps
37
- * the count consistent transactionally, so this is only needed after external
38
- * corruption. Run it when the session is quiescent — it `SET`s the count, so a
39
- * concurrent append's increment could be clobbered. Requires the session to
40
- * already exist; reconciling a nonexistent session throws {@link ConflictError}
41
- * rather than creating a permanent, TTL-less metadata-only row. Returns the
42
- * reconciled count.
16
+ * Recompute `messageCount` from the number of stored message items and write it
17
+ * back, repairing drift. The append path keeps the count consistent
18
+ * transactionally, so this is only needed after external corruption.
19
+ *
20
+ * **Safe to run on a live session.** The count is written under a condition on
21
+ * the value the row held when the count was computed, so an append landing in
22
+ * between makes the write fail rather than clobber the increment; the tool then
23
+ * recounts and tries again. Writing it unconditionally — which is what this did
24
+ * — silently discarded concurrent appends on exactly the sessions an operator
25
+ * reaches for this tool to fix.
26
+ *
27
+ * Accepts: `sessionId` — validated, and an existing session: repairing one that
28
+ * does not exist would mean creating it. `signal` — aborts the reads.
29
+ *
30
+ * Returns: the count now stored, which is the number of messages a reader would
31
+ * see.
32
+ *
33
+ * Throws: `VALIDATION` naming `sessionId`; `CONDITION_CONFLICT` when the
34
+ * session does not exist — rather than creating a permanent, TTL-less
35
+ * metadata-only row — and when it stays too busy to settle within
36
+ * {@link OVERWRITE_CAS_MAX_ATTEMPTS} attempts; `FORMAT_UNSUPPORTED` for a
37
+ * message row a newer release wrote, and `VALIDATION` naming `message` for
38
+ * a row in the session's message key space that this adapter did not write,
39
+ * both of which `getMessages` refuses too — writing a count back for a session
40
+ * no read can open would repair nothing; whatever the reads and the write
41
+ * throw.
42
+ *
43
+ * Guarantees: safe on a live session. The write is pinned to the value the row
44
+ * held when the count was computed, so an append landing in between fails the
45
+ * write rather than clobbering its increment, and the tool recounts. Expired
46
+ * messages are not counted, so the repaired number agrees with what
47
+ * `getMessages` returns rather than with what the table still holds.
43
48
  */
44
49
  async function reconcileMessageCount(context, sessionId, signal) {
45
- (0, validation_1.validateSessionId)(sessionId);
46
- const count = await countMessages(context, sessionId, signal);
47
- try {
48
- await (0, retry_1.withDynamoDBRetry)(() => context.client.update({
49
- TableName: context.tableName,
50
- Key: { PK: (0, keys_1.sessionPartition)(sessionId), SK: keys_1.SESSION_SORT_KEY },
51
- UpdateExpression: 'SET #count = :count',
52
- ExpressionAttributeNames: { '#count': 'messageCount' },
53
- ExpressionAttributeValues: { ':count': count },
54
- ConditionExpression: 'attribute_exists(PK)',
55
- }), (0, retry_policy_1.retryFor)(context, signal));
56
- }
57
- catch (error) {
58
- if (error.name === 'ConditionalCheckFailedException') {
59
- throw new errors_1.ConflictError(`Cannot reconcile messageCount: session "${sessionId}" does not exist`, error);
60
- }
61
- throw error;
62
- }
63
- return count;
50
+ return (0, session_1.repairMessageCount)(context, (0, parse_1.parseSessionId)(sessionId), signal);
64
51
  }