@juspay/neurolink 13.9.0 → 13.10.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.
- package/CHANGELOG.md +2 -2
- package/dist/browser/neurolink.min.js +470 -429
- package/dist/core/conversationErasureFence.d.ts +48 -0
- package/dist/core/conversationErasureFence.js +270 -0
- package/dist/core/conversationMemoryInitializer.js +7 -0
- package/dist/core/redisConversationMemoryManager.d.ts +18 -1
- package/dist/core/redisConversationMemoryManager.js +79 -29
- package/dist/neurolink.d.ts +6 -0
- package/dist/neurolink.js +26 -1
- package/dist/types/conversation.d.ts +83 -2
- package/dist/types/conversation.js +24 -0
- package/package.json +2 -1
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Conversation erasure write fence (`conversation-erasure-v1`).
|
|
3
|
+
*
|
|
4
|
+
* A writer that opts in is admitted once, at initialization, against a
|
|
5
|
+
* standalone Redis running `maxmemory-policy noeviction`. Each later write is
|
|
6
|
+
* one atomic script that refuses unless the server run id, the store epoch and
|
|
7
|
+
* the eviction counter still match what the writer was admitted under, and
|
|
8
|
+
* refuses a session whose erasure tombstone exists. A permanent erasure sets
|
|
9
|
+
* the tombstone, deletes the session's keys and index entry in the same script.
|
|
10
|
+
*
|
|
11
|
+
* Only participating writers are fenced. A writer that did not opt in keeps the
|
|
12
|
+
* ordinary storage behaviour (`legacy` mode) and cannot erase permanently.
|
|
13
|
+
*/
|
|
14
|
+
import type { ConversationErasureProtocol, ConversationErasureResult, ConversationErasureWriteContext, ConversationErasureWriterStatus, RedisClient, RedisStorageConfig } from "../types/index.js";
|
|
15
|
+
export { ConversationSessionErasedError, ConversationWriterEpochError, } from "../types/index.js";
|
|
16
|
+
export declare const ERASURE_FENCE_PROTOCOL: ConversationErasureProtocol;
|
|
17
|
+
/** Key of the per-session erasure tombstone. */
|
|
18
|
+
export declare const erasureFenceKey: (sessionKey: string) => string;
|
|
19
|
+
/**
|
|
20
|
+
* Resolve the write context once, before the manager admits asynchronous work
|
|
21
|
+
* (not at the later commit of a write).
|
|
22
|
+
*
|
|
23
|
+
* Without `strict` the writer does not participate and stays `legacy`. With
|
|
24
|
+
* `strict`, anything short of a standalone, non-evicting Redis whose epoch
|
|
25
|
+
* could be read and pinned throws {@link ConversationWriterEpochError}.
|
|
26
|
+
*/
|
|
27
|
+
export declare const prepareConversationWriteContext: (client: RedisClient, config: Required<RedisStorageConfig>, strict?: boolean) => Promise<ConversationErasureWriteContext>;
|
|
28
|
+
/** Write the session metadata blob (SET plus TTL). */
|
|
29
|
+
export declare const fencedSessionMetadataWrite: (client: RedisClient, config: Required<RedisStorageConfig>, sessionId: string, userId: string | undefined, payload: string, context: ConversationErasureWriteContext | undefined) => Promise<void>;
|
|
30
|
+
/** Add the session to the user's session index (SADD plus TTL). */
|
|
31
|
+
export declare const fencedSessionIndexWrite: (client: RedisClient, config: Required<RedisStorageConfig>, sessionId: string, userId: string, context: ConversationErasureWriteContext | undefined) => Promise<void>;
|
|
32
|
+
/**
|
|
33
|
+
* Write the message LIST and the metadata blob together. Resolves to 1 once
|
|
34
|
+
* the write landed; a refused write throws instead.
|
|
35
|
+
*/
|
|
36
|
+
export declare const fencedSessionPersist: (client: RedisClient, config: Required<RedisStorageConfig>, sessionId: string, userId: string | undefined, write: {
|
|
37
|
+
mode: "replace" | "append";
|
|
38
|
+
messages: string[];
|
|
39
|
+
payload: string;
|
|
40
|
+
}, context: ConversationErasureWriteContext | undefined) => Promise<number>;
|
|
41
|
+
/**
|
|
42
|
+
* Permanently erase one session: tombstone, data keys and index entry in one
|
|
43
|
+
* atomic step. Requires a strict, fenced writer and an explicit session and
|
|
44
|
+
* user id.
|
|
45
|
+
*/
|
|
46
|
+
export declare const eraseSessionPermanently: (client: RedisClient, config: Required<RedisStorageConfig>, sessionId: string, userId: string, context: ConversationErasureWriteContext | undefined) => Promise<ConversationErasureResult>;
|
|
47
|
+
/** Whether the writer that resolved `context` participates in the v1 fence. */
|
|
48
|
+
export declare const conversationErasureWriterStatus: (context: ConversationErasureWriteContext | undefined) => ConversationErasureWriterStatus;
|
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Conversation erasure write fence (`conversation-erasure-v1`).
|
|
3
|
+
*
|
|
4
|
+
* A writer that opts in is admitted once, at initialization, against a
|
|
5
|
+
* standalone Redis running `maxmemory-policy noeviction`. Each later write is
|
|
6
|
+
* one atomic script that refuses unless the server run id, the store epoch and
|
|
7
|
+
* the eviction counter still match what the writer was admitted under, and
|
|
8
|
+
* refuses a session whose erasure tombstone exists. A permanent erasure sets
|
|
9
|
+
* the tombstone, deletes the session's keys and index entry in the same script.
|
|
10
|
+
*
|
|
11
|
+
* Only participating writers are fenced. A writer that did not opt in keeps the
|
|
12
|
+
* ordinary storage behaviour (`legacy` mode) and cannot erase permanently.
|
|
13
|
+
*/
|
|
14
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
15
|
+
import { ConversationSessionErasedError, ConversationWriterEpochError, } from "../types/index.js";
|
|
16
|
+
import { addToSetWithTtl, getSessionKey, getSessionMessagesKey, getUserSessionsKey, setWithTtl, } from "../utils/redis.js";
|
|
17
|
+
export { ConversationSessionErasedError, ConversationWriterEpochError, } from "../types/index.js";
|
|
18
|
+
export const ERASURE_FENCE_PROTOCOL = "conversation-erasure-v1";
|
|
19
|
+
const digest = (value) => createHash("sha256").update(value).digest("hex");
|
|
20
|
+
/** Key of the per-session erasure tombstone. */
|
|
21
|
+
export const erasureFenceKey = (sessionKey) => `neurolink-erasure-v1:${digest(sessionKey)}`;
|
|
22
|
+
const epochKey = (config) => `neurolink-erasure-epoch-v1:${digest(JSON.stringify([config.keyPrefix, config.userSessionsKeyPrefix]))}`;
|
|
23
|
+
const infoField = (info, name) => new RegExp(`(?:^|[\\r\\n])${name}:([^\\r\\n]+)`).exec(info)?.[1];
|
|
24
|
+
// Binds the epoch record to the current server run: a restarted server (whose
|
|
25
|
+
// data may have been lost) gets a fresh epoch, and an eviction-capable policy
|
|
26
|
+
// is refused outright.
|
|
27
|
+
const PREPARE_SCRIPT = String.raw `
|
|
28
|
+
local server=redis.call('INFO','server')
|
|
29
|
+
local current=string.match(server,'run_id:([^\r\n]+)')
|
|
30
|
+
if current~=ARGV[1] then return redis.error_reply('SESSION_WRITER_EPOCH_LOST') end
|
|
31
|
+
local memory=redis.call('INFO','memory')
|
|
32
|
+
if string.match(memory,'maxmemory_policy:([^\r\n]+)')~='noeviction' then return redis.error_reply('SESSION_WRITER_POLICY_UNSUPPORTED') end
|
|
33
|
+
local stored=redis.call('GET',KEYS[1])
|
|
34
|
+
if not stored or string.sub(stored,1,string.len(ARGV[1])+1)~=ARGV[1]..':' then
|
|
35
|
+
stored=ARGV[1]..':'..ARGV[2];redis.call('SET',KEYS[1],stored)
|
|
36
|
+
end
|
|
37
|
+
local stats=redis.call('INFO','stats')
|
|
38
|
+
local evicted=string.match(stats,'evicted_keys:(%d+)')
|
|
39
|
+
if not evicted then return redis.error_reply('SESSION_WRITER_EPOCH_LOST') end
|
|
40
|
+
return {stored,evicted}`;
|
|
41
|
+
/**
|
|
42
|
+
* Resolve the write context once, before the manager admits asynchronous work
|
|
43
|
+
* (not at the later commit of a write).
|
|
44
|
+
*
|
|
45
|
+
* Without `strict` the writer does not participate and stays `legacy`. With
|
|
46
|
+
* `strict`, anything short of a standalone, non-evicting Redis whose epoch
|
|
47
|
+
* could be read and pinned throws {@link ConversationWriterEpochError}.
|
|
48
|
+
*/
|
|
49
|
+
export const prepareConversationWriteContext = async (client, config, strict = false) => {
|
|
50
|
+
if (!strict) {
|
|
51
|
+
return Object.freeze({
|
|
52
|
+
mode: "legacy",
|
|
53
|
+
reason: "compatible-client",
|
|
54
|
+
strict: false,
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
try {
|
|
58
|
+
const cluster = await client.info("cluster");
|
|
59
|
+
if (infoField(cluster, "cluster_enabled") !== "0") {
|
|
60
|
+
throw new ConversationWriterEpochError();
|
|
61
|
+
}
|
|
62
|
+
const memory = await client.info("memory");
|
|
63
|
+
if (infoField(memory, "maxmemory_policy") !== "noeviction") {
|
|
64
|
+
throw new ConversationWriterEpochError();
|
|
65
|
+
}
|
|
66
|
+
const server = await client.info("server");
|
|
67
|
+
const runId = infoField(server, "run_id");
|
|
68
|
+
if (!runId) {
|
|
69
|
+
throw new ConversationWriterEpochError();
|
|
70
|
+
}
|
|
71
|
+
const result = await client.eval(PREPARE_SCRIPT, {
|
|
72
|
+
keys: [epochKey(config)],
|
|
73
|
+
arguments: [runId, randomUUID()],
|
|
74
|
+
});
|
|
75
|
+
if (!Array.isArray(result) ||
|
|
76
|
+
typeof result[0] !== "string" ||
|
|
77
|
+
!/^\d+$/.test(String(result[1]))) {
|
|
78
|
+
throw new ConversationWriterEpochError();
|
|
79
|
+
}
|
|
80
|
+
return Object.freeze({
|
|
81
|
+
mode: "fenced",
|
|
82
|
+
strict,
|
|
83
|
+
runId,
|
|
84
|
+
epoch: result[0],
|
|
85
|
+
evictedKeys: String(result[1]),
|
|
86
|
+
evictionPolicy: "noeviction",
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
catch {
|
|
90
|
+
throw new ConversationWriterEpochError();
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
// KEYS: 1 session blob, 2 messages LIST, 3 user index SET, 4 tombstone, 5 epoch
|
|
94
|
+
// ARGV: 1 mode, 2 session id, 3 ttl, 4 payload / append mode, 5 messages JSON,
|
|
95
|
+
// 6 metadata payload, 7 spare, 8 run id, 9 epoch, 10 eviction counter
|
|
96
|
+
const FENCED_SCRIPT = String.raw `
|
|
97
|
+
local server=redis.call('INFO','server')
|
|
98
|
+
if string.match(server,'run_id:([^\r\n]+)')~=ARGV[8] then return redis.error_reply('SESSION_WRITER_EPOCH_LOST') end
|
|
99
|
+
if redis.call('GET',KEYS[5])~=ARGV[9] then return redis.error_reply('SESSION_WRITER_EPOCH_LOST') end
|
|
100
|
+
local memory=redis.call('INFO','memory')
|
|
101
|
+
if string.match(memory,'maxmemory_policy:([^\r\n]+)')~='noeviction' then return redis.error_reply('SESSION_WRITER_EPOCH_LOST') end
|
|
102
|
+
local stats=redis.call('INFO','stats')
|
|
103
|
+
if string.match(stats,'evicted_keys:(%d+)')~=ARGV[10] then return redis.error_reply('SESSION_WRITER_EPOCH_LOST') end
|
|
104
|
+
local mode=ARGV[1]
|
|
105
|
+
if mode=='erase' then
|
|
106
|
+
redis.call('SET',KEYS[4],'conversation-erasure-v1')
|
|
107
|
+
local deleted=redis.call('DEL',KEYS[1],KEYS[2])
|
|
108
|
+
local member=redis.call('SREM',KEYS[3],ARGV[2])
|
|
109
|
+
return {1,deleted,member}
|
|
110
|
+
end
|
|
111
|
+
if redis.call('EXISTS',KEYS[4])~=0 then return redis.error_reply('SESSION_ERASED') end
|
|
112
|
+
local ttl=tonumber(ARGV[3])
|
|
113
|
+
if mode=='index' then
|
|
114
|
+
redis.call('SADD',KEYS[3],ARGV[2]);if ttl>0 then redis.call('EXPIRE',KEYS[3],ttl) end;return 1
|
|
115
|
+
end
|
|
116
|
+
if mode=='persist' then
|
|
117
|
+
if ARGV[4]=='replace' then redis.call('DEL',KEYS[2]) end
|
|
118
|
+
for _,message in ipairs(cjson.decode(ARGV[5])) do redis.call('RPUSH',KEYS[2],message) end
|
|
119
|
+
redis.call('SET',KEYS[1],ARGV[6]);if ttl>0 then redis.call('EXPIRE',KEYS[1],ttl);redis.call('EXPIRE',KEYS[2],ttl) end;return 1
|
|
120
|
+
end
|
|
121
|
+
if mode=='metadata' then
|
|
122
|
+
redis.call('SET',KEYS[1],ARGV[4]);if ttl>0 then redis.call('EXPIRE',KEYS[1],ttl) end;return 1
|
|
123
|
+
end
|
|
124
|
+
return redis.error_reply('Unsupported erasure-fence mode')`;
|
|
125
|
+
const fenceKeys = (config, sessionId, userId) => {
|
|
126
|
+
const sessionKey = getSessionKey(config, sessionId, userId);
|
|
127
|
+
return [
|
|
128
|
+
sessionKey,
|
|
129
|
+
getSessionMessagesKey(config, sessionId, userId),
|
|
130
|
+
getUserSessionsKey(config, userId || "randomUser"),
|
|
131
|
+
erasureFenceKey(sessionKey),
|
|
132
|
+
epochKey(config),
|
|
133
|
+
];
|
|
134
|
+
};
|
|
135
|
+
const errorText = (error) => error instanceof Error ? error.message : String(error);
|
|
136
|
+
const runFenced = async (client, config, sessionId, userId, scriptArguments, context) => {
|
|
137
|
+
if (context?.mode !== "fenced") {
|
|
138
|
+
throw new ConversationWriterEpochError();
|
|
139
|
+
}
|
|
140
|
+
const padded = [...scriptArguments];
|
|
141
|
+
while (padded.length < 7) {
|
|
142
|
+
padded.push("");
|
|
143
|
+
}
|
|
144
|
+
padded.push(context.runId, context.epoch, context.evictedKeys);
|
|
145
|
+
try {
|
|
146
|
+
return await client.eval(FENCED_SCRIPT, {
|
|
147
|
+
keys: fenceKeys(config, sessionId, userId),
|
|
148
|
+
arguments: padded,
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
catch (error) {
|
|
152
|
+
const text = errorText(error);
|
|
153
|
+
if (text.includes("SESSION_ERASED")) {
|
|
154
|
+
throw new ConversationSessionErasedError();
|
|
155
|
+
}
|
|
156
|
+
if (text.includes("SESSION_WRITER_EPOCH_LOST")) {
|
|
157
|
+
throw new ConversationWriterEpochError();
|
|
158
|
+
}
|
|
159
|
+
throw error;
|
|
160
|
+
}
|
|
161
|
+
};
|
|
162
|
+
/** Write the session metadata blob (SET plus TTL). */
|
|
163
|
+
export const fencedSessionMetadataWrite = async (client, config, sessionId, userId, payload, context) => {
|
|
164
|
+
if (context?.mode === "legacy") {
|
|
165
|
+
await setWithTtl(client, getSessionKey(config, sessionId, userId), payload, config.ttl);
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
await runFenced(client, config, sessionId, userId, ["metadata", sessionId, String(config.ttl), payload], context);
|
|
169
|
+
};
|
|
170
|
+
/** Add the session to the user's session index (SADD plus TTL). */
|
|
171
|
+
export const fencedSessionIndexWrite = async (client, config, sessionId, userId, context) => {
|
|
172
|
+
if (context?.mode === "legacy") {
|
|
173
|
+
await addToSetWithTtl(client, getUserSessionsKey(config, userId), sessionId, config.ttl);
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
await runFenced(client, config, sessionId, userId, ["index", sessionId, String(config.ttl)], context);
|
|
177
|
+
};
|
|
178
|
+
/**
|
|
179
|
+
* Write the message LIST and the metadata blob together. Resolves to 1 once
|
|
180
|
+
* the write landed; a refused write throws instead.
|
|
181
|
+
*/
|
|
182
|
+
export const fencedSessionPersist = async (client, config, sessionId, userId, write, context) => {
|
|
183
|
+
const { mode, messages, payload } = write;
|
|
184
|
+
if (context?.mode === "legacy") {
|
|
185
|
+
const blobKey = getSessionKey(config, sessionId, userId);
|
|
186
|
+
const listKey = getSessionMessagesKey(config, sessionId, userId);
|
|
187
|
+
const transaction = client.multi();
|
|
188
|
+
if (mode === "replace") {
|
|
189
|
+
transaction.del(listKey);
|
|
190
|
+
}
|
|
191
|
+
if (messages.length > 0) {
|
|
192
|
+
transaction.rPush(listKey, messages);
|
|
193
|
+
}
|
|
194
|
+
transaction.set(blobKey, payload);
|
|
195
|
+
if (config.ttl > 0) {
|
|
196
|
+
transaction.expire(blobKey, config.ttl);
|
|
197
|
+
transaction.expire(listKey, config.ttl);
|
|
198
|
+
}
|
|
199
|
+
await transaction.exec();
|
|
200
|
+
return 1;
|
|
201
|
+
}
|
|
202
|
+
await runFenced(client, config, sessionId, userId, [
|
|
203
|
+
"persist",
|
|
204
|
+
sessionId,
|
|
205
|
+
String(config.ttl),
|
|
206
|
+
mode,
|
|
207
|
+
JSON.stringify(messages),
|
|
208
|
+
payload,
|
|
209
|
+
], context);
|
|
210
|
+
return 1;
|
|
211
|
+
};
|
|
212
|
+
/**
|
|
213
|
+
* Permanently erase one session: tombstone, data keys and index entry in one
|
|
214
|
+
* atomic step. Requires a strict, fenced writer and an explicit session and
|
|
215
|
+
* user id.
|
|
216
|
+
*/
|
|
217
|
+
export const eraseSessionPermanently = async (client, config, sessionId, userId, context) => {
|
|
218
|
+
if (typeof sessionId !== "string" ||
|
|
219
|
+
!sessionId.trim() ||
|
|
220
|
+
typeof userId !== "string" ||
|
|
221
|
+
!userId.trim()) {
|
|
222
|
+
throw new Error("Explicit sessionId and userId are required for permanent erasure");
|
|
223
|
+
}
|
|
224
|
+
if (context?.mode !== "fenced" || context.strict !== true) {
|
|
225
|
+
throw new ConversationWriterEpochError();
|
|
226
|
+
}
|
|
227
|
+
const result = await runFenced(client, config, sessionId, userId, ["erase", sessionId], context);
|
|
228
|
+
if (!Array.isArray(result) || Number(result[0]) !== 1) {
|
|
229
|
+
throw new Error("Erasure outcome unconfirmed");
|
|
230
|
+
}
|
|
231
|
+
return {
|
|
232
|
+
status: "erased",
|
|
233
|
+
backend: "redis-standalone",
|
|
234
|
+
protocol: ERASURE_FENCE_PROTOCOL,
|
|
235
|
+
participatingWritesFenced: true,
|
|
236
|
+
strictWriteProtocol: true,
|
|
237
|
+
legacyWritersFenced: false,
|
|
238
|
+
sessionId,
|
|
239
|
+
userId,
|
|
240
|
+
namespaceDigest: digest(getSessionKey(config, sessionId, userId)),
|
|
241
|
+
serverRunIdDigest: digest(context.runId),
|
|
242
|
+
storeEpochDigest: digest(context.epoch),
|
|
243
|
+
evictionPolicy: "noeviction",
|
|
244
|
+
evictionCounter: Number(context.evictedKeys),
|
|
245
|
+
deletedKeys: Number(result[1]),
|
|
246
|
+
removedIndexMembers: Number(result[2]),
|
|
247
|
+
tombstoneExpiry: null,
|
|
248
|
+
};
|
|
249
|
+
};
|
|
250
|
+
/** Whether the writer that resolved `context` participates in the v1 fence. */
|
|
251
|
+
export const conversationErasureWriterStatus = (context) => {
|
|
252
|
+
if (context?.mode !== "fenced") {
|
|
253
|
+
return {
|
|
254
|
+
status: "unsupported",
|
|
255
|
+
protocol: ERASURE_FENCE_PROTOCOL,
|
|
256
|
+
strict: false,
|
|
257
|
+
reason: context?.mode === "legacy" ? context.reason : "not-initialized",
|
|
258
|
+
};
|
|
259
|
+
}
|
|
260
|
+
return {
|
|
261
|
+
status: "participating",
|
|
262
|
+
strict: context.strict === true,
|
|
263
|
+
backend: "redis-standalone",
|
|
264
|
+
protocol: ERASURE_FENCE_PROTOCOL,
|
|
265
|
+
serverRunIdDigest: digest(context.runId),
|
|
266
|
+
storeEpochDigest: digest(context.epoch),
|
|
267
|
+
evictionPolicy: "noeviction",
|
|
268
|
+
evictionCounter: Number(context.evictedKeys),
|
|
269
|
+
};
|
|
270
|
+
};
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
* Conversation Memory Initializer
|
|
3
3
|
* Provides integration with Redis storage for conversation memory
|
|
4
4
|
*/
|
|
5
|
+
import { ConversationMemoryError } from "../types/index.js";
|
|
5
6
|
import { applyConversationMemoryDefaults } from "../utils/conversationMemory.js";
|
|
6
7
|
import { logger } from "../utils/logger.js";
|
|
7
8
|
import { createConversationMemoryManager, getRedisConfigFromEnv, getStorageType, } from "./conversationMemoryFactory.js";
|
|
@@ -77,6 +78,12 @@ export async function initializeConversationMemory(config, eventEmitter) {
|
|
|
77
78
|
}
|
|
78
79
|
else {
|
|
79
80
|
logger.info("[conversationMemoryInitializer] Initializing in-memory conversation memory manager");
|
|
81
|
+
// The erasure write protocol is a Redis-only fence. Handing back a
|
|
82
|
+
// process-local manager would let a writer that asked for it run with no
|
|
83
|
+
// fence and no permanent erasure, which is the downgrade it exists to refuse.
|
|
84
|
+
if (memoryConfig.erasureWriteProtocol === "conversation-erasure-v1") {
|
|
85
|
+
throw new ConversationMemoryError('erasureWriteProtocol "conversation-erasure-v1" requires Redis conversation storage', "CONFIG_ERROR", { storageType });
|
|
86
|
+
}
|
|
80
87
|
// Create in-memory conversation memory manager
|
|
81
88
|
logger.debug("[conversationMemoryInitializer] Creating in-memory conversation memory manager");
|
|
82
89
|
const memoryManager = createConversationMemoryManager(memoryConfig);
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* Redis Conversation Memory Manager for NeuroLink
|
|
3
3
|
* Redis-based implementation of conversation storage with same interface as ConversationMemoryManager
|
|
4
4
|
*/
|
|
5
|
-
import type { ChatMessage, ConversationMemoryConfig, ConversationMemoryStats, RedisConversationObject, RedisStorageConfig, SessionListItem, SessionMemory, SessionMetadata, StoreConversationTurnOptions, AgenticLoopReportMetadata, IConversationMemoryManager, NeuroLinkEvents, TypedEventEmitter } from "../types/index.js";
|
|
5
|
+
import type { ChatMessage, ConversationMemoryConfig, ConversationErasureResult, ConversationErasureWriterStatus, ConversationMemoryStats, RedisConversationObject, RedisStorageConfig, SessionListItem, SessionMemory, SessionMetadata, StoreConversationTurnOptions, AgenticLoopReportMetadata, IConversationMemoryManager, NeuroLinkEvents, TypedEventEmitter } from "../types/index.js";
|
|
6
6
|
/**
|
|
7
7
|
* Redis-based implementation of the ConversationMemoryManager
|
|
8
8
|
* Uses the same interface but stores data in Redis
|
|
@@ -13,6 +13,12 @@ export declare class RedisConversationMemoryManager implements IConversationMemo
|
|
|
13
13
|
private summarizationEngine;
|
|
14
14
|
private redisConfig;
|
|
15
15
|
private redisClient;
|
|
16
|
+
/**
|
|
17
|
+
* Resolved once per initialization, before any write is admitted. Every
|
|
18
|
+
* write reads it up front so an in-flight write keeps the epoch it started
|
|
19
|
+
* under.
|
|
20
|
+
*/
|
|
21
|
+
private erasureWriteContext;
|
|
16
22
|
/**
|
|
17
23
|
* Receives `conversation:titleGenerated` once a new conversation's title is
|
|
18
24
|
* stored. Optional because the manager can be constructed standalone.
|
|
@@ -193,6 +199,17 @@ export declare class RedisConversationMemoryManager implements IConversationMemo
|
|
|
193
199
|
* Get statistics about conversation storage
|
|
194
200
|
*/
|
|
195
201
|
getStats(): Promise<ConversationMemoryStats>;
|
|
202
|
+
/**
|
|
203
|
+
* Whether this writer participates in the `conversation-erasure-v1` fence.
|
|
204
|
+
* Only participating writers are fenced; others are NOT.
|
|
205
|
+
*/
|
|
206
|
+
getConversationErasureWriterStatus(): ConversationErasureWriterStatus;
|
|
207
|
+
/**
|
|
208
|
+
* Permanently erase one session. Fences participating writers only, and
|
|
209
|
+
* needs a writer initialized with `erasureWriteProtocol:
|
|
210
|
+
* "conversation-erasure-v1"`.
|
|
211
|
+
*/
|
|
212
|
+
eraseSessionPermanently(sessionId: string, userId: string): Promise<ConversationErasureResult>;
|
|
196
213
|
/**
|
|
197
214
|
* Clear a specific session
|
|
198
215
|
*/
|
|
@@ -10,15 +10,19 @@ import { generateToolOutputPreview } from "../context/toolOutputLimits.js";
|
|
|
10
10
|
import { NEUROLINK_ARTIFACT_ID_KEY } from "../mcp/mcpOutputNormalizer.js";
|
|
11
11
|
import { SummarizationEngine } from "../context/summarizationEngine.js";
|
|
12
12
|
import { NeuroLink } from "../neurolink.js";
|
|
13
|
-
import { ConversationMemoryError } from "../types/index.js";
|
|
13
|
+
import { ConversationMemoryError, ConversationSessionErasedError, ConversationWriterEpochError, } from "../types/index.js";
|
|
14
14
|
import { withTimeout } from "../utils/errorHandling.js";
|
|
15
15
|
import { buildContextFromPointer, getEffectiveTokenThreshold, } from "../utils/conversationMemory.js";
|
|
16
16
|
import { logger } from "../utils/logger.js";
|
|
17
|
+
import { conversationErasureWriterStatus, eraseSessionPermanently as erasePermanently, fencedSessionIndexWrite, fencedSessionMetadataWrite, fencedSessionPersist, prepareConversationWriteContext, } from "./conversationErasureFence.js";
|
|
17
18
|
import { assistantTurnIdentity, isTurnAlreadyStored, turnMessageFields, userTurnIdentity, } from "../utils/conversationTurnIdentity.js";
|
|
18
19
|
import { extractIsErrorText } from "../utils/toolResultStatus.js";
|
|
19
|
-
import {
|
|
20
|
+
import { deserializeConversation, encodeStoredMessages, MESSAGES_KEY_SUFFIX, isSessionMessagesKey, parseStoredMessages, serializeConversationMetadata, usesSplitMessageStorage, getNormalizedConfig, getPooledRedisClient, getSessionKey, getUserSessionsKey, releasePooledRedisClient, scanKeys, serializeConversation, } from "../utils/redis.js";
|
|
20
21
|
const redisTracer = tracers.redis;
|
|
21
22
|
const REDIS_TIMEOUT_MS = 5000;
|
|
23
|
+
/** A fence refusal must reach the caller; a swallowed one reads as a stored write. */
|
|
24
|
+
const isErasureFenceRefusal = (error) => error instanceof ConversationSessionErasedError ||
|
|
25
|
+
error instanceof ConversationWriterEpochError;
|
|
22
26
|
/**
|
|
23
27
|
* Redis-based implementation of the ConversationMemoryManager
|
|
24
28
|
* Uses the same interface but stores data in Redis
|
|
@@ -29,6 +33,12 @@ export class RedisConversationMemoryManager {
|
|
|
29
33
|
summarizationEngine = new SummarizationEngine();
|
|
30
34
|
redisConfig;
|
|
31
35
|
redisClient = null;
|
|
36
|
+
/**
|
|
37
|
+
* Resolved once per initialization, before any write is admitted. Every
|
|
38
|
+
* write reads it up front so an in-flight write keeps the epoch it started
|
|
39
|
+
* under.
|
|
40
|
+
*/
|
|
41
|
+
erasureWriteContext;
|
|
32
42
|
/**
|
|
33
43
|
* Receives `conversation:titleGenerated` once a new conversation's title is
|
|
34
44
|
* stored. Optional because the manager can be constructed standalone.
|
|
@@ -62,6 +72,7 @@ export class RedisConversationMemoryManager {
|
|
|
62
72
|
logger.debug("[RedisConversationMemoryManager] Already initialized, skipping");
|
|
63
73
|
return;
|
|
64
74
|
}
|
|
75
|
+
this.erasureWriteContext = undefined;
|
|
65
76
|
await redisTracer.startActiveSpan("memory.initialize", {
|
|
66
77
|
kind: SpanKind.CLIENT,
|
|
67
78
|
attributes: {
|
|
@@ -78,6 +89,7 @@ export class RedisConversationMemoryManager {
|
|
|
78
89
|
ttl: this.redisConfig.ttl,
|
|
79
90
|
});
|
|
80
91
|
this.redisClient = await getPooledRedisClient(this.redisConfig);
|
|
92
|
+
this.erasureWriteContext = await prepareConversationWriteContext(this.redisClient, this.redisConfig, this.config.erasureWriteProtocol === "conversation-erasure-v1");
|
|
81
93
|
this.isInitialized = true;
|
|
82
94
|
logger.info("RedisConversationMemoryManager initialized", {
|
|
83
95
|
storage: "redis",
|
|
@@ -92,6 +104,15 @@ export class RedisConversationMemoryManager {
|
|
|
92
104
|
});
|
|
93
105
|
}
|
|
94
106
|
catch (error) {
|
|
107
|
+
if (this.redisClient && !this.isInitialized) {
|
|
108
|
+
this.redisClient = null;
|
|
109
|
+
try {
|
|
110
|
+
await releasePooledRedisClient(this.redisConfig);
|
|
111
|
+
}
|
|
112
|
+
catch {
|
|
113
|
+
// The initialization error below stays authoritative.
|
|
114
|
+
}
|
|
115
|
+
}
|
|
95
116
|
span.setStatus({
|
|
96
117
|
code: SpanStatusCode.ERROR,
|
|
97
118
|
message: error instanceof Error ? error.message : String(error),
|
|
@@ -105,6 +126,12 @@ export class RedisConversationMemoryManager {
|
|
|
105
126
|
port: this.redisConfig.port,
|
|
106
127
|
},
|
|
107
128
|
});
|
|
129
|
+
// A strict writer the server cannot admit (cluster, an evicting
|
|
130
|
+
// policy, no readable epoch) is a typed refusal callers can match;
|
|
131
|
+
// wrapping it as a generic CONFIG_ERROR would hide which it was.
|
|
132
|
+
if (error instanceof ConversationWriterEpochError) {
|
|
133
|
+
throw error;
|
|
134
|
+
}
|
|
108
135
|
throw new ConversationMemoryError("Failed to initialize Redis conversation memory", "CONFIG_ERROR", {
|
|
109
136
|
error: error instanceof Error ? error.message : String(error),
|
|
110
137
|
});
|
|
@@ -265,15 +292,18 @@ export class RedisConversationMemoryManager {
|
|
|
265
292
|
/**
|
|
266
293
|
* Add a session to user's session set (private method)
|
|
267
294
|
*/
|
|
268
|
-
async addUserSession(userId, sessionId
|
|
295
|
+
async addUserSession(userId, sessionId, writeContext = this
|
|
296
|
+
.erasureWriteContext) {
|
|
269
297
|
if (!this.redisClient || !userId) {
|
|
270
298
|
return;
|
|
271
299
|
}
|
|
272
300
|
try {
|
|
273
|
-
|
|
274
|
-
await addToSetWithTtl(this.redisClient, userSessionsKey, sessionId, this.redisConfig.ttl);
|
|
301
|
+
await fencedSessionIndexWrite(this.redisClient, this.redisConfig, sessionId, userId, writeContext);
|
|
275
302
|
}
|
|
276
303
|
catch (error) {
|
|
304
|
+
if (isErasureFenceRefusal(error)) {
|
|
305
|
+
throw error;
|
|
306
|
+
}
|
|
277
307
|
logger.error("[RedisConversationMemoryManager] Failed to add session to user set", {
|
|
278
308
|
userId,
|
|
279
309
|
sessionId,
|
|
@@ -381,6 +411,7 @@ export class RedisConversationMemoryManager {
|
|
|
381
411
|
userId: options.userId,
|
|
382
412
|
});
|
|
383
413
|
await this.ensureInitialized();
|
|
414
|
+
const writeContext = this.erasureWriteContext;
|
|
384
415
|
// NLK-GAP-012: Add span for storeTurn CRUD operation
|
|
385
416
|
return redisTracer.startActiveSpan("memory.storeTurn", {
|
|
386
417
|
kind: SpanKind.CLIENT,
|
|
@@ -424,7 +455,7 @@ export class RedisConversationMemoryManager {
|
|
|
424
455
|
updatedConversation.updatedAt = new Date().toISOString();
|
|
425
456
|
const serializedData = serializeConversation(updatedConversation);
|
|
426
457
|
if (this.redisClient) {
|
|
427
|
-
await
|
|
458
|
+
await fencedSessionMetadataWrite(this.redisClient, this.redisConfig, options.sessionId, options.userId || undefined, serializedData, writeContext);
|
|
428
459
|
this.emitTitleGenerated({
|
|
429
460
|
sessionId: options.sessionId,
|
|
430
461
|
userId: normalizedUserId,
|
|
@@ -501,7 +532,7 @@ export class RedisConversationMemoryManager {
|
|
|
501
532
|
// Append-only: push just this turn's messages and persist a SMALL
|
|
502
533
|
// metadata blob. A session not yet using split storage (new, or a
|
|
503
534
|
// legacy blob) is converted once here, then every later turn appends.
|
|
504
|
-
await this.persistConversation(conversation, options.sessionId, options.userId, wasSplitStorage ? messageCountBeforeTurn : undefined);
|
|
535
|
+
await this.persistConversation(conversation, options.sessionId, options.userId, wasSplitStorage ? messageCountBeforeTurn : undefined, writeContext);
|
|
505
536
|
// Scheduled AFTER the write, never before it. On the single turn that
|
|
506
537
|
// converts a legacy session, `checkAndSummarize` re-reads the blob and
|
|
507
538
|
// writes it back; observing the pre-conversion blob would make it
|
|
@@ -515,7 +546,7 @@ export class RedisConversationMemoryManager {
|
|
|
515
546
|
if (!this.summarizationInProgress.has(summarizationKey)) {
|
|
516
547
|
const summarizeWithContext = context.bind(context.active(), async () => {
|
|
517
548
|
try {
|
|
518
|
-
await this.checkAndSummarize(conversation, tokenThreshold, options.sessionId, options.userId, options.requestId);
|
|
549
|
+
await this.checkAndSummarize(conversation, tokenThreshold, options.sessionId, options.userId, options.requestId, writeContext);
|
|
519
550
|
}
|
|
520
551
|
catch (error) {
|
|
521
552
|
logger.error("Background summarization failed", {
|
|
@@ -552,7 +583,7 @@ export class RedisConversationMemoryManager {
|
|
|
552
583
|
});
|
|
553
584
|
}
|
|
554
585
|
if (options.userId) {
|
|
555
|
-
await this.addUserSession(options.userId, options.sessionId);
|
|
586
|
+
await this.addUserSession(options.userId, options.sessionId, writeContext);
|
|
556
587
|
}
|
|
557
588
|
span.setAttribute("message.count", conversation.messages.length);
|
|
558
589
|
span.setStatus({ code: SpanStatusCode.OK });
|
|
@@ -581,7 +612,8 @@ export class RedisConversationMemoryManager {
|
|
|
581
612
|
/**
|
|
582
613
|
* Check if summarization is needed based on token count
|
|
583
614
|
*/
|
|
584
|
-
async checkAndSummarize(conversation, threshold, sessionId, userId, requestId
|
|
615
|
+
async checkAndSummarize(conversation, threshold, sessionId, userId, requestId, writeContext = this
|
|
616
|
+
.erasureWriteContext) {
|
|
585
617
|
const normalizedUserId = userId || "randomUser";
|
|
586
618
|
const summarizationKey = `${sessionId}:${normalizedUserId}`;
|
|
587
619
|
if (this.summarizationInProgress.has(summarizationKey)) {
|
|
@@ -633,7 +665,7 @@ export class RedisConversationMemoryManager {
|
|
|
633
665
|
const freshSerialized = usesSplitMessageStorage(latestConversation)
|
|
634
666
|
? serializeConversationMetadata(latestConversation)
|
|
635
667
|
: serializeConversation(latestConversation);
|
|
636
|
-
await
|
|
668
|
+
await fencedSessionMetadataWrite(this.redisClient, this.redisConfig, sessionId, userId, freshSerialized, writeContext);
|
|
637
669
|
}
|
|
638
670
|
}
|
|
639
671
|
}
|
|
@@ -709,34 +741,25 @@ export class RedisConversationMemoryManager {
|
|
|
709
741
|
* fast path); omit it to rewrite the LIST wholesale, which is also how a
|
|
710
742
|
* legacy blob gets converted.
|
|
711
743
|
*/
|
|
712
|
-
async persistConversation(conversation, sessionId, userId, appendFrom
|
|
744
|
+
async persistConversation(conversation, sessionId, userId, appendFrom, writeContext = this
|
|
745
|
+
.erasureWriteContext) {
|
|
713
746
|
if (!this.redisClient) {
|
|
714
747
|
return;
|
|
715
748
|
}
|
|
716
|
-
const redisKey = getSessionKey(this.redisConfig, sessionId, userId);
|
|
717
|
-
const messagesKey = getSessionMessagesKey(this.redisConfig, sessionId, userId);
|
|
718
749
|
// One MULTI, not four to six independent commands. The replace path is a
|
|
719
750
|
// DEL followed by an RPUSH, and on the legacy-conversion path the inline
|
|
720
751
|
// blob is the only copy of the history until the SET lands — so a failure
|
|
721
752
|
// between any two of them leaves the session either empty or unrecoverable.
|
|
722
753
|
// Grouping them also collapses the round trips, which is the point of the
|
|
723
754
|
// append-only layout.
|
|
724
|
-
const tx = this.redisClient.multi();
|
|
725
|
-
if (appendFrom === undefined) {
|
|
726
|
-
tx.del(messagesKey);
|
|
727
|
-
}
|
|
728
755
|
const toPush = appendFrom === undefined
|
|
729
756
|
? conversation.messages
|
|
730
757
|
: conversation.messages.slice(appendFrom);
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
tx.expire(redisKey, this.redisConfig.ttl);
|
|
737
|
-
tx.expire(messagesKey, this.redisConfig.ttl);
|
|
738
|
-
}
|
|
739
|
-
await withTimeout(tx.exec(), REDIS_TIMEOUT_MS);
|
|
758
|
+
await withTimeout(fencedSessionPersist(this.redisClient, this.redisConfig, sessionId, userId, {
|
|
759
|
+
mode: appendFrom === undefined ? "replace" : "append",
|
|
760
|
+
messages: toPush.length > 0 ? encodeStoredMessages(toPush) : [],
|
|
761
|
+
payload: serializeConversationMetadata(conversation),
|
|
762
|
+
}, writeContext), REDIS_TIMEOUT_MS);
|
|
740
763
|
}
|
|
741
764
|
/**
|
|
742
765
|
* Build context messages for AI prompt injection (TOKEN-BASED)
|
|
@@ -1157,6 +1180,7 @@ User message: "${userMessage}"`;
|
|
|
1157
1180
|
*/
|
|
1158
1181
|
async setSessionMessages(sessionId, messages, userId) {
|
|
1159
1182
|
await this.ensureInitialized();
|
|
1183
|
+
const writeContext = this.erasureWriteContext;
|
|
1160
1184
|
if (!this.redisClient) {
|
|
1161
1185
|
throw new ConversationMemoryError("Redis client not initialized", "STORAGE_ERROR", { sessionId });
|
|
1162
1186
|
}
|
|
@@ -1176,7 +1200,7 @@ User message: "${userMessage}"`;
|
|
|
1176
1200
|
conversation.lastTokenCount = undefined;
|
|
1177
1201
|
conversation.lastCountedAt = undefined;
|
|
1178
1202
|
// Wholesale replacement: rewrite the LIST rather than appending.
|
|
1179
|
-
await this.persistConversation(conversation, sessionId, userId);
|
|
1203
|
+
await this.persistConversation(conversation, sessionId, userId, undefined, writeContext);
|
|
1180
1204
|
logger.debug("[RedisConversationMemoryManager] Session messages replaced", {
|
|
1181
1205
|
sessionId,
|
|
1182
1206
|
userId,
|
|
@@ -1184,6 +1208,9 @@ User message: "${userMessage}"`;
|
|
|
1184
1208
|
});
|
|
1185
1209
|
}
|
|
1186
1210
|
catch (error) {
|
|
1211
|
+
if (isErasureFenceRefusal(error)) {
|
|
1212
|
+
throw error;
|
|
1213
|
+
}
|
|
1187
1214
|
if (error instanceof ConversationMemoryError) {
|
|
1188
1215
|
throw error;
|
|
1189
1216
|
}
|
|
@@ -1241,6 +1268,25 @@ User message: "${userMessage}"`;
|
|
|
1241
1268
|
totalTurns,
|
|
1242
1269
|
};
|
|
1243
1270
|
}
|
|
1271
|
+
/**
|
|
1272
|
+
* Whether this writer participates in the `conversation-erasure-v1` fence.
|
|
1273
|
+
* Only participating writers are fenced; others are NOT.
|
|
1274
|
+
*/
|
|
1275
|
+
getConversationErasureWriterStatus() {
|
|
1276
|
+
return conversationErasureWriterStatus(this.erasureWriteContext);
|
|
1277
|
+
}
|
|
1278
|
+
/**
|
|
1279
|
+
* Permanently erase one session. Fences participating writers only, and
|
|
1280
|
+
* needs a writer initialized with `erasureWriteProtocol:
|
|
1281
|
+
* "conversation-erasure-v1"`.
|
|
1282
|
+
*/
|
|
1283
|
+
async eraseSessionPermanently(sessionId, userId) {
|
|
1284
|
+
await this.ensureInitialized();
|
|
1285
|
+
if (!this.redisClient) {
|
|
1286
|
+
throw new ConversationMemoryError("Redis unavailable; erasure unconfirmed", "STORAGE_ERROR", { sessionId });
|
|
1287
|
+
}
|
|
1288
|
+
return erasePermanently(this.redisClient, this.redisConfig, sessionId, userId, this.erasureWriteContext);
|
|
1289
|
+
}
|
|
1244
1290
|
/**
|
|
1245
1291
|
* Clear a specific session
|
|
1246
1292
|
*/
|
|
@@ -1674,6 +1720,7 @@ User message: "${userMessage}"`;
|
|
|
1674
1720
|
reportStatus: report.reportStatus,
|
|
1675
1721
|
});
|
|
1676
1722
|
await this.ensureInitialized();
|
|
1723
|
+
const writeContext = this.erasureWriteContext;
|
|
1677
1724
|
if (!this.redisClient) {
|
|
1678
1725
|
logger.warn("[RedisConversationMemoryManager] Redis client not available for report update", { sessionId, userId });
|
|
1679
1726
|
return;
|
|
@@ -1715,7 +1762,7 @@ User message: "${userMessage}"`;
|
|
|
1715
1762
|
const serializedData = usesSplitMessageStorage(conversation)
|
|
1716
1763
|
? serializeConversationMetadata(conversation)
|
|
1717
1764
|
: serializeConversation(conversation);
|
|
1718
|
-
await withTimeout(
|
|
1765
|
+
await withTimeout(fencedSessionMetadataWrite(this.redisClient, this.redisConfig, sessionId, userId || undefined, serializedData, writeContext), 5000);
|
|
1719
1766
|
logger.info("[RedisConversationMemoryManager] Successfully updated agentic loop report", {
|
|
1720
1767
|
sessionId,
|
|
1721
1768
|
userId,
|
|
@@ -1724,6 +1771,9 @@ User message: "${userMessage}"`;
|
|
|
1724
1771
|
});
|
|
1725
1772
|
}
|
|
1726
1773
|
catch (error) {
|
|
1774
|
+
if (isErasureFenceRefusal(error)) {
|
|
1775
|
+
throw error;
|
|
1776
|
+
}
|
|
1727
1777
|
logger.error("[RedisConversationMemoryManager] Failed to update agentic loop report", {
|
|
1728
1778
|
sessionId,
|
|
1729
1779
|
userId,
|