[Pitch] Allowing Multiple Major Versions of a Package

This pitch is based on some investigative and prototype work that I've developed over the last few months. The goal with this feature is to extend the versatility of SwiftPM as a sophisticated package manager tool that grants users the flexibility to migrate alongside major version bumps to their dependencies without the strain of being limited to a single version per package. I've brought this topic up for discussion some months back (Multiple Major Versions of a Package in SwiftPM: Opening the Discussion), and with this post I'm looking to formalize the steps needed to successfully implement this -- with your feedback, of course :)

Introduction

Since its inception, SwiftPM has resolved exactly one version of each uniquely identified package in a dependency graph. In graphs with few dependencies, this rarely causes problems. As graphs grow, however, it becomes common for a package to be reached through multiple paths (better known as a diamond dependency). When those paths require different, non-overlapping major versions of the same package, resolution fails. This pitch proposes allowing multiple major versions of the same package to coexist in a single resolved graph, so that projects with such conflicts can build and run successfully.

Motivation

Conflicting major version requirements on the same package can happen well beyond what the root package controls, in transitive dependencies the user may not even be aware of.

Today's workarounds all shift the burden onto developers: clients restrict dependency versions in their own manifests and give up on newer releases; package authors avoid major version bumps, which holds back API evolution for everyone downstream; and others fork and rename a repository to represent a new major version, creating a separate package identity that must be maintained by hand.

Rather than requiring developer intervention around a tooling limitation, SwiftPM should offer a solution. When different parts of a graph legitimately need different major versions of the same package, SwiftPM should resolve and build them together instead of failing.

Example

For a concrete view into this problem, consider the following example:

As a user, I have a root package (say, FunPackage) that I develop for others seeking to use fun things. In this package, I need some networking capabilities that I can utilize via a dependency on FunNetworking:

let package = Package( 
	name: "FunPackage",
	// ...
	dependencies: [ 
		.package(url: "https://foo.bar/fun-org/fun-networking", from: "1.0.0")
	]
)

With this simple package graph, I can easily declare an import against any modules available in FunNetworking in my own source.

Consider now that I must extend the capabilities of my FunPackage so it reports usage events, and I'd like to make use of an existing package, FunAnalytics, to do that. FunAnalytics is maintained by a different organization. Its 3.0.0 release moved to the new async/await-based FunNetworking 2.0 API, so its manifest looks like this:

// FunAnalytics, version 3.0.0
let package = Package(
    name: "FunAnalytics",
    // ...
    products: [
        .library(name: "FunAnalytics", targets: ["FunAnalytics"])
    ],
    dependencies: [
        .package(url: "https://foo.bar/fun-org/fun-networking", from: "2.0.0")
    ],
    targets: [
        .target(
            name: "FunAnalytics",
            dependencies: [
                .product(name: "FunNetworking", package: "fun-networking")
            ]
        )
    ]
)

And now, my FunPackage adds the dependency to FunAnalytics:

let package = Package(
    name: "FunPackage",
    // ...
    dependencies: [
        .package(url: "https://foo.bar/fun-org/fun-networking", from: "1.0.0"),
        .package(url: "https://foo.bar/amazing-org/fun-analytics", from: "3.0.0")
    ]
)

The dependency graph for this would look like the following:

FunPackage
โ”œโ”€โ”€ fun-networking   1.0.0..<2.0.0   (direct)
โ””โ”€โ”€ fun-analytics    3.0.0..<4.0.0   (direct)
    โ””โ”€โ”€ fun-networking   2.0.0..<3.0.0   (transitive)


Notice that there are two instances of fun-networking, both requiring not-overlapping versions. Today, SwiftPM would report an error:

error: Dependencies could not be resolved because `fun-package` depends on 'fun-networking' 1.0.0..<2.0.0 and `fun-analytics` depends on 'fun-networking' 2.0.0..<3.0.0.

While there is technically a workaround by widening the version constraint of FunPackage's dependency on FunNetworking,

	.package(url: "https://foo.bar/fun-org/fun-networking", "1.0.0"..<"3.0.0")

every workaround has the same consequence. SwiftPM resolves exactly one version of fun-networking for the entire package graph, so any fix means changing which version of that dependency everything builds against.

For example, widening the requirement to "1.0.0"..<"3.0.0" like the above resolves FunNetworking to 2.x, which could mean that any reliance on FunNetworking's 1.x APIs used in FunPackage will need to be updated all at once, and pinning FunAnalytics to an older major version forces the whole graph back onto FunNetworking @ 1.x, which surrenders the usage of any newer features from 2.x.

This conflict isn't limited to packages the user declares themselves. Notably, it can show up anywhere in the graph, including far from the root where it is much harder to diagnose and fix. Using the same example, consider the case where its dependency tree instead looks like the following:

FunPackage
โ”œโ”€โ”€ fun-analytics   from 3.0.0
โ”‚   โ””โ”€โ”€ fun-transport   from 1.0.0
โ”‚       โ””โ”€โ”€ fun-networking   1.0.0..<2.0.0
โ””โ”€โ”€ fun-ui   from 2.0.0
    โ””โ”€โ”€ fun-image-loader   from 4.0.0
        โ””โ”€โ”€ fun-networking   2.0.0..<3.0.0


There is little a user can do through its root FunPackage to avoid a conflict in SwiftPM's ability to resolve this graph beyond constraining their own dependencies rigorously or requesting that package authors create a fork for every new major version.

Proposed solution

When a package graph requires disjoint major versions of the same package, SwiftPM would resolve one version per major range instead of failing. In the example above, FunPackage would resolve fun-networking 1.x for its own use and 2.x for fun-analytics, and should build both in parallel.

A prototype of this work can be found here. This prototype is not a full and complete implementation of all the stages of the solution proposed below (there is no implementation of PURLs, and the PubGrub modifications are incomplete), however it does act as a proof of concept that SwiftPM is capable of building a package graph with multiple major versions of one package, and can link a binary that runs successfully.

Similarly, a project board was created to track the issues related to the investigation and implementation of the multiple majors feature: [SwiftPM] Multiple Major Versions ยท GitHub

The implementation can be broken into five stages, each described below:

  1. Identify packages with a PURL
    • Introduce PURLs as a way to identify packages, carrying provenance and version data that will allow SwiftPM to easily distinguish between major versions. A PackageIdentity can still be derived by a PURL.
  2. Resolve using major version buckets
    • Augment the PubGrub algorithm so that disjoint version constraints on the same package no longer produce an error.
    • SwiftPM would track disjoint major version ranges and would represent these choices as higher-level bucket nodes.
  3. Rewire the package graph
    • Where the graph would previously point every edge at a single resolved version of a package, point each edge at the major version bucket that satisfies that edge's constraint.
  4. Alias the modules
    • Synthesize module aliases that incorporate the package identity and major version, so that same-named modules from different buckets don't collide at build time.
  5. Introduce an opt-in flag
    • Developers will have to explicitly opt-in to this behaviour; a flag will be introduced to run alongside any swift commands (swift package resolve, swift build, swift run, etc.)

To confirm this works end to end, the resulting object files should contain distinct, mangled symbols for each major version, and any final linked binaries should run successfully.

Note that the initial implementation within SwiftPM will support Swift modules only. When a conflict involves a package containing C modules, SwiftPM will instead inform the user of this conflict, and will suggest to rename the C symbols on a major version bump to mitigate the collision between major versions. As such, SwiftPM will still fail out when encountering C modules with colliding names, but a more informative diagnostic will guide developers on how to move forward.

Detailed design

Replace PackageIdentity with PURL

The resolver and package graph need a stable way to name each major version bucket of a package, as well as the edge packages described above. PackageIdentity can't express this today. It identifies a package only by name, so fun-networking at 1.x and fun-networking at 2.x share one identity, which is exactly why the graph can hold only one of them.

A PURL (Package URL) is an identifier (and has already been adopted in SwiftPM as a part of SE-0509) consisting of a scheme (which is always pkg), a type (a registered identity in the specification that refers to a particular language or build system), an optional namespace, a name, an optional version, and optional qualifiers. For example, the different versions of FunNetworking used in the example above may be identified (using the String representation of PURL) as:

// PURL scheme: pkg:<type>/<namespace>/<name>@<version>?<qualifiers>
pkg:swift/fun-org/fun-networking@1.x
pkg:swift/fun-org/fun-networking@2.x

PURLs also address a related SwiftPM weakness: today, package Foo from GitHub at 1.2.3 and package Foo from a custom registry at 1.2.3 share a PackageIdentity of Foo, so SwiftPM relies on heuristics (such as DependencyMapper), to decide which one is being referred to. A PURL carries the origin as part of the identifier, so the two would become easily distinguishable.

// Example PURLs for a package, fun-stuff, in two separate locations.

// For a package awesome.fun-stuff @ v1.x located on registry foo.bar.com
"pkg:swift/awesome/fun-stuff@1.x?registry_url=https://foo.bar.com"

// For a package with the same name, located on GitHub:
"pkg:swift/awesome/fun-stuff@1.x?vcs_url=https://github.com"

A PURL, conceptually, builds on top of what is already available in a PackageIdentity, since the name field (and, where applicable, namespace) is effectively the same as today's PackageIdentity. Any additional information acts as metadata, further differentiating two similarly-declared packages, and can be extended to return richer types compatible with SwiftPM's internal models:

extension PURL { 
	/// Where the package originates (source control, registry, etc.)
	public var kind: PackageKind { 
		// ...
	}
	
	/// The base-name identity of the package.
	public var identity: PackageIdentity { 
		// ...
	}
	
	/// The version of the package.
	public var version: Version { 
		// ...
	}
	
	// ... etc.
}

With the introduction of PURLs as the standard in which SwiftPM can identify packages, it becomes rightly more specific to refer to any given package anywhere in SwiftPM.

Augmenting PubGrub to bucket major versions

To support multiple major versions, the resolver will treat each major version of a package as its own bucket, represented by a single constraint. Ranges of major versions will be bucketed by the dependency edge itself, with each version therein representing a major-version bucket.

A bucket is identified by its package (what would canonically be the PackageIdentity) and a major version, and would cover that major version's range. A PURL-bucket would represent a major version range for that dependency:

// The PURL String representation, when printed:
"pkg:swift/fun-networking@1"
// Applicable versions for this would be 1.0.0..<2.0.0

// A possible extension to PURL, for use in PubGrub:
extension PURL { 
	/// The major version range that this PURL bucket represents.
	public var majorVersionBucket: Int?
	
	/// The string representation of the PURL bucket.
	public var bucketDescription: String? { 
		guard let major = self.majorVersionBucket else { return nil }
		return "pkg:swift/\(self.name)@\(major)"
	}
	
	/// Detects which available versions for the base package is
	/// eligible for this bucket.
	public func availableVersions(_ versions: [Version]) -> [Version] { 
		if let major = self.majorVersionBucket { 
			return versions.filter({ $0.major == major })
		}
		
		return versions
	}
}

For FunAnalytics, say its dependency on FunNetworking has expanded its version range constraint to 2.0.0..<4.0.0. There would then be two possible major-version buckets that represent this range, and therefore this new dependency edge constraint would span several majors. Here, this would correspond to two buckets:

// ... for some `container` representing the package `fun-networking`

let allVersionsFunNetworking = container.versionsAscending()
print(allVersionsFunNetworking)
// E.g.: 
// 1.0.0, 1.0.1, 2.0.0, 2.0.1, 2.1.0, 2.2.0, 2.2.1, 3.0.0, 3.1.0, 3.1.1

// bucket: FunNetworking@v2
let funNetworkingV2 = PURL("pkg:swift/fun-networking@2")
let v2 = funNetworkingV2.availableVersions(allVersionsFunNetworking)
print(v2)
// 2.0.0, 2.0.1, 2.1.0, 2.2.0, 2.2.1

// bucket: FunNetworking@v3
let funNetworkingV3 = PURL("pkg:swift/fun-networking@3")
let v3 = funNetworkingV3.availableVersions(allVersionsFunNetworking)
print(v3)
// 3.0.0, 3.1.0, 3.1.1

FunAnalytics is requesting any one version of FunNetworking within the 2.0.0..<4.0.0 range. If SwiftPM were to add one bucket per major version as separate constraints, it would require resolving to both a 2.x version and a 3.x version, which is incorrect. Instead, each dependency edge becomes an intermediate representation whose synthesized "dependencies" are the buckets representing a major version range.

// synthesized package: FunAnalytics->FunNetworking
// available versions: 2.0.0, 3.0.0
//
// version: 2.0.0
// dependencies:
//   - FunNetworking@v2
//
// version: 3.0.0
// dependencies:
//   - FunNetworking@v3

Each version of this intermediate edge corresponds directly to its "dependencies", which would be the major version bucket. Since this would imply the addition of new incompatibilities that PubGrub would need to derive and inject into its algorithm, it stands to reason that there must be some extra maintenance within the state to fully capture and track each of these synthesized decision nodes.

Inject major version-specific nodes into the package graph

Once resolution is complete, each dependency edge has selected one major version bucket, and each bucket resolves to a single version. The package graph is then built from this result. Where today a single node represents the one version a package resolved to, the graph would instead contain one node per bucket that was selected by at least one edge.

In the running example, the graph would change as follows:

Today (fails when the ranges are disjoint):

  FunPackage โ”€โ”€โ–บ fun-networking
  FunPackage โ”€โ”€โ–บ fun-analytics โ”€โ”€โ–บ fun-networking 

With major version nodes:

  FunPackage โ”€โ”€โ–บ fun-networking@1 (resolved to some v 1.x)
  FunPackage โ”€โ”€โ–บ fun-analytics โ”€โ”€โ–บ fun-networking@2 (resolved to some v 2.x)

Where each major version nodes PURLs may look like, respectively:

pkg:swift/fun-org/fun-networking@1.1.0
pkg:swift/fun-org/fun-networking@2.4.3

Each dependency edge points at the major version node it selected, identified by a PURL containing the exact version it resolved to. Edges that select the same major version share a node (much like today's SwiftPM sharing the node between dependents who require the same dependency), so if another package also depends on fun-networking@2, it points at the same node, and every dependent of that major version sees the same resolved 2.x.

Leverage module aliasing to resolve same-name collisions

The resulting package graph once resolution is complete will introduce two or more of the same package at different major versions, which would typically contain modules of the same name. Today, two packages that have modules with the same name would cause SwiftPM to fail and would suggest to use module aliasing to resolve this, so that the mangled symbols (which use the module name) aren't identical.

Reasonably, module aliasing is therefore needed at this stage. After the graph is built, SwiftPM would need to add a phase that identifies packages that have multiple major versions and should generate a unique alias for each of their modules, derived from the package identity and major version:

fun-networking@1.x:  FunNetworkingModule  ->  FunNetworkingModule_v1
fun-networking@2.x:  FunNetworkingModule  ->  FunNetworkingModule_v2

The ModuleAliasTracker will then need a supplementary method that serves to gather and and create the aliases for all of the major versions of one package.


func addMultipleMajorAliases(_ package: PURL, modules: [Module], products: [Product]) { 
	// ...
	for product in products { 
		// ...
		for module in modules { 
			derivedAliases[module.name] = "\(module.name)_v\(PURL.majorVersion)"
		}
		// ...
		// This would populate the tracker with new synthesized aliases,
		// and should in theory be handled as any other alias.
		try addAliases(
			derivedAliases,
			productID: product.identity,
			productName: product.name,
			originPackage: package,
			consumingPackage: package 
		)
	}
}


Today module aliasing is driven by the user, who declares aliases in their manifest. This phase would instead be synthesized by SwiftPM during resolved package graph construction and would run alongside the existing alias handling. An open question is how SwiftPM should reconcile user-declared aliases with the major version aliasing.

Note on C module compatibility

SwiftPM passes module aliases to the Swift compiler through the -module-alias flag. This mechanism applies to Swift modules. C modules are compiled with clang, and requires additional investigation in how those sources are built.

Opt-in flag

Allowing SwiftPM to resolve multiple major versions of a package will be strictly opt-in. The entrypoint to users will be through the use of a flag (for example, --allow-multiple-majors, although the final name is to be determined) on commands that resolve or build a package graph, such as swift package resolve, swift build, and swift run. Without specifying this flag, resolution would behave exactly as it does today.

If users ever encounter a scenario where multiple major versions of a package dependency causes a resolution failure, the error message would mention this flag for discoverability:

note: this conflict involves disjoint major versions of 'fun-networking'.
Pass '--allow-multiple-majors' to resolve each major version separately.

Additional implementation notes

Developer experience

To aid in the developer experience for those looking to import modules of a multiple major package, if the canonical module name is referred to in the source of the root package (say, import FunNetworking) there will be some diagnostic error informing the user that such a module does not exist. There should be additional reasoning for this phenomenon, namely that the canonical module refers to some package that has now been resolved to multiple major versions, and the diagnostic should offer a list of the newly aliased modules that the developer could be referring to (in this example, possibly FunNetworking_v1, FunNetworking_v2).

Extending major-version definition

TBC

  • 0.x.y should treat "x" as a "major" here, so "0.1" vs "0.2" gets the same handling as "1" vs "2"
  • x.y.z-... versions should treat each "..." as a different major, so "1.0.0-alpha.1" is a different "major" than "1.0.0-alpha.2"

Security

Older major versions may be known to carry vulnerabilities, and users may not be aware if an older major is resolved transitively. Notably, the attack surface grows with each additional copy of a package. As a security measure, SBOMs (which uses PURLs) are used to audit these potential vulnerabilities -- therefore, it would be possible to easily identify such a package since the PURL will act as the identifier. Further discussion would be appreciated here.

Edit:

While introducing multiple major versions of a package may indeed introduce a wider attack surface (notably for older major versions who would've required a security patch), this feature will enable users to in fact speed up their incremental migration to newer major versions, in which security fixes have been shipped. This would remove the friction larger ecosystems would have with today's SwiftPM, where migrating all at once to a new major is a long and tedious process, and can make quicker use of the security fixes that are available to them.

Impact on Existing Packages

This feature will be explicitly opt-in, not automatic. Thus, this shouldn't change how existing packages are resolved and built without explicit user intervention.

The Package.resolved will now need to accommodate multiple entries per package. This should also not break previous toolchain versions, however there is an open question as to how older toolchains should handle this new format. Other commands, such as dump-package and show-dependencies are affected by this change and similarly must accommodate multiple entries per package.

Only packages flagged for multiple major versions will introduce new package graph nodes; however, if there are further conflicts in their dependencies these subtrees could also duplicate.

The resulting binaries could inflate in size. There could also be longer download times as the amount of packages to checkout could, in the worst case, double.

Alternatives considered

Users can opt to module alias conflicting packages themselves, however this task is incredibly manual and tedious and is not guaranteed to work, particularly for dependencies deeper in the graph.

Rather than relying on PURLs, the initial investigation began by simply modifying a PackageIdentity in-place during resolution to include the major version appended, while maintaining a mapping in the Pub Grub state that tracks each of the packages involved in multiple majors. This is effectively the behaviour we will be getting by introducing PURLs as a the mechanism for identifying packages.

Future directions

  • Per-package opt-in/out
  • C module support
    TBD
13 Likes

Great to see this pitch and overall heavily +1 on solving this problem. We have come across this many times in the Swift Server ecosystem and had to resort to workarounds such as new repositories for new major versions. Overall, the pitch is well motivated but I think the detailed design section contains a little too much SwiftPM implementation detail such as internal representations.

I was surprised seeing this. Why do we want to keep this behavior behind an opt-in flag? I think large package graphs will commonly hit this and making this opt-in makes it seem like something unexpected. As far as I know, other package managers don't require an opt-in. What I could see useful is updating the existing swift package update --dry-run or introducing a new swift package outdated command that shows which dependencies force multiple major versions in the graph.

I think this is too restrictive. Many of our packages have C targets to talk to system APIs. If we plain out ban packages with C targets then I am afraid we won't get much adoption from this feature. Since packages with C targets already have to prefix all of their C symbols to avoid symbol collisions, I think a different approach could be to just update our guidance to say these packages should prefix their C targets in a way that each major version has a different prefix.

6 Likes

Thank you for the feedback Franz!

I can absolutely make the detailed design more concise and less implementation-heavy, hopefully it wasn't too dense :smiley:

Why do we want to keep this behavior behind an opt-in flag?

The thinking here was that this could be a fairly large behavioural change that some users may not be expecting. Since the effects of this feature could introduce longer download times and larger binaries, having this be default may be confusing to those who are accustomed to and are expecting the usual behaviour of SwiftPM.

That said, you make a fair point that large package graphs are more susceptible to hitting this issue and would need this feature anyways, and other package managers are able to manage this by default. I do think that introducing additional commands that highlight multiple major versions would bring about more visibility to those wanting to investigate their package graph. Super open to discussion here and would love to hear what folks think!

I think a different approach could be to just update our guidance to say these packages should prefix their C targets in a way that each major version has a different prefix.

I'm in agreement here -- the only reason C modules were called out specifically was to highlight that it would be difficult on the part of SwiftPM to automatically handle how these modules are compiled, since they are handed off to clang. The way I envision this is that SwiftPM won't necessarily fail out if there are C modules present in the various major versions, however it can certainly bring awareness to the idea that package authors can certainly prefix their symbols at each major version bump. Does that align more with what you were thinking here?

1 Like

One idea I had is to do something similar to module aliasing. That was introduced to resolve module name conflicts that can happen somewhere in the transitive target dependencies. It is added to a root package and then inherited by users of that package.

We could add a clause to the package description to list packages from the transitive package dependencies that are allowed to have multiple major versions.

Some thought really needs to happen when allowing multi majors. You do end up with multiple copies of libraries in the resulting executables. Say for example that happens to Vapour and you end up with multiple embedded web servers each trying to open the same port.

1 Like

Yeah that aligns with my thinking. From the proposal text it sounded like packages with C targets were outright forbidden. It may be worth updating the proposal to convey what you outlined here.

1 Like

Thanks for working on this, @bripeticca :folded_hands:

As you point out in your intro, we're currently essentially unable to release new major versions of established packages without breaking the ecosystem :grimacing: So I'm very excited about this coming solution.

A few questions below:

Q1: I strongly agree with Franz here that the final solution should be for this to be the default. Now, I do think it's reasonable to keep the flag as opt-in initially, and then make it default in a future swift-tools-version. However, since you might get multiple majors only in your transitive dependencies, it would be a quite bad experience for one day your CI to stop working, because one of your transitive dependencies decided to start moving between two majors of a dependency. But just like other ecosystems, this shouldn't be considered exceptional - once our ecosystem matures, there will always be some foundational packages shipping new majors and much of the ecosystem in a constant gradual migration between such majors. It'll be the norm - and I don't think we want to end up with every developer always adding this flag without thinking, like essentially mandatory boilerplate.

The grpc-swift v1 -> v2 migration has shown us how much we're missing SwiftPM's support here, and I feel strongly that we shouldn't expect every transitive dependee of such a package to have to know and act on their transitive dependency migrating.

Q2: Is this also proposing a change to the Swift PURL definition? Because the above doesn't match the current one: purl-spec/types/swift-definition.json at main ยท package-url/purl-spec ยท GitHub.

Q3: How would the above handle forks? Often, the root package developer needs to override an upstream with their own fork (temporarily or permanently), and the identity only including the name is the hack feature we rely on today. How would one do it with your proposed rewrite?

Q4: Taking a step back - it hasn't yet sunk in for me how moving to PURL in more places is related to being able to handle multiple majors. Doesn't SwiftPM have all the required information already today? I agree it's a good change, but is it really a prerequisite? Or is this just a good time to do both, since they touch the same area? (Not against it, just trying to understand.)

Q5: Will I be able to directly depend on two versions of one package? For example, there are large projects depending on grpc-swift (which had to duplicate their package to allow a v1 to v2 migration last year) that need to migrate majors incrementally, so it'd be good to be able to temporarily depend on both majors, move code over gradually, and as a final step remove the old major dependency.

Today some large packages are still using grpc-swift v1 because they simply can't afford to do an "atomic" update to v2 without a massive amount of risk (work + qualification) - that's why being able to migrate incrementally, over many PRs and releases, is a must-have, IMO. Otherwise folks will just have to create a dummy package to insert into their dependency graph to still get the ability to move between two majors in one package gradually, and that seems like unnecessary friction.

With a new major of Vapor coming up at some point, it'd be good to test-drive this new feature and show that the migration story is much easier than it was with grpc-swift.

Q6: Right, but the details always depend on the exact package, and can differ across the ecosystem quite a lot. Many important packages ship security patches for older majors for a long time. In fact, this feature will help speed up the ecosystem's migration to new (and more secure) majors, because it can be done incrementally (assuming the answer to Q5 is "yes"). So I think it's worth mentioning under the Security heading that multiple majors, if anything, should be a net-positive for security, not a net-negative (which it might look like initially, thinking that people will be able to stay on old majors and have no forcing function to move to the next major; but in fact, in practice, it's the opposite, as migrating to new majors will become easier, and fewer folks will stay on an old/unsupported major forever)

Q7: I think we should follow some other package managers and extend the definition of a "major" to not just the first component in a normal semantic version string, like 1.0.0, but also:

  • 0.x.y should treat "x" as a "major" here, so "0.1" vs "0.2" gets the same handling as "1" vs "2"
  • x.y.z-... versions should treat each "..." as a different major, so "1.0.0-alpha.1" is a different "major" than "1.0.0-alpha.2"

Without this, pre-1.0 packages, where many actual API breaks happen, won't be able to take advantage of this feature.

1 Like

This will be a great improvement, but I'm actually looking forward to what it may enable more.

First, completely isolated dependency subtrees. If I create an SDK, I would like to be able to use external dependencies, but any that I do will become part of every consumer's dependency tree. While this proposal lifts the requirement that their major versions match, my SDK would ideally have no impact on the project's other dependency resolution at all. That includes major, minor, and patch versions. The SDK's packages wouldn't even show up for use unless the user added their own declaration of the dependency.

Second, dynamic replacement without having to worry about source. Right now it's not really possible to replace (or perhaps just not easy?) a single package across the dependency tree with another version from another source. If PURLs are acting as fully unique IDs, could that mean we can finally declare one unique ID to replace another across the entire tree? This is trivial in other package managers, and even CocoaPods could do it, because you could just say you were replacing some ID with some other source (e.g. pod "Alamofire", :git => 'https://mysource...'. It would be nice to get that back.

This will be a great improvement regardless.

1 Like

Gotcha. I'll make this more clear in the proposal, thanks again!

1 Like

For sure! I do think it's worth discussing whether phasing this in could be beneficial, with the final goal having it be the default behaviour. If folks feel strongly enough about just making this default right out the gate, I'm definitely in support of that. Like you mention, the burden of having to know when to opt-in to such a feature shouldn't be passed onto the user at every transitive dependency migration.

It's entirely possible that the example PURLs here aren't entirely correct, however for the purposes of how SwiftPM may be modelling these identities internally through PubGrub may not in themselves be 100% in line the Swift PURL definition. The hope is that the final PURL for each resolved package should be a "correct" Swift PURL.

Wonderful question! The idea behind introducing PURLs was that since it contains much of the provenance data we would need for features like say, mirrors, the mapping heuristics of SwiftPM today (which are a bit hacky complex) would benefit greatly from this location data we can derive directly from a PURL. The qualifiers of a PURL offer the ability to denote whether a package is coming from a registry, source control, or even locally in your filesystem.

While not entirely planned out, I do feel strongly that PURLs will help a ton here.

Another good question :) It's true that SwiftPM doesn't necessarily require PURLs to make multiple majors work, however it touches the notion of being able to strongly identify packages in an easier way. This is particularly helpful during Pub Grub and the resulting package graph that comes from the decisions made in Pub Grub, whose nodes are driven by the PackageIdentity today. Rather than modifying an identity in-place to include a major version so that the graph's nodes aren't simply overridden by using the canonical and unchanged PackageIdentity (e.g. Foo would need to become Foo@v2, for example, to differentiate itself in the graph), PURLs all have a version property that can be used to differentiate a package Foo at 1.1.1 vs Foo at 2.1.1 much more easily.

Now, that's all explanation for how this would help with multiple majors, but as I alluded a little in the previous answer I think that this change would help greatly for other existing features in SwiftPM that require some identity mapping heuristics (mirrors, --replace-scm-with-registry, etc.). It would aggregate much of the metadata one would need to identify a very specific package without needing to rely so much on these existing heuristics, which in experience have been a bit difficult to deal with.

Overall, it's a change that would touch on various features in SwiftPM, both existing and prospective :smiley:

I was hoping this would be brought up for discussion! Initially I was unsure if I wanted to allow users to do this, but I'm also not familiar with what use-cases exist where someone would want this behaviour. I think you bring up a good point that allowing this flexibility would help package authors to migrate incrementally, and not whole-sale switching over to a new major version bump since that could be incredibly arduous all at once.

I see your point! I will update the security section.

This is a good point! I will add a section to look into this as well.

Thank you so much for your feedback! I hope I was able to answer some of your questions :smiley:

2 Likes

Sorry if I may have missed this discussion previously, but what is the developer experience when the same(ish) type from 2 different major versions of a transitive dependency interact?

Concretely, in your example setup from the pitch:

  FunPackage โ”€โ”€โ–บ fun-networking@1 (resolved to some v 1.x)
  FunPackage โ”€โ”€โ–บ fun-analytics โ”€โ”€โ–บ fun-networking@2 (resolved to some v 2.x)

Lets say the fun-networking package has a public currency type such as a FunDomainName or something like that. If fun-analytics exposes a public API that uses FunDomainName that FunPackage uses, FunPackage has both a FunDomainName type from fun-networking@1 and a FunDomainName type from fun-networking@2. Presumably they aren't the same type (module aliasing makes them declared in different modules even if the module names are the same, and due to the major version change properties may be different as well so the types aren't bitwise compatible anyways), but what happens when FunPackage ends up trying to use both types in the same context? Is there a clear diagnostic explaining why the types aren't compatible?

I ask since Foundation has often dealt with the "two Foundations" problem where during development we have a local copy of Foundation and a copy from the toolchain and ambiguity between the two modules with the same name can sometimes trigger compiler errors that are really had to reason about. I'm curious what the end experience looks like here now that two modules with the same name is becoming a feature and whether there's any diagnostic improvements on that front that should be part of the road map.

2 Likes

This is a great question! There will also need to be some rigorous testing done to uncover where all the pain points here might arise, and I do think that diagnostics would be a foundational way to at the very least inform developers of said incompatibility when it arises.

If I'm understanding correctly, there would have to be an explicit distinction between using FunNetworking_v1.FunDomainName vs FunNetworking_v2.DomainName and they would have to be treated as individual and different entities. If a consuming package is attempting to use both of these types, it would both have to be fully qualified (as depicted, and similar to how today if someone were to make use of a method named log present in two imported modules, users would have to make that declaration more specific with <Intended-Module>.log in their source file) and there would possibly need to be some transformation between types to successfully pass over information using one type to the other.

e.g.,

// ...
let fundomainv1 = FunNetworking_v1.FunDomain()

func doSomething(_ domain: FunNetworking_v2.FunDomain) { 
// ...
}

doSomething(fundomainv1) // ! this would cause an error, since it's expecting v2

// Consider this translation method:
func oldDomainToNewDomain(_ old: FunNetworking_v1.FunDomain) -> FunNetworking_v2.FunDomain { 
   var newDomain = FunNetworking_v2.FunDomain()
   newDomain.property1 = old.property1
   // ... etc.
   return newDomain
}

doSomething(oldDomainToNewDomain(fundomainv1)) // this should now be compatible
3 Likes

Thanks for the explanation! Yeah that's the situation that I was envisioning. So does this mean that while client code would typically name them both as FunNetworking.FunDomain, it's still possible to disambiguate by specifying FunNetworking_v1.FunDomain directly in source? If so I think that answers the question about what developers should do in this scenario (converting between the two types is the only plausible thing to do).

I'm still curious about what the developer experience is when that happens (can we make the ambiguity diagnostic call out how to disambiguate if it doesn't already? what happens when the ambiguity happens in one of your dependencies where you can't change the source code itself?) but that might be more of an implementation detail rather than a critical piece of the pitch.

1 Like

Correct -- in a pre-multiple majors world, FunNetworking.FunDomain would resolve to one symbol. With multiple majors (and considering the effects of module aliasing), it'll be possible for users to disambiguate by specifying via the major version-aliased module names (FunNetworking_v1 for FunNetworking @ v 1.x, for example, though the official naming for module aliasing these major versions is not yet 100% decided at the moment).

As for the developer experience, there is some discussions to be had about the impact of programatically introducing a module alias against the major versions as this would result in the modules themselves being fundamentally different.

E.g.

import FunNetworking_v1
import FunNetworking_v2

let domainv1 = FunNetworking_v1.FunDomain()
let domainv2 = FunNetworking_v2.FunDomain()

Would be an example source file for some root package looking to use the multiple major versions of FunNetworking. If one were to simply say import FunNetworking in this example, this would result in a diagnostic error stating that it is unable to find such a module, since it'll now be dealing with the aliased names.

Another good question! I'll certainly need to test against more complex package graph structures, however the hope is that if I've hooked up module aliasing correctly, the internal mapping SwiftPM tracks for transitive dependencies and how they refer to these symbols in their own source should hopefully not change.

To be more concrete, I've done some investigation on the module aliasing feature in SwiftPM and there are cases where, somewhere in a transitive dependency (let's call it MyLibrary) it refers to a dependency package Foo and its module FooModule by some aliased name (say, BarModule) in its own source. If FooModule is further alias upstream, as in some parent of MyLibrary decides to rename its alias BarModule to FooBarModule, this will not change the source of MyLibrary that knew this module as BarModule. A bit of a vague example here, but all this to say that this is how module aliasing works today and one can think of the programmatic addition to multiple majors as yet another "link" in this chain of aliases.

That said, there is undoubtedly an impact for the root package author and how it must now refer to these modules as described above, but I'll need to investigate this further and also determine how folks feel about that.

In cases where a user tries to import via the canonical name of the module (pre-aliasing), I think it would be useful to have a diagnostic informing developers of the multiple-major aliasing that has changed the naming here, and should list the available modules that they could be referring to while informing the user as to why these new names exist.

So, like the first example, rather than just being a diagnostic error saying that the module FunNetworking couldn't be found, I imagine some additional information about the fact that FunNetworking has multiple major versions resolved, and the available modules the user could be referring to would be one of FunNetworking_v1, FunNetworking_v2.

I'm ok with this being a short-term solution, but I feel it's not the correct long-term usability solution. From my opinion, package author enabling use of multiple major package versions should not require modifying their production source code. The tooling and feature should automatically handle this.

Most, if not all, package frameworks (e.g.: npm, maven) that currently support multiple version of a library do not require the developer to update the source code when a dependency resolves to multiple versions. In the long-term, Swift and SwiftPM should strive for the same developer experience.

1 Like

For sure, ultimately I'd like for the developer experience to not be so burdensome and have to rely on manual interjection for this to work.

It could be possible to introduce a mechanism for developers to decide how they'd like to refer to multiple major versions of a package (say, if some source file has explicit reason for wanting to use many versions for some incremental upgrade). The semantics of this would essentially be equivalent to a manual module alias today, but perhaps could be more explicit in the manifest (or otherwise).

Otherwise, in cases where a package does not require the use of multiple versions, I do believe there should be no changes to the source for a package who directly depends on a particular version of that package. There will need to be some testing for this case :smiley: