Skip to content

Commit d25f87e

Browse files
authored
fix: Generate desktop runtime core lock (#125)
* fix: generate desktop runtime core lock * fix: harden desktop runtime core lock handling Reuse the launcher env constant and only suppress missing top_level.txt metadata so unexpected lock-generation failures stay visible. * fix: honor desktop runtime core lock overrides Preserve explicit launcher lock path overrides for tests and advanced setups, and let the Python lock generator own output directory creation. * docs: fix dependency boundary design wording Clarify the Cua failure-mode sentence in the desktop plugin dependency boundary design by replacing the comma splice with clearer punctuation. * fix: harden runtime core lock generation Replace brittle runtime core lock source-inspection tests with behavior checks, add generator context to failure messages, and tolerate undecodable top-level metadata. Remove the tool-specific execution note from the implementation plan doc. * fix: verify runtime core lock generator output Report signal-terminated generator failures clearly and reject invalid generated lock files so broken build artifacts fail fast with actionable diagnostics.
1 parent 732b1bd commit d25f87e

7 files changed

Lines changed: 694 additions & 0 deletions
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
# Desktop Plugin Dependency Boundary Design
2+
3+
## Context
4+
5+
Packaged desktop builds run AstrBot inside a bundled CPython runtime. Runtime plugin
6+
dependencies are installed into `ASTRBOT_ROOT/data/site-packages` and are then
7+
prepended to `sys.path` by AstrBot's pip installer.
8+
9+
This allows plugin-only dependencies to work, but it also allows plugin installs to
10+
shadow packages already used by the bundled backend runtime. Packages such as
11+
`openai`, `pydantic`, `fastapi`, `numpy`, and PyObjC modules are unsafe to hot-reload
12+
inside a running backend process. Installing Cua exposed this failure mode: pip
13+
installed a second dependency set into plugin `site-packages`; the installer tried to
14+
prefer those modules in-process, and the running OpenAI client later saw incompatible
15+
class identities.
16+
17+
## Goals
18+
19+
- Keep packaged desktop plugin installs from replacing bundled core runtime modules.
20+
- Preserve normal plugin dependency installation when dependencies are not core
21+
runtime packages.
22+
- Make the desktop bundle self-describing enough that runtime code can distinguish
23+
bundled core dependencies from plugin dependencies.
24+
- Favor explicit incompatibility or restart-required behavior over in-process module
25+
replacement.
26+
27+
## Non-Goals
28+
29+
- Full per-plugin virtual environment isolation.
30+
- Rewriting AstrBot's plugin manager.
31+
- Guaranteeing that every PyPI package can coexist in the backend process.
32+
33+
## Design
34+
35+
The desktop backend build writes a `runtime-core-lock.json` file into
36+
`resources/backend/app`. The lock captures distributions installed in the bundled
37+
runtime, their versions, and top-level import modules. The launcher exposes this file
38+
to the backend through `ASTRBOT_DESKTOP_CORE_LOCK_PATH`.
39+
40+
When running in packaged desktop mode, AstrBot's pip installer reads the lock and uses
41+
it for two protections:
42+
43+
1. Add constraints for locked distributions so plugin pip installs cannot upgrade or
44+
downgrade bundled runtime packages.
45+
2. Avoid preferring locked top-level modules from `data/site-packages` after install.
46+
47+
If pip cannot satisfy a plugin because it truly requires a different core dependency
48+
version, installation fails with the existing dependency conflict path. This is
49+
intentional: a clear install-time incompatibility is safer than corrupting the live
50+
backend process.
51+
52+
## Data Flow
53+
54+
1. `scripts/backend/build-backend.mjs` installs backend requirements into the copied
55+
runtime.
56+
2. The build script runs a small Python helper against that runtime to enumerate
57+
installed distributions.
58+
3. The helper writes `app/runtime-core-lock.json`.
59+
4. `launch_backend.py` sets `ASTRBOT_DESKTOP_CORE_LOCK_PATH` before running
60+
`main.py`.
61+
5. The packaged backend pip installer reads the lock while installing plugin
62+
requirements and while attempting dependency preference.
63+
64+
## Error Handling
65+
66+
- If the lock cannot be generated during resource preparation, the backend build
67+
fails. A packaged desktop runtime without this boundary is not considered safe.
68+
- If the lock cannot be read at runtime, AstrBot falls back to existing behavior and
69+
logs a warning. This keeps old custom launch setups from breaking.
70+
- If a plugin conflicts with locked core dependencies, the install fails with a
71+
dependency conflict message.
72+
73+
## Testing
74+
75+
- Script tests cover lock generation and launcher environment wiring.
76+
- AstrBot pip installer tests cover adding lock constraints and skipping locked
77+
modules during post-install preference.
Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
# Desktop Plugin Dependency Boundary Implementation Plan
2+
3+
**Goal:** Prevent packaged desktop plugin installs from replacing bundled backend runtime dependencies.
4+
5+
**Architecture:** Generate a runtime core dependency lock during desktop backend packaging, expose it through an environment variable at launch, and teach AstrBot's packaged pip installer to constrain and skip locked core modules. This keeps plugin-only dependencies installable while preventing unsafe in-process replacement of backend dependencies.
6+
7+
**Tech Stack:** Node.js resource preparation scripts, Python launcher/runtime code, AstrBot pip installer tests with pytest, Node `node:test`.
8+
9+
---
10+
11+
### Task 1: Generate the Desktop Runtime Core Lock
12+
13+
**Files:**
14+
- Modify: `scripts/backend/build-backend.mjs`
15+
- Create: `scripts/backend/templates/generate_runtime_core_lock.py`
16+
- Test: `scripts/backend/runtime-core-lock.test.mjs`
17+
18+
**Step 1: Write the failing test**
19+
20+
Add a Node test that creates a fake runtime Python command, runs the lock generator entry point, and expects `runtime-core-lock.json` to be written under the backend app directory.
21+
22+
**Step 2: Run test to verify it fails**
23+
24+
Run: `node --test scripts/backend/runtime-core-lock.test.mjs`
25+
Expected: FAIL because the helper/export does not exist yet.
26+
27+
**Step 3: Write minimal implementation**
28+
29+
Add a Python helper that uses `importlib.metadata.distributions()` to collect:
30+
- distribution name
31+
- distribution version
32+
- `top_level.txt` modules when present
33+
34+
Call it from `build-backend.mjs` after runtime dependency installation and before the manifest is written.
35+
36+
**Step 4: Run test to verify it passes**
37+
38+
Run: `node --test scripts/backend/runtime-core-lock.test.mjs`
39+
Expected: PASS.
40+
41+
### Task 2: Expose the Lock to the Packaged Backend
42+
43+
**Files:**
44+
- Modify: `scripts/backend/templates/launch_backend.py`
45+
- Test: `scripts/prepare-resources/backend-runtime.test.mjs` or a focused launcher template test
46+
47+
**Step 1: Write the failing test**
48+
49+
Add a test that verifies the launcher template contains `ASTRBOT_DESKTOP_CORE_LOCK_PATH` and points it at `APP_DIR / "runtime-core-lock.json"` only when the file exists.
50+
51+
**Step 2: Run test to verify it fails**
52+
53+
Run: `pnpm run test:prepare-resources`
54+
Expected: FAIL because the launcher does not set the env var yet.
55+
56+
**Step 3: Write minimal implementation**
57+
58+
Set `os.environ["ASTRBOT_DESKTOP_CORE_LOCK_PATH"]` in `launch_backend.py` before `runpy.run_path()` when the lock file exists.
59+
60+
**Step 4: Run test to verify it passes**
61+
62+
Run: `pnpm run test:prepare-resources`
63+
Expected: PASS.
64+
65+
### Task 3: Apply Lock Constraints in the Pip Installer
66+
67+
**Files:**
68+
- Modify: `vendor/AstrBot/astrbot/core/utils/core_constraints.py`
69+
- Modify: `vendor/AstrBot/astrbot/core/utils/pip_installer.py`
70+
- Test: `vendor/AstrBot/tests/test_pip_installer.py`
71+
72+
**Step 1: Write the failing test**
73+
74+
Add a test that sets `ASTRBOT_DESKTOP_CORE_LOCK_PATH` to a JSON lock containing `openai==2.32.0`, then verifies `PipInstaller.install(package_name="Cua")` adds `-c <constraints file>` and the constraints include `openai==2.32.0`.
75+
76+
**Step 2: Run test to verify it fails**
77+
78+
Run: `cd vendor/AstrBot && uv run pytest tests/test_pip_installer.py::<test_name> -q`
79+
Expected: FAIL because the lock is ignored.
80+
81+
**Step 3: Write minimal implementation**
82+
83+
Teach `CoreConstraintsProvider` to merge existing core metadata constraints with locked desktop runtime constraints in packaged mode.
84+
85+
**Step 4: Run test to verify it passes**
86+
87+
Run: `cd vendor/AstrBot && uv run pytest tests/test_pip_installer.py::<test_name> -q`
88+
Expected: PASS.
89+
90+
### Task 4: Skip Locked Modules During Post-Install Preference
91+
92+
**Files:**
93+
- Modify: `vendor/AstrBot/astrbot/core/utils/pip_installer.py`
94+
- Test: `vendor/AstrBot/tests/test_pip_installer.py`
95+
96+
**Step 1: Write the failing test**
97+
98+
Add a test where candidate modules include `openai` and `cua_agent`, the lock marks `openai` as a core module, and `_ensure_plugin_dependencies_preferred` calls `_ensure_preferred_modules` only with `cua_agent`.
99+
100+
**Step 2: Run test to verify it fails**
101+
102+
Run: `cd vendor/AstrBot && uv run pytest tests/test_pip_installer.py::<test_name> -q`
103+
Expected: FAIL because locked modules are still preferred.
104+
105+
**Step 3: Write minimal implementation**
106+
107+
Filter candidate modules using the lock's top-level module set before attempting `_prefer_module_from_site_packages`.
108+
109+
**Step 4: Run test to verify it passes**
110+
111+
Run: `cd vendor/AstrBot && uv run pytest tests/test_pip_installer.py::<test_name> -q`
112+
Expected: PASS.
113+
114+
### Task 5: Full Verification and PR
115+
116+
**Files:**
117+
- All touched files
118+
119+
**Step 1: Run focused tests**
120+
121+
Run:
122+
- `pnpm run test:prepare-resources`
123+
- `cd vendor/AstrBot && uv run pytest tests/test_pip_installer.py -q`
124+
125+
**Step 2: Run repository tests if feasible**
126+
127+
Run:
128+
- `make test`
129+
130+
**Step 3: Commit and open PR**
131+
132+
Commit only intentional files, push `codex/desktop-plugin-dependency-lock`, and create a draft PR against `AstrBotDevs/AstrBot-desktop:main`.

scripts/backend/build-backend.mjs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import {
1919
pruneLinuxTkinterRuntime,
2020
} from './runtime-linux-compat-utils.mjs';
2121
import { isWindowsArm64BundledRuntime } from './runtime-arch-utils.mjs';
22+
import { generateRuntimeCoreLock } from './runtime-core-lock.mjs';
2223

2324
const __dirname = path.dirname(fileURLToPath(import.meta.url));
2425
const projectRoot = path.resolve(__dirname, '..', '..');
@@ -29,6 +30,7 @@ const outputDir = path.join(projectRoot, 'resources', 'backend');
2930
const appDir = path.join(outputDir, 'app');
3031
const runtimeDir = path.join(outputDir, 'python');
3132
const manifestPath = path.join(outputDir, 'runtime-manifest.json');
33+
const runtimeCoreLockPath = path.join(appDir, 'runtime-core-lock.json');
3234
const launcherPath = path.join(outputDir, 'launch_backend.py');
3335
const launcherTemplatePath = path.join(__dirname, 'templates', 'launch_backend.py');
3436
const importScannerScriptPath = path.join(__dirname, 'tools', 'scan_imports.py');
@@ -613,6 +615,10 @@ const main = () => {
613615
copyAppSources(resolvedSourceDir);
614616
const runtimePython = prepareRuntimeExecutable(runtimeSourceReal);
615617
installRuntimeDependencies(runtimePython);
618+
generateRuntimeCoreLock({
619+
runtimePython,
620+
outputPath: runtimeCoreLockPath,
621+
});
616622
pruneLinuxTkinterRuntime(runtimeDir);
617623
patchLinuxRuntimeRpaths(runtimeDir);
618624
writeLauncherScript();
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
import fs from 'node:fs';
2+
import path from 'node:path';
3+
import { spawnSync } from 'node:child_process';
4+
import { fileURLToPath } from 'node:url';
5+
6+
const __dirname = path.dirname(fileURLToPath(import.meta.url));
7+
const generatorScriptPath = path.join(__dirname, 'tools', 'generate_runtime_core_lock.py');
8+
const formatGeneratorContext = (pythonPath) =>
9+
`(python: ${pythonPath ?? 'undefined'}, script: ${generatorScriptPath})`;
10+
11+
export const generateRuntimeCoreLock = ({ runtimePython, outputPath }) => {
12+
if (!runtimePython?.absolute) {
13+
throw new Error(
14+
`Missing runtime Python executable for runtime core lock generation ${formatGeneratorContext(runtimePython?.absolute)}.`,
15+
);
16+
}
17+
if (!outputPath) {
18+
throw new Error(
19+
`Missing output path for runtime core lock generation ${formatGeneratorContext(runtimePython.absolute)}.`,
20+
);
21+
}
22+
23+
const result = spawnSync(
24+
runtimePython.absolute,
25+
[generatorScriptPath, '--output', outputPath],
26+
{
27+
encoding: 'utf8',
28+
stdio: ['ignore', 'pipe', 'pipe'],
29+
windowsHide: true,
30+
},
31+
);
32+
33+
if (result.error) {
34+
throw new Error(
35+
`Failed to generate runtime core lock ${formatGeneratorContext(runtimePython.absolute)}: ${result.error.message}`,
36+
);
37+
}
38+
if (result.status !== 0) {
39+
let detail;
40+
if (result.signal) {
41+
detail = `terminated by signal ${result.signal}`;
42+
} else {
43+
detail = result.stderr?.trim() || result.stdout?.trim() || `exit code ${result.status}`;
44+
}
45+
throw new Error(
46+
`Runtime core lock generation failed ${formatGeneratorContext(runtimePython.absolute)}: ${detail}`,
47+
);
48+
}
49+
50+
{
51+
const context = formatGeneratorContext(runtimePython.absolute);
52+
const baseMessage = `Runtime core lock generator did not create valid ${outputPath} ${context}.`;
53+
54+
if (!fs.existsSync(outputPath)) {
55+
throw new Error(baseMessage);
56+
}
57+
58+
try {
59+
const contents = fs.readFileSync(outputPath, 'utf8');
60+
if (!contents.trim()) {
61+
throw new Error('empty runtime core lock output');
62+
}
63+
JSON.parse(contents);
64+
} catch {
65+
throw new Error(baseMessage);
66+
}
67+
}
68+
};

0 commit comments

Comments
 (0)