fix(python): preserve deployed dependency validation

(cherry picked from commit e18abca88589347975a5866925c590a16f1b2aed)
This commit is contained in:
fz authored and imccyu committed 2026-11-02 16:07:29 +08:00
1 parent 125fabd8d0
commit 67e2d1e506
13 files changed
+145 -21

No files matched your search

+4 -4
View File
@@ -14,9 +14,9 @@ function isHoistedLocations(value: unknown): value is Record<string, string[]> {
* Different peer resolutions and third-party packages keep their installed locations.
* All metadata paths are checked before deletion; the caller first materializes links.
* @param staging - Symlink-free deployed payload root.
* @param workspace - Workspace root relative to which pnpm records hoisted locations.
* @param metadataRoot - Base for pnpm hoistedLocations: the workspace for legacy deploy, the deployment for default deploy.
*/
export async function deduplicateStagedWorkspacePackages(staging: string, workspace: string): Promise<void> {
export async function deduplicateStagedWorkspacePackages(staging: string, metadataRoot: string): Promise<void> {
const modules = resolve(staging, 'node_modules')
const file = join(modules, '.modules.yaml')
const manifest: unknown = load(await readFile(file, 'utf8'))
@@ -27,7 +27,7 @@ export async function deduplicateStagedWorkspacePackages(staging: string, worksp
const duplicates: string[] = []
for (const [identity, locations] of Object.entries(manifest.hoistedLocations)) {
const paths = locations.map((location) => {
const path = resolve(workspace, location)
const path = resolve(metadataRoot, location)
const local = relative(modules, path)
if (local === '' || local === '..' || local.startsWith(`..${sep}`) || isAbsolute(local)) {
throw new Error(`${file}: hoistedLocations path is outside deployed node_modules: ${location}`)
@@ -62,7 +62,7 @@ async function findSymlink(directory: string): Promise<string | undefined> {
/**
* Replace every deploy-time package link below the staged payload with real files.
*
* Legacy deploy links workspace packages into the target's `node_modules`, and
* pnpm deploy can link workspace packages into the target's `node_modules`, and
* those links must survive packaging as files. One link is not a package: when
* the deploy target sits inside the deployed project, pnpm links that project
* into its own `node_modules`. Dereferencing it would copy the payload into
+3
View File
@@ -136,6 +136,9 @@ describe('Python runtime executable builder CLI', () => {
const deploy = result.stdout.split('\n').find(line => line.includes(' --filter dsh-python-runtime-closure deploy'))
expect(deploy).toContain('--prod --config.allow-unused-patches=true')
expect(deploy).toContain('--config.hoist-workspace-packages=false')
expect(deploy).toContain(`--config.pnpmfile=${join(root, 'scripts/python-runtime-deploy.pnpmfile.mjs')}`)
expect(deploy).not.toContain('--legacy')
expect(deploy).not.toContain('--config.auto-install-peers=false')
expect(result.stdout.split('--config.allow-unused-patches=true')).toHaveLength(2)
expect(result.stdout).not.toContain(resolve(root, 'python/sdk-runtime/runtime-bootstrap.mjs'))
expect(result.stdout).toContain('"bin":"runtime-bootstrap.mjs"')
+2 -1
View File
@@ -9,7 +9,7 @@
import { createHash } from 'node:crypto'
import { build as bundle } from 'tsdown'
import { spawn } from 'node:child_process'
import { pnpmInvocation } from './executable-packaging.ts'
import { pnpmInvocation, verifyStagedDependencies } from './executable-packaging.ts'
import { existsSync, statSync } from 'node:fs'
import { chmod, copyFile, cp, glob, mkdir, readFile, readdir, rm, writeFile } from 'node:fs/promises'
import { basename, dirname, join, resolve, sep } from 'node:path'
@@ -334,6 +334,7 @@ class SingleExeBuild {
}
await materializeStagedLinks(this.staging)
await deduplicateStagedWorkspacePackages(this.staging, this.staging)
await verifyStagedDependencies(this.staging)
}
/** Add the executable entry and pkg assets to the staged manifest. */
+18 -1
View File
@@ -2,7 +2,7 @@ import { lstat, mkdir, mkdtemp, readFile, rm, symlink, writeFile } from 'node:fs
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { expect, it, onTestFinished } from 'vitest'
import { restoreLegacyHoists } from './executable-packaging.ts'
import { restoreLegacyHoists, verifyStagedDependencies } from './executable-packaging.ts'
import { materializeStagedLinks } from './build-exe-for-python-sdk-staging.ts'
async function fixture() {
@@ -45,3 +45,20 @@ it('materializes a package junction without deleting its source and drops linked
expect(await readFile(join(test.source, 'peer/index.js'), 'utf8')).toBe('intact')
await expect(lstat(join(test.modules, '.bin'))).rejects.toThrow('ENOENT')
})
it('accepts complete direct dependency directories without requiring optional dependencies', async () => {
const test = await fixture()
await writeFile(join(test.staging, 'package.json'), JSON.stringify({
dependencies: { '@scope/present': '1.0.0' }, optionalDependencies: { optional: '1.0.0' },
}))
await mkdir(join(test.modules, '@scope/present'), { recursive: true })
await expect(verifyStagedDependencies(test.staging)).resolves.toBeUndefined()
})
it.each(['absent', 'file'])('rejects a direct dependency that is %s instead of a directory', async (kind) => {
const test = await fixture()
await writeFile(join(test.staging, 'package.json'), JSON.stringify({ dependencies: { missing: '1.0.0' } }))
if (kind === 'file') await writeFile(join(test.modules, 'missing'), '')
await expect(verifyStagedDependencies(test.staging))
.rejects.toThrow('staged dependencies remain missing: missing.')
})
+18 -6
View File
@@ -1,5 +1,5 @@
/** Shared production-deploy preparation for the SDK and SSH executable carriers. */
import { existsSync } from 'node:fs'
import { existsSync, statSync } from 'node:fs'
import { cp, mkdir, readFile } from 'node:fs/promises'
import { dirname, extname, join, resolve, sep } from 'node:path'
@@ -61,10 +61,22 @@ export async function restoreLegacyHoists(staging: string, sourceNodeModules: st
})
restored.push(dependency)
}
const stillMissing = Object.keys(manifest.dependencies ?? {})
.filter(dependency => !existsSync(join(staging, 'node_modules', dependency)))
if (stillMissing.length > 0) {
throw new Error(`executable-packaging: staged dependencies remain missing: ${stillMissing.join(', ')}.`)
}
await verifyStagedDependencies(staging)
return restored
}
/**
* Reject a deployed payload whose manifest names missing direct dependency directories.
* @param staging - Deployed payload root containing package.json and node_modules.
* @returns Resolves when every declared direct dependency has a directory.
*/
export async function verifyStagedDependencies(staging: string): Promise<void> {
const manifest = JSON.parse(await readFile(join(staging, 'package.json'), 'utf8')) as {
dependencies?: Record<string, string>
}
const missing = Object.keys(manifest.dependencies ?? {}).sort()
.filter(dependency => !statSync(join(staging, 'node_modules', dependency), { throwIfNoEntry: false })?.isDirectory())
if (missing.length > 0) {
throw new Error(`executable-packaging: staged dependencies remain missing: ${missing.join(', ')}.`)
}
}
+6 -3
View File
@@ -1,11 +1,14 @@
/** Preserve workspace build approvals when pnpm deploy converts local dependencies to file URLs. */
/**
* Preserve workspace build approvals when pnpm deploy records local dependencies as file:// URLs.
* This hook lives in the workspace root's scripts/ directory; relative file: approvals use that root.
*/
import { resolve } from 'node:path'
import { pathToFileURL } from 'node:url'
/**
* Translate local build identities without changing their approved or denied status.
* @param {Record<string, unknown> & { allowBuilds?: Record<string, boolean | string> }} config - Source workspace configuration.
* @returns {Record<string, unknown>} Deployment configuration with exact file URL approvals.
* @param {import('./python-runtime-deploy.pnpmfile.mjs').RuntimeDeployConfig} config - Source workspace configuration.
* @returns {import('./python-runtime-deploy.pnpmfile.mjs').RuntimeDeployConfig} Deployment configuration with exact file URL approvals.
*/
function updateConfig(config) {
if (config.allowBuilds === undefined) return config
+2 -2
View File
@@ -1,8 +1,8 @@
/**
* Verify that the executable deploy manifest supplies every plugin referenced
* by a shipped agent preset and every required workspace peer in its dependency
* graph. With auto peer installation disabled, either omission can otherwise
* fail only when Cordis loads the packaged plugin.
* graph. Frozen deployment preserves the locked peer graph; this check also
* requires explicit workspace peers so omissions fail before plugin loading.
*/
import { globSync } from 'node:fs'
import { readFile } from 'node:fs/promises'