memory-vfs.spec.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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('decomposes a directory rename into replayable destination state', () => {
  190. const recorded: VfsMutation[] = []
  191. const vfs = new MemoryVfs({
  192. sink: { record: (mutation) => { recorded.push(mutation) }, flush: () => Promise.resolve() },
  193. })
  194. vfs.seedDirectory('/dsh/staging/nested', { mode: 0o700 })
  195. vfs.seed('/dsh/staging/nested/file', 'value', { mode: 0o600 })
  196. vfs.renameSync('/dsh/staging', '/dsh/published')
  197. expect(recorded.map(mutation => [mutation.kind, mutation.path])).toEqual([
  198. ['remove', '/dsh/staging'],
  199. ['mkdir', '/dsh/published'],
  200. ['mkdir', '/dsh/published/nested'],
  201. ['write', '/dsh/published/nested/file'],
  202. ])
  203. expect(recorded[3]).toMatchObject({ kind: 'write', mode: 0o600, entryChanged: true })
  204. expect(recorded[3]?.kind === 'write' && new TextDecoder().decode(recorded[3].bytes)).toBe('value')
  205. })
  206. })
  207. describe('directory rename', () => {
  208. it('rejects file, non-empty directory, and missing-parent destinations before mutation', () => {
  209. const vfs = new MemoryVfs()
  210. vfs.seed('/dsh/source/nested/file', 'source')
  211. vfs.seed('/dsh/file', 'destination')
  212. vfs.seed('/dsh/non-empty/child', 'destination')
  213. const mutations: VfsMutation[] = []
  214. vfs.subscribe((mutation) => { mutations.push(mutation) })
  215. expect(() => { vfs.renameSync('/dsh/source', '/dsh/file') })
  216. .toThrow(expect.objectContaining({ code: 'ENOTDIR' }))
  217. expect(() => { vfs.renameSync('/dsh/source', '/dsh/non-empty') })
  218. .toThrow(expect.objectContaining({ code: 'ENOTEMPTY' }))
  219. expect(() => { vfs.renameSync('/dsh/source', '/missing/destination') })
  220. .toThrow(expect.objectContaining({ code: 'ENOENT' }))
  221. expect(vfs.readFileSync('/dsh/source/nested/file', 'utf8')).toBe('source')
  222. expect(vfs.readFileSync('/dsh/file', 'utf8')).toBe('destination')
  223. expect(vfs.readFileSync('/dsh/non-empty/child', 'utf8')).toBe('destination')
  224. expect(mutations).toEqual([])
  225. })
  226. it('replaces an empty directory with the source subtree', () => {
  227. const vfs = new MemoryVfs()
  228. vfs.seedDirectory('/dsh/source/nested', { mode: 0o700 })
  229. vfs.seed('/dsh/source/nested/file', 'source')
  230. vfs.seedDirectory('/dsh/destination', { mode: 0o711 })
  231. vfs.renameSync('/dsh/source', '/dsh/destination')
  232. expect(vfs.existsSync('/dsh/source')).toBe(false)
  233. expect(vfs.readFileSync('/dsh/destination/nested/file', 'utf8')).toBe('source')
  234. expect((vfs.statSync('/dsh/destination') as VfsStats).mode & 0o777).toBe(0o755)
  235. expect((vfs.statSync('/dsh/destination/nested') as VfsStats).mode & 0o777).toBe(0o700)
  236. })
  237. })
  238. describe('hard links', () => {
  239. it('shares identity, bytes, and mode until one name is removed', () => {
  240. const vfs = new MemoryVfs()
  241. vfs.seed('/dsh/session.jsonl', 'committed\n')
  242. vfs.linkSync('/dsh/session.jsonl', '/dsh/session-latest.jsonl')
  243. vfs.linkSync('/dsh/session-latest.jsonl', '/dsh/session-archive.jsonl')
  244. expect(identity(vfs, '/dsh/session-latest.jsonl')).toBe(identity(vfs, '/dsh/session.jsonl'))
  245. expect(linkCount(vfs, '/dsh/session.jsonl')).toBe(3n)
  246. expect(vfs.readFileSync('/dsh/session-latest.jsonl', 'utf8')).toBe('committed\n')
  247. const changedPaths: string[] = []
  248. vfs.subscribe((mutation) => { changedPaths.push(mutation.path) })
  249. vfs.appendFileSync('/dsh/session.jsonl', 'appended\n')
  250. expect(changedPaths).toEqual([
  251. '/dsh/session.jsonl',
  252. '/dsh/session-latest.jsonl',
  253. '/dsh/session-archive.jsonl',
  254. ])
  255. expect(vfs.readFileSync('/dsh/session.jsonl', 'utf8')).toBe('committed\nappended\n')
  256. expect(vfs.readFileSync('/dsh/session-latest.jsonl', 'utf8')).toBe('committed\nappended\n')
  257. vfs.chmodSync('/dsh/session-latest.jsonl', 0o600)
  258. expect((vfs.statSync('/dsh/session.jsonl') as VfsStats).mode & 0o777).toBe(0o600)
  259. vfs.unlinkSync('/dsh/session-latest.jsonl')
  260. expect(linkCount(vfs, '/dsh/session.jsonl')).toBe(2n)
  261. vfs.unlinkSync('/dsh/session-archive.jsonl')
  262. expect(linkCount(vfs, '/dsh/session.jsonl')).toBe(1n)
  263. expect(vfs.readFileSync('/dsh/session.jsonl', 'utf8')).toBe('committed\nappended\n')
  264. })
  265. it('treats rename between names of the same node as a no-op', () => {
  266. const vfs = new MemoryVfs()
  267. vfs.seed('/dsh/source', 'value')
  268. vfs.linkSync('/dsh/source', '/dsh/alias')
  269. const mutations: VfsMutation[] = []
  270. vfs.subscribe((mutation) => { mutations.push(mutation) })
  271. vfs.renameSync('/dsh/source', '/dsh/alias')
  272. expect(vfs.readFileSync('/dsh/source', 'utf8')).toBe('value')
  273. expect(vfs.readFileSync('/dsh/alias', 'utf8')).toBe('value')
  274. expect(linkCount(vfs, '/dsh/source')).toBe(2n)
  275. expect(mutations).toEqual([])
  276. })
  277. it('retargets linked names through file replacement and directory moves', () => {
  278. const vfs = new MemoryVfs()
  279. vfs.seed('/dsh/replacement', 'replacement')
  280. vfs.seed('/dsh/target', 'old')
  281. vfs.linkSync('/dsh/target', '/dsh/target-alias')
  282. const replaced = vfs.openFileSync('/dsh/target', 'r+')
  283. vfs.renameSync('/dsh/replacement', '/dsh/target')
  284. const mutations: VfsMutation[] = []
  285. vfs.subscribe((mutation) => { mutations.push(mutation) })
  286. replaced.write(0, new TextEncoder().encode('changed'))
  287. expect(mutations.map(mutation => mutation.path)).toEqual(['/dsh/target-alias'])
  288. expect(vfs.readFileSync('/dsh/target', 'utf8')).toBe('replacement')
  289. expect(vfs.readFileSync('/dsh/target-alias', 'utf8')).toBe('changed')
  290. expect(linkCount(vfs, '/dsh/target-alias')).toBe(1n)
  291. vfs.seed('/dsh/tree/file', 'tree')
  292. vfs.linkSync('/dsh/tree/file', '/dsh/outside')
  293. const moved = vfs.openFileSync('/dsh/tree/file', 'r+')
  294. vfs.renameSync('/dsh/tree', '/dsh/moved')
  295. mutations.length = 0
  296. moved.write(0, new TextEncoder().encode('moved'))
  297. expect(mutations.map(mutation => mutation.path)).toEqual(['/dsh/outside', '/dsh/moved/file'])
  298. expect(linkCount(vfs, '/dsh/moved/file')).toBe(2n)
  299. vfs.rmSync('/dsh/moved', { recursive: true })
  300. mutations.length = 0
  301. moved.write(0, new TextEncoder().encode('kept!'))
  302. expect(mutations.map(mutation => mutation.path)).toEqual(['/dsh/outside'])
  303. expect(vfs.readFileSync('/dsh/outside', 'utf8')).toBe('kept!')
  304. expect(linkCount(vfs, '/dsh/outside')).toBe(1n)
  305. })
  306. it('rejects renaming a file over an existing directory', () => {
  307. const vfs = new MemoryVfs()
  308. vfs.seed('/dsh/file', 'value')
  309. vfs.seedDirectory('/dsh/directory')
  310. expect(() => { vfs.renameSync('/dsh/file', '/dsh/directory') }).toThrow(expect.objectContaining({ code: 'EISDIR' }))
  311. expect(vfs.readFileSync('/dsh/file', 'utf8')).toBe('value')
  312. expect(vfs.statSync('/dsh/directory').isDirectory()).toBe(true)
  313. })
  314. })