session-database-identity-migration.test.ts 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. import { DatabaseSync } from "node:sqlite";
  2. import { expect, it } from "vitest";
  3. import {
  4. runSqliteSessionMigrations,
  5. runSqliteSessionMigrationsAsync,
  6. type SqliteMigrationProgress,
  7. } from "../src/storage/session-store/migration-runner.js";
  8. import { runSessionDatabaseIdentityMigration } from "@zcode/shared/sqlite-migrations";
  9. it.each(["source-first", "agent-first"])(
  10. "%s:两端共用同一 checksum,结构接管不生成业务代际",
  11. async (order) => {
  12. const db = new DatabaseSync(":memory:");
  13. try {
  14. const agent = () => runSqliteSessionMigrations(db, ":memory:");
  15. const source = () => runSessionDatabaseIdentityMigration(db);
  16. await (order === "source-first" ? source : agent)();
  17. const initial = db
  18. .prepare("SELECT * FROM schema_migration WHERE id='0024_session_database_identity'")
  19. .get();
  20. await (order === "source-first" ? agent : source)();
  21. expect(
  22. db
  23. .prepare("SELECT * FROM schema_migration WHERE id='0024_session_database_identity'")
  24. .get(),
  25. ).toEqual(initial);
  26. expect(db.prepare("SELECT * FROM zcode_database_identity").all()).toEqual([]);
  27. expect(db.prepare("SELECT COUNT(*) AS n FROM schema_migration").get()?.n).toBe(24);
  28. } finally {
  29. db.close();
  30. }
  31. },
  32. );
  33. it("Source 记账失败回滚新表,Agent 与 Source 都拒绝已有 checksum 损坏", async () => {
  34. const db = new DatabaseSync(":memory:");
  35. try {
  36. db.exec(`CREATE TABLE schema_migration (id TEXT PRIMARY KEY, checksum TEXT NOT NULL, app_version TEXT, time_applied INTEGER NOT NULL);
  37. CREATE TRIGGER reject_identity BEFORE INSERT ON schema_migration
  38. WHEN NEW.id='0024_session_database_identity'
  39. BEGIN SELECT RAISE(ABORT, 'injected identity ledger failure'); END;`);
  40. expect(() => runSessionDatabaseIdentityMigration(db)).toThrow(
  41. "injected identity ledger failure",
  42. );
  43. expect(
  44. db.prepare("SELECT 1 FROM sqlite_master WHERE name='zcode_database_identity'").get(),
  45. ).toBeUndefined();
  46. expect(db.prepare("SELECT * FROM schema_migration").all()).toEqual([]);
  47. db.exec("DROP TRIGGER reject_identity");
  48. runSessionDatabaseIdentityMigration(db);
  49. db.exec("UPDATE schema_migration SET checksum='broken'");
  50. expect(() => runSessionDatabaseIdentityMigration(db)).toThrow(/checksum mismatch/);
  51. await expect(runSqliteSessionMigrations(db, ":memory:")).rejects.toThrow(/checksum mismatch/);
  52. // Agent 更早的迁移也在同一事务内回滚,损坏记录不会被覆盖。
  53. expect(db.prepare("SELECT id, checksum FROM schema_migration").all()).toEqual([
  54. { id: "0024_session_database_identity", checksum: "broken" },
  55. ]);
  56. } finally {
  57. db.close();
  58. }
  59. });
  60. it("Agent 正式迁移接管已有 Source identity,不覆盖代际且重复打开不改账本", async () => {
  61. const db = new DatabaseSync(":memory:");
  62. try {
  63. db.exec(`CREATE TABLE zcode_database_identity (scope TEXT PRIMARY KEY, identity TEXT NOT NULL);
  64. INSERT INTO zcode_database_identity VALUES ('session', 'existing-generation')`);
  65. await runSqliteSessionMigrations(db, ":memory:");
  66. expect(
  67. db.prepare("SELECT id FROM schema_migration WHERE id='0024_session_database_identity'").get(),
  68. ).toEqual({
  69. id: "0024_session_database_identity",
  70. });
  71. const ledger = db.prepare("SELECT * FROM schema_migration ORDER BY id").all();
  72. await runSqliteSessionMigrations(db, ":memory:");
  73. expect(db.prepare("SELECT * FROM schema_migration ORDER BY id").all()).toEqual(ledger);
  74. expect(db.prepare("SELECT identity FROM zcode_database_identity").get()).toEqual({
  75. identity: "existing-generation",
  76. });
  77. } finally {
  78. db.close();
  79. }
  80. });
  81. it("Agent/Source 共用应用原语,identity SQL 成功但记账失败时保留真实执行数量", async () => {
  82. const db = new DatabaseSync(":memory:");
  83. const states: SqliteMigrationProgress[] = [];
  84. try {
  85. await expect(
  86. runSqliteSessionMigrationsAsync(db, ":memory:", {
  87. onProgress: async (state) => {
  88. states.push(state);
  89. if (
  90. state.phase === "migrating" &&
  91. state.migrationId === "0024_session_database_identity"
  92. ) {
  93. db.exec(`CREATE TRIGGER reject_identity BEFORE INSERT ON schema_migration
  94. WHEN NEW.id='0024_session_database_identity'
  95. BEGIN SELECT RAISE(ABORT, 'injected identity ledger failure'); END;`);
  96. }
  97. },
  98. }),
  99. ).rejects.toMatchObject({ kind: "sql_failed", migrationId: "0024_session_database_identity" });
  100. expect(states.at(-1)).toMatchObject({
  101. phase: "failed",
  102. migration: { kind: "initialize", executedCount: 24, committedCount: 0 },
  103. });
  104. expect(db.isTransaction).toBe(false);
  105. expect(
  106. db.prepare("SELECT 1 FROM sqlite_master WHERE name='zcode_database_identity'").get(),
  107. ).toBeUndefined();
  108. expect(
  109. db.prepare("SELECT 1 FROM sqlite_master WHERE name='schema_migration'").get(),
  110. ).toBeUndefined();
  111. } finally {
  112. db.close();
  113. }
  114. });