Unverified Commit 43f90177 authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

Add `next internal post-build` CLI command for Turbopack database compaction (#91336)

### What?

Adds a \`next internal post-build\` CLI command that performs Turbopack
persistent cache database compaction as a separate step after \`next
build\`.

### Why?

Database compaction during shutdown can be slow and blocks the build
process. By deferring compaction to a separate post-build step, we can:
- Keep the main \`next build\` fast by skipping compaction at shutdown
(controlled via \`NEXT_USE_POST_BUILD=1\`)
- Run compaction independently, e.g. as a separate CI step or in the
background
- Perform a full compaction (\`max_merge_segment_count: usize::MAX\`)
that is more thorough than the runtime shutdown compaction

**Intended usage in a build pipeline:**
\`\`\`sh
NEXT_USE_POST_BUILD=1 next build # fast build, skips compaction at
shutdown
next internal post-build # separate step: full compaction of the cache
\`\`\`

### How?

**Rust side:**
- Added \`compact_database()\` to \`turbo-tasks-backend\` that opens the
database and runs a full compaction using
\`TurboTasksParallelScheduler\` backed by a dedicated multi-threaded
Tokio runtime (same scheduler as the normal runtime path, enabling
parallel work-stealing)
- Added \`turbopack_database_compact\` NAPI binding that resolves the
versioned DB path and calls \`compact_database()\`
- Added \`skip_compaction\` flag to \`NapiTurboEngineOptions\` /
\`TurboKeyValueDatabase\` to skip compaction during normal shutdown when
post-build will handle it; asserted that \`skip_compaction=true\`
requires \`is_short_session=true\` (enforcing the logical dependency)
- Extracted shared \`DB_CONFIG\`, \`FAMILIES\`, and \`COMPACT_CONFIG\`
constants and \`git_version_info()\` helper to avoid duplication between
the runtime DB and standalone compaction paths

**TypeScript side:**
- Added \`next internal post-build\` command that loads the Next.js
config, finds the Turbopack cache directory, and calls the native
compaction binding
- Added \`databaseCompact\` to the turbo bindings interface (native +
WASM stub)
- \`turbopack-build/impl.ts\` sets \`skipCompaction: true\` when
\`NEXT_USE_POST_BUILD=1\`

**Tests:**
- Added \`test/production/app-dir/post-build/\` integration test that
verifies compaction runs successfully on a persistent-cache build and
reports nothing to do when persistent caching is disabled

---------
Co-authored-by: 's avatarTobias Koppers <sokra@users.noreply.github.com>
Co-authored-by: 's avatarClaude <noreply@anthropic.com>
parent 9920dbac
......@@ -284,6 +284,8 @@ pub struct NapiTurboEngineOptions {
pub is_ci: Option<bool>,
/// Whether the project is running in a short session.
pub is_short_session: Option<bool>,
/// Whether to skip database compaction during shutdown.
pub skip_compaction: Option<bool>,
}
impl From<NapiWatchOptions> for WatchOptions {
......@@ -539,6 +541,7 @@ pub fn project_new(
let dependency_tracking = turbo_engine_options.dependency_tracking.unwrap_or(true);
let is_ci = turbo_engine_options.is_ci.unwrap_or(false);
let is_short_session = turbo_engine_options.is_short_session.unwrap_or(false);
let skip_compaction = turbo_engine_options.skip_compaction.unwrap_or(false);
let turbo_tasks = create_turbo_tasks(
PathBuf::from(&options.dist_dir),
options.is_persistent_caching_enabled,
......@@ -546,6 +549,7 @@ pub fn project_new(
dependency_tracking,
is_ci,
is_short_session,
skip_compaction,
)?;
let turbopack_ctx = NextTurbopackContext::new(turbo_tasks.clone(), napi_callbacks);
......@@ -2491,3 +2495,15 @@ pub async fn project_write_analyze_data(
.collect(),
})
}
/// Opens the Turbopack persistent cache database at the given path and performs a full compaction.
///
/// The `path` should point to the `<distDir>/cache/turbopack` directory.
#[napi]
pub async fn turbopack_database_compact(path: String) -> napi::Result<()> {
let version_info = crate::next_api::turbopack_ctx::git_version_info();
let is_ci = std::env::var("CI").is_ok_and(|v| !v.is_empty());
turbo_tasks_backend::compact_database(&PathBuf::from(path), &version_info, is_ci)
.map_err(|e| napi::Error::from_reason(format!("Database compaction failed: {e}")))?;
Ok(())
}
......@@ -208,6 +208,18 @@ impl NapiNextTurbopackCallbacks {
}
}
/// Returns version info derived from compile-time git metadata.
///
/// The `dirty` flag is only set when not running in CI (`CI` env var unset at build time) and the
/// working tree was dirty at build time.
pub fn git_version_info() -> GitVersionInfo<'static> {
GitVersionInfo {
describe: env!("VERGEN_GIT_DESCRIBE"),
dirty: option_env!("CI").is_none_or(|value| value.is_empty())
&& env!("VERGEN_GIT_DIRTY") == "true",
}
}
pub fn create_turbo_tasks(
output_path: PathBuf,
persistent_caching: bool,
......@@ -215,18 +227,16 @@ pub fn create_turbo_tasks(
dependency_tracking: bool,
is_ci: bool,
is_short_session: bool,
skip_compaction: bool,
) -> Result<NextTurboTasks> {
Ok(if persistent_caching {
let version_info = GitVersionInfo {
describe: env!("VERGEN_GIT_DESCRIBE"),
dirty: option_env!("CI").is_none_or(|value| value.is_empty())
&& env!("VERGEN_GIT_DIRTY") == "true",
};
let version_info = git_version_info();
let (backing_storage, cache_state) = turbo_backing_storage(
&output_path.join("cache/turbopack"),
&version_info,
is_ci,
is_short_session,
skip_compaction,
)?;
let tt = TurboTasks::new(TurboTasksBackend::new(
BackendOptions {
......
......@@ -1144,5 +1144,6 @@
"1143": "Prefetch inlining is enabled but no hint tree was provided during incremental static revalidation. The prefetch-hints.json manifest should contain an entry for this route.",
"1144": "Prefetch inlining is enabled but no hints were found for route \"%s\". This is a bug in the Next.js build pipeline — prefetch-hints.json should contain an entry for every route that produces segment data.",
"1145": "Internal Next.js Error: Prefetch inlining is enabled but no hints were found for route \"%s\". prefetch-hints.json should contain an entry for every route that produces segment data. This is a bug in Next.js.",
"1146": "Internal Next.js Error: Prefetch inlining is enabled but no hint tree was provided during incremental static revalidation. The prefetch-hints.json manifest should contain an entry for this route. This is a bug in Next.js."
"1146": "Internal Next.js Error: Prefetch inlining is enabled but no hint tree was provided during incremental static revalidation. The prefetch-hints.json manifest should contain an entry for this route. This is a bug in Next.js.",
"1147": "Turbopack database compaction is not supported on this platform"
}
......@@ -30,6 +30,7 @@ import type { NextDevOptions } from '../cli/next-dev.js'
import type { NextAnalyzeOptions } from '../cli/next-analyze.js'
import type { NextBuildOptions } from '../cli/next-build.js'
import type { NextTypegenOptions } from '../cli/next-typegen.js'
import type { NextPostBuildOptions } from '../cli/next-post-build.js'
if (process.env.NEXT_RSPACK) {
// silent rspack's schema check
......@@ -551,4 +552,24 @@ internal
)
})
internal
.command('post-build')
.description(
'Runs post-build optimization steps (e.g. Turbopack database compaction).'
)
.argument(
'[directory]',
`A directory on which to run post-build steps. ${italic(
'If no directory is provided, the current directory will be used.'
)}`
)
.action((directory: string, options: NextPostBuildOptions) => {
return (
require('../cli/next-post-build.js') as typeof import('../cli/next-post-build.js')
)
.nextPostBuild(options, directory)
.then(() => process.exit(0))
})
.usage('[directory] [options]')
program.parse(process.argv)
......@@ -317,6 +317,8 @@ export interface NapiTurboEngineOptions {
isCi?: boolean
/** Whether the project is running in a short session. */
isShortSession?: boolean
/** Whether to skip database compaction during shutdown. */
skipCompaction?: boolean
}
export declare function projectNew(
options: NapiProjectOptions,
......@@ -481,6 +483,12 @@ export declare function projectWriteAnalyzeData(
project: { __napiType: 'Project' },
appDirOnly: boolean
): Promise<TurbopackResult>
/**
* Opens the Turbopack persistent cache database at the given path and performs a full compaction.
*
* The `path` should point to the `<distDir>/cache/turbopack` directory.
*/
export declare function turbopackDatabaseCompact(path: string): Promise<void>
/**
* A version of [`NapiNextTurbopackCallbacks`] that can accepted as an argument to a napi function.
*
......
......@@ -1393,6 +1393,11 @@ async function loadWasm(importPath = '') {
`Only WebAssembly (WASM) bindings were loaded, and Turbopack requires native bindings.`
)
},
databaseCompact(_path: string): Promise<void> {
throw new Error(
'Turbopack database compaction is not supported on this platform'
)
},
},
mdx: {
compile(src: string, options: any) {
......@@ -1637,6 +1642,9 @@ function loadNative(importPath?: string): Binding {
port
)
},
databaseCompact(dbPath: string) {
return (customBindings ?? bindings).turbopackDatabaseCompact(dbPath)
},
},
mdx: {
compile(src: string, options: any) {
......
......@@ -31,6 +31,7 @@ export interface Binding {
traceFilePath: string,
port: number | undefined
): void
databaseCompact(path: string): Promise<void>
nextBuild?: any
}
......
......@@ -121,6 +121,7 @@ export async function turbopackBuild(): Promise<{
dependencyTracking: persistentCaching || hasDeferredEntries,
isCi: isCI,
isShortSession: true,
skipCompaction: process.env.NEXT_USE_POST_BUILD === '1',
}
const sriEnabled = Boolean(config.experimental.sri?.algorithm)
......
#!/usr/bin/env node
import { existsSync } from 'fs'
import path from 'path'
import loadConfig from '../server/config'
import { PHASE_PRODUCTION_BUILD } from '../shared/lib/constants'
import { getProjectDir } from '../lib/get-project-dir'
import { printAndExit } from '../server/lib/utils'
import { loadBindings } from '../build/swc'
export type NextPostBuildOptions = {}
const nextPostBuild = async (
_options: NextPostBuildOptions,
directory?: string
) => {
const dir = getProjectDir(directory)
if (!existsSync(dir)) {
printAndExit(`> No such directory exists as the project root: ${dir}`)
}
const config = await loadConfig(PHASE_PRODUCTION_BUILD, dir)
const persistentCaching =
config.experimental?.turbopackFileSystemCacheForBuild || false
if (!persistentCaching) {
console.log('Persistent caching for build is not enabled. Nothing to do.')
return
}
const distDir = path.join(dir, config.distDir)
const cachePath = path.join(distDir, 'cache', 'turbopack')
if (!existsSync(cachePath)) {
console.log('No Turbopack cache directory found. Nothing to do.')
return
}
const bindings = await loadBindings(config.experimental?.useWasmBinary)
await bindings.turbo.databaseCompact(cachePath)
console.log('Turbopack database compaction complete.')
}
export { nextPostBuild }
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Page() {
return <p>hello world</p>
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
turbopackFileSystemCacheForBuild: true,
},
}
module.exports = nextConfig
import { nextTestSetup, isNextStart } from 'e2e-utils'
import { runNextCommand } from 'next-test-utils'
import { existsSync } from 'fs'
import path from 'path'
describe('post-build', () => {
if (!isNextStart) {
it('skipped for non-start mode', () => {})
return
}
const { next, isTurbopack, skipped } = nextTestSetup({
files: __dirname,
skipStart: true,
skipDeployment: true,
env: {
NEXT_USE_POST_BUILD: '1',
},
})
if (skipped) return
it('should run post-build compaction on the turbopack cache', async () => {
if (!isTurbopack) {
console.log('Skipping: turbopack-only test')
return
}
// Build with NEXT_USE_POST_BUILD=1 which skips compaction during build
const buildResult = await next.build()
expect(buildResult.exitCode).toBe(0)
const cachePath = path.join(next.testDir, '.next', 'cache', 'turbopack')
expect(existsSync(cachePath)).toBe(true)
// Run `next internal post-build` to compact the database
const result = await runNextCommand(['internal', 'post-build'], {
cwd: next.testDir,
stderr: true,
stdout: true,
})
if (result.code !== 0) {
console.log('post-build stdout:', result.stdout)
console.log('post-build stderr:', result.stderr)
}
expect(result.code).toBe(0)
expect(result.stdout + result.stderr).toContain(
'Turbopack database compaction complete.'
)
})
it('should report nothing to do when persistent caching is disabled', async () => {
// Override config to disable persistent caching
await next.patchFile(
'next.config.js',
`module.exports = {
experimental: {
turbopackFileSystemCacheForBuild: false,
},
}`
)
try {
const result = await runNextCommand(['internal', 'post-build'], {
cwd: next.testDir,
stderr: true,
stdout: true,
})
expect(result.code).toBe(0)
expect(result.stdout + result.stderr).toContain('Nothing to do.')
} finally {
// Restore original config
await next.patchFile(
'next.config.js',
`/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
turbopackFileSystemCacheForBuild: true,
},
}
module.exports = nextConfig`
)
}
})
})
......@@ -12,6 +12,21 @@ pub enum KeySpace {
TaskCache = 3,
}
impl KeySpace {
/// Constructs a [`KeySpace`] from its numeric index (i.e., the `usize` discriminant).
///
/// # Panics
///
/// Panics if `i` is out of range (i.e., `>= FAMILIES`).
pub const fn from_index(i: usize) -> Self {
match i {
0 => KeySpace::Infra,
1 => KeySpace::TaskMeta,
2 => KeySpace::TaskData,
3 => KeySpace::TaskCache,
_ => panic!("KeySpace index out of range"),
}
}
/// Returns the persistence configuration for this keyspace.
pub const fn family_config(&self) -> FamilyConfig {
match self {
......
......@@ -18,19 +18,28 @@ use turbo_tasks::{
use crate::database::{
key_value_database::{KeySpace, KeyValueDatabase},
turbo::parallel_scheduler::TurboTasksParallelScheduler,
write_batch::{ConcurrentWriteBatch, WriteBuffer},
};
mod parallel_scheduler;
pub(crate) use parallel_scheduler::TurboTasksParallelScheduler;
/// Number of key families, see KeySpace enum for their numbers.
const FAMILIES: usize = 4;
/// Number of key families, see [`KeySpace`] enum for their numbers.
pub const FAMILIES: usize = 4;
const COMPACTION_MESSAGE: &str = "Finished filesystem cache database compaction";
const MB: u64 = 1024 * 1024;
const COMPACT_CONFIG: CompactConfig = CompactConfig {
/// Returns the database configuration for the Turbopack persistent cache, mapping each
/// [`KeySpace`] to its persistence family config.
pub fn db_config() -> DbConfig<FAMILIES> {
DbConfig {
family_configs: std::array::from_fn(|i| KeySpace::from_index(i).family_config()),
}
}
pub const COMPACT_CONFIG: CompactConfig = CompactConfig {
min_merge_count: 3,
optimal_merge_count: 8,
max_merge_count: 64,
......@@ -45,24 +54,30 @@ pub struct TurboKeyValueDatabase {
is_ci: bool,
is_short_session: bool,
is_fresh: bool,
skip_compaction: bool,
}
impl TurboKeyValueDatabase {
pub fn new(versioned_path: PathBuf, is_ci: bool, is_short_session: bool) -> Result<Self> {
const CONFIG: DbConfig<FAMILIES> = DbConfig {
family_configs: [
KeySpace::Infra.family_config(),
KeySpace::TaskMeta.family_config(),
KeySpace::TaskData.family_config(),
KeySpace::TaskCache.family_config(),
],
};
let db = Arc::new(TurboPersistence::open_with_config(versioned_path, CONFIG)?);
pub fn new(
versioned_path: PathBuf,
is_ci: bool,
is_short_session: bool,
skip_compaction: bool,
) -> Result<Self> {
assert!(
!skip_compaction || is_short_session,
"skip_compaction=true requires is_short_session=true"
);
let db = Arc::new(TurboPersistence::open_with_config(
versioned_path,
db_config(),
)?);
Ok(Self {
db: db.clone(),
is_ci,
is_short_session,
is_fresh: db.is_empty(),
skip_compaction,
})
}
}
......@@ -125,7 +140,7 @@ impl KeyValueDatabase for TurboKeyValueDatabase {
fn shutdown(&self) -> Result<()> {
// Compact the database on shutdown
// (Avoid compacting a fresh database since we don't have any usage info yet)
if !self.is_fresh {
if !self.is_fresh && !self.skip_compaction {
if self.is_ci {
// Fully compact in CI to reduce cache size
do_compact(&self.db, COMPACTION_MESSAGE, usize::MAX)?;
......
......@@ -521,7 +521,7 @@ mod tests {
// Use is_short_session=true to disable background compaction (which requires turbo-tasks
// context)
let db = TurboKeyValueDatabase::new(path.to_path_buf(), false, true)?;
let db = TurboKeyValueDatabase::new(path.to_path_buf(), false, true, false)?;
// Simulate a hash collision by writing multiple TaskIds with the same hash key
let collision_hash: u64 = 0xDEADBEEF;
......
......@@ -14,13 +14,19 @@ mod utils;
use std::path::Path;
use anyhow::Result;
use turbo_persistence::{CompactConfig, TurboPersistence};
use crate::database::{noop_kv::NoopKvDb, turbo::TurboKeyValueDatabase};
use crate::database::{
noop_kv::NoopKvDb,
turbo::{self, TurboKeyValueDatabase},
};
pub use crate::{
backend::{BackendOptions, StorageMode, TurboTasksBackend},
backing_storage::BackingStorage,
database::{
db_invalidation, db_invalidation::StartupCacheState, db_versioning::GitVersionInfo,
db_invalidation,
db_invalidation::StartupCacheState,
db_versioning::{GitVersionInfo, handle_db_versioning},
},
kv_backing_storage::KeyValueDatabaseBackingStorage,
};
......@@ -35,12 +41,13 @@ pub fn turbo_backing_storage(
version_info: &GitVersionInfo,
is_ci: bool,
is_short_session: bool,
skip_compaction: bool,
) -> Result<(TurboBackingStorage, StartupCacheState)> {
KeyValueDatabaseBackingStorage::open_versioned_on_disk(
base_path.to_owned(),
version_info,
is_ci,
|path| TurboKeyValueDatabase::new(path, is_ci, is_short_session),
|path| TurboKeyValueDatabase::new(path, is_ci, is_short_session, skip_compaction),
)
}
......@@ -50,3 +57,43 @@ pub type NoopBackingStorage = KeyValueDatabaseBackingStorage<NoopKvDb>;
pub fn noop_backing_storage() -> NoopBackingStorage {
KeyValueDatabaseBackingStorage::new_in_memory(NoopKvDb)
}
/// Opens a Turbopack persistent cache database at the given base path and performs a full
/// compaction. This is intended for use by the `next internal post-build` CLI command to optimize
/// the database after a build, without requiring the full turbo-tasks runtime.
///
/// The parallel scheduler requires a Tokio runtime. If one is already active (e.g. when called
/// from a NAPI async function), it is reused. Otherwise a new multi-threaded runtime is created.
pub fn compact_database(
base_path: &Path,
version_info: &GitVersionInfo,
is_ci: bool,
) -> Result<()> {
let versioned_path = handle_db_versioning(base_path, version_info, is_ci)?;
// The parallel scheduler uses `tokio::task::block_in_place` internally, which
// requires a multi-threaded Tokio runtime. Create one only if there is no
// active runtime (e.g. when called from a standalone CLI context).
let _owned_runtime = if tokio::runtime::Handle::try_current().is_ok() {
None
} else {
Some(
tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()?,
)
};
// If we created a runtime, enter it so the scheduler can find it.
let _guard = _owned_runtime.as_ref().map(|rt| rt.enter());
let db =
TurboPersistence::<turbo::TurboTasksParallelScheduler, { turbo::FAMILIES }>::open_with_config(
versioned_path,
turbo::db_config(),
)?;
// Fully compact with no segment count limit (unlike the runtime shutdown path
// which caps segments based on available parallelism).
db.compact(&CompactConfig {
max_merge_segment_count: usize::MAX,
..turbo::COMPACT_CONFIG
})?;
db.shutdown()
}
......@@ -21,6 +21,7 @@
},
false,
true,
false,
).unwrap().0
)
)
......
......@@ -20,6 +20,7 @@
},
false,
true,
false,
).unwrap().0
)
)
......
......@@ -20,6 +20,7 @@
},
false,
true,
false,
).unwrap().0
)
)
......
......@@ -540,7 +540,7 @@ pub async fn build(args: &BuildArguments) -> Result<()> {
.clone()
.unwrap_or_else(|| PathBuf::from(&*project_dir).join(".turbopack/cache"));
let (backing_storage, cache_state) =
turbo_backing_storage(&cache_dir, &version_info, is_ci, is_short_session)?;
turbo_backing_storage(&cache_dir, &version_info, is_ci, is_short_session, false)?;
let storage_mode = if std::env::var("TURBO_ENGINE_READ_ONLY").is_ok() {
StorageMode::ReadOnly
} else if is_ci || is_short_session {
......
......@@ -391,7 +391,7 @@ pub async fn start_server(args: &DevArguments) -> Result<()> {
.clone()
.unwrap_or_else(|| PathBuf::from(&*project_dir).join(".turbopack/cache"));
let (backing_storage, cache_state) =
turbo_backing_storage(&cache_dir, &version_info, is_ci, is_short_session)?;
turbo_backing_storage(&cache_dir, &version_info, is_ci, is_short_session, false)?;
let storage_mode = if std::env::var("TURBO_ENGINE_READ_ONLY").is_ok() {
StorageMode::ReadOnly
} else if is_ci || is_short_session {
......
......@@ -21,6 +21,7 @@
},
false,
true,
false,
).unwrap().0
)
)
......
......@@ -321,6 +321,7 @@ fn node_file_trace_persistent(#[case] input: CaseInput) {
},
false,
true,
false,
)
.unwrap()
.0,
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment