Repository navigation
feat(base): persist channel sessions across restarts #3865
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from 10 commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
77d73d0
feat(base): persist channel sessions across restarts
Mr-Maidong c4cf65e
fix(base): address review feedback on session persistence PR
Mr-Maidong 9573868
test: add regression tests for clearAll persist and loadSession rejec…
2e3a524
refactor: address review suggestions for session-restore PR
cb02426
fix: prevent data loss and crashes in session restore
1743540
Merge branch 'QwenLM:main' into fix/session-restore
Mr-Maidong c832ca5
fix(base): address latest review feedback on session persist
06036bd
fix(base): clean stale mappings on failed restore and fix setBridge o…
ac56d92
fix(base): add loadSession timeout to prevent indefinite blocking dur…
04f24d1
fix(base): address critical review feedback on session persistence
7e40926
fix(base): improve crash recovery ordering and error messages
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -217,6 +217,67 @@ describe('SessionRouter', () => { | |
| expect(router.hasSession('ch', 'alice', 'chat1')).toBe(false); | ||
| expect(router.getAll()).toEqual([]); | ||
| }); | ||
|
|
||
| it('preserves persist file for restoration on next start', async () => { | ||
| const { writeFileSync, rmSync, readFileSync, existsSync, mkdtempSync } = | ||
| await import('node:fs'); | ||
| const { join } = await import('node:path'); | ||
| const { tmpdir } = await import('node:os'); | ||
| const tmpDir = mkdtempSync(join(tmpdir(), 'test-clearAll-persist-')); | ||
|
|
||
| const persistFile = join(tmpDir, 'sessions.json'); | ||
| const originalEntries = { | ||
| 'telegram:alice:chat1': { | ||
| sessionId: 'session-xyz', | ||
| target: { | ||
| channelName: 'telegram', | ||
| senderId: 'alice', | ||
| chatId: 'chat1', | ||
| }, | ||
| cwd: '/workspace', | ||
| }, | ||
| }; | ||
|
|
||
| try { | ||
| // Create a router, write a session, then clearAll | ||
| const router = new SessionRouter(bridge, '/tmp', 'user', persistFile); | ||
| await router.resolve('telegram', 'alice', 'chat1'); | ||
|
|
||
| // Populate the persist file with known data | ||
| writeFileSync(persistFile, JSON.stringify(originalEntries, null, 2)); | ||
|
|
||
| router.clearAll(); | ||
|
|
||
| // Memory should be cleared | ||
| expect(router.hasSession('telegram', 'alice', 'chat1')).toBe(false); | ||
| expect(router.getAll()).toEqual([]); | ||
|
|
||
| // Persist file should still exist with original content | ||
| expect(existsSync(persistFile)).toBe(true); | ||
| const onDisk = JSON.parse(readFileSync(persistFile, 'utf-8')); | ||
| expect(onDisk).toEqual(originalEntries); | ||
|
|
||
| // A fresh router should be able to restore from it | ||
| const freshRouter = new SessionRouter( | ||
| bridge, | ||
| '/tmp', | ||
| 'user', | ||
| persistFile, | ||
| ); | ||
| const result = await freshRouter.restoreSessions(); | ||
|
|
||
| expect(result.restored).toBe(1); | ||
| expect(result.failed).toBe(0); | ||
| expect(freshRouter.hasSession('telegram', 'alice', 'chat1')).toBe(true); | ||
| expect(freshRouter.getTarget('session-xyz')).toEqual({ | ||
| channelName: 'telegram', | ||
| senderId: 'alice', | ||
| chatId: 'chat1', | ||
| }); | ||
| } finally { | ||
| rmSync(tmpDir, { recursive: true }); | ||
| } | ||
| }); | ||
| }); | ||
|
|
||
| describe('setBridge', () => { | ||
|
|
@@ -229,4 +290,302 @@ describe('SessionRouter', () => { | |
| expect(bridge.newSession).not.toHaveBeenCalled(); | ||
| }); | ||
| }); | ||
|
|
||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [Suggestion] — deepseek-v4-pro via Qwen Code /review |
||
| describe('restoreSessions', () => { | ||
| it('restores sessions from persist file', async () => { | ||
| const { writeFileSync, rmSync, mkdtempSync } = await import('node:fs'); | ||
| const { join } = await import('node:path'); | ||
| const { tmpdir } = await import('node:os'); | ||
| const tmpDir = mkdtempSync(join(tmpdir(), 'test-restore-')); | ||
|
|
||
| try { | ||
| const persistFile = join(tmpDir, 'sessions.json'); | ||
| const entries = { | ||
| 'telegram:alice:chat1': { | ||
| sessionId: 'old-session-1', | ||
| target: { | ||
| channelName: 'telegram', | ||
| senderId: 'alice', | ||
| chatId: 'chat1', | ||
| }, | ||
| cwd: '/workspace', | ||
| }, | ||
| 'telegram:bob:chat2': { | ||
| sessionId: 'old-session-2', | ||
| target: { | ||
| channelName: 'telegram', | ||
| senderId: 'bob', | ||
| chatId: 'chat2', | ||
| }, | ||
| cwd: '/workspace', | ||
| }, | ||
| }; | ||
| writeFileSync(persistFile, JSON.stringify(entries, null, 2)); | ||
|
|
||
| const router = new SessionRouter(bridge, '/tmp', 'user', persistFile); | ||
| const result = await router.restoreSessions(); | ||
|
|
||
| expect(result.restored).toBe(2); | ||
| expect(result.failed).toBe(0); | ||
| expect(bridge.loadSession).toHaveBeenCalledTimes(2); | ||
| expect(router.hasSession('telegram', 'alice', 'chat1')).toBe(true); | ||
| expect(router.hasSession('telegram', 'bob', 'chat2')).toBe(true); | ||
|
|
||
| const target = router.getTarget('old-session-1'); | ||
| expect(target).toEqual({ | ||
| channelName: 'telegram', | ||
| senderId: 'alice', | ||
| chatId: 'chat1', | ||
| }); | ||
| } finally { | ||
| rmSync(tmpDir, { recursive: true }); | ||
| } | ||
| }); | ||
|
|
||
| it('skips entries whose loadSession throws', async () => { | ||
| const { writeFileSync, rmSync, mkdtempSync } = await import('node:fs'); | ||
| const { join } = await import('node:path'); | ||
| const { tmpdir } = await import('node:os'); | ||
| const tmpDir = mkdtempSync(join(tmpdir(), 'test-restore-fail-')); | ||
|
|
||
| try { | ||
| const persistFile = join(tmpDir, 'sessions.json'); | ||
| const entries = { | ||
| 'telegram:alice:chat1': { | ||
| sessionId: 'good-session', | ||
| target: { | ||
| channelName: 'telegram', | ||
| senderId: 'alice', | ||
| chatId: 'chat1', | ||
| }, | ||
| cwd: '/workspace', | ||
| }, | ||
| 'telegram:bob:chat2': { | ||
| sessionId: 'stale-session', | ||
| target: { | ||
| channelName: 'telegram', | ||
| senderId: 'bob', | ||
| chatId: 'chat2', | ||
| }, | ||
| cwd: '/workspace', | ||
| }, | ||
| }; | ||
| writeFileSync(persistFile, JSON.stringify(entries, null, 2)); | ||
|
|
||
| // Make loadSession throw for the stale session | ||
| (bridge.loadSession as ReturnType<typeof vi.fn>).mockImplementation( | ||
| (id: string) => { | ||
| if (id === 'stale-session') { | ||
| throw new Error('Session not found'); | ||
| } | ||
| return id; | ||
| }, | ||
| ); | ||
|
|
||
| const router = new SessionRouter(bridge, '/tmp', 'user', persistFile); | ||
| const result = await router.restoreSessions(); | ||
|
|
||
| expect(result.restored).toBe(1); | ||
| expect(result.failed).toBe(1); | ||
| expect(router.hasSession('telegram', 'alice', 'chat1')).toBe(true); | ||
| expect(router.hasSession('telegram', 'bob', 'chat2')).toBe(false); | ||
|
|
||
| // Persist file should be updated to remove the failed entry | ||
| const { readFileSync } = await import('node:fs'); | ||
| const updated = JSON.parse(readFileSync(persistFile, 'utf-8')); | ||
| expect(Object.keys(updated)).toEqual(['telegram:alice:chat1']); | ||
| } finally { | ||
| rmSync(tmpDir, { recursive: true }); | ||
| } | ||
| }); | ||
|
|
||
| it('removes stale in-memory mappings on failed restore (crash recovery)', async () => { | ||
| const { writeFileSync, rmSync, mkdtempSync } = await import('node:fs'); | ||
| const { join } = await import('node:path'); | ||
| const { tmpdir } = await import('node:os'); | ||
| const tmpDir = mkdtempSync(join(tmpdir(), 'test-restore-crash-')); | ||
|
|
||
| try { | ||
| const persistFile = join(tmpDir, 'sessions.json'); | ||
| const entries = { | ||
| 'telegram:alice:chat1': { | ||
| sessionId: 'will-fail', | ||
| target: { | ||
| channelName: 'telegram', | ||
| senderId: 'alice', | ||
| chatId: 'chat1', | ||
| }, | ||
| cwd: '/workspace', | ||
| }, | ||
| }; | ||
| writeFileSync(persistFile, JSON.stringify(entries, null, 2)); | ||
|
|
||
| // Simulate pre-crash in-memory state: the router already has a mapping | ||
| // for this key from before the bridge crash. | ||
| const router = new SessionRouter(bridge, '/tmp', 'user', persistFile); | ||
| (bridge.newSession as ReturnType<typeof vi.fn>).mockResolvedValueOnce( | ||
| 'will-fail', | ||
| ); | ||
| await router.resolve( | ||
| 'telegram', | ||
| 'alice', | ||
| 'chat1', | ||
| undefined, | ||
| '/workspace', | ||
| ); | ||
| expect(router.hasSession('telegram', 'alice', 'chat1')).toBe(true); | ||
|
|
||
| // Now make loadSession throw so restoreSessions hits the catch path. | ||
| (bridge.loadSession as ReturnType<typeof vi.fn>).mockRejectedValueOnce( | ||
| new Error('Session not found'), | ||
| ); | ||
|
|
||
| const result = await router.restoreSessions(); | ||
| expect(result.restored).toBe(0); | ||
| expect(result.failed).toBe(1); | ||
| // The stale in-memory mapping should be cleaned up | ||
| expect(router.hasSession('telegram', 'alice', 'chat1')).toBe(false); | ||
| } finally { | ||
| rmSync(tmpDir, { recursive: true }); | ||
| } | ||
| }); | ||
|
|
||
| it('returns zeros when no persist file exists', async () => { | ||
| const router = new SessionRouter( | ||
| bridge, | ||
| '/tmp', | ||
| 'user', | ||
| '/nonexistent/sessions.json', | ||
| ); | ||
| const result = await router.restoreSessions(); | ||
| expect(result).toEqual({ restored: 0, failed: 0 }); | ||
| }); | ||
|
|
||
| it('returns zeros when persist file is empty', async () => { | ||
| const { writeFileSync, rmSync, mkdtempSync } = await import('node:fs'); | ||
| const { join } = await import('node:path'); | ||
| const { tmpdir } = await import('node:os'); | ||
| const tmpDir = mkdtempSync(join(tmpdir(), 'test-restore-empty-')); | ||
|
|
||
| try { | ||
| const persistFile = join(tmpDir, 'sessions.json'); | ||
| writeFileSync(persistFile, '{}'); | ||
|
|
||
| const router = new SessionRouter(bridge, '/tmp', 'user', persistFile); | ||
| const result = await router.restoreSessions(); | ||
|
|
||
| expect(result).toEqual({ restored: 0, failed: 0 }); | ||
| expect(bridge.loadSession).not.toHaveBeenCalled(); | ||
| } finally { | ||
| rmSync(tmpDir, { recursive: true }); | ||
| } | ||
| }); | ||
|
|
||
| it('times out when loadSession hangs and logs error to stderr', async () => { | ||
| const { writeFileSync, rmSync, mkdtempSync } = await import('node:fs'); | ||
| const { join } = await import('node:path'); | ||
| const { tmpdir } = await import('node:os'); | ||
| const tmpDir = mkdtempSync(join(tmpdir(), 'test-restore-timeout-')); | ||
|
|
||
| vi.useFakeTimers(); | ||
|
|
||
| try { | ||
| const persistFile = join(tmpDir, 'sessions.json'); | ||
| const entries = { | ||
| 'telegram:alice:chat1': { | ||
| sessionId: 'hanging-session', | ||
| target: { | ||
| channelName: 'telegram', | ||
| senderId: 'alice', | ||
| chatId: 'chat1', | ||
| }, | ||
| cwd: '/workspace', | ||
| }, | ||
| }; | ||
| writeFileSync(persistFile, JSON.stringify(entries, null, 2)); | ||
|
|
||
| // Make loadSession hang indefinitely (never resolves/rejects) | ||
| let hangingResolve: (value: string) => void; | ||
| const hangingPromise = new Promise<string>((resolve) => { | ||
| hangingResolve = resolve; | ||
| }); | ||
| (bridge.loadSession as ReturnType<typeof vi.fn>).mockReturnValue( | ||
| hangingPromise, | ||
| ); | ||
|
|
||
| const router = new SessionRouter(bridge, '/tmp', 'user', persistFile); | ||
|
|
||
| // Start restoreSessions - it will hang waiting for loadSession | ||
| const resultPromise = router.restoreSessions(); | ||
|
|
||
| // Advance time past the 30s timeout | ||
| await vi.advanceTimersByTimeAsync(30_000); | ||
|
|
||
| const result = await resultPromise; | ||
|
|
||
| // Should have recorded a failure due to timeout | ||
| expect(result.restored).toBe(0); | ||
| expect(result.failed).toBe(1); | ||
| expect(router.hasSession('telegram', 'alice', 'chat1')).toBe(false); | ||
|
|
||
| // The hanging loadSession should have a no-op catch attached | ||
| // to prevent unhandled rejection. Resolve it now to verify no crash. | ||
| hangingResolve!('hanging-session'); | ||
| await Promise.resolve(); // let microtasks settle | ||
| } finally { | ||
| vi.useRealTimers(); | ||
| rmSync(tmpDir, { recursive: true }); | ||
| } | ||
| }); | ||
|
|
||
| it('clears timeout when loadSession completes before timeout', async () => { | ||
| const { writeFileSync, rmSync, mkdtempSync } = await import('node:fs'); | ||
| const { join } = await import('node:path'); | ||
| const { tmpdir } = await import('node:os'); | ||
| const tmpDir = mkdtempSync(join(tmpdir(), 'test-restore-notimeout-')); | ||
|
|
||
| vi.useFakeTimers(); | ||
|
|
||
| try { | ||
| const persistFile = join(tmpDir, 'sessions.json'); | ||
| const entries = { | ||
| 'telegram:alice:chat1': { | ||
| sessionId: 'fast-session', | ||
| target: { | ||
| channelName: 'telegram', | ||
| senderId: 'alice', | ||
| chatId: 'chat1', | ||
| }, | ||
| cwd: '/workspace', | ||
| }, | ||
| }; | ||
| writeFileSync(persistFile, JSON.stringify(entries, null, 2)); | ||
|
|
||
| // Make loadSession resolve quickly (within timeout) | ||
| (bridge.loadSession as ReturnType<typeof vi.fn>).mockImplementation( | ||
| (id: string) => Promise.resolve(id), | ||
| ); | ||
|
|
||
| const router = new SessionRouter(bridge, '/tmp', 'user', persistFile); | ||
| const resultPromise = router.restoreSessions(); | ||
|
|
||
| // Advance time a bit (but not past timeout) | ||
| await vi.advanceTimersByTimeAsync(1000); | ||
|
|
||
| const result = await resultPromise; | ||
|
|
||
| // Should have succeeded | ||
| expect(result.restored).toBe(1); | ||
| expect(result.failed).toBe(0); | ||
| expect(router.hasSession('telegram', 'alice', 'chat1')).toBe(true); | ||
|
|
||
| // Advance past the original timeout to ensure no stray timer fires | ||
| await vi.advanceTimersByTimeAsync(30_000); | ||
| // No error should occur (timeout was cleared) | ||
| } finally { | ||
| vi.useRealTimers(); | ||
| rmSync(tmpDir, { recursive: true }); | ||
| } | ||
| }); | ||
| }); | ||
| }); | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[Nit] 行为契约从「返回 agent 报告的 session ID」改成了「直接回显调用者传入的 sessionId,信任 ACP agent 用同样的 ID 加载」。这是正确的——
LoadSessionResponse规范里就没这个字段——但建议加一行注释,避免未来 reader 觉得「这看起来像 bug」又把它改回去: