server: preserve profile config authority at spawn

This commit is contained in:
2026-08-14 09:54:11 +09:00
parent 4857910410
commit c0f4e80320
3 changed files with 125 additions and 16 deletions
+50 -9
View File
@@ -80,10 +80,6 @@ fn main_config_contract_with_schema(
) )
} }
fn main_config_contract() -> ToolchainContract {
main_config_contract_with_schema(WorkspaceConfigSchemaBundle::empty())
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ts_rs::TS)] #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ts_rs::TS)]
#[ts(export)] #[ts(export)]
pub struct WorkspaceConfigState { pub struct WorkspaceConfigState {
@@ -122,12 +118,14 @@ pub struct ConfigPreviewRequest {
} }
impl SqliteWorkspaceStore { impl SqliteWorkspaceStore {
pub fn ensure_workspace_config_materialized( pub fn ensure_workspace_config_materialized_with_schema(
&self, &self,
workspace_id: &str, workspace_id: &str,
materialized_at: &str, materialized_at: &str,
schema_bundle: WorkspaceConfigSchemaBundle,
) -> Result<WorkspaceConfigState> { ) -> Result<WorkspaceConfigState> {
self.with_conn_mut(|conn| { let desired_schema = schema_bundle.clone();
let state = self.with_conn_mut(|conn| {
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?; let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
let workspace_exists: bool = tx.query_row( let workspace_exists: bool = tx.query_row(
"SELECT EXISTS(SELECT 1 FROM workspaces WHERE workspace_id = ?1)", "SELECT EXISTS(SELECT 1 FROM workspaces WHERE workspace_id = ?1)",
@@ -140,14 +138,21 @@ impl SqliteWorkspaceStore {
let state = match load_state(&tx, workspace_id)? { let state = match load_state(&tx, workspace_id)? {
Some(state) => state, Some(state) => state,
None => { None => {
let state = initial_state()?; let state = initial_state_with_schema(schema_bundle.clone())?;
insert_materialized_state(&tx, workspace_id, &state, materialized_at)?; insert_materialized_state(&tx, workspace_id, &state, materialized_at)?;
state state
} }
}; };
tx.commit()?; tx.commit()?;
Ok(state) Ok(state)
}) })?;
if state.contract.schema_bundle.contributions.is_empty()
&& !desired_schema.contributions.is_empty()
{
let candidate = evaluate_candidate(state, &[], desired_schema)?;
return self.commit_evaluated_workspace_config(workspace_id, &candidate);
}
Ok(state)
} }
pub fn load_workspace_config( pub fn load_workspace_config(
@@ -526,6 +531,12 @@ pub(crate) fn load_state(
} }
pub(crate) fn initial_state() -> Result<WorkspaceConfigState> { pub(crate) fn initial_state() -> Result<WorkspaceConfigState> {
initial_state_with_schema(WorkspaceConfigSchemaBundle::empty())
}
pub(crate) fn initial_state_with_schema(
schema_bundle: WorkspaceConfigSchemaBundle,
) -> Result<WorkspaceConfigState> {
let path = main_config_path(); let path = main_config_path();
let snapshot = ConfigTreeSnapshot::empty() let snapshot = ConfigTreeSnapshot::empty()
.apply(&[ConfigTreeChange::Create { .apply(&[ConfigTreeChange::Create {
@@ -534,7 +545,7 @@ pub(crate) fn initial_state() -> Result<WorkspaceConfigState> {
content: DEFAULT_MAIN_CONFIG_SOURCE.to_string(), content: DEFAULT_MAIN_CONFIG_SOURCE.to_string(),
}]) }])
.map_err(config_error)?; .map_err(config_error)?;
let contract = main_config_contract(); let contract = main_config_contract_with_schema(schema_bundle);
let projection_digest = SnapshotEnvironment::new(snapshot.clone()) let projection_digest = SnapshotEnvironment::new(snapshot.clone())
.evaluate_contract(&contract) .evaluate_contract(&contract)
.map_err(|diagnostics| { .map_err(|diagnostics| {
@@ -935,6 +946,36 @@ mod tests {
assert!(error.to_string().contains("schema fingerprint")); assert!(error.to_string().contains("schema fingerprint"));
} }
#[tokio::test]
async fn initial_materialization_persists_composed_schema_contract() {
let store = open_store().await;
let schema_bundle = WorkspaceConfigSchemaBundle::compose([ConfigSchemaContribution::new(
"builtin:test",
"test",
"1",
r#"{ test = { value = String default "initial"; }; }"#,
)
.unwrap()])
.unwrap();
let expected = initial_state_with_schema(schema_bundle.clone()).unwrap();
let state = store
.ensure_workspace_config_materialized_with_schema(
"w-config",
"2026-08-13T00:00:00Z",
schema_bundle,
)
.unwrap();
assert_eq!(state.contract.fingerprint, expected.contract.fingerprint);
assert_eq!(
state.contract.schema_bundle,
expected.contract.schema_bundle
);
assert_eq!(state.projection_digest, expected.projection_digest);
let reloaded = store.load_workspace_config("w-config").unwrap().unwrap();
assert_eq!(reloaded.contract, state.contract);
assert_eq!(reloaded.projection_digest, state.projection_digest);
}
#[tokio::test] #[tokio::test]
async fn workspace_materializes_main_entrypoint() { async fn workspace_materializes_main_entrypoint() {
let store = open_store().await; let store = open_store().await;
+69 -2
View File
@@ -1201,6 +1201,21 @@ impl RuntimeRegistry {
_ => {} _ => {}
} }
let runtime = self.runtime(runtime_id)?; let runtime = self.runtime(runtime_id)?;
if let Some(bundle) = request.resolved_config_bundle.clone() {
let sync = runtime.sync_config_bundle(bundle);
if sync.state != WorkerOperationState::Accepted {
let message = sync
.diagnostics
.first()
.map(|diagnostic| diagnostic.message.clone())
.unwrap_or_else(|| "Runtime rejected the resolved config bundle".to_string());
return Err(RuntimeRegistryError::RuntimeOperationFailed {
runtime_id: runtime_id.to_string(),
code: "worker_config_bundle_sync_rejected".to_string(),
message,
});
}
}
Ok(runtime.spawn_worker(request)) Ok(runtime.spawn_worker(request))
} }
@@ -1960,12 +1975,13 @@ impl WorkspaceWorkerRuntime for EmbeddedWorkerRuntime {
} }
}; };
let workspace_id = workspace_api.workspace_id.clone(); let workspace_id = workspace_api.workspace_id.clone();
let config_bundle = spawn_config_bundle_ref(&request);
let create_request = CreateWorkerRequest { let create_request = CreateWorkerRequest {
idempotency_key, idempotency_key,
idempotency_fingerprint, idempotency_fingerprint,
profile, profile,
display_name: request.requested_worker_name.clone(), display_name: request.requested_worker_name.clone(),
config_bundle: None, config_bundle,
profile_source, profile_source,
initial_input: initial_worker_input(&request.initial_submit), initial_input: initial_worker_input(&request.initial_submit),
working_directory_request: request.resolved_working_directory_request.clone(), working_directory_request: request.resolved_working_directory_request.clone(),
@@ -3090,12 +3106,13 @@ impl WorkspaceWorkerRuntime for RemoteWorkerRuntime {
}; };
} }
}; };
let config_bundle = spawn_config_bundle_ref(&request);
let create = CreateWorkerRequest { let create = CreateWorkerRequest {
idempotency_key, idempotency_key,
idempotency_fingerprint, idempotency_fingerprint,
profile, profile,
display_name: request.requested_worker_name.clone(), display_name: request.requested_worker_name.clone(),
config_bundle: None, config_bundle,
profile_source, profile_source,
initial_input: initial_worker_input(&request.initial_submit), initial_input: initial_worker_input(&request.initial_submit),
working_directory_request: request.resolved_working_directory_request.clone(), working_directory_request: request.resolved_working_directory_request.clone(),
@@ -3360,6 +3377,16 @@ fn embedded_worker_projection_diagnostics() -> Vec<RuntimeDiagnostic> {
)] )]
} }
fn spawn_config_bundle_ref(request: &WorkerSpawnRequest) -> Option<ConfigBundleRef> {
request
.resolved_config_bundle
.as_ref()
.map(|bundle| ConfigBundleRef {
id: bundle.metadata.id.clone(),
digest: bundle.metadata.digest.clone(),
})
}
fn profile_source_archive_for_request( fn profile_source_archive_for_request(
request: &WorkerSpawnRequest, request: &WorkerSpawnRequest,
profile: &ProfileSelector, profile: &ProfileSelector,
@@ -4776,6 +4803,46 @@ mod tests {
} }
} }
#[test]
fn spawn_config_bundle_ref_preserves_bundle_identity() {
let mut request = embedded_spawn_request();
let bundle = test_config_bundle();
let expected_id = bundle.metadata.id.clone();
let expected_digest = bundle.metadata.digest.clone();
request.resolved_config_bundle = Some(bundle);
let bundle_ref = spawn_config_bundle_ref(&request).expect("bundle reference");
assert_eq!(bundle_ref.id, expected_id);
assert_eq!(bundle_ref.digest, expected_digest);
}
#[test]
fn registry_syncs_bundle_before_embedded_spawn() {
let runtime = EmbeddedWorkerRuntime::new_memory_with_execution_backend(
"local:test",
Arc::new(AcceptingExecutionBackend::default()),
)
.expect("test backend should connect");
let registry = RuntimeRegistry::for_workspace(runtime);
let mut request = embedded_spawn_request();
let bundle = test_config_bundle();
let bundle_ref = ConfigBundleRef {
id: bundle.metadata.id.clone(),
digest: bundle.metadata.digest.clone(),
};
request.resolved_config_bundle = Some(bundle);
let result = registry
.spawn_worker("embedded-worker-runtime", request)
.expect("spawn request");
assert_eq!(result.state, WorkerOperationState::Accepted);
let check = registry
.check_config_bundle("embedded-worker-runtime", bundle_ref)
.expect("bundle check");
assert_eq!(check.state, WorkerOperationState::Accepted);
assert!(check.availability.is_some());
}
#[test] #[test]
fn embedded_runtime_rejects_missing_workspace_api_binding() { fn embedded_runtime_rejects_missing_workspace_api_binding() {
let runtime = EmbeddedWorkerRuntime::new_memory_with_execution_backend( let runtime = EmbeddedWorkerRuntime::new_memory_with_execution_backend(
+6 -5
View File
@@ -751,14 +751,15 @@ impl WorkspaceApi {
let config_store = Arc::new(crate::SqliteWorkspaceStore::open( let config_store = Arc::new(crate::SqliteWorkspaceStore::open(
config.database_path.clone(), config.database_path.clone(),
)?); )?);
config_store.ensure_workspace_config_materialized(
&config.workspace_id,
&Utc::now().to_rfc3339_opts(SecondsFormat::Secs, true),
)?;
let config_schema_registry = crate::config_source::WorkspaceConfigSchemaRegistry::default() let config_schema_registry = crate::config_source::WorkspaceConfigSchemaRegistry::default()
.with_provider(Arc::new( .with_provider(Arc::new(
crate::profile_settings::ProfileConfigSchemaProvider, crate::profile_settings::ProfileConfigSchemaProvider,
)); ));
config_store.ensure_workspace_config_materialized_with_schema(
&config.workspace_id,
&Utc::now().to_rfc3339_opts(SecondsFormat::Secs, true),
config_schema_registry.compose()?,
)?;
let api = Self { let api = Self {
config_store, config_store,
config_schema_registry, config_schema_registry,
@@ -17291,7 +17292,7 @@ mod tests {
let path = format!("/api/w/{TEST_WORKSPACE_ID}/settings/profiles"); let path = format!("/api/w/{TEST_WORKSPACE_ID}/settings/profiles");
let settings = get_json(app.clone(), &path).await; let settings = get_json(app.clone(), &path).await;
assert_eq!(settings["default_profile"], "builtin:companion"); assert_eq!(settings["default_profile"], "builtin:companion");
assert_eq!(settings["config_revision"], 0); assert_eq!(settings["config_revision"], 1);
assert!(settings["tree_digest"].as_str().is_some()); assert!(settings["tree_digest"].as_str().is_some());
assert!(settings["projection_digest"].as_str().is_some()); assert!(settings["projection_digest"].as_str().is_some());
assert!( assert!(