Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions rust/contracts/rust-core-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -538,8 +538,8 @@ or removing a command fails until the table changes in the same commit.
| `build.decodeConfiguration` | Validate native source identities, raw/effective values and XML bindings |
| `build.prepareRunPlan` | Plan Provider-owned application/service/task preparation from a model target |
| `build.decodeRunPreparation` | Validate portable launch data before the native Run host starts a process |
| `build.testDiscoveryPlan` | Plan opt-in Provider test discovery for an instance |
| `build.decodeTestDiscovery` | Validate, deduplicate and order Provider test selectors |
| `build.testDiscoveryPlan` | Plan opt-in command or Provider test discovery for an instance |
| `build.decodeTestDiscovery` | Validate, deduplicate and order discovered test selectors |
| `build.runEntrypointsPlan` | Plan a Provider request for the run entrypoints of one source file (`buildProviders` 1) |
| `build.decodeRunEntrypoints` | Validate and deduplicate the run entrypoints a Provider named |
| `build.dependencyPlan` | Expand the command that prints a project's dependency tree, or the request a build provider answers |
Expand Down Expand Up @@ -5281,8 +5281,8 @@ and the directories are absolute host paths used only as substitution text.
| `build.runConfigurationPlan` | `manifest`, `buildSystemID`, required `workspaceRoot`, and `request: {configurationId, localDocument?, instances: [{root, options?, modelInputs?}], pluginDirectory?, workspaceStateDirectory?}` | `plan` as `build.taskPlan` returns it plus `runType: {pluginID, buildSystemID, type}`: the global arguments, then the type's `arguments` with the saved field values, the instance's options and the configuration's program arguments, at the configuration's working directory, with its environment over the options'. The instance is the deepest one whose root holds the working directory, or the only one; `plugin.build.invalidSelection` when several exist and none holds it or the configuration belongs to another plugin or build system, `plugin.build.unavailable` when the type is no longer declared, `plugin.build.invalidRunConfiguration` with `field: values.<fieldID>` when a saved value no longer fits. A configuration that is missing, disabled, unavailable or of another provider fails the call |
| `build.beforeLaunchTaskPlan` | `manifest`, `buildSystemID`, required `workspaceRoot`, and `request: {task, workingDirectory, instances: [{root, options?, modelInputs?}], pluginDirectory?, workspaceStateDirectory?}`, with `task` and `workingDirectory` as `runConfig.beforeLaunch` returned the step | `plan` as `build.taskPlan` returns it plus `beforeLaunchTask: {pluginID, buildSystemID, type}`: the global arguments, then the task's `arguments` with the saved field values and the instance's options, at the step's working directory with the options' environment, as a `task` execution. The instance is chosen as for `build.runConfigurationPlan`; `plugin.build.invalidSelection` when several exist and none holds the working directory or the task belongs to another plugin or build system, `plugin.build.unavailable` when the task is no longer declared, `plugin.build.invalidBeforeLaunchTask` with `field: values.<fieldID>` when a saved value no longer fits. A working directory outside the workspace fails the call |
| `build.testPlan` | plan fields plus `project?`, `target?`, `suite?`, `case?`, `userArguments?`, `projects?` (the model's project directories) | command plan or `provider: {method: "lithe/build/test", params}`, plus `results`: `null`, `{ decoder, reports }` with workspace-relative globs (for the selected project, or for the root and every listed project when none is selected), or command-only `{ decoder: "hostIntegration" }`. Command filters that templates cannot place, such as a case without its suite when the tool only addresses `Suite#case`, are `plugin.build.invalidSelection`; Provider filters remain separate typed values and must be declared supported |
| `build.testDiscoveryPlan` | common plan fields plus `refresh?`, `tool?`; no project/output file | `plan.provider` for `lithe/build/discoverTests`, only with `test.discovery: true`, using the same effective options and effect metadata |
| `build.decodeTestDiscovery` | common plan fields plus canonical `result` | `discovery.tests` with validated `{id, suite, case, project?, target?}` selectors; bounded at 10,000 items/32 MiB, deterministic and exactly runnable; malformed replies reject in full |
| `build.testDiscoveryPlan` | Common plan fields, plus a fresh absolute `outputFile` for `test.discoveryCommand`, or optional `refresh` and `tool` for `test.discovery: true`. No project selection. | Command plan with argv, environment, instance working directory, `output: "outputFile"`, `decoder: "litheTestDiscovery"` and effect metadata, or `plan.provider` for `lithe/build/discoverTests` with the effective options. |
| `build.decodeTestDiscovery` | Original common plan fields plus the same `outputFile` for a completed command or canonical inline `result` for a Provider. | `discovery.tests` with validated `{id, suite, case, project?, target?}` selectors. Bounded at 10,000 items and 32 MiB, deterministic and exactly runnable. Malformed results reject in full with `plugin.build.invalidOutput`. |
| `build.runEntrypointsPlan` | common plan fields plus `file` (workspace-relative, inside the instance), `refresh?`, `tool?`; no project/output file | `plan.provider` for `lithe/build/runEntrypoints` with `file`, only when a run declares `entrypoints: true`; decoder `litheRunEntrypoints` |
| `build.decodeRunEntrypoints` | common plan fields plus canonical `result` | `entrypoints.entrypoints`: `[{run, name, entrypoint, project:{name, path}}]` in the provider's order without exact duplicates; at most 64; each names an entrypoint run, a 1–256 byte name, a 1–4,096 byte entrypoint and a project inside the instance; malformed replies reject in full with `plugin.build.invalidOutput` |
| `build.prepareRunPlan` | common plan fields, `run`, required `project`, `target` (required for a target run, refused for an entrypoint run), `userArguments?`, `optionOverrides?`, `launchOptions?`, `workspaceRoot?` (required for an explicit launch cwd); no output file | `plan.provider` for `lithe/build/prepareRun`, selected declaration/tags/paths/options validated; typed launch options must match the run's declared execution kind, a service or task run requires them, and an entrypoint run requires `launchOptions.entrypoint` and sends no `target` |
Expand Down Expand Up @@ -6935,6 +6935,7 @@ a code has one meaning across every contribution with that lifecycle:
| `debugAdapter/start` | `debugAdapters[]` | process start |
| `lithe/build/model` | `buildSystems[].model` command source | command run |
| `lithe/build/dependencies` | `buildSystems[].dependencies` command source | command run |
| `lithe/build/discoverTests` | `buildSystems[].test.discoveryCommand` | command run |
| `commandInstaller/install` | `commandInstallers[]` installation the user confirmed; `decode` when a provided command is missing after a successful exit | command run |

| `stage` | Process start | Command run |
Expand Down
2 changes: 1 addition & 1 deletion rust/crates/build/src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -302,7 +302,7 @@ pub fn build_test_plan_command<M: BuildManifest>(payload: Value) -> Result<Value
)
}

/// `build.testDiscoveryPlan`: a typed request for provider-owned test discovery.
/// `build.testDiscoveryPlan`: a command plan or provider request for test discovery.
pub fn build_test_discovery_plan_command<M: BuildManifest>(
payload: Value,
) -> Result<Value, CoreError> {
Expand Down
57 changes: 49 additions & 8 deletions rust/crates/build/src/decode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
use lithe_plugin_model::{PluginRejection, Validation};
use lithe_workspace::{self as workspace, fs};
use serde_json::Value;
use std::io::Read;
use std::path::{Component, Path, PathBuf};
use std::time::UNIX_EPOCH;

Expand Down Expand Up @@ -62,24 +63,41 @@ fn first_line(text: &str) -> &str {

/// Reads a UTF-8 file up to the output bound.
pub(crate) fn read_bounded(path: &Path) -> Validation<String> {
String::from_utf8(read_file_bytes(path)?)
.map_err(|_| invalid_output("The build tool output is not UTF-8."))
}

/// Bytes of a file up to the output bound, or `None` when it is absent, not
/// a regular file, or too large.
pub(crate) fn read_bytes_bounded(path: &Path) -> Option<Vec<u8>> {
// Sync fingerprints treat an unreadable input as absent.
read_file_bytes(path).ok()
}

fn read_file_bytes(path: &Path) -> Validation<Vec<u8>> {
let metadata = fs::metadata(path)
.map_err(|_| invalid_output("The build tool did not write its output file."))?;
if !metadata.is_file() || metadata.len() > MAX_OUTPUT_BYTES as u64 {
return Err(invalid_output(
"The build tool output file is missing or too large.",
));
}
fs::read_to_string(path).map_err(|_| invalid_output("The build tool output is not UTF-8."))
let file = fs::File::open(path)
.map_err(|_| invalid_output("The build tool output file could not be opened."))?;
read_output(file, metadata.len() as usize)
}

/// Bytes of a file up to the output bound, or `None` when it is absent, not
/// a regular file, or too large.
pub(crate) fn read_bytes_bounded(path: &Path) -> Option<Vec<u8>> {
let metadata = fs::metadata(path).ok()?;
if !metadata.is_file() || metadata.len() > MAX_OUTPUT_BYTES as u64 {
return None;
fn read_output(reader: impl Read, observed_size: usize) -> Validation<Vec<u8>> {
let mut bytes = Vec::with_capacity(observed_size + 1);
// The opened file may have grown since the metadata check.
reader
.take(MAX_OUTPUT_BYTES as u64 + 1)
.read_to_end(&mut bytes)
.map_err(|_| invalid_output("The build tool output file could not be read."))?;
if bytes.len() > MAX_OUTPUT_BYTES {
return Err(invalid_output("The build tool output is too large."));
}
fs::read(path).ok()
Ok(bytes)
}

/// Bounds a host-provided output text before it is parsed line by line.
Expand Down Expand Up @@ -428,6 +446,29 @@ fn is_current(path: &Path, not_before_millis: Option<u64>) -> bool {
mod tests {
use super::*;

#[test]
fn output_read_enforces_the_limit_even_if_the_file_grows() {
let limit = MAX_OUTPUT_BYTES as u64;
let at_limit = std::io::repeat(b'x').take(limit);
assert_eq!(
read_output(at_limit, MAX_OUTPUT_BYTES).unwrap().len(),
MAX_OUTPUT_BYTES
);

// Metadata reported an in-budget size, but the stream contains more.
let mut over_limit = std::io::repeat(b'x').take(limit + 2);
let rejected = match read_output(&mut over_limit, MAX_OUTPUT_BYTES) {
Ok(bytes) => panic!("accepted an oversized output of {} bytes", bytes.len()),
Err(error) => error,
};
assert_eq!(rejected.code, "plugin.build.invalidOutput");
assert_eq!(
over_limit.limit(),
1,
"read past the extra byte needed to detect overflow"
);
}

#[test]
fn wildcards_match_within_a_segment() {
assert!(wildcard("TEST-*.xml", "TEST-demo.OrderTest.xml"));
Expand Down
3 changes: 3 additions & 0 deletions rust/crates/build/src/manifest/checks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,9 @@ fn program(build_system: &BuildSystemDeclaration) -> Value {
review["source"] = json!("provider");
}
if test.discovery { review["discovery"] = json!(true); }
if let Some(command) = &test.discovery_command {
review["discoveryCommand"] = json!(command);
}
review
}),
"model": model,
Expand Down
6 changes: 6 additions & 0 deletions rust/crates/build/src/manifest/options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,12 @@ impl BuildSystemDeclaration {
}
if let Some(test) = &self.test {
lists.push((format!("{field}.test.arguments"), &test.arguments));
if let Some(command) = &test.discovery_command {
lists.push((
format!("{field}.test.discoveryCommand.arguments"),
&command.arguments,
));
}
}
if let Some(ModelSource::Command { arguments, .. }) = &self.model {
lists.push((format!("{field}.model.arguments"), arguments));
Expand Down
56 changes: 52 additions & 4 deletions rust/crates/build/src/manifest/testing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,29 @@ pub(crate) struct TestDeclaration {
/// The provider can enumerate exact selectors for the native test tree.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub(crate) discovery: bool,
/// A separate discovery command that writes a canonical selector document.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(crate) discovery_command: Option<TestDiscoveryCommand>,
pub(crate) arguments: Vec<BuildArgument>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(crate) results: Option<TestResultsSource>,
}

impl TestDeclaration {
pub(crate) fn discovers_tests(&self) -> bool {
self.discovery || self.discovery_command.is_some()
}
}

/// Command input plus the effect facts the host needs before launch.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub(crate) struct TestDiscoveryCommand {
pub(crate) arguments: Vec<BuildArgument>,
pub(crate) executes_project_code: bool,
pub(crate) may_use_network: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub(crate) enum TestFilter {
Expand All @@ -62,6 +80,13 @@ pub(crate) enum TestResultsSource {
}

impl BuildSystemDeclaration {
/// Whether the declaration needs buildSystems 1 for command-based discovery.
pub fn has_test_discovery_command(&self) -> bool {
self.test
.as_ref()
.is_some_and(|test| test.discovery_command.is_some())
}

pub(crate) fn validate_test(
&mut self,
field: &str,
Expand Down Expand Up @@ -95,16 +120,39 @@ impl BuildSystemDeclaration {
test.selector_kinds.sort();
test.filters.sort();
test.filters.dedup();
if test.discovery
&& (test.source != TaskSource::Provider
|| !test.filters.contains(&TestFilter::Suite)
if test.discovers_tests()
&& (!test.filters.contains(&TestFilter::Suite)
|| !test.filters.contains(&TestFilter::Case))
{
return Err(invalid(
&field,
"Test discovery requires a provider and suite/case filters.",
"Test discovery requires suite and case filters.",
));
}
if test.discovery
&& (test.source != TaskSource::Provider || test.discovery_command.is_some())
{
return Err(invalid(
&field,
"Provider test discovery requires provider tests and no discoveryCommand.",
));
}
if let Some(command) = &test.discovery_command {
let field = format!("{field}.discoveryCommand");
let arguments = format!("{field}.arguments");
check_argument_count(&command.arguments, &arguments)?;
template::validate_arguments(
&command.arguments,
&Allowed {
root: true,
host_directories: true,
options: Some(options),
..Allowed::none()
},
&arguments,
)?;
check_output_channel(OutputChannel::OutputFile, &command.arguments, &field)?;
}
if test.source == TaskSource::Provider {
if !test.arguments.is_empty() {
return Err(invalid(&field, "Provider tests require empty arguments."));
Expand Down
2 changes: 1 addition & 1 deletion rust/crates/build/src/outputs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ fn message_text(value: &str) -> Option<String> {
}

/// The text a finished command left: its stdout, or the file it wrote.
fn command_output(
pub(crate) fn command_output(
channel: OutputChannel,
output: Option<&str>,
output_file: Option<&str>,
Expand Down
Loading
Loading