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
4 changes: 2 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions crates/utopia-core/src/models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -685,6 +685,8 @@ pub struct StatementQualifier {
pub value: Option<serde_json::Value>,
pub entity_id: Option<Uuid>,
pub entity_name: Option<String>,
/// 说这个值的那几块(0070):两块活着的块说法不同,各自一条
pub chunk_ids: Vec<Uuid>,
}

/// 一次 OWL 导入的记录。原文按内容寻址存在 blob 里,这行只是账。
Expand Down
60 changes: 56 additions & 4 deletions crates/utopia-reason/src/rules.rs
Original file line number Diff line number Diff line change
Expand Up @@ -670,15 +670,13 @@ fn satisfies(c: &Condition, value: &serde_json::Value, bound: &HashMap<Uuid, &At
match (&c.op, &c.operand) {
(Op::Present, _) => !value.is_null(),
// 值不在集合里就算满足;**没有值不算**——那是「没记」,不是「不是它」
(Op::NotIn, Operand::Set(set)) => {
!value.is_null() && text(value).is_some_and(|v| !set.iter().any(|s| s == &v))
}
(Op::NotIn, Operand::Set(set)) => !value.is_null() && in_set(value, set) == Some(false),
(Op::Gt, Operand::Num(n)) => num(value).is_some_and(|v| v > *n),
(Op::Gte, Operand::Num(n)) => num(value).is_some_and(|v| v >= *n),
(Op::Lt, Operand::Num(n)) => num(value).is_some_and(|v| v < *n),
(Op::Lte, Operand::Num(n)) => num(value).is_some_and(|v| v <= *n),
(Op::Between, Operand::Range(lo, hi)) => num(value).is_some_and(|v| v >= *lo && v <= *hi),
(Op::In, Operand::Set(set)) => text(value).is_some_and(|s| set.iter().any(|x| x == &s)),
(Op::In, Operand::Set(set)) => in_set(value, set) == Some(true),
// op 与操作数形状对不上:库里的 CHECK 挡了大部分,剩下的当不满足
_ => false,
}
Expand All @@ -695,6 +693,23 @@ fn num(v: &serde_json::Value) -> Option<f64> {
}
}

/// 集合成员(0029)。读数与集合里的一项都读得出数时按数比:数值属性存成 f64,
/// 读回来是 `3.0`,集合里写的是 `3`;写成 `[3.0]` 的集合存的又是 "3.0"。按字比
/// 两头总有一头对不上。别的照旧按字面比。读数连字面都没有时是 `None`
fn in_set(value: &serde_json::Value, set: &[String]) -> Option<bool> {
let v = text(value)?;
let n = match value {
serde_json::Value::Number(n) => n.as_f64(),
serde_json::Value::String(s) => s.trim().parse::<f64>().ok(),
_ => None,
}
.filter(|n| n.is_finite());
Some(
set.iter()
.any(|x| x == &v || n.is_some_and(|n| x.trim().parse::<f64>().is_ok_and(|x| x == n))),
)
}

/// 类别。数字与布尔也转成字面形态参与集合比较,理由同上。
fn text(v: &serde_json::Value) -> Option<String> {
match v {
Expand Down Expand Up @@ -1148,6 +1163,43 @@ mod tests {
assert_eq!(hits.len(), 1);
}

/// 数值属性的读数存成 f64:`3` 存进去读出来是 `3.0`,「属于 {3}」照样要命中
#[test]
fn a_stored_number_is_one_of_the_numbers_in_the_set() {
let rule = BusinessRule {
id: id(90),
join_predicate: None,
conclusion: Conclusion::Typing {
class: "Grade3".into(),
},
conditions: vec![Condition {
group: 0,
side: Side::X,
predicate: id(10),
op: Op::In,
operand: Operand::Set(vec!["3".into()]),
}],
};
let facts = vec![fact(1, 50, 10, json!(3.0))];
let spans = HashMap::from([(id(1), (None, None))]);
let (hits, _) = evaluate(std::slice::from_ref(&rule), &facts, &spans, &[]);
assert_eq!(hits.len(), 1);
// `parse_operand` 把 `[3.0]` 存成 "3.0":读数 3.0 仍在其中,整数 3 也在其中
let mut rule = rule;
rule.conditions[0].operand = Operand::Set(vec!["3.0".into()]);
let facts = vec![fact(1, 50, 10, json!(3.0))];
let (hits, _) = evaluate(std::slice::from_ref(&rule), &facts, &spans, &[]);
assert_eq!(hits.len(), 1);
let facts = vec![fact(1, 50, 10, json!(3))];
let (hits, _) = evaluate(std::slice::from_ref(&rule), &facts, &spans, &[]);
assert_eq!(hits.len(), 1);
// 不是数的照旧按字面比
rule.conditions[0].operand = Operand::Set(vec!["3".into()]);
let facts = vec![fact(1, 50, 10, json!("三"))];
let (hits, _) = evaluate(&[rule], &facts, &spans, &[]);
assert!(hits.is_empty());
}

/// 阈值抬高到读数之上,同一份数据就不再命中——降/升阈值重跑是 0021 的验收项
#[test]
fn raising_the_threshold_clears_the_hit() {
Expand Down
8 changes: 1 addition & 7 deletions crates/utopia-server/src/api/google_drive_routes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -469,13 +469,7 @@ pub async fn select(
)
.await?;
if !body.folders.is_empty() {
let _ = utopia_store::sources::mark_queued(&state.pool, source_id).await;
utopia_store::jobs::enqueue(
&state.pool,
"sync_source",
json!({ "source_id": source_id }),
)
.await?;
utopia_store::sources::enqueue_sync_after_config_change(&state.pool, source_id).await?;
}
state.emit_source(kb_id);
let _ = utopia_store::audit::record(
Expand Down
121 changes: 121 additions & 0 deletions crates/utopia-server/src/api/google_drive_routes_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@
//! 测试环境没配 OAuth 客户端:过了所有关卡的回调停在「没配置」,不会去敲 Google
use super::*;
use crate::auth::SessionOrToken;
use axum::body::{to_bytes, Body};
use axum::http::{Request, StatusCode};
use std::sync::Arc;
use tower::ServiceExt;
use utopia_core::models::User;

struct Fixture {
Expand Down Expand Up @@ -115,6 +118,124 @@ impl Fixture {
.await?
.config)
}

async fn sync_http(&self) -> anyhow::Result<(StatusCode, Value)> {
let token = crate::auth::issue_token(&self.state, self.connector.id)?;
let response = super::super::router(self.state.clone(), &Default::default())
.oneshot(
Request::post(format!(
"/api/v1/kbs/{}/sources/{}/sync",
self.kb, self.source
))
.header("Authorization", format!("Bearer {token}"))
.body(Body::empty())?,
)
.await?;
let status = response.status();
let bytes = to_bytes(response.into_body(), 1 << 20).await?;
Ok((status, serde_json::from_slice(&bytes)?))
}

async fn sync_state(&self) -> anyhow::Result<(String, i64)> {
Ok(sqlx::query_as(
"SELECT last_sync_status,
(SELECT count(*) FROM jobs WHERE kind = 'sync_source'
AND payload->>'source_id' = sources.id::text)
FROM sources WHERE id = $1",
)
.bind(self.source)
.fetch_one(&self.pool)
.await?)
}

async fn choose_folder(&self, id: &str) -> ApiResult<Json<Value>> {
select(
State(self.state.clone()),
AuthUser(self.connector.clone()),
Path((self.kb, self.source)),
Json(SelectBody {
folders: vec![FolderEntry {
id: id.into(),
name: id.into(),
}],
}),
)
.await
}

async fn reject_sync_jobs(&self, reject: bool) -> anyhow::Result<()> {
// 名称和拒绝条件都限定到本测试的来源,清理不会删除其他测试的注入器。
let guard = format!("test_reject_source_sync_{}", self.source.simple());
let sql = if reject {
format!(
"CREATE FUNCTION {guard}() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN
IF NEW.kind = 'sync_source' AND NEW.payload->>'source_id' = '{}'
THEN RAISE EXCEPTION 'test source sync insert failure'; END IF;
RETURN NEW; END $$;
CREATE TRIGGER {guard} BEFORE INSERT ON jobs
FOR EACH ROW EXECUTE FUNCTION {guard}();",
self.source
)
} else {
format!("DROP TRIGGER IF EXISTS {guard} ON jobs; DROP FUNCTION IF EXISTS {guard}();")
};
sqlx::raw_sql(&sql).execute(&self.pool).await?;
Ok(())
}
}

#[tokio::test]
async fn source_sync_enqueue_manual_failure_rolls_back_and_can_retry() -> anyhow::Result<()> {
let Some(fx) = Fixture::new().await? else {
return Ok(());
};
fx.reject_sync_jobs(true).await?;
// 检查失败也先清理触发器,避免把故障注入留在共享测试库里。
let result = async {
let (status, body) = fx.sync_http().await?;
anyhow::ensure!(status == StatusCode::INTERNAL_SERVER_ERROR, "{body}");
let state = fx.sync_state().await?;
anyhow::ensure!(state == ("never".into(), 0), "{state:?}");
Ok::<(), anyhow::Error>(())
}
.await;
fx.reject_sync_jobs(false).await?;
result?;

let (status, body) = fx.sync_http().await?;
assert_eq!(status, StatusCode::OK, "{body}");
assert_eq!(body["queued"], true);
assert_eq!(fx.sync_state().await?, ("queued".into(), 1));
Ok(())
}

#[tokio::test]
async fn source_sync_enqueue_drive_failure_keeps_config_but_rolls_back_queue() -> anyhow::Result<()>
{
let Some(fx) = Fixture::new().await? else {
return Ok(());
};
fx.reject_sync_jobs(true).await?;
let result = async {
anyhow::ensure!(matches!(
fx.choose_folder("saved-folder").await,
Err(ApiErr(AppError::Db(_)))
));
anyhow::ensure!(fx.config().await?["folders"][0]["id"] == "saved-folder");
let state = fx.sync_state().await?;
anyhow::ensure!(state == ("never".into(), 0), "{state:?}");
Ok::<(), anyhow::Error>(())
}
.await;
fx.reject_sync_jobs(false).await?;
result?;

let _ = fx
.choose_folder("saved-folder")
.await
.map_err(|ApiErr(error)| error)?;
assert_eq!(fx.sync_state().await?, ("queued".into(), 1));
Ok(())
}

fn denied_code<T>(result: ApiResult<T>) -> Option<&'static str> {
Expand Down
3 changes: 2 additions & 1 deletion crates/utopia-server/src/api/mcp_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1028,7 +1028,8 @@ async fn entity_facts_reads_back_a_statements_role_words() -> anyhow::Result<()>
.unwrap();
assert_eq!(
fact["statement_qualifiers"],
json!([{"role":"lines","value":{"value":"10-42"},"entity_id":null,"entity_name":null}])
json!([{"role":"lines","value":{"value":"10-42"},"entity_id":null,"entity_name":null,
"chunk_ids":[f.chunk]}])
);
f.clean().await
}
Expand Down
16 changes: 2 additions & 14 deletions crates/utopia-server/src/api/sources_routes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -155,13 +155,7 @@ pub async fn create(
.await?;
// 拉取型来源建好立即同步一次(有配置即产出,无需等下一个调度周期)
if matches!(source.kind.as_str(), "url" | "rss" | "custom") {
let _ = utopia_store::sources::mark_queued(&state.pool, source.id).await;
utopia_store::jobs::enqueue(
&state.pool,
"sync_source",
json!({ "source_id": source.id }),
)
.await?;
utopia_store::sources::enqueue_sync(&state.pool, source.id).await?;
}
// api 来源:生成专属推送密钥(此后可随时经 get_token 查看)
let mut ingest_token: Option<String> = None;
Expand Down Expand Up @@ -484,14 +478,8 @@ pub async fn sync_now(
) -> ApiResult<Json<serde_json::Value>> {
require_kb(&state, &user, kb_id, Role::Editor).await?;
source_in_kb(&state, kb_id, source_id).await?;
let queued = utopia_store::sources::mark_queued(&state.pool, source_id).await?;
let queued = utopia_store::sources::enqueue_sync(&state.pool, source_id).await?;
if queued {
utopia_store::jobs::enqueue(
&state.pool,
"sync_source",
json!({ "source_id": source_id }),
)
.await?;
state.emit_source(kb_id);
}
Ok(Json(json!({ "queued": queued })))
Expand Down
36 changes: 36 additions & 0 deletions crates/utopia-server/src/api/sources_statements_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -437,6 +437,42 @@ async fn a_second_push_under_the_same_identity_updates_in_place() -> anyhow::Res
f.cleanup().await
}

/// 0070 的例子:再推一次把 `lines` 从 40-52 改成 58-70,读回来只有新的范围
#[tokio::test]
async fn a_re_push_that_moves_lines_to_58_70_reads_back_only_58_70() -> anyhow::Result<()> {
let Some(f) = Fixture::new().await? else {
return Ok(());
};
for lines in ["40-52", "58-70"] {
let mut body = observation("08:14:03", "kitchen table");
body["s"][0][5] = json!({ "lines": lines });
let (status, body) = f.push(f.source, &f.token, &body).await?;
assert_eq!(status, StatusCode::OK, "{body}");
let doc = documents::find_by_external_key(&f.pool, f.source, "statements:obs-000412")
.await?
.expect("the push has a document");
crate::pipeline::process_document(&f.state, doc.id).await?;
let proposer = Proposer {
user_id: None,
token_id: None,
};
crate::extraction::extract_document(&f.state, doc.id, proposer).await?;
}
let (cup,): (Uuid,) =
sqlx::query_as("SELECT id FROM entities WHERE kb_id = $1 AND canonical_name = 'cup-7'")
.bind(f.kb)
.fetch_one(&f.pool)
.await?;
let (_, facts) = utopia_store::graph::entity_detail(&f.pool, f.kb, cup, None, None).await?;
let said: Vec<_> = facts
.iter()
.flat_map(|x| &x.statement_qualifiers)
.map(|q| (q.role.as_str(), q.value.clone()))
.collect();
assert_eq!(said, vec![("lines", Some(json!("58-70")))]);
f.cleanup().await
}

/// 门口的拒绝走到 HTTP 是 422(`AppError::Validation`,与 `api` 推送被拒时同一个码),
/// 并且这次推送留在 run 历史里;`api` 来源不认这条路由(404),钥匙不对是 401
#[tokio::test]
Expand Down
18 changes: 4 additions & 14 deletions crates/utopia-server/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -234,20 +234,10 @@ async fn main() -> anyhow::Result<()> {
match utopia_store::sources::due_sources(&sched_state.pool).await {
Ok(due) => {
for s in due {
match utopia_store::sources::mark_queued(&sched_state.pool, s.id).await {
Ok(true) => {
if let Err(e) = utopia_store::jobs::enqueue(
&sched_state.pool,
"sync_source",
serde_json::json!({ "source_id": s.id }),
)
.await
{
tracing::warn!(source_id = %s.id, error = %e, "同步任务入队失败");
}
}
Ok(false) => {}
Err(e) => tracing::warn!(source_id = %s.id, error = %e, "标记入队失败"),
if let Err(e) =
utopia_store::sources::enqueue_sync(&sched_state.pool, s.id).await
{
tracing::warn!(source_id = %s.id, error = %e, "同步任务入队失败");
}
}
}
Expand Down
Loading
Loading