suno_core/roots.rs
1//! Async lineage-root resolution: walk a whole library back to each clip's
2//! root ancestor, gap-filling ancestors that are missing from the caller's
3//! listing over the network.
4//!
5//! This is the IO surface lifted out of [`crate::lineage`], which stays pure.
6//! A clip's parent edge is classified there; here those pure classifiers
7//! ([`immediate_parent`], [`attribution_edges`]) are threaded up each parent
8//! chain to a root ([`resolve_roots`]), reaching the network only through the
9//! [`Http`] port (via [`SunoClient`]) to fill ancestors absent from the
10//! caller's listing. The dependency is one-way: `roots` depends on `lineage`,
11//! never the reverse.
12
13use std::collections::{HashMap, HashSet};
14
15use crate::client::SunoClient;
16use crate::clock::Clock;
17use crate::error::Result;
18use crate::http::Http;
19use crate::lineage::{Resolution, ResolveStatus, RootInfo, attribution_edges, immediate_parent};
20use crate::model::Clip;
21
22/// Tunables bounding how hard [`resolve_roots`] works per call.
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub struct ResolveOpts {
25 /// Maximum number of missing ancestor ids to fetch from the network. This
26 /// is the only budget: in-index walking is unbounded (a cycle guard, not a
27 /// hop cap, guarantees termination), so a deep chain resolves in full.
28 pub max_gap_fills: u32,
29 /// Maximum concurrent by-id clip fetches during one gap-fill batch.
30 pub concurrency: u32,
31}
32
33impl Default for ResolveOpts {
34 fn default() -> Self {
35 Self {
36 max_gap_fills: 200,
37 concurrency: 4,
38 }
39 }
40}
41
42/// Resolve the root ancestor of every clip in `clips`.
43///
44/// Walks each clip up its [`immediate_parent`] chain to a root. Chains that
45/// stay within `clips` resolve with no network access. When a parent is absent
46/// from the index it is gap-filled: missing ids are fetched in a batch through
47/// [`SunoClient::get_clips_by_ids`], and any id that cannot be retrieved that
48/// way falls back to [`SunoClient::get_clip_parent`], which yields one ancestor
49/// hop to keep walking (never assumed to be the absolute root).
50///
51/// Gap-filled clips (which may be trashed) are held in an index that is kept
52/// structurally separate from the caller's `clips`; they exist only to resolve
53/// ancestry and must never be treated as download candidates by later phases.
54///
55/// Bounded by [`ResolveOpts`]: at most `max_gap_fills` ancestor ids are fetched
56/// (exhaustion yields [`ResolveStatus::External`] at the last reachable
57/// ancestor). In-index chains are not hop-capped: a chain that stays within the
58/// index (or persisted archive) is walked in full to its true parentless root,
59/// however deep, terminating via a `visited` cycle guard. A cycle yields
60/// [`ResolveStatus::Cycle`] rooted at the cycle's canonical (lexicographically
61/// smallest) member, so cyclic data resolves order-independently. The returned
62/// [`Resolution`] has a root entry for every input clip, plus the gap-filled
63/// ancestor clips it fetched.
64pub async fn resolve_roots(
65 clips: &[Clip],
66 archived_parents: &HashMap<String, String>,
67 client: &SunoClient<impl Clock>,
68 http: &impl Http,
69 opts: ResolveOpts,
70) -> Result<Resolution> {
71 let mut resolver = Resolver::new(clips, opts, archived_parents);
72 resolver.run(client, http).await?;
73 Ok(resolver.into_resolution(clips))
74}
75
76/// The result of walking one chain as far as the current index allows.
77enum Walk {
78 /// The start clip's root is now recorded in the memo.
79 Resolved,
80 /// The walk stalled needing this ancestor id gap-filled.
81 Blocked(String),
82}
83
84/// Working state for one [`resolve_roots`] call.
85///
86/// `index` holds the input clips plus any gap-filled ancestors so the walk can
87/// read their pointers; `gap_filled` records which ids were fetched here so
88/// later phases can tell ancestors apart from download candidates. `bridges`
89/// maps a missing id to the known parent that the parent endpoint returned in
90/// its place, and `external` records ids the API reported as parentless roots.
91struct Resolver<'a> {
92 index: HashMap<String, Clip>,
93 /// Persisted `child_id -> parent_id` links from the durable store's primary
94 /// edges. Consulted before any network gap-fill so a walk can hop through an
95 /// ancestor whose clip is absent (e.g. an intermediate remix, or one Suno
96 /// has since purged) using data captured on an earlier run.
97 archived_parents: &'a HashMap<String, String>,
98 gap_filled: HashSet<String>,
99 bridges: HashMap<String, String>,
100 external: HashSet<String>,
101 /// Clip-root ids already attempted as a gap-fill seed, so a root that the
102 /// batch never returns is tried once and then left alone (never re-seeded,
103 /// never bridged, never external).
104 seeded: HashSet<String>,
105 memo: HashMap<String, RootInfo>,
106 targets: Vec<String>,
107 budget: u32,
108 concurrency: u32,
109}
110
111impl<'a> Resolver<'a> {
112 fn new(
113 clips: &[Clip],
114 opts: ResolveOpts,
115 archived_parents: &'a HashMap<String, String>,
116 ) -> Self {
117 let index = clips
118 .iter()
119 .map(|clip| (clip.id.clone(), clip.clone()))
120 .collect();
121 let targets = clips.iter().map(|clip| clip.id.clone()).collect();
122 Self {
123 index,
124 archived_parents,
125 gap_filled: HashSet::new(),
126 bridges: HashMap::new(),
127 external: HashSet::new(),
128 seeded: HashSet::new(),
129 memo: HashMap::new(),
130 targets,
131 budget: opts.max_gap_fills,
132 concurrency: opts.concurrency,
133 }
134 }
135
136 /// Resolve every target, gap-filling missing ancestors until the whole set
137 /// is settled or the budget runs out.
138 async fn run(&mut self, client: &SunoClient<impl Clock>, http: &impl Http) -> Result<()> {
139 let targets = self.targets.clone();
140 loop {
141 let mut frontier: Vec<String> = Vec::new();
142 let mut seen: HashSet<String> = HashSet::new();
143 let mut blocked: Vec<(String, String)> = Vec::new();
144
145 for target in &targets {
146 if self.memo.contains_key(target) {
147 continue;
148 }
149 if let Walk::Blocked(missing) = self.walk(target) {
150 if seen.insert(missing.clone()) {
151 frontier.push(missing.clone());
152 }
153 blocked.push((target.clone(), missing));
154 }
155 }
156
157 if blocked.is_empty() {
158 break;
159 }
160 if self.budget == 0 || !self.gap_fill(client, http, &frontier).await? {
161 self.finalise_external(&blocked);
162 break;
163 }
164 }
165 Ok(())
166 }
167
168 /// Walk `start` up its parent chain within the current index, memoising the
169 /// root for every node reached. Returns [`Walk::Blocked`] with the first
170 /// ancestor id that is missing and needs gap-filling.
171 fn walk(&mut self, start: &str) -> Walk {
172 if self.memo.contains_key(start) {
173 return Walk::Resolved;
174 }
175 let mut chain: Vec<String> = Vec::new();
176 let mut visited: HashSet<String> = HashSet::new();
177 let mut current = start.to_string();
178
179 loop {
180 if let Some(info) = self.memo.get(¤t).cloned() {
181 self.assign(&chain, &info);
182 return Walk::Resolved;
183 }
184 if visited.contains(¤t) {
185 // A cycle. Root it at its canonical (lexicographically smallest)
186 // member so the same cyclic data resolves the same root whatever
187 // order its clips were listed in. The members are the nodes from
188 // `current`'s first occurrence in the chain onward; any non-cycle
189 // lead-in walked before that point is excluded.
190 let cycle_start = chain.iter().position(|id| *id == current).unwrap_or(0);
191 let root = chain[cycle_start..]
192 .iter()
193 .min()
194 .cloned()
195 .unwrap_or_else(|| current.clone());
196 let info = self.terminal(&root, ResolveStatus::Cycle);
197 self.assign(&chain, &info);
198 self.memo.insert(current, info);
199 return Walk::Resolved;
200 }
201
202 // The parent of `current` comes from its live/fetched clip, or from
203 // a persisted archived edge when the clip itself is not in hand. An
204 // id known through neither is unknown locally and must be gap-filled
205 // (this is the guard: an edgeless archived node is fetched, never
206 // assumed a root, so a not-yet-persisted remix still gets its real
207 // parent).
208 let parent_id = if let Some(clip) = self.index.get(¤t) {
209 immediate_parent(clip).map(|(id, _edge)| id)
210 } else if let Some(parent) = self.archived_parents.get(¤t) {
211 Some(parent.clone())
212 } else {
213 return Walk::Blocked(current);
214 };
215
216 let Some(parent_id) = parent_id else {
217 let info = RootInfo {
218 root_id: current.clone(),
219 root_title: self.title_of(¤t),
220 status: ResolveStatus::Resolved,
221 };
222 self.assign(&chain, &info);
223 self.memo.insert(current, info);
224 return Walk::Resolved;
225 };
226
227 visited.insert(current.clone());
228 chain.push(current);
229
230 if self.index.contains_key(&parent_id) || self.archived_parents.contains_key(&parent_id)
231 {
232 current = parent_id;
233 } else if let Some(bridged) = self.bridges.get(&parent_id).cloned() {
234 visited.insert(parent_id);
235 current = bridged;
236 } else if self.external.contains(&parent_id) {
237 let info = self.terminal(&parent_id, ResolveStatus::External);
238 self.assign(&chain, &info);
239 self.memo.insert(parent_id, info);
240 return Walk::Resolved;
241 } else {
242 return Walk::Blocked(parent_id);
243 }
244 }
245 }
246
247 /// Fetch missing `frontier` ancestors, batching by id and falling back to
248 /// the parent endpoint. Same-owner `clip_roots` are additionally seeded as
249 /// best-effort root candidates. Returns whether the index (or
250 /// bridges/externals) grew, so the caller can detect a stalled resolution.
251 async fn gap_fill(
252 &mut self,
253 client: &SunoClient<impl Clock>,
254 http: &impl Http,
255 frontier: &[String],
256 ) -> Result<bool> {
257 // Structural frontier: ancestors a walk is blocked on. They get the full
258 // treatment (batch fetch, then a parent-endpoint fallback that may bridge
259 // one hop or mark the id external).
260 let mut want: Vec<String> = frontier
261 .iter()
262 .filter(|id| !self.known(id))
263 .cloned()
264 .collect();
265 want.sort();
266 want.dedup();
267
268 // Same-owner clip_root seeds: an OPTIONAL extra root candidate. They ride
269 // the batch and its per-id fallback, but never the parent-endpoint path
270 // below, so a seed the fetch omits is simply dropped, never bridged,
271 // externalised, or forced to a root: clip_roots can neither fabricate a
272 // parent link nor arm a delete. Foreign-owned roots are excluded
273 // (fail-closed by handle), and each seed is attempted at most once.
274 let mut seeds: Vec<String> = self
275 .clip_root_seeds()
276 .into_iter()
277 .filter(|id| !self.known(id) && !self.seeded.contains(id) && !want.contains(id))
278 .collect();
279 seeds.sort();
280 seeds.dedup();
281
282 if want.is_empty() && seeds.is_empty() {
283 return Ok(false);
284 }
285
286 // Frontier ids take budget priority so a blocked walk is never starved
287 // by a best-effort seed.
288 let frontier_take = (self.budget as usize).min(want.len());
289 let frontier_batch: Vec<String> = want.into_iter().take(frontier_take).collect();
290 self.budget -= frontier_batch.len() as u32;
291
292 let seed_take = (self.budget as usize).min(seeds.len());
293 let seed_batch: Vec<String> = seeds.into_iter().take(seed_take).collect();
294 self.budget -= seed_batch.len() as u32;
295 for id in &seed_batch {
296 self.seeded.insert(id.clone());
297 }
298
299 // One batch call covers frontier + seeds; the parent-endpoint fallback
300 // below is confined to the structural frontier.
301 let all: Vec<&str> = frontier_batch
302 .iter()
303 .chain(seed_batch.iter())
304 .map(String::as_str)
305 .collect();
306 let fetched = client
307 .get_clips_by_ids(http, &all, self.concurrency as usize)
308 .await?;
309
310 let mut returned: HashSet<String> = HashSet::new();
311 let mut progressed = false;
312 for clip in fetched {
313 returned.insert(clip.id.clone());
314 if self.insert_ancestor(clip) {
315 progressed = true;
316 }
317 }
318
319 for id in &frontier_batch {
320 if returned.contains(id) {
321 continue;
322 }
323 match client.get_clip_parent(http, id).await? {
324 Some(parent) => {
325 let parent_id = parent.id.clone();
326 self.insert_ancestor(parent);
327 self.bridges.insert(id.clone(), parent_id);
328 progressed = true;
329 }
330 None => {
331 self.external.insert(id.clone());
332 progressed = true;
333 }
334 }
335 }
336
337 Ok(progressed)
338 }
339
340 /// Same-owner `clip_root` ids across the current index, as extra root
341 /// candidates for gap-fill. Foreign-owned roots are excluded (fail-closed by
342 /// handle) so a foreign remix source is never folded into the owner's album.
343 fn clip_root_seeds(&self) -> Vec<String> {
344 let mut seeds = Vec::new();
345 for clip in self.index.values() {
346 for edge in attribution_edges(clip) {
347 if edge.same_owner {
348 seeds.push(edge.parent_id);
349 }
350 }
351 }
352 seeds
353 }
354
355 /// Add a gap-filled ancestor to the index, tracking it as an ancestor-only
356 /// clip. Returns whether it was newly added.
357 fn insert_ancestor(&mut self, clip: Clip) -> bool {
358 if clip.id.is_empty() || self.index.contains_key(&clip.id) {
359 return false;
360 }
361 self.gap_filled.insert(clip.id.clone());
362 self.index.insert(clip.id.clone(), clip);
363 true
364 }
365
366 /// Whether an id is already resolvable without another fetch.
367 fn known(&self, id: &str) -> bool {
368 self.index.contains_key(id)
369 || self.archived_parents.contains_key(id)
370 || self.bridges.contains_key(id)
371 || self.external.contains(id)
372 }
373
374 /// Mark every still-unresolved blocked target as external at the ancestor it
375 /// stalled on.
376 fn finalise_external(&mut self, blocked: &[(String, String)]) {
377 for (target, missing) in blocked {
378 if self.memo.contains_key(target) {
379 continue;
380 }
381 let info = self.terminal(missing, ResolveStatus::External);
382 self.memo.insert(target.clone(), info);
383 }
384 }
385
386 /// Build a [`RootInfo`] rooted at `id`, titled from the index when present.
387 fn terminal(&self, id: &str, status: ResolveStatus) -> RootInfo {
388 RootInfo {
389 root_id: id.to_string(),
390 root_title: self.title_of(id),
391 status,
392 }
393 }
394
395 /// The title of an indexed clip, or empty when it is not in the index.
396 fn title_of(&self, id: &str) -> String {
397 self.index
398 .get(id)
399 .map_or_else(String::new, |clip| clip.title.clone())
400 }
401
402 /// Record `info` as the root for every node on `chain`.
403 fn assign(&mut self, chain: &[String], info: &RootInfo) {
404 for id in chain {
405 self.memo.insert(id.clone(), info.clone());
406 }
407 }
408
409 /// Project the memo onto the input clips (so every one has a root entry) and
410 /// collect the gap-filled ancestors, sorted by id for a deterministic order.
411 fn into_resolution(self, clips: &[Clip]) -> Resolution {
412 let mut roots = HashMap::with_capacity(clips.len());
413 for clip in clips {
414 let info = self
415 .memo
416 .get(&clip.id)
417 .cloned()
418 .unwrap_or_else(|| RootInfo {
419 root_id: clip.id.clone(),
420 root_title: clip.title.clone(),
421 status: ResolveStatus::Unresolved,
422 });
423 roots.insert(clip.id.clone(), info);
424 }
425
426 let mut gap_filled: Vec<Clip> = self
427 .gap_filled
428 .iter()
429 .filter_map(|id| self.index.get(id).cloned())
430 .collect();
431 gap_filled.sort_by(|a, b| a.id.cmp(&b.id));
432
433 let mut bridges: Vec<(String, String)> = self
434 .bridges
435 .iter()
436 .map(|(child, parent)| (child.clone(), parent.clone()))
437 .collect();
438 bridges.sort();
439
440 Resolution {
441 roots,
442 gap_filled,
443 bridges,
444 }
445 }
446}
447
448#[cfg(test)]
449mod tests;