Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

refactor(tasks): split local package dependency resolver (#90774)

posthog[bot]d4d1f8668dee
diff --git a/products/tasks/backend/logic/services/local_packages.py b/products/tasks/backend/logic/services/local_packages.py
index 2ee70c13ed8d..f7b493655aaf 100644
--- a/products/tasks/backend/logic/services/local_packages.py
+++ b/products/tasks/backend/logic/services/local_packages.py
@@ -80,75 +80,99 @@ def get_local_posthog_code_packages() -> tuple[LocalPackage, ...] | None:
return packages
+def _read_manifest_dependencies(manifest_path: Path) -> dict[str, str]:
+ """Read and validate the `dependencies` object from a package manifest."""
+ manifest = json.loads(manifest_path.read_text())
+ package_dependencies = manifest.get("dependencies", {})
+ if not isinstance(package_dependencies, dict):
+ raise ValueError(f"Expected dependencies to be an object in {manifest_path}")
+ for name, version in package_dependencies.items():
+ if not isinstance(name, str) or not isinstance(version, str):
+ raise ValueError(f"Expected dependency names and versions to be strings in {manifest_path}")
+ return package_dependencies
+
+
+def _find_workspace_manifest(source_path: Path) -> Path | None:
+ """Find the nearest pnpm-workspace.yaml above a package source path."""
+ return next(
+ (
+ parent / "pnpm-workspace.yaml"
+ for parent in source_path.parents
+ if (parent / "pnpm-workspace.yaml").is_file()
+ ),
+ None,
+ )
+
+
+def _load_workspace_catalogs(workspace_manifest_path: Path) -> tuple[dict[str, str], dict[str, dict[str, str]]]:
+ """Read and validate the default catalog and named catalogs from a workspace manifest."""
+ workspace_manifest = yaml.safe_load(workspace_manifest_path.read_text())
+ catalog = workspace_manifest.get("catalog", {}) if isinstance(workspace_manifest, dict) else None
+ catalogs = workspace_manifest.get("catalogs", {}) if isinstance(workspace_manifest, dict) else None
+ if not isinstance(catalog, dict) or not all(
+ isinstance(catalog_name, str) and isinstance(catalog_version, str)
+ for catalog_name, catalog_version in catalog.items()
+ ):
+ raise ValueError(f"Expected catalog to contain string dependencies in {workspace_manifest_path}")
+ if not isinstance(catalogs, dict) or not all(
+ isinstance(catalog_name, str)
+ and isinstance(named_catalog, dict)
+ and all(
+ isinstance(dependency_name, str) and isinstance(dependency_version, str)
+ for dependency_name, dependency_version in named_catalog.items()
+ )
+ for catalog_name, named_catalog in catalogs.items()
+ ):
+ raise ValueError(f"Expected catalogs to contain named string dependencies in {workspace_manifest_path}")
+ return catalog, catalogs
+
+
+def _resolve_catalog_dependency(
+ package: LocalPackage,
+ manifest_path: Path,
+ name: str,
+ version: str,
+ catalog_cache: dict[Path, tuple[dict[str, str], dict[str, dict[str, str]]]],
+) -> str:
+ """Resolve a `catalog:` dependency version from the workspace catalogs."""
+ workspace_manifest_path = _find_workspace_manifest(package.source_path)
+ if workspace_manifest_path is None:
+ raise ValueError(f"Could not resolve catalog dependency {name} from {manifest_path}")
+
+ if workspace_manifest_path not in catalog_cache:
+ catalog_cache[workspace_manifest_path] = _load_workspace_catalogs(workspace_manifest_path)
+ catalog, catalogs = catalog_cache[workspace_manifest_path]
+
+ catalog_reference = version.removeprefix("catalog:")
+ if catalog_reference in {"", "*"}:
+ selected_catalog = catalog
+ else:
+ named_catalog = catalogs.get(catalog_reference)
+ if named_catalog is None:
+ raise ValueError(f"Catalog {catalog_reference} is missing from {workspace_manifest_path}")
+ selected_catalog = named_catalog
+
+ resolved_version = selected_catalog.get(name)
+ if resolved_version is None:
+ raise ValueError(f"Catalog dependency {name} is missing from {workspace_manifest_path}")
+ return resolved_version
+
+
def get_local_package_runtime_dependencies(packages: tuple[LocalPackage, ...]) -> dict[str, dict[str, str]]:
"""Collect registry dependencies needed by the overlaid local package builds."""
dependencies: dict[str, dict[str, str]] = {}
- dependency_catalogs: dict[Path, tuple[dict[str, str], dict[str, dict[str, str]]]] = {}
+ catalog_cache: dict[Path, tuple[dict[str, str], dict[str, dict[str, str]]]] = {}
for package in packages:
manifest_path = package.source_path / "package.json"
- manifest = json.loads(manifest_path.read_text())
- package_dependencies = manifest.get("dependencies", {})
- if not isinstance(package_dependencies, dict):
- raise ValueError(f"Expected dependencies to be an object in {manifest_path}")
+ package_dependencies = _read_manifest_dependencies(manifest_path)
runtime_dependencies: dict[str, str] = {}
for name, version in package_dependencies.items():
- if not isinstance(name, str) or not isinstance(version, str):
- raise ValueError(f"Expected dependency names and versions to be strings in {manifest_path}")
if version.startswith("workspace:"):
continue
if version.startswith("catalog:"):
- workspace_manifest_path = next(
- (
- parent / "pnpm-workspace.yaml"
- for parent in package.source_path.parents
- if (parent / "pnpm-workspace.yaml").is_file()
- ),
- None,
- )
- if workspace_manifest_path is None:
- raise ValueError(f"Could not resolve catalog dependency {name} from {manifest_path}")
-
- if workspace_manifest_path not in dependency_catalogs:
- workspace_manifest = yaml.safe_load(workspace_manifest_path.read_text())
- catalog = workspace_manifest.get("catalog", {}) if isinstance(workspace_manifest, dict) else None
- catalogs = workspace_manifest.get("catalogs", {}) if isinstance(workspace_manifest, dict) else None
- if not isinstance(catalog, dict) or not all(
- isinstance(catalog_name, str) and isinstance(catalog_version, str)
- for catalog_name, catalog_version in catalog.items()
- ):
- raise ValueError(
- f"Expected catalog to contain string dependencies in {workspace_manifest_path}"
- )
- if not isinstance(catalogs, dict) or not all(
- isinstance(catalog_name, str)
- and isinstance(named_catalog, dict)
- and all(
- isinstance(dependency_name, str) and isinstance(dependency_version, str)
- for dependency_name, dependency_version in named_catalog.items()
- )
- for catalog_name, named_catalog in catalogs.items()
- ):
- raise ValueError(
- f"Expected catalogs to contain named string dependencies in {workspace_manifest_path}"
- )
- dependency_catalogs[workspace_manifest_path] = (catalog, catalogs)
-
- catalog, catalogs = dependency_catalogs[workspace_manifest_path]
- catalog_reference = version.removeprefix("catalog:")
- if catalog_reference in {"", "*"}:
- selected_catalog = catalog
- else:
- named_catalog = catalogs.get(catalog_reference)
- if named_catalog is None:
- raise ValueError(f"Catalog {catalog_reference} is missing from {workspace_manifest_path}")
- selected_catalog = named_catalog
-
- resolved_version = selected_catalog.get(name)
- if resolved_version is None:
- raise ValueError(f"Catalog dependency {name} is missing from {workspace_manifest_path}")
- version = resolved_version
+ version = _resolve_catalog_dependency(package, manifest_path, name, version, catalog_cache)
runtime_dependencies[name] = version
if runtime_dependencies:
diff --git a/products/tasks/backend/logic/services/tests/test_local_packages.py b/products/tasks/backend/logic/services/tests/test_local_packages.py
index 944634707c68..2c2d42cdd4ba 100644
--- a/products/tasks/backend/logic/services/tests/test_local_packages.py
+++ b/products/tasks/backend/logic/services/tests/test_local_packages.py
@@ -103,3 +103,30 @@ def test_resolves_default_catalog_runtime_dependencies(fake_monorepo: Path) -> N
"star-catalog-runtime": "2.3.4",
}
}
+
+
+def test_keeps_registry_versions_and_skips_workspace_dependencies(fake_monorepo: Path) -> None:
+ agent_source_path = fake_monorepo / "packages" / "agent"
+ (agent_source_path / "package.json").write_text(
+ '{"dependencies":{"registry-runtime":"^4.5.6","local-runtime":"workspace:*"}}'
+ )
+ package = LocalPackage(
+ name="agent",
+ source_path=agent_source_path,
+ sandbox_install_path="/scripts/node_modules/@posthog/agent",
+ )
+
+ assert get_local_package_runtime_dependencies((package,)) == {"agent": {"registry-runtime": "^4.5.6"}}
+
+
+def test_rejects_manifest_with_non_object_dependencies(fake_monorepo: Path) -> None:
+ agent_source_path = fake_monorepo / "packages" / "agent"
+ (agent_source_path / "package.json").write_text('{"dependencies":["registry-runtime"]}')
+ package = LocalPackage(
+ name="agent",
+ source_path=agent_source_path,
+ sandbox_install_path="/scripts/node_modules/@posthog/agent",
+ )
+
+ with pytest.raises(ValueError, match="Expected dependencies to be an object"):
+ get_local_package_runtime_dependencies((package,))