vercel/next.js · #102016

Turbopack: diff server HMR pulls against a Rust-owned loaded-module set

wbinnssmith · merged Nov 23, 202627 files · 964 + / 522 −
Cargo.lock1 + / 0 −
@@ -4153,6 +4153,7 @@ dependencies = [  "tokio",  "tracing",  "turbo-bincode",+ "turbo-frozenmap",  "turbo-rcstr",  "turbo-tasks",  "turbo-tasks-backend",
crates/next-api/Cargo.toml1 + / 0 −
@@ -36,6 +36,7 @@ swc_core = { workspace = true } tracing = { workspace = true } tokio = { workspace = true } turbo-bincode = { workspace = true }+turbo-frozenmap = { workspace = true } turbo-rcstr = { workspace = true } turbo-tasks = { workspace = true } turbo-tasks-hash = { workspace = true }
crates/next-api/src/aggregate_hmr.rs532 + / 379 −
@@ -4,27 +4,37 @@ use std::{ };  use anyhow::Result;+use bincode::{+    Decode, Encode,+    de::Decoder,+    enc::Encoder,+    error::{DecodeError, EncodeError},+    impl_borrow_decode,+};+use rustc_hash::{FxHashMap, FxHashSet}; use serde::Serialize;+use smallvec::SmallVec;+use turbo_frozenmap::{FrozenMap, FrozenSet}; use turbo_rcstr::RcStr; use turbo_tasks::{-    FxIndexMap, FxIndexSet, NonLocalValue, ReadRef, ResolvedVc, TryJoinIterExt, Vc,+    FxIndexMap, FxIndexSet, NonLocalValue, OperationValue, OperationVc, ReadRef, ResolvedVc, State,+    TransientInstance, TryJoinIterExt, Vc,     debug::ValueDebugFormat,     message_queue::{CompilationEvent, Severity},     turbo_tasks, };-use turbo_tasks_hash::{Xxh3Hash64Hasher, encode_base64}; use turbopack_core::{-    update_instruction::UpdateInstruction,-    version::{PartialUpdate, Update, Version},-};-use turbopack_ecmascript::chunk_list::{-    merged_update::EcmascriptMergedUpdate,-    update::{ChunkListUpdate, ChunkUpdate, EcmascriptUpdateInstruction},-    version::ChunkListVersion,+    chunk::ModuleId,+    version::{Version, VersionedContent}, };-use turbopack_nodejs::ecmascript::node::entry::chunk_list_content::{-    EcmascriptBuildNodeChunkListContent, compute_update_from_version_operation,+use turbopack_ecmascript::{+    chunk_list::merged_update::{+        EcmascriptMergedChunkPartial, EcmascriptMergedChunkUpdate, EcmascriptMergedUpdate,+        EcmascriptModuleEntry,+    },+    hmr::{EcmascriptHmrChunkContent, version::EcmascriptChunkVersion}, };+use turbopack_nodejs::ecmascript::node::entry::chunk_list_content::EcmascriptBuildNodeChunkListContent;  #[derive(Clone, PartialEq, Eq, ValueDebugFormat, NonLocalValue)] pub struct ServerHmrChunkList {@@ -51,117 +61,330 @@ impl ServerHmrChunkLists {     } } -#[turbo_tasks::value(serialization = "skip", shared)]-#[derive(Debug)]-pub struct ServerHmrChunkListVersion {-    pub versions_by_chunk_list_path: FxIndexMap<RcStr, ReadRef<ChunkListVersion>>,+/// What the server runtimes have loaded, as far as server HMR knows: the modules of every route+/// pulled since the server modules were last fully re-evaluated, and the modules shipped to the+/// runtimes since then.+///+/// Held in a project-global `State`.+#[derive(Clone, Debug, Default, PartialEq, Eq, NonLocalValue, OperationValue)]+pub struct ServerHmrLoadedState {+    /// The code a runtime may have installed for a module, by runtime directory (the chunks'+    /// output directory, which is how updates are routed to a runtime) and module id. Each runtime+    /// has its own module factories, and some ids (e.g. externals) are loaded by several runtimes.+    ///+    /// Usually one piece of code. A runtime installs a module from whichever of its chunks loads+    /// first, so when the chunks have different code for the module (see+    /// [`ServerHmrRouteModule::code`]), any of them may be installed.+    modules: FxHashMap<RuntimeDirectory, FxHashMap<ModuleId, SmallVec<[InstalledCode; 1]>>>,+    /// Version ids of chunks that can't be expanded into modules, by chunk path.+    opaque_chunks: FxHashMap<RcStr, RcStr>,+    /// The routes pulled, by entry paths.+    pulled_routes: FxHashSet<FrozenSet<RcStr>>, } -#[turbo_tasks::value_impl]-impl Version for ServerHmrChunkListVersion {-    #[turbo_tasks::function]-    async fn id(&self) -> Result<Vc<RcStr>> {-        let mut hasher = Xxh3Hash64Hasher::new();-        hasher.write_value(self.versions_by_chunk_list_path.len());-        for (path, version) in &self.versions_by_chunk_list_path {-            hasher.write_value(path.as_str());-            hasher.write_value(version.id.as_str());-        }-        Ok(Vc::cell(encode_base64(hasher.finish()).into()))+impl Encode for ServerHmrLoadedState {+    fn encode<E: Encoder>(&self, _encoder: &mut E) -> Result<(), EncodeError> {+        Ok(())     } } -impl ServerHmrChunkListVersion {-    pub async fn from_chunk_lists(chunk_lists: &[ServerHmrChunkList]) -> Result<Self> {-        let versions_by_chunk_list_path = chunk_lists-            .iter()-            .map(|chunk_list| {-                let relative_path = chunk_list.relative_path.clone();-                let versioned_content = chunk_list.versioned_content;-                async move {-                    let version = versioned_content.version().await?;-                    anyhow::Ok((relative_path, version))-                }-            })-            .try_join()-            .await?-            .into_iter()-            .collect();-        Ok(Self {-            versions_by_chunk_list_path,-        })+impl<Context> Decode<Context> for ServerHmrLoadedState {+    fn decode<D: Decoder<Context = Context>>(_decoder: &mut D) -> Result<Self, DecodeError> {+        Ok(Self::default())     } } -#[derive(Default)]-pub struct ChunkListUpdateBuilder {-    chunks: FxIndexMap<RcStr, ChunkUpdate>,-    merged: FxIndexSet<EcmascriptMergedUpdate>,+impl_borrow_decode!(ServerHmrLoadedState);++/// The output directory of a server runtime's chunks, which identifies the runtime: each runtime+/// has its own module factories, and updates are routed to a runtime by the directory of their+/// chunks.+#[derive(Clone, Debug, PartialEq, Eq, Hash, ValueDebugFormat, NonLocalValue, OperationValue)]+pub struct RuntimeDirectory(RcStr);++impl RuntimeDirectory {+    fn of_chunk(chunk_path: &str) -> Self {+        Self(+            chunk_path+                .rsplit_once('/')+                .map_or("", |(dir, _)| dir)+                .into(),+        )+    } } -impl ChunkListUpdateBuilder {-    pub fn add_instruction(&mut self, instruction: &UpdateInstruction) {-        let instruction = instruction-            .downcast_ref::<EcmascriptUpdateInstruction>()-            .expect("aggregate HMR only accepts ECMAScript update instructions");+/// Code that a runtime may have installed for a module.+#[derive(Clone, Copy, Debug, PartialEq, Eq, NonLocalValue, OperationValue)]+struct InstalledCode {+    /// The hash of the installed code.+    hash: u128,+    /// The chunk the code was installed from. Read for the chunk's *current* version, to check+    /// whether it still has this code (see `outdated_modules`), so it is not a snapshot.+    chunk_version: OperationVc<EcmascriptChunkVersion>,+} -        match instruction {-            EcmascriptUpdateInstruction::ChunkList(update) => {-                for (chunk_path, update) in &update.chunks {-                    self.chunks.insert(chunk_path.clone(), update.clone());-                }-                for update in &update.merged {-                    self.push_merged(update);+#[turbo_tasks::function(operation, root)]+fn server_hmr_chunk_version_operation(+    content: ResolvedVc<Box<dyn EcmascriptHmrChunkContent>>,+) -> Vc<EcmascriptChunkVersion> {+    content.ecmascript_chunk_version()+}++impl ServerHmrLoadedState {+    /// Records a route's modules as loaded, after the `outdated` ones (by runtime index) were+    /// shipped. Returns whether anything changed.+    fn record(+        &mut self,+        route: &ServerHmrRouteModules,+        entry_paths: FrozenSet<RcStr>,+        outdated: &[FxHashSet<ModuleId>],+    ) -> bool {+        let mut changed = self.pulled_routes.insert(entry_paths);+        for (index, runtime) in route.runtimes.iter().enumerate() {+            if runtime.modules.is_empty() {+                continue;+            }+            let outdated = outdated.get(index);+            let modules = self.modules.entry(runtime.output_dir.clone()).or_default();+            let mut chunk_versions = vec![None; runtime.chunks.len()];+            let mut installed_code = |code: &ServerHmrModuleCode| InstalledCode {+                hash: code.hash,+                chunk_version: *chunk_versions[code.chunk].get_or_insert_with(|| {+                    server_hmr_chunk_version_operation(runtime.chunks[code.chunk].content)+                }),+            };+            for (id, module) in &runtime.modules {+                match modules.get_mut(id) {+                    // Up to date modules stay installed as they are.+                    Some(_) if !outdated.is_some_and(|outdated| outdated.contains(id)) => {}+                    // Shipped.+                    Some(installed) => {+                        *installed = module+                            .code+                            .first()+                            .into_iter()+                            .map(&mut installed_code)+                            .collect();+                        changed = true;+                    }+                    // Installed from any of the route's chunks (or shipped).+                    None => {+                        let code = module.code.iter().map(&mut installed_code).collect();+                        modules.insert(id.clone(), code);+                        changed = true;+                    }                 }             }-            EcmascriptUpdateInstruction::Merged(update) => self.push_merged(update),         }+        for opaque in &route.opaque_chunks {+            changed |= self+                .opaque_chunks+                .insert(opaque.path.clone(), opaque.version_id.clone())+                .as_ref()+                != Some(&opaque.version_id);+        }+        changed     }+} -    fn push_merged(&mut self, update: &EcmascriptMergedUpdate) {-        self.merged.insert(update.clone());-    }+#[derive(Clone, PartialEq, Eq, ValueDebugFormat, NonLocalValue)]+pub struct ServerHmrRouteChunk {+    pub content: ResolvedVc<Box<dyn EcmascriptHmrChunkContent>>,+    pub version: ReadRef<EcmascriptChunkVersion>,+}++/// Code that a route's chunks have for a module.+#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueDebugFormat, NonLocalValue)]+pub struct ServerHmrModuleCode {+    /// The index of the chunk (in [`ServerHmrRouteRuntime::chunks`]) that has the code.+    pub chunk: usize,+    pub hash: u128,+} -    pub fn is_empty(&self) -> bool {-        self.chunks.is_empty() && self.merged.is_empty()+/// A module of a route, in one runtime.+#[derive(Clone, Debug, Default, PartialEq, Eq, ValueDebugFormat, NonLocalValue)]+pub struct ServerHmrRouteModule {+    /// The distinct code the runtime's chunks have for the module. The first is shipped.+    ///+    /// Usually one piece of code. Async loaders, for example, only load the chunks that aren't+    /// available yet where they are imported, so their code depends on the chunk that has them.+    pub code: SmallVec<[ServerHmrModuleCode; 1]>,+}++impl ServerHmrRouteModule {+    fn has(&self, hash: u128) -> bool {+        self.code.iter().any(|code| code.hash == hash)     }+}++/// A route's chunks that one runtime loads, expanded into modules.+#[derive(Clone, PartialEq, Eq, ValueDebugFormat, NonLocalValue)]+pub struct ServerHmrRouteRuntime {+    pub output_dir: RuntimeDirectory,+    pub chunks: Vec<ServerHmrRouteChunk>,+    pub modules: FxIndexMap<ModuleId, ServerHmrRouteModule>,+}++/// A chunk of a route's chunk lists whose content isn't ECMAScript, so it can't be expanded into+/// modules and only its version is compared. Server chunk lists normally only have ECMAScript+/// chunks (CSS and WebAssembly, for example, don't add any), but a chunk list can track any output+/// asset.+#[derive(Clone, Debug, PartialEq, Eq, ValueDebugFormat, NonLocalValue)]+pub struct ServerHmrOpaqueChunk {+    pub path: RcStr,+    pub version_id: RcStr,+}++/// A route's chunks, by runtime.+#[turbo_tasks::value(serialization = "skip", shared)]+pub struct ServerHmrRouteModules {+    pub runtimes: Vec<ServerHmrRouteRuntime>,+    pub opaque_chunks: Vec<ServerHmrOpaqueChunk>,+}++impl ServerHmrRouteModules {+    pub async fn from_chunk_lists(chunk_lists: &[ServerHmrChunkList]) -> Result<Self> {+        let mut contents = FxIndexMap::default();+        for chunk_list in chunk_lists {+            let chunk_list = chunk_list.versioned_content.await?;+            for (path, content) in chunk_list.chunks_contents() {+                contents.insert(path.clone(), *content);+            }+        } -    pub fn build(self) -> UpdateInstruction {-        ChunkListUpdate {-            chunks: self.chunks,-            merged: self.merged.into_iter().collect(),+        let mut ecmascript = Vec::new();+        let mut opaque = Vec::new();+        for (path, content) in contents {+            match ResolvedVc::try_sidecast::<Box<dyn EcmascriptHmrChunkContent>>(content) {+                Some(content) => ecmascript.push(content),+                None => opaque.push((RcStr::from(path), content)),+            }+        }++        let chunks = ecmascript+            .into_iter()+            .map(async |content| {+                Ok(ServerHmrRouteChunk {+                    content,+                    version: content.ecmascript_chunk_version().await?,+                })+            })+            .try_join()+            .await?;+        let mut runtimes = FxIndexMap::<RuntimeDirectory, ServerHmrRouteRuntime>::default();+        for chunk in chunks {+            let dir = RuntimeDirectory::of_chunk(&chunk.version.chunk_path);+            let runtime = runtimes+                .entry(dir.clone())+                .or_insert_with(|| ServerHmrRouteRuntime {+                    output_dir: dir,+                    chunks: Vec::new(),+                    modules: FxIndexMap::default(),+                });+            let index = runtime.chunks.len();+            for (id, &hash) in &chunk.version.entries_hashes {+                let module = runtime.modules.entry(id.clone()).or_default();+                if !module.has(hash) {+                    module.code.push(ServerHmrModuleCode { chunk: index, hash });+                }+            }+            runtime.chunks.push(chunk);         }-        .into_instruction()++        let opaque_chunks = opaque+            .into_iter()+            .map(async |(path, content)| {+                Ok(ServerHmrOpaqueChunk {+                    path,+                    version_id: content.version().id().owned().await?,+                })+            })+            .try_join()+            .await?;+        Ok(Self {+            runtimes: runtimes.into_values().collect(),+            opaque_chunks,+        })     } } -/// An update plus the baseline for the next pull.-#[derive(Debug)]-pub enum ServerHmrUpdate {-    /// No runtime update and the graph is equivalent. However, `to` may still advance the pull-    /// version.-    NoRuntimeUpdate {-        to: Option<ReadRef<ServerHmrChunkListVersion>>,-    },-    FullReevaluation {-        to: ReadRef<ServerHmrChunkListVersion>,-    },-    Partial {-        to: ReadRef<ServerHmrChunkListVersion>,-        instruction: UpdateInstruction,-    },+/// Modules of a chunk to read, with the hash they're expected to have.+#[derive(NonLocalValue)]+struct ChunkModules {+    content: ResolvedVc<Box<dyn EcmascriptHmrChunkContent>>,+    chunk_path: RcStr,+    hashes: FxIndexMap<ModuleId, u128>, } -struct DiffResult {-    chunk_updates: Vec<ReadRef<Update>>,-    membership: ChunkListMembershipChange,+/// The code of the requested modules, by request, or `None` when any of them is gone or no longer+/// has the requested hash.+#[turbo_tasks::value(transparent, serialization = "skip")]+struct ServerHmrModuleEntries(Option<Vec<FxIndexMap<ModuleId, EcmascriptModuleEntry>>>);++/// Reads the code of modules of several chunks, in one operation so that it is read strongly+/// consistently at once.+#[turbo_tasks::function(operation, root)]+async fn server_hmr_module_entries_operation(+    requests: TransientInstance<Vec<ChunkModules>>,+) -> Result<Vc<ServerHmrModuleEntries>> {+    let chunks = requests+        .iter()+        .map(async |request| {+            let entries = request.content.entries().await?;+            let Some(entries) = request+                .hashes+                .keys()+                .map(|id| entries.get(id).map(|entry| (id, entry)))+                .collect::<Option<Vec<_>>>()+            else {+                return Ok(None);+            };+            let entries = entries+                .into_iter()+                .map(async |(id, entry)| {+                    if *entry.hash.await? != request.hashes[id] {+                        return Ok(None);+                    }+                    let entry =+                        EcmascriptModuleEntry::from_code(id, *entry.code, &request.chunk_path)+                            .await?;+                    Ok(Some((id.clone(), entry)))+                })+                .try_join()+                .await?;+            Ok(entries.into_iter().collect::<Option<FxIndexMap<_, _>>>())+        })+        .try_join()+        .await?;+    Ok(Vc::cell(chunks.into_iter().collect())) } -/// Chunk lists that appeared or vanished relative to the pull baseline.-#[derive(Default, Clone, Copy)]-struct ChunkListMembershipChange {-    has_new: bool,-    has_removed: bool,+/// The current version of each of the chunks, or `None` for a chunk that can't be read anymore.+#[turbo_tasks::value(transparent, serialization = "skip")]+struct ServerHmrChunkVersions(Vec<Option<ReadRef<EcmascriptChunkVersion>>>);++/// Reads the versions of several chunks, in one operation so that they are read strongly+/// consistently at once.+#[turbo_tasks::function(operation, root)]+async fn server_hmr_chunk_versions_operation(+    chunk_versions: Vec<OperationVc<EcmascriptChunkVersion>>,+) -> Result<Vc<ServerHmrChunkVersions>> {+    let versions = chunk_versions+        .into_iter()+        .map(async |chunk_version| Ok(chunk_version.connect().await.ok()))+        .try_join()+        .await?;+    Ok(Vc::cell(versions))+}++#[derive(Debug)]+pub enum ServerHmrUpdate {+    /// Nothing to ship.+    None,+    /// The runtimes can't be updated in place, so all server modules need to be re-evaluated.+    FullReevaluation,+    /// One update per runtime directory. Each update only touches chunks of its runtime.+    Partial(Vec<EcmascriptMergedUpdate>), }  static TRACE_DIFFING: LazyLock<bool> = LazyLock::new(|| {@@ -199,321 +422,251 @@ impl CompilationEvent for ServerHmrChunkListDiffEvent {     } } -async fn diff_chunks_against(-    chunk_lists: &[ServerHmrChunkList],-    from: &ServerHmrChunkListVersion,-) -> Result<DiffResult> {-    let current_chunk_list_paths = chunk_lists-        .iter()-        .map(|chunk_list| &chunk_list.relative_path)-        .collect::<FxIndexSet<_>>();-    let has_removed_chunk_lists = from-        .versions_by_chunk_list_path-        .keys()-        .any(|path| !current_chunk_list_paths.contains(path));-    let mut has_new_chunk_lists = false;-    let chunk_updates = chunk_lists-        .iter()-        .filter_map(-            |ServerHmrChunkList {-                 relative_path,-                 versioned_content,-             }| {-                if *TRACE_DIFFING {-                    turbo_tasks().send_compilation_event(Arc::new(ServerHmrChunkListDiffEvent {-                        chunk_list_path: relative_path.clone(),-                    }));-                }-                let Some(prev) = from.versions_by_chunk_list_path.get(relative_path).cloned()-                else {-                    has_new_chunk_lists = true;-                    return None;-                };-                Some((*versioned_content, prev))-            },-        )-        .map(|(content, prev)| async move {-            compute_update_from_version_operation(-                content,-                turbo_tasks::TransientInstance::new(prev),-            )-            .read_strongly_consistent()-            .await-        })-        .try_join()-        .await?;-    Ok(DiffResult {-        chunk_updates,-        membership: ChunkListMembershipChange {-            has_new: has_new_chunk_lists,-            has_removed: has_removed_chunk_lists,-        },-    })-}--enum ServerHmrChunkUpdate<'a> {-    None,-    Missing,-    Total,-    Partial(&'a UpdateInstruction),+/// The modules of one chunk to ship.+#[derive(Default)]+struct ChunkShipment {+    /// The modules to ship, with the hash they're shipped at.+    hashes: FxIndexMap<ModuleId, u128>,+    /// Which of them the runtime doesn't have yet.+    added: FxIndexSet<ModuleId>, } -impl<'a> From<&'a Update> for ServerHmrChunkUpdate<'a> {-    fn from(update: &'a Update) -> Self {-        match update {-            Update::None => Self::None,-            Update::Missing => Self::Missing,-            Update::Total(_) => Self::Total,-            Update::Partial(PartialUpdate { instruction, .. }) => Self::Partial(instruction),+/// The modules to ship to one runtime, by chunk (parallel to [`ServerHmrRouteRuntime::chunks`]).+///+/// The `outdated` modules (see `outdated_modules`) are shipped. A module the runtime doesn't have+/// yet is shipped when the route was pulled before (its code is already running and may now import+/// it), or when anything else is shipped to the runtime (a re-run self-accepting module may import+/// it). Otherwise the route's chunks install it when they load.+fn plan_runtime(+    runtime: &ServerHmrRouteRuntime,+    loaded: Option<&FxHashMap<ModuleId, SmallVec<[InstalledCode; 1]>>>,+    outdated: &FxHashSet<ModuleId>,+    route_was_pulled: bool,+) -> Vec<ChunkShipment> {+    let ship_missing = route_was_pulled || !outdated.is_empty();++    let mut shipments = std::iter::repeat_with(ChunkShipment::default)+        .take(runtime.chunks.len())+        .collect::<Vec<_>>();+    for (id, module) in &runtime.modules {+        let missing = match loaded.is_some_and(|modules| modules.contains_key(id)) {+            true if outdated.contains(id) => false,+            true => continue,+            false if ship_missing => true,+            false => continue,+        };+        let Some(code) = module.code.first() else {+            continue;+        };+        let Some(shipment) = shipments.get_mut(code.chunk) else {+            continue;+        };+        shipment.hashes.insert(id.clone(), code.hash);+        if missing {+            shipment.added.insert(id.clone());         }     }+    shipments } -fn classify_server_hmr_update<'a>(-    chunk_updates: impl IntoIterator<Item = ServerHmrChunkUpdate<'a>>,-    membership: ChunkListMembershipChange,-    to: ReadRef<ServerHmrChunkListVersion>,-) -> ServerHmrUpdate {-    if membership.has_removed {-        return ServerHmrUpdate::FullReevaluation { to };-    }--    let mut builder = ChunkListUpdateBuilder::default();-    for update in chunk_updates {-        match update {-            ServerHmrChunkUpdate::None => {}-            ServerHmrChunkUpdate::Missing | ServerHmrChunkUpdate::Total => {-                return ServerHmrUpdate::FullReevaluation { to };+/// Reads the code of the planned modules, by runtime (parallel to `plans`), into one update per+/// runtime, or `None` when the code no longer matches the plans.+async fn read_updates(+    plans: Vec<(&ServerHmrRouteRuntime, Vec<ChunkShipment>)>,+) -> Result<Option<Vec<EcmascriptMergedUpdate>>> {+    let plan_count = plans.len();+    let mut requests = Vec::new();+    // The plan and added modules of each request.+    let mut shipped = Vec::new();+    for (plan, (runtime, shipments)) in plans.into_iter().enumerate() {+        for (chunk, ChunkShipment { hashes, added }) in runtime.chunks.iter().zip(shipments) {+            if hashes.is_empty() {+                continue;             }-            ServerHmrChunkUpdate::Partial(instruction) => builder.add_instruction(instruction),+            requests.push(ChunkModules {+                content: chunk.content,+                chunk_path: chunk.version.chunk_path.clone(),+                hashes,+            });+            shipped.push((plan, chunk.version.chunk_path.clone(), added));         }     }--    // New chunks load on demand but must advance the baseline.-    if builder.is_empty() {-        return ServerHmrUpdate::NoRuntimeUpdate {-            to: membership.has_new.then_some(to),-        };+    if requests.is_empty() {+        return Ok(Some(Vec::new()));     } -    ServerHmrUpdate::Partial {-        to,-        instruction: builder.build(),-    }-}--/// Kept outside Turbo Tasks so old pull baselines cannot reactivate.-pub async fn compute_server_hmr_update(-    chunk_lists: &[ServerHmrChunkList],-    from: Option<&ServerHmrChunkListVersion>,-    to: ReadRef<ServerHmrChunkListVersion>,-) -> Result<ServerHmrUpdate> {-    if chunk_lists.is_empty() {-        return Ok(ServerHmrUpdate::NoRuntimeUpdate { to: None });-    }--    let Some(from) = from else {-        return Ok(ServerHmrUpdate::NoRuntimeUpdate { to: Some(to) });+    let entries = server_hmr_module_entries_operation(TransientInstance::new(requests))+        .read_strongly_consistent()+        .await?;+    let Some(entries) = &*entries else {+        return Ok(None);     }; -    let DiffResult {-        chunk_updates,-        membership,-    } = diff_chunks_against(chunk_lists, from).await?;--    Ok(classify_server_hmr_update(-        chunk_updates-            .iter()-            .map(|update| ServerHmrChunkUpdate::from(&**update)),-        membership,-        to,+    let mut updates = std::iter::repeat_with(|| (FxIndexMap::default(), FxIndexMap::default()))+        .take(plan_count)+        .collect::<Vec<_>>();+    for ((plan, chunk_path, added), chunk_entries) in shipped.into_iter().zip(entries) {+        let Some((entries, chunks)) = updates.get_mut(plan) else {+            continue;+        };+        entries.extend(+            chunk_entries+                .iter()+                .map(|(id, entry)| (id.clone(), entry.clone())),+        );+        chunks.insert(+            chunk_path,+            EcmascriptMergedChunkUpdate::Partial(EcmascriptMergedChunkPartial {+                added: FrozenSet::from(added),+                deleted: FrozenSet::default(),+            }),+        );+    }+    Ok(Some(+        updates+            .into_iter()+            .map(|(entries, chunks)| EcmascriptMergedUpdate {+                entries: FrozenMap::from(entries),+                chunks: FrozenMap::from(chunks),+            })+            .collect(),     )) } -#[cfg(test)]-mod tests {-    use turbo_tasks::{FxIndexMap, FxIndexSet, ReadRef};-    use turbopack_core::update_instruction::UpdateInstruction;-    use turbopack_ecmascript::chunk_list::{-        merged_update::{-            EcmascriptMergedChunkDeleted, EcmascriptMergedChunkUpdate, EcmascriptMergedUpdate,-        },-        update::{ChunkListUpdate, ChunkUpdate, EcmascriptUpdateInstruction},-    };--    use super::{-        ChunkListMembershipChange, ChunkListUpdateBuilder, ServerHmrChunkListVersion,-        ServerHmrChunkUpdate, ServerHmrUpdate, classify_server_hmr_update,-    };--    fn version() -> ReadRef<ServerHmrChunkListVersion> {-        ReadRef::new_owned(ServerHmrChunkListVersion {-            versions_by_chunk_list_path: Default::default(),-        })-    }--    fn unchanged_membership() -> ChunkListMembershipChange {-        ChunkListMembershipChange::default()-    }--    fn added_chunk_lists() -> ChunkListMembershipChange {-        ChunkListMembershipChange {-            has_new: true,-            has_removed: false,+/// The modules of each of the route's runtimes that the runtime may have at code that isn't+/// current.+///+/// Installed code is current when the route has it too. Otherwise, it may still be current, from a+/// chunk with different code for the module (see [`ServerHmrRouteModule::code`]), so the chunk it+/// is from is checked. Shipping it again would replace one valid piece of code with another, on+/// every request alternating between routes that disagree.+async fn outdated_modules(+    route: &ServerHmrRouteModules,+    loaded: &State<ServerHmrLoadedState>,+) -> Result<Vec<FxHashSet<ModuleId>>> {+    // Installed code the route doesn't have, with the index of the chunk it is from.+    let mut chunk_versions = FxIndexSet::default();+    let mut unknown = Vec::new();+    {+        // Untracked, like every read of the loaded state: it is only used outside of tasks.+        let loaded = loaded.get_untracked();+        for (index, runtime) in route.runtimes.iter().enumerate() {+            let Some(installed) = loaded.modules.get(&runtime.output_dir) else {+                continue;+            };+            for (id, module) in &runtime.modules {+                for code in installed.get(id).into_iter().flatten() {+                    if !module.has(code.hash) {+                        let (chunk, _) = chunk_versions.insert_full(code.chunk_version);+                        unknown.push((index, id.clone(), code.hash, chunk));+                    }+                }+            }         }     } -    fn removed_chunk_lists() -> ChunkListMembershipChange {-        ChunkListMembershipChange {-            has_new: false,-            has_removed: true,-        }+    let mut outdated = vec![FxHashSet::default(); route.runtimes.len()];+    if unknown.is_empty() {+        return Ok(outdated);     }--    fn merged(chunk_path: &str) -> EcmascriptMergedUpdate {-        EcmascriptMergedUpdate {-            entries: Default::default(),-            chunks: [(-                chunk_path.into(),-                EcmascriptMergedChunkUpdate::Deleted(EcmascriptMergedChunkDeleted {-                    modules: Default::default(),-                }),-            )]-            .into_iter()-            .collect(),+    let versions = server_hmr_chunk_versions_operation(chunk_versions.into_iter().collect())+        .read_strongly_consistent()+        .await?;+    for (index, id, hash, chunk) in unknown {+        // A chunk that can't be read anymore doesn't have the code either.+        let current = versions+            .get(chunk)+            .and_then(Option::as_ref)+            .is_some_and(|version| version.entries_hashes.get(&id) == Some(&hash));+        if !current {+            outdated[index].insert(id);         }     }+    Ok(outdated)+} -    #[test]-    fn unchanged_chunks_produce_no_runtime_update() {-        assert!(matches!(-            classify_server_hmr_update(-                [ServerHmrChunkUpdate::None],-                unchanged_membership(),-                version()-            ),-            ServerHmrUpdate::NoRuntimeUpdate { to: None }-        ));-    }--    #[test]-    fn missing_chunk_produces_full_reevaluation() {-        assert!(matches!(-            classify_server_hmr_update(-                [ServerHmrChunkUpdate::Missing],-                unchanged_membership(),-                version()-            ),-            ServerHmrUpdate::FullReevaluation { .. }-        ));-    }--    #[test]-    fn total_update_produces_full_reevaluation() {-        assert!(matches!(-            classify_server_hmr_update(-                [ServerHmrChunkUpdate::Total],-                unchanged_membership(),-                version()-            ),-            ServerHmrUpdate::FullReevaluation { .. }-        ));-    }--    #[test]-    fn partial_instructions_are_combined() {-        let chunk_list = ChunkListUpdate {-            chunks: FxIndexMap::from_iter([("a.js".into(), ChunkUpdate::Added)]),-            merged: vec![],+/// Computes the update that brings the server runtimes up to date for a requested route, by+/// diffing the route's modules against the modules the runtimes have loaded, and records the+/// route's modules as loaded.+///+/// Only the route's own modules are shipped, so modules of other routes are still evaluated+/// lazily, on their next request. See `plan_runtime` for which modules are shipped.+///+/// Kept outside Turbo Tasks: the loaded state is not a task input. No task depends on it, so it is+/// read untracked.+pub async fn compute_server_hmr_update(+    chunk_lists: &[ServerHmrChunkList],+    route: &ServerHmrRouteModules,+    entry_paths: FrozenSet<RcStr>,+    loaded: &State<ServerHmrLoadedState>,+) -> Result<ServerHmrUpdate> {+    if *TRACE_DIFFING {+        for chunk_list in chunk_lists {+            turbo_tasks().send_compilation_event(Arc::new(ServerHmrChunkListDiffEvent {+                chunk_list_path: chunk_list.relative_path.clone(),+            }));         }-        .into_instruction();-        let merged_instruction =-            UpdateInstruction::new(EcmascriptUpdateInstruction::Merged(merged("b.js")));--        let ServerHmrUpdate::Partial { instruction, .. } = classify_server_hmr_update(-            [-                ServerHmrChunkUpdate::Partial(&chunk_list),-                ServerHmrChunkUpdate::Partial(&merged_instruction),-            ],-            unchanged_membership(),-            version(),-        ) else {-            panic!("partial instructions should produce a partial aggregate update");-        };-        let instruction = instruction-            .downcast_ref::<EcmascriptUpdateInstruction>()-            .expect("aggregate instruction is ECMAScript");-        let EcmascriptUpdateInstruction::ChunkList(update) = instruction else {-            panic!("aggregate instruction should be a chunk-list update");-        };-        assert_eq!(update.chunks["a.js"], ChunkUpdate::Added);-        assert_eq!(update.merged, [merged("b.js")]);     }--    #[test]-    fn new_chunk_lists_advance_baseline_without_runtime_update() {-        assert!(matches!(-            classify_server_hmr_update([], added_chunk_lists(), version()),-            ServerHmrUpdate::NoRuntimeUpdate { to: Some(_) }-        ));+    if route.runtimes.is_empty() && route.opaque_chunks.is_empty() {+        // Nothing of the route is built (e.g. its endpoint is gone), so nothing loads either.+        return Ok(ServerHmrUpdate::None);     } -    #[test]-    fn removed_chunk_lists_produce_full_reevaluation() {-        assert!(matches!(-            classify_server_hmr_update([], removed_chunk_lists(), version()),-            ServerHmrUpdate::FullReevaluation { .. }-        ));+    if route.opaque_chunks.iter().any(|opaque| {+        loaded+            .get_untracked()+            .opaque_chunks+            .get(&opaque.path)+            .is_some_and(|version_id| *version_id != opaque.version_id)+    }) {+        // Non-ECMAScript chunks can't be updated in place.+        return Ok(ServerHmrUpdate::FullReevaluation);     } -    #[test]-    fn deduplicates_merged_updates_in_first_seen_order() {-        let first = merged("first.js");-        let second = merged("second.js");-        let mut builder = ChunkListUpdateBuilder::default();--        builder.add_instruction(&UpdateInstruction::new(-            EcmascriptUpdateInstruction::Merged(first.clone()),-        ));-        builder.add_instruction(&UpdateInstruction::new(-            EcmascriptUpdateInstruction::Merged(second.clone()),-        ));-        builder.add_instruction(&UpdateInstruction::new(-            EcmascriptUpdateInstruction::Merged(first.clone()),-        ));--        assert_eq!(builder.merged, FxIndexSet::from_iter([first, second]));-    }+    let outdated = outdated_modules(route, loaded).await?;+    let plans = {+        let loaded = loaded.get_untracked();+        let route_was_pulled = loaded.pulled_routes.contains(&entry_paths);+        route+            .runtimes+            .iter()+            .zip(&outdated)+            .map(|(runtime, outdated)| {+                let shipments = plan_runtime(+                    runtime,+                    loaded.modules.get(&runtime.output_dir),+                    outdated,+                    route_was_pulled,+                );+                (runtime, shipments)+            })+            .filter(|(_, shipments)| shipments.iter().any(|shipment| !shipment.hashes.is_empty()))+            .collect::<Vec<_>>()+    }; -    #[test]-    fn chunk_updates_use_last_writer_and_stable_order() {-        let mut builder = ChunkListUpdateBuilder::default();-        let first = ChunkListUpdate {-            chunks: FxIndexMap::from_iter([-                ("a.js".into(), ChunkUpdate::Total),-                ("b.js".into(), ChunkUpdate::Added),-            ]),-            merged: vec![],-        };-        let second = ChunkListUpdate {-            chunks: FxIndexMap::from_iter([-                ("a.js".into(), ChunkUpdate::Deleted),-                ("c.js".into(), ChunkUpdate::Total),-            ]),-            merged: vec![],-        };+    // The code is read after the module hashes were snapshotted, and a file may have changed in+    // between. Don't record or ship a plan whose code no longer matches.+    let Some(updates) = read_updates(plans).await? else {+        return Ok(ServerHmrUpdate::FullReevaluation);+    }; -        builder.add_instruction(&first.into_instruction());-        builder.add_instruction(&second.into_instruction());+    loaded.update_conditionally(|loaded| loaded.record(route, entry_paths, &outdated)); -        assert_eq!(-            builder-                .chunks-                .keys()-                .map(|path| path.as_str())-                .collect::<Vec<_>>(),-            ["a.js", "b.js", "c.js"]-        );-        assert_eq!(builder.chunks["a.js"], ChunkUpdate::Deleted);+    if updates.is_empty() {+        return Ok(ServerHmrUpdate::None);     }+    Ok(ServerHmrUpdate::Partial(updates))+}++/// Forgets what the server runtimes have loaded, and optionally records a route's modules as+/// loaded (the route the runtimes load next).+pub fn reset_server_hmr_state(+    loaded: &State<ServerHmrLoadedState>,+    route: Option<(&ServerHmrRouteModules, FrozenSet<RcStr>)>,+) {+    let mut state = ServerHmrLoadedState::default();+    if let Some((route, entry_paths)) = route {+        state.record(route, entry_paths, &[]);+    }+    loaded.set(state); }
crates/next-api/src/project.rs11 + / 2 −
@@ -120,7 +120,7 @@ use crate::{     additional_roots::{         AdditionalDiskFileSystem, BuiltinRootsConfig, create_additional_root_file_systems,     },-    aggregate_hmr::ServerHmrChunkLists,+    aggregate_hmr::{ServerHmrChunkLists, ServerHmrLoadedState},     app::{AppProject, CLIENT_TRANSITION_NAME, OptionAppProject},     empty::EmptyEndpoint,     entrypoints::Entrypoints,@@ -469,6 +469,8 @@ pub struct ProjectContainer {     options_state: State<Option<ProjectOptions>>,     file_systems_state: State<Option<ProjectFileSystemState>>,     additional_roots_state: State<Vec<(RcStr, AdditionalDiskFileSystem)>>,+    /// What the server runtimes have loaded, for server HMR.+    server_hmr_loaded_state: State<ServerHmrLoadedState>,     #[turbo_tasks(debug_ignore, unsafe_ignore)]     #[bincode(skip)]     fs_map_init_lock: tokio::sync::Mutex<()>,@@ -493,13 +495,20 @@ impl ProjectContainer {             options_state: State::new(None),             file_systems_state: State::new(None),             additional_roots_state: State::new(Vec::new()),+            server_hmr_loaded_state: State::new(ServerHmrLoadedState::default()),             fs_map_init_lock: tokio::sync::Mutex::new(()),         }         .cell())     } }  impl ProjectContainer {+    /// What the server runtimes have loaded, for server HMR. It must be cleared whenever all+    /// server modules are re-evaluated.+    pub fn server_hmr_loaded_state(&self) -> &State<ServerHmrLoadedState> {+        &self.server_hmr_loaded_state+    }+     /// Attach process-local cleanup after resolving the container. Shutdown hooks must not be     /// task inputs: making the container transient also prevents its project graph from persisting.     pub fn register_shutdown_hooks(&self, shutdown: &crate::shutdown::ShutdownHooks) {@@ -2959,7 +2968,7 @@ impl Project {         }     } -    /// Server entry chunks shared by all pull baselines.+    /// Server entry chunk lists that server HMR pulls select from.     #[turbo_tasks::function]     pub async fn server_hmr_chunks(self: Vc<Self>) -> Result<Vc<ServerHmrChunkLists>> {         let Some(map) = self.await?.versioned_content_map else {
crates/next-napi-bindings/src/next_api/project.rs83 + / 42 −
@@ -20,7 +20,8 @@ use napi::{ use napi_derive::napi; use next_api::{     aggregate_hmr::{-        ServerHmrChunkListVersion, ServerHmrChunkLists, ServerHmrUpdate, compute_server_hmr_update,+        ServerHmrChunkLists, ServerHmrRouteModules, ServerHmrUpdate, compute_server_hmr_update,+        reset_server_hmr_state,     },     entrypoints::Entrypoints,     next_server_nft::next_server_nft_assets,@@ -2011,15 +2012,15 @@ async fn hmr_update_with_issues_operation( #[turbo_tasks::value(serialization = "skip")] struct ServerHmrSnapshotWithEffects {     chunk_lists: ReadRef<ServerHmrChunkLists>,-    version: ReadRef<ServerHmrChunkListVersion>,+    route: ReadRef<ServerHmrRouteModules>,     issues: Arc<Vec<ReadRef<PlainIssue>>>,     effects: Arc<Effects>, }  #[turbo_tasks::value(serialization = "skip")] struct ServerHmrSnapshot {     chunk_lists: ReadRef<ServerHmrChunkLists>,-    version: ReadRef<ServerHmrChunkListVersion>,+    route: ReadRef<ServerHmrRouteModules>, }  #[turbo_tasks::function(operation, root)]@@ -2028,18 +2029,14 @@ async fn project_server_hmr_snapshot_operation(     entry_paths: Vec<RcStr>, ) -> Result<Vc<ServerHmrSnapshot>> {     let chunk_lists = project.server_hmr_chunks_for_entries(entry_paths).await?;-    let version = ServerHmrChunkListVersion::from_chunk_lists(chunk_lists.as_slice())+    let route = ServerHmrRouteModules::from_chunk_lists(chunk_lists.as_slice())         .await?         .cell()         .await?;-    Ok(ServerHmrSnapshot {-        chunk_lists,-        version,-    }-    .cell())+    Ok(ServerHmrSnapshot { chunk_lists, route }.cell()) } -/// Snapshot only; diffing here would keep old baselines active.+/// Snapshot only; the diff against the loaded state happens outside of tasks. #[tracing::instrument(level = "info", name = "server hmr snapshot", skip_all)] #[turbo_tasks::function(operation, root)] async fn server_hmr_snapshot_with_effects_operation(@@ -2058,56 +2055,48 @@ async fn server_hmr_snapshot_with_effects_operation(     let effects = Arc::new(take_effects(snapshot_op).await?);     Ok(ServerHmrSnapshotWithEffects {         chunk_lists: snapshot.chunk_lists.clone(),-        version: snapshot.version.clone(),+        route: snapshot.route.clone(),         issues,         effects,     }     .cell()) } -pub struct ServerHmrVersion(ReadRef<ServerHmrChunkListVersion>);- #[napi(object, object_from_js = false)] pub struct NapiServerHmrUpdate {     #[napi(ts_type = "\"none\" | \"partial\" | \"restart\"")]     pub kind: String,-    /// `unknown` forces the TypeScript boundary to narrow the payload.+    /// For `partial`: one merged update per runtime directory, each touching only chunks of its+    /// runtime. `unknown` forces the TypeScript boundary to narrow the payload.     #[napi(ts_type = "unknown")]-    pub instruction: Option<serde_json::Value>,-    pub version: Option<External<ServerHmrVersion>>,+    pub updates: Option<serde_json::Value>, }  impl NapiServerHmrUpdate {     /// Flattens the union for napi; `swc/types.ts` restores it.     fn new(update: &ServerHmrUpdate) -> Result<Self> {-        let (kind, to, instruction) = match update {-            ServerHmrUpdate::NoRuntimeUpdate { to } => ("none", to.as_ref(), None),-            ServerHmrUpdate::FullReevaluation { to } => ("restart", Some(to), None),-            ServerHmrUpdate::Partial { to, instruction } => {-                ("partial", Some(to), Some(instruction))-            }+        let (kind, updates) = match update {+            ServerHmrUpdate::None => ("none", None),+            ServerHmrUpdate::FullReevaluation => ("restart", None),+            ServerHmrUpdate::Partial(updates) => ("partial", Some(updates)),         };          Ok(Self {             kind: kind.into(),-            instruction: instruction.map(serde_json::to_value).transpose()?,-            version: to.map(|to| External::new(ServerHmrVersion(to.clone()))),+            updates: updates.map(serde_json::to_value).transpose()?,         })     } } -#[tracing::instrument(level = "info", name = "get server HMR update", skip_all)]-#[napi]-pub async fn project_get_server_hmr_update(-    #[napi(ts_arg_type = "{ __napiType: \"Project\" }")] project: &External<ProjectInstance>,-    from: Option<&External<ServerHmrVersion>>,+/// Snapshots the route with the given entries (writing its chunks), while the project is held.+async fn server_hmr_snapshot(+    project: &ProjectInstance,     entry_paths: Vec<RcStr>,-) -> napi::Result<TurbopackResult<NapiServerHmrUpdate>> {+) -> napi::Result<(ResolvedVc<Project>, ReadRef<ServerHmrSnapshotWithEffects>)> {     let container = project.container;-    let turbo_tasks = project.turbopack_ctx.turbo_tasks();-    let from = from.map(|from| from.0.clone());--    let (project, read) = turbo_tasks+    project+        .turbopack_ctx+        .turbo_tasks()         .run(async move {             // HACK(bgw): Remove this unmark call             unmark_top_level_task_may_leak_eventually_consistent_state();@@ -2120,22 +2109,41 @@ pub async fn project_get_server_hmr_update(             Ok((project, read))         })         .await-        .map_err(|e| napi::Error::from_reason(PrettyPrintError(&e.into()).to_string()))?;+        .map_err(|e| napi::Error::from_reason(PrettyPrintError(&e.into()).to_string()))+}++/// Pulls the update that brings the server runtimes up to date for the route with the given+/// entries, and records the route's modules as loaded.+#[tracing::instrument(level = "info", name = "get server HMR update", skip_all)]+#[napi]+pub async fn project_get_server_hmr_update(+    #[napi(ts_arg_type = "{ __napiType: \"Project\" }")] project: &External<ProjectInstance>,+    entry_paths: Vec<RcStr>,+) -> napi::Result<TurbopackResult<NapiServerHmrUpdate>> {+    let container = project.container;+    let (keep_alive, read) = server_hmr_snapshot(project, entry_paths.clone()).await?; -    // Diffing must not remain active after the pull completes.-    let (update, issues) = turbo_tasks+    // The diff reads and updates the loaded state, so it must not run in a task.+    let (update, issues) = project+        .turbopack_ctx+        .turbo_tasks()         .run(async move {             // The snapshot's chunk-list `Vc`s are only valid while the project is held.-            let _project_keep_alive = project;+            let _project_keep_alive = keep_alive;             let ServerHmrSnapshotWithEffects {                 chunk_lists,-                version,+                route,                 issues,                 ..             } = &*read;-            let update =-                compute_server_hmr_update(chunk_lists.as_slice(), from.as_deref(), version.clone())-                    .await?;+            let container = container.await?;+            let update = compute_server_hmr_update(+                chunk_lists.as_slice(),+                route,+                entry_paths.into_iter().collect(),+                container.server_hmr_loaded_state(),+            )+            .await?;             Ok::<_, anyhow::Error>((update, issues.clone()))         })         .await@@ -2151,6 +2159,39 @@ pub async fn project_get_server_hmr_update(     }) } +/// Forgets what the server runtimes have loaded. Must be called whenever all server modules are+/// re-evaluated. When the runtimes load a route next, pass its entries to record its modules as+/// loaded.+#[napi]+pub async fn project_reset_server_hmr_state(+    #[napi(ts_arg_type = "{ __napiType: \"Project\" }")] project: &External<ProjectInstance>,+    entry_paths: Option<Vec<RcStr>>,+) -> napi::Result<()> {+    let container = project.container;+    let snapshot = match entry_paths {+        Some(entry_paths) => Some((+            server_hmr_snapshot(project, entry_paths.clone()).await?,+            entry_paths,+        )),+        None => None,+    };+    project+        .turbopack_ctx+        .turbo_tasks()+        .run(async move {+            let container = container.await?;+            // The snapshot's chunk-list `Vc`s are only valid while the project is held, which+            // `snapshot` does.+            let route = snapshot.as_ref().map(|((_, read), entry_paths)| {+                (&*read.route, entry_paths.iter().cloned().collect())+            });+            reset_server_hmr_state(container.server_hmr_loaded_state(), route);+            Ok(())+        })+        .await+        .map_err(|e| napi::Error::from_reason(PrettyPrintError(&e.into()).to_string()))+}+ #[tracing::instrument(level = "info", name = "get client HMR events", skip(env, project, func), fields(chunk_name = %chunk_name))] #[napi(ts_return_type = "{ __napiType: \"RootTask\" }")] pub fn project_client_hmr_events(
packages/next/src/build/swc/generated-native.d.ts19 + / 5 −
@@ -9,7 +9,6 @@ import type {  export type TurboTasks = { readonly __tag: unique symbol } export type ExternalEndpoint = { readonly __tag: unique symbol }-export type ServerHmrVersion = { readonly __tag: unique symbol } export type NextTurboTasks = { readonly __tag: unique symbol } export type RefCell<_T = unknown> = { readonly __tag: unique symbol } export type FlushGuard = { readonly __tag: unique symbol }@@ -496,9 +495,11 @@ export interface NapiRoute {  export interface NapiServerHmrUpdate {   kind: 'none' | 'partial' | 'restart'-  /** `unknown` forces the TypeScript boundary to narrow the payload. */-  instruction?: unknown-  version?: ExternalObject<ServerHmrVersion>+  /**+   * For `partial`: one merged update per runtime directory, each touching only chunks of its+   * runtime. `unknown` forces the TypeScript boundary to narrow the payload.+   */+  updates?: unknown }  export interface NapiSource {@@ -654,9 +655,12 @@ export declare function projectGetAllCompilationIssues(project: {   __napiType: 'Project' }): Promise<TurbopackResult<undefined>> +/**+ * Pulls the update that brings the server runtimes up to date for the route with the given+ * entries, and records the route's modules as loaded.+ */ export declare function projectGetServerHmrUpdate(   project: { __napiType: 'Project' },-  from: ExternalObject<ServerHmrVersion> | undefined | null,   entryPaths: Array<RcStr> ): Promise<TurbopackResult<NapiServerHmrUpdate>> @@ -699,6 +703,16 @@ export declare function projectOnExit(project: {   __napiType: 'Project' }): Promise<void> +/**+ * Forgets what the server runtimes have loaded. Must be called whenever all server modules are+ * re-evaluated. When the runtimes load a route next, pass its entries to record its modules as+ * loaded.+ */+export declare function projectResetServerHmrState(+  project: { __napiType: 'Project' },+  entryPaths?: Array<RcStr> | undefined | null+): Promise<void>+ /**  * Runs resource cleanup, stops Turbo Tasks, and then flushes the project's exit handlers.  *
packages/next/src/build/swc/index.ts4 + / 3 −
@@ -34,7 +34,6 @@ import type {   RawEntrypoints,   Route,   ServerHmrUpdate,-  ServerHmrVersion,   TurboEngineOptions,   TurbopackResult,   TurbopackStackFrame,@@ -775,17 +774,19 @@ function bindingToApi(     }      async getServerHmrUpdate(-      from: ServerHmrVersion | undefined,       entryPaths: string[]     ): Promise<TurbopackResult<ServerHmrUpdate>> {       // napi cannot express the field correlation.       return binding.projectGetServerHmrUpdate(         this._nativeProject,-        from,         entryPaths       ) as Promise<TurbopackResult<ServerHmrUpdate>>     } +    async resetServerHmrState(entryPaths?: string[]): Promise<void> {+      await binding.projectResetServerHmrState(this._nativeProject, entryPaths)+    }+     clientHmrEvents(       chunkName: string     ): AsyncIterableIterator<TurbopackResult<Update>> {
packages/next/src/build/swc/types.ts15 + / 9 −
@@ -14,7 +14,6 @@ import type {   TraceQueryResult,   MemoryEvictionMode,   NapiTurbopackGcOptions,-  ServerHmrVersion as NativeServerHmrVersion,   LockfileError,   LockfileResult,   projectCompilationEventsSubscribe,@@ -274,17 +273,14 @@ export interface NodeJsPartialHmrUpdate {   instruction: NodeJsEcmascriptMergedUpdate | NodeJsChunkListUpdate } -/** Opaque baseline for the next pull. */-export type ServerHmrVersion = ExternalObject<NativeServerHmrVersion>- /** Restores the union flattened by napi. */ export type ServerHmrUpdate =-  | { kind: 'none'; version?: ServerHmrVersion }-  | { kind: 'restart'; version: ServerHmrVersion }+  | { kind: 'none' }+  | { kind: 'restart' }   | {       kind: 'partial'-      version: ServerHmrVersion-      instruction: NodeJsPartialHmrUpdate['instruction']+      /** One update per runtime directory, each touching only its chunks. */+      updates: NodeJsEcmascriptMergedUpdate[]     }  export interface HmrChunkNames {@@ -357,11 +353,21 @@ export interface Project {     TurbopackResult<RawEntrypoints | {}>   > +  /**+   * Pulls the update that brings the server runtimes up to date for the route+   * with these entries, and records the route's modules as loaded.+   */   getServerHmrUpdate(-    from: ServerHmrVersion | undefined,     entryPaths: string[]   ): Promise<TurbopackResult<ServerHmrUpdate>> +  /**+   * Forgets what the server runtimes have loaded. Must be called whenever all+   * server modules are re-evaluated. When the runtimes load a route next, pass+   * its entries to record its modules as loaded.+   */+  resetServerHmrState(entryPaths?: string[]): Promise<void>+   clientHmrEvents(     identifier: string   ): AsyncIterableIterator<TurbopackResult<Update>>
packages/next/src/server/dev/hot-reloader-turbopack.ts31 + / 60 −
@@ -32,7 +32,6 @@ import type {   Project,   Entrypoints,   NodeJsPartialHmrUpdate,-  ServerHmrVersion, } from '../../build/swc/types' import { createDefineEnv, getBindingsSync } from '../../build/swc' import * as Log from '../../build/output/log'@@ -217,37 +216,6 @@ declare global {     | undefined } -/**- * Collects the output chunk paths touched by a partial HMR update. Both- * single-chunk `EcmascriptMergedUpdate`s and `ChunkListUpdate`s (which nest- * per-chunk deltas inside `merged`) are flattened so the manifest cache can be- * invalidated for every affected chunk after a successful apply.- */-function collectUpdatedChunkPaths(-  instruction: NodeJsPartialHmrUpdate['instruction']-): string[] {-  const paths = new Set<string>()-  if (instruction.type === 'EcmascriptMergedUpdate') {-    for (const chunkPath of Object.keys(instruction.chunks ?? {})) {-      paths.add(chunkPath)-    }-  } else if (instruction.type === 'ChunkListUpdate') {-    for (const chunkPath of Object.keys(instruction.chunks ?? {})) {-      paths.add(chunkPath)-    }-    for (const merged of instruction.merged ?? []) {-      for (const chunkPath of Object.keys(merged.chunks ?? {})) {-        paths.add(chunkPath)-      }-    }-  } else {-    throw new Error(-      `[Server HMR] unreachable: unknown HMR instruction type ${(instruction as { type: string }).type}`-    )-  }-  return Array.from(paths)-}- function setupServerHmr(   project: Project,   {@@ -259,15 +227,15 @@ function setupServerHmr(   } ) {   let pending = Promise.resolve()-  // Each pull snapshots only the requested endpoint's entries. Keep independent-  // baselines so building one route does not discard another route's version.-  const versions = new Map<string, ServerHmrVersion>()+  // What the server runtimes have loaded lives in Turbopack, which diffs each+  // requested route against it.   let needsReEvaluation = false -  async function recover() {+  async function recover(entryPaths: string[]) {     try {       await reEvaluateAllModulesExpensive()-      versions.clear()+      // The requested route loads from scratch next.+      await project.resetServerHmrState(entryPaths)       needsReEvaluation = false     } catch (error) {       console.error('[Server HMR] Re-evaluating modules failed:', error)@@ -277,43 +245,40 @@ function setupServerHmr(   function apply(entryPaths: string[]): Promise<void> {     const applyPromise = pending.then(async () => {       if (needsReEvaluation) {-        await recover()+        await recover(entryPaths)         return       }        try {-        const versionKey = [...entryPaths].sort().join('\0')         // `issues` is intentionally dropped: this pull scans project-wide chunk         // lists, so its issues may belong to an unrelated or removed route, and         // endpoint writes already report route-scoped issues.-        const { value: update } = await project.getServerHmrUpdate(-          versions.get(versionKey),-          entryPaths-        )-        if (update.version) {-          versions.set(versionKey, update.version)-        }+        const { value: update } = await project.getServerHmrUpdate(entryPaths)         switch (update.kind) {           case 'none':             return           case 'partial': {             const handlers = globalThis.__turbopack_server_hmr_handlers__             if (!handlers || handlers.size === 0) return -            const payload: NodeJsPartialHmrUpdate = {-              type: 'partial',-              instruction: update.instruction,-            }             if (typeof __turbopack_server_hmr_apply__ === 'function') {               try {-                __turbopack_server_hmr_apply__(payload)-                mirrorModuleStateToDevValidationWorker({-                  type: 'apply',-                  update: payload,-                })+                // Each update targets one runtime directory, so it is routed+                // only to its own runtime.+                for (const instruction of update.updates) {+                  const payload: NodeJsPartialHmrUpdate = {+                    type: 'partial',+                    instruction,+                  }+                  __turbopack_server_hmr_apply__(payload)+                  mirrorModuleStateToDevValidationWorker({+                    type: 'apply',+                    update: payload,+                  })+                } -                const updatedChunkPaths = collectUpdatedChunkPaths(-                  update.instruction+                const updatedChunkPaths = update.updates.flatMap(+                  (instruction) => Object.keys(instruction.chunks ?? {})                 )                 if (updatedChunkPaths.length > 0) {                   await onApplied(updatedChunkPaths)@@ -338,16 +303,22 @@ function setupServerHmr(       }        needsReEvaluation = true-      await recover()+      await recover(entryPaths)     })     pending = applyPromise     return applyPromise   }    function reset(): Promise<void> {-    const resetState = () => {-      versions.clear()+    const resetState = async () => {       needsReEvaluation = false+      try {+        await project.resetServerHmrState()+      } catch (error) {+        // Keep the queue usable; the next pull re-evaluates everything instead.+        needsReEvaluation = true+        console.error('[Server HMR] Clearing the loaded state failed:', error)+      }     }     const resetPromise = pending.then(resetState, resetState)     pending = resetPromise
test/development/app-dir/server-hmr-async-loader-variants/app/direct/page.tsxadded14 + / 0 −
@@ -0,0 +1,14 @@+// Changes whenever this page module is evaluated again.+const evaluatedAt = `${Date.now()}-${Math.random()}`++// Imports `lib/dyn.ts` where `lib/dep.ts` isn't available yet, so its async+// loader also loads the chunk of `lib/dep.ts`.+export default async function Page() {+  const { value } = await import('../../lib/dyn')+  return (+    <>+      <p id="value">{value}</p>+      <p id="evaluated-at">{evaluatedAt}</p>+    </>+  )+}
test/development/app-dir/server-hmr-async-loader-variants/app/layout.tsxadded9 + / 0 −
@@ -0,0 +1,9 @@+import type { ReactNode } from 'react'++export default function Root({ children }: { children: ReactNode }) {+  return (+    <html>+      <body>{children}</body>+    </html>+  )+}
test/development/app-dir/server-hmr-async-loader-variants/app/page.tsxadded6 + / 0 −
@@ -0,0 +1,6 @@+import { evaluatedAt } from '../lib/clock'++// Unrelated to the route with the async loader variants.+export default function Page() {+  return <p id="evaluated-at">{evaluatedAt}</p>+}
test/development/app-dir/server-hmr-async-loader-variants/app/variants/page.tsxadded7 + / 0 −
@@ -0,0 +1,7 @@+// Imports `lib/dyn.ts` both directly and from `lib/wrap.ts`, so the route's+// chunks have two variants of its async loader.+export default async function Page() {+  const { value } = await import('../../lib/dyn')+  const { viaWrap } = await import('../../lib/wrap')+  return <p id="value">{`${value}|${await viaWrap()}`}</p>+}
test/development/app-dir/server-hmr-async-loader-variants/app/via-wrap/page.tsxadded14 + / 0 −
@@ -0,0 +1,14 @@+// Changes whenever this page module is evaluated again.+const evaluatedAt = `${Date.now()}-${Math.random()}`++// Only imports `lib/dyn.ts` from `lib/wrap.ts`, so the route has a different+// variant of its async loader than `/direct`.+export default async function Page() {+  const { viaWrap } = await import('../../lib/wrap')+  return (+    <>+      <p id="value">{await viaWrap()}</p>+      <p id="evaluated-at">{evaluatedAt}</p>+    </>+  )+}
test/development/app-dir/server-hmr-async-loader-variants/lib/clock.tsadded2 + / 0 −
@@ -0,0 +1,2 @@+// Changes whenever the module is evaluated again.+export const evaluatedAt = `${Date.now()}-${Math.random()}`
test/development/app-dir/server-hmr-async-loader-variants/lib/dep.tsadded1 + / 0 −
@@ -0,0 +1 @@+export const dep = 'dep'
test/development/app-dir/server-hmr-async-loader-variants/lib/dyn.tsadded3 + / 0 −
@@ -0,0 +1,3 @@+import { dep } from './dep'++export const value = `dyn-v1:${dep}`
test/development/app-dir/server-hmr-async-loader-variants/lib/wrap.tsadded8 + / 0 −
@@ -0,0 +1,8 @@+import { dep } from './dep'++// `dep` is already available here, so this import of `./dyn` gets an async+// loader that only loads the chunk of `./dyn`.+export async function viaWrap() {+  const { value } = await import('./dyn')+  return `wrap:${dep}:${value}`+}
test/development/app-dir/server-hmr-async-loader-variants/next.config.tsadded11 + / 0 −
@@ -0,0 +1,11 @@+import type { NextConfig } from 'next'++const nextConfig: NextConfig = {+  experimental: {+    // Gives the async loader of `lib/dyn.ts` different code in the chunks of+    // one route, depending on what is already available where it's imported.+    turbopackServerSideNestedAsyncChunking: true,+  },+}++export default nextConfig
test/development/app-dir/server-hmr-async-loader-variants/server-hmr-async-loader-variants.test.tsadded71 + / 0 −
@@ -0,0 +1,71 @@+import { nextTestSetup } from 'e2e-utils'+import { retry } from 'next-test-utils'++// Server HMR is a Turbopack-only feature+// @force-gate turbopack+describe('server-hmr-async-loader-variants', () => {+  const { next } = nextTestSetup({+    files: __dirname,+  })++  async function evaluatedAt() {+    const $ = await next.render$('/')+    return $('#evaluated-at').text()+  }++  async function variantsValue() {+    const $ = await next.render$('/variants')+    return $('#value').text()+  }++  it('does not re-evaluate unrelated modules on requests to a route with async loader variants', async () => {+    const outputStart = next.cliOutput.length+    const initialEvaluatedAt = await evaluatedAt()++    for (let i = 0; i < 3; i++) {+      expect(await variantsValue()).toBe('dyn-v1:dep|wrap:dep:dyn-v1:dep')+    }++    expect(await evaluatedAt()).toBe(initialEvaluatedAt)+    expect(next.cliOutput.slice(outputStart)).not.toContain('[Server HMR]')+  })++  it('does not update routes with different async loader variants when alternating between them', async () => {+    const outputStart = next.cliOutput.length+    const render = async (path: string) => {+      const $ = await next.render$(path)+      return {+        value: $('#value').text(),+        evaluatedAt: $('#evaluated-at').text(),+      }+    }++    const direct = await render('/direct')+    const viaWrap = await render('/via-wrap')+    expect(direct.value).toBe('dyn-v1:dep')+    expect(viaWrap.value).toBe('wrap:dep:dyn-v1:dep')++    // An update of the async loader would re-evaluate the page that imports it.+    for (let i = 0; i < 3; i++) {+      expect(await render('/direct')).toEqual(direct)+      expect(await render('/via-wrap')).toEqual(viaWrap)+    }+    expect(next.cliOutput.slice(outputStart)).not.toContain('[Server HMR]')+  })++  it('updates a route with async loader variants', async () => {+    const outputStart = next.cliOutput.length+    const initialEvaluatedAt = await evaluatedAt()+    expect(await variantsValue()).toBe('dyn-v1:dep|wrap:dep:dyn-v1:dep')++    await next.patchFile('lib/dyn.ts', (content) =>+      content.replace('dyn-v1', 'dyn-v2')+    )+    await retry(async () => {+      expect(await variantsValue()).toBe('dyn-v2:dep|wrap:dep:dyn-v2:dep')+    })++    expect(await evaluatedAt()).toBe(initialEvaluatedAt)+    expect(next.cliOutput.slice(outputStart)).not.toContain('[Server HMR]')+  })+})
test/development/app-dir/server-hmr/app/api/new-export-cached/alpha/route.tsadded5 + / 0 −
@@ -0,0 +1,5 @@+import { alpha } from '../shared'++export async function GET() {+  return Response.json({ result: await alpha('x') })+}
test/development/app-dir/server-hmr/app/api/new-export-cached/shared.tsadded4 + / 0 −
@@ -0,0 +1,4 @@+export async function alpha(input: string) {+  'use cache'+  return 'alpha:' + input+}
test/development/app-dir/server-hmr/app/api/new-export/alpha/route.tsadded6 + / 0 −
@@ -0,0 +1,6 @@+import { alpha } from '../shared'+import { evaluatedAt } from '../unmodified'++export async function GET() {+  return Response.json({ result: alpha('x'), evaluatedAt })+}
test/development/app-dir/server-hmr/app/api/new-export/shared.tsadded3 + / 0 −
@@ -0,0 +1,3 @@+export function alpha(input: string) {+  return 'alpha:' + input+}
test/development/app-dir/server-hmr/app/api/new-export/unmodified.tsadded1 + / 0 −
@@ -0,0 +1 @@+export const evaluatedAt = Date.now()
test/development/app-dir/server-hmr/server-hmr.test.ts93 + / 0 −
@@ -686,6 +686,99 @@ describe('server-hmr', () => {       })     })   })++  describe('new export on an already-evaluated module', () => {+    async function fetchJson(pathname: string) {+      const res = await next.fetch(pathname)+      expect(res.status).toBe(200)+      return res.json()+    }++    it('exposes the new export to a newly added route handler', async () => {+      const initial = await fetchJson('/api/new-export/alpha')+      expect(initial.result).toBe('alpha:x')+      const outputLengthBeforePatch = next.cliOutput.length++      await next.patchFile(+        'app/api/new-export/shared.ts',+        (content) =>+          content ++          `+export function gamma(input: string) {+  return 'gamma:' + input+}+`,+        async () => {+          await next.patchFile(+            'app/api/new-export/gamma/route.ts',+            `import { gamma } from '../shared'+import { evaluatedAt } from '../unmodified'++export async function GET() {+  return Response.json({ result: gamma('h'), evaluatedAt })+}+`,+            async () => {+              // The first request to the new route compiles it, which can take+              // most of the default retry duration.+              await retry(async () => {+                expect(await fetchJson('/api/new-export/gamma')).toEqual({+                  result: 'gamma:h',+                  // The unmodified module should NOT have been re-evaluated+                  evaluatedAt: initial.evaluatedAt,+                })+              }, 10000)+              expect(+                next.cliOutput.slice(outputLengthBeforePatch)+              ).not.toContain('is not a function')+            }+          )+        }+      )+    })++    // `'use cache'` requires Cache Components.+    // @force-gate cacheComponents+    it('exposes a new `use cache` export to a newly added route handler', async () => {+      expect(await fetchJson('/api/new-export-cached/alpha')).toEqual({+        result: 'alpha:x',+      })+      const outputLengthBeforePatch = next.cliOutput.length++      await next.patchFile(+        'app/api/new-export-cached/shared.ts',+        (content) =>+          content ++          `+export async function gamma(input: string) {+  'use cache'+  return 'gamma:' + input+}+`,+        async () => {+          await next.patchFile(+            'app/api/new-export-cached/gamma/route.ts',+            `import { gamma } from '../shared'++export async function GET() {+  return Response.json({ result: await gamma('h') })+}+`,+            async () => {+              await retry(async () => {+                expect(await fetchJson('/api/new-export-cached/gamma')).toEqual(+                  { result: 'gamma:h' }+                )+              })+              expect(+                next.cliOutput.slice(outputLengthBeforePatch)+              ).not.toContain('is not a function')+            }+          )+        }+      )+    })+  }) })  // The server Fast Refresh opt-out only applies to Turbopack.
turbopack/crates/turbopack-nodejs/src/ecmascript/node/entry/chunk_list_content.rs9 + / 22 −
@@ -1,5 +1,5 @@ use anyhow::{Result, bail};-use turbo_tasks::{OrderedAutoMap, ReadRef, ResolvedVc, TransientInstance, TryJoinIterExt, Vc};+use turbo_tasks::{OrderedAutoMap, ResolvedVc, TryJoinIterExt, Vc}; use turbo_tasks_fs::FileSystemPath; use turbopack_core::{     asset::{Asset, AssetContent},@@ -51,22 +51,17 @@ pub struct EcmascriptBuildNodeChunkListContent {     pub(super) chunks_contents: OrderedAutoMap<String, ResolvedVc<Box<dyn VersionedContent>>>, } -#[turbo_tasks::value_impl] impl EcmascriptBuildNodeChunkListContent {-    #[turbo_tasks::function]-    pub async fn compute_update_from_version(-        self: Vc<Self>,-        from: TransientInstance<ReadRef<ChunkListVersion>>,-    ) -> Result<Vc<Update>> {-        let to = self.version();-        update_chunk_list(-            &self.await?.chunks_contents,-            to,-            ResolvedVc::upcast(ReadRef::resolved_cell((*from).clone())),-        )-        .await+    /// The tracked chunks' versioned contents, by `output_root`-relative path.+    pub fn chunks_contents(+        &self,+    ) -> &OrderedAutoMap<String, ResolvedVc<Box<dyn VersionedContent>>> {+        &self.chunks_contents     }+} +#[turbo_tasks::value_impl]+impl EcmascriptBuildNodeChunkListContent {     #[turbo_tasks::function]     pub async fn new(         chunking_context: ResolvedVc<NodeJsChunkingContext>,@@ -156,11 +151,3 @@ impl VersionedContent for EcmascriptBuildNodeChunkListContent {         update_chunk_list(&this.chunks_contents, to_version, from_version).await     } }--#[turbo_tasks::function(operation, root)]-pub fn compute_update_from_version_operation(-    content: ResolvedVc<EcmascriptBuildNodeChunkListContent>,-    from: TransientInstance<ReadRef<ChunkListVersion>>,-) -> Vc<Update> {-    content.compute_update_from_version(from)-}