Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Draft] Switch to libsolv port #236

Closed
wants to merge 17 commits into from
Closed
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
12 changes: 12 additions & 0 deletions crates/libsolv_rs/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
[package]
name = "libsolv_rs"
version = "0.1.0"
edition = "2021"
Comment on lines +3 to +4
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This needs additional information like the README etc before we can release it.


[dependencies]
itertools = "0.11.0"
petgraph = "0.6.3"
rattler_conda_types = { version = "0.4.0", path = "../rattler_conda_types" }

[dev-dependencies]
insta = "1.29.0"
58 changes: 58 additions & 0 deletions crates/libsolv_rs/src/arena.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
use std::marker::PhantomData;
use std::ops::{Index, IndexMut};

/// An `Arena<TValue>` holds a collection of `TValue`s but allocates persistent `TId`s that are used
/// to refer to an element in the arena. When adding an item to an `Arena` it returns a `TId` that
/// can be used to index into the arena.
pub(crate) struct Arena<TId: ArenaId, TValue> {
data: Vec<TValue>,
phantom: PhantomData<TId>,
}

impl<TId: ArenaId, TValue> Arena<TId, TValue> {
pub(crate) fn new() -> Self {
Self {
data: Vec::new(),
phantom: PhantomData::default(),
}
}

pub(crate) fn clear(&mut self) {
self.data.clear();
}

pub(crate) fn alloc(&mut self, value: TValue) -> TId {
let id = TId::from_usize(self.data.len());
self.data.push(value);
id
}

pub(crate) fn len(&self) -> usize {
self.data.len()
}

#[cfg(test)]
pub(crate) fn as_slice(&self) -> &[TValue] {
&self.data
}
}

impl<TId: ArenaId, TValue> Index<TId> for Arena<TId, TValue> {
type Output = TValue;

fn index(&self, index: TId) -> &Self::Output {
&self.data[index.to_usize()]
}
}

impl<TId: ArenaId, TValue> IndexMut<TId> for Arena<TId, TValue> {
fn index_mut(&mut self, index: TId) -> &mut Self::Output {
&mut self.data[index.to_usize()]
}
}

/// A trait indicating that the type can be transformed to `usize` and back
pub(crate) trait ArenaId {
fn from_usize(x: usize) -> Self;
fn to_usize(self) -> usize;
}
145 changes: 145 additions & 0 deletions crates/libsolv_rs/src/conda_util.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
use crate::arena::Arena;
use crate::id::{NameId, SolvableId};
use crate::mapping::Mapping;
use crate::solvable::Solvable;
use rattler_conda_types::{MatchSpec, PackageRecord, Version};
use std::cmp::Ordering;
use std::collections::HashMap;
use std::str::FromStr;

/// Returns the order of two candidates based on rules used by conda.
pub(crate) fn compare_candidates(
solvables: &Arena<SolvableId, Solvable>,
interned_strings: &HashMap<String, NameId>,
packages_by_name: &Mapping<NameId, Vec<SolvableId>>,
a: &PackageRecord,
b: &PackageRecord,
) -> Ordering {
// First compare by "tracked_features". If one of the packages has a tracked feature it is
// sorted below the one that doesn't have the tracked feature.
let a_has_tracked_features = !a.track_features.is_empty();
let b_has_tracked_features = !b.track_features.is_empty();
match a_has_tracked_features.cmp(&b_has_tracked_features) {
Ordering::Less => return Ordering::Less,
Ordering::Greater => return Ordering::Greater,
Ordering::Equal => {}
};

// Otherwise, select the variant with the highest version
match a.version.cmp(&b.version) {
Ordering::Less => return Ordering::Greater,
Ordering::Greater => return Ordering::Less,
Ordering::Equal => {}
};

// Otherwise, select the variant with the highest build number
match a.build_number.cmp(&b.build_number) {
Ordering::Less => return Ordering::Greater,
Ordering::Greater => return Ordering::Less,
Ordering::Equal => {}
};

// Otherwise, compare the dependencies of the variants. If there are similar
// dependencies select the variant that selects the highest version of the dependency.
let a_match_specs: Vec<_> = a
.depends
.iter()
.map(|d| MatchSpec::from_str(d).unwrap())
.collect();
let b_match_specs: Vec<_> = b
.depends
.iter()
.map(|d| MatchSpec::from_str(d).unwrap())
.collect();

let b_specs_by_name: HashMap<_, _> = b_match_specs
.iter()
.filter_map(|spec| spec.name.as_ref().map(|name| (name, spec)))
.collect();

let a_specs_by_name = a_match_specs
.iter()
.filter_map(|spec| spec.name.as_ref().map(|name| (name, spec)));

let mut total_score = 0;
for (a_dep_name, a_spec) in a_specs_by_name {
if let Some(b_spec) = b_specs_by_name.get(&a_dep_name) {
if &a_spec == b_spec {
continue;
}

// Find which of the two specs selects the highest version
let highest_a =
find_highest_version(solvables, interned_strings, packages_by_name, a_spec);
let highest_b =
find_highest_version(solvables, interned_strings, packages_by_name, b_spec);

// Skip version if no package is selected by either spec
let (a_version, a_tracked_features, b_version, b_tracked_features) = if let (
Some((a_version, a_tracked_features)),
Some((b_version, b_tracked_features)),
) =
(highest_a, highest_b)
{
(a_version, a_tracked_features, b_version, b_tracked_features)
} else {
continue;
};

// If one of the dependencies only selects versions with tracked features, down-
// weight that variant.
if let Some(score) = match a_tracked_features.cmp(&b_tracked_features) {
Ordering::Less => Some(-100),
Ordering::Greater => Some(100),
Ordering::Equal => None,
} {
total_score += score;
continue;
}

// Otherwise, down-weigh the version with the lowest selected version.
total_score += match a_version.cmp(&b_version) {
Ordering::Less => 1,
Ordering::Equal => 0,
Ordering::Greater => -1,
};
}
}

// If ranking the dependencies provides a score, use that for the sorting.
match total_score.cmp(&0) {
Ordering::Equal => {}
ord => return ord,
};

// Otherwise, order by timestamp
b.timestamp.cmp(&a.timestamp)
}

pub(crate) fn find_highest_version(
solvables: &Arena<SolvableId, Solvable>,
interned_strings: &HashMap<String, NameId>,
packages_by_name: &Mapping<NameId, Vec<SolvableId>>,
match_spec: &MatchSpec,
) -> Option<(Version, bool)> {
let name = match_spec.name.as_deref().unwrap();
let name_id = interned_strings[name];

// For each record that matches the spec
let candidates = packages_by_name[name_id]
.iter()
.map(|&s| solvables[s].package().record)
.filter(|s| match_spec.matches(s));

candidates.fold(None, |init, record| {
Some(init.map_or_else(
|| (record.version.clone(), !record.track_features.is_empty()),
|(version, has_tracked_features)| {
(
version.max(record.version.clone()),
has_tracked_features && record.track_features.is_empty(),
)
},
))
})
}
142 changes: 142 additions & 0 deletions crates/libsolv_rs/src/id.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
use crate::arena::ArenaId;

#[repr(transparent)]
#[derive(Clone, Copy, Eq, PartialEq, Hash)]
pub struct RepoId(u32);
baszalmstra marked this conversation as resolved.
Show resolved Hide resolved

impl RepoId {
pub(crate) fn new(id: u32) -> Self {
baszalmstra marked this conversation as resolved.
Show resolved Hide resolved
Self(id)
}
}

#[repr(transparent)]
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct NameId(u32);

impl NameId {
pub(crate) fn new(index: usize) -> Self {
Self(index as u32)
}

pub(crate) fn index(self) -> usize {
self.0 as usize
}
}

impl ArenaId for NameId {
fn from_usize(x: usize) -> Self {
NameId::new(x)
}

fn to_usize(self) -> usize {
self.index()
}
}

#[repr(transparent)]
#[derive(Clone, Copy, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub struct MatchSpecId(u32);

impl MatchSpecId {
pub(crate) fn new(index: usize) -> Self {
Self(index as u32)
}

pub(crate) fn index(self) -> usize {
self.0 as usize
}
}

impl ArenaId for MatchSpecId {
fn from_usize(x: usize) -> Self {
MatchSpecId::new(x)
}

fn to_usize(self) -> usize {
self.index()
}
}

#[repr(transparent)]
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug, Ord, PartialOrd)]
pub struct SolvableId(u32);

impl SolvableId {
pub(crate) fn new(index: usize) -> Self {
baszalmstra marked this conversation as resolved.
Show resolved Hide resolved
debug_assert_ne!(index, u32::MAX as usize);
Self(index as u32)
}

pub(crate) fn root() -> Self {
Self(0)
}

pub(crate) fn is_root(self) -> bool {
self.0 == 0
}

pub(crate) fn null() -> Self {
Self(u32::MAX)
}

pub(crate) fn is_null(self) -> bool {
self.0 == u32::MAX
}

pub(crate) fn index(self) -> usize {
self.0 as usize
}
}

impl ArenaId for SolvableId {
fn from_usize(x: usize) -> Self {
SolvableId::new(x)
}

fn to_usize(self) -> usize {
self.index()
}
}

#[repr(transparent)]
#[derive(Copy, Clone, PartialOrd, Ord, Eq, PartialEq, Debug, Hash)]
pub(crate) struct RuleId(u32);

impl RuleId {
pub(crate) fn new(index: usize) -> Self {
debug_assert_ne!(index, 0);
debug_assert_ne!(index, u32::MAX as usize);

Self(index as u32)
}

pub(crate) fn install_root() -> Self {
Self(0)
}

pub(crate) fn index(self) -> usize {
self.0 as usize
}

pub(crate) fn is_null(self) -> bool {
self.0 == u32::MAX
}

pub(crate) fn null() -> RuleId {
RuleId(u32::MAX)
}
}

#[derive(Copy, Clone, Debug)]
pub(crate) struct LearntRuleId(u32);

impl ArenaId for LearntRuleId {
fn from_usize(x: usize) -> Self {
Self(x as u32)
}

fn to_usize(self) -> usize {
self.0 as usize
}
}
10 changes: 10 additions & 0 deletions crates/libsolv_rs/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
mod arena;
mod conda_util;
pub mod id;
mod mapping;
pub mod pool;
pub mod problem;
pub mod solvable;
pub mod solve_jobs;
pub mod solver;
pub mod transaction;
Loading