World's first open-source enterprise world model.
Rust agent-memorybitemporalgraphragknowledge-baseknowledge-graphllmontologypgvectorpostgresqlragrustself-hostedsemantic-searchtemporal-knowledge-graphworld-model
Adopting a proposal commits the element, its follow-up work and the decision together (#1257)
Maya Kid1cc0bfbc4ca9
diff --git a/crates/utopia-server/src/api/ontology_routes.rs b/crates/utopia-server/src/api/ontology_routes.rsindex 2be1dd56..5c66b7c5 100644--- a/crates/utopia-server/src/api/ontology_routes.rs+++ b/crates/utopia-server/src/api/ontology_routes.rs@@ -541,15 +541,17 @@ pub async fn stored_proposals(pub struct DecideProposalReq {pub section: String,pub key: String,- /// adopted | rejected+ /// 只收 rejected;采纳走 `/ontology/proposals/adopt`pub status: String,- /// 拒绝的理由(0061:下一轮代理读得到)。采纳时忽略+ /// 拒绝的理由(0061:下一轮代理读得到)#[serde(default)]pub reason: Option<String>,}-/// 一条提案有人表态了。**改状态不删行**:采纳发生过、拒绝也发生过,-/// 而拒绝留痕正是下一轮 Suggest 不再把它刷回待看的依据。+/// 拒绝一条提案。**改状态不删行**:拒绝留痕正是下一轮代理不再把它刷回待看的依据。+///+/// 从前这里也收 adopted,只把状态改成采纳,元素、回归用例、对齐一样都没有。采纳要把+/// 这些和状态一起提交,只有 `/ontology/proposals/adopt` 做得到(0061 决定 3)pub async fn decide_proposal(State(state): State<AppState>,AuthUser(user): AuthUser,@@ -557,35 +559,25 @@ pub async fn decide_proposal(Json(req): Json<DecideProposalReq>,) -> ApiResult<Json<serde_json::Value>> {require_kb(&state, &user, kb_id, Role::Editor).await?;- if !matches!(req.status.as_str(), "adopted" | "rejected") {- return Err(AppError::invalid("bad_status", "status 只能是 adopted 或 rejected").into());- }- let reason = req- .reason- .as_deref()- .map(str::trim)- .filter(|s| !s.is_empty());- if req.status == "rejected" && reason.is_some() {- utopia_store::ontology::reject_proposal(- &state.pool,- kb_id,- &req.section,- &req.key,- reason,- user.id,- )- .await?;- } else {- utopia_store::ontology::decide_proposal(- &state.pool,- kb_id,- &req.section,- &req.key,- &req.status,- user.id,+ if req.status == "adopted" {+ return Err(AppError::invalid(+ "adoption_endpoint",+ "Adopt a proposal through /ontology/proposals/adopt; this endpoint only rejects",)- .await?;+ .into());}+ if req.status != "rejected" {+ return Err(AppError::invalid("bad_status", "status 只能是 rejected").into());+ }+ utopia_store::ontology::reject_proposal(+ &state.pool,+ kb_id,+ &req.section,+ &req.key,+ req.reason.as_deref(),+ user.id,+ )+ .await?;Ok(Json(json!({ "ok": true })))}diff --git a/crates/utopia-server/src/ontology_agent.rs b/crates/utopia-server/src/ontology_agent.rsindex 979cba57..449e8391 100644--- a/crates/utopia-server/src/ontology_agent.rs+++ b/crates/utopia-server/src/ontology_agent.rs@@ -10,10 +10,12 @@ use std::collections::{HashMap, HashSet};use serde::Deserialize;use serde_json::{json, Value};use sha2::{Digest, Sha256};+use sqlx::{Postgres, Transaction};use utopia_core::models::{RelationAxioms, RelationTypeView};use utopia_core::AppError;use utopia_extract::ontology_agent as agent;use utopia_store::agent_reviews::{self, Review};+use utopia_store::ontology::StoredProposal;use utopia_store::phrase_bindings::PhraseSignature;use utopia_store::type_bindings::KindWordSignature;use utopia_store::{competency_questions, phrase_bindings, type_bindings};@@ -852,8 +854,12 @@ fn strings(v: Option<&Value>) -> Vec<String> {.collect()}-/// 采纳一条代理提案(0061 决定 3):建出元素,标记提案,排对齐让形状重判。-/// 返回新元素的 id+/// 采纳一条代理提案(0061 决定 3):锁住提案,在一个事务里重读并锁住它要的类或复用的目标,+/// 写元素(复用时写人的判定)、回归用例、采纳的状态和后续任务,一次提交。返回新元素的 id,+/// 复用时是目标的 id。+///+/// 从前这几步各自提交:属性先落库,例句写回归用例时才发现宾语是实体(`bad_property_shape`),+/// 留下一个没有提案采纳过的属性、一份排着的对齐,和一条键已被占、再也采纳不了的提案pub async fn adopt(state: &AppState,kb_id: Uuid,@@ -863,9 +869,120 @@ pub async fn adopt(actor: Uuid,) -> Result<Uuid, AppError> {let pool = &state.pool;- let Some(p) = utopia_store::ontology::open_proposal(pool, kb_id, section, key).await? else {+ let mut tx = pool.begin().await?;+ let (id, detail) = match adopt_on(&mut tx, kb_id, section, key, edits, actor).await {+ Ok(done) => done,+ Err(error) => {+ // 回滚完再答:马上重试的请求不会撞上这次还没放掉的锁+ if let Err(rollback) = tx.rollback().await {+ return Err(AppError::Other(+ anyhow::Error::new(error)+ .context(format!("rolling back an adoption: {rollback}")),+ ));+ }+ return Err(busy(error));+ }+ };+ tx.commit().await?;+ let _ = utopia_store::audit::record(+ pool,+ Some(kb_id),+ actor,+ "ontology_proposal.adopted",+ section.trim_end_matches('s'),+ Some(id),+ detail,+ )+ .await;+ state.emit_graph(kb_id);+ if section == "map_to" {+ state.emit_review(kb_id);+ }+ Ok(id)+}++/// 采纳和别的写撞上、整个事务回滚了,什么都没留下,重试是安全的:答审核页认得、可以重试的+/// `alignment_busy`。死锁(40P01)在这个事务的哪一步碰上都这样答(比如复用类按词改实体时,+/// 和先改留下的、再改并掉的实体合并互相等),话里也不指认是谁在改。等锁超时(55P03)只出在+/// 复用类那一段(只有它设了 `lock_timeout`),照审核页定类别词时的话答+fn busy(error: AppError) -> AppError {+ if matches!(&error, AppError::Db(sqlx::Error::Database(e))+ if e.code().as_deref() == Some("40P01"))+ {+ return AppError::CodedConflict {+ code: "alignment_busy",+ message: "Another change touched what this adoption writes; nothing was saved. Please try again."+ .into(),+ };+ }+ type_bindings::busy_on_lock_timeout(error)+}++/// 按键找到这些类,锁住防删(FOR KEY SHARE),返回的 id 和键一一对应:采纳提交之前它们删不掉,+/// 正被删的等删完再答 `unknown_class`,不会写父类、定义域时才撞上外键答 500。按 id 的顺序锁。+///+/// 不用 FOR SHARE:那会挡住这几行上的每一次 UPDATE。补向量的任务(`set_type_embeddings`)在+/// 一个事务里按堆的顺序改一批类,和按 id 顺序的 FOR SHARE 互相等成死锁。采纳只读 id,防删就够了+async fn lock_classes(+ tx: &mut Transaction<'_, Postgres>,+ kb_id: Uuid,+ keys: &[String],+) -> Result<Vec<Uuid>, AppError> {+ let found: Vec<(String, Uuid)> = sqlx::query_as(+ "SELECT key, id FROM entity_types WHERE kb_id = $1 AND key = ANY($2)+ ORDER BY id FOR KEY SHARE",+ )+ .bind(kb_id)+ .bind(keys)+ .fetch_all(&mut **tx)+ .await?;+ keys.iter()+ .map(|k| {+ found+ .iter()+ .find(|(key, _)| key == k)+ .map(|(_, id)| *id)+ .ok_or_else(|| {+ AppError::invalid("unknown_class", format!("class `{k}` does not exist"))+ })+ })+ .collect()+}++/// 采纳锁住的那一行+#[derive(sqlx::FromRow)]+struct Locked {+ id: Uuid,+ #[sqlx(flatten)]+ proposal: StoredProposal,+}++/// 采纳在事务里的全部;返回元素的 id 和审计要记的几格+async fn adopt_on(+ tx: &mut Transaction<'_, Postgres>,+ kb_id: Uuid,+ section: &str,+ key: &str,+ edits: AdoptEdits,+ actor: Uuid,+) -> Result<(Uuid, Value), AppError> {+ // 先锁提案:同一条的另一次采纳、拒绝和代理的刷新都等这次提交,提交后它已不再开着。+ // 只认代理提的:旧 Suggest 留下的提案没有采纳的入口+ let locked: Option<Locked> = sqlx::query_as(+ "SELECT id, section, key, payload, proposed_by, serves, signatures+ FROM ontology_proposals+ WHERE kb_id = $1 AND section = $2 AND key = $3 AND status = 'open' AND proposed_by = 'agent'+ FOR UPDATE",+ )+ .bind(kb_id)+ .bind(section)+ .bind(key)+ .fetch_optional(&mut **tx)+ .await?;+ let Some(locked) = locked else {return Err(AppError::NotFound);};+ let p = &locked.proposal;// 人改过几格:决定 5 的第二个数要它let edited = edits.label.is_some()|| edits.description.is_some()@@ -873,17 +990,6 @@ pub async fn adopt(|| edits.domains.is_some()|| edits.ranges.is_some()|| edits.parents.is_some();- let classes = utopia_store::graph::entity_types(pool, kb_id).await?;- let by_key: HashMap<&str, Uuid> = classes.iter().map(|c| (c.key.as_str(), c.id)).collect();- let resolve = |keys: Vec<String>| -> Result<Vec<Uuid>, AppError> {- keys.iter()- .map(|k| {- by_key.get(k.as_str()).copied().ok_or_else(|| {- AppError::invalid("unknown_class", format!("class `{k}` does not exist"))- })- })- .collect()- };let label = edits.label.as_deref()@@ -901,15 +1007,18 @@ pub async fn adopt(.to_string();let id = match section {// 「用已有的」:形状各写一条人的绑定判定(同审核页),类别词各归到那个类- "map_to" => adopt_map_to(state, kb_id, &p, &classes).await?,+ "map_to" => adopt_map_to(tx, kb_id, p).await?,"entity_types" => {- let parents = resolve(- edits+ let parents = lock_classes(+ tx,+ kb_id,+ &edits.parents.unwrap_or_else(|| strings(p.payload.get("parents"))),- )?;+ )+ .await?;let id = utopia_store::ontology::create_entity_type(- pool,+ &mut **tx,kb_id,key,&label,@@ -920,13 +1029,7 @@ pub async fn adopt().await?;// 多了一个类:类别词里「没有」「没定」的要重判,短语对齐跟在它后面- let _ = utopia_store::jobs::enqueue_unless_pending(- pool,- "align_types",- json!({ "kb_id": kb_id }),- std::time::Duration::from_secs(5),- )- .await;+ embed_then_align(tx, kb_id, "align_types").await?;id}"relation_types" | "attribute_types" => {@@ -935,20 +1038,19 @@ pub async fn adopt(} else {"relation"};- let domains = resolve(- edits- .domains- .unwrap_or_else(|| strings(p.payload.get("domains"))),- )?;+ let domains = edits+ .domains+ .unwrap_or_else(|| strings(p.payload.get("domains")));let ranges = if kind == "relation" {- resolve(- edits- .ranges- .unwrap_or_else(|| strings(p.payload.get("ranges"))),- )?+ edits+ .ranges+ .unwrap_or_else(|| strings(p.payload.get("ranges")))} else {Vec::new()};+ // 定义域和值域一次锁上,整批按 id 排序+ let classes = lock_classes(tx, kb_id, &[domains.as_slice(), &ranges].concat()).await?;+ let (domains, ranges) = classes.split_at(domains.len());let datatype = if kind == "attribute" {Some(datatype_or_text(@@ -963,7 +1065,7 @@ pub async fn adopt(None};let id = utopia_store::ontology::create_relation_type(- pool,+ &mut **tx,kb_id,key,&label,@@ -971,20 +1073,14 @@ pub async fn adopt(RelationAxioms::default(),&description,kind,- &domains,- &ranges,+ domains,+ ranges,datatype.as_deref(),None,).await?;// 多了一个属性:判成 none / undecided 的形状也许对得上了(0053 的指纹变了)- let _ = utopia_store::jobs::enqueue_unless_pending(- pool,- "align_phrases",- json!({ "kb_id": kb_id }),- std::time::Duration::from_secs(5),- )- .await;+ embed_then_align(tx, kb_id, "align_phrases").await?;id}_ => {@@ -994,39 +1090,50 @@ pub async fn adopt())}};- // 新元素要有向量,对齐的短名单才看得见它(候选多于短名单长度时按向量挑;没向量的- // 属性永远进不了名单,形状的指纹就不变,采纳了也不重判——第一次真跑 bordered_by 就- // 是这样)。补的只是缺的那几条,通常一次 embed 调用- if section != "map_to" {- if let Err(e) = crate::ontology_index::refresh(state, kb_id).await {- tracing::warn!(%kb_id, error = %e, "采纳后本体向量没补上,对齐的短名单看不见新元素");- }- }- finish_adoption(pool, kb_id, &p, id, actor).await?;- if edited {- utopia_store::ontology::mark_proposal_edited(pool, kb_id, section, key).await?;- }- let _ = utopia_store::audit::record(- pool,- Some(kb_id),- actor,- "ontology_proposal.adopted",- section.trim_end_matches('s'),- Some(id),- json!({ "key": key, "label": label, "proposed_by": p.proposed_by, "serves": p.serves }),+ finish_adoption(tx, kb_id, &locked, id, actor, edited).await?;+ let detail =+ json!({ "key": key, "label": label, "proposed_by": p.proposed_by, "serves": p.serves });+ Ok((id, detail))+}++/// 新元素的后续任务,和元素一起提交:先补向量、再对齐,同编辑器的次序。新元素要有向量,对齐+/// 的短名单才看得见它(候选多于短名单长度时按向量挑;没向量的属性永远进不了名单,形状的指纹+/// 就不变,采纳了也不重判——第一次真跑 bordered_by 就是这样)。从前采纳在请求里就地嵌+/// (cut 1.1),现在对齐开跑时看见补向量的还排着或跑着就等它(`align_*_reasking`)。+/// 两份都照排,不看有没有同样的排着:排着的那份可能在这次提交之前就被领走,读的是还没有这个+/// 元素的本体(0051)+async fn embed_then_align(+ tx: &mut Transaction<'_, Postgres>,+ kb_id: Uuid,+ align: &str,+) -> Result<(), AppError> {+ let payload = json!({ "kb_id": kb_id });+ utopia_store::jobs::enqueue_with_max_attempts_tx(tx, "embed_ontology", payload.clone(), 3)+ .await?;+ // 对齐晚几秒到期,同编辑器(补向量 2 秒后、对齐 5 秒后)。两份同时到期的话 worker 一起+ // 领走,对齐看见补向量正跑着,就把自己挪到半分钟后。补向量更慢时照样等它+ utopia_store::jobs::enqueue_with_max_attempts_after_tx(+ tx,+ align,+ payload,+ 3,+ std::time::Duration::from_secs(5),)- .await;- state.emit_graph(kb_id);- Ok(id)+ .await?;+ Ok(())}+/// 回归用例和采纳的状态(决定 4),在采纳的事务里。人改过没有(决定 5 的第二个数)和状态同一条+/// UPDATE 写下:从前是采纳提交之后的另一条语句async fn finish_adoption(- pool: &sqlx::PgPool,+ tx: &mut Transaction<'_, Postgres>,kb_id: Uuid,- proposal: &utopia_store::ontology::StoredProposal,+ locked: &Locked,property_id: Uuid,actor: Uuid,+ edited: bool,) -> Result<(), AppError> {+ let proposal = &locked.proposal;let mut examples = Vec::new();let property = matches!(proposal.section.as_str(),@@ -1054,22 +1161,15 @@ async fn finish_adoption(examples.extend(ids.into_iter().map(|statement| (statement, direction)));}}- let mut tx = pool.begin().await?;- let open: Option<Uuid> = sqlx::query_scalar(- "SELECT id FROM ontology_proposals WHERE kb_id=$1 AND section=$2 AND key=$3 AND status='open' FOR UPDATE"- ).bind(kb_id).bind(&proposal.section).bind(&proposal.key).fetch_optional(&mut *tx).await?;- if open.is_none() {- return Err(AppError::NotFound);- }for (statement_id, direction) in examples {// Removed examples cannot be checked; never substitute another statement.let live: Option<Uuid> = sqlx::query_scalar("SELECT id FROM facts WHERE kb_id=$1 AND id=$2 AND layer='open' AND invalidated_at IS NULL FOR SHARE")- .bind(kb_id).bind(statement_id).fetch_optional(&mut *tx).await?;+ .bind(kb_id).bind(statement_id).fetch_optional(&mut **tx).await?;if live.is_none() {continue;}utopia_store::ontology_regressions::add_on(- &mut tx,+ tx,kb_id,utopia_store::ontology_regressions::NewCase {statement_id,@@ -1082,55 +1182,62 @@ async fn finish_adoption(.await?;}sqlx::query(- "UPDATE ontology_proposals SET status='adopted',decided_by=$2,decided_at=now() WHERE id=$1",+ "UPDATE ontology_proposals SET status='adopted',decided_by=$2,decided_at=now(),edited=edited OR $3 WHERE id=$1",)- .bind(open)+ .bind(locked.id).bind(actor)- .execute(&mut *tx)+ .bind(edited)+ .execute(&mut **tx).await?;- tx.commit().await?;Ok(())}-/// map_to 的采纳:目标是属性,提案里的每条形状写成人的绑定(属性 + 方向),投影跟着-/// 排(同审核页的 `decide_alignment_phrase`);目标是类,每个类别词归到它。返回目标的 id+/// map_to 的采纳,在采纳的事务里:目标是属性,提案里的每条形状写成人的绑定(属性 + 方向),+/// 投影跟着排(同审核页的 `decide_alignment_phrase`);目标是类,每个类别词归到它,短语对齐+/// 跟着排。返回目标的 idasync fn adopt_map_to(- state: &AppState,+ tx: &mut Transaction<'_, Postgres>,kb_id: Uuid,- p: &utopia_store::ontology::StoredProposal,- classes: &[utopia_core::models::EntityType],+ p: &StoredProposal,) -> Result<Uuid, AppError> {- let pool = &state.pool;let kind = p.payload.get("kind").and_then(Value::as_str).unwrap_or("relation");if kind == "class" {- let class = classes- .iter()- .find(|c| c.key == p.key)- .map(|c| c.id)- .ok_or_else(|| AppError::invalid("unknown_class", "no class with that key"))?;- for w in strings(p.signatures.get("kind_words")) {- type_bindings::decide_and_apply_human(- pool,- kb_id,- &w,- Some(class),- &json!({ "person": p.key, "via": "ontology_agent" }),- )+ let class = lock_classes(tx, kb_id, std::slice::from_ref(&p.key)).await?[0];+ // 实体正被抽取或对齐改着时只等 2 秒,同审核页的类别词判定+ sqlx::query("SET LOCAL lock_timeout = '2s'")+ .execute(&mut **tx).await?;+ let votes = json!({ "person": p.key, "via": "ontology_agent" });+ for w in strings(p.signatures.get("kind_words")) {+ type_bindings::decide_and_apply_human_tx(tx, kb_id, &w, Some(class), &votes).await?;}+ // 换了类,这些实体的短语签名跟着变:短语对齐和判定一起提交,整次采纳排一份。照排,不看+ // 有没有同样的排着,理由同 `embed_then_align`:排着的那份可能在这次提交之前就被领走+ utopia_store::jobs::enqueue_with_max_attempts_tx(+ tx,+ "align_phrases",+ json!({ "kb_id": kb_id }),+ 3,+ )+ .await?;return Ok(class);}- let property = utopia_store::ontology::relation_type_views(pool, kb_id)- .await?- .into_iter()- .find(|r| r.key == p.key)- .map(|r| r.id)+ // 目标在事务里重读并锁住防删(FOR KEY SHARE,理由同 `lock_classes`):采纳提交之前它删不掉+ let property: Option<Uuid> = sqlx::query_scalar(+ "SELECT id FROM relation_types WHERE kb_id = $1 AND key = $2 FOR KEY SHARE",+ )+ .bind(kb_id)+ .bind(&p.key)+ .fetch_optional(&mut **tx)+ .await?;+ let property = property.ok_or_else(|| AppError::invalid("unknown_property", "no property with that key"))?;- let sigs = phrase_bindings::signatures(pool, kb_id).await?;+ let sigs = phrase_bindings::signatures(&mut **tx, kb_id).await?;+ let mut written = false;for shape in p.signatures.get("phrases")@@ -1147,8 +1254,8 @@ async fn adopt_map_to(_ => "forward",};let votes = json!({ "person": { "property": p.key, "direction": direction, "via": "ontology_agent" } });- phrase_bindings::decide_with_delivery(- pool,+ written |= phrase_bindings::decide_on(+ tx,kb_id,sig,phrase_bindings::Decision {@@ -1164,7 +1271,17 @@ async fn adopt_map_to().await?;}- state.emit_review(kb_id);+ if written {+ // 判定和它的投影一起提交(0051)。整次提交排一份,不是一条形状一份:这些判定都和这一份+ // 同一次提交,它跑时读当下的绑定,0051 要的「每条判定都有和它一起提交的任务」照样成立+ utopia_store::jobs::enqueue_with_max_attempts_tx(+ tx,+ phrase_bindings::MATERIALIZE_KIND,+ json!({ "kb_id": kb_id }),+ 3,+ )+ .await?;+ }Ok(property)}diff --git a/crates/utopia-server/src/ontology_agent_tests.rs b/crates/utopia-server/src/ontology_agent_tests.rsindex ac822692..410f4f6d 100644--- a/crates/utopia-server/src/ontology_agent_tests.rs+++ b/crates/utopia-server/src/ontology_agent_tests.rs@@ -2,15 +2,25 @@//! `ontology_proposals` 并记下服务的问题与形状;采纳建出属性并排对齐;提过的形状下一轮//! 不再送。没有 `UTOPIA_DATABASE_URL` 时跳过。use super::*;+use axum::body::{to_bytes, Body};+use axum::http::{Request, StatusCode};use axum::{extract::State, response::IntoResponse, routing::post, Json, Router};use serde_json::{json, Value};+use std::sync::atomic::{AtomicUsize, Ordering};use std::sync::{Arc, Mutex};+use tower::ServiceExt;use utopia_store::phrase_bindings::Decision;#[derive(Clone)]struct Model {replies: Arc<Mutex<Vec<Value>>>,requests: Arc<Mutex<Vec<Value>>>,+ embeds: Arc<AtomicUsize>,+}+/// 嵌入端点只数次数:采纳不该在请求里调它+async fn embed(State(m): State<Model>) -> Json<Value> {+ m.embeds.fetch_add(1, Ordering::SeqCst);+ Json(json!({ "data": [] }))}async fn reply(State(m): State<Model>, Json(body): Json<Value>) -> impl IntoResponse {m.requests.lock().unwrap().push(body);@@ -89,11 +99,13 @@ impl Fx {let model = Model {replies: Arc::new(Mutex::new(replies)),requests: Arc::new(Mutex::new(Vec::new())),+ embeds: Arc::new(AtomicUsize::new(0)),};let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;let endpoint = format!("http://{}", listener.local_addr()?);let router = Router::new().route("/chat/completions", post(reply))+ .route("/embeddings", post(embed)).with_state(model.clone());let server = tokio::spawn(async move { axum::serve(listener, router).await.unwrap() });utopia_store::settings::upsert(@@ -178,6 +190,89 @@ impl Fx {self.model.requests.lock().unwrap().len()}+ /// 一条形状写进提案里的样子,带第一条例句的陈述 id+ async fn shape(&self, phrase: &str) -> anyhow::Result<Value> {+ let sigs = phrase_bindings::signatures(&self.pool, self.kb).await?;+ let sig = sigs+ .iter()+ .find(|s| s.phrase == phrase)+ .ok_or_else(|| anyhow::anyhow!("no shape `{phrase}`"))?;+ Ok(shape_of(sig))+ }++ /// 代理提过的一条,直接落库+ async fn seed(+ &self,+ section: &str,+ key: &str,+ payload: Value,+ signatures: Value,+ ) -> anyhow::Result<()> {+ utopia_store::ontology::save_agent_proposals(+ &self.pool,+ self.kb,+ &[utopia_store::ontology::AgentProposal {+ section: section.into(),+ key: key.into(),+ payload,+ serves: Vec::new(),+ signatures,+ }],+ )+ .await?;+ Ok(())+ }++ /// 以这个库的编辑身份走一次接口+ async fn post(&self, path: &str, body: Value) -> anyhow::Result<(StatusCode, Value)> {+ sqlx::query(+ "INSERT INTO kb_members(kb_id,user_id,role) VALUES($1,$2,'editor') ON CONFLICT DO NOTHING",+ )+ .bind(self.kb)+ .bind(self.user)+ .execute(&self.pool)+ .await?;+ let token = crate::auth::issue_token(&self.state, self.user)?;+ let request = Request::post(format!("/api/v1/kbs/{}{path}", self.kb))+ .header("content-type", "application/json")+ .header("authorization", format!("Bearer {token}"))+ .body(Body::from(body.to_string()))?;+ let response = crate::api::router(self.state.clone(), &Default::default())+ .oneshot(request)+ .await?;+ let status = response.status();+ let bytes = to_bytes(response.into_body(), 1 << 20).await?;+ Ok((+ status,+ serde_json::from_slice(&bytes).unwrap_or(Value::Null),+ ))+ }++ /// 这个库排着的任务,按到期的先后+ async fn queued(&self) -> anyhow::Result<Vec<String>> {+ Ok(sqlx::query_scalar(+ "SELECT kind FROM jobs WHERE status='queued' AND payload->>'kb_id'=$1 ORDER BY run_at, id",+ )+ .bind(self.kb.to_string())+ .fetch_all(&self.pool)+ .await?)+ }++ /// 一个键留下了什么:同键的元素在不在、提案的状态、这个库的任务数、回归用例数+ async fn left_by(&self, key: &str) -> anyhow::Result<(bool, String, i64, i64)> {+ Ok(sqlx::query_as(+ "SELECT EXISTS(SELECT 1 FROM relation_types WHERE kb_id=$1 AND key=$2)+ OR EXISTS(SELECT 1 FROM entity_types WHERE kb_id=$1 AND key=$2),+ (SELECT status FROM ontology_proposals WHERE kb_id=$1 AND key=$2),+ (SELECT count(*) FROM jobs WHERE payload->>'kb_id'=$1::text),+ (SELECT count(*) FROM ontology_regression_cases WHERE kb_id=$1)",+ )+ .bind(self.kb)+ .bind(key)+ .fetch_one(&self.pool)+ .await?)+ }+async fn cleanup(self) -> anyhow::Result<()> {self.server.abort();sqlx::query("DELETE FROM jobs WHERE payload->>'kb_id'=$1")@@ -201,6 +296,17 @@ impl Fx {}}+/// founded in 那条形状提成的关系:organization → place+fn founded_in() -> Value {+ json!({ "key": "founded_in", "label": "founded in", "description": "where an organization was founded",+ "temporal": "state", "domains": ["organization"], "ranges": ["place"], "proposed_by": "agent" })+}++/// 代理提的新类:city,父类 place+fn city() -> Value {+ json!({ "key": "city", "label": "City", "description": "a city", "parents": ["place"], "proposed_by": "agent" })+}+fn user_text(request: &Value) -> String {request["messages"].as_array()@@ -676,3 +782,222 @@ async fn a_base_with_no_questions_gets_them_proposed_and_the_report_counts_them();f.cleanup().await}++/// 采纳半途失败什么都不留。字面值属性的例句宾语是实体,回归用例写不进去:从前属性先提交、+/// 对齐先排上,提案还开着而键已被占,这条提案再也采纳不了+#[tokio::test]+async fn a_failed_adoption_leaves_nothing_behind() -> anyhow::Result<()> {+ let Some(f) = Fx::new(Vec::new()).await? else {+ return Ok(());+ };+ let founding_note = json!({ "key": "founding_note", "label": "founding note", "description": "x",+ "datatype": "text", "domains": ["organization"], "proposed_by": "agent" });+ let shapes = json!({ "phrases": [f.shape("founded in").await?] });+ f.seed("attribute_types", "founding_note", founding_note, shapes)+ .await?;+ let adopt = json!({ "section": "attribute_types", "key": "founding_note" });+ let (status, body) = f.post("/ontology/proposals/adopt", adopt).await?;+ assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY, "{body}");+ assert_eq!(body["code"], "bad_property_shape");+ assert_eq!(+ f.left_by("founding_note").await?,+ (false, "open".to_string(), 0, 0),+ "no attribute, no job, no case; the proposal stays open for a person to reject"+ );+ f.cleanup().await+}++/// 只改状态的接口不再收「采纳」:从前它把提案标成采纳,元素却没建+#[tokio::test]+async fn the_status_only_endpoint_does_not_adopt() -> anyhow::Result<()> {+ let Some(f) = Fx::new(Vec::new()).await? else {+ return Ok(());+ };+ f.seed("relation_types", "founded_in", founded_in(), json!({}))+ .await?;+ let adopt = json!({ "section": "relation_types", "key": "founded_in", "status": "adopted" });+ let (status, body) = f.post("/ontology/proposals", adopt).await?;+ assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY, "{body}");+ assert_eq!(body["code"], "adoption_endpoint");+ assert_eq!(+ f.left_by("founded_in").await?,+ (false, "open".to_string(), 0, 0)+ );+ f.cleanup().await+}++/// 退役的 Suggest 留下的提案不能采纳:工作台早就不列它(`stored_proposals`),从前直接调采纳的+/// 接口却照样建出元素+#[tokio::test]+async fn a_proposal_the_retired_suggest_left_is_not_adopted() -> anyhow::Result<()> {+ let Some(f) = Fx::new(Vec::new()).await? else {+ return Ok(());+ };+ f.seed("relation_types", "founded_in", founded_in(), json!({}))+ .await?;+ sqlx::query("UPDATE ontology_proposals SET proposed_by='suggest' WHERE kb_id=$1")+ .bind(f.kb)+ .execute(&f.pool)+ .await?;+ let adopt = json!({ "section": "relation_types", "key": "founded_in" });+ let (status, body) = f.post("/ontology/proposals/adopt", adopt).await?;+ assert_eq!(status, StatusCode::NOT_FOUND, "{body}");+ f.cleanup().await+}++/// 采纳像编辑器一样先排补向量、再排对齐(新属性排短语对齐,新类排类别词对齐),和元素同一次+/// 提交,请求里不调嵌入。对齐晚 5 秒到期:同时到期的话两份一起被领走,对齐看见补向量正跑着,+/// 就把自己挪到半分钟后+#[tokio::test]+async fn adoption_queues_vectors_before_alignment() -> anyhow::Result<()> {+ let Some(f) = Fx::new(Vec::new()).await? else {+ return Ok(());+ };+ // 配上嵌入模型:请求里就地嵌的话,嵌入端点数得到+ sqlx::query(+ "UPDATE llm_settings SET embed_base_url = chat_base_url, embed_model = 'scripted-embed'+ WHERE workspace_id = (SELECT workspace_id FROM knowledge_bases WHERE id = $1)",+ )+ .bind(f.kb)+ .execute(&f.pool)+ .await?;+ f.seed("relation_types", "founded_in", founded_in(), json!({}))+ .await?;+ f.seed("entity_types", "city", city(), json!({})).await?;+ for (section, key, align) in [+ ("relation_types", "founded_in", "align_phrases"),+ ("entity_types", "city", "align_types"),+ ] {+ let adopt = json!({ "section": section, "key": key });+ let (status, body) = f.post("/ontology/proposals/adopt", adopt).await?;+ assert_eq!(status, StatusCode::OK, "{body}");+ assert_eq!(+ (f.queued().await?, f.model.embeds.load(Ordering::SeqCst)),+ (vec!["embed_ontology".to_string(), align.to_string()], 0),+ "{key}: the vectors are queued ahead of alignment, and the request embeds nothing"+ );+ let gap: f64 = sqlx::query_scalar(+ "SELECT extract(epoch FROM max(run_at) - min(run_at))::float8 FROM jobs WHERE payload->>'kb_id'=$1",+ )+ .bind(f.kb.to_string())+ .fetch_one(&f.pool)+ .await?;+ assert!(+ gap >= 5.0,+ "{key}: alignment is due {gap} s after the vectors"+ );+ sqlx::query("DELETE FROM jobs WHERE payload->>'kb_id'=$1")+ .bind(f.kb.to_string())+ .execute(&f.pool)+ .await?;+ }+ f.cleanup().await+}++/// 复用属性时每条形状写一条人的绑定,整次采纳排一份投影,不是一条形状一份+#[tokio::test]+async fn a_reuse_queues_one_projection_for_its_shapes() -> anyhow::Result<()> {+ let Some(f) = Fx::new(Vec::new()).await? else {+ return Ok(());+ };+ let shapes = json!({ "phrases": [f.shape("located in").await?, f.shape("founded in").await?] });+ let reuse = json!({ "key": "located_in", "label": "located in", "kind": "relation", "proposed_by": "agent" });+ f.seed("map_to", "located_in", reuse, shapes).await?;+ let adopt = json!({ "section": "map_to", "key": "located_in" });+ let (status, body) = f.post("/ontology/proposals/adopt", adopt).await?;+ assert_eq!(status, StatusCode::OK, "{body}");+ let bound: i64 = sqlx::query_scalar(+ "SELECT count(*) FROM phrase_bindings WHERE kb_id=$1 AND decided_by='person' AND relation_type_id=$2",+ )+ .bind(f.kb)+ .bind(f.located_in)+ .fetch_one(&f.pool)+ .await?;+ assert_eq!(+ (bound, f.queued().await?),+ (2, vec![phrase_bindings::MATERIALIZE_KIND.to_string()]),+ "both shapes are the person's, and one projection follows them"+ );+ f.cleanup().await+}++/// 复用类时类别词写成人的判定,整次采纳另排一份短语对齐,已经排着一份也照排:那份可能在这次+/// 提交之前就被领走,读不到换过的类+#[tokio::test]+async fn a_class_reuse_queues_its_own_phrase_alignment() -> anyhow::Result<()> {+ let Some(f) = Fx::new(Vec::new()).await? else {+ return Ok(());+ };+ utopia_store::jobs::enqueue(&f.pool, "align_phrases", json!({ "kb_id": f.kb })).await?;+ let reuse = json!({ "key": "organization", "kind": "class", "proposed_by": "agent" });+ let words = json!({ "kind_words": ["company"] });+ f.seed("map_to", "organization", reuse, words).await?;+ let adopt = json!({ "section": "map_to", "key": "organization" });+ let (status, body) = f.post("/ontology/proposals/adopt", adopt).await?;+ assert_eq!(status, StatusCode::OK, "{body}");+ let bound: Option<Uuid> = sqlx::query_scalar(+ "SELECT type_id FROM type_bindings WHERE kb_id=$1 AND kind_word='company' AND decided_by='person'",+ )+ .bind(f.kb)+ .fetch_one(&f.pool)+ .await?;+ assert_eq!(+ (bound, f.queued().await?),+ (Some(f.organization), vec!["align_phrases".to_string(); 2]),+ "company is the person's, and the adoption queues its own phrase alignment"+ );+ f.cleanup().await+}++/// 采纳途中,提案要的类被删了:等删完答 unknown_class,什么都不写,不是写父类时才撞上外键+#[tokio::test]+async fn a_class_deleted_during_adoption_answers_unknown_class() -> anyhow::Result<()> {+ let Some(f) = Fx::new(Vec::new()).await? else {+ return Ok(());+ };+ // 没有实体的类才删得掉+ sqlx::query(+ "INSERT INTO entity_types(id,kb_id,key,label,color,shape,description)+ VALUES ($1,$2,'region','Region','#000','circle','x')",+ )+ .bind(Uuid::now_v7())+ .bind(f.kb)+ .execute(&f.pool)+ .await?;+ let mut town = city();+ town["parents"] = json!(["region"]);+ f.seed("entity_types", "city", town, json!({})).await?;+ let mut deleting = f.pool.begin().await?;+ let pid: i32 = sqlx::query_scalar("SELECT pg_backend_pid()")+ .fetch_one(&mut *deleting)+ .await?;+ sqlx::query("DELETE FROM entity_types WHERE kb_id=$1 AND key='region'")+ .bind(f.kb)+ .execute(&mut *deleting)+ .await?;+ let pool = f.pool.clone();+ let delete = async move {+ // 等采纳排到这次删除后面,再提交+ for _ in 0..500 {+ let waiting: bool = sqlx::query_scalar(+ "SELECT EXISTS(SELECT 1 FROM pg_stat_activity WHERE $1 = ANY(pg_blocking_pids(pid)))",+ )+ .bind(pid)+ .fetch_one(&pool)+ .await?;+ if waiting {+ break;+ }+ tokio::time::sleep(std::time::Duration::from_millis(10)).await;+ }+ deleting.commit().await?;+ anyhow::Ok(())+ };+ let adopt = json!({ "section": "entity_types", "key": "city" });+ let ((status, body), ()) =+ tokio::try_join!(f.post("/ontology/proposals/adopt", adopt), delete)?;+ assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY, "{body}");+ assert_eq!(body["code"], "unknown_class");+ assert_eq!(f.left_by("city").await?, (false, "open".to_string(), 0, 0));+ f.cleanup().await+}diff --git a/crates/utopia-store/src/jobs.rs b/crates/utopia-store/src/jobs.rsindex 12d2553d..0ca39fc2 100644--- a/crates/utopia-store/src/jobs.rs+++ b/crates/utopia-store/src/jobs.rs@@ -187,6 +187,35 @@ pub async fn enqueue_with_max_attempts_tx(Ok(id)}+/// 同 [`enqueue_with_max_attempts_tx`],但 `after` 之后才到期。从插入这一刻+/// (`clock_timestamp()`)算起:`now()` 是事务开始的时刻,事务长了,提交时延迟已经用掉+pub async fn enqueue_with_max_attempts_after_tx(+ tx: &mut Transaction<'_, Postgres>,+ kind: &str,+ payload: serde_json::Value,+ max_attempts: i32,+ after: Duration,+) -> AppResult<i64> {+ if !(1..=32).contains(&max_attempts) {+ return Err(utopia_core::AppError::Validation(+ "max_attempts must be between 1 and 32".into(),+ ));+ }+ let (id,): (i64,) = sqlx::query_as(+ "INSERT INTO jobs (kind, payload, max_attempts, run_at)+ VALUES ($1, $2, $3, clock_timestamp() + make_interval(secs => $4))+ RETURNING id",+ )+ .bind(kind)+ .bind(payload)+ .bind(max_attempts)+ .bind(after.as_secs_f64())+ .fetch_one(&mut **tx)+ .await?;+ notify_worker_tx(tx).await?;+ Ok(id)+}+/// Wake idle workers only after the transaction containing the job is committed./// PostgreSQL delivers `NOTIFY` at commit, so a worker can never wake up before/// the row it needs to claim is visible.diff --git a/crates/utopia-store/src/ontology.rs b/crates/utopia-store/src/ontology.rsindex 7c12bb23..0b86f343 100644--- a/crates/utopia-store/src/ontology.rs+++ b/crates/utopia-store/src/ontology.rs@@ -153,8 +153,8 @@ fn validate_key(key: &str) -> AppResult<()> {}#[allow(clippy::too_many_arguments)]-pub async fn create_entity_type(- pool: &PgPool,+pub async fn create_entity_type<'a>(+ pool: impl sqlx::Acquire<'a, Database = sqlx::Postgres>,kb_id: Uuid,key: &str,label: &str,@@ -165,6 +165,7 @@ pub async fn create_entity_type() -> AppResult<Uuid> {validate_key(key)?;validate_shape(shape)?;+ let mut tx = pool.begin().await?;let id = Uuid::now_v7();sqlx::query("INSERT INTO entity_types (id, kb_id, key, label, color, shape, description)@@ -177,7 +178,7 @@ pub async fn create_entity_type(.bind(color).bind(shape).bind(description)- .execute(pool)+ .execute(&mut *tx).await.map_err(|e| match &e {sqlx::Error::Database(db) if db.is_unique_violation() => {@@ -185,7 +186,8 @@ pub async fn create_entity_type(}_ => AppError::Db(e),})?;- set_parents(&mut *pool.acquire().await?, kb_id, id, parents).await?;+ set_parents(&mut tx, kb_id, id, parents).await?;+ tx.commit().await?;Ok(id)}@@ -455,8 +457,8 @@ async fn validate_property_links(}#[allow(clippy::too_many_arguments)]-pub async fn create_relation_type(- pool: &PgPool,+pub async fn create_relation_type<'a>(+ pool: impl sqlx::Acquire<'a, Database = sqlx::Postgres>,kb_id: Uuid,key: &str,label: &str,@@ -476,9 +478,10 @@ pub async fn create_relation_type());}validate_attribute_fields(kind, domains, datatype)?;+ let mut tx = pool.begin().await?;let label = &lower_camel(label);// 新建的行 id 还不存在,指向自己无从谈起——所以 self_id 传 None- validate_property_links(&mut *pool.acquire().await?, kb_id, None, kind, ax).await?;+ validate_property_links(&mut tx, kb_id, None, kind, ax).await?;let is_attr = kind == "attribute";let id = Uuid::now_v7();sqlx::query(@@ -509,7 +512,7 @@ pub async fn create_relation_type(// 属性不带这两条(上面已经拦了非空的情况,这里是兜底).bind(if is_attr { None } else { ax.inverse_of }).bind(if is_attr { None } else { ax.sub_property_of })- .execute(pool)+ .execute(&mut *tx).await.map_err(|e| match &e {sqlx::Error::Database(db) if db.is_unique_violation() => {@@ -518,13 +521,8 @@ pub async fn create_relation_type(_ => AppError::Db(e),})?;// attribute 不写 range:它的值域是字面量类型,落在 datatype 上- set_domains_ranges(- &mut *pool.acquire().await?,- id,- domains,- if is_attr { &[] } else { ranges },- )- .await?;+ set_domains_ranges(&mut tx, id, domains, if is_attr { &[] } else { ranges }).await?;+ tx.commit().await?;Ok(id)}@@ -1817,7 +1815,10 @@ pub async fn signatures_already_proposed(.await?)}-/// 一条提案被拒了,连理由。改状态不删行(同 `decide_proposal`)+/// 一条提案被拒了,连理由(没写就空着)。+///+/// **改状态而不是删行**:拒绝发生过,跟 `fact_adoptions`、`entity_retypes` 同一条路。+/// 留痕还有个当下就用得着的作用——代理下一轮不会把它刷回待看。pub async fn reject_proposal(pool: &PgPool,kb_id: Uuid,@@ -1841,7 +1842,7 @@ pub async fn reject_proposal(Ok(())}-/// 一条还开着的提案,按键取(采纳时要读它的 payload)+/// 一条还开着的提案,按键取(代理把这一轮的 map_to 并进上一轮的时候读它)pub async fn open_proposal(pool: &PgPool,kb_id: Uuid,@@ -1871,34 +1872,6 @@ pub async fn open_proposals(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<StoredP.await?)}-/// 一条提案被采纳或拒绝了。-///-/// **改状态而不是删行**:采纳发生过、拒绝也发生过。跟 `fact_adoptions`、-/// `entity_retypes` 同一条路。拒绝留痕还有个当下就用得着的作用——下一轮-/// Suggest 不会把它刷回待看。-pub async fn decide_proposal(- pool: &PgPool,- kb_id: Uuid,- section: &str,- key: &str,- status: &str,- actor: Uuid,-) -> AppResult<()> {- sqlx::query(- "UPDATE ontology_proposals- SET status = $4, decided_by = $5, decided_at = now()- WHERE kb_id = $1 AND section = $2 AND key = $3 AND status = 'open'",- )- .bind(kb_id)- .bind(section)- .bind(key)- .bind(status)- .bind(actor)- .execute(pool)- .await?;- Ok(())-}-/// 这些类的全部祖先(不含自己)。沿 `subClassOf` 上溯,多继承与菱形都走得通。////// 给按块检索的候选补地板用:向量检索偏爱字面出现在正文里的叶子类,@@ -2062,22 +2035,3 @@ pub async fn agent_proposal_report(pool: &PgPool, kb_id: Uuid) -> AppResult<Agen.fetch_one(pool).await?)}--/// 采纳时人改过:记下来,占比才算得出-pub async fn mark_proposal_edited(- pool: &PgPool,- kb_id: Uuid,- section: &str,- key: &str,-) -> AppResult<()> {- sqlx::query(- "UPDATE ontology_proposals SET edited = true- WHERE kb_id = $1 AND section = $2 AND key = $3",- )- .bind(kb_id)- .bind(section)- .bind(key)- .execute(pool)- .await?;- Ok(())-}diff --git a/crates/utopia-store/src/phrase_bindings.rs b/crates/utopia-store/src/phrase_bindings.rsindex a54a933c..2d62a0d8 100644--- a/crates/utopia-store/src/phrase_bindings.rs+++ b/crates/utopia-store/src/phrase_bindings.rs@@ -52,7 +52,11 @@ pub struct PhraseSignature {}/// 库里每条 distinct 的签名:活着的开放陈述,按短语、两端的类、宾语是不是字面值分组。-pub async fn signatures(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<PhraseSignature>> {+/// 采纳复用一条属性时在它自己的事务里读(不另占一条连接),所以收任何执行器+pub async fn signatures<'e>(+ pool: impl sqlx::Executor<'e, Database = sqlx::Postgres>,+ kb_id: Uuid,+) -> AppResult<Vec<PhraseSignature>> {// 一条陈述可以有多条证据。计数、取例句前先为每条陈述选一条稳定的引用,// 优先有完整位置的证据,避免证据多的陈述挤掉其他陈述。let sql = format!(diff --git a/crates/utopia-store/src/type_bindings.rs b/crates/utopia-store/src/type_bindings.rsindex 86f119f9..0c5e8b79 100644--- a/crates/utopia-store/src/type_bindings.rs+++ b/crates/utopia-store/src/type_bindings.rs@@ -17,7 +17,7 @@//! 不收([`decide_and_apply_if_current`])。use chrono::{DateTime, Utc};-use sqlx::{Executor, PgPool, Postgres};+use sqlx::{Executor, PgPool, Postgres, Transaction};use std::collections::HashMap;use utopia_core::{AppError, AppResult};use uuid::Uuid;@@ -438,18 +438,7 @@ pub async fn decide_and_apply_human(sqlx::query("SET LOCAL lock_timeout = '2s'").execute(&mut *tx).await?;- let written = write_decision_and_projection(- &mut tx,- kb_id,- kind_word,- &[],- type_id,- if type_id.is_some() { "bound" } else { "none" },- votes,- "person",- None,- )- .await?;+ let written = decide_and_apply_human_tx(&mut tx, kb_id, kind_word, type_id, votes).await?;if written {crate::jobs::enqueue_unless_queued_tx(&mut tx,@@ -474,20 +463,53 @@ pub async fn decide_and_apply_human("rolling back human kind-word decision: {rollback}"))));}- if matches!(&error, AppError::Db(sqlx::Error::Database(e))- if e.code().as_deref() == Some("55P03"))- {- return Err(AppError::CodedConflict {- code: "alignment_busy",- message: "This kind word is being updated by another operation. Please try again shortly."- .into(),- });- }- Err(error)+ Err(busy_on_lock_timeout(error))}}}+/// A person's decision and its entity projection, written as [`decide_and_apply_human`]+/// writes them but on the caller's transaction, so they commit or roll back with the+/// caller's other writes. The caller queues the phrase alignment the changed classes+/// need in the same transaction, and sets its own lock timeout and maps it with+/// [`busy_on_lock_timeout`].+pub async fn decide_and_apply_human_tx(+ tx: &mut Transaction<'_, Postgres>,+ kb_id: Uuid,+ kind_word: &str,+ type_id: Option<Uuid>,+ votes: &serde_json::Value,+) -> AppResult<bool> {+ write_decision_and_projection(+ tx,+ kb_id,+ kind_word,+ &[],+ type_id,+ if type_id.is_some() { "bound" } else { "none" },+ votes,+ "person",+ None,+ )+ .await+}++/// A lock wait that ran out (55P03 under `lock_timeout`) means another operation+/// is updating the kind word: answer the retryable 409 the review page knows.+pub fn busy_on_lock_timeout(error: AppError) -> AppError {+ if matches!(&error, AppError::Db(sqlx::Error::Database(e))+ if e.code().as_deref() == Some("55P03"))+ {+ return AppError::CodedConflict {+ code: "alignment_busy",+ message:+ "This kind word is being updated by another operation. Please try again shortly."+ .into(),+ };+ }+ error+}+#[allow(clippy::too_many_arguments)]async fn write_decision_and_projection(connection: &mut sqlx::PgConnection,diff --git a/docs/decisions/0061-the-ontology-is-proposed-from-the-open-graph-and-judged-by-its-questions.md b/docs/decisions/0061-the-ontology-is-proposed-from-the-open-graph-and-judged-by-its-questions.mdindex 9f66ca3d..219055dd 100644--- a/docs/decisions/0061-the-ontology-is-proposed-from-the-open-graph-and-judged-by-its-questions.md+++ b/docs/decisions/0061-the-ontology-is-proposed-from-the-open-graph-and-judged-by-its-questions.md@@ -1,6 +1,6 @@# 0061 · The ontology is proposed from the open graph and judged by its questions-- **Status**: In progress · accepted 2026-09-26 · cuts 1 and 1.1 built (#947, #950), cut 3 slices 1–2 (#955, #962) · open: cut 2, the rest of cut 3, cut 4+- **Status**: In progress · accepted 2026-09-26 · cuts 1 and 1.1 built (#947, #950), cut 3 slices 1–2 (#955, #962) · revised 2026-10-16 (#1257) · open: cut 2, the rest of cut 3, cut 4- **Written**: 2026-09-26 (conventions in the [README](README.md))- **Related**: [0044](0044-the-ontology-is-a-view-over-what-documents-say.md) §4 decided the workbench and named this cut; [0003](0003-ontology-growth-loop.md) grew the ontology from `ontology_misses` and surface predicates, which [0044](0044-the-ontology-is-a-view-over-what-documents-say.md) cut 1 left idle and #725 retires; [0012](0012-the-ontology-is-a-contract-not-a-suggestion.md) makes every element a contract a person signed, which this record keeps; [0053](0053-a-phrase-decision-records-the-inputs-it-considered.md) is what makes approval re-decide signatures without a new mechanism; [0008](0008-ontology-packs-as-cold-start.md) is the second of the three sources; [0043](0043-every-review-queue-is-governed.md) and #725 give the queue its shape. From #725's "Ontology proposals" row and 0044's open question about a base with no questions.@@ -18,6 +18,8 @@ The open graph holds statements with their phrases, quotes, kind words and names**3. Approval is an action that writes the ontology and re-decides the signatures.** Adopting a proposal creates or edits the element with its definition, domains and ranges: structure is part of approval [0044 §4], so a property arrives with the classes it joins, not as a bare label. The signatures the proposal named are then re-decided by alignment with no new mechanism: their basis changed, which is exactly what 0053 made re-decision mean. Edit-and-approve is the same path with the person's text. A signature a person decided stays as the person left it. Rejecting records the reason so the agent does not propose the same element again for the same signatures.+**Revision 2026-10-16 (adoption is one commit, #1257):** decision 3 did not say that adopting is one operation, and adoption committed the element, its alignment job and the adopted status separately, embedding the element inside the request; an attribute whose example statement has an entity object was committed before its regression case was refused, leaving an element no proposal adopted. Adopting now commits the element (for a reuse, the person's bindings), its regression cases, the adopted status and its follow-up jobs together or not at all, and makes no model call: like the editor, it queues `embed_ontology` ahead of alignment. Only adoption adopts; the status-only endpoint rejects.+**4. Every approved element carries regression cases.** The example statements that motivated a proposal become `ontology_regression_cases` on adoption: a statement and the property or class it is expected to bind to. A later edit to the element's definition, domains or ranges reruns alignment on exactly those signatures and records which cases still bind. A failing case is shown on the workbench beside the edit; it is not reverted for the person, because a definition may be tightened on purpose. A person can add a case from any statement ("this should bind here"), which is the "make a rule" action #725 names.**5. Two numbers measure the ontology.** Questions answered correctly: each accepted question is asked over the typed graph the way a person would ask it in chat, and the answer is judged against the expected answer where one is written, or against whether the shape it needs exists and holds facts. Proposals people change: the share of the agent's proposals rejected or edited before adoption. Both are reported per base and by the bench 0044's table names, FDA and statistics corpora with written questions.diff --git a/docs/design/ontology.md b/docs/design/ontology.mdindex 65fdaed6..0e1cfee9 100644--- a/docs/design/ontology.md+++ b/docs/design/ontology.md@@ -70,9 +70,9 @@ the ten properties nearest by the ontology's own vectors (`embed_ontology`) arelabel shares a word with the phrase; without an embedding model the model sees every structuralcandidate. A property without a vector never enters the shortlist, so the fingerprint of theshapes it could bind does not change and they are never re-decided: every path that adds or-relabels an element therefore refreshes the index before alignment. The ontology agent's adoption-refreshes it in place [0061 cut 1.1]; the editor's create and update handlers queue-`embed_ontology` ahead of the alignment job, and both aligners wait while that job is queued or+relabels an element therefore refreshes the index before alignment. The ontology agent's adoption,+like the editor's create and update handlers, queues `embed_ontology` ahead of the alignment job;+adoption queues both in the element's commit [0061]. Both aligners wait while that job is queued orrunning, so the order is vectors, then kind words, then phrases. The shortlist is part of thedecision's basis, so a changed list re-asks. The candidateproperties are described once per batch and each item names only its keys. A signature the votes disagree on is `undecided` for the alignment queue of #725; one with no