Skip to content

Fix parallel package installation - #5979

Merged
laurmaedje merged 17 commits into
typst:mainfrom
Andrew15-5:parallel-package-installation
Mar 11, 2025
Merged

laurmaedje merged 17 commits into
typst:mainfrom
Andrew15-5:parallel-package-installation

Conversation

@Andrew15-5

Copy link
Copy Markdown
Contributor

Attempt number 2, here we go...

Also removes the possibility of a broken package cache state.

Notes:

  • Which root download directory should be used?
  • Should it be relative to some other known Typst directory?
  • Should a user be able to override it?
  • If all downloads are successful, there will be an empty download directory somewhere.
  • If some downloads fail, there will be some amount of garbage that can accumulate over time unless user clears the cache directory.
  • There is a small concern about multiple downloads of the same package which can be fixed via lock files (which will add some complexity).

Cc: @laurmaedje, @tingerrr, @PgBiel

Fixes #2739.
Fixes #5935.

@tingerrr tingerrr left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Looks good so far, I'm thinking we may still need a lock file to ensure that non-atomic moves are actually finished before another process tries to access it.

Comment thread crates/typst-kit/src/package.rs Resolved
Comment thread crates/typst-kit/src/package.rs Resolved
Comment thread crates/typst-kit/src/package.rs Resolved
@tingerrr

tingerrr commented Mar 1, 2025

Copy link
Copy Markdown
Contributor
  • Which root download directory should be used?

I think typst/downloads is probably fine, but it's technically also for extraction. Using something like tempdir here would come with the benefit of auto cleanup by most operating system configurations. But this also implies a tempfs for most distros, which I think would remove the atomicity of the rename.

  • Should it be relative to some other known Typst directory?

Is it not already with it being in typst?

  • Should a user be able to override it?

Maybe, I don't see much of a point here, perhaps with an environment variable only.

  • If all downloads are successful, there will be an empty download directory somewhere.

No biggie.

  • If some downloads fail, there will be some amount of garbage that can accumulate over time unless user clears the cache directory.

We could give users the ability to gc this will a custom command like I suggested, something like typst util clean --package-cache --temp or so to select what to clean. See above for the tempdir thing, then we'd not need this.

  • There is a small concern about multiple downloads of the same package which can be fixed via lock files (which will add some complexity).

Laurenz said he doesn't mind too much if there's duplicate, competing work on the same package download. I think it's not much of a big deal, too.

Also removes the possibility of a broken package cache state.
@Andrew15-5
Andrew15-5 force-pushed the parallel-package-installation branch from fd9e7fe to 2aaf8a8 Compare March 1, 2025 21:30
@Andrew15-5

Copy link
Copy Markdown
Contributor Author
  • Which root download directory should be used?

I think typst/downloads is probably fine, but it's technically also for extraction.

It's technically only for extraction.

But this also implies a tempfs for most distros, which I think would remove the atomicity of the rename.

Perhaps.

  • Should it be relative to some other known Typst directory?

Is it not already with it being in typst?

It is already. It can be in the temp dir outside the "Typst cache dir".

  • Should a user be able to override it?

Maybe, I don't see much of a point here, perhaps with an environment variable only.

Yeah, with how much is already customizable it becomes more bloated to my eye, but if we started this trend, then we might as well continue delivering on the customizablity. But this also would depend on the final location of the download directory.

  • If some downloads fail, there will be some amount of garbage that can accumulate over time unless user clears the cache directory.

We could give users the ability to gc this will a custom command like I suggested, something like typst util clean --package-cache --temp or so to select what to clean. See above for the tempdir thing, then we'd not need this.

I'm impartial to this.

@PgBiel
PgBiel self-requested a review March 1, 2025 23:17
@laurmaedje

Copy link
Copy Markdown
Member

I don't want to add a new CLI command for clean up for now. Maybe we'll add one in the future or maybe we'll auto-cleanup the stuff somehow, but I don't want to commit to having it in the CLI interface.

@PgBiel PgBiel left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Overall, I have to admit I'm not too fond of this approach, but I'll leave some comments on its current state.

Comment thread crates/typst-kit/src/package.rs Resolved
Comment thread crates/typst-kit/src/package.rs Resolved
@tingerrr

tingerrr commented Mar 5, 2025

Copy link
Copy Markdown
Contributor

I've read up on the wall of text, and I've got a few comments.

I think we're definitely overthinking at this point. We can't really ensure that the src and dst are on the same file system, a user can simply replace one of the directories with a mount to an external drive, and we'd be none the wiser.

In my opinion, we should simply provide the users with the necessary documentation to fix up the rare error case in some form of FAQ. Approach 1 of PgBiel is also what I thought of while reading the discussion, it would at the very least reduce the possibility of accidentally putting the src and dst on different file systems. Would also be future-proof if we add other download/cache directories. But approach 2 would work just fine too, I reckon.

Let's talk about the edge cases, or more helpfully, their consequences when compiling:

  1. A file or directory is missing
  2. A file is corrupted (unexpected EOF in source files, images can't be decoded, etc.)
  3. Any of the above combined

All of these would occur exclusively inside a cached package (not a local package) if we assume corruption due to concurrent access or mid-operation crash. This could also be the case if the maintainer pushes a broken update, but I think it's safe to ignore this.

If/Once we have unique error codes for certain types of errors, we could very easily identify any of these issues. Meaning, if we run into these issues in a cached package, we can simply suggest clearing the package directory and re-download on the next compilation. Honestly, we can probably emit this diagnostic already. Compare the full paths with the package cache path when such an error occurs and emit the hint that it could be corrupted. Regardless, that should be a different PR and should not block this one.

@Andrew15-5

Copy link
Copy Markdown
Contributor Author

That honestly sounds like checksum without checksum. But also, since a general assumption that program's cache can be removed at any moment (by the program, or by the user) and nothing should break (removing that during compilation would be of course not ideal), I don't think that we should ask user to clean anything, if compiler can identify that its cache is broken, then who if not the compiler knows the best course of action to fix the problem. So I'll say that it can remove the corrupted package and re-download it (once). If anything, it can simply emit a warning that such thing happened and that it already have been taken care of.

@laurmaedje

Copy link
Copy Markdown
Member

I definitely agree that there's overthinking going on here.

I still don't understand how we expect the package cache to get broken in the first place. The only concurrent "write" access is the rename operation and does any mainstream file steam actually fail mid-operation here? I don't see how a file should go missing or corrupted. And if the compiler sees a bad source file, how should it know that it got broken somehow rather than just being a bad package? Especially a missing file might just be an error by the package author.

The only case I can see happening realistically is a user hitting Ctrl+C mid-unzipping. And the only consequence of that is a bit of wasted space in the randomly named directory in the cache.

@Andrew15-5

Copy link
Copy Markdown
Contributor Author

I still don't understand how we expect the package cache to get broken in the first place.

I don't know what to say except reread all the previous statements that describe how exactly it can happen.

As to corrupted vs. bad package, I guess we can't know for sure which one it is. Compiler can re-download the package once and if it still fails, then it's highly likely that it's a bad package. But a proper solution is checksum.

I actually didn't read the existing code carefully enough and now know that you do remove the failed extraction directory. So that's one mystery out of the way.

@PgBiel

PgBiel commented Mar 5, 2025

Copy link
Copy Markdown
Contributor

I disagree with the overthinking claims, given that, if we didn't want to handle edge cases, this PR wouldn't be open in the first place. We can always "not care" about the problem - but we chose to care, so let's think about it properly. Doing things in a rush and without proper consideration will just lead to the same issue being reopened in a different case. And it's essential Typst works well in most environments.

With that said, I'd say we can try the solution of downloading in the target directory into a .partial-v1.2.3-randomstring folder.

@laurmaedje

Copy link
Copy Markdown
Member

Maybe overthinking is the wrong term. It's more that we're going in circles a bit, with everybody kinda just repeating their arguments.

Now the "downloads" constant isn't required.
@Andrew15-5

Copy link
Copy Markdown
Contributor Author

I'm guessing we won't have any tests for this one?

Comment thread crates/typst-kit/src/package.rs Resolved
@tingerrr

tingerrr commented Mar 7, 2025

Copy link
Copy Markdown
Contributor

I'm guessing we won't have any tests for this one?

I don't think this is feasible to test.

This way, we auto-clean-up in all code paths, and possibly even on panic. Makes it a bit simpler conceptually.
Because the package directory was created immediately empty (before extraction), other Typst instances would already start using it and complain about missing `typst.toml`. The package directory must not exist until the rename takes place.

To simplify that, this commit moves the location of the temporary dir into the package subfolder so that it's a move to a direct sibling location.
@laurmaedje

Copy link
Copy Markdown
Member

I made a few changes:

  • The randomness dependency is now optional and guarded by the packages feature
  • Switched to fastrand because it's already in our dep tree and used by tempfile (which is the recommended successor to the deprecated tempdir crate)
  • Created a Tempdir struct to clean up on Drop instead of manually cleaning up in all code paths
  • Tidied things up a bit and reworded comments a bit
  • Most importantly, fixed a mistake that meant that Package installations interfer when multiple Typst instances are running #2739 was not actually fixed: The code created both the temporary directory and the final directory at the same time, before decompressing. This meant that a parallel Typst instance would already see the empty directory before it was populated and would complain about a missing typst.toml. The package directory must not exist until the rename takes place. To simplify that, my change moves the location of the temporary dir into the package subfolder so that it's a move to a direct sibling location.

From my side, this would be ready to merge now. I'll wait a bit to give you all a chance to take a look if you want.

Comment thread crates/typst-kit/src/package.rs Resolved
@Andrew15-5

Copy link
Copy Markdown
Contributor Author

PackageError::Other(Some(err)) already has a "failed to load package ({err})" format, by adding PackageError::Other(Some(eco_format!("{message} ({err})"))) on top, it makes the error (look like (this)), which I don't like, hence why I checked that at the beginning and used main error: {err} template instead (failed to load package (main error: {err})). Though I missed one spot, it looks like, but that's gone now anyway.

@Andrew15-5

Andrew15-5 commented Mar 11, 2025 •

Copy link
Copy Markdown
Contributor Author

Also, it looks like #[cold] doesn't really do that much (https://stackoverflow.com/a/73575594). Do you have benchmarks that prove that this marker will improve performance? I don't see the point in using that.

@Andrew15-5

Copy link
Copy Markdown
Contributor Author

And lastly, I think the Tempdir patch introduces too much stuff. Maybe the Drop candy is fine, but the rest can be removed:

patch
diff --git a/crates/typst-kit/src/package.rs b/crates/typst-kit/src/package.rs
index abfc66f8..4e2b3a93 100644
--- a/crates/typst-kit/src/package.rs
+++ b/crates/typst-kit/src/package.rs
@@ -219,7 +219,7 @@ impl PackageStorage {
         // Decompress the archive into the temporary directory.
         let decompressed = flate2::read::GzDecoder::new(data.as_slice());
         tar::Archive::new(decompressed)
-            .unpack(&tempdir)
+            .unpack(&tempdir.0)
             .map_err(|err| PackageError::MalformedArchive(Some(eco_format!("{err}"))))?;

         // When trying to move (i.e., `rename`) the directory from one place to
@@ -234,7 +234,7 @@ impl PackageStorage {
         // directory already existed in the first place. If situations with
         // broken packages still occur even with the rename safeguard, we might
         // consider more complex solutions like file locking or checksums.
-        match fs::rename(&tempdir, &package_dir) {
+        match fs::rename(&tempdir.0, &package_dir) {
             Ok(()) => Ok(()),
             Err(err) if err.kind() == io::ErrorKind::DirectoryNotEmpty => Ok(()),
             Err(err) => {
@@ -269,20 +269,6 @@ impl Drop for Tempdir {
     }
 }

-impl AsRef<Path> for Tempdir {
-    fn as_ref(&self) -> &Path {
-        self
-    }
-}
-
-impl Deref for Tempdir {
-    type Target = Path;
-
-    fn deref(&self) -> &Self::Target {
-        &self.0
-    }
-}
-
 /// Enriches an I/O error with a message and turns it into a
 /// `PackageError::Other`.
 #[cold]

I remember that working with Drop objects can be a real pain, as I discovered myself when the Drop was called without me even knowing it (so spent a lot of time debugging this). Not sure what was wrong, but that is why I don't like it that much.

@laurmaedje

Copy link
Copy Markdown
Member

PackageError::Other(Some(err)) already has a "failed to load package ({err})" format, by adding PackageError::Other(Some(eco_format!("{message} ({err})"))) on top, it makes the error (look like (this)), which I don't like, hence why I checked that at the beginning and used main error: {err} template instead (failed to load package (main error: {err})). Though I missed one spot, it looks like, but that's gone now anyway.

Changed.

Also, it looks like #[cold] doesn't really do that much (https://stackoverflow.com/a/73575594). Do you have benchmarks that prove that this marker will improve performance? I don't see the point in using that.

I don't have benchmarks, but I like it, it does not hurt, is used across the codebase, and I don't really wanna argue about it in this PR.

And lastly, I think the Tempdir patch introduces too much stuff. Maybe the Drop candy is fine, but the rest can be removed:

The Deref is unnecessary, but I think the AsRef is nice.

I remember that working with Drop objects can be a real pain, as I discovered myself when the Drop was called without me even knowing it (so spent a lot of time debugging this). Not sure what was wrong, but that is why I don't like it that much.

It's how tempdir/tempfile does it. I think it's fine.

@laurmaedje
laurmaedje enabled auto-merge March 11, 2025 20:12
@laurmaedje

Copy link
Copy Markdown
Member

Thanks for your work on this!

@laurmaedje
laurmaedje added this pull request to the merge queue Mar 11, 2025
@laurmaedje
laurmaedje removed this pull request from the merge queue due to a manual request Mar 11, 2025
@laurmaedje
laurmaedje enabled auto-merge March 11, 2025 20:17
Comment thread crates/typst-kit/src/package.rs Resolved
@laurmaedje
laurmaedje added this pull request to the merge queue Mar 11, 2025
@Andrew15-5

Copy link
Copy Markdown
Contributor Author

Great work everyone.

Merged via the queue into typst:main with commit 0214320 Mar 11, 2025
@Andrew15-5
Andrew15-5 deleted the parallel-package-installation branch March 11, 2025 20:34
hongjr03 pushed a commit to hongjr03/typst that referenced this pull request Apr 16, 2025
Dikluwe pushed a commit to Dikluwe/typst-crystalline that referenced this pull request Sep 12, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Terminating typst may leave package cache in broken state Package installations interfer when multiple Typst instances are running

4 participants