From daaffe4101a52c19057d43ad4f1a0ec22f0a0759 Mon Sep 17 00:00:00 2001 From: Seongmin Lee Date: Wed, 28 Oct 2026 16:17:18 +0900 Subject: [PATCH] sh_org: seed multiple versions Signed-off-by: Seongmin Lee --- crates/sh_org/src/schema.sql | 9 +- crates/sh_org/src/seed.rs | 18 +++- crates/sh_org/src/store/accounts.rs | 4 +- crates/sh_org_knot_check/src/main.rs | 133 +++++++++++++++++---------- 4 files changed, 109 insertions(+), 55 deletions(-) diff --git a/crates/sh_org/src/schema.sql b/crates/sh_org/src/schema.sql index a41db16be..a31abc511 100644 --- a/crates/sh_org/src/schema.sql +++ b/crates/sh_org/src/schema.sql @@ -75,16 +75,15 @@ CREATE TABLE IF NOT EXISTS accounts ( note TEXT ); --- org records not seeded yet whose sh record still exists: only a ticket's latest version, --- and a ticket exists while its first version's issue or pull does. One view, so the --- queries deciding which accounts have work and the one reading it out agree. +-- org record versions not seeded yet whose sh record still exists: a ticket exists while its +-- first version's issue or pull does. One view, so the queries deciding which accounts have +-- work and the one reading it out agree. CREATE VIEW IF NOT EXISTS seedable AS SELECT m.id, m.org_uri, m.org_cid, m.org_record FROM migrated m JOIN migrated o ON o.id = (SELECT min(id) FROM migrated WHERE org_uri = m.org_uri) JOIN records r ON r.sh_uri = o.sh_uri -WHERE m.seeded = 0 AND r.state <> 'deleted' - AND m.id = (SELECT max(id) FROM migrated WHERE org_uri = m.org_uri); +WHERE m.seeded = 0 AND r.state <> 'deleted'; -- blobs the owner's host cannot serve otherwise: ones phase 2 made, and ones owned by an -- account other than the uploader. The liar PDS's getBlob falls back to the uploader's PDS. diff --git a/crates/sh_org/src/seed.rs b/crates/sh_org/src/seed.rs index b9a48bd4f..101d5c144 100644 --- a/crates/sh_org/src/seed.rs +++ b/crates/sh_org/src/seed.rs @@ -472,6 +472,12 @@ struct SeedRecord<'a> { record: &'a RawValue, } +#[derive(Deserialize)] +struct OwnCreatedAt { + #[serde(rename = "createdAt")] + created_at: Option, +} + #[derive(Deserialize)] struct Fostered { results: Vec, @@ -523,7 +529,17 @@ fn foster(store: &mut Store, session: &Session, did: &Did) -> anyhow::Result<()> ids.push(*id); continue; } - let created_at = created_at.as_deref().unwrap_or(&head.created_at); + // a copied definition keeps the original's createdAt, not its repo row's + let own = match collection.as_str() { + "org.tangled.label.definition" => { + serde_json::from_str::(&row.org_record)?.created_at + } + _ => None, + }; + let created_at = own + .as_deref() + .or(created_at.as_deref()) + .unwrap_or(&head.created_at); let created_at = match chrono::DateTime::parse_from_rfc3339(created_at) { Ok(stamp) => stamp.timestamp(), Err(error) => { diff --git a/crates/sh_org/src/store/accounts.rs b/crates/sh_org/src/store/accounts.rs index 246f00512..7718434ab 100644 --- a/crates/sh_org/src/store/accounts.rs +++ b/crates/sh_org/src/store/accounts.rs @@ -77,7 +77,7 @@ impl Store { .prepare_cached( "SELECT id, org_uri, org_cid, org_record FROM seedable WHERE org_uri >= 'at://' || ?1 || '/' AND org_uri < 'at://' || ?1 || '0' - ORDER BY org_uri LIMIT ?2", + ORDER BY org_uri, id LIMIT ?2", )? .query_map((did.as_str(), limit as i64), |row| { Ok(( @@ -131,7 +131,7 @@ impl Store { JOIN migrated m ON m.id = s.id LEFT JOIN records r ON r.sh_uri = m.sh_uri WHERE s.org_uri >= 'at://' || ?1 || '/' AND s.org_uri < 'at://' || ?1 || '0' - ORDER BY s.org_uri LIMIT ?2", + ORDER BY s.org_uri, s.id LIMIT ?2", )? .query_map((did.as_str(), limit as i64), |row| { Ok(( diff --git a/crates/sh_org_knot_check/src/main.rs b/crates/sh_org_knot_check/src/main.rs index 109b760f7..8a16c2921 100644 --- a/crates/sh_org_knot_check/src/main.rs +++ b/crates/sh_org_knot_check/src/main.rs @@ -145,8 +145,7 @@ fn rows(conn: &Connection, did: &str) -> anyhow::Result> { LEFT JOIN records r ON r.sh_uri = m.sh_uri WHERE m.org_uri >= 'at://' || ?1 || '/' AND m.org_uri < 'at://' || ?1 || '0' AND ro.state <> 'deleted' - AND m.id = (SELECT max(id) FROM migrated WHERE org_uri = m.org_uri) - ORDER BY m.org_uri", + ORDER BY m.org_uri, m.id", )? .query_map((did,), |row| { Ok(Row { @@ -178,14 +177,84 @@ impl Checker { repo: &RepoDid, head: &ManifestHead, labels: &BTreeSet, - row: &Row, + versions: &[Row], ) -> Result<(), Failure> { - let mut parts = row.org_uri.trim_start_matches("at://").splitn(3, '/'); + let tip = versions.last().expect("a record has a version"); + let mut parts = tip.org_uri.trim_start_matches("at://").splitn(3, '/'); let (_, collection, rkey) = (parts.next(), parts.next().unwrap_or(""), parts.next().unwrap_or("")); + let mut seeds: Vec<(serde_json::Value, SeedRecord, RecordBody)> = Vec::new(); + for row in versions { + let seeded = self.seeded(head, collection, rkey, row)?; + // knot-xrpc foster.rs seed_one skips a seed already standing + if seeds.last().is_none_or(|(_, _, last)| last.cid() != seeded.2.cid()) { + seeds.push(seeded); + } + } + let (_, first, first_body) = &seeds[0]; + let (record, seed, body) = seeds.last().expect("a record has a seed"); + let address = RecordAddress::new(seed.collection.clone(), seed.rkey.clone()); + let produces = body.cid(); + let edits: Vec<(Editing, RecordBody)> = seeds + .windows(2) + .map(|pair| { + let (_, seed, body) = &pair[1]; + let editing = Editing { + author: seed.author.clone(), + from: pair[0].2.cid(), + produces: body.cid(), + edited_at: seed.created_at, + }; + (editing, body.clone()) + }) + .collect(); + + let drafted = drafts::reencode(collection, rkey, repo, record, seed.created_at, &seed.author, labels); + let native = drafted.as_ref().ok().cloned().flatten(); + if let Some(native) = native.as_ref().filter(|native| native.cid() != produces) { + *self.reencoded.entry(collection.to_owned()).or_default() += 1; + if std::env::var_os("KNOTCHECK_DUMP").is_some() { + let native: ipld_core::ipld::Ipld = serde_ipld_dagcbor::from_slice(native.as_bytes()).expect("native cbor"); + let ours: ipld_core::ipld::Ipld = serde_ipld_dagcbor::from_slice(body.as_bytes()).expect("our cbor"); + eprintln!("REENCODE {}\n ours {ours:?}\n native {native:?}", tip.org_uri); + } + } + + let creation = Creation { + address, + author: first.author.clone(), + number: SubjectNumber::FIRST, + parent: None, + created_at: first.created_at, + produces: first_body.cid(), + }; + self.rotate(repo).map_err(|(reason, detail)| fail(collection, reason, detail))?; + let dir = &self.current.as_ref().expect("rotated").1; + let outcome = match collection { + knot_record::ticket::TICKET_COLLECTION => self.lifecycle::(&dir, repo, creation, first_body.clone(), edits, body.clone(), native), + knot_record::comment::COMMENT_COLLECTION => self.lifecycle::(&dir, repo, creation, first_body.clone(), edits, body.clone(), native), + knot_record::reaction::REACTION_COLLECTION => self.lifecycle::(&dir, repo, creation, first_body.clone(), edits, body.clone(), native), + knot_record::label::LABEL_DEF_COLLECTION => self.lifecycle::(&dir, repo, creation, first_body.clone(), edits, body.clone(), native), + knot_record::pull::PATCH_COLLECTION => self.lifecycle::(&dir, repo, creation, first_body.clone(), edits, body.clone(), native), + knot_record::artifact::ARTIFACT_COLLECTION => self.lifecycle::(&dir, repo, creation, first_body.clone(), edits, body.clone(), native), + _ => Err(("no lifecycle for collection", String::new())), + }; + outcome.and(drafted.map(|_| ())).map_err(|(reason, detail)| fail(collection, reason, detail)) + } + + fn seeded( + &self, + head: &ManifestHead, + collection: &str, + rkey: &str, + row: &Row, + ) -> Result<(serde_json::Value, SeedRecord, RecordBody), Failure> { let record: serde_json::Value = serde_json::from_str(&row.org_record) .map_err(|error| fail(collection, "org_record isn't json", error))?; - let created_at = row.created_at.as_deref().unwrap_or(&head.created_at); + let own = (collection == "org.tangled.label.definition") + .then(|| record.get("createdAt").and_then(|at| at.as_str())) + .flatten(); + let created_at = own.or(row.created_at.as_deref()).unwrap_or(&head.created_at); let stamp = chrono::DateTime::parse_from_rfc3339(created_at) .map_err(|error| fail(collection, "sh_org: createdAt isn't rfc3339", error))? .timestamp(); @@ -224,43 +293,10 @@ impl Checker { Some(Err(why)) => return Err(fail(collection, "seedRepo: validate_stored", why)), Some(Ok(())) => {} } - let address = RecordAddress::new(seed.collection.clone(), seed.rkey.clone()); - let produces = body.cid(); - if produces.to_string() != row.org_cid { - return Err(fail(collection, "cid: knot2 computes a different cid", format!("ours {} knot {produces}", row.org_cid))); - } - - let drafted = drafts::reencode(collection, rkey, repo, &record, seed.created_at, &seed.author, labels); - let native = drafted.as_ref().ok().cloned().flatten(); - if let Some(native) = native.as_ref().filter(|native| native.cid() != produces) { - *self.reencoded.entry(collection.to_owned()).or_default() += 1; - if std::env::var_os("KNOTCHECK_DUMP").is_some() { - let native: ipld_core::ipld::Ipld = serde_ipld_dagcbor::from_slice(native.as_bytes()).expect("native cbor"); - let ours: ipld_core::ipld::Ipld = serde_ipld_dagcbor::from_slice(body.as_bytes()).expect("our cbor"); - eprintln!("REENCODE {}\n ours {ours:?}\n native {native:?}", row.org_uri); - } + if body.cid().to_string() != row.org_cid { + return Err(fail(collection, "cid: knot2 computes a different cid", format!("ours {} knot {}", row.org_cid, body.cid()))); } - - let creation = Creation { - address, - author: seed.author.clone(), - number: SubjectNumber::FIRST, - parent: None, - created_at: seed.created_at, - produces, - }; - self.rotate(repo).map_err(|(reason, detail)| fail(collection, reason, detail))?; - let dir = &self.current.as_ref().expect("rotated").1; - let outcome = match collection { - knot_record::ticket::TICKET_COLLECTION => self.lifecycle::(&dir, repo, creation, body, native), - knot_record::comment::COMMENT_COLLECTION => self.lifecycle::(&dir, repo, creation, body, native), - knot_record::reaction::REACTION_COLLECTION => self.lifecycle::(&dir, repo, creation, body, native), - knot_record::label::LABEL_DEF_COLLECTION => self.lifecycle::(&dir, repo, creation, body, native), - knot_record::pull::PATCH_COLLECTION => self.lifecycle::(&dir, repo, creation, body, native), - knot_record::artifact::ARTIFACT_COLLECTION => self.lifecycle::(&dir, repo, creation, body, native), - _ => Err(("no lifecycle for collection", String::new())), - }; - outcome.and(drafted.map(|_| ())).map_err(|(reason, detail)| fail(collection, reason, detail)) + Ok((record, seed, body)) } // handover's convert_seeded + reconcile, then putRecord's edit and deleteRecord's erase, @@ -293,6 +329,8 @@ impl Checker { repo: &RepoDid, creation: Creation, body: RecordBody, + edits: Vec<(Editing, RecordBody)>, + tip: RecordBody, native: Option, ) -> Result<(), (&'static str, String)> { let store = CobStore::new(git); @@ -300,11 +338,11 @@ impl Checker { let home = CobHome::from(repo); let address = creation.address.clone(); let author = creation.author.clone(); - let mut from = creation.produces; - knot_cobs::settle_stored(&store, &home, repo, &self.signer, address.collection(), creation, body.clone()) + let mut from = tip.cid(); + knot_cobs::settle_stored(&store, &home, repo, &self.signer, address.collection(), creation, body, edits) .map_err(|e| ("handover: settle_stored", e.to_string()))? .ok_or(("handover: settle_stored: unknown collection", String::new()))?; - self.apply(git, repo, &address, RecordOp::Create { record: body }) + self.apply(git, repo, &address, RecordOp::Create { record: tip }) .map_err(|e| ("handover: chain create", e))?; let settled: Vec<_> = store .list::>() @@ -391,7 +429,8 @@ fn work(db: &Path, dids: &[String], checker: &mut Checker) -> anyhow::Result anyhow::Result