memory-vfs.spec.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. /**
  2. * The identity, timestamp, link, mutation, and durability-sink guarantees
  3. * MemoryVfs owes its consumers, asserted directly rather than through the
  4. * `node:fs` bridge.
  5. *
  6. * `dsh-fs-local` builds a version token from `dev:ino:size:mtimeNs:ctimeNs` and
  7. * refuses a write whose token moved since it read. Two properties carry that:
  8. * `ino` identifies the entry at a path, and `mtimeMs` moves on every write. The
  9. * timestamp cases freeze the clock, because these writes are in memory and two
  10. * revisions routinely land in the same millisecond — a real-clock test passes
  11. * whether or not the strict increment exists.
  12. */
  13. import { afterEach, describe, expect, it, vi } from 'vitest'
  14. import { MemoryVfs } from '../../src/storage/memory.ts'
  15. import type { VfsBigIntStats, VfsMutation, VfsMutationSink, VfsStats } from '../../src/storage/types.ts'
  16. const identity = (vfs: MemoryVfs, path: string): bigint =>
  17. (vfs.statSync(path, { bigint: true }) as VfsBigIntStats).ino
  18. const linkCount = (vfs: MemoryVfs, path: string): bigint =>
  19. (vfs.statSync(path, { bigint: true }) as VfsBigIntStats).nlink
  20. const modified = (vfs: MemoryVfs, path: string): number => (vfs.statSync(path) as VfsStats).mtimeMs
  21. afterEach(() => { vi.restoreAllMocks() })
  22. describe('entry identity', () => {
  23. it('distinguishes paths and holds each identity across repeated stats', () => {
  24. const vfs = new MemoryVfs()
  25. vfs.seed('/dsh/one.txt', 'one')
  26. vfs.seed('/dsh/two.txt', 'two')
  27. const first = identity(vfs, '/dsh/one.txt')
  28. expect(identity(vfs, '/dsh/two.txt')).not.toBe(first)
  29. expect(identity(vfs, '/dsh/one.txt')).toBe(first)
  30. })
  31. it('forgets the identities under a directory removed as a subtree', () => {
  32. const vfs = new MemoryVfs()
  33. vfs.seed('/dsh/skills/git/SKILL.md', '# git\n')
  34. const before = identity(vfs, '/dsh/skills/git/SKILL.md')
  35. vfs.rmSync('/dsh/skills', { recursive: true })
  36. vfs.seed('/dsh/skills/git/SKILL.md', '# git rebuilt\n')
  37. expect(identity(vfs, '/dsh/skills/git/SKILL.md')).not.toBe(before)
  38. })
  39. it('moves the source identity when a file replaces another path', () => {
  40. const vfs = new MemoryVfs()
  41. vfs.seed('/dsh/from.txt', 'moved')
  42. vfs.seed('/dsh/to.txt', 'replaced')
  43. const [source, destination] = [identity(vfs, '/dsh/from.txt'), identity(vfs, '/dsh/to.txt')]
  44. vfs.renameSync('/dsh/from.txt', '/dsh/to.txt')
  45. const renamed = identity(vfs, '/dsh/to.txt')
  46. expect(vfs.readFileSync('/dsh/to.txt', 'utf8')).toBe('moved')
  47. expect([renamed === source, renamed === destination]).toEqual([true, false])
  48. })
  49. })
  50. describe('modification time', () => {
  51. it('hydrates explicit metadata without confusing timestamps with permission bits', () => {
  52. const vfs = new MemoryVfs()
  53. vfs.seed('/dsh/restored', 'value', { mode: 0o600, mtimeMs: 1_600_000_000_000 })
  54. vfs.seedDirectory('/dsh/restored-directory', { mode: 0o700, mtimeMs: 1_600_000_000_001 })
  55. const stats = vfs.statSync('/dsh/restored') as VfsStats
  56. const directory = vfs.statSync('/dsh/restored-directory') as VfsStats
  57. expect([stats.mode & 0o777, stats.mtimeMs]).toEqual([0o600, 1_600_000_000_000])
  58. expect([directory.mode & 0o777, directory.mtimeMs]).toEqual([0o700, 1_600_000_000_001])
  59. })
  60. it('advances on every write even while the clock stands still', () => {
  61. vi.spyOn(Date, 'now').mockReturnValue(1_700_000_000_000)
  62. const vfs = new MemoryVfs()
  63. vfs.seed('/dsh/log.jsonl', 'first\n')
  64. const seeded = modified(vfs, '/dsh/log.jsonl')
  65. vfs.writeFileSync('/dsh/log.jsonl', 'second\n')
  66. const written = modified(vfs, '/dsh/log.jsonl')
  67. vfs.appendFileSync('/dsh/log.jsonl', 'third\n')
  68. const appended = modified(vfs, '/dsh/log.jsonl')
  69. vfs.truncateSync('/dsh/log.jsonl', 6)
  70. const truncated = modified(vfs, '/dsh/log.jsonl')
  71. expect([written > seeded, appended > written, truncated > appended]).toEqual([true, true, true])
  72. // One millisecond per revision: the increment is the minimum that separates
  73. // two tokens, not a coarser bump that would skew a real timestamp.
  74. expect(truncated - seeded).toBe(3)
  75. })
  76. it('takes the clock once the clock has passed the entry', () => {
  77. const clock = vi.spyOn(Date, 'now').mockReturnValue(1_700_000_000_000)
  78. const vfs = new MemoryVfs()
  79. vfs.seed('/dsh/log.jsonl', 'first\n')
  80. clock.mockReturnValue(1_700_000_005_000)
  81. vfs.writeFileSync('/dsh/log.jsonl', 'second\n')
  82. expect(modified(vfs, '/dsh/log.jsonl')).toBe(1_700_000_005_000)
  83. })
  84. it('extends truncation with zero bytes', async () => {
  85. const vfs = new MemoryVfs()
  86. vfs.seed('/dsh/file', new Uint8Array([1, 2]))
  87. vfs.truncateSync('/dsh/file', 5)
  88. expect([...vfs.readFileSync('/dsh/file') as Uint8Array]).toEqual([1, 2, 0, 0, 0])
  89. const handle = vfs.open('/dsh/file', 'r+')
  90. await handle.truncate(7)
  91. expect([...vfs.readFileSync('/dsh/file') as Uint8Array]).toEqual([1, 2, 0, 0, 0, 0, 0])
  92. })
  93. it('advances a directory only when its immediate entry set changes', () => {
  94. vi.spyOn(Date, 'now').mockReturnValue(1_700_000_000_000)
  95. const vfs = new MemoryVfs()
  96. vfs.seedDirectory('/dsh/workspace')
  97. const empty = modified(vfs, '/dsh/workspace')
  98. vfs.writeFileSync('/dsh/workspace/file.txt', 'one')
  99. const created = modified(vfs, '/dsh/workspace')
  100. vfs.writeFileSync('/dsh/workspace/file.txt', 'two')
  101. const rewritten = modified(vfs, '/dsh/workspace')
  102. vfs.rmSync('/dsh/workspace/file.txt')
  103. const removed = modified(vfs, '/dsh/workspace')
  104. expect([created > empty, rewritten === created, removed > rewritten]).toEqual([true, true, true])
  105. })
  106. })
  107. describe('mutation publication', () => {
  108. it('publishes only committed runtime changes and keeps image seeding silent', () => {
  109. const vfs = new MemoryVfs()
  110. const mutations: VfsMutation[] = []
  111. vfs.subscribe((mutation) => { mutations.push(mutation) })
  112. vfs.seed('/dsh/seeded.txt', 'seeded')
  113. expect(mutations).toEqual([])
  114. vfs.writeFileSync('/dsh/seeded.txt', 'changed')
  115. vfs.mkdirSync('/dsh/created')
  116. vfs.chmodSync('/dsh/created', 0o700)
  117. vfs.renameSync('/dsh/seeded.txt', '/dsh/renamed.txt')
  118. vfs.rmSync('/dsh/created', { recursive: true })
  119. expect(mutations.map(mutation => ({
  120. kind: mutation.kind,
  121. path: mutation.path,
  122. ...mutation.kind === 'write' ? { entryChanged: mutation.entryChanged } : {},
  123. ...mutation.kind === 'chmod' ? { mode: mutation.mode } : {},
  124. }))).toEqual([
  125. { kind: 'write', path: '/dsh/seeded.txt', entryChanged: false },
  126. { kind: 'mkdir', path: '/dsh/created' },
  127. { kind: 'chmod', path: '/dsh/created', mode: 0o700 },
  128. { kind: 'remove', path: '/dsh/seeded.txt' },
  129. { kind: 'write', path: '/dsh/renamed.txt', entryChanged: true },
  130. { kind: 'remove', path: '/dsh/created' },
  131. ])
  132. const renamed = mutations[4]
  133. expect(renamed?.kind === 'write' && new TextDecoder().decode(renamed.bytes)).toBe('changed')
  134. expect(() => { vfs.writeFileSync('/missing/file', 'no') }).toThrow(/ENOENT/)
  135. expect(mutations).toHaveLength(6)
  136. })
  137. it('contains a faulty observer and lets disposal stop later notifications', () => {
  138. const vfs = new MemoryVfs()
  139. vfs.seedDirectory('/dsh')
  140. const reported = vi.spyOn(console, 'error').mockImplementation(() => {})
  141. const first = vfs.subscribe(() => { throw new Error('observer failed') })
  142. const seen: string[] = []
  143. const second = vfs.subscribe((mutation) => { seen.push(mutation.path) })
  144. vfs.writeFileSync('/dsh/one', '1')
  145. first()
  146. second()
  147. vfs.writeFileSync('/dsh/two', '2')
  148. expect(seen).toEqual(['/dsh/one'])
  149. expect(reported).toHaveBeenCalledOnce()
  150. })
  151. it('feeds the same complete mutations to a durable sink and live subscribers', async () => {
  152. const recorded: VfsMutation[] = []
  153. let flushes = 0
  154. const sink: VfsMutationSink = {
  155. record: (mutation) => { recorded.push(mutation) },
  156. flush: async () => { flushes += 1 },
  157. }
  158. const vfs = new MemoryVfs({ sink })
  159. vfs.seedDirectory('/dsh')
  160. const observed: VfsMutation[] = []
  161. vfs.subscribe((mutation) => { observed.push(mutation) })
  162. vfs.writeFileSync('/dsh/log', 'a')
  163. vfs.appendFileSync('/dsh/log', 'bc')
  164. await vfs.flush()
  165. expect(observed).toEqual(recorded)
  166. expect(observed[0]).toBe(recorded[0])
  167. expect(recorded[0]).toMatchObject({ kind: 'write', path: '/dsh/log', mode: 0o644, entryChanged: true })
  168. expect(recorded[1]).toMatchObject({ kind: 'write', path: '/dsh/log', mode: 0o644, entryChanged: false, appendedFrom: 1 })
  169. expect(recorded[1]?.kind === 'write' && new TextDecoder().decode(recorded[1].bytes)).toBe('abc')
  170. expect(flushes).toBe(1)
  171. })
  172. it('publishes descriptor writes at the file identity current path', () => {
  173. const mutations: VfsMutation[] = []
  174. const vfs = new MemoryVfs()
  175. vfs.seed('/dsh/source', 'old')
  176. const descriptor = vfs.openFileSync('/dsh/source', 'r+')
  177. vfs.subscribe((mutation) => { mutations.push(mutation) })
  178. vfs.renameSync('/dsh/source', '/dsh/destination')
  179. mutations.length = 0
  180. descriptor.write(0, new TextEncoder().encode('new'))
  181. expect(mutations.map(mutation => mutation.path)).toEqual(['/dsh/destination'])
  182. expect(vfs.readFileSync('/dsh/destination', 'utf8')).toBe('new')
  183. vfs.unlinkSync('/dsh/destination')
  184. mutations.length = 0
  185. descriptor.write(0, new TextEncoder().encode('detached'))
  186. expect(mutations).toEqual([])
  187. expect(new TextDecoder().decode(descriptor.read(0, descriptor.stat().size))).toBe('detached')
  188. })
  189. it('reports the path identity through a BigInt file handle stat', async () => {
  190. const vfs = new MemoryVfs()
  191. vfs.seed('/dsh/session.lock', '')
  192. const handle = vfs.open('/dsh/session.lock', 'w')
  193. const held = await handle.stat({ bigint: true }) as VfsBigIntStats
  194. const current = vfs.statSync('/dsh/session.lock', { bigint: true }) as VfsBigIntStats
  195. expect([held.dev, held.ino]).toEqual([current.dev, current.ino])
  196. await handle.chmod(0o600)
  197. expect((vfs.statSync('/dsh/session.lock') as VfsStats).mode & 0o777).toBe(0o600)
  198. await handle.close()
  199. })
  200. it('decomposes a directory rename into replayable destination state', () => {
  201. const recorded: VfsMutation[] = []
  202. const vfs = new MemoryVfs({
  203. sink: { record: (mutation) => { recorded.push(mutation) }, flush: () => Promise.resolve() },
  204. })
  205. vfs.seedDirectory('/dsh/staging/nested', { mode: 0o700 })
  206. vfs.seed('/dsh/staging/nested/file', 'value', { mode: 0o600 })
  207. vfs.renameSync('/dsh/staging', '/dsh/published')
  208. expect(recorded.map(mutation => [mutation.kind, mutation.path])).toEqual([
  209. ['remove', '/dsh/staging'],
  210. ['mkdir', '/dsh/published'],
  211. ['mkdir', '/dsh/published/nested'],
  212. ['write', '/dsh/published/nested/file'],
  213. ])
  214. expect(recorded[3]).toMatchObject({ kind: 'write', mode: 0o600, entryChanged: true })
  215. expect(recorded[3]?.kind === 'write' && new TextDecoder().decode(recorded[3].bytes)).toBe('value')
  216. })
  217. })
  218. describe('directory rename', () => {
  219. it('rejects file, non-empty directory, and missing-parent destinations before mutation', () => {
  220. const vfs = new MemoryVfs()
  221. vfs.seed('/dsh/source/nested/file', 'source')
  222. vfs.seed('/dsh/file', 'destination')
  223. vfs.seed('/dsh/non-empty/child', 'destination')
  224. const mutations: VfsMutation[] = []
  225. vfs.subscribe((mutation) => { mutations.push(mutation) })
  226. expect(() => { vfs.renameSync('/dsh/source', '/dsh/file') })
  227. .toThrow(expect.objectContaining({ code: 'ENOTDIR' }))
  228. expect(() => { vfs.renameSync('/dsh/source', '/dsh/non-empty') })
  229. .toThrow(expect.objectContaining({ code: 'ENOTEMPTY' }))
  230. expect(() => { vfs.renameSync('/dsh/source', '/missing/destination') })
  231. .toThrow(expect.objectContaining({ code: 'ENOENT' }))
  232. expect(vfs.readFileSync('/dsh/source/nested/file', 'utf8')).toBe('source')
  233. expect(vfs.readFileSync('/dsh/file', 'utf8')).toBe('destination')
  234. expect(vfs.readFileSync('/dsh/non-empty/child', 'utf8')).toBe('destination')
  235. expect(mutations).toEqual([])
  236. })
  237. it('replaces an empty directory with the source subtree', () => {
  238. const vfs = new MemoryVfs()
  239. vfs.seedDirectory('/dsh/source/nested', { mode: 0o700 })
  240. vfs.seed('/dsh/source/nested/file', 'source')
  241. vfs.seedDirectory('/dsh/destination', { mode: 0o711 })
  242. vfs.renameSync('/dsh/source', '/dsh/destination')
  243. expect(vfs.existsSync('/dsh/source')).toBe(false)
  244. expect(vfs.readFileSync('/dsh/destination/nested/file', 'utf8')).toBe('source')
  245. expect((vfs.statSync('/dsh/destination') as VfsStats).mode & 0o777).toBe(0o755)
  246. expect((vfs.statSync('/dsh/destination/nested') as VfsStats).mode & 0o777).toBe(0o700)
  247. })
  248. })
  249. describe('hard links', () => {
  250. it('shares identity, bytes, and mode until one name is removed', () => {
  251. const vfs = new MemoryVfs()
  252. vfs.seed('/dsh/session.jsonl', 'committed\n')
  253. vfs.linkSync('/dsh/session.jsonl', '/dsh/session-latest.jsonl')
  254. vfs.linkSync('/dsh/session-latest.jsonl', '/dsh/session-archive.jsonl')
  255. expect(identity(vfs, '/dsh/session-latest.jsonl')).toBe(identity(vfs, '/dsh/session.jsonl'))
  256. expect(linkCount(vfs, '/dsh/session.jsonl')).toBe(3n)
  257. expect(vfs.readFileSync('/dsh/session-latest.jsonl', 'utf8')).toBe('committed\n')
  258. const changedPaths: string[] = []
  259. vfs.subscribe((mutation) => { changedPaths.push(mutation.path) })
  260. vfs.appendFileSync('/dsh/session.jsonl', 'appended\n')
  261. expect(changedPaths).toEqual([
  262. '/dsh/session.jsonl',
  263. '/dsh/session-latest.jsonl',
  264. '/dsh/session-archive.jsonl',
  265. ])
  266. expect(vfs.readFileSync('/dsh/session.jsonl', 'utf8')).toBe('committed\nappended\n')
  267. expect(vfs.readFileSync('/dsh/session-latest.jsonl', 'utf8')).toBe('committed\nappended\n')
  268. vfs.chmodSync('/dsh/session-latest.jsonl', 0o600)
  269. expect((vfs.statSync('/dsh/session.jsonl') as VfsStats).mode & 0o777).toBe(0o600)
  270. vfs.unlinkSync('/dsh/session-latest.jsonl')
  271. expect(linkCount(vfs, '/dsh/session.jsonl')).toBe(2n)
  272. vfs.unlinkSync('/dsh/session-archive.jsonl')
  273. expect(linkCount(vfs, '/dsh/session.jsonl')).toBe(1n)
  274. expect(vfs.readFileSync('/dsh/session.jsonl', 'utf8')).toBe('committed\nappended\n')
  275. })
  276. it('treats rename between names of the same node as a no-op', () => {
  277. const vfs = new MemoryVfs()
  278. vfs.seed('/dsh/source', 'value')
  279. vfs.linkSync('/dsh/source', '/dsh/alias')
  280. const mutations: VfsMutation[] = []
  281. vfs.subscribe((mutation) => { mutations.push(mutation) })
  282. vfs.renameSync('/dsh/source', '/dsh/alias')
  283. expect(vfs.readFileSync('/dsh/source', 'utf8')).toBe('value')
  284. expect(vfs.readFileSync('/dsh/alias', 'utf8')).toBe('value')
  285. expect(linkCount(vfs, '/dsh/source')).toBe(2n)
  286. expect(mutations).toEqual([])
  287. })
  288. it('retargets linked names through file replacement and directory moves', () => {
  289. const vfs = new MemoryVfs()
  290. vfs.seed('/dsh/replacement', 'replacement')
  291. vfs.seed('/dsh/target', 'old')
  292. vfs.linkSync('/dsh/target', '/dsh/target-alias')
  293. const replaced = vfs.openFileSync('/dsh/target', 'r+')
  294. vfs.renameSync('/dsh/replacement', '/dsh/target')
  295. const mutations: VfsMutation[] = []
  296. vfs.subscribe((mutation) => { mutations.push(mutation) })
  297. replaced.write(0, new TextEncoder().encode('changed'))
  298. expect(mutations.map(mutation => mutation.path)).toEqual(['/dsh/target-alias'])
  299. expect(vfs.readFileSync('/dsh/target', 'utf8')).toBe('replacement')
  300. expect(vfs.readFileSync('/dsh/target-alias', 'utf8')).toBe('changed')
  301. expect(linkCount(vfs, '/dsh/target-alias')).toBe(1n)
  302. vfs.seed('/dsh/tree/file', 'tree')
  303. vfs.linkSync('/dsh/tree/file', '/dsh/outside')
  304. const moved = vfs.openFileSync('/dsh/tree/file', 'r+')
  305. vfs.renameSync('/dsh/tree', '/dsh/moved')
  306. mutations.length = 0
  307. moved.write(0, new TextEncoder().encode('moved'))
  308. expect(mutations.map(mutation => mutation.path)).toEqual(['/dsh/outside', '/dsh/moved/file'])
  309. expect(linkCount(vfs, '/dsh/moved/file')).toBe(2n)
  310. vfs.rmSync('/dsh/moved', { recursive: true })
  311. mutations.length = 0
  312. moved.write(0, new TextEncoder().encode('kept!'))
  313. expect(mutations.map(mutation => mutation.path)).toEqual(['/dsh/outside'])
  314. expect(vfs.readFileSync('/dsh/outside', 'utf8')).toBe('kept!')
  315. expect(linkCount(vfs, '/dsh/outside')).toBe(1n)
  316. })
  317. it('rejects renaming a file over an existing directory', () => {
  318. const vfs = new MemoryVfs()
  319. vfs.seed('/dsh/file', 'value')
  320. vfs.seedDirectory('/dsh/directory')
  321. expect(() => { vfs.renameSync('/dsh/file', '/dsh/directory') }).toThrow(expect.objectContaining({ code: 'EISDIR' }))
  322. expect(vfs.readFileSync('/dsh/file', 'utf8')).toBe('value')
  323. expect(vfs.statSync('/dsh/directory').isDirectory()).toBe(true)
  324. })
  325. })