From c6b29ee3a2bbaf05bf2495716c2acc43e44676db Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Tue, 24 Nov 2026 02:12:33 +0000 Subject: [PATCH] =?UTF-8?q?feat(id):=20Notion=20importer=20slice=203=20?= =?UTF-8?q?=E2=80=94=20database=20note=20identity=20and=20per-source=20sch?= =?UTF-8?q?ema=20claims?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Database notes get assigned note IDs (Manifest::assign_database_identities, mirroring pages, with cross-kind uniqueness) and convert_database records each data source's schema as provenance claims on the database note, scoped by data_source_id so colliding property names/ids never merge. Adds the colliding Status property (status in source-alpha, select in source-beta) to the multi-source fixture and a recorded_databases integration test for design #6436 §8 check 8 (first half: identity + disjoint schema claims). Registers the new test file and the previously unwired recorded_content.rs in the suite registry. Refs #13523 --- .github/test-suite-registry.json | 6 +- pkgs/id/crates/id-import-notion/Cargo.toml | 2 +- .../crates/id-import-notion/src/databases.rs | 299 ++++++++++++++++++ pkgs/id/crates/id-import-notion/src/lib.rs | 61 +++- .../tests/fixtures/data_sources.json | 12 +- .../tests/recorded_databases.rs | 120 +++++++ 6 files changed, 495 insertions(+), 5 deletions(-) create mode 100644 pkgs/id/crates/id-import-notion/src/databases.rs create mode 100644 pkgs/id/crates/id-import-notion/tests/recorded_databases.rs diff --git a/.github/test-suite-registry.json b/.github/test-suite-registry.json index d1a4258f91..db340fda1b 100644 --- a/.github/test-suite-registry.json +++ b/.github/test-suite-registry.json @@ -1605,7 +1605,11 @@ }, { "id": "id.rust.id-import-notion.integration", - "paths": ["pkgs/id/crates/id-import-notion/tests/recorded_inventory.rs"], + "paths": [ + "pkgs/id/crates/id-import-notion/tests/recorded_inventory.rs", + "pkgs/id/crates/id-import-notion/tests/recorded_content.rs", + "pkgs/id/crates/id-import-notion/tests/recorded_databases.rs" + ], "invocation": "nix flake check ./pkgs/id (check test-sandbox runs cargo nextest --all-features for default workspace members)", "venue": { "workflow": ".github/workflows/id-check.yml", diff --git a/pkgs/id/crates/id-import-notion/Cargo.toml b/pkgs/id/crates/id-import-notion/Cargo.toml index 58e46a1cb6..0fded4da89 100644 --- a/pkgs/id/crates/id-import-notion/Cargo.toml +++ b/pkgs/id/crates/id-import-notion/Cargo.toml @@ -3,7 +3,7 @@ name = "id-import-notion" version = "0.1.0" edition = "2024" rust-version = "1.96" -description = "Notion importer manifest, inventory, and page/block conversion primitives (slices 1-2, #8419/#13522)" +description = "Notion importer manifest, inventory, page/block conversion, and database schema-claim primitives (slices 1-3, #8419/#13522/#13523)" license = "MIT OR Apache-2.0" [dependencies] diff --git a/pkgs/id/crates/id-import-notion/src/databases.rs b/pkgs/id/crates/id-import-notion/src/databases.rs new file mode 100644 index 0000000000..c1bfeeacc3 --- /dev/null +++ b/pkgs/id/crates/id-import-notion/src/databases.rs @@ -0,0 +1,299 @@ +//! Database notes and per-data-source schema claims, slice 3 (#13523). +//! +//! Converts inventoried databases to the §2.2 form: one note per database, +//! with each of its data sources' schemas recorded as provenance claims +//! on the database note, scoped by `data_source_id` so two sources' claims +//! are never merged — even where property names (or property ids) collide. +//! +//! This slice covers database-note identity and schema claims only. +//! Row notes, relations as typed references, rollups/formulas, and system +//! properties are follow-up slices on the same issue; they build on the +//! identities assigned here. Resolving `child_database` references to +//! their database note ids (left as `None` by slice 2's [`crate::content`]) +//! is the next slice after this one. + +use std::collections::BTreeSet; + +use anyhow::{Context, Result, bail}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +use crate::{Manifest, Outcome, Stage}; + +/// One per-data-source schema provenance claim on a database note (§2.2). +/// +/// The claim identity is (`data_source_id`, `property_id`): the same +/// property name or id in another source of the same database is a +/// different claim, never a merged one. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct SchemaClaim { + pub data_source_id: String, + pub property_id: String, + pub property_name: String, + pub property_type: String, + /// The verbatim property schema object from the data source. + pub definition: Value, +} + +/// The result of converting one inventoried database (§2.2): its note +/// identity plus one schema claim per property of each of its data +/// sources, in source-id then property-name order. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] +pub struct DatabaseConversion { + pub database_id: String, + pub note_id: String, + pub schema_claims: Vec, +} + +/// Convert one inventoried database to its §2.2 form, advancing its +/// manifest checkpoint to [`Stage::Content`]. +/// +/// The caller must have run [`Manifest::assign_database_identities`] +/// first (the §3 two-pass rule, as for pages); converting a database +/// with no assigned note ID fails rather than minting identity +/// mid-content. Conversion is safe to re-run: identities already +/// recorded are kept, and progress never rewinds (§6.3). +pub fn convert_database( + manifest: &mut Manifest, + database_id: &str, +) -> Result { + let object = manifest + .inventory + .objects + .get(database_id) + .with_context(|| format!("database {database_id} is not in the inventory"))?; + if object.kind != "database" { + bail!( + "inventory object {database_id} is a {}, not a database", + object.kind + ); + } + let note_id = manifest + .database_id_to_note_id + .get(database_id) + .with_context(|| { + format!( + "database {database_id} has no assigned note id; run assign_database_identities first" + ) + })? + .clone(); + let sources = manifest + .inventory + .data_sources + .get(database_id) + .with_context(|| format!("database {database_id} has no enumerated data sources"))?; + if sources.is_empty() { + bail!("database {database_id} has no data sources"); + } + let mut schema_claims = Vec::new(); + for source in sources { + let properties = source + .source + .get("properties") + .and_then(Value::as_object) + .with_context(|| format!("data source {} has no properties object", source.id))?; + let mut seen_property_ids = BTreeSet::new(); + let mut entries: Vec<(&String, &Value)> = properties.iter().collect(); + entries.sort_by(|left, right| left.0.cmp(right.0)); + for (name, definition) in entries { + let property_id = definition + .get("id") + .and_then(Value::as_str) + .with_context(|| { + format!("data source {} property {name} is missing its id", source.id) + })? + .to_owned(); + let property_type = definition + .get("type") + .and_then(Value::as_str) + .with_context(|| { + format!( + "data source {} property {name} is missing its type", + source.id + ) + })? + .to_owned(); + if !seen_property_ids.insert(property_id.clone()) { + bail!( + "data source {} repeats property id {property_id}", + source.id + ); + } + schema_claims.push(SchemaClaim { + data_source_id: source.id.clone(), + property_id, + property_name: name.clone(), + property_type, + definition: definition.clone(), + }); + } + } + advance(manifest, database_id, Stage::Content, Outcome::Clean, None)?; + Ok(DatabaseConversion { + database_id: database_id.to_owned(), + note_id, + schema_claims, + }) +} + +/// Record staged progress without rewinding it (§6.3): re-converting a +/// database whose checkpoint already sits at a later stage refreshes +/// the conversion artifacts but leaves the checkpoint alone. +fn advance( + manifest: &mut Manifest, + object_id: &str, + stage: Stage, + outcome: Outcome, + reason: Option, +) -> Result<()> { + let rank = |value: &Stage| match value { + Stage::Inventory => 0, + Stage::Files => 1, + Stage::Content => 2, + Stage::References => 3, + Stage::Report => 4, + }; + let current = manifest + .objects + .get(object_id) + .with_context(|| format!("object {object_id} is not in the manifest inventory"))?; + if rank(&stage) >= rank(¤t.stage) { + manifest.record_progress(object_id, stage, outcome, reason)?; + } + Ok(()) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used)] +mod tests { + use super::*; + use crate::{Inventory, NOTION_API_VERSION}; + use serde_json::json; + use std::collections::BTreeMap; + + fn manifest_for(sources: Vec) -> Manifest { + let database = json!({ + "object": "database", + "id": "db-1", + "parent": {"type": "workspace", "workspace": true}, + "data_sources": sources.iter().map(|source| { + json!({"id": source["id"].as_str().unwrap()}) + }).collect::>(), + }); + let mut by_database = BTreeMap::new(); + by_database.insert("db-1".into(), sources); + let inventory = Inventory::from_recorded_responses( + &[json!({"object":"list","results":[database],"has_more":false})], + &by_database, + vec!["db-1".into()], + BTreeMap::new(), + None, + ) + .unwrap(); + Manifest::new( + "workspace-1".into(), + vec!["api".into()], + NOTION_API_VERSION.into(), + inventory, + ) + .unwrap() + } + + fn source(id: &str, properties: Value) -> Value { + json!({ + "object": "data_source", + "id": id, + "parent": {"type": "database_id", "database_id": "db-1"}, + "properties": properties, + }) + } + + #[test] + fn unassigned_database_note_id_fails_closed() { + let mut manifest = manifest_for(vec![source( + "ds-1", + json!({"Name": {"id": "title", "type": "title", "title": {}}}), + )]); + let err = convert_database(&mut manifest, "db-1").unwrap_err(); + assert!(err.to_string().contains("no assigned note id"), "{err:#}"); + } + + #[test] + fn converting_a_page_as_a_database_fails_closed() { + let inventory = Inventory::from_recorded_responses( + &[json!({"object":"list","results":[{"object":"page","id":"p-1"}],"has_more":false})], + &BTreeMap::new(), + vec!["p-1".into()], + BTreeMap::from([("p-1".into(), false)]), + None, + ) + .unwrap(); + let mut manifest = Manifest::new( + "workspace-1".into(), + vec!["api".into()], + NOTION_API_VERSION.into(), + inventory, + ) + .unwrap(); + let err = convert_database(&mut manifest, "p-1").unwrap_err(); + assert!(err.to_string().contains("not a database"), "{err:#}"); + } + + #[test] + fn property_without_type_fails_closed() { + let mut manifest = manifest_for(vec![source( + "ds-1", + json!({"Name": {"id": "title"}}), + )]); + manifest + .assign_database_identities(&mut |id| Ok(format!("note-{id}"))) + .unwrap(); + let err = convert_database(&mut manifest, "db-1").unwrap_err(); + assert!(err.to_string().contains("missing its type"), "{err:#}"); + } + + #[test] + fn source_without_properties_fails_closed() { + let mut source = source("ds-1", json!({})); + source.as_object_mut().unwrap().remove("properties"); + let mut manifest = manifest_for(vec![source]); + manifest + .assign_database_identities(&mut |id| Ok(format!("note-{id}"))) + .unwrap(); + let err = convert_database(&mut manifest, "db-1").unwrap_err(); + assert!( + err.to_string().contains("no properties object"), + "{err:#}" + ); + } + + #[test] + fn same_property_id_in_two_sources_stays_two_claims() { + let mut manifest = manifest_for(vec![ + source( + "ds-a", + json!({"Status": {"id": "status", "type": "status", "status": {}}}), + ), + source( + "ds-b", + json!({"Status": {"id": "status", "type": "select", "select": {"options": []}}}), + ), + ]); + manifest + .assign_database_identities(&mut |id| Ok(format!("note-{id}"))) + .unwrap(); + let conversion = convert_database(&mut manifest, "db-1").unwrap(); + assert_eq!(conversion.schema_claims.len(), 2); + assert_eq!( + conversion.schema_claims[0], + SchemaClaim { + data_source_id: "ds-a".into(), + property_id: "status".into(), + property_name: "Status".into(), + property_type: "status".into(), + definition: json!({"id": "status", "type": "status", "status": {}}), + } + ); + assert_eq!(conversion.schema_claims[1].property_type, "select"); + } +} diff --git a/pkgs/id/crates/id-import-notion/src/lib.rs b/pkgs/id/crates/id-import-notion/src/lib.rs index 5b35344fa3..881afbb782 100644 --- a/pkgs/id/crates/id-import-notion/src/lib.rs +++ b/pkgs/id/crates/id-import-notion/src/lib.rs @@ -4,8 +4,11 @@ //! bearer token is never accepted by or serialized from [`Manifest`]. //! //! Slice 2 (page/block core, link rewriting, files) lives in [`content`]. +//! Slice 3 (databases: note identity and per-data-source schema claims) +//! lives in [`databases`]. pub mod content; +pub mod databases; #[cfg(unix)] use std::fs::File; @@ -563,6 +566,11 @@ pub struct Manifest { pub inventory: Inventory, /// Stable Notion page UUID -> destination note UUID. pub page_id_to_note_id: BTreeMap, + /// Stable Notion database UUID -> destination note UUID. Assigned by + /// [`Manifest::assign_database_identities`]; absent from slice-1/2 + /// manifests, so it defaults empty when an older manifest is loaded. + #[serde(default)] + pub database_id_to_note_id: BTreeMap, /// Stable Notion block UUID -> (destination note UUID, block identity). pub block_id_to_identity: BTreeMap, /// Stable data-source UUID -> (current database UUID, source identity). @@ -628,6 +636,7 @@ impl Manifest { .collect(), inventory, page_id_to_note_id: BTreeMap::new(), + database_id_to_note_id: BTreeMap::new(), block_id_to_identity: BTreeMap::new(), data_source_id_to_identity, file_blobs: BTreeMap::new(), @@ -652,8 +661,12 @@ impl Manifest { .filter(|object| object.kind == "page") .map(|object| object.id.clone()) .collect(); - let mut taken: std::collections::BTreeSet = - self.page_id_to_note_id.values().cloned().collect(); + let mut taken: std::collections::BTreeSet = self + .page_id_to_note_id + .values() + .cloned() + .chain(self.database_id_to_note_id.values().cloned()) + .collect(); let mut assigned = 0; for page_id in page_ids { if self.page_id_to_note_id.contains_key(&page_id) { @@ -673,6 +686,50 @@ impl Manifest { Ok(assigned) } + /// Assign a destination note ID to every inventoried database that + /// lacks one (design §2.2: one note per database; §3: identity is + /// assigned for the whole inventory before any content converts, so + /// forward references resolve). Mirrors + /// [`Manifest::assign_page_identities`]: assignments already recorded + /// are never changed, and a minter that returns an empty or + /// already-used ID fails the pass rather than forking identity. + /// Returns how many databases were newly assigned. + pub fn assign_database_identities( + &mut self, + mint: &mut dyn FnMut(&str) -> Result, + ) -> Result { + let database_ids: Vec = self + .inventory + .objects + .values() + .filter(|object| object.kind == "database") + .map(|object| object.id.clone()) + .collect(); + let mut taken: std::collections::BTreeSet = self + .database_id_to_note_id + .values() + .cloned() + .chain(self.page_id_to_note_id.values().cloned()) + .collect(); + let mut assigned = 0; + for database_id in database_ids { + if self.database_id_to_note_id.contains_key(&database_id) { + continue; + } + let note_id = mint(&database_id) + .with_context(|| format!("mint note id for database {database_id}"))?; + if note_id.trim().is_empty() { + bail!("note id minter returned an empty id for database {database_id}"); + } + if !taken.insert(note_id.clone()) { + bail!("note id minter returned duplicate id {note_id}"); + } + self.database_id_to_note_id.insert(database_id, note_id); + assigned += 1; + } + Ok(assigned) + } + /// Reject resume against another workspace before callers create objects. pub fn verify_resume_identity(&self, workspace_id: &str, notion_version: &str) -> Result<()> { if self.workspace_id != workspace_id { diff --git a/pkgs/id/crates/id-import-notion/tests/fixtures/data_sources.json b/pkgs/id/crates/id-import-notion/tests/fixtures/data_sources.json index 2ca7eb38f5..edc69381d2 100644 --- a/pkgs/id/crates/id-import-notion/tests/fixtures/data_sources.json +++ b/pkgs/id/crates/id-import-notion/tests/fixtures/data_sources.json @@ -16,7 +16,17 @@ "parent": { "type": "database_id", "database_id": "db-alpha" }, "properties": { "Name": { "id": "title", "type": "title", "title": {} }, - "Archived": { "id": "checkbox", "type": "checkbox", "checkbox": {} } + "Archived": { "id": "checkbox", "type": "checkbox", "checkbox": {} }, + "Status": { + "id": "status", + "type": "select", + "select": { + "options": [ + { "name": "Open", "color": "green" }, + { "name": "Done", "color": "gray" } + ] + } + } } } ], diff --git a/pkgs/id/crates/id-import-notion/tests/recorded_databases.rs b/pkgs/id/crates/id-import-notion/tests/recorded_databases.rs new file mode 100644 index 0000000000..177ad38c54 --- /dev/null +++ b/pkgs/id/crates/id-import-notion/tests/recorded_databases.rs @@ -0,0 +1,120 @@ +use std::collections::{BTreeMap, BTreeSet}; + +use id_import_notion::{ + Inventory, Manifest, Stage, NOTION_API_VERSION, databases::convert_database, +}; +use tempfile::tempdir; + +/// Design §8 check 8, first half: the multi-source fixture database +/// (db-alpha, sources alpha + beta) converts to one database note whose +/// schema claims are disjoint per data source. The oracle is the +/// recorded fixture: source-alpha carries Status as `status`, source-beta +/// carries the same property name as `select`, both under property id +/// `status` — so any implementation that keys claims by property id or +/// name alone merges them and fails this test. +#[test] +fn recorded_multi_source_database_yields_disjoint_schema_claims() { + let search: serde_json::Value = + serde_json::from_str(include_str!("fixtures/search.json")).unwrap(); + let data_sources: serde_json::Value = + serde_json::from_str(include_str!("fixtures/data_sources.json")).unwrap(); + let database: serde_json::Value = + serde_json::from_str(include_str!("fixtures/database.json")).unwrap(); + let sources = data_sources["results"].as_array().unwrap().clone(); + let inventory = Inventory::from_recorded_responses( + &[ + search, + serde_json::json!({"object":"list","results":[database],"has_more":false}), + ], + &BTreeMap::from([("db-alpha".into(), sources)]), + vec!["db-alpha".into(), "page-root".into()], + BTreeMap::from([("page-root".into(), true)]), + Some("business".into()), + ) + .unwrap(); + let mut manifest = Manifest::new( + "workspace-alpha".into(), + vec!["api".into()], + NOTION_API_VERSION.into(), + inventory, + ) + .unwrap(); + + let assigned = manifest + .assign_database_identities(&mut |database_id| Ok(format!("note-{database_id}"))) + .unwrap(); + assert_eq!(assigned, 1); + assert_eq!( + manifest.database_id_to_note_id["db-alpha"], "note-db-alpha" + ); + + let conversion = convert_database(&mut manifest, "db-alpha").unwrap(); + assert_eq!(conversion.database_id, "db-alpha"); + assert_eq!(conversion.note_id, "note-db-alpha"); + + // (a) The manifest records both data_source_ids under the one + // database note: both sources enumerate under db-alpha. + assert_eq!(manifest.inventory.data_sources["db-alpha"].len(), 2); + let claimed_sources: BTreeSet<&str> = conversion + .schema_claims + .iter() + .map(|claim| claim.data_source_id.as_str()) + .collect(); + assert_eq!(claimed_sources, BTreeSet::from(["source-alpha", "source-beta"])); + + // (b) The colliding property name appears once per source, with each + // source's type — the claims are disjoint, never merged. + let status: Vec<_> = conversion + .schema_claims + .iter() + .filter(|claim| claim.property_name == "Status") + .collect(); + assert_eq!(status.len(), 2); + assert!( + status + .iter() + .any(|claim| claim.data_source_id == "source-alpha" + && claim.property_type == "status"), + "source-alpha Status claim: {status:?}" + ); + assert!( + status + .iter() + .any(|claim| claim.data_source_id == "source-beta" + && claim.property_type == "select"), + "source-beta Status claim: {status:?}" + ); + // Same property id in both sources stays two claims: the claim + // identity is (data_source_id, property_id). + let status_keys: BTreeSet<(&str, &str)> = status + .iter() + .map(|claim| (claim.data_source_id.as_str(), claim.property_id.as_str())) + .collect(); + assert_eq!(status_keys.len(), 2); + + // Every claim key is unique and every definition round-trips its type. + let keys: BTreeSet<(&str, &str)> = conversion + .schema_claims + .iter() + .map(|claim| (claim.data_source_id.as_str(), claim.property_id.as_str())) + .collect(); + assert_eq!(keys.len(), conversion.schema_claims.len()); + assert_eq!(conversion.schema_claims.len(), 5); + for claim in &conversion.schema_claims { + assert_eq!( + claim.definition["type"].as_str(), + Some(claim.property_type.as_str()), + "claim definition must round-trip its type: {claim:?}" + ); + } + + // Conversion advances the database checkpoint to Content, and the + // new identity map survives a manifest round-trip. + assert_eq!(manifest.objects["db-alpha"].stage, Stage::Content); + let dir = tempdir().unwrap(); + let path = dir.path().join("manifest.json"); + manifest.save_atomic(&path).unwrap(); + let loaded = Manifest::load(&path).unwrap(); + assert_eq!(loaded.database_id_to_note_id["db-alpha"], "note-db-alpha"); + assert_eq!(loaded, manifest); +}