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

Add CurrentRepository() to Python runfiles library #16341

Closed
wants to merge 1 commit into from

Conversation

fmeum
Copy link
Collaborator

@fmeum fmeum commented Sep 26, 2022

runfiles.CurrentRepository() can be used to get the canonical name of
the Bazel repository containing the caller at runtime. This information
is required to look up runfiles while taking repository mappings into
account.

Work towards #16124

@fmeum fmeum marked this pull request as draft September 26, 2022 16:52
@fmeum fmeum changed the title Add CurrentRepository() to Python runfiles library WIP: Add CurrentRepository() to Python runfiles library Sep 26, 2022
@fmeum fmeum force-pushed the 16124-py-current-repository branch 4 times, most recently from 7589b6e to 067a535 Compare September 26, 2022 18:46
@fmeum fmeum marked this pull request as ready for review September 26, 2022 19:43
@fmeum fmeum changed the title WIP: Add CurrentRepository() to Python runfiles library Add CurrentRepository() to Python runfiles library Sep 26, 2022
@fmeum
Copy link
Collaborator Author

fmeum commented Sep 26, 2022

@Wyverald

@fmeum fmeum force-pushed the 16124-py-current-repository branch 2 times, most recently from 73ea8a1 to 42196a4 Compare September 26, 2022 21:37
@ShreeM01 ShreeM01 added team-Rules-Python Native rules for Python awaiting-review PR is awaiting review from an assigned reviewer team-ExternalDeps External dependency handling, remote repositiories, WORKSPACE file. and removed team-Rules-Python Native rules for Python labels Sep 26, 2022
@fmeum
Copy link
Collaborator Author

fmeum commented Sep 27, 2022

@rickeylev If you have time, I would be very interested in your feedback on this PR. A planned follow-up (see #16124 for more context) would be to make the repository mappings available to the runfiles library at runtime.

@rickeylev
Copy link
Contributor

My initial reaction to "how do I get runtime resources?" is to use importlib.resources

This is the first time I've seen this code, so this is a bit slow going.

@fmeum
Copy link
Collaborator Author

fmeum commented Sep 28, 2022

Generally speaking, this library is meant to solve a bootstrap problem for Python: When repository mappings are used, such as with Bzlmod, a repository with canonical, on-disk name "foo" may see another repo with canonical name "bar" as "my_bar". When "foo" wants to access files (be it data or Python files) from "bar", we first need to resolve "my_bar" to "bar". We will have the full repository mapping available at runtime soon (#16321) as a map with entries (foo, my_bar) -> bar. Crucially, we need the canonical name of the repository containing the current file to resolve any reference to repositories - that's where this PR comes in.

Once packages can be found in the runfiles tree, it shouldn't matter too much whether users rely on Rlocation or Python-specific ways of looking up resources. The nice thing about Rlocation is that it is available in a consistent way across programming languages and can also be used in subprocesses.

My initial reaction to "how do I get runtime resources?" is to use importlib.resources

Looking at https://stackoverflow.com/a/58941536/297261, it seems that resource access in Python is relatively fragmented. Is pkgutil.get_data a reasonable way too?

This is the first time I've seen this code, so this is a bit slow going.

No worries, I am specifically looking for someone not deep in the runfiles library issue to check that we aren't going in the wrong direction here.

@rickeylev
Copy link
Contributor

Looking at https://stackoverflow.com/a/58941536/297261, it seems that resource access in Python is relatively fragmented. Is pkgutil.get_data a reasonable way too?

importlib.resources is the modern thing and provides a unified API. As of Python 3.7, it should do most everything you want. For earlier versions, there's a mix of options; that SO post you found covers them. I think the important thing is to avoid the expensive distutils/setuptools library it mentions (it is, indeed expensive, as it causes every available import to happen, iirc).

importlib_resources (note the underscore, not dot) is a third party package that is a backport of importlib.resources for earlier versions of Python, but at this point, "earlier" isn't many. PyPI says it now only supports Python 3.7+.

Note that Python 3.6 and earlier are no longer supported; they're EOL and no longer available for download on e.g. Python.org. IMHO, I think it makes sense to consider that here; that if you want better runfiles lookup support, you need a newer language version.

For a moment, lets ignore earlier Python versions: For what case must you use this api instead of importlib.resources? I'm having trouble figuring that one out. The current code appears to restrict lookups such that it would be the same as what importlib.resources would consider.

A big reason to prefer importlib.resources is because it was created directly out of the need to abstract accessing data that is bundled with the application. So it doesn't make assumptions about e.g. the python code being physical files on disk in .py form. It leaves that up to the runtime to figure out (because a single-file executable that precompiles python sources to machine code has no such concept of any of that).

The nice thing about Rlocation is that it is available in a consistent way across programming languages and can also be used in subprocesses.

I've having trouble reconciling "consistent across processes" with what the code appears to do and my understanding of why it needs to do so. The code appears to make lookups context-dependent on the caller -- how is that consistent? It needs to do this because repo-mappings change the name of directories in the runfiles tree -- if the directory names change, how can a path be consistent between different repo-units?

This code seems to imply that a single process has multiple runfiles directories. But that is directly at odds with the fact that there's only one runfiles directory. So what am I missing?

I get the impression that what this is trying to do is make something like this work?

# repo(repoA)
# BUILD:
py_binary(name=a, data=[a.txt], deps=[@b//:b)

# a.py:
Rlocation("a.txt")
from b import b

# repo(repoB)
# BUILD
py_library(name=b, data=[b.txt])
# b.py:
Rlocation("b.txt")  # or should this be repoB/b.txt? Or something?

# bazel build //:a
# -> runfiles looks like
bazel-bin/a.runfiles
  repoA/a.py
  repoA/a.txt
  repoB/b.py
  repoB/b.txt

i.e. within b.py, Rlocation() calls resolve to just what's under repo=b. Within b.py, Rlocation() calls resolve to just what's under repo=a.

Is that correct? It's hard to tell because the added test is just of the CurrentRepository() function. It'd help my understanding if I had a concrete example for when, within the same process, the pre-existing logic fails.

tools/python/runfiles/runfiles.py Outdated Show resolved Hide resolved
tools/python/runfiles/runfiles.py Outdated Show resolved Hide resolved
tools/python/runfiles/runfiles.py Outdated Show resolved Hide resolved
@@ -106,6 +138,17 @@ def Create(env=None):
return None


def _FindPythonRunfilesRoot():
Copy link
Contributor

Choose a reason for hiding this comment

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

I'm very wary of re-implementing logic to find the runfiles. The logic to find it is very non-trivial in the stub template:

https://github.com/bazelbuild/bazel/blob/master/src/main/java/com/google/devtools/build/lib/bazel/rules/python/python_stub_template.txt

If you look at runfiles.py here, you see that the Create() function doesn't try to guess any of that -- it just expects someone to have set one of the RUNFILES_* env vars.

Actually, er -- this newly added logic looks completely independent of that? The self._python_runfiles_root is never actually used anywhere? Am I missing something?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

I added a comment explaining why I am using this logic: Essentially, we just want to know what was in sys.path[0] when the Python stub ran. If it's unlikely that a py_binary would modify sys.path[0] at runtime, I could just use that here. What do you think?

Copy link
Contributor

Choose a reason for hiding this comment

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

Modifying sys.path is not uncommon. There is no expectation that sys.path[0] points to anything in particular.

I think you meant say sys.argv? sys.argv can be futz'd with in various when run under coverage, debuggers, by tests, etc. If it was as simple as looking at sys.argv[0], then (1) you wouldn't see all the logic to try and figure out the runfiles directory in the stub startup, and (2) the code in here would just do it instead of forcing the caller to specify it.

Does this need to be a module level function? All access goes through an instance of the Runfiles class, which must be given the location of of the runfiles directory.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Runfiles libraries are given either the runfiles directory or the path of the runfiles manifest file and have to work with that. While the runfiles directory can be reverse engineered from the path of the runfiles manifest, that logic is non-trivial (hence the stub template) and may not work with --build_python_zip.

I found it both easier and more reliable to reverse engineer the Python runfiles directory from an actual Python file instead - after all, we know that the stub template set everything up for us as otherwise we wouldn't be running.

@Wyverald
Copy link
Member

The nice thing about Rlocation is that it is available in a consistent way across programming languages and can also be used in subprocesses.

I've having trouble reconciling "consistent across processes" with what the code appears to do and my understanding of why it needs to do so. The code appears to make lookups context-dependent on the caller -- how is that consistent?

By "consistent", Fabian likely meant "consistent across programming languages". The rlocation API is used to access runfiles at runtime for many languages that Bazel supports (C++, Java, Python, etc.), and they all work under the same premise -- I know Bazel has prepped a runfiles directory for me, now give me the file behind this path.

It needs to do this because repo-mappings change the name of directories in the runfiles tree -- if the directory names change, how can a path be consistent between different repo-units?

Repo mappings don't really change the name of directories in the runfiles tree. The names in the runfiles tree are the "canonical" names of the repos, and repo mappings allows you to refer to them with nicknames, if you will. If you think of a repo as a person, you could say every person has a canonical ID-card name (@@-prefixed), and every person could refer to another person with a different nickname (@-prefixed). The runfiles tree doesn't change; it always contains the canonical ID-card name.

(aside: without repo mapping, there is no difference between canonical names and nicknames. so everyone has to refer to everyone using their canonical name.)

This code seems to imply that a single process has multiple runfiles directories. But that is directly at odds with the fact that there's only one runfiles directory. So what am I missing?

There is only one runfiles directory. But code built into a binary could come from source code in different repositories; what code from @@foo~1.0 refers to as @bar might differ from what code from @@quux~2.0 refers to as @bar. That's why, when calling rlocation, we need to know who's calling -- is it @@foo~1.0 or @@quux~2.0?

I get the impression that what this is trying to do is make something like this work?

Yes, that's largely correct. Except that right now, the rlocation path always starts with the repo name (i.e. starts from the runfiles tree root), so instead of rlocation("b.txt"), you would say rlocation("repoB/b.txt") as you alluded to. What repo mapping does here, is that instead of saying rlocation("repoB/b.txt"), you would say rlocation("repoBs_nickname_for_itself/b.txt") -- that is, make it possible to use nicknames; and then the rlocation function would take CurrentRepository() to see who's calling (in this case repoB), and consult a dictionary to translate the "nickname" repoBs_nickname_for_itself to the canonical name repoB.

@rickeylev
Copy link
Contributor

rickeylev commented Sep 30, 2022

Ok, I think I understand, but I just don't see how this can be made to work.

Part of my point is, when a path is interpreted in a context-specific manner, it is no longer consistent across boundaries.

If code in a.py understands "nickname/data.txt" to mean one thing, while code in b.py understands it to mean another, then the same path-string can't be passed between them. Similar applies if you're trying to pass the string between different languages and process boundaries.

This is on top of the difficulty of correctly identify who is actually asking for the lookup. As control flow passes back and forth between modules, you might end up with a.py passing an a-path to b.py, which does the actual runfiles lookup, except it's going to interpret it as a b-path, because it's the closest caller to the runfiles-api-call.

I don't see how you can retain the existing API and still safely do what you want without also introducing confusing corner cases. The existing api is, essentially, "<canonical repo name>/<path to file within that repo>".

What if we introduce a qualifier? e.g. "@nickname/data.txt" ? That at least makes it clear that it's a nickname, and the path is context dependent. A resolve function might also be useful? (transforms the nickname into a canonical name)

Another question I have is: what if a nickname and canonical repo have the same name? How do you know whether to interpret "X/data.txt" as referring to the local X or the canonical repo named X?

@fmeum
Copy link
Collaborator Author

fmeum commented Sep 30, 2022

Ok, I think I understand, but I just don't see how this can be made to work.

Part of my point is, when a path is interpreted in a context-specific manner, it is no longer consistent across boundaries.

If code in a.py understands "nickname/data.txt" to mean one thing, while code in b.py understands it to mean another, then the same path-string can't be passed between them. Similar applies if you're trying to pass the string between different languages and process boundaries.

This is on top of the difficulty of correctly identify who is actually asking for the lookup. As control flow passes back and forth between modules, you might end up with a.py passing an a-path to b.py, which does the actual runfiles lookup, except it's going to interpret it as a b-path, because it's the closest caller to the runfiles-api-call.

My plan is to update the Rlocation function to accept an optional second parameter that allows passing in a canonical repository name as context. If that parameter isn't provided, it defaults to CurrentRepository(). In my experience, most runfiles lookups do not cross repo boundaries, so having this default should ease migration and be generally more user-friendly.

I don't see how you can retain the existing API and still safely do what you want without also introducing confusing corner cases. The existing api is, essentially, "/".

What if we introduce a qualifier? e.g. "@nickname/data.txt" ? That at least makes it clear that it's a nickname, and the path is context dependent. A resolve function might also be useful? (transforms the nickname into a canonical name)

With Bzlmod, the @@-canonical-ids are intentionally unwieldy and only ever used by generated code. They can also be distinguished from nicknames (e.g. they contain tildes, which nicknames never do). User code will only ever use nicknames, so I think there is little potential for confusion in real usage scenarios. 

Having a separate resolve function makes sense, I could add one when I implement the actual Rlocation function.

Another question I have is: what if a nickname and canonical repo have the same name? How do you know whether to interpret "X/data.txt" as referring to the local X or the canonical repo named X?

See above, collisions should not occur with Bzlmod. Non-Bzlmod repo mappings could collide in this way, but are very rarely used and will go away with WORKSPACE at some point.

@Wyverald
Copy link
Member

Part of my point is, when a path is interpreted in a context-specific manner, it is no longer consistent across boundaries.

Another question I have is: what if a nickname and canonical repo have the same name? How do you know whether to interpret "X/data.txt" as referring to the local X or the canonical repo named X?

This is the same situation that Bazel itself faces with labels. Labels can contain repo nicknames (@foo//:bar) and are often passed around as strings, but they need to be resolved in a context into a label with canonical repo names (ok I'm in @@myrepo~1.0 to whom @foo is a nickname for @@yourrepo~2.0 so let me translate that into @@yourrepo~2.0//:bar). This translation is often done across a string -> Label object type boundary, so if you get a Label object (instead of a raw string), you can rest assured that it's post-resolution.

Perhaps we can do the same with the runfiles libraries if the need arises.


With that said, AFAIK runfile lookups are usually done very locally (as in, often just Rlocation("some_string_literal") instead of Rlocation(some_string_variable_passed_in_from_somewhere_else)) -- @fmeum please correct me if I'm wrong about that. If that's the case, there's little opportunity for cross-repo contamination, so to speak.

@fmeum
Copy link
Collaborator Author

fmeum commented Sep 30, 2022

The only case I've encountered frequently where it's not just Rlocation(string_literal) is if the Rlocation path is passed in as an argument to a wrapper script (e.g. an sh_binary). Crossing repo boundaries wouldn't seem common in that case.

tools/python/runfiles/runfiles.py Outdated Show resolved Hide resolved
@@ -106,6 +138,17 @@ def Create(env=None):
return None


def _FindPythonRunfilesRoot():
Copy link
Contributor

Choose a reason for hiding this comment

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

Modifying sys.path is not uncommon. There is no expectation that sys.path[0] points to anything in particular.

I think you meant say sys.argv? sys.argv can be futz'd with in various when run under coverage, debuggers, by tests, etc. If it was as simple as looking at sys.argv[0], then (1) you wouldn't see all the logic to try and figure out the runfiles directory in the stub startup, and (2) the code in here would just do it instead of forcing the caller to specify it.

Does this need to be a module level function? All access goes through an instance of the Runfiles class, which must be given the location of of the runfiles directory.

from .runfiles_constants import MAIN_REPOSITORY_RUNFILES_DIRECTORY


def CurrentRepository(frame = 1):
Copy link
Contributor

Choose a reason for hiding this comment

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

I think it might make more sense for this to be a method on the Runfiles class instead of a module-level function. This is both more consistent with the existing code, avoids needing to try and compute the runfiles dir at the module scope, and will give you more flexibility in how lookups are performed.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Made it an instance method.

Comment on lines 84 to 85
# Converts all path separators to os.path.sep.
caller_runfiles_path = os.path.normpath(caller_runfiles_path)
Copy link
Contributor

Choose a reason for hiding this comment

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

This comment implies that caller_runfiles_path is getting non-native path separators? All these APIs are working with the native platform's file paths -- how are you seeing e.g. / on windows or \ on linux for the path separator?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

I was worried that Python file paths may end up using / also on Windows and that causing issues with the logic that checks for .. + path sep, but I guess that's unnecessary as inspect.getfile() should return a path appropriate for the current platform. Removed this line.

tools/python/runfiles/runfiles.py Outdated Show resolved Hide resolved
tools/python/runfiles/runfiles.py Outdated Show resolved Hide resolved
tools/python/runfiles/runfiles_constants.py Outdated Show resolved Hide resolved
@fmeum fmeum force-pushed the 16124-py-current-repository branch from 21380f0 to 184ee88 Compare October 4, 2022 12:13
@fmeum fmeum force-pushed the 16124-py-current-repository branch from 184ee88 to d0e3d02 Compare October 6, 2022 22:45
@fmeum
Copy link
Collaborator Author

fmeum commented Oct 11, 2022 via email

@fmeum fmeum requested a review from rickeylev October 12, 2022 10:21
@rickeylev
Copy link
Contributor

rickeylev commented Oct 13, 2022

Sorry, didn't see your response until just now. If you don't get a response from me within a day or two, please tag me in the thread or message me on bazel's slack; it's highly likely it got lost in my maelstromic void email inbox. I'll have a look now.

tools/python/runfiles/runfiles.py Outdated Show resolved Hide resolved
tools/python/runfiles/runfiles.py Outdated Show resolved Hide resolved
tools/python/runfiles/runfiles.py Outdated Show resolved Hide resolved
tools/python/runfiles/runfiles.py Outdated Show resolved Hide resolved
tools/python/runfiles/runfiles.py Outdated Show resolved Hide resolved
tools/python/runfiles/runfiles.py Outdated Show resolved Hide resolved
tools/python/runfiles/runfiles.py Outdated Show resolved Hide resolved
tools/python/runfiles/BUILD Outdated Show resolved Hide resolved
tools/python/gen_runfiles_constants.bzl Outdated Show resolved Hide resolved
@@ -114,6 +117,7 @@ class _Runfiles(object):

def __init__(self, strategy):
self._strategy = strategy
self._python_runfiles_root = _FindPythonRunfilesRoot()
Copy link
Contributor

Choose a reason for hiding this comment

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

Have the caller of the _Runfiles object pass the runfiles directory in as an argument. This avoids most of the issues with trying to re-find the runfiles directory.

In CreateDirectoryBased(), the path can be directly passed in.

In CreateManifestBased(), you can use the same logic the launcher itself uses, which is pretty simple:
https://cs.opensource.google/bazel/bazel/+/master:src/main/java/com/google/devtools/build/lib/bazel/rules/python/python_stub_template.txt;l=134-144;drc=c3425feeb3bc204923979773ae985dd2f3e24b9f

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Doing that leads to this test failure: https://storage.googleapis.com/bazel-untrusted-buildkite-artifacts/0183d34f-4545-4f97-933c-3164ea7a67b1/tools%5Cpython%5Crunfiles%5Crunfiles_test%5Ctest.log
Do you know whether there is a convenient way to handle UNC paths in Python?

Copy link
Contributor

Choose a reason for hiding this comment

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

Hm. I think you can simply strip of \\? and \\.. From the docs I've found, it looks like those are special "dos device paths" that refer to the current device, and the difference between \\? and \\. is something to do how windows does path normalization.

Or maybe check the manifest mapping for the caller's file? _ManifestBased._result has a runfile_path -> fs path mapping. If it can be found in there, it's not a big deal to maintain a reverse map.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Did that, but this is now hitting a more fundamental problem (see these logs): The Bazel runfiles root may very well be distinct from the Python runfiles root when using --build_python_zip. But the lookup of the current repository should always use the Python runfiles root.

The previous approach handled this distinction. Would you be okay with reverting to it?

Copy link
Contributor

Choose a reason for hiding this comment

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

But the lookup of the current repository should always use the Python runfiles root.

Ah, yeah, that's a good point.

How about just looking for ".runfiles" (or the other substrings for the other various cases) in the caller's file path?

I forget what the previous approach was. The module-level _FindRunfilesRoot() function, based upon sys.argv? I could accept that at this point. Not using sys.path, though.

That said, part of the point I'm trying to make here -- one that I'm not really convinced is landing -- is that there just isn't any good way to get the runfiles root after program startup. sys.argv isn't reliable because user code may change it, or it may point to a symlink that points elsewhere. Looking at the callstack is iffy because not all callers have a file, and a caller doesn't necessarily have to live in the runfiles. If we look at all the code surrounding "where is the runfiles root?" (i.e. here and the stub launcher), we see it's very non-trivial with many special cases.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Upfront: Thanks for being diligent and persisting through the review of this arguably weird PR! My situation is really just that we have to make runfiles work as well as possible with the drastic changes that Bzlmod necessarily brings for them. I know this is certainly not ideal and gets us into the fringe parts of the different languages - you don't want to know how we are planning to implement CurrentRepository in Java ;-)

How about just looking for ".runfiles" (or the other substrings for the other various cases) in the caller's file path?

I forget what the previous approach was. The module-level _FindRunfilesRoot() function, based upon sys.argv? I could accept that at this point. Not using sys.path, though.

I preserved it in the first commit: 4b87045#diff-21d70609ca9dc507b2d33f4a68d89bca3cd727191ffe3a6319b63c36e750deb2R215

It's quite similar to scanning for .runfiles in the scripts own file path, but slightly more precise since we just know the suffix we need to strip.

That said, part of the point I'm trying to make here -- one that I'm not really convinced is landing -- is that there just isn't any good way to get the runfiles root after program startup. sys.argv isn't reliable because user code may change it, or it may point to a symlink that points elsewhere. Looking at the callstack is iffy because not all callers have a file, and a caller doesn't necessarily have to live in the runfiles. If we look at all the code surrounding "where is the runfiles root?" (i.e. here and the stub launcher), we see it's very non-trivial with many special cases.

I do think that it is important to consider the following two aspects of this PR separately. Doing that will also help me understand your point better:

  1. Finding the Python runfiles root:
    I don't yet see why this should be difficult: The script at bazel_tools/tools/py/runfiles/runfiles.py is an honest Python file and it lies under the runfiles root because the launcher either found the Bazel runfiles directory with this file in the known relative location or set up a runfiles-like directory by extracting the ZIP. Deriving the root from that requires neither sys.argv nor sys.path, we just strip a suffix from this one particular file's path.
    This is important because if this part of the runfiles library isn't reliable, the library can't really be used at all.

  2. Using that information to derive the Bazel repository containing the caller:
    This is where we invoke a lot of magic that may break in a myriad of ways: It requires investigating the call stack, assumes that the caller is a file, assumes that it lies in the runfiles root, and so on.
    Luckily for us, if this magic procedure breaks from a particular location, it's not too bad: It just means that users can't look up their Bazel context from that particular location. Assuming they want to use runfiles, they will likely find some more well-behaved place in their program where the lookup is successful and then pass the repo name on to code that can then call Rlocation without any further magic involved.

Does this assessment agree with what you are thinking?

Copy link
Contributor

Choose a reason for hiding this comment

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

I preserved it in the first commit: 4b87045#diff-21d70609ca9dc507b2d33f4a68d89bca3cd727191ffe3a6319b63c36e750deb2R215

It's quite similar to scanning for .runfiles in the scripts own file path, but slightly more precise since we just know the suffix we need to strip.

Yes, lets just go with that.

  1. Finding the Python runfiles root: I don't yet see why this should be difficult

It's difficult because (1) the precise layout of the Python side of runfiles is an implementation detail, and (2) Python itself doesn't have an equivalent concept as Bazel's runfiles directory.

The proposed usage of __file__ assumes the layout is <root>/<repo>/<path>, but a layout such as e.g. <root>/site-packages/<libname>/<path> works just as well as far as Python code is concerned.

The __file__ attribute is also optional, so whether it works also depends on how the runfiles library was imported, and the particular details of any custom importer.

Stated another way: this runfiles library is only usable for a particular implementation of the Python rules and resulting layout of the files in runfiles. While this may sound innocuous at face value, as a language rule owner, its very unappealing because it means anyone using this runfiles library breaks when we want to change the language rule implementation. Except a user doesn't see "the runfiles library was relying on implementation details", they just see "the language rules changed and broke me".

  1. Using that information to derive the Bazel repository containing the caller:
    This is where we invoke a lot of magic that may break in a myriad of ways: It requires investigating the call stack, assumes that the caller is a file, assumes that it lies in the runfiles root, and so on.
    Luckily for us, if this magic procedure breaks from a particular location, it's not too bad: It just means that users can't look up their Bazel context from that particular location. Assuming they want to use runfiles, they will likely find some more well-behaved place in their program where the lookup is successful and then pass the repo name on to code that can then call Rlocation without any further magic involved.

I consider the "they can just pick another location to call their code" assumption a weak one. It assumes the person who picks the path is also the one that calls the runfiles APIs. This assumption breaks down because people like to build libraries. For example, a Django plugin that inherently understood runfiles. Such a case has a user specifying paths, while the actual runfiles API call is done by e.g. django code.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Yes, lets just go with that.

I dropped the last commit, so we are now back to this.

Stated another way: this runfiles library is only usable for a particular implementation of the Python rules and resulting layout of the files in runfiles. While this may sound innocuous at face value, as a language rule owner, its very unappealing because it means anyone using this runfiles library breaks when we want to change the language rule implementation. Except a user doesn't see "the runfiles library was relying on implementation details", they just see "the language rules changed and broke me".

I agree that's not a good situation, in particular because you didn't ask for this feature. I can at least promise that if you ever want to change the runfiles layout used by the Python rules, you can ping me and I will adapt this library as needed.

As long as the runfiles library remains coupled to the source of truth for the python rules, such breakages should at least be detected by the test I added. If anybody copies the runfiles library somewhere other than @bazel_tools//tools/runfiles/python and imports them in a different way without making the necessary changes, they would be on their own.

I consider the "they can just pick another location to call their code" assumption a weak one. It assumes the person who picks the path is also the one that calls the runfiles APIs. This assumption breaks down because people like to build libraries. For example, a Django plugin that inherently understood runfiles. Such a case has a user specifying paths, while the actual runfiles API call is done by e.g. django code.

I think that the hypothetical Django plugin could, similar to how Rlocation will be adapated, receive an optional repository name argument that, if provided, is used as context instead of the magic CurrentRepository(). That would again put the user in control.

@rickeylev
Copy link
Contributor

update the Rlocation function to accept an optional second
parameter that allows passing in a canonical repository name as context.

Another idea I just thought of to this problem is allowing a Runfiles instance to be "bound" to a particular repository context. e.g.

rf = runfiles.Create(repo="bazel_tools")
rf.Rlocation(...) # all lookups happen assuming the bazel_tools repo context.

Then you never have to worry about who is calling Rlocation, and code using runfiles doesn't have to carry around an extra optional "repo" arg just in case someone needs to explicitly give the repo.

@fmeum fmeum force-pushed the 16124-py-current-repository branch 4 times, most recently from 7ffe6f5 to 8ce75e2 Compare October 13, 2022 21:45
runfiles the caller is located to determine which repository it came from.
This may fail or produce incorrect results depending on who the caller is.
Use the `frame` argument to control the stack lookup, or pre-resolve the
repository via other means, for example by passing it in from Starlark, to
Copy link
Contributor

Choose a reason for hiding this comment

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

"by passing it in from starlark" -- how is one supposed to do this?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

One could pass in Label.workspace_name (sic, this should really be called repository_name) via an argument or environment variable.

I would rather have people

  1. try calling this function from somewhere else if they are doing something "interesting" on the Python side.
  2. file an issue so we learn about this.

Would you be fine me changing this comment to say that?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Do you happen to have an example of a situation in which you would expect this to fail? If we can't think of any, we should maybe tell users to file issues directly.

Copy link
Contributor

Choose a reason for hiding this comment

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

To clarify, I'm not asking for any changes here. I was just asking a question. I wasn't aware of Label.workspace_name previously.

The main thing I'm after here is that the doc clearly says it has known limitations and what those limitations are. You shouldn't have to do a deep dive of source code to diagnose an error when you're providing apparently valid inputs, only to find out your inputs aren't actually valid but fall into some known but undocumented edge case.

I'm fine with the two doc changes you suggested.

Do you happen to have an example of a situation in which you would expect this to fail?

The main case that comes to mind is whenever inspect.getfile() would fail, likely due to getframe() ending up in some builtin (i.e. C) function somehow.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

I added a note saying that this could for example fail if the caller isn't represented by a Python source file and removed the part about Starlark. Rather than passing in repository names, in edge cases it would be better to pass in entire runfiles paths. I will make sure to document that possibility when I update the Rlocation function.

@fmeum fmeum force-pushed the 16124-py-current-repository branch 2 times, most recently from 12dda9a to 859ace2 Compare October 14, 2022 08:45
@fmeum fmeum force-pushed the 16124-py-current-repository branch 2 times, most recently from a3d9abf to 4b87045 Compare October 19, 2022 18:13
`runfiles.CurrentRepository()` can be used to get the canonical name of
the Bazel repository containing the caller at runtime. This information
is required to look up runfiles while taking repository mappings into
account.
@fmeum fmeum force-pushed the 16124-py-current-repository branch from 4b87045 to 5a7149b Compare October 19, 2022 18:22
@Wyverald Wyverald added awaiting-PR-merge PR has been approved by a reviewer and is ready to be merge internally and removed awaiting-review PR is awaiting review from an assigned reviewer labels Oct 20, 2022
@fmeum fmeum deleted the 16124-py-current-repository branch October 24, 2022 16:31
@sgowroji sgowroji removed the awaiting-PR-merge PR has been approved by a reviewer and is ready to be merge internally label Oct 26, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
team-ExternalDeps External dependency handling, remote repositiories, WORKSPACE file.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants