From 0e98fdaf8f2bf1c243fafe2e4ea70b9a3416ea13 Mon Sep 17 00:00:00 2001 From: Hadrien Blanc Date: Mon, 2 Nov 2026 12:04:54 +0100 Subject: [PATCH] Fix stale file reads during a CLI rebuild A chain link was appended for each event that got past pendingRebuilds. A raw rename read the file and then awaited that chain, so the pending slot stayed taken and later renames of the same file were dropped. The follow-up rebuild kept the first read. Keep one pending change per file and one in-flight rebuild. Resolve recordChangedFile immediately so a later rename replaces the queued read. --- CHANGELOG.md | 1 + src/cli/build/watching.js | 92 +++++++++++------------- tests/watching.test.js | 145 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 187 insertions(+), 51 deletions(-) create mode 100644 tests/watching.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 6416b45c670c..fd9a8e2fb4ce 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- Use the latest file contents when an atomic save lands during a CLI `--watch` rebuild ([#20636](https://github.com/tailwindlabs/tailwindcss/pull/20636)) - Ensure classes are extracted when a variant precedes an arbitrary variant containing a quoted attribute selector (e.g. `focus-visible:[&:not([aria-selected="true"])]:bg-red-500`) ([#20374](https://github.com/tailwindlabs/tailwindcss/pull/20374)) - Fix negation of `theme()` in arbitrary values (e.g. `-m-[theme(margin.1)]`) ([#19928](https://github.com/tailwindlabs/tailwindcss/pull/19928)) diff --git a/src/cli/build/watching.js b/src/cli/build/watching.js index b7788726c1cb..aa73e4b3bc13 100644 --- a/src/cli/build/watching.js +++ b/src/cli/build/watching.js @@ -50,15 +50,12 @@ export function createWatcher(args, { state, rebuild }) { : false, }) - // A queue of rebuilds, file reads, etc… to run - let chain = Promise.resolve() - /** - * A list of files that have been changed since the last rebuild + * Latest pending change per file. * - * @type {{file: string, content: () => Promise, extension: string}[]} + * @type {Map Promise, extension: string}>} */ - let changedContent = [] + let changedFiles = new Map() /** * A list of files for which a rebuild has already been queued. @@ -68,31 +65,48 @@ export function createWatcher(args, { state, rebuild }) { **/ let pendingRebuilds = new Set() - let _timer - let _reject + /** @type {ReturnType | null} */ + let timer = null - /** - * Rebuilds the changed files and resolves when the rebuild is - * complete regardless of whether it was successful or not - */ - async function rebuildAndContinue() { - let changes = changedContent.splice(0) + let running = false + + function arm() { + if (running) { + return + } + + if (timer) { + clearTimeout(timer) + } + + timer = setTimeout(run, 10) + } + + async function run() { + timer = null + + let changes = [...changedFiles.values()] + changedFiles.clear() - // There are no changes to rebuild so we can just do nothing if (changes.length === 0) { - return Promise.resolve() + return } // Clear all pending rebuilds for the about-to-be-built files changes.forEach((change) => pendingRebuilds.delete(change.file)) - // Resolve the promise even when the rebuild fails - return rebuild(changes).then( - () => {}, - (e) => { - console.error(e.toString()) - } - ) + running = true + try { + await rebuild(changes) + } catch (e) { + console.error(e.toString()) + } finally { + running = false + } + + if (changedFiles.size > 0) { + arm() + } } /** @@ -115,33 +129,15 @@ export function createWatcher(args, { state, rebuild }) { // It MUST happen synchronously before the rebuild is queued for this to be effective pendingRebuilds.add(file) - changedContent.push({ + changedFiles.set(file, { file, content: content ?? (() => fs.promises.readFile(file, 'utf8')), extension: path.extname(file).slice(1), }) - if (_timer) { - clearTimeout(_timer) - _reject() - } + arm() - // If a rebuild is already in progress we don't want to start another one until the 10ms timer has expired - chain = chain.then( - () => - new Promise((resolve, reject) => { - _timer = setTimeout(resolve, 10) - _reject = reject - }) - ) - - // Resolves once this file has been rebuilt (or the rebuild for this file has failed) - // This queues as many rebuilds as there are changed files - // But those rebuilds happen after some delay - // And will immediately resolve if there are no changes - chain = chain.then(rebuildAndContinue, rebuildAndContinue) - - return chain + return Promise.resolve() } watcher.on('change', (file) => recordChangedFile(file)) @@ -184,23 +180,17 @@ export function createWatcher(args, { state, rebuild }) { return } - // We'll go ahead and add the file to the pending rebuilds list here - // It'll be removed when the rebuild starts unless the read fails - // which will be taken care of as well pendingRebuilds.add(filePath) async function enqueue() { try { - // We need to read the file as early as possible outside of the chain - // because it may be gone by the time we get to it. doing the read - // immediately increases the chance that the file is still there + // The file may be gone by the time the rebuild runs. let content = await readFileWithRetries(path.resolve(filePath)) if (content === undefined) { return } - // This will push the rebuild onto the chain // We MUST skip the rebuild check here otherwise the rebuild will never happen on Linux // This is because the order of events and timing is different on Linux // @ts-ignore: TypeScript isn't picking up that content is a string here diff --git a/tests/watching.test.js b/tests/watching.test.js new file mode 100644 index 000000000000..3645620becf5 --- /dev/null +++ b/tests/watching.test.js @@ -0,0 +1,145 @@ +import fs from 'fs' +import os from 'os' +import path from 'path' +import { createWatcher } from '../src/cli/build/watching' + +let tmp +let current +let releaseGate = () => {} + +beforeEach(() => { + tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'tw-watch-')) +}) + +afterEach(async () => { + releaseGate() + releaseGate = () => {} + await current?.fswatcher.close() + current = undefined + fs.rmSync(tmp, { recursive: true, force: true }) +}) + +function write(name, text) { + let file = path.join(tmp, name) + fs.writeFileSync(file, text) + return file +} + +function delay(ms) { + return new Promise((resolve) => setTimeout(resolve, ms)) +} + +async function waitFor(predicate) { + let started = Date.now() + while (!predicate()) { + if (Date.now() - started > 5000) { + throw new Error('timed out waiting for the watcher') + } + await delay(10) + } +} + +function watch(rebuild) { + current = createWatcher( + {}, + { + state: { + contentPatterns: { + all: [path.join(tmp, '**/*')], + dynamic: [path.join(tmp, '**/*')], + }, + contextDependencies: new Set(), + configBag: { dependencies: new Set() }, + }, + rebuild, + } + ) + + return current +} + +async function readChanges(changes) { + let read = [] + for (let change of changes) { + read.push({ + file: change.file, + extension: change.extension, + content: await change.content(), + }) + } + return read +} + +function holdFirstRebuild() { + let calls = [] + let markStarted + let started = new Promise((resolve) => { + markStarted = resolve + }) + let gate = new Promise((resolve) => { + releaseGate = resolve + }) + + watch(async (changes) => { + calls.push(await readChanges(changes)) + if (calls.length === 1) { + markStarted() + await gate + } + }) + + return { calls, started } +} + +test('repeated change events during a rebuild still coalesce into one follow-up read', async () => { + let { calls, started } = holdFirstRebuild() + let page = write('page.html', 'initial') + let view = write('view.html', 'initial') + + current.fswatcher.emit('change', page) + await started + + for (let i = 0; i < 20; i++) { + fs.writeFileSync(page, `page ${i}`) + fs.writeFileSync(view, `view ${i}`) + current.fswatcher.emit('change', page) + current.fswatcher.emit('change', view) + } + releaseGate() + + await waitFor(() => calls.length >= 2) + await delay(80) + + expect(calls).toHaveLength(2) + expect(calls[1]).toEqual([ + { file: path.resolve(page), extension: 'html', content: 'page 19' }, + { file: path.resolve(view), extension: 'html', content: 'view 19' }, + ]) +}) + +test('rename events during a rebuild keep each file once, with its latest text', async () => { + let { calls, started } = holdFirstRebuild() + let page = write('page.html', 'seed') + let view = write('view.html', 'seed') + + current.fswatcher.emit('change', page) + await started + + for (let i = 0; i < 8; i++) { + fs.writeFileSync(page, `page ${i}`) + fs.writeFileSync(view, `view ${i}`) + current.fswatcher.emit('raw', 'rename', page, { watchedPath: page }) + current.fswatcher.emit('raw', 'rename', view, { watchedPath: view }) + await delay(30) + } + releaseGate() + + await waitFor(() => calls.length >= 2) + await delay(80) + + expect(calls).toHaveLength(2) + expect(calls[1]).toEqual([ + { file: path.resolve(page), extension: 'html', content: 'page 7' }, + { file: path.resolve(view), extension: 'html', content: 'view 7' }, + ]) +})