Skip to content

[Feature][Client] Add per-user cache location and distribution URL to Python SDK - #13402

Open
karthik-0306 wants to merge 3 commits into
apache:devfrom
karthik-0306:feature/python-sdk-distribution-cache
Open

karthik-0306 wants to merge 3 commits into
apache:devfrom
karthik-0306:feature/python-sdk-distribution-cache

Conversation

@karthik-0306

@karthik-0306 karthik-0306 commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Purpose of this pull request

Related to #12707 (pip-installable SeaTunnel launcher).

This PR contributes step 1 of the launcher roadmap on #12707 to Apache SeaTunnel: a per-user, per-version cache location and deterministic distribution URL construction. As agreed with @SEZ9 and @DanielLeens on #12707, it was opened only after #12858 merged, and it is kept strictly to those two pieces. It adds tools/seatunnel-python-sdk/seatunnel/distribution.py with two functions:

  • cache_dir(version) returns the directory that holds one SeaTunnel version for the current user. It only computes the path and never creates it.
  • distribution_url(version, base_url=DEFAULT_BASE_URL) returns the URL of the binary distribution archive of a release, for example https://downloads.apache.org/seatunnel/3.0.0/apache-seatunnel-3.0.0-bin.tar.gz.

Behaviour:

  1. Cache location per platform:

    • Linux: $XDG_CACHE_HOME/seatunnel/<version>, or ~/.cache/seatunnel/<version>
    • macOS: ~/Library/Caches/seatunnel/<version>
    • Windows: %LOCALAPPDATA%\seatunnel\<version>, or ~\AppData\Local\seatunnel\<version> when LOCALAPPDATA is not set

    A relative XDG_CACHE_HOME / LOCALAPPDATA, or one that resolves to the filesystem root, is ignored and the home directory is used instead. If the home directory cannot be resolved (~ returned unchanged) or resolves to the filesystem root (HOME=/ or HOME="", which would give every such user the same /.cache), DistributionError is raised and the message names the variable to set for the platform. The result is always an absolute path.

  2. Version validation: a version must start with a digit, end with a letter or digit, and may only contain A-Z a-z 0-9 . _ -. A version can never name a folder outside the cache (.., ../x, a/b) or a Windows device name (nul, con, com1), and 3.0. and 3.0 stay apart on Windows, which drops a trailing dot from folder names. Whitespace around the version is dropped.

  3. Deterministic URL: <base_url>/<version>/apache-seatunnel-<version>-bin.tar.gz, built without network access. The .sha512 checksum and the .asc signature are at the same URL with those suffixes, so the verification steps can reuse it.

  4. Base URL validation: base_url defaults to https://downloads.apache.org/seatunnel. downloads.apache.org only keeps current releases, and older ones move to https://archive.apache.org/dist/seatunnel, which a caller can pass instead. Surrounding whitespace and trailing slashes are dropped, and the result is built from the validated string. It must be an https:// URL with a host. It must not contain credentials, a query (?), a fragment (#, even with nothing after it), port 0 or a non-numeric port, [/] outside an IPv6 host, a malformed % escape, or spaces, control characters, non-ASCII characters or \. Parse errors from urlsplit are raised as DistributionError, and credentials are hidden in error messages.

  5. No side effects: the module creates no directory, writes no file, opens no network connection and downloads nothing.

Ownership boundary: cache_dir() is the per-user, per-version directory that the launcher owns, and it is the only location that later launcher helpers (download, extraction, plugin installation through install_plugins() from #12858) are allowed to modify. By default it is under the user's own cache directory, outside any source checkout, shared installation or site-packages, so installing or upgrading the Python package neither touches nor loses a downloaded distribution. The location follows the home directory and XDG_CACHE_HOME / LOCALAPPDATA. A value that resolves to the filesystem root is not used, but the location is not otherwise checked, so pointing those variables at a shared directory makes the cache shared too. This is stated in the module and cache_dir() docstrings.

Design note: the cache follows each platform's standard per-user cache location instead of a fixed ~/.seatunnel folder. A downloaded distribution can always be fetched again, so it belongs in the cache directory. Versions are case-sensitive in the URL, but Windows and macOS file systems usually are not, so 3.0.0-SNAPSHOT and 3.0.0-snapshot share one folder there, as the cache_dir() docstring notes. Left to later steps of #12707, as agreed there: the mirror environment variable, an explicit cache-location override (added with the step that first writes to the folder), gpg CLI vs. a Python dependency for signature checks, and the first target version.

Scope: two new files under tools/seatunnel-python-sdk. Standard library only, not exported from seatunnel/__init__.py. The engine, shell scripts and plugin_config are untouched. Usage docs will come with the launcher command.

Does this PR introduce any user-facing change?

No. It is an internal helper that nothing calls yet, and it is not part of the SDK's public API.

How was this patch tested?

Added 27 unit tests in tools/seatunnel-python-sdk/tests/test_distribution.py. They fake sys.platform, the home directory and the cache variables, so all platform branches run on any OS, with no network and no files written. They cover:

  • URL resolution: the exact URL for 3.0.0; deterministic; different versions give different URLs; whitespace around the version and the base URL is dropped; trailing slashes are ignored; valid versions (3, 2.3.9, 3.0.0-SNAPSHOT, 3.0.0-RC1); valid hosts and ports (DNS name, IPv4, IPv6, custom port, %20)
  • Invalid versions: .., ., ../x, -3.0.0, 3.0., 3.0-, 3.0/1, 3.0\1, spaces, ;, ?, #, v3.0.0, nul, con, aux, prn, com1, lpt1, None, non-string
  • Invalid base URLs: not HTTPS; no host (https://, https:///x, https://:443/x, https://user@/x); https://[::1/x; bad ports (abc, 99999, 0); credentials; query or fragment, including bare ? and #; embedded space, \n, \t, \r, \x00, \, non-ASCII; malformed % escapes; brackets in the path; non-string values. Error messages explain the problem and never show credentials.
  • Cache location: each platform's default; XDG_CACHE_HOME; LOCALAPPDATA; the Windows home fallback; relative or root cache variables ignored; home at the filesystem root raises; unresolved home raises and names the variable to set; a cache variable works without a home directory
  • Isolation: versions get sibling folders; users get folders under their own home; a version cannot name a folder outside the cache
  • No side effects: the path is absolute and the folder is not created

Results: all SDK tests pass on Linux (Python 3.9 and 3.10: 94 passed) and Windows (Python 3.11: 93 passed, 1 skipped; the skipped test is the POSIX-only lock test from #12858).

I also ran a randomized probe: about 180,000 malformed base URLs and 30,000 random versions across the linux, darwin and win32 branches, on Linux and Windows. It checks that only DistributionError is raised and that every accepted URL is HTTPS, has a host, has no query, fragment, credentials or whitespace, and ends in /<version>/apache-seatunnel-<version>-bin.tar.gz. It found no failures. On real Linux without mocks, HOME=/ and HOME="" raise the new error, and XDG_CACHE_HOME=/ falls back to ~/.cache.

To run the tests (from tools/seatunnel-python-sdk/):

python -m pytest tests/ -v

Check list

@SEZ9 SEZ9 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for working on this. I reviewed the latest head c7b8fb1d62a7.

What this PR fixes

  • User pain: the pip-installable launcher planned in #12707 has no agreed place to keep a downloaded SeaTunnel distribution and no single definition of where a release archive lives, so later download/extract/plugin steps would otherwise invent paths or write into a source checkout, shared install or site-packages.
  • Fix approach: adds a pure, side-effect-free seatunnel/distribution.py with cache_dir(version) ($XDG_CACHE_HOME or ~/.cache, ~/Library/Caches, %LOCALAPPDATA%, then seatunnel/<version>, absolute or DistributionError) and distribution_url(version, base_url=DEFAULT_BASE_URL) (https-only base plus /<version>/apache-seatunnel-<version>-bin.tar.gz), sharing one _VERSION_RE check, with 21 unittest cases.
  • One-line summary: self-contained module with no callers yet; the remaining gaps are in base_url validation and in how strongly the per-user isolation is worded compared with what the code enforces.

Runtime chain I rechecked

No production caller yet: grep of tools/seatunnel-python-sdk finds distribution_url / cache_dir / DistributionError only in distribution.py and tests/test_distribution.py; seatunnel/__init__.py:17-31 does not export them.

distribution_url(version, base_url)  tools/seatunnel-python-sdk/seatunnel/distribution.py:58
  -> _validate_version(version)  distribution.py:49   (strips, then full-matches _VERSION_RE; returns the stripped value)
  -> urlsplit(base_url)  distribution.py:78   (not guarded; can raise ValueError)
  -> scheme == "https", truthy netloc, falsy query and fragment  distribution.py:79-85
  -> f"{base_url.rstrip('/')}/{version}/apache-seatunnel-{version}-bin.tar.gz"  distribution.py:90   (built from the raw base_url, not from the parsed parts)

cache_dir(version)  distribution.py:112
  -> _cache_root()  distribution.py:93
       -> os.path.expanduser("~")  distribution.py:95   (POSIX: HOME="" or "/" yields "/"; no HOME and no passwd entry yields a literal "~")
       -> win32: LOCALAPPDATA or <home>/AppData/Local  distribution.py:96-97
       -> darwin: <home>/Library/Caches  distribution.py:98-99
       -> else: XDG_CACHE_HOME if absolute, otherwise <home>/.cache  distribution.py:102-104
       -> if not os.path.isabs(base): raise DistributionError  distribution.py:105-108
  -> os.path.join(_cache_root(), _validate_version(version))  distribution.py:126

Findings

Issue 1: distribution_url validates the parsed base_url but builds the result from the raw string, so whitespace and control characters pass validation and end up in the returned URL

  • Location: tools/seatunnel-python-sdk/seatunnel/distribution.py:90

  • Why it matters: Root cause: the checks at distribution.py:79-85 run on urlsplit(base_url), but the result at distribution.py:90 is built from the raw base_url. urlsplit cleans its input before parsing (it removes tab, CR and LF anywhere in the string, and current CPython releases also strip leading whitespace). The raw string keeps all of it.

  • Trailing whitespace: distribution_url("2.3.9", "https://archive.apache.org/dist/seatunnel/ ") passes every check. rstrip('/') removes nothing because the string ends with a space, so the result is https://archive.apache.org/dist/seatunnel/ /2.3.9/apache-seatunnel-2.3.9-bin.tar.gz.

  • Newlines and tabs: "https://x/seatunnel\n" behaves the same way, and an embedded tab, CR or LF also passes because urlsplit drops it before the checks see it.

  • The version is handled differently: _validate_version strips it and returns the stripped value (distribution.py:50-55), and test_surrounding_whitespace_in_version_is_dropped covers that. base_url has no equivalent.

  • Impact: nothing calls this yet, so no download is affected today. The PR description leaves a mirror environment variable to a later step, and that is where a value with a stray space or newline would come from. The caller would then get a malformed URL with nothing pointing back at the base URL.

  • Suggested fix: strip base_url the same way as the version, reject any remaining whitespace or control character, and build the result from the string that was actually validated. Please also add "https://x/seatunnel/ " and "https://x/seatunnel\n" to the base URL tests.

  • Evidence: tools/seatunnel-python-sdk/seatunnel/distribution.py:82 or not parts.netloc; tools/seatunnel-python-sdk/seatunnel/distribution.py:90 return f"{base_url.rstrip('/')}/{version}/apache-seatunnel-{version}-bin.tar.gz"; tools/seatunnel-python-sdk/tests/test_distribution.py:65 for base_url in ("http://downloads.apache.org/seatunnel", "ftp://x/y", "https://",

  • Suggested fix: The checks above run on urlsplit(base_url), but this line builds the result from the raw base_url, and the two can disagree:

  • distribution_url("2.3.9", "https://archive.apache.org/dist/seatunnel/ ") passes and returns .../dist/seatunnel/ /2.3.9/.... The version is stripped, the base URL is not, and rstrip('/') does not help once a space or newline follows the slash.

  • urlsplit removes tab, CR and LF before parsing, so "https://x/seatunnel\n" or a base URL with an embedded newline also passes while the raw string keeps the character.

Could you strip base_url like the version, reject any remaining whitespace or control character, and build the result from the validated value? Two extra entries in the base URL tests ("https://x/seatunnel/ " and "https://x/seatunnel\n") would pin it.

  • Priority: P1 — should fix in this PR
  • I traced this in the code.
  • When it happens: distribution_url("2.3.9", "https://archive.apache.org/dist/seatunnel/ ") returns https://archive.apache.org/dist/seatunnel/ /2.3.9/apache-seatunnel-2.3.9-bin.tar.gz instead of raising DistributionError. distribution_url("3.0.0", "https://downloads.apache.org/sea\ntunnel") returns a URL containing a raw newline. distribution_url("3.0.0", "https://:443/seatunnel") returns https://:443/seatunnel/3.0.0/apache-seatunnel-3.0.0-bin.tar.gz, which has no host.

Issue 2: A bare trailing ? or # in base_url passes the "no query or fragment" check, so the version, the archive name and the .sha512 / .asc suffixes all land in the query or fragment instead of the path

  • Location: tools/seatunnel-python-sdk/seatunnel/distribution.py:84
  • Why it matters: Root cause: distribution.py:83-84 test the truthiness of parts.query and parts.fragment. urlsplit returns an empty string for both when the delimiter is present with nothing after it, so the check cannot tell https://x/seatunnel from https://x/seatunnel#.
  • https://x/seatunnel# is accepted. rstrip('/') leaves the # in place, so the result is https://x/seatunnel#/3.0.0/apache-seatunnel-3.0.0-bin.tar.gz. HTTP clients do not send the fragment, so the request goes to https://x/seatunnel.
  • https://x/seatunnel? is accepted in the same way and yields https://x/seatunnel?/3.0.0/apache-seatunnel-3.0.0-bin.tar.gz, where the version and file name are a query string on the path /seatunnel.
  • The docstring says the checksum and signature are "at the same URL with a .sha512 or .asc suffix" (distribution.py:63-64). With a fragment, all three URLs resolve to one resource, so a later verification step compares a file against itself and fails with a confusing error.
  • Scope: I do not see an exploitable path. base_url is supplied by the caller, who could just as well pass a different https host, the module reads no environment variable, and nothing calls it yet. The issue is that the documented rule ("no query or fragment, so the archive, checksum and signature cannot be altered in transit", distribution.py:72-74) is stricter than what the code enforces.
  • Suggested fix: reject the delimiters on the raw string, for example "?" in base_url or "#" in base_url. Please add https://x/seatunnel# and https://x/seatunnel? to test_invalid_base_url_raises, which today only covers ?mirror=1 and #top.
  • Evidence: tools/seatunnel-python-sdk/seatunnel/distribution.py:84 or parts.fragment; tools/seatunnel-python-sdk/seatunnel/distribution.py:90 return f"{base_url.rstrip('/')}/{version}/apache-seatunnel-{version}-bin.tar.gz"; tools/seatunnel-python-sdk/tests/test_distribution.py:66 "https:///seatunnel", "https://x/seatunnel?mirror=1",
  • Suggested fix: parts.query and parts.fragment are empty strings when the delimiter is present with nothing after it, so https://x/seatunnel# and https://x/seatunnel? pass this check. The result is then https://x/seatunnel#/3.0.0/apache-seatunnel-3.0.0-bin.tar.gz: the version, the archive name and the .sha512 / .asc suffixes sit in the fragment (or query), and the fragment form sends all three requests to https://x/seatunnel.

I don't see a way to exploit this, since the caller controls base_url anyway and a later checksum step would fail rather than pass. It is still not what the docstring promises. Checking the raw string ("?" in base_url or "#" in base_url) closes it; could you also add both inputs to test_invalid_base_url_raises?

  • Priority: P1 — should fix in this PR
  • I traced this in the code.
  • When it happens: distribution_url("3.0.0", "https://x/seatunnel#") returns https://x/seatunnel#/3.0.0/apache-seatunnel-3.0.0-bin.tar.gz. The request target is https://x/seatunnel, and it is the same for the .sha512 and .asc suffixes. distribution_url("3.0.0", "https://x/seatunnel?") returns https://x/seatunnel?/3.0.0/apache-seatunnel-3.0.0-bin.tar.gz, with the version and file name in the query string. https://x/seatunnel/? behaves the same way. None of these raises DistributionError.

Issue 3: The "has a host" check uses netloc instead of hostname, and urlsplit can raise ValueError, so some invalid base URLs are accepted and others escape as a non-DistributionError

  • Location: tools/seatunnel-python-sdk/seatunnel/distribution.py:78
  • Why it matters: Root cause: parts.netloc is the raw authority string, not the host, and the urlsplit call at distribution.py:78 is not guarded.
  • Host-less authorities are accepted: for https://:443/seatunnel the netloc is :443, and for https://user@/seatunnel it is user@. Both are truthy while parts.hostname is None, so the function returns a URL with no host even though the docstring and the error message both require one.
  • A non-numeric port such as https://host:abc/seatunnel is also accepted, because parts.port is never read. Reading it would raise ValueError.
  • Wrong exception type: urlsplit("https://[::1/seatunnel") raises ValueError("Invalid IPv6 URL"). It is not caught, so the caller gets a ValueError although the docstring says :raises DistributionError: If the version or base URL is invalid (distribution.py:75).
  • Impact: limited to the helper's contract for now, since nothing calls it. A later download step that catches only DistributionError would show a traceback for a mistyped mirror URL, and a host-less URL would only fail once the HTTP client tries it.
  • Test gap: test_invalid_base_url_raises (test_distribution.py:65-68) covers https:// and https:///seatunnel, where the netloc is empty, but none of the cases above.
  • Suggested fix: wrap the parse in try/except ValueError and raise DistributionError, check parts.hostname instead of parts.netloc, and read parts.port inside the same try so a bad port is rejected too.
  • Evidence: tools/seatunnel-python-sdk/seatunnel/distribution.py:82 or not parts.netloc; tools/seatunnel-python-sdk/tests/test_distribution.py:65 for base_url in ("http://downloads.apache.org/seatunnel", "ftp://x/y", "https://",; tools/seatunnel-python-sdk/seatunnel/distribution.py:78 parts = urlsplit(base_url) if isinstance(base_url, str) else None
  • Suggested fix: Two gaps around this parse:
  1. urlsplit raises ValueError for inputs like https://[::1/seatunnel ("Invalid IPv6 URL"). It is not caught, so the caller gets a ValueError although the docstring promises DistributionError for an invalid base URL.
  2. not parts.netloc below does not prove there is a host: https://:443/seatunnel and https://user@/seatunnel have a non-empty netloc but parts.hostname is None. https://host:abc/seatunnel also passes because parts.port is never read.

Could you wrap the parse in try/except ValueError, check parts.hostname, and read parts.port inside the same try? Adding these four inputs to test_invalid_base_url_raises would cover it.

  • Priority: P1 — should fix in this PR
  • I traced this in the code.
  • When it happens: distribution_url("3.0.0", "https://[::1/seatunnel") raises ValueError: Invalid IPv6 URL, so a caller with except DistributionError does not catch it. distribution_url("3.0.0", "https://user@/seatunnel") returns https://user@/seatunnel/3.0.0/apache-seatunnel-3.0.0-bin.tar.gz. distribution_url("3.0.0", "https://host:abc/seatunnel") returns a URL with a non-numeric port.

Issue 4: HOME=/ or HOME="" resolves to a shared /.cache/seatunnel/<version> because _cache_root only checks that the base is absolute, and the launcher has no explicit way to relocate the cache

  • Location: tools/seatunnel-python-sdk/seatunnel/distribution.py:105
  • Why it matters: Root cause: _cache_root() only checks that the base is absolute (distribution.py:105). On POSIX, os.path.expanduser("~") returns / when HOME is / or the empty string. base then becomes /.cache, passes the check, and cache_dir("3.0.0") returns /.cache/seatunnel/3.0.0.
  • HOME=/ is a realistic value for containers that run with an arbitrary UID and for some service accounts. Every such user resolves to the same directory, which is the opposite of "two users never share or overwrite files" (distribution.py:115-116).
  • It matters for the later steps: plugin_installer rewrites config/plugin_config in place and tells callers to pass only a copy they own, "such as the launcher's per-user, per-version cache directory" (plugin_installer.py:18-21). A shared /.cache breaks that assumption without any error.
  • No override: Linux users can set XDG_CACHE_HOME, but on macOS the only input is HOME, and there is no launcher-specific parameter or variable for choosing the directory.
  • Suggested fix: treat a home directory that resolves to the filesystem root as "no per-user location" and raise DistributionError, and consider an explicit override (a parameter on cache_dir, or a variable handled by the launcher step). Either can wait for the PR that first writes to this directory, but the current behaviour should at least be covered by a test.
  • The docstring wording for the same guarantee is covered separately in PR13402-F6.
  • Evidence: tools/seatunnel-python-sdk/seatunnel/distribution.py:104 base = os.path.join(home, ".cache"); tools/seatunnel-python-sdk/seatunnel/distribution.py:105 if not os.path.isabs(base):; tools/seatunnel-python-sdk/seatunnel/distribution.py:20 this directory and nothing else. It is never inside a source checkout, a shared
  • Suggested fix: isabs is the only guard here, and it does not catch a home directory that resolves to the filesystem root. On POSIX os.path.expanduser("~") returns / when HOME is / or empty (arbitrary-UID containers, some service accounts), so this returns /.cache/seatunnel/<version> for every such user. That is a shared directory, and install_plugins() would later rewrite config/plugin_config inside it.

Could we raise DistributionError when the home fallback resolves to the root, and give the launcher an explicit way to choose the cache directory? On macOS there is currently no way to move it other than changing HOME.

  • Priority: P2 — optional
  • I traced this in the code.
  • When it happens: On Linux with HOME=/ (or HOME="") and XDG_CACHE_HOME unset, cache_dir("3.0.0") returns /.cache/seatunnel/3.0.0. Two different UIDs with that environment get the identical directory.

Issue 5: test_cache_dir_is_not_inside_the_installed_package depends on the real environment, and CI exercises the Windows/macOS branches only with a faked sys.platform on a POSIX os.path

  • Location: tools/seatunnel-python-sdk/tests/test_distribution.py:179
  • Why it matters: An earlier concern about this SDK, that no workflow ran tools/seatunnel-python-sdk/tests, no longer applies. .github/workflows/python-sdk.yml runs python -m pytest tests -v on ubuntu-24.04 with Python 3.9 and 3.13, so these tests do gate the PR. Two gaps remain.
  • Non-hermetic test: test_cache_dir_is_not_inside_the_installed_package (test_distribution.py:176-181) calls cache_dir("3.0.0") against the real platform and environment. It raises DistributionError when HOME is unset and the UID has no passwd entry, and its result depends on where XDG_CACHE_HOME points on the build host. It also only shows that this machine's environment is not inside the package directory; it does not show that the code prevents it.
  • Platform coverage: the workflow runs on Ubuntu only. The win32 and darwin branches are reached by patching distribution.sys.platform (test_distribution.py:87) while os.path.join and os.path.isabs remain the POSIX implementations. os.path.expanduser is also replaced with a fixed value (test_distribution.py:88), so its real edge cases (~ returned unchanged, /) are never exercised. Windows path semantics, such as what isabs accepts for a drive-letter path, are only covered by the author's local Windows run mentioned in the PR description.
  • Suggested fix: run the package-directory test under self._environment(...) with an explicit home so it is deterministic, or turn it into a test of a real guard if one is added. For the platform branches, either add windows-latest / macos-latest to the workflow matrix or state in the test comment that CI checks branch selection only.
  • Evidence: tools/seatunnel-python-sdk/tests/test_distribution.py:179 path = cache_dir("3.0.0"); tools/seatunnel-python-sdk/tests/test_distribution.py:87 stack.enter_context(mock.patch.object(distribution.sys, "platform", platform)); tools/seatunnel-python-sdk/tests/test_distribution.py:176 def test_cache_dir_is_not_inside_the_installed_package(self):
  • Suggested fix: This is the one test that reads the real platform and environment, which makes it non-hermetic. It raises DistributionError when HOME is unset and the UID has no passwd entry, and its result depends on where XDG_CACHE_HOME points on the build host. It also only shows that this machine's environment is not inside the package, not that the code prevents it.

Could you run it under self._environment(...) with an explicit home so the outcome is fixed? Separately, the SDK workflow runs on ubuntu-24.04 only, so the win32 / darwin cases above are checked with a faked sys.platform on a POSIX os.path. Adding a Windows and a macOS entry to the matrix, or a short note in the test saying that CI covers branch selection only, would make that explicit.

  • Priority: P2 — optional
  • I traced this in the code.
  • When it happens: From tools/seatunnel-python-sdk after pip install -e ., run XDG_CACHE_HOME=$PWD/.cache python -m pytest tests/test_distribution.py -k not_inside_the_installed_package. path is <sdk>/.cache/seatunnel/3.0.0, which starts with package_dir + os.sep, so the assertion at line 181 fails. Alternatively, run the test in a container with an arbitrary UID that has no passwd entry and with HOME unset: cache_dir raises DistributionError at line 179.

Issue 6: The docstrings state "never inside a source checkout or shared installation" and "two users never share" as guarantees, but the location is derived only from environment variables and nothing checks it

  • Location: tools/seatunnel-python-sdk/seatunnel/distribution.py:20
  • Why it matters: This is the documentation side of PR13402-F4: the wording is stronger than the code.
  • The module docstring says the cache directory "is never inside a source checkout, a shared installation or the Python package directory" (distribution.py:20-21), and cache_dir says "two versions or two users never share or overwrite files" (distribution.py:115-116).
  • The root comes entirely from HOME, XDG_CACHE_HOME or LOCALAPPDATA, and an absolute XDG_CACHE_HOME is used as-is (distribution.py:102-104). An XDG_CACHE_HOME that points into a CI workspace or checkout, a cache home shared by several service accounts, or sudo keeping the invoking user's HOME all produce a path that the docstring says cannot happen.
  • test_users_are_isolated_from_each_other only shows that two different faked home directories give two different paths, which is true by construction.
  • Why the wording matters: plugin_installer relies on exactly this boundary. Its docstring says to pass only a copy the caller owns, "such as the launcher's per-user, per-version cache directory", and never a source checkout or shared installation (plugin_installer.py:18-21). A reader of both modules will assume cache_dir() enforces that.
  • Suggested fix: describe this as the default behaviour rather than a guarantee, for example "by default this is under the user's cache directory; the location follows HOME / XDG_CACHE_HOME / LOCALAPPDATA and is not otherwise checked". If the guarantee is meant to hold, add the check in the step that first writes to the directory.
  • Evidence: tools/seatunnel-python-sdk/seatunnel/distribution.py:115 Each user and each version gets a separate directory, so two versions or two users never; tools/seatunnel-python-sdk/seatunnel/distribution.py:102 base = os.environ.get("XDG_CACHE_HOME", "")
  • Suggested fix: "It is never inside a source checkout, a shared installation ..." (and "two users never share" in cache_dir) reads as a guarantee, but the root is whatever HOME / XDG_CACHE_HOME / LOCALAPPDATA say. XDG_CACHE_HOME pointing into a CI workspace, a cache home shared by several service accounts, or sudo preserving HOME all break it. plugin_installer.install_plugins rewrites config/plugin_config in place and its docstring names this directory as the safe place to do that, so readers will take the sentence literally.

Could you either word it as the default ("by default under the user's cache directory; follows the environment and is not otherwise checked") or enforce it in the step that first writes here?

  • Priority: P2 — optional
  • I traced this in the code.
  • When it happens: On Linux with XDG_CACHE_HOME=/work/seatunnel/.cache, where /work/seatunnel is a source checkout, cache_dir("3.0.0") returns /work/seatunnel/.cache/seatunnel/3.0.0, which is inside the checkout. With XDG_CACHE_HOME=/srv/cache exported for users A and B, both get /srv/cache/seatunnel/3.0.0.

Issue 7: _VERSION_RE reasons about Windows directory naming but still accepts reserved device names and case-variant versions that collapse to one directory while producing different URLs

  • Location: tools/seatunnel-python-sdk/seatunnel/distribution.py:42

  • Why it matters: Root cause: the comment at distribution.py:38-41 explains that the pattern exists because the version is used as a directory name, and it already handles the Windows trailing-dot rule. The pattern at distribution.py:42 still lets two other directory-name cases through.

  • Windows reserved device names: nul, con, aux, prn, com1 and lpt1 all match. cache_dir("nul") returns %LOCALAPPDATA%\seatunnel\nul, which Windows resolves to the NUL device rather than a directory.

  • Case folding: NTFS and default APFS are case-insensitive, so 3.0.0-SNAPSHOT and 3.0.0-snapshot map to the same cache directory, while distribution_url returns two different URLs for them. That breaks the one-version-one-directory assumption stated in cache_dir.

  • Impact is small, since real release versions do not look like this. It is worth closing because the pattern is the single place where the directory-name rules are written down.

  • Suggested fix: requiring the version to start with a digit (SeaTunnel versions such as 2.3.9 and 3.0.0-SNAPSHOT all do) removes every reserved device name with a one-character-class change, and the existing single-character test ("3") still passes. For case, either document that versions are case-sensitive in the URL but not necessarily on disk, or compare versions case-insensitively when the directory is later reused.

  • Evidence: tools/seatunnel-python-sdk/seatunnel/distribution.py:126 return os.path.join(_cache_root(), _validate_version(version)); tools/seatunnel-python-sdk/seatunnel/distribution.py:126 return os.path.join(_cache_root(), _validate_version(version))

  • Suggested fix: Since the comment above already handles the Windows trailing-dot rule, two more directory-name cases are worth closing here:

  • Reserved device names (nul, con, aux, prn, com1, lpt1) match this pattern, so cache_dir("nul") returns a path Windows resolves to a device rather than a folder.

  • NTFS and default APFS are case-insensitive, so 3.0.0-SNAPSHOT and 3.0.0-snapshot share one cache directory while distribution_url returns two different URLs.

Requiring a leading digit ([0-9] as the first character) would rule out all the device names, and every SeaTunnel version starts with one. For the case issue, a sentence in the cache_dir docstring is probably enough for now.

  • Priority: P2 — optional
  • I traced this in the code.
  • When it happens: With sys.platform == 'win32' and LOCALAPPDATA=C:\Users\a\AppData\Local: cache_dir('nul') returns C:\Users\a\AppData\Local\seatunnel\nul instead of raising DistributionError; that final component is a reserved DOS device name, not a creatable directory. cache_dir('3.0.0-SNAPSHOT') and cache_dir('3.0.0-snapshot') return ...\seatunnel\3.0.0-SNAPSHOT and ...\seatunnel\3.0.0-snapshot, the same NTFS directory, while distribution_url returns .../3.0.0-SNAPSHOT/apache-seatunnel-3.0.0-SNAPSHOT-bin.tar.gz and .../3.0.0-snapshot/apache-seatunnel-3.0.0-snapshot-bin.tar.gz.

Issue 8: _cache_root does not handle an unresolvable home directory explicitly, and the resulting error does not say which variable to fix

  • Location: tools/seatunnel-python-sdk/seatunnel/distribution.py:95
  • Why it matters: os.path.expanduser("~") does not fail when the home directory is unknown; it returns the literal "~" (distribution.py:95).
  • When it happens: on POSIX, when HOME is unset and the UID has no passwd entry (a container started with an arbitrary --user and a cleaned environment, or env -i). On Windows, when USERPROFILE and HOMEPATH are both missing and LOCALAPPDATA is empty (distribution.py:97).
  • What the user sees: base becomes ~/.cache and the final isabs guard raises Cannot determine a per-user cache location: '~/.cache' is not an absolute path. Raising is the right outcome, but it happens by accident of the generic guard, and the message does not explain that the home directory could not be resolved or that setting HOME (or XDG_CACHE_HOME on Linux, LOCALAPPDATA on Windows) fixes it.
  • The related case where HOME is empty and expanduser returns / is not caught at all; that one is covered in PR13402-F4.
  • Suggested fix: check the home fallback explicitly where it is used (the result of expanduser is still "~" or not absolute) and raise a DistributionError that names the variable to set for the current platform. Keep the check on the fallback path only, so an absolute XDG_CACHE_HOME or LOCALAPPDATA still works without a home directory. The existing _environment(..., home="~") helper can drive a test for it.
  • Evidence: tools/seatunnel-python-sdk/seatunnel/distribution.py:97 base = os.environ.get("LOCALAPPDATA") or os.path.join(home, "AppData", "Local"); tools/seatunnel-python-sdk/seatunnel/distribution.py:107 f"Cannot determine a per-user cache location: '{base}' is not an absolute path."
  • Suggested fix: os.path.expanduser("~") returns the literal "~" when the home directory cannot be resolved (HOME unset and no passwd entry for the UID, which happens in containers started with an arbitrary --user). The guard below then reports '~/.cache' is not an absolute path, which does not tell the user to set HOME or XDG_CACHE_HOME.

Could you check the home fallback explicitly and raise a DistributionError that names the variable to set on the current platform? Please keep it on the fallback path only, so an absolute XDG_CACHE_HOME / LOCALAPPDATA still works without a home directory. A test using _environment("linux", home="~") would cover it.

  • Priority: P2 — optional
  • I traced this in the code.
  • When it happens: (a) Linux, env -u HOME -u XDG_CACHE_HOME under a uid with no passwd entry (for example docker run --user 12345): cache_dir('3.0.0') raises DistributionError("Cannot determine a per-user cache location: '~/.cache' is not an absolute path."), with no hint to set HOME or XDG_CACHE_HOME. (b) Linux, HOME='' and XDG_CACHE_HOME unset: cache_dir('3.0.0') returns /.cache/seatunnel/3.0.0 without error.

Review conclusion

Conclusion: final approval remains pending on the previous comments

2. Remaining follow-ups

  • Issue 1: distribution_url validates the parsed base_url but builds the result from the raw string, so whitespace and control characters pass validation and end up in the returned URL
  • Issue 2: A bare trailing ? or # in base_url passes the "no query or fragment" check, so the version, the archive name and the .sha512 / .asc suffixes all land in the query or fragment instead of the path
  • Issue 3: The "has a host" check uses netloc instead of hostname, and urlsplit can raise ValueError, so some invalid base URLs are accepted and others escape as a non-DistributionError
  • Issue 4: HOME=/ or HOME="" resolves to a shared /.cache/seatunnel/<version> because _cache_root only checks that the base is absolute, and the launcher has no explicit way to relocate the cache
  • Issue 5: test_cache_dir_is_not_inside_the_installed_package depends on the real environment, and CI exercises the Windows/macOS branches only with a faked sys.platform on a POSIX os.path
  • Issue 6: The docstrings state "never inside a source checkout or shared installation" and "two users never share" as guarantees, but the location is derived only from environment variables and nothing checks it
  • Issue 7: _VERSION_RE reasons about Windows directory naming but still accepts reserved device names and case-variant versions that collapse to one directory while producing different URLs
  • Issue 8: _cache_root does not handle an unresolvable home directory explicitly, and the resulting error does not say which variable to fix

Thanks for the updates so far. Happy to discuss the remaining points.

@karthik-0306

Copy link
Copy Markdown
Contributor Author

Thanks @SEZ9 for the thorough review. All eight points are addressed in the new head; status per finding:

  • F1 fixed. The base URL is stripped like the version, validated, and the result is built from the validated string. Spaces, control characters, non-ASCII characters and \ anywhere in it are rejected. Tests: test_surrounding_whitespace_in_base_url_is_dropped (".../seatunnel/ ", "...\n"), test_invalid_base_url_raises (embedded space, \n, \t, \r, \x00, \, é).
  • F2 fixed. ? and # are rejected on the raw string, so a bare trailing delimiter fails too. Tests: https://x/seatunnel?, https://x/seatunnel#, https://x/seatunnel/? in test_invalid_base_url_raises.
  • F3 fixed. urlsplit, .hostname and .port run inside one try that converts ValueError to DistributionError; the host check uses hostname; port 0 and a non-numeric or out-of-range port are rejected. Credentials (user@, user:pw@) are rejected and redacted from error messages. Tests: https://[::1/seatunnel, https://:443/..., https://user@/..., https://host:abc/..., https://host:99999/..., https://host:0/..., plus test_credentials_are_not_shown_in_errors and test_valid_hosts_and_ports_are_accepted (IPv6, IPv4, custom port).
  • F4 fixed. A home directory or cache variable that resolves to the filesystem root is not used: XDG_CACHE_HOME=/ or LOCALAPPDATA=C:\ falls back to the home directory, and HOME=/ / HOME="" raises DistributionError. Tests: test_home_at_the_filesystem_root_raises, test_relative_or_root_cache_variable_is_ignored. I left the explicit override (parameter or launcher variable) to the PR that first writes to the directory, as you suggested.
  • F5 fixed. I removed the non-hermetic test; with F6 the docs no longer claim the location is checked against the package directory, so there is nothing real for it to test. TestCacheDir now has a comment saying CI checks branch selection with Linux path rules and that Windows path rules come from running the suite on Windows. I kept the workflow matrix unchanged in this PR; happy to add windows-latest / macos-latest in a separate CI PR if you'd like.
  • F6 fixed. The module and cache_dir docstrings now describe the location as the default under the user's cache directory, say it follows the home directory and XDG_CACHE_HOME (Linux) or LOCALAPPDATA (Windows) and is not otherwise checked, and that pointing those at a shared directory makes the cache shared. The base_url docs now list every rejected input, so docs and code match.
  • F7 fixed. A version must now start with a digit, which rules out nul, con, aux, prn, com1, lpt1, and the cache_dir docstring notes that 3.0.0-SNAPSHOT and 3.0.0-snapshot share one directory on case-insensitive file systems. Tests: device names and v3.0.0 in test_invalid_versions_raise; 3, 3.0.0-SNAPSHOT, 3.0.0-RC1 in test_valid_versions_are_accepted.
  • F8 fixed. The home fallback is checked explicitly (only when no usable cache variable is set), and the error names the variable to set for the platform: XDG_CACHE_HOME or HOME, HOME, or LOCALAPPDATA or USERPROFILE. Tests: test_unresolved_home_raises_and_names_the_variable_to_set (home "~"), test_cache_variable_works_without_a_home_directory.

While fixing these I also rejected invalid percent escapes (%zz, trailing %) and [/] outside an IPv6 host.

Verification: the SDK suite passes on Linux with Python 3.9 and 3.10 (94 passed) and on Windows with Python 3.11 (93 passed, 1 POSIX-only skip). I also ran a randomized probe (about 180,000 malformed base URLs and 30,000 random versions across the linux/darwin/win32 branches, on Linux and Windows) checking that only DistributionError is raised and that every accepted URL is https, has a host, has no query, fragment, credentials or whitespace, and ends in /<version>/apache-seatunnel-<version>-bin.tar.gz; it found no failures. On real Linux without mocks, HOME=/ and HOME="" raise the new error and XDG_CACHE_HOME=/ falls back to ~/.cache. The PR description is updated to match.

@DanielLeens DanielLeens 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.

Thanks for contributing to Apache SeaTunnel! I reviewed the complete current diff and traced the affected entry points, state changes, and failure paths. Details below should make the next steps concrete.

What Problem Does This PR Solve?

User pain point. The planned pip-installable launcher needs one documented cache location and one deterministic release-archive URL, rather than writing into an arbitrary installation or inventing paths in later steps.

Fix approach. Add pure cache_dir and distribution_url helpers, validate version/path inputs, normalize and validate HTTPS bases, and reject unresolved or filesystem-root home fallbacks.

One-sentence summary. The new module computes locations without performing downloads, creating directories, or changing existing launcher behavior.

Simple example. For version 2.3.9 and the ASF archive base, the helper returns the versioned apache-seatunnel-2.3.9-bin.tar.gz URL; an XDG cache root yields its seatunnel/2.3.9 subdirectory without creating it.

1. Code Change Review

1.1 Core Logic Analysis

tools/seatunnel-python-sdk/seatunnel/distribution.py:66-106 validates versions/base URLs; :109-134 builds the archive URL; :137-199 selects an absolute non-root cache base and appends the validated version. The other changed file is the unittest suite. Searches found no production caller yet; the module is installed within the existing seatunnel package by setup.py find_packages.

Before

New module: no distribution location helper exists in the base tree.

After

version = _validate_version(version)
url = _validate_base_url(base_url)
return f"{url}/{version}/apache-seatunnel-{version}-bin.tar.gz"

Key Findings

  • This is an additive helper layer; the current job-launch path does not call it yet.
  • Base validation now examines the normalized string used to build the result, rejects query/fragment delimiters, and converts parsing/port failures to DistributionError.
  • Cache lookup honors explicit usable cache roots before consulting home, and documents environment-controlled sharing and case-folding limits.
  • The old non-hermetic package-directory test was removed and the platform-test boundary is now explicit; no download or ownership-enforcement claim is made.

Complete Runtime Path

Future caller imports seatunnel.distribution (no production caller in this head)
  -> distribution_url(version, base_url) [distribution.py:109]
      -> _validate_version [66-72]
      -> _validate_base_url [75-106]: normalize -> character/percent check -> urlsplit/host/port -> credential rejection
      -> append version/archive to the validated base [132-134]
  -> cache_dir(version) [181-199]
      -> _cache_root [151-178]
          -> usable LOCALAPPDATA / XDG_CACHE_HOME, or platform home fallback
          -> reject unresolved, relative, or root fallback
          -> append seatunnel
      -> append validated version
No mkdir, HTTP request, extraction, installation, checkpoint or job-state mutation.

The reported need is real within the explicitly staged launcher roadmap, while normal SeaTunnel execution is unchanged. Version values cannot introduce slash-based traversal. Root/home checks occur only when needed, so a usable cache variable works without a resolvable home. The function computes an HTTPS location; actual release existence, ownership, signature verification, extraction safety and concurrency belong to the future downloading/writing step and are not proven here.

1.2 Compatibility Impact

Fully compatible. Additive Python module and exception only; existing SDK APIs, CLI defaults, configuration, protocols and serialized job data are unchanged. The new functions document accepted version/base values rather than altering a previously published helper.

1.3 Performance / Side-Effect Analysis

Only bounded string parsing, regex matching, environment lookup and path construction occur. There is no networking, persistent cache, lock, timer, retry, thread or open resource. Existing launcher operations and per-row processing are unaffected.

1.4 Error Handling and Logging

Invalid inputs consistently raise DistributionError for the covered parser/host/port cases, with actionable platform-variable guidance. Credential-bearing URL strings are redacted before inclusion in validation messages. Actual network/download errors cannot occur because this module performs no I/O.

No blocking issues found in the source changes. The CI and repository merge gates below are assessed separately.

2. Code Quality Assessment

2.1 Coding Standards

ASF headers are present. The module and public functions document scope, side effects, accepted values, platform behavior and limitations. Helper comments explain the Windows-name, malformed-escape, root-directory and environment-fallback constraints.

2.2 Test Coverage and Test Stability

The suite covers exact release URLs, custom bases, normalization, malformed authorities/ports, credentials, invalid versions, platform branch selection, root/unresolved fallback and no directory creation. The existing Python SDK workflow runs pytest on Ubuntu with Python 3.9 and 3.13. Its fake-platform tests do not constitute native Windows/macOS path validation; that boundary is explicitly documented, and the author’s reported Windows run is contributor evidence, not a run performed here.

Stability rating: Stable. tools/seatunnel-python-sdk/tests/test_distribution.py:157-167 scopes environment/platform/home patches with ExitStack; :275-282 uses TemporaryDirectory and checks that the helper creates no files. No asynchronous waits, real network calls, fixed ports, system-clock expectations, or leaked global patches were found. Native platform behavior remains the stated coverage limit.

Local verification: fetched and checked out seatunnel-review-13402 at the exact head; the complete git diff <base>...<head> file set matches GitHub Files changed (2 files). git diff --check exit code: 0. The full two-file diff was read. rg traced every helper reference, setup.py package discovery and the Python SDK workflow matrix; no production caller was found. No Python module/test was executed locally. Compilation, unit tests, IT/E2E, packaging, Docker, and PR runtime execution were not run locally, as requested. Runtime evidence is limited to the linked exact-head GitHub CI snapshot.

2.3 Documentation Updates

Public/module docstrings now state the default cache ownership boundary, environment-controlled sharing, case-insensitive filesystem caveat, current-versus-archive ASF hosts, and no-I/O scope. No existing user-facing CLI option or en/zh launcher guide changes because this step does not wire a launcher command. Both language guides should be updated when that command first exposes these choices.

3. Architectural Soundness

3.1 Elegance of the Solution

Long-term solution. A pure distribution-location module is the appropriate foundation for later download/extraction steps and keeps those side effects outside these helpers.

Change-location assessment

Current and best responsibility boundary: seatunnel.distribution. There is no runtime fault to relocate. Putting this in plugin_installer or the HTTP downloader would mix location policy with mutation or transport. The smallest safe deliverable and best current design coincide: pure helpers with explicit limits. Stronger ownership, locking and signature guarantees should be implemented and tested in the first step that writes, rather than asserted by a path-returning function.

3.2 Maintainability

Normalization/validation is centralized, and the raised error identifies the input contract or environment fallback. The native-platform test limit is stated rather than hidden.

3.3 Extensibility

Later download, extraction and plugin-install steps can consume the same location policy without duplicating it.

3.4 Historical-Version Compatibility

No existing caller or serialized state changes. No migration or incompatible-change entry is needed for this additive, currently uncalled module.

4. Issue Summary

No formal source issues. See the separate CI/merge-gate assessment below.

Completeness check: all changed files, affected call chains, configuration/serialization and compatibility boundaries, error paths, changed tests, documentation/examples, community reviews, and CI/conflict/review gates were inspected. This is static source review, not runtime acceptance.

5. Merge Recommendation

Conclusion: Ready to merge after fixes

  1. Blockers — must be fixed
  • No source blocker.

CI gate: the reviewed head has successful Python 3.9 and Python 3.13 checks; the aggregate Build was still in progress in the inspected snapshot. Final merge waits for its completed exact-head result and the write-maintainer review gate. No source patch is requested merely to chase a pending check.

Snapshot: head 1cfe3e9fe8204a4f970e4251a8990303c5d61373, base dev at a76348f1f98953444fd030fbbc56209d8ad40d18. Compare: ahead, ahead_by=2, behind_by=0; GitHub merge state blocked, review decision REVIEW_REQUIRED. Daniel has READ repository permission; this technical review does not clear any write-maintainer approval or dismissal requirement.

  1. Recommended fixes — non-blocking
  • None beyond the explicit validation limits above.

Community review reconciliation: +1 to @SEZ9’s earlier input-contract and environment-isolation review. I reconciled all eight points against the full new head: normalized URL construction, raw delimiter rejection, guarded hostname/port parsing, root-home rejection, hermetic tests with explicit platform limits, qualified ownership wording, leading-digit versions with documented case folding, and actionable unresolved-home guidance. They are addressed as described above, so I am not duplicating them as new numbered issues. SEZ9’s review was tied to the previous head, not this one.

Overall assessment and alternatives: No blocking source issues found in this scoped, side-effect-free step. The remaining action is completed exact-head CI and maintainer review; wiring a downloader or adding broad filesystem ownership policy here would expand the agreed scope.

@karthik-0306

Copy link
Copy Markdown
Contributor Author

Thanks @DanielLeens for the full review and for reconciling all eight points against the new head. I'll keep the head unchanged while the Build check finishes and @SEZ9 takes another look.

@DanielLeens

Copy link
Copy Markdown
Contributor

Thanks for confirming! The reviewed head is unchanged. The exact-head fork Build is still queued in the current snapshot, so there is no further source change requested from my side. Please keep this focused while that run completes and @SEZ9 reviews the updated contracts. My source-clear conclusion is separate from the required write-capable maintainer approval.

@zhangshenghang

Copy link
Copy Markdown
Member

Thanks for keeping this on top of #12858 and limited to location calculation. I ran the 27 distribution unit tests from 1cfe3e9f on Python 3.12; all passed. The Apache Python SDK workflow is green on that head too. Please validate the write boundary for custom cache roots when the later download/extraction PR starts writing there.

@DanielLeens

Copy link
Copy Markdown
Contributor

Thanks for the additional validation and for keeping the boundary explicit. The green Python SDK workflow and your 27-test run support the location-only change; I am not presenting your local run as my own execution. I agree that the later downloader/extractor must validate writes under custom cache roots when it starts creating files. That write-boundary work is outside this read-only location calculation. No new source request from me on this unchanged head; the fork Build and effective maintainer approval remain separate gates.

@SEZ9 SEZ9 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for the follow-up. I checked the latest changes at 1cfe3e9fe820 against my previous review comments.

The scope of this pass is limited to the findings from the previous review; it does not introduce a new set of review items.

What this PR fixes

The commits since the previous review change only tools/seatunnel-python-sdk/seatunnel/distribution.py and tools/seatunnel-python-sdk/tests/test_distribution.py. The module is still a pure location calculator: it creates no directory, opens no connection and downloads nothing. No other code under tools/ calls cache_dir or distribution_url yet, so existing launcher behavior is unaffected.

Base URL validation moved into _validate_base_url, the version rule was tightened to require a leading digit, and cache-root selection now goes through _usable_dir. Validating writes under a custom cache root belongs to the later download/extraction change that first writes there, as already noted in the discussion.

Runtime chain I rechecked

`distribution_url(version, base_url)` -> `_validate_version` (strip, `_VERSION_RE.fullmatch`) -> `_validate_base_url` (strip, character whitelist, percent-escape check, `urlsplit` with `ValueError` converted to `DistributionError`, then scheme / hostname / credentials / bracket / port checks, `rstrip("/")`) -> `f"{url}/{version}/apache-seatunnel-{version}-bin.tar.gz"`.

`cache_dir(version)` -> `_cache_root()` (per platform: `_usable_dir(LOCALAPPDATA)` on Windows, no variable on macOS, `_usable_dir(XDG_CACHE_HOME)` on Linux; when that gives nothing, `os.path.expanduser("~")` is checked by `_usable_dir` and either joined with the platform fallback or rejected with a `DistributionError` naming the variables to set) -> `os.path.join(root, "seatunnel", _validate_version(version))`.

Resolved previous findings

  • PR13402-F1 distribution_url validates the parsed base_url but builds the result from the raw string, so whitespace and control characters pass validation and end up in the returned URL
  • PR13402-F2 A bare trailing ? or # in base_url passes the "no query or fragment" check, so the version, the archive name and the .sha512 / .asc suffixes all land in the query or fragment instead of the path
  • PR13402-F3 The "has a host" check uses netloc instead of hostname, and urlsplit can raise ValueError, so some invalid base URLs are accepted and others escape as a non-DistributionError
  • PR13402-F4 HOME=/ or HOME="" resolves to a shared /.cache/seatunnel/<version> because _cache_root only checks that the base is absolute, and the launcher has no explicit way to relocate the cache
  • PR13402-F5 test_cache_dir_is_not_inside_the_installed_package depends on the real environment, and CI exercises the Windows/macOS branches only with a faked sys.platform on a POSIX os.path
  • PR13402-F6 The docstrings state "never inside a source checkout or shared installation" and "two users never share" as guarantees, but the location is derived only from environment variables and nothing checks it
  • PR13402-F7 _VERSION_RE reasons about Windows directory naming but still accepts reserved device names and case-variant versions that collapse to one directory while producing different URLs
  • PR13402-F8 _cache_root does not handle an unresolvable home directory explicitly, and the resulting error does not say which variable to fix

Review conclusion

Conclusion: verification is incomplete; approval is not ready

Nice work — the previous concerns are addressed. Thanks again for the contribution.

@DanielLeens

Copy link
Copy Markdown
Contributor

Thanks, @SEZ9 — that matches the source-level conclusion of my full review on this head: the location calculator remains side-effect-free, and the earlier input/environment concerns were reconciled there.

The CI fact has changed since my pending-Build note: fork Build45140313334 has completed as cancelled, while the Apache bridge reports TIMED_OUT. Its 97-job manifest has no failed job, but four lanes were cancelled: transform-v2-it-part-2 on JDK11/17, all-connectors-it-7/JDK11, and LocalFile/JDK11. The two Python checks attached to the PR are successful. Please rerun the cancelled lanes on this head and let them complete; no unrelated downloader, dependency or filesystem-ownership patch is indicated by a cancellation.

My source conclusion is unchanged. Completed applicable CI and effective maintainer approval remain the next gates.

This is a discussion/CI follow-up on unchanged head 1cfe3e9fe8204a4f970e4251a8990303c5d61373, not a fresh full source review. No local build, test or SeaTunnel runtime execution was performed.

@DanielLeens DanielLeens 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.

Thanks for the update! I re-reviewed both complete new files, the SDK package/call sites and all eight earlier review points. I agree with @SEZ9's resolution of those concerns. The current module is a location calculator only; I found no remaining source blocker within that boundary.

What problem does this PR solve?

User pain: Later launcher download/extraction/plugin steps need a consistent distribution URL and cache location instead of inventing paths or modifying an installed package.

Fix: Add pure per-version URL and platform cache-location helpers with explicit validation/error contracts.

In one sentence: Compute where a release should come from and where a caller-owned cached copy should live, without downloading or writing it yet.

1. Code changes

1.1 Core logic

Complete runtime path:

No production caller in this SDK yet: only the two function declarations occur in the source search
Future caller -> distribution_url -> normalized safe version segment
 -> strip base URL -> character/percent validation -> urlsplit hostname/port checks
 -> HTTPS/no userinfo/no query/fragment -> append version/archive name
Future caller -> cache_dir -> platform cache variable or home fallback
 -> usable absolute non-root path -> seatunnel/version -> return string
No mkdir, network request, archive extraction, signature verification or plugin mutation occurs

Key findings and correctness:

Both full files and source-call searches were read. The validated normalized base string is used in the result; embedded controls/whitespace, raw query/fragment delimiters, malformed percent escapes, malformed ports/hostless authorities and userinfo are rejected. Parse failures become DistributionError and recognized userinfo is redacted. Version starts with a digit and ends alphanumeric, excluding traversal separators, Windows device names and trailing-dot aliases. Cache selection uses host os.path rules and rejects lexical filesystem roots/relative overrides, falling back to home only when needed. Unknown home is diagnosed with the variable to set. This does not validate ownership, realpath/symlinks or custom-root write safety, and the current docstrings correctly avoid claiming that it does. Case-insensitive filesystem aliasing is explicitly disclosed. Examples distinguish the current-download mirror from the archive root. A future writer must establish the actual write boundary rather than treating a computed path as permission to modify it.

Before:


After:

#  Licensed to the Apache Software Foundation (ASF) under one or more
#  contributor license agreements.  See the NOTICE file distributed with
#  this work for additional information regarding copyright ownership.
#  The ASF licenses this file to You under the Apache License, Version 2.0
#  (the "License"); you may not use this file except in compliance with
#  the License.  You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

"""Locate the per-user cache of a SeaTunnel distribution and build its download URL.

Ownership boundary: :func:`cache_dir` is the per-user, per-version directory that the
launcher owns. Later launcher steps (download, extraction, plugin installation) may modify
this directory and nothing else. By default it is under the user's own cache directory,
outside any source checkout, shared installation or the Python package directory
(``site-packages``), so installing or upgrading the Python package neither touches nor loses
a downloaded distribution. The location follows the user's home directory and
``XDG_CACHE_HOME`` (Linux) or ``LOCALAPPDATA`` (Windows); a relative value or one that
resolves to the filesystem root is not used, but the location is not otherwise checked, so
pointing those at a shared directory makes the cache shared too.

This module only computes locations. It creates no directory, opens no connection and
downloads nothing; those belong to later steps of
https://github.com/apache/seatunnel/issues/12707.
"""

import os
import re
import sys
from typing import Optional
from urllib.parse import urlsplit

DEFAULT_BASE_URL = "https://downloads.apache.org/seatunnel"

_CACHE_DIR_NAME = "seatunnel"

# A release version is used as a URL path segment and as a directory name. It must start with
# a digit, as every SeaTunnel release does: that rules out "." and "..", which would let a
# version name a directory outside the cache, and the Windows device names such as "nul",
# "con" or "com1", which are not directories. It must end with a letter or digit, because
# Windows drops a trailing dot from directory names and "3.0." would share "3.0"'s directory.
_VERSION_RE = re.compile(r"[0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?")

# Characters allowed in a base URL: the RFC 3986 unreserved and reserved characters and "%",
# without "?" and "#". That excludes spaces, control characters, non-ASCII characters and "\",
# and keeps a query or fragment from swallowing the version and file name appended to it.
_BASE_URL_RE = re.compile(r"[A-Za-z0-9._~:/@!$&'()*+,;=%\[\]-]+")

# A "%" that does not start a two-digit hexadecimal escape such as "%20".

Exact-head CI and upstream check: Fork Build45642253620 ended CANCELLED and the Apache aggregate is FAILURE. I read all three failed child logs: all-connectors-6/J11 job139305817503 and Paimon/J17 job139305818861 stop at repeated wrapper HTTP429 then missing MavenWrapperMain; Kafka/J11 job139305818239 executes KafkaFormatIT.testFormatCompatibleTombstoneCheck and times out waiting for the SKIP tombstone consumer-group committed offset. Five other lanes are cancelled. These Java connector failures are outside this uncalled Python module; green Python checks do not replace them. Latest dev has no mvnw or KafkaFormatIT fixing delta establishing a sync cure; #13466 is proposed, not in the captured base. Preserve the failing links and complete the existing affected/cancelled checks after bootstrap availability or the relevant upstream correction; please do not add Java dependencies or speculative Kafka changes to this PR.

1.2 Compatibility

Fully compatible for the existing SDK: a new module with no production callers, no change to existing launcher APIs/options/defaults, engine protocols or persisted formats. The new helper contract intentionally accepts only documented version/base forms. It computes strings, so future cache-format/ownership changes still need their own compatibility review.

1.3 Performance and side effects

Pure string/regex/path parsing only: no network, directory creation, archive buffer, worker lock or retry. Input-length work is linear over caller-provided strings. Tests patch process-wide environment/platform only within synchronous scoped contexts; no background task observes a retained override.

1.4 Errors, logging, and findings

No new source-level blocker found. Exceptions must still reach the existing job failure path; this review does not substitute for current-head CI.

+1 to @SEZ9's latest source resolution: F1/F2 normalized/raw URL handling, F3 parser/host/port/exception contract, F4 root exclusion, F5 hermetic tests/platform-evidence limits, F6 truthful default/isolation wording, F7 version/device/case rules, and F8 explicit unresolved-home fallback are reflected in the latest code. These are resolved shared points, not new Daniel findings. Their remaining verification/approval qualification is consistent with the non-passing aggregate below; no maintainer approval is inferred.

2. Code quality

2.1 Conventions

Reviewed all changed files for license, imports, naming, core-method and state-field comments. No additional convention blocker found.

2.2 Test coverage and stability

Stability rating: Stable. Stable. Tests are pure and deterministic, patching platform/home/cache variables in scoped ExitStack contexts and restoring them on exit. The one temporary directory is owned by TemporaryDirectory and asserts no mutation. No download, port, sleep or timing assertion is used. URL cases cover invalid types, byte/control characters, raw delimiters, credentials, IPv4/IPv6/ports, percent escapes and valid single-character/release versions. Cache cases cover home/root/unresolved fallback and supported variable precedence. Linux CI exercising a mocked win32 branch does not execute Windows path semantics; the test comment acknowledges that native-platform coverage remains separate. Current Apache Python3.9/3.13 checks pass; no local tests were run.

2.3 Documentation

Module/function docstrings state ownership limits, supported environment variables, normalization, exceptions, current/archive mirror difference and case aliasing. Existing user commands do not change and no download feature is exposed by this patch, so EN/ZH operational guides need no new invocation yet. Document actual download/extraction ownership when those later steps are integrated.

3. Architecture

3.1 Change location

Keep pure URL/cache calculation separate from future directory ownership, download verification and extraction. This module establishes reusable inputs without pretending the later launcher work is implemented.

3.2 Maintainability

Keep the behavior, lifecycle ownership, and failure contract together. Keep pure URL/cache calculation separate from future directory ownership, download verification and extraction. This module establishes reusable inputs without pretending the later launcher work is implemented.

3.3 Extensibility

Prefer the existing component boundary and tests over unrelated shared abstractions.

3.4 Upgrade impact

Fully compatible for the existing SDK: a new module with no production callers, no change to existing launcher APIs/options/defaults, engine protocols or persisted formats. The new helper contract intentionally accepts only documented version/base forms. It computes strings, so future cache-format/ownership changes still need their own compatibility review.

4. Findings summary

Completeness check: All changed files and affected entry/failure paths were reviewed; configuration/serialization compatibility, test failure capability and stability, documentation/examples, change ownership, and current CI/conflict/review gates are covered above. No unreviewed source scope is claimed complete.

# Finding Location Severity
- No new source blocker found - -

5. Merge recommendation

Can merge once the recorded CI and repository gates are satisfied

Blocking items: No source blocker. Current-head CI and write-capable maintainer review remain independent requirements.

Non-blocking suggestions: None beyond the validation limits above.

Overall: the reviewed source path is coherent; no runtime acceptance is claimed beyond the actual CI result. Daniel has READ permission, so this COMMENT cannot dismiss historical requested changes or satisfy a write-capable maintainer approval gate.

CI and repository state: Signal pull request update: SUCCESS; Test with Python 3.9: SUCCESS; Test with Python 3.13: SUCCESS; Build: FAILURE; Build: cancelled. GitHub reports BLOCKED / REVIEW_REQUIRED.

Verification: Reviewed all changed files and the referenced call sites at d40dcbb7ef86eda99ce8a9fd66eaf9a8e5fedd3b against merge base bbeb327127fd174962f6560b4ff7d8ed1418bc54. git diff --check passed. I did not build, run tests, or execute SeaTunnel locally.

Review time: 2026-11-26T07:26:59.218293-05:00

Local evidence: git fetch obtained head d40dcbb7ef86eda99ce8a9fd66eaf9a8e5fedd3b; git merge-base returned bbeb327127fd174962f6560b4ff7d8ed1418bc54; git diff --stat reports 2 files changed, 484 insertions(+). git show and source searches were used for the entry points above. No local build, unit test, E2E, Docker run or service startup was executed.

This branch has not been deployed

No deployments
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.

4 participants