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.

feat(devex): read ownership files with a GitHub credential from posthog/ownership (#103852)

Julian Bez3cacbe7e1a40
diff --git a/docs/internal/ownership-model-proposal.md b/docs/internal/ownership-model-proposal.md
deleted file mode 100644
index 3710b55bd3a0..000000000000
--- a/docs/internal/ownership-model-proposal.md
+++ /dev/null
@@ -1,314 +0,0 @@
-# Repo ownership model: distributed `owners.yaml`
-
-Status: implemented (landed with the PR that introduced this document)
-
-The format itself is now specified in [`packages/owners-yaml/SPEC.md`](../../packages/owners-yaml/SPEC.md), and the package README covers usage.
-This document keeps the design reasoning and how the PostHog monorepo wires the resolver in.
-PostHog's repo settings (`github_org`, `producers`, `reserved_dirs`, `codeowners`) live in the root `owners.yaml`.
-CI regenerates the CODEOWNERS projection before each Trunk test upload in `.github/scripts/trunk-codeowners.sh`, so Trunk Flaky Tests can attribute a test to a team.
-
-Design a single ownership source of truth that multiple consumers (review automation, CI validation, lookup CLIs, service catalogs, future tools) can read, instead of each tool re-parsing `CODEOWNERS-soft` and `product.yaml` on its own.
-
-Scope decisions (locked):
-
-- `owners.yaml` becomes the canonical ownership format.
-- `.github/CODEOWNERS-soft` is deleted; the PR-assignment flow reads the new resolver instead.
-- `products/*/product.yaml` stays and is an **accepted alias** of `owners.yaml` — its `owners:` key is a first-class ownership source, all other fields are ignored for ownership purposes.
-- The hard `.github/CODEOWNERS` is left alone for now: hand-maintained, GitHub-enforced, out of the schema.
-- Everything lands in **one PR**.
-
-## 1. Survey of prior art
-
-| System | Placement | Match resolution | Roles | Inheritance control | Metadata |
-| --------------------------- | ------------------- | ---------------------------- | -------------------------- | -------------------------- | ----------------------------------------------------- |
-| GitHub CODEOWNERS | one central file | last-match-wins (whole file) | none | none | none |
-| GitLab CODEOWNERS | one central file | last-match-wins per section | sections + `@@role` refs | section-scoped | none |
-| Gerrit/Chromium OWNERS | per directory | ancestor union | none (Gerrit labels) | `set noparent`, `per-file` | sibling DIR_METADATA (component, team contact) |
-| Kubernetes/Prow OWNERS | per directory, YAML | ancestor union | `approvers` vs `reviewers` | `options.no_parent_owners` | `labels`, `emeritus_approvers`, root `OWNERS_ALIASES` |
-| Backstage catalog-info.yaml | per component | explicit reference, no globs | typed `spec.owner` (Group) | n/a | open-ended annotations |
-
-Lessons that shaped this proposal:
-
-- Central single-file systems rot via pattern-order bugs: last-match-wins makes line order load-bearing, and a broad glob added late silently swallows earlier specific rules. Our own `CODEOWNERS-soft` already relies on deliberate ordering (the managed-reverse-proxy block must stay last).
-- Per-directory files match the mental model ("who owns _this_ directory") and scale with a monorepo, but need a coverage audit tool since nothing forces a new directory to get an owner.
-- The approver/reviewer split (Kubernetes) is the single most useful role distinction: "can gate a merge" vs "should see this PR" are different sets. We already have exactly this split — hard `CODEOWNERS` vs soft — just encoded as two separate files with different formats and different consumers.
-- Chromium separates approval (OWNERS) from routing metadata (DIR_METADATA: team contact, bug component). Keeping "who approves" and "who to page/ping" in one schema but different fields avoids a second file.
-- Kubernetes avoids GitHub Teams for grouping (no audit trail for membership) via a PR-reviewable `OWNERS_ALIASES` file. We _do_ want GitHub team slugs (the auto-assigner needs them), and we deliberately skip the alias layer: individuals appear inline as `@handles`, matching what `product.yaml` already allows.
-- The compile-to-CODEOWNERS pattern (structured YAML as source, flat CODEOWNERS as build artifact) is common and keeps native platform integration for free.
-
-## 2. What the repo has today
-
-Two data sources, one shared matcher, four consumers — all hand-maintained.
-
-**Sources**
-
-- `.github/CODEOWNERS` (58 lines): blocking. Deliberately tiny, infra/security-critical trees only ("extraordinary justification" header). Uses owner-less lines as _resets_ to clear a blocking owner for a subtree (e.g. `posthog/hogql/database/schema/**`).
-- `.github/CODEOWNERS-soft` (383 lines): non-blocking review tagging. Carries all product mapping for shared code outside `products/` (~25 teams). Header already says: product-level ownership belongs in `product.yaml`; this file is for sub-folder overrides, secondary reviewers, and paths outside `products/`.
-- `products/*/product.yaml` (68 files): exactly two fields, `name` and `owners` (list of team slugs, occasionally `@individual`). Owns all of `products/<name>/**` and beats any CODEOWNERS entry in the resolution used by the ownership skill.
-
-**Consumers and their parsers**
-
-| Consumer | Reads | Parser |
-| --------------------------------------------------------- | -------------------------- | ------------------------------------------------------------------------- |
-| `.github/scripts/assign-reviewers.js` (CI auto-assign) | soft + product.yaml | vendored matcher + own YAML mini-parser |
-| `hogli product:lint:owners` | product.yaml | own loader (`product_yaml.py`), validates slugs against live GitHub teams |
-| `.agents/skills/establishing-code-ownership/ownership.js` | hard + soft + product.yaml | vendored matcher + own YAML mini-parser |
-| `products/stamphog/packages/pr-approval-agent/gates.py` | soft only | fully independent reimplementation |
-
-The vendored matcher is `.github/scripts/codeowners.js` (a port of `hmarr/codeowners`, faithful to GitHub semantics).
-
-**Gaps**
-
-- Four parsers of the same two files; only two share the matcher. Drift is a when, not an if.
-- Only `product.yaml` is CI-validated. Nothing checks that `CODEOWNERS-soft` globs still match existing files or that its team slugs exist (the assigner discovers dead teams at runtime via 422s).
-- No schema for `product.yaml`; no oncall/Slack/escalation routing anywhere in the repo (handbook only).
-- Consumers disagree about scope: the assigner and pr-approval-agent ignore the hard file; only the skill layers all three sources.
-- No structured notion of generated/vendored/deprecated code — the assigner hardcodes an ignore list (`frontend/src/generated/**`, `*.ambr`, lockfiles, …).
-
-## 3. Proposed canonical format: `owners.yaml`
-
-One schema, distributed per directory. Under `products/`, the existing `product.yaml` **is** the ownership file (see the alias rule below) — no new files needed there.
-
-```yaml
-# owners.yaml — full form; every field except `owners` is optional
-version: 1
-
-# The one required field, same key and semantics as product.yaml.
-# Ordered, mixed list of GitHub team slugs (minus @PostHog/) and
-# '@handles'; the first entry is the primary owner, used for defaults
-# like the derived Slack channel (see the `teams:` registry below).
-# A single owner can be written bare: `owners: team-error-tracking`.
-# Owners are tagged for review (non-blocking) and are the answer to
-# "who owns this path".
-owners: [team-error-tracking, '@pauldambra']
-
-# Lifecycle of the code under this directory.
-# active (default) | deprecated | generated | vendored
-status: active
-
-# When true (default), fields not set here fall through to the nearest
-# ancestor owners.yaml. false = Gerrit's `set noparent`.
-inherit: true
-
-# The owners of ADDITIONS below this directory, as opposed to the owners
-# of the files already in it. Names people only; what counts as an
-# addition, and whether a consumer asks them for review or blocks on
-# them, is that consumer's policy. Unlike every other field this one
-# adds up across the walk (see below).
-additions: [team-devex]
-
-# Per-path overrides inside this directory, *within this file only*.
-# Every matching rule applies in order, and each replaces only the fields
-# it sets: owners, status, or inherit. `match` is one glob or a list of globs (each is its own
-# boundary — the list is just shorthand for repeating owners/status).
-rules:
- - match: 'generated/**'
- status: generated
- - match: 'vendor/**'
- status: vendored
- owners: null # explicit reset: unowned-by-design, lint-exempt
- - match: ['migrations/**', 'legacy/**']
- owners: [team-error-tracking, team-data-modeling]
-```
-
-The 90% case is two lines:
-
-```yaml
-# rust/owners.yaml
-version: 1
-owners: team-ingestion
-```
-
-### `additions:` — ownership of the namespace, not the file
-
-`owners:` answers "whose is this file".
-`additions:` answers a different question about the same path: "who owns what gets added here".
-The two are independent: each product under `products/` is owned by its team, while the owners of additions to `products/` can be one team.
-Much of the architecture guidance already has this shape as prose that nothing checks, such as reserving top-level `tools/`, `services/` and `packages/` for cross-product things.
-
-- **It adds up across the walk.** Every declaration on the walk applies, so a nested directory cannot drop the owners of additions that an ancestor names.
- `owners:` stays nearest-wins, and `inherit: false` still cuts everything, additions included.
-- **Ask about the directory, not a file inside it.** The walk stops at the parent of the path it resolves, so resolving `products/newthing` matches a `match: '/*'` rule on `products/`, while resolving `products/newthing/product.yaml` does not.
- `/*` therefore means "a direct child", and `/**` reaches any descendant.
- A directory query also skips that directory's own ownership file, so a new product cannot remove itself from what its parent names.
-- **Newness and enforcement belong to the consumer.** The file only names the owners and where they apply. A consumer works out from the diff that a directory is new, treats a rename into the directory as an addition (git reports it as `R`, not `A`), and decides whether the answer is a review request or a blocking check.
-
-**Why not `owners:` on the parent directory.**
-An owner on `products/` would also claim every file below it that has no nearer owner.
-That misattributes those files, and it satisfies the coverage check for them, which turns real gaps into permanent false coverage.
-Over a hundred files under `products/` are unowned today and would flip.
-`additions:` contributes nothing to `owners`, so the coverage signal survives.
-
-**A consumer can combine `owners` and `additions`.**
-The owners are already responsible for everything in their tree.
-An empty `additions` means that the file names no separate owners of additions, not that nobody owns them.
-That is also why the key does not default to `owners`: a reader could no longer tell a directory with its own owners of additions from one that merely has an owner.
-
-The normative definition is section 3.6 of [`packages/owners-yaml/SPEC.md`](../../packages/owners-yaml/SPEC.md).
-
-### `product.yaml` as an accepted alias
-
-`products/<name>/product.yaml` with an `owners:` key is read by the resolver as an `owners.yaml` with that same `owners:` list, because the root `owners.yaml` enables it with `alias_files: [product.yaml]`, which is also the default when a root file does not declare the setting. Every other field in `product.yaml` (`name:` today, anything added later) is ignored for ownership purposes — `product.yaml` remains free to grow product metadata without touching the ownership schema. Rules:
-
-- A directory may have `product.yaml`-with-`owners` **or** `owners.yaml`, never both — lint error.
-- Sub-folder overrides inside a product use nested `owners.yaml` as anywhere else (e.g. `products/x/backend/migrations/owners.yaml`).
-- The `team-CHANGEME` scaffold placeholder resolves to unowned, as all consumers already treat it.
-
-This keeps all 68 products at zero migration cost and preserves `hogli product:lint:owners` unchanged.
-
-### Slack derivation: measured, not assumed
-
-Checked every team slug in use against live Slack channels (first pass 2026-07-15). The counts below follow the root `owners.yaml` registry, over the 30 slugs in use:
-
-- 22/30: `#<slug>` exists verbatim, so no entry is needed.
-- 8/30 need an entry in the root `teams:` registry (below):
- - `ai-research`, `batch-exports`, `clickhouse`, `conversations`, `mcp-analytics`, `platform-ux` — these predate the `team-` convention and are the real org slugs; `team-clickhouse` and friends do not exist as GitHub teams, so the slugs cannot be "fixed" and the channel is `#team-<slug>`.
- - `team-data-stack` → `#group-data-stack`.
- - `team-posthog-desktop` → `#team-desktop`, the name the channel was created under.
-
-So the derived default is right for most teams and the rest carry one entry each.
-
-Nothing validates that a derived channel actually exists — a wrong or dead channel fails silently.
-An opt-in Slack-API check in `owners:lint`, mirroring the existing opt-in live GitHub-team validation, would close that gap; it is not built.
-
-#### The `teams:` registry (repo-root only)
-
-The channel-to-team mapping is declared **once**, at the root, never per file — a team that owns paths across many directories should not restate its channel in each.
-The **repo-root** `owners.yaml` may carry a `teams:` registry — a mapping of team slug to the channels that team declares.
-Every value is a string starting with `#`, or `false` to mean "no channel, don't derive":
-
-- `slack` — where the people are. This is the channel a human is pointed at.
-- `notifications` — where automation posts. It falls back to `slack`, so a team that never separates the two keeps one entry, and `notifications: false` keeps automation out without hiding the team's channel from people.
-
-`notifications` may also be a mapping of producer name to channel, so a team can silence or redirect one bot on its own.
-A producer the mapping does not name falls through to `slack`.
-Only a producer listed in the root `producers:` setting may be named, so a typo is a lint error rather than an opt-out that never applies.
-
-```yaml
-# owners.yaml (repo root only)
-teams:
- clickhouse:
- slack: '#team-clickhouse'
- team-data-stack:
- slack: '#group-data-stack'
- notifications: '#group-data-stack-bots'
- quiet-team:
- slack: '#team-quiet'
- notifications: false
- digest-free-team:
- slack: '#team-digest-free'
- notifications:
- stamphog: false
- some-retired-team:
- slack: false
-```
-
-A team is registered only when it declares at least one channel, so a slug's presence in the registry means "this repo answered for that team" and nothing more.
-Consumers ask for the purpose they need, which is what keeps a bot's destination out of the channel a human is pointed at.
-
-`teams:` in any non-root `owners.yaml` is a schema error, and `product.yaml` aliases never carry it.
-There is no per-path or per-file Slack override — the registry (plus the derived default) is the only way a channel is set.
-
-The effective Slack channel for a path is resolved by this precedence chain, first match wins:
-
-1. the registry entry for the **primary owner** (`owners[0]`), but only when it is a team slug (not an `@handle`) — a `false` entry suppresses derivation;
-2. the derived `#<owners[0]>` when the primary owner is a team slug;
-3. otherwise `None`.
-
-The registry only changes how the resolver computes the channel; the wire format is unchanged — `slack` still flows through as the final string or `null`.
-
-### Individuals, no alias layer
-
-There is no `OWNERS_ALIASES` file. `owners:` takes GitHub team slugs or `@handles` directly — the same convention `product.yaml` already uses for `user_interviews`. Lint validates handles against org membership the same way it validates team slugs. The auto-assigner requests individual reviewers through the API's `reviewers` field (it currently skips `@`-entries entirely, so individuals only work via `CODEOWNERS-soft` today — this closes that gap and lets the soft-file wiring die with the file).
-
-### Design choices, argued
-
-- **Distributed, not central.** The repo already voted: `product.yaml` is per-directory and the soft file's own header pushes ownership toward it. Central files are what we're escaping (ordering bugs, merge conflicts on one hot file). The audit story ("show me everything") is a tool's job (`hogli owners:map`), not a file layout's.
-- **Nearest-file-wins with per-field fallthrough, not ancestor union.** Kubernetes unions approvers up the tree because its bar is "someone must approve"; our soft model is "tag the right team, don't spam five". Union inheritance would tag `posthog/` owners on every deep PR. Override semantics also match what the ownership skill already implements (product.yaml beats CODEOWNERS). Fallthrough is per field: a child file that only sets `owners` still inherits `status` from its ancestor.
-- **`rules:` are file-local.** Cross-file glob interactions are the CODEOWNERS footgun; here a glob can only override its own directory's defaults, so reading one file plus its ancestors fully explains any path.
-- **`owners: null` is explicit, not absent.** Unowned must be a decision (vendored code, scratch dirs), never a default. The coverage check treats missing resolution as an error and `owners: null` as an exemption with a paper trail.
-- **One `owners` list, no role split.** A `team`-vs-`reviewers` distinction (Kubernetes-style) was considered and dropped: with blocking out of scope, "who is responsible" and "who gets tagged" are the same set, and product.yaml already speaks `owners`. Ordering carries the only extra signal needed — first entry is the primary owner. A blocking role, if ever needed, is a new field later, not a split now.
-- **`status:` replaces hardcoded ignore lists.** The assigner's generated-file ignore list, review-noise suppression, and future tooling (e.g. excluding vendored code from lint) all key off one field instead of N copies.
-
-## 4. Resolution model
-
-For a path `P`:
-
-1. Walk from the repo root toward `P`, collecting every `owners.yaml` (or aliased `product.yaml`) on the way. If a file sets `inherit: false`, drop everything collected above it.
-2. Effective config = shallow merge, nearest file winning per field (lists replace, never merge — predictability over cleverness).
-3. Within each file, apply every rule whose `match` glob (gitignore-style semantics, documented with the schema) matches `P` relative to that file's directory, in file order. Each rule replaces only the fields it sets, before the file's fields merge into the result.
-4. Review tagging = resolved `owners`. Primary owner = its first entry.
-5. No ownership file on the walk and no rule match → **unowned**, which fails the coverage check unless the path is under an `owners: null` rule.
-
-**Consolidation vs distribution is a readability choice, not a semantic one.** A parent `owners.yaml` may own subtrees through anchored directory rules (`- match: '/rust/capture/'`), and a deeper `owners.yaml` still wins by nearest-file resolution. So a cluster of one-line child files and a single parent file with equivalent rules resolve identically; pick whichever reads better for that tree. `owners:lint` nudges toward folding when a directory accumulates enough single-purpose children.
-
-The hard `.github/CODEOWNERS` stays outside this walk entirely. It keeps its own GitHub-native semantics and remains hand-maintained and GitHub-enforced; the resolver does **not** read it — blocking ownership is consulted manually (or via GitHub's own UI) when needed. It never influences the resolved `owners`, and nothing in this proposal writes to it.
-
-## 5. Tool independence: one resolver, many consumers
-
-The stability guarantee is architectural: **consumers never parse ownership files themselves.** One resolver library owns the semantics; everything else calls it.
-
-- **Resolver**: single implementation in the installable `owners-yaml` package at `packages/owners-yaml/` exposing `resolve(path)`, `map()`, `unowned()` as a library, and `hogli owners:resolve --json <path...>` (paths also accepted on stdin) as the CLI. Rationale: hogli already lints ownership, and two of the four consumers are Python, so this makes lint, lookup, and the pr-approval agent native library callers with zero subprocess hops. Glob matching for `rules:` uses gitignore-style semantics implemented (and documented) here — the vendored JS matcher stays only for the hard-CODEOWNERS overlay parsing, or is replaced by an equivalent Python CODEOWNERS parser.
-- **JS consumers** shell out to the CLI and read JSON — `assign-reviewers.js` feeds the PR's changed files in and gets resolved owners back; the `establishing-code-ownership` skill does the same. The auto-assign workflow gains a Python/uv setup step (it is node-only today). `gates.py` imports the library directly. No committed lock file, so no freshness-check machinery; if one is ever wanted (offline consumers, Backstage `catalog-info.yaml` emitters), it is a trivial fold over `map()` added later.
-- **Validator**: `hogli owners:lint` — schema check, team slugs and `@handles` against the live GitHub org (`owners_yaml.github`, which `product/gh.py` reuses), dead `rules:` globs (match zero files), same-directory `product.yaml`/`owners.yaml` conflicts, reserved-location rejection (see below), and full-tree coverage (every `git ls-files` path resolves or is `owners: null`). It also prints advisory consolidation suggestions when it spots a cluster of single-purpose owners.yaml files a single parent could absorb (never affects the exit code).
-
-**Reserved locations.** `owners.yaml` must not live in a directory whose own tooling globs every YAML file there — GitHub Actions/actionlint treat everything under `.github/workflows/` as a workflow, and the `services/mcp` generate-tools step globs YAML configs under `products/*/mcp/`. Lint rejects `owners.yaml` in those spots; hoist the ownership into the parent's `rules:` instead (e.g. a `/workflows/` rule in `.github/owners.yaml`).
-
-- **Lookup**: `hogli owners:who <path>` / `owners:team <slug>` / `owners:unowned` — thin wrappers over the library; the `establishing-code-ownership` skill's `ownership.js` becomes a shim over the CLI (or is deleted in favor of it).
-
-One tradeoff to acknowledge: today `.github/scripts/` sits behind the blocking `CODEOWNERS` (`team-security`), so changes to assignment logic require their approval. Moving the resolver out of `.github/scripts/` takes it out of that gate. Done — the resolver package (`packages/owners-yaml/owners_yaml/`) is under the blocking file, a deliberate exception to "leave CODEOWNERS alone" since the auto-assigner executes it on `pull_request_target`.
-
-If the first consumer (say the auto-assigner) is ever replaced, the resolver, schema, and lint are untouched — only one caller changes. That is the "source of truth, not tool config" property.
-
-### Portability: repo = data, app = resolver
-
-Nothing in the resolver is PostHog-specific — `owners.yaml` is a repo-agnostic format, and the library needs only pyyaml and a way to load files.
-That is why it ships as the standalone, installable `packages/owners-yaml` package (`owners-yaml`), which any repo can run without vendoring: `uvx owners-yaml lint` (pin the version in CI).
-That last part is the seam: resolution walks an abstract file map, not the filesystem (the `owners:fmt` equivalence proof already runs the real resolver over an in-memory layout).
-So when a consumer like stamphog becomes a hosted app that other repos enable without adding any code, the model is: **the repo contributes only ownership data; the resolver ships inside the app.**
-A hosted reviewer fetches the default-branch tree (one API call), pulls just the ownership files (a few dozen blobs, cacheable per commit SHA), and resolves in-process.
-Repos without `owners.yaml` fall back to a `CODEOWNERS` loader behind the same resolver interface — the glob semantics here are CODEOWNERS semantics already — and a repo with neither is simply unowned.
-
-Two properties carry over intact.
-Ownership is always read from the default branch, never the PR head, so a PR cannot rewrite ownership to approve itself.
-And ownership _content_ stays in git even when enablement moves to a UI — a far-away ownership store is exactly what rots (§2); the UI configures which source and branch, never the data.
-
-## Canonical placement (`owners:fmt`)
-
-Because consolidation is a readability choice and not a semantic one (§4), the tree has many layouts that resolve identically, and it drifts between them as people fold and split by hand.
-`owners:fmt` names the drift: it models ownership as a piecewise-constant function on the directory tree, where each `match`/`owners` statement is one _boundary_ (a change point) and the physical file that carries it is pure presentation.
-Placing statements onto files optimally is a **capacitated facility-location** problem on the tree — open a file where a cluster of boundaries makes a dedicated file cheaper than carrying them all up as ancestor rules, otherwise fold them into the nearest existing carrier.
-
-The cost model lives in module constants, so "canonical" is defined only relative to them: `ALPHA` (the price of a dedicated simple `owners.yaml` existing at all — pinned carriers like `product.yaml` manifests, non-simple files, glob files, and the repo root are free because they exist anyway), `GAMMA` (the per-level price of carrying a statement as an ancestor rule), and `MAX_RULES` (the split cap that forces a dedicated child file once a carrier gets too dense).
-Glob rules are crosscutting rather than tree boundaries, so any file carrying one is pinned and passes through untouched.
-Every run ends with a built-in equivalence proof: the proposed layout is simulated in memory and every tracked path re-resolved against it, which must match the current resolution exactly — a mismatch is a bug in `fmt`, not a suggestion.
-
-`owners:fmt` is a **read-only oracle** — it never writes, and there is no `--write` flag.
-The division of labor: `owners:lint`'s fold/split suggestions are the everyday incremental mechanism (with hysteresis, so small clusters don't thrash), `fmt` is the drift oracle you consult deliberately, and an actual reflow of files is a human decision, not something a formatter should apply on save.
-
-## 6. The one PR
-
-Everything lands atomically. The delivery order below is a review guide, not a merge sequence.
-
-1. **Resolver + schema.** `packages/owners-yaml/` (resolution per §4), `hogli owners:resolve --json`, JSON-schema for `owners.yaml`.
-2. **Convert `CODEOWNERS-soft` → distributed `owners.yaml`.** Mechanical translation of the 383 lines into per-directory files under `posthog/`, `frontend/src/scenes/`, `nodejs/`, `rust/`, `services/`, `ee/`, plugin-server, etc. Where the soft file relied on last-match ordering (e.g. the trailing managed-reverse-proxy block overriding a broad settings-scene rule), that intent becomes an explicit nested file or `rules:` entry — order-independence is the point. This was driven by a one-shot converter that ran during the PR and was removed once the conversion landed (it remains in the branch history).
-3. **Equivalence proof.** A differ resolved every `git ls-files` path under (old: soft + product.yaml) and (new: owners.yaml + product.yaml) and asserted identical reviewer sets. It ran during the PR to verify the migration and was removed once the conversion landed; intentional divergences (there were a few — dead globs, stale teams the 422 fallback already skips) were listed explicitly in the PR description rather than slipping through.
-4. **Flip consumers.**
- - `assign-reviewers.js`: replace soft-file parsing + `loadProductYamlRules` with a call to `hogli owners:resolve --json` (workflow gains a Python setup step). Substantive-owner thresholds, 5-team cap, comment/label behavior unchanged; `@handle` owners become individual review requests instead of being skipped. `status: generated` replaces the hardcoded ignore list.
- - `gates.py`: replace the private CODEOWNERS-soft parser with a direct library import.
- - `ownership.js` (skill): becomes a shim over the CLI; SKILL.md updated.
-5. **Delete `.github/CODEOWNERS-soft`.** Also drop its entry from anything referencing it.
-6. **Lint wiring.** `hogli owners:lint` + a CI job (extend the existing `validate-product-yamls` job rather than adding a new one). Coverage starts warn-only; ratchet to fail in a follow-up once `owners:unowned` is clean or explicitly `owners: null`.
-
-Safety properties of the atomic switch:
-
-- `auto-assign-reviewers.yml` runs on `pull_request_target` and always checks out **master**, so the new flow activates only at merge — no half-migrated window, and in-flight unrebased PRs are unaffected (the repo's CI-backwards-compat rule holds by construction).
-- The hard `CODEOWNERS` and GitHub's native enforcement are untouched, so worst case on a resolver bug is wrong _soft_ tagging, which is recoverable and non-blocking.
-- The equivalence differ is the review artifact: reviewers approve a proven-identical resolution plus an explicit list of intentional diffs, not 400 lines of glob translation on faith.
-
-## 7. Open questions for maintainers
-
-1. **Oncall routing**: resolved — dropped from v1. The Slack channel costs nothing (derived from the team slug by convention, with the root `teams:` registry overriding or setting `slack: false` where needed), but nothing consumes an oncall reference, so it is not carried. Re-adding it is additive once a consumer exists.
-2. **Resolver ownership**: resolved — the resolver package is covered by the hard `CODEOWNERS` (see §5).
-3. **Coverage gating cadence**: how soon after the PR to flip `owners:lint` coverage from warn to fail — immediately for _new_ directories (ratchet), or only once the whole tree is clean?
-4. **Hard-CODEOWNERS future** (explicitly out of scope now): if blocking gates ever move into the schema, approver inheritance should probably union up the tree rather than nearest-wins — parked until `team-security` wants to revisit. `additions:` set the precedent for the union half; it is advisory, so it did not settle the blocking half.
diff --git a/packages/owners-yaml/CHANGELOG.md b/packages/owners-yaml/CHANGELOG.md
index 599acf24d786..3e20f11a01fd 100644
--- a/packages/owners-yaml/CHANGELOG.md
+++ b/packages/owners-yaml/CHANGELOG.md
@@ -21,6 +21,19 @@ the GitHub Release body, so add the entry here before you cut the tag.
- Path normalization removes a trailing `/`. `products/new/` and `products/new` now resolve alike; before, the slash put the directory's own ownership file on the walk.
- Every matching rule in a file now applies, and each replaces only the fields it sets. Before, the last matching rule replaced the earlier ones entirely, so a rule that set only `status` dropped the `owners` an earlier rule had set. `SPEC.md` section 3.4 records the amendment.
+## 0.2.1
+
+### Added
+
+- `--producer NAME` on `owners resolve` and on `python -m owners_yaml`, and a `producer` argument on `OwnersResolver`. Without it, a team that maps `notifications` per producer was never matched, so every bot fell back to the team's `slack` channel. A name the root file's `producers` list does not declare is an error, because it would silently route to the people channel. SPEC section 7.1 now defines the producer as part of a resolver request.
+
+### Docs
+
+- The `notifications` example in the README and the command next to it now agree: a per-producer mapping needs `--purpose notifications --producer review-bot`. A plain channel string covers all automation.
+- The install section warns that the PyPI project named `owners` is a different package. Always write `owners-yaml`.
+- "Lint in CI" says what plain `lint` does not check: it does not know which teams exist, `lint --live` asks GitHub through the `gh` CLI, and `who` and `resolve` answer from the parent directory when a file does not parse.
+- SPEC section 10 and the README record a non-goal: CODEOWNERS is an export target and a one-time migration source, never a second input format.
+
## 0.2.0
First release on PyPI, as `owners-yaml`. The package was developed in the monorepo as `posthog-owners` and never published under that name.
diff --git a/packages/owners-yaml/README.md b/packages/owners-yaml/README.md
index 5243691f3f70..a6b4718520e3 100644
--- a/packages/owners-yaml/README.md
+++ b/packages/owners-yaml/README.md
@@ -65,7 +65,9 @@ uvx owners-yaml --help # run it once without installing
```
The package installs two identical commands, `owners` and `owners-yaml`.
-In CI, pin the version (`owners-yaml==0.2.0`), because a new release can change how paths resolve.
+An unrelated project on PyPI is named `owners`, so always write `owners-yaml` when you install or run it: `uvx owners` fetches that other package.
+After `uv tool install owners-yaml`, the `owners` command on your PATH is this one.
+In CI, pin the version (`owners-yaml==0.2.1`), because a new release can change how paths resolve.
Requirements: Python 3.10 or later, PyYAML, and click.
The commands read tracked files through `git`. Outside a git worktree, pass `--repo-root` and they read the files from disk.
@@ -158,14 +160,18 @@ $ owners resolve --json billing/vendor/stripe.py web/app.ts
}
```
-`resolve` also reads paths from stdin, one per line. Add `--purpose notifications` to get the channel where automation posts.
+`resolve` also reads paths from stdin, one per line.
+Add `--purpose notifications` to get the channel where automation posts.
+When a team maps `notifications` per producer, as in the settings example above, name the automation as well: `--purpose notifications --producer review-bot`.
+Without `--producer`, a per-producer mapping is skipped and the answer falls back to the team's `slack` channel.
+A team that sends every bot to one channel writes a plain channel string instead (`notifications: '#billing-alerts'`), which answers any producer.
To list what nobody owns, run `owners unowned`. Paths under `owners: null` are left out.
### Lint in CI
```console
-$ uvx owners-yaml==0.2.0 lint
+$ uvx owners-yaml==0.2.1 lint
⚠ coverage: 0 of 5 tracked file(s) resolve to unowned
✓ owners.yaml lint passed (1 warning(s))
@@ -174,9 +180,15 @@ $ uvx owners-yaml==0.2.0 lint
`lint` fails on schema errors, a directory with two ownership files, `owners.yaml` files in reserved locations, and a rule that names a directory without the trailing `/`.
Write `docs/` for a directory, because `docs` also matches a file called `docs`.
It warns about rule patterns that match no tracked file, and it reports coverage.
-`lint --live` also checks each team slug and `@handle` against the GitHub organization in `github_org`, or in `--org`.
Pass the changed ownership files as arguments to check only those.
+Plain `lint` does not know which teams exist, so it accepts a slug for a team that was renamed or deleted.
+`lint --live` checks each team slug and `@handle` against the GitHub organization in `github_org`, or in `--org`.
+It asks GitHub through the [GitHub CLI](https://cli.github.com/), which must be signed in with an account that can read the organization's teams.
+
+Run `lint` before you trust a lookup.
+A file that `who` or `resolve` cannot parse counts as absent, so they answer from the parent directory instead of reporting the problem (SPEC section 4, step 3).
+
`owners fmt` shows where files could be merged or split without changing any resolution. It never writes.
### Call it from other tools
@@ -196,7 +208,7 @@ Submodules can change between minor releases.
From any language, pipe paths to the JSON entrypoint. `uvx` fetches the package from PyPI, so the machine needs only `uv`:
```bash
-echo "billing/api/invoices.py" | uvx --from owners-yaml==0.2.0 python -m owners_yaml --repo-root path/to/repo
+echo "billing/api/invoices.py" | uvx --from owners-yaml==0.2.1 python -m owners_yaml --repo-root path/to/repo
```
The entrypoint imports only PyYAML. A tool that already has the source can run it with no install: `PYTHONPATH=path/to/packages/owners-yaml python3 -m owners_yaml`.
@@ -275,6 +287,10 @@ Other tools cover parts of this.
[codeowners-generator](https://github.com/gagoar/codeowners-generator) builds one from files spread across the repo.
Backstage and other service catalogs track ownership per service, not per path.
+The resolver reads ownership files only.
+CODEOWNERS is an export target, never a second input: the two formats resolve differently, and a CODEOWNERS file carries owners and nothing else, so an answer would depend on which file a tool found.
+Moving an existing CODEOWNERS file into `owners.yaml` files is a one-time migration, by hand today.
+
## When not to use it
- **You need GitHub to block merges on an owner's approval.** Keep that in `.github/CODEOWNERS`. `owners.yaml` routes, it doesn't block. The CODEOWNERS export covers test files only.
@@ -294,12 +310,12 @@ Run its tests with `uv run --no-project --with pyyaml --with click --with pytest
To release, bump `version` in `pyproject.toml`, add the matching section to `CHANGELOG.md`, merge, then tag `master`:
```bash
-git tag owners-yaml-v0.2.0 && git push origin owners-yaml-v0.2.0
+git tag owners-yaml-v0.2.1 && git push origin owners-yaml-v0.2.1
```
The tag starts [`publish-owners-yaml.yml`](https://github.com/PostHog/posthog/blob/master/.github/workflows/publish-owners-yaml.yml).
It checks that the tag matches the version, builds and tests the wheel, and publishes to PyPI with trusted publishing.
It then creates a GitHub release from the changelog section.
-To retry a failed run, dispatch the workflow on the same tag: `gh workflow run publish-owners-yaml.yml --ref owners-yaml-v0.2.0`.
+To retry a failed run, dispatch the workflow on the same tag: `gh workflow run publish-owners-yaml.yml --ref owners-yaml-v0.2.1`.
MIT licensed.
diff --git a/packages/owners-yaml/SPEC.md b/packages/owners-yaml/SPEC.md
index 40c9f19acb7f..f5f79eeb38e7 100644
--- a/packages/owners-yaml/SPEC.md
+++ b/packages/owners-yaml/SPEC.md
@@ -251,6 +251,7 @@ To find the channel for a team slug `T`, a purpose, and an optional producer:
The channel of a path is the channel of its primary owner.
When the primary owner is a person handle, the path has no channel.
+An implementation that answers requests from other programs takes the purpose and the producer from the consumer, as section 7.1 states.
## 6. Alias files
@@ -283,6 +284,9 @@ In `owners-yaml`, both `owners resolve --json` and `python -m owners_yaml` imple
2. When the consumer passes no path arguments, the resolver MUST read paths from standard input, one path per line. It MUST remove whitespace at the start and end of each line and MUST skip empty lines.
3. The consumer MAY name the repository root. Without one, the resolver MAY find the root itself, for example from the git worktree.
4. The consumer MAY name the purpose of the channel: people or notifications (section 5.2). The default is people. `owners-yaml` spells these `--purpose slack` and `--purpose notifications`.
+5. The consumer MAY name the producer of the channel (section 5.2). The default is no producer. `owners-yaml` spells this `--producer NAME`.
+6. The resolver MUST pass the producer to the channel lookup of section 5.2 for every path of the request.
+7. When the root file declares `producers` and the consumer names a producer that is not in that list, the resolver MUST exit with a non-zero status. The error message MUST list the declared names.
### 7.2 Response
@@ -460,9 +464,12 @@ rules:
- **The alias default is for old trees.** `product.yaml` is the default alias file name so that a repository written before `alias_files` existed resolves the same as it did then. A repository with no alias files sets `alias_files: []` and pays no lookups for it.
- **Owners of additions add up.** Owners are nearest-file-wins because the union tags too many teams. `additions` answers a different question: who owns additions below a directory. If a nested file could drop the owners of additions that an ancestor file names, the answer of the ancestor would not be reliable. A separate field keeps coverage checks correct: `owners` on the parent directory would claim every file below it that has no nearer owner.
- **Routing, not approval.** The format answers "who owns this path" for review requests, alerts, and reports. It does not replace a platform's required-approval rules. `additions` is routing too: it names owners, and it does not approve or block a change.
+- **`additions` does not default to `owners`.** An empty list means that the file names no separate owners of additions. A default would hide which directories have their own owners of additions and which only have owners.
+- **One input format.** A resolver reads ownership files only. CODEOWNERS is an export target, and a source for a one-time migration into ownership files, never a second input the resolver reads. The two formats resolve differently: CODEOWNERS takes the last matching line in one file, and this format takes the nearest file, field by field. CODEOWNERS also carries owners and nothing else, so it can say nothing about status or channels. Reading both would make the answer depend on which file a tool found first.
## Changelog
- **1** (2026-09): First published version.
- **1**, amended (2026-09): Section 3.5 adds `[...]` character classes. No pattern that was valid before the amendment changes meaning. Section 6 gives `alias_files` the default `[product.yaml]`, so a root file that does not declare the key now has one alias file instead of none.
+- **1**, amended (2026-09): Section 7.1 adds the producer to the resolver request, so a consumer can reach a team's per-producer `notifications` mapping through an entrypoint. No ownership file changes meaning.
- **1**, amended (unreleased): Section 3.4 applies every matching rule, field by field. Before, the last matching rule replaced the earlier ones. Section 3.6 adds the optional `additions` field. Section 7.2 adds the `additions` member, and a consumer treats a missing member as empty (section 7.4). Section 4 step 1 removes a trailing `/`, so a request for `docs/` resolves the same as `docs`.
diff --git a/packages/owners-yaml/owners_yaml/__main__.py b/packages/owners-yaml/owners_yaml/__main__.py
index 48e27416927c..aa5733da44c6 100644
--- a/packages/owners-yaml/owners_yaml/__main__.py
+++ b/packages/owners-yaml/owners_yaml/__main__.py
@@ -7,6 +7,8 @@ JSON object keyed by normalized path to stdout::
``--purpose notifications`` resolves ``slack`` to the team's automation channel
(falls back to the people channel); the default is the people channel.
+``--producer NAME`` names the automation asking, which a team's per-producer
+``notifications`` mapping answers; without it such a mapping falls back to the people channel.
``--codeowners FILE`` switches to the other mode: it ignores the path arguments and writes a
CODEOWNERS projection of every tracked test file's ownership to FILE (``-`` for stdout), for a
@@ -40,6 +42,11 @@ from .resolver import DEFAULT_PURPOSE, OwnersResolver, Purpose, RepoRootNotFound
def main() -> None:
parser = argparse.ArgumentParser(prog="python -m owners_yaml")
parser.add_argument("--purpose", choices=["slack", "notifications"], default=DEFAULT_PURPOSE)
+ parser.add_argument(
+ "--producer",
+ default=None,
+ help="The automation asking, for a team that maps notifications per producer",
+ )
parser.add_argument(
"--repo-root",
default=None,
@@ -65,9 +72,12 @@ def main() -> None:
parser.error(f"--repo-root {ns.repo_root!r} is not a directory")
repo_root = Path(ns.repo_root) if ns.repo_root is not None else None
try:
- resolver = OwnersResolver(repo_root=repo_root, purpose=cast("Purpose", ns.purpose))
+ resolver = OwnersResolver(repo_root=repo_root, purpose=cast("Purpose", ns.purpose), producer=ns.producer)
except RepoRootNotFound as exc:
parser.error(str(exc))
+ producer_error = resolver.producer_error()
+ if producer_error is not None:
+ parser.error(producer_error)
if ns.codeowners:
org = ns.org or resolver.settings().github_org
diff --git a/packages/owners-yaml/owners_yaml/cli.py b/packages/owners-yaml/owners_yaml/cli.py
index 3359465427fc..6b83b76af278 100644
--- a/packages/owners-yaml/owners_yaml/cli.py
+++ b/packages/owners-yaml/owners_yaml/cli.py
@@ -39,11 +39,15 @@ org_option = click.option(
)
-def _resolver(repo_root: Path | None, purpose: Purpose = "slack") -> OwnersResolver:
+def _resolver(repo_root: Path | None, purpose: Purpose = "slack", producer: str | None = None) -> OwnersResolver:
try:
- return OwnersResolver(repo_root=repo_root, purpose=purpose)
+ resolver = OwnersResolver(repo_root=repo_root, purpose=purpose, producer=producer)
except RepoRootNotFound as exc:
raise click.ClickException(str(exc)) from exc
+ error = resolver.producer_error()
+ if error is not None:
+ raise click.ClickException(error)
+ return resolver
def _github_org(org: str | None, settings: RepoSettings) -> str:
@@ -70,10 +74,17 @@ def _read_paths(paths: tuple[str, ...]) -> list[str]:
default="slack",
help="Which team channel `slack` resolves to: where people are, or where automation posts",
)
+ "--producer",
+ default=None,
+ help="The automation asking, for a team that maps `notifications` per producer",
+)
@repo_root_option
@click.argument("paths", nargs=-1)
-def cmd_resolve(as_json: bool, purpose: str, repo_root: Path | None, paths: tuple[str, ...]) -> None:
- resolver = _resolver(repo_root, cast(Purpose, purpose))
+def cmd_resolve(
+ as_json: bool, purpose: str, producer: str | None, repo_root: Path | None, paths: tuple[str, ...]
+) -> None:
+ resolver = _resolver(repo_root, cast(Purpose, purpose), producer)
targets = _read_paths(paths)
result = {normalize_path(path): resolution_to_wire(resolver.resolve(path)) for path in targets}
if as_json:
diff --git a/packages/owners-yaml/owners_yaml/resolver.py b/packages/owners-yaml/owners_yaml/resolver.py
index 033aab0f0262..27f1a0c1697e 100644
--- a/packages/owners-yaml/owners_yaml/resolver.py
+++ b/packages/owners-yaml/owners_yaml/resolver.py
@@ -242,6 +242,9 @@ class OwnersResolver:
Reads a worktree by default, locating the repo root via ``git rev-parse`` (override with
``repo_root`` for testing). Pass ``source`` to resolve without one. Parsed files are cached per
directory.
+
+ ``purpose`` and ``producer`` decide which channel a resolution reports; ``team_channel``
+ documents how they select one.
"""
def __init__(
@@ -249,10 +252,12 @@ class OwnersResolver:
repo_root: Path | None = None,
purpose: Purpose = DEFAULT_PURPOSE,
source: OwnershipSource | None = None,
+ producer: Producer | None = None,
) -> None:
self.repo_root = (repo_root or (VIRTUAL_ROOT if source is not None else _git_repo_root())).resolve()
self.source = source if source is not None else DiskSource(self.repo_root)
self.purpose = purpose
+ self.producer = producer
self._dir_cache: dict[str, OwnersFile | None] = {}
# The worktree is treated as immutable for the resolver's lifetime.
self._tracked_cache: dict[str | None, list[str]] = {}
@@ -401,12 +406,28 @@ class OwnersResolver:
root = self._load_dir_file("")
return root.settings if root is not None else RepoSettings()
+ def producer_error(self) -> str | None:
+ """Why this resolver's ``producer`` cannot be honored, or None when it can.
+
+ A name the root file does not declare would fall through to the people channel, which is
+ the one place automation must not post, so an entrypoint reports this instead of resolving.
+ A repo that declares no ``producers`` accepts any name.
+ """
+ if self.producer is None:
+ return None
+ if not self.producer:
+ return "producer name must not be empty"
+ declared = self.settings().producers
+ if declared is None or self.producer in declared:
+ return None
+ return f"unknown producer '{self.producer}' (declared in 'producers': {', '.join(sorted(declared))})"
+
def _effective_slack(self, owners: list[str] | None) -> str | None:
"""The Slack channel for a path: the registry entry for the primary owner
(team slugs only), then the derived ``#<slug>``, else None. Only a team slug
(not an ``@handle``) carries a channel."""
if owners and not owners[0].startswith("@"):
- return team_channel(owners[0], self._teams_registry(), self.purpose).channel
+ return team_channel(owners[0], self._teams_registry(), self.purpose, self.producer).channel
return None
def _build_resolution(self, path: str, merged: _Merged) -> Resolution:
diff --git a/packages/owners-yaml/pyproject.toml b/packages/owners-yaml/pyproject.toml
index 5143c7c0ff32..3c1c6a6078a9 100644
--- a/packages/owners-yaml/pyproject.toml
+++ b/packages/owners-yaml/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "owners-yaml"
-version = "0.2.0"
+version = "0.2.1"
description = "Code ownership in owners.yaml files next to the code: resolver, linter, and CODEOWNERS export"
readme = "README.md"
license = "MIT"
diff --git a/packages/owners-yaml/tests/test_conformance.py b/packages/owners-yaml/tests/test_conformance.py
index 6a58cc5a3f81..7ffe7896ba36 100644
--- a/packages/owners-yaml/tests/test_conformance.py
+++ b/packages/owners-yaml/tests/test_conformance.py
@@ -8,7 +8,7 @@ from typing import Any
import pytest
import yaml
-from owners_yaml.resolver import OWNERS_FILENAME, OwnersResolver, Purpose, team_channel, teams_registry
+from owners_yaml.resolver import OwnersResolver, Purpose
CONFORMANCE_DIR = Path(__file__).parent.parent / "conformance"
CASE_FILES = sorted((CONFORMANCE_DIR / "cases").glob("*.yaml"))
@@ -38,32 +38,23 @@ def load_cases() -> list[pytest.ParameterSet]:
return params
-def resolve_channel(case: ConformanceCase, owners: list[str], resolved_slack: str | None) -> str | None:
- if case.producer is None or not owners or owners[0].startswith("@"):
- return resolved_slack
- # OwnersResolver takes no producer, so a producer case looks the channel up with team_channel.
- registry = teams_registry(case.files.get(OWNERS_FILENAME, ""))
- return team_channel(owners[0], registry, case.purpose, case.producer).channel
-
-
@pytest.mark.parametrize("case", load_cases())
def test_conformance_case(tmp_path: Path, case: ConformanceCase) -> None:
for rel, text in case.files.items():
target = tmp_path / rel
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(text)
- resolver = OwnersResolver(repo_root=tmp_path, purpose=case.purpose)
+ resolver = OwnersResolver(repo_root=tmp_path, purpose=case.purpose, producer=case.producer)
actual = {}
for path in case.expect:
resolution = resolver.resolve(path)
- owners = resolution.owners or []
actual[path] = {
- "owners": owners,
+ "owners": resolution.owners or [],
"unowned_by_design": resolution.unowned_by_design,
"status": resolution.status,
"source": resolution.source,
- "slack": resolve_channel(case, owners, resolution.slack),
+ "slack": resolution.slack,
"additions": resolution.additions,
}
# A case that leaves `additions` out expects none, so the cases written before the field
diff --git a/packages/owners-yaml/tests/test_owners.py b/packages/owners-yaml/tests/test_owners.py
index f5bab389aafb..6efe0743f8a7 100644
--- a/packages/owners-yaml/tests/test_owners.py
+++ b/packages/owners-yaml/tests/test_owners.py
@@ -124,16 +124,18 @@ def registry_repo(tmp_path: Path) -> Path:
_write(
tmp_path,
"owners.yaml",
- "version: 1\nowners: []\nteams:\n"
+ "version: 1\nowners: []\nproducers: [review-bot]\nteams:\n"
" team-registry:\n slack: '#registry-chan'\n"
" team-silent:\n slack: false\n"
- " team-split:\n slack: '#split-people'\n notifications: '#split-bots'\n",
+ " team-split:\n slack: '#split-people'\n notifications: '#split-bots'\n"
+ " team-mapped:\n slack: '#mapped-people'\n notifications:\n review-bot: '#mapped-reviews'\n",
)
_write(tmp_path, "reg/owners.yaml", "version: 1\nowners: [team-registry]\n")
_write(tmp_path, "silent/owners.yaml", "version: 1\nowners: [team-silent]\n")
_write(tmp_path, "derive/owners.yaml", "version: 1\nowners: [team-nonreg]\n")
_write(tmp_path, "indiv/owners.yaml", "version: 1\nowners: ['@alice', team-registry]\n")
_write(tmp_path, "split/owners.yaml", "version: 1\nowners: [team-split]\n")
+ _write(tmp_path, "mapped/owners.yaml", "version: 1\nowners: [team-mapped]\n")
return tmp_path
@@ -870,6 +872,43 @@ def test_json_entrypoint_repo_root_reads_stdin_paths_and_honors_purpose(registry
assert wire["derive/x.py"]["slack"] == "#team-nonreg"
+def _resolve_json(front_door: str, repo: Path, args: list[str]) -> tuple[int, str]:
+ """`resolve --json` and `python -m owners_yaml` on one path, as (exit code, output)."""
+ if front_door == "cli":
+ result = CliRunner().invoke(main, ["resolve", "--json", "--repo-root", str(repo), *args])
+ return result.exit_code, result.output
+ completed = _run_entrypoint(repo, "--repo-root", str(repo), *args)
+ return completed.returncode, completed.stdout + completed.stderr
+
+
[email protected]("front_door", ["cli", "module"])
+ "producer,channel",
+ [
+ (None, "#mapped-people"),
+ ("review-bot", "#mapped-reviews"),
+ ("typo-bot", None),
+ ],
+ ids=["no-producer", "mapped-producer", "undeclared-producer"],
+)
+def test_both_front_doors_pass_the_producer_to_the_channel_lookup(
+ registry_repo: Path, front_door: str, producer: str | None, channel: str | None
+) -> None:
+ # Without the flag a per-producer mapping is never selected, so every bot lands on the people
+ # channel; with an undeclared name it would land there too, which is why that is an error.
+ args = ["--purpose", "notifications", *(["--producer", producer] if producer else []), "mapped/x.py"]
+
+ exit_code, output = _resolve_json(front_door, registry_repo, args)
+
+ if channel is None:
+ assert exit_code != 0
+ assert "unknown producer 'typo-bot'" in output
+ assert "review-bot" in output
+ return
+ assert exit_code == 0, output
+ assert json.loads(output)["mapped/x.py"]["slack"] == channel
+
+
@pytest.mark.parametrize("root", ["nope", ""], ids=["missing", "empty"])
def test_json_entrypoint_rejects_a_repo_root_that_is_not_a_directory(registry_repo: Path, root: str) -> None:
# An empty root is the unset "$VAR" case: Path("") is Path("."), which would
@@ -1047,8 +1086,9 @@ def test_cli_lints_a_tree_that_is_not_a_git_worktree(registry_repo: Path) -> Non
result = CliRunner().invoke(main, ["lint", "--repo-root", str(registry_repo)])
assert result.exit_code == 0, result.output
- # The walk finds the six ownership files plus the two code files, and only loose/code.py is unowned.
- assert "coverage: 2 of 8 tracked file(s) resolve to unowned" in result.output
+ # The walk finds the seven ownership files plus the two code files. The root file declares no
+ # owners, so it and loose/code.py are the unowned two.
+ assert "coverage: 2 of 9 tracked file(s) resolve to unowned" in result.output
def test_cli_live_lint_validates_names_used_only_in_additions(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
diff --git a/posthog/egress/github/README.md b/posthog/egress/github/README.md
index 63dc950635bf..6c2388ee9052 100644
--- a/posthog/egress/github/README.md
+++ b/posthog/egress/github/README.md
@@ -27,6 +27,7 @@ Deferrable background callers construct their client on the `BATCH` lane (`GitHu
A shed sweep stops for the cycle and resumes on the next scheduled run.
A caller that walks pages, such as the warehouse source, paces with `github_installation_pace_seconds` instead of getting denied.
The warehouse source's page fetches run on `BATCH`, while its repository validation and webhook management run on `NORMAL`, because a person waits on them. Customer Analytics feature-request link and resume lookups also run on `NORMAL` because an editor waits for the current issue state. Signals refreshes the stored pull request review decision from GitHub webhooks on `BATCH`; the inbox can keep the last known value when the lane is shed and update it after a retry.
+The ownership file reader (`posthog/ownership/`, source `ownership_github_api`) runs on `NORMAL` where a person waits for a board or a snapshot list, and on `BATCH` for the scheduled digests and report generation. Its GraphQL reads charge `core`, as every GraphQL call does.
The `BATCH` floor on the `core` resource is **demand-responsive**, because a reserve is only worth holding against traffic that exists.
An installation whose only consumer is a bulk one (a warehouse backfill of a repository nothing else touches) would otherwise forfeit 30% of its hourly budget to contention that never arrives, and the hourly budget is what decides whether a large backfill finishes in one run.
diff --git a/posthog/models/integration/github.py b/posthog/models/integration/github.py
index b189647e9eed..28535e68d8e4 100644
--- a/posthog/models/integration/github.py
+++ b/posthog/models/integration/github.py
@@ -13,8 +13,9 @@ from django.conf import settings
import requests
import structlog
-from posthog.egress.github.transport import github_request
+from posthog.egress.github.transport import GitHubRateLimitError, github_request
from posthog.egress.limiter.policies import Priority
+from posthog.egress.transport.transport import EgressBudgetExhausted
from posthog.models.github_integration_base import (
GitHubIntegrationBase,
GitHubIntegrationError,
@@ -321,13 +322,27 @@ class GitHubIntegration(GitHubIntegrationBase):
check below interpolates it into an authenticated ``GET /repos/{repository}``. Reject anything
that isn't a plain ``owner/repo`` first, so a crafted value (``owner/repo/contents/x?ref=y``)
can't steer that authenticated request to a different GitHub endpoint as a probe.
+
+ An installation whose probe runs out of egress budget or hits GitHub's rate limit is
+ skipped. When no other installation covers the repository, that first error is raised.
"""
if not _is_safe_github_repo_path(repository):
return None
+ exhausted: Exception | None = None
for integration in model.Integration.objects.filter(team_id=team_id, kind="github").order_by("id"):
github = cls(integration, source=source, priority=priority)
- if github.installation_can_access_repository(repository):
+ try:
+ covers = github.installation_can_access_repository(repository)
+ except (EgressBudgetExhausted, GitHubRateLimitError) as e:
+ # A team's first installation being out of budget must not hide a later one that
+ # covers the repository. The first error is kept and raised only when none does,
+ # so a caller that has no reader still sees why.
+ exhausted = exhausted or e
+ continue
+ if covers:
return github
+ if exhausted is not None:
+ raise exhausted
return None
def __init__(
diff --git a/posthog/models/test/integration/test_github.py b/posthog/models/test/integration/test_github.py
index 0b2515ffda11..cb434ef5203c 100644
--- a/posthog/models/test/integration/test_github.py
+++ b/posthog/models/test/integration/test_github.py
@@ -872,6 +872,39 @@ class TestGitHubIntegrationModel(BaseTest):
assert result is not None
mock_access.assert_called_once_with("PostHog/posthog")
+ @parameterized.expand(
+ [
+ ("our_budget", GitHubEgressBudgetExhausted("shed")),
+ ("githubs_limit", GitHubRateLimitError("429")),
+ ]
+ )
+ def test_first_for_team_repository_looks_past_an_exhausted_installation(self, _name, error):
+ # The search is ordered by id, so an exhausted first installation would otherwise hide a
+ # healthy later one that covers the repository.
+ self.create_integration(sensitive_config={"access_token": "FIRST"})
+ covering = self.create_integration(sensitive_config={"access_token": "SECOND"})
+ with patch.object(GitHubIntegration, "installation_can_access_repository", side_effect=[error, True]):
+ result = GitHubIntegration.first_for_team_repository(self.team.id, "PostHog/posthog")
+ assert result is not None
+ assert result.integration.id == covering.id
+
+ @parameterized.expand(
+ [
+ ("our_budget", GitHubEgressBudgetExhausted("shed")),
+ ("githubs_limit", GitHubRateLimitError("429")),
+ ]
+ )
+ def test_first_for_team_repository_raises_when_only_an_exhausted_installation_could_have_covered(
+ self, _name, error
+ ):
+ # No other installation answered, so the caller has to hear why rather than read it as
+ # "this team has no integration for the repository".
+ self.create_integration(sensitive_config={"access_token": "FIRST"})
+ self.create_integration(sensitive_config={"access_token": "SECOND"})
+ with patch.object(GitHubIntegration, "installation_can_access_repository", side_effect=[error, False]):
+ with pytest.raises(type(error)):
+ GitHubIntegration.first_for_team_repository(self.team.id, "PostHog/posthog")
+
@parameterized.expand(
[
("owner_repo", "PostHog/posthog", "https://api.github.com/repos/PostHog/posthog/pulls/123"),
diff --git a/posthog/ownership/README.md b/posthog/ownership/README.md
new file mode 100644
index 000000000000..eb847ff5ebc6
--- /dev/null
+++ b/posthog/ownership/README.md
@@ -0,0 +1,61 @@
+# Ownership
+
+Who owns a path in a code repository.
+
+The answer comes from the repository's own `owners.yaml` files, parsed by the `owners_yaml` package.
+This module adds the part `owners_yaml` does not have: a source that reads those files over the network.
+A server process has no checkout of the repository it reports on.
+
+Both readers read the default branch, never the head of a pull request.
+A pull request can edit ownership files, so a read at its head would let it name its own owners and route its own approval.
+
+## Layout
+
+- `repo_files.py`: `GitHubRepoFiles`, the anonymous source, plus the `RepoFiles` protocol and the `OwnershipUnavailable` errors.
+- `github_files.py`: `GitHubFilesFetcher`, the authenticated reader, `AuthenticatedRepoFiles`, the source built on it, and `fetcher_for_team`.
+- `paths.py`: `resolve_path_owners`, the entry point, and the `PathOwnership` contract it returns.
+
+## Callers
+
+- Engineering analytics: the team that owns a quarantined test.
+- Visual review: the team that owns a Storybook snapshot, and the debt digest that splits per team.
+- Signals: the team that owns the files a pull request changes.
+
+## Behavior
+
+Reads are fail-closed.
+One unreadable file makes every other answer in the batch suspect, so the whole batch fails together.
+`PathOwnership.resolved` is then false, every path is `UNOWNED_TEAM`, and the registry is empty.
+A repository with no root `owners.yaml` resolves to the same answer, because a private or renamed repository answers 404 to every path and cannot be told apart from one that declares nothing.
+
+The whole resolution has a time budget, so a stalled host releases the worker instead of holding it.
+A file above the size limit is refused.
+All GitHub traffic goes through the GitHub egress transport, and every caller names its lane: `NORMAL` where a person waits for the page, `BATCH` for scheduled work.
+
+## How the files are read
+
+There are two readers, and a caller picks one by what credential it holds.
+
+`AuthenticatedRepoFiles` reads through the GitHub GraphQL API with a credential.
+It resolves the default branch's head commit first, then reads the batch's files at that commit, about a hundred files per request, with the chunks in parallel.
+GitHub charges one rate-limit point per request whatever the number of aliased files in it, and it answers a few hundred files with a 502, which is what sets the chunk size.
+A file the commit does not hold comes back as absent.
+This reader answers for a private repository.
+
+`GitHubRepoFiles` reads `raw.githubusercontent.com` anonymously, one request per file, and caches for six hours with jitter.
+The raw host serves public repositories only, so this reader is the fallback for a repository no credential covers.
+It reads at the ref `HEAD` rather than at a commit, because it has no credential to ask the API which commit the default branch points at.
+
+The authenticated reader caches per commit.
+The content at a commit never changes, so a blob is held for a day; the head lookup is held for about two minutes, and that is the whole staleness window of an ownership change.
+The cache key names the credential's audience, an installation or a digest of a token, because a private repository one installation can read is not readable by the next caller that names the same repository.
+A token never reaches a cache key or a log line.
+Pass `fresh_head=True` when the run derives a decision it never stores and so cannot correct later, such as digest routing, and the reader asks GitHub for the head instead of reading that shared entry.
+
+## How a caller gets a source
+
+- The caller holds a GitHub integration: `AuthenticatedRepoFiles(repository, GitHubFilesFetcher.from_integration(integration, priority=...))`.
+- The caller holds a bare token, such as a warehouse source's personal access token or a product's own installation token: `GitHubFilesFetcher.from_token(token, installation_id=..., priority=...)`.
+- The caller holds only a team: `fetcher_for_team(team_id, repository, priority=...)`, which finds the team's GitHub integration whose installation covers the repository and falls back to the anonymous reader.
+
+`resolve_path_owners` still defaults to the anonymous reader, so a caller that passes no source keeps working.
diff --git a/posthog/ownership/__init__.py b/posthog/ownership/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/posthog/ownership/github_files.py b/posthog/ownership/github_files.py
new file mode 100644
index 000000000000..470b026a84b0
--- /dev/null
+++ b/posthog/ownership/github_files.py
@@ -0,0 +1,468 @@
+"""A repository's ownership files read from the GitHub API with a credential.
+
+The raw host in ``repo_files`` serves public repositories only, and it costs one request per file.
+This module reads the same files through the GitHub GraphQL API, which authenticates, answers for a
+private repository, and returns about a hundred files per request.
+
+Every read is pinned to the default branch's head commit. The content at a commit never changes, so
+the cache needs no invalidation, and a merge is visible as soon as the short-lived head lookup
+expires. The anonymous raw host reader has no credential to learn the head commit, so it reads at
+the ref `HEAD` and keeps its own cache and its own six-hour staleness window.
+"""
+
+import json
+from collections.abc import Callable, Sequence
+from functools import partial
+from http import HTTPStatus
+from typing import Any
+
+import requests
+import structlog
+
+from posthog.egress.github.transport import GitHubRateLimitError, github_request, raise_if_github_rate_limited
+from posthog.egress.limiter.policies import Priority
+from posthog.egress.observability.observability import scope_fingerprint
+from posthog.egress.transport.transport import EgressBudgetExhausted
+from posthog.models.github_integration_base import GitHubIntegrationBase
+from posthog.models.integration import GitHubIntegration, Integration
+from posthog.models.integration.github import _is_safe_github_repo_path
+from posthog.ownership.repo_files import (
+ _ABSENT,
+ _MAX_FILE_BYTES,
+ CachedRepoFiles,
+ GitHubRepoFiles,
+ OwnershipUnavailable,
+ _fetch_all,
+ capped_text,
+ pooled_session,
+)
+from posthog.utils import get_safe_cache, safe_cache_set
+
+logger = structlog.get_logger(__name__)
+
+_API_HOST = "https://api.github.com"
+_GRAPHQL_URL = f"{_API_HOST}/graphql"
+# A separate label from the raw host's, because these calls are authenticated and land on a
+# different meter. Renaming either one would break the dashboards that already query them.
+EGRESS_SOURCE = "ownership_github_api"
+_HEAD_ENDPOINT = "/graphql:ownershipHeadCommit"
+_FILES_ENDPOINT = "/graphql:ownershipFiles"
+_TIMEOUT_SECONDS = 10.0
+
+# GitHub charges one rate-limit point for a whole aliased query, so the files of a batch cost one
+# point per chunk. The ceiling is latency and the server's own limits: this repo answers about a
+# hundred files in a few seconds and refuses four hundred with a 502.
+_CHUNK_FILES = 100
+
+_CACHE_PREFIX = "ownership:github_api"
+# A commit's content is immutable, so the TTL only releases memory. Nothing reads a commit's entries
+# after the head moves past it, so a longer TTL only keeps dead keys in the shared cache.
+# No jitter: a whole batch expiring together can only stampede for a commit that nothing has read
+# for a day, and that answer is worth refetching anyway.
+_BLOB_CACHE_TTL_SECONDS = 24 * 60 * 60
+# Short, because this is the whole staleness window of an ownership change. Long enough that a burst
+# of page loads asks GitHub for the head once rather than once each.
+_HEAD_CACHE_TTL_SECONDS = 120
+# Which integration covers a repository costs one uncached GitHub probe per integration the team
+# has, and a page load asks for it on every request. Short for the same reason as the head lookup:
+# a repository added to an installation has to become readable without anyone clearing a cache.
+_INTEGRATION_CACHE_TTL_SECONDS = 120
+# No integration covers the repository. A row id is never 0, so the negative needs no second key.
+_NO_COVERING_INTEGRATION = 0
+# One answer carries up to _CHUNK_FILES blobs, and the per-file limit alone would let a chunk of
+# near-limit files materialize a hundred megabytes in a worker and in the cache. A real ownership
+# file is a few kilobytes, so a whole chunk of them is tens of kilobytes; this leaves that room many
+# times over and still bounds what one answer can cost.
+_MAX_RESPONSE_BYTES = 4 * 1024 * 1024
+
+_HEAD_QUERY = """
+query($owner: String!, $name: String!) {
+ repository(owner: $owner, name: $name) {
+ defaultBranchRef { target { oid } }
+ }
+}
+"""
+
+# Each file is one aliased `object` lookup. The path rides in a variable rather than in the query
+# text, so a path can never change the shape of the query. `isTruncated` comes along because GitHub
+# cuts a large blob's `text` short without saying so anywhere else in the answer.
+_TEXT_SELECTION = "... on Blob { text isTruncated }"
+_EXISTS_SELECTION = "__typename"
+
+
+def _token_audience(token: str) -> str:
+ """A stable name for what one token is allowed to read.
+
+ Two credentials must never share cached file content: a private repository one installation can
+ read is not readable by the next caller that names the same repository. The token itself must
+ stay out of the key, so the key carries the same digest the egress metrics use for an identity
+ that cannot appear in plain form.
+ """
+ return f"token:{scope_fingerprint(token)}"
+
+
+def _files_query(count: int, selection: str) -> str:
+ variables = ", ".join(f"$p{index}: String!" for index in range(count))
+ fields = "\n".join(f" f{index}: object(expression: $p{index}) {{ {selection} }}" for index in range(count))
+ return f"query($owner: String!, $name: String!, {variables}) {{\n repository(owner: $owner, name: $name) {{\n{fields}\n }}\n}}"
+
+
+def _chunks(paths: Sequence[str]) -> list[tuple[str, ...]]:
+ return [tuple(paths[start : start + _CHUNK_FILES]) for start in range(0, len(paths), _CHUNK_FILES)]
+
+
+def _entry(field: dict[str, Any], index: int) -> dict[str, Any] | None:
+ # Only an explicit null means absent. Reading a malformed alias as absent moves ownership to an ancestor.
+ alias = f"f{index}"
+ if alias not in field:
+ raise OwnershipUnavailable(f"the answer has no {alias} lookup")
+ entry = field[alias]
+ if entry is not None and not isinstance(entry, dict):
+ raise OwnershipUnavailable(f"the {alias} lookup is not an object")
+ return entry
+
+
+def _is_blob(entry: dict[str, Any] | None) -> bool:
+ return entry is not None and entry.get("__typename") == "Blob"
+
+
+def _refreshed_installation_token(integration: GitHubIntegrationBase) -> str:
+ """A newly minted installation token.
+
+ ``get_access_token`` returns the stored token until it is close to expiry, so it can hand back
+ the very token a 401 has just refused. Only ``refresh_access_token`` mints a new one.
+ """
+ integration.refresh_access_token()
+ return integration.get_access_token()
+
+
+class GitHubFilesFetcher:
+ """Reads a repository's files from the GitHub GraphQL API with one credential.
+
+ Build one with :meth:`from_integration` or :meth:`from_token`. It holds the batch's HTTP
+ connections and its token, so construct one per batch.
+ """
+
+ @classmethod
+ def from_integration(cls, integration: GitHubIntegrationBase, *, priority: Priority) -> "GitHubFilesFetcher":
+ """Read as a GitHub App installation, which is what a connected team already has."""
+ installation_id = integration.github_installation_id
+ return cls(
+ token=integration.get_access_token,
+ refresh=partial(_refreshed_installation_token, integration),
+ installation_id=installation_id,
+ audience=(
+ f"installation:{installation_id}"
+ if installation_id
+ else f"integration:{type(integration.integration).__name__}:{integration.integration.pk}"
+ ),
+ priority=priority,
+ )
+
+ @classmethod
+ def from_token(
+ cls,
+ token: str,
+ *,
+ installation_id: str | None = None,
+ refresh: Callable[[], str] | None = None,
+ priority: Priority,
+ ) -> "GitHubFilesFetcher":
+ """Read with a token the caller already holds: a personal access token, or an installation
+ token minted by a product's own GitHub App. Pass ``installation_id`` when the token belongs
+ to an installation, so the calls are gated on that installation's shared budget.
+
+ ``refresh`` mints a replacement after a 401, for a caller that can mint one. A personal
+ access token cannot be re-minted, so it leaves ``refresh`` unset and fails closed instead."""
+ return cls(
+ token=lambda: token,
+ refresh=refresh,
+ installation_id=installation_id,
+ audience=f"installation:{installation_id}" if installation_id else _token_audience(token),
+ priority=priority,
+ )
+
+ def __init__(
+ self,
+ *,
+ token: Callable[[], str],
+ installation_id: str | None,
+ audience: str,
+ priority: Priority,
+ refresh: Callable[[], str] | None = None,
+ ) -> None:
+ self.audience = audience
+ self._token = token
+ self._refresh = refresh
+ self._resolved_token: str | None = None
+ self._installation_id = installation_id
+ self._priority = priority
+ self._session = pooled_session(_API_HOST)
+
+ def head_commit_sha(self, repository: str) -> str | None:
+ """The commit at the head of the repository's default branch, or None when there is none.
+
+ A repository with no commits has no default branch, and GitHub answers that with a null
+ ``defaultBranchRef`` and no error. It holds no file, so that is a normal answer rather than
+ an unreadable one: a caller that fails it instead would take down every repository it reads
+ beside this one.
+ """
+ field = self._graphql(repository, _HEAD_QUERY, {}, endpoint=_HEAD_ENDPOINT)
+ ref = field.get("defaultBranchRef")
+ if ref is None:
+ return None
+ target = ref.get("target") if isinstance(ref, dict) else None
+ sha = target.get("oid") if isinstance(target, dict) else None
+ if not isinstance(sha, str) or not sha:
+ raise OwnershipUnavailable(f"{repository} named no default branch head")
+ return sha
+
+ def read_files(self, repository: str, sha: str, paths: Sequence[str], deadline: float) -> dict[str, str]:
+ """The text of every path at ``sha``, with ``_ABSENT`` for a path the commit does not hold."""
+ return self._read_chunks(repository, sha, paths, deadline, _TEXT_SELECTION, self._text)
+
+ def files_exist(self, repository: str, sha: str, paths: Sequence[str], deadline: float) -> dict[str, bool]:
+ """Whether the commit holds each path as a file. Asks for no body, because most probed paths
+ are candidates a batch only wants to rule out."""
+ return self._read_chunks(
+ repository, sha, paths, deadline, _EXISTS_SELECTION, lambda _path, entry: _is_blob(entry)
+ )
+
+ def _text(self, path: str, entry: dict[str, Any] | None) -> str:
+ if entry is None:
+ return _ABSENT
+ if entry.get("isTruncated"):
+ # GitHub cuts a large blob's text short and still answers 200. Parsing the prefix would
+ # read as a complete file and cache a wrong ownership answer for the whole TTL.
+ raise OwnershipUnavailable(f"{path} came back truncated")
+ text = entry.get("text")
+ if not isinstance(text, str):
+ # GitHub answers with no text for a binary or oversized blob, and an ownership file is
+ # neither. Reading it as absent would reattribute everything under it to an ancestor.
+ raise OwnershipUnavailable(f"{path} is not readable as text")
+ if len(text.encode()) > _MAX_FILE_BYTES:
+ raise OwnershipUnavailable(f"{path} exceeds the {_MAX_FILE_BYTES}-byte limit")
+ return text
+
+ def _read_chunks(
+ self,
+ repository: str,
+ sha: str,
+ paths: Sequence[str],
+ deadline: float,
+ selection: str,
+ parse: "Callable[[str, dict[str, Any] | None], Any]",
+ ) -> dict[str, Any]:
+ def read_chunk(chunk: tuple[str, ...]) -> dict[str, Any]:
+ query = _files_query(len(chunk), selection)
+ variables = {f"p{index}": f"{sha}:{path}" for index, path in enumerate(chunk)}
+ field = self._graphql(repository, query, variables, endpoint=_FILES_ENDPOINT, deadline=deadline)
+ return {path: parse(path, _entry(field, index)) for index, path in enumerate(chunk)}
+
+ results: dict[str, Any] = {}
+ for chunk in _fetch_all(read_chunk, _chunks(list(dict.fromkeys(paths))), deadline).values():
+ results.update(chunk)
+ return results
+
+ def _graphql(
+ self,
+ repository: str,
+ query: str,
+ variables: dict[str, str],
+ *,
+ endpoint: str,
+ deadline: float | None = None,
+ ) -> dict[str, Any]:
+ """The ``repository`` object of one GraphQL answer.
+
+ Anything else raises rather than reading as an empty repository, because a repository the
+ credential cannot see answers the same way as one that declares nothing.
+ """
+ if not _is_safe_github_repo_path(repository):
+ # A connected source's repository name is team-writable, so a crafted value must not
+ # steer the query at a repository the caller did not name.
+ raise OwnershipUnavailable(f"unsafe repository path: {repository!r}")
+ owner, name = repository.split("/", 1)
+ payload = {"query": query, "variables": {"owner": owner, "name": name, **variables}}
+ status, body = self._answer(repository, payload, endpoint=endpoint, deadline=deadline)
+ if status == HTTPStatus.UNAUTHORIZED and self._refresh is not None:
+ # The token was revoked or rotated under the batch, and it stays memoized, so every
+ # later read would fail with it too. A 401 means nothing ran, so the retry is safe.
+ self._refresh_token(repository)
+ status, body = self._answer(repository, payload, endpoint=endpoint, deadline=deadline)
+ if status != HTTPStatus.OK:
+ raise OwnershipUnavailable(f"{repository} answered {status} for {endpoint}")
+ errors = body.get("errors") if isinstance(body, dict) else None
+ if errors:
+ # GitHub reports a path the commit does not hold as a null alias and no error at all, so
+ # an error means the alias failed rather than being absent. A partial answer also carries
+ # the repository object, and reading its null aliases as absent files would cache that
+ # absence for the whole TTL and move ownership to an ancestor.
+ raise OwnershipUnavailable(f"{repository} answered with errors for {endpoint}: {errors}")
+ data = body.get("data") if isinstance(body, dict) else None
+ field = data.get("repository") if isinstance(data, dict) else None
+ if not isinstance(field, dict):
+ raise OwnershipUnavailable(f"{repository} is unreadable for {endpoint}")
+ return field
+
+ def _answer(
+ self, repository: str, payload: dict[str, Any], *, endpoint: str, deadline: float | None
+ ) -> tuple[int, Any]:
+ """One POST's status and decoded body, read under the response cap and closed before it
+ returns."""
+ with self._post(repository, payload, endpoint=endpoint) as response:
+ if response.status_code != HTTPStatus.OK:
+ return response.status_code, None
+ text = capped_text(
+ response,
+ description=f"the {endpoint} answer for {repository}",
+ limit=_MAX_RESPONSE_BYTES,
+ deadline=deadline,
+ )
+ try:
+ return HTTPStatus.OK, json.loads(text)
+ except ValueError as e:
+ raise OwnershipUnavailable(f"{repository} answered with no JSON for {endpoint}") from e
+
+ def _post(self, repository: str, payload: dict[str, Any], *, endpoint: str) -> requests.Response:
+ try:
+ response = github_request(
+ "POST",
+ _GRAPHQL_URL,
+ source=EGRESS_SOURCE,
+ headers={"Authorization": f"Bearer {self._token_value()}"},
+ installation_id=self._installation_id,
+ priority=self._priority,
+ endpoint=endpoint,
+ json=payload,
+ timeout=_TIMEOUT_SECONDS,
+ session=self._session,
+ # The body is read under a cap in _answer, so it must not be buffered whole first.
+ stream=True,
+ )
+ # A rate limit answers 403 or 429, which would otherwise read as a plain refusal. It is
+ # still fail-closed, but the failure says which of the two it was.
+ raise_if_github_rate_limited(response)
+ except Exception as e:
+ raise OwnershipUnavailable(f"could not read ownership files from {repository}: {e}") from e
+ return response
+
+ def _refresh_token(self, repository: str) -> None:
+ if self._refresh is None:
+ return
+ try:
+ self._resolved_token = self._refresh()
+ except Exception as e:
+ raise OwnershipUnavailable(f"could not refresh the credential for {repository}: {e}") from e
+
+ def _token_value(self) -> str:
+ # Once per batch: an integration mints or refreshes its token here, and a batch is far
+ # shorter than a token's life.
+ if self._resolved_token is None:
+ self._resolved_token = self._token()
+ return self._resolved_token
+
+
+class AuthenticatedRepoFiles(CachedRepoFiles):
+ """A repository's ownership files read with a credential, cached per commit.
+
+ Build one per batch: it holds the batch's memo, its head commit, and its time budget.
+
+ ``fresh_head`` asks GitHub for the head on this run rather than reading the shared head cache,
+ for a caller that derives a decision it never stores and so cannot correct later. It still
+ writes the head cache, and blob reads stay cached because content at a commit never changes.
+ """
+
+ def __init__(self, repository: str, fetcher: GitHubFilesFetcher, *, fresh_head: bool = False) -> None:
+ super().__init__(repository)
+ self._fetcher = fetcher
+ self._fresh_head = fresh_head
+ self._sha: str | None = None
+
+ def _head_commit_sha(self) -> str | None:
+ if self._sha is None:
+ key = f"{_CACHE_PREFIX}:head:{self._fetcher.audience}:{self.repository}"
+ cached = None if self._fresh_head else get_safe_cache(key)
+ if isinstance(cached, str) and cached:
+ self._sha = cached
+ else:
+ self._sha = self._fetcher.head_commit_sha(self.repository)
+ if self._sha is not None:
+ safe_cache_set(key, self._sha, _HEAD_CACHE_TTL_SECONDS)
+ return self._sha
+
+ def _commit(self) -> str:
+ sha = self._head_commit_sha()
+ if sha is None:
+ raise OwnershipUnavailable(f"{self.repository} has no commits")
+ return sha
+
+ def _cache_key(self, kind: str, path: str) -> str:
+ return f"{_CACHE_PREFIX}:{kind}:{self._fetcher.audience}:{self.repository}:{self._commit()}:{path}"
+
+ def _cache_ttl(self) -> int:
+ return _BLOB_CACHE_TTL_SECONDS
+
+ def _read_missing(self, paths: list[str]) -> dict[str, str]:
+ return self._fetcher.read_files(self.repository, self._commit(), paths, self._deadline)
+
+ def _probe_missing(self, paths: list[str]) -> dict[str, bool]:
+ return self._fetcher.files_exist(self.repository, self._commit(), paths, self._deadline)
+
+ def read_all(self, paths: list[str]) -> None:
+ if self._head_commit_sha() is None:
+ # A repository with no commits holds no file. There is no commit to key a cache entry
+ # by, so the absence is answered per batch rather than written to the cache.
+ self._bodies.update({path: _ABSENT for path in paths if path not in self._bodies})
+ return
+ super().read_all(paths)
+
+ def exists_all(self, paths: list[str]) -> dict[str, bool]:
+ if self._head_commit_sha() is None:
+ return dict.fromkeys(paths, False)
+ return super().exists_all(paths)
+
+
+def _covering_integration(team_id: int, repository: str, *, priority: Priority) -> GitHubIntegration | None:
+ """The team's GitHub integration whose installation can read the repository.
+
+ The lookup itself probes GitHub once per integration the team has, uncached, and a page load
+ asks for it on every request. Only the decision is cached, never a token: the id of the
+ integration that answered, or the marker for "none of them did", so a team with no installation
+ does not re-probe either.
+ """
+ key = f"{_CACHE_PREFIX}:integration:{team_id}:{repository.casefold()}"
+ cached = get_safe_cache(key)
+ if isinstance(cached, int):
+ if cached == _NO_COVERING_INTEGRATION:
+ return None
+ integration = Integration.objects.filter(team_id=team_id, id=cached, kind="github").first()
+ # A disconnected integration falls through to a fresh lookup rather than to no reader.
+ if integration is not None:
+ return GitHubIntegration(integration, source=EGRESS_SOURCE, priority=priority)
+ covering = GitHubIntegration.first_for_team_repository(team_id, repository, source=EGRESS_SOURCE, priority=priority)
+ decision = covering.integration.pk if covering is not None else _NO_COVERING_INTEGRATION
+ safe_cache_set(key, decision, _INTEGRATION_CACHE_TTL_SECONDS)
+ return covering
+
+
+def fetcher_for_team(
+ team_id: int, repository: str, *, priority: Priority
+) -> "AuthenticatedRepoFiles | GitHubRepoFiles":
+ """The best reader the team has for this repository.
+
+ A team whose GitHub App installation covers the repository reads it authenticated, which also
+ works for a private repository. Every other team falls back to the anonymous raw host, which
+ answers for a public repository only.
+ """
+ try:
+ integration = _covering_integration(team_id, repository, priority=priority)
+ except (EgressBudgetExhausted, GitHubRateLimitError):
+ # The probe is optional enrichment for a caller that already handles an unresolved answer,
+ # so a spent budget must degrade rather than raise past it. Nothing is cached: the next
+ # call has to probe again once the budget refills.
+ logger.warning("ownership_covering_integration_budget_exhausted", team_id=team_id, repository=repository)
+ return GitHubRepoFiles(repository)
+ if integration is None:
+ return GitHubRepoFiles(repository)
+ return AuthenticatedRepoFiles(repository, GitHubFilesFetcher.from_integration(integration, priority=priority))
diff --git a/posthog/ownership/paths.py b/posthog/ownership/paths.py
new file mode 100644
index 000000000000..42f6ab4bef71
--- /dev/null
+++ b/posthog/ownership/paths.py
@@ -0,0 +1,77 @@
+"""Which team owns each path of a repository, resolved from the repository's own ownership files.
+
+The answer comes from the repository as it stands, not from anything PostHog stores, so a caller
+needs no team and gets whoever owes the work now.
+"""
+
+from collections.abc import Mapping, Sequence
+
+import structlog
+from owners_yaml import OwnersResolver
+from owners_yaml.resolver import teams_registry
+from owners_yaml.schema import TeamEntry
+from pydantic.dataclasses import dataclass
+
+from posthog.ownership.repo_files import (
+ ROOT_OWNERS_FILE,
+ GitHubRepoFiles,
+ NoRootOwnersFile,
+ OwnershipUnavailable,
+ RepoFiles,
+)
+
+logger = structlog.get_logger(__name__)
+
+# The first-class team every unattributed path aggregates under, on every surface that reads this.
+UNOWNED_TEAM = "unowned"
+
+
+@dataclass(frozen=True)
+class PathOwnership:
+ """Which team owns each repository path, plus the repo's Slack registry from the root ``owners.yaml``.
+ The registry rides along because the caller that asks who owns a path usually has to reach that
+ team next, and the root file answers both questions in one read.
+
+ ``resolved`` is false when the ownership files could not be read; every path is then
+ ``UNOWNED_TEAM`` and the registry is empty. A caller that says so beats one that reads the blind
+ answer as "nobody owns this"."""
+
+ team_by_path: Mapping[str, str]
+ registry: Mapping[str, TeamEntry]
+ resolved: bool
+
+
+def _team(owners: list[str] | None) -> str:
+ """An '@handle' owner is a person, and every surface downstream keys on a team slug."""
+ return next((owner for owner in owners or [] if not owner.startswith("@")), UNOWNED_TEAM)
+
+
+def own_paths(files: RepoFiles, root: str, paths: list[str]) -> PathOwnership:
+ owners = OwnersResolver(source=files).map(paths)
+ return PathOwnership(
+ team_by_path={path: _team(owners[path].owners) for path in paths},
+ registry=teams_registry(root),
+ resolved=True,
+ )
+
+
+def read_root(repository: str, files: RepoFiles) -> str:
+ root = files.read(ROOT_OWNERS_FILE)
+ if root is None:
+ raise NoRootOwnersFile(f"{repository} has no root {ROOT_OWNERS_FILE}")
+ return root
+
+
+def resolve_path_owners(repository: str, paths: Sequence[str], files: RepoFiles | None = None) -> PathOwnership:
+ """Name the team that owns each repository path, and return the repo's Slack registry. Paths must
+ be repo-relative: unlike reported test paths, they get no candidate-path search."""
+ reader = files if files is not None else GitHubRepoFiles(repository)
+ try:
+ return own_paths(reader, read_root(repository, reader), list(dict.fromkeys(paths)))
+ except NoRootOwnersFile:
+ # Most repositories declare no owners.yaml, so this is no error for a caller to act on.
+ logger.info("repo_path_ownership_no_root_file", repository=repository)
+ return PathOwnership(team_by_path=dict.fromkeys(paths, UNOWNED_TEAM), registry={}, resolved=False)
+ except OwnershipUnavailable:
+ logger.exception("repo_path_ownership_unavailable", repository=repository)
+ return PathOwnership(team_by_path=dict.fromkeys(paths, UNOWNED_TEAM), registry={}, resolved=False)
diff --git a/posthog/ownership/repo_files.py b/posthog/ownership/repo_files.py
new file mode 100644
index 000000000000..8ca57f61da91
--- /dev/null
+++ b/posthog/ownership/repo_files.py
@@ -0,0 +1,259 @@
+"""A repository's ownership files, read over the network and cached.
+
+The web container has no checkout, so the files are fetched from the repository's default branch.
+A read that fails is fail-closed: the caller gets no attribution rather than a partial one.
+"""
+
+import random
+from collections.abc import Callable, Iterable
+from concurrent.futures import ThreadPoolExecutor
+from http import HTTPStatus
+from time import monotonic
+from typing import Any, Protocol, TypeVar
+
+from django.core.cache import cache
+
+import requests
+import structlog
+from owners_yaml import BatchOwnershipSource
+from requests.adapters import HTTPAdapter
+
+from posthog.egress.github.transport import github_request
+from posthog.models.integration.github import _is_safe_github_repo_path
+
+logger = structlog.get_logger(__name__)
+
+_T = TypeVar("_T")
+_K = TypeVar("_K")
+
+# The raw host serves a public repo's files off a CDN, so these reads draw on no GitHub API rate
+# limit, and the HEAD ref follows the default branch. A private repo answers 404 to all of it, which
+# the root-file guard in read_root catches.
+_RAW_HOST = "https://raw.githubusercontent.com"
+_REF = "HEAD"
+_EGRESS_SOURCE = "engineering_analytics_ownership"
+# Egress metrics are labeled by endpoint, so a raw file path per label would be unbounded.
+_EGRESS_ENDPOINT = "/{owner}/{repo}/{ref}/{path}"
+_TIMEOUT_SECONDS = 5.0
+_FETCH_WORKERS = 16
+# A connected repository controls these files, so an unbounded read would put its bytes in a
+# worker's memory and in Redis. An ownership file is a few KB; this repo's whole set is under 25 KB.
+_MAX_FILE_BYTES = 1024 * 1024
+# The whole resolution, not one request. A quarantine snapshot is capped at HogQL's implicit 100
+# rows, so a cold board can ask for hundreds of files; if the raw host stalls, the per-request
+# timeout alone would still let one board load hold a web worker for minutes. Past this the board
+# says ownership is unavailable, which beats hanging.
+_RESOLVE_BUDGET_SECONDS = 20.0
+
+# Ownership files change at review speed, so a stale answer stays right, and only the request that
+# finds the cache cold pays for the fetches. A batch writes every key at once, so the jitter spreads
+# their expiry over later requests instead of stranding one with the whole refetch.
+_CACHE_TTL_SECONDS = 6 * 60 * 60
+_CACHE_TTL_JITTER_SECONDS = 60 * 60
+_CACHE_PREFIX = "eng_analytics:repo_file"
+# Absence needs a cache value of its own, and no file holds this one.
+_ABSENT = "\x00absent"
+
+ROOT_OWNERS_FILE = "owners.yaml"
+
+
+class OwnershipUnavailable(Exception):
+ """The repository's ownership files could not be read, so no attribution is trustworthy."""
+
+
+class NoRootOwnersFile(OwnershipUnavailable):
+ """The repository answers with no root owners file, which is normal for most repositories."""
+
+
+class RepoFiles(BatchOwnershipSource, Protocol):
+ """A repository's ownership files: one file, or a whole batch's before the resolver reads any."""
+
+
+def _fetch_all(fetch: Callable[[_K], _T], keys: Iterable[_K], deadline: float) -> dict[_K, _T]:
+ """Fetch every distinct key concurrently, within what is left of the batch's budget. The one
+ place this package waits on the network. A key is one file for the raw host, and one chunk of
+ files for the GraphQL reader."""
+ todo = list(dict.fromkeys(keys))
+ if not todo:
+ return {}
+ pool = ThreadPoolExecutor(max_workers=min(_FETCH_WORKERS, len(todo)))
+ try:
+ futures = {key: pool.submit(fetch, key) for key in todo}
+ return {key: future.result(max(deadline - monotonic(), 0)) for key, future in futures.items()}
+ except TimeoutError as e:
+ raise OwnershipUnavailable(f"ownership took longer than {_RESOLVE_BUDGET_SECONDS}s") from e
+ finally:
+ # Not a `with` block: its exit waits for every running fetch, which holds the request thread
+ # past the deadline. A lost batch drops the queued fetches and leaves the running ones to
+ # stop at the same deadline on their own, which the read in capped_text enforces.
+ pool.shutdown(wait=False, cancel_futures=True)
+
+
+def capped_text(response: requests.Response, *, description: str, limit: int, deadline: float | None = None) -> str:
+ """A streamed response body as text, refused past ``limit`` bytes.
+
+ The body belongs to the connected repository, so an unbounded read would put its bytes in a
+ worker's memory and in Redis. ``description`` names what is being read, for the failure.
+ """
+ too_large = f"{description} exceeds the {limit}-byte limit"
+ # Content-Length can be absent or wrong, so the streamed read below is the actual ceiling.
+ declared = response.headers.get("Content-Length")
+ if declared is not None and declared.isdigit() and int(declared) > limit:
+ raise OwnershipUnavailable(too_large)
+ body = bytearray()
+ for chunk in response.iter_content(chunk_size=8192):
+ # The request timeout starts again on every chunk received, so a host that sends the body
+ # slowly enough holds this read for as long as the byte limit allows. _fetch_all stops
+ # waiting for a fetch at the deadline, so the fetch stops at the first chunk after it,
+ # which the request timeout puts within _TIMEOUT_SECONDS of the deadline.
+ if deadline is not None and monotonic() > deadline:
+ raise OwnershipUnavailable(f"reading {description} passed the resolution budget")
+ body.extend(chunk)
+ if len(body) > limit:
+ raise OwnershipUnavailable(too_large)
+ return body.decode(response.encoding or "utf-8", errors="replace")
+
+
+def pooled_session(host: str) -> requests.Session:
+ """A session whose connection pool is as wide as the fetch pool.
+
+ requests pools ten connections by default and discards the overflow, so a smaller pool than the
+ worker count makes most of a batch pay a fresh TLS handshake.
+ """
+ session = requests.Session()
+ session.mount(host, HTTPAdapter(pool_connections=_FETCH_WORKERS, pool_maxsize=_FETCH_WORKERS))
+ return session
+
+
+def _cache_get_many(keys: list[str]) -> dict[str, Any]:
+ """The cached values of ``keys``. An unreachable cache reads as all misses.
+
+ The cache only saves requests. A Redis outage must not turn every ownership answer into an
+ error page, because the files can still be read from GitHub.
+ """
+ try:
+ return cache.get_many(keys)
+ except Exception:
+ logger.warning("ownership_cache_read_failed", exc_info=True)
+ return {}
+
+
+def _cache_set_many(values: dict[str, Any], ttl: int) -> None:
+ try:
+ cache.set_many(values, ttl)
+ except Exception:
+ logger.warning("ownership_cache_write_failed", exc_info=True)
+
+
+class CachedRepoFiles:
+ """The shared skeleton of a repository's file readers: one memo per batch, one Redis round trip
+ per kind of read, and one time budget for the whole resolution.
+
+ Build one per batch. A subclass says where a file comes from, how its cache key is built, and
+ how long a cached value keeps.
+ """
+
+ def __init__(self, repository: str) -> None:
+ self.repository = repository
+ # Raw cache values, so ``_ABSENT`` rather than None for a file the repository does not hold.
+ # The resolver reads each file again after the batch fetched it, and Redis is a network hop too.
+ self._bodies: dict[str, str] = {}
+ self._deadline = monotonic() + _RESOLVE_BUDGET_SECONDS
+
+ def _cache_key(self, kind: str, path: str) -> str:
+ raise NotImplementedError
+
+ def _cache_ttl(self) -> int:
+ raise NotImplementedError
+
+ def _read_missing(self, paths: list[str]) -> dict[str, str]:
+ raise NotImplementedError
+
+ def _probe_missing(self, paths: list[str]) -> dict[str, bool]:
+ raise NotImplementedError
+
+ def _batch(self, kind: str, paths: Iterable[str], fetch: Callable[[list[str]], dict[str, _T]]) -> dict[str, _T]:
+ todo = list(dict.fromkeys(paths))
+ if not todo:
+ return {}
+ by_key = {self._cache_key(kind, path): path for path in todo}
+ known = {by_key[key]: value for key, value in _cache_get_many(list(by_key)).items()}
+ missing = [path for path in todo if path not in known]
+ if missing:
+ fetched = fetch(missing)
+ _cache_set_many({self._cache_key(kind, path): value for path, value in fetched.items()}, self._cache_ttl())
+ known.update(fetched)
+ return known
+
+ def read(self, path: str) -> str | None:
+ if path not in self._bodies:
+ self.read_all([path])
+ return None if self._bodies[path] == _ABSENT else self._bodies[path]
+
+ def read_all(self, paths: list[str]) -> None:
+ """Take every file the batch needs before it reads any, so one Redis round trip and one set
+ of fetches cover them all."""
+ self._bodies.update(self._batch("text", [p for p in paths if p not in self._bodies], self._read_missing))
+
+ def exists_all(self, paths: list[str]) -> dict[str, bool]:
+ return self._batch("exists", paths, self._probe_missing)
+
+
+class GitHubRepoFiles(CachedRepoFiles):
+ """A public repository's files over HTTPS, cached in Redis. Build one per batch: it holds the
+ batch's memo and its HTTP connections."""
+
+ def __init__(self, repository: str) -> None:
+ super().__init__(repository)
+ self._session = pooled_session(_RAW_HOST)
+
+ def _cache_key(self, kind: str, path: str) -> str:
+ return f"{_CACHE_PREFIX}:{kind}:{self.repository}:{_REF}:{path}"
+
+ def _cache_ttl(self) -> int:
+ return _CACHE_TTL_SECONDS + random.randint(0, _CACHE_TTL_JITTER_SECONDS)
+
+ def _read_missing(self, paths: list[str]) -> dict[str, str]:
+ return _fetch_all(self._get, paths, self._deadline)
+
+ def _probe_missing(self, paths: list[str]) -> dict[str, bool]:
+ return _fetch_all(self._head, paths, self._deadline)
+
+ def _get(self, path: str) -> str:
+ """The file's text, or ``_ABSENT`` when the repository has no such file."""
+ with self._response("GET", path, stream=True) as response:
+ if response.status_code == HTTPStatus.NOT_FOUND:
+ return _ABSENT
+ return capped_text(
+ response,
+ description=f"{path} in {self.repository}",
+ limit=_MAX_FILE_BYTES,
+ deadline=self._deadline,
+ )
+
+ def _head(self, path: str) -> bool:
+ with self._response("HEAD", path) as response:
+ return response.status_code != HTTPStatus.NOT_FOUND
+
+ def _response(self, method: str, path: str, **kwargs: Any) -> requests.Response:
+ """Any status but 200 or 404 raises rather than reading as absent, because a missing
+ ownership file silently reattributes everything under it to an ancestor."""
+ if not _is_safe_github_repo_path(self.repository):
+ # Source config is team-writable, so a crafted value must not steer the URL.
+ raise OwnershipUnavailable(f"unsafe repository path: {self.repository!r}")
+ url = f"{_RAW_HOST}/{self.repository}/{_REF}/{path}"
+ try:
+ response = github_request(
+ method,
+ url,
+ source=_EGRESS_SOURCE,
+ endpoint=_EGRESS_ENDPOINT,
+ timeout=_TIMEOUT_SECONDS,
+ session=self._session,
+ **kwargs,
+ )
+ except Exception as e:
+ raise OwnershipUnavailable(f"could not read {path} from {self.repository}: {e}") from e
+ if response.status_code not in (HTTPStatus.OK, HTTPStatus.NOT_FOUND):
+ raise OwnershipUnavailable(f"{self.repository} answered {response.status_code} for {path}")
+ return response
diff --git a/posthog/ownership/test/__init__.py b/posthog/ownership/test/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/posthog/ownership/test/test_github_files.py b/posthog/ownership/test/test_github_files.py
new file mode 100644
index 000000000000..8ad2ab75abb4
--- /dev/null
+++ b/posthog/ownership/test/test_github_files.py
@@ -0,0 +1,368 @@
+import json
+from collections.abc import Callable, Iterator
+from threading import Event
+from time import monotonic
+from typing import Any
+
+from posthog.test.base import BaseTest
+from unittest.mock import MagicMock, patch
+
+from django.core.cache import cache
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from posthog.egress.github.transport import GitHubEgressBudgetExhausted, GitHubRateLimitError
+from posthog.egress.limiter.policies import Priority
+from posthog.models.integration import GitHubIntegration, Integration
+from posthog.ownership.github_files import (
+ _CACHE_PREFIX,
+ _CHUNK_FILES,
+ _MAX_RESPONSE_BYTES,
+ AuthenticatedRepoFiles,
+ GitHubFilesFetcher,
+ fetcher_for_team,
+)
+from posthog.ownership.repo_files import GitHubRepoFiles, OwnershipUnavailable
+
+_REPOSITORY = "PostHog/posthog"
+_SHA = "a" * 40
+_NEW_SHA = "b" * 40
+_ROOT_OWNERS = "version: 1\nowners: [team-root]\n"
+
+
+class _Response:
+ def __init__(self, status: int, body: Any, *, raw: bytes | None = None) -> None:
+ self.status_code = status
+ self.headers: dict[str, str] = {}
+ self.encoding = "utf-8"
+ self._raw = raw if raw is not None else json.dumps(body).encode()
+
+ def iter_content(self, chunk_size: int = 8192) -> Iterator[bytes]:
+ for start in range(0, len(self._raw), chunk_size):
+ yield self._raw[start : start + chunk_size]
+
+ def __enter__(self) -> "_Response":
+ return self
+
+ def __exit__(self, *_exc: Any) -> None:
+ return None
+
+
+class _FakeGitHub:
+ """Answers the two queries this module sends, and counts what it was asked."""
+
+ def __init__(self, blobs: dict[str, str], *, sha: str | None = _SHA, trees: frozenset[str] = frozenset()) -> None:
+ self.blobs = blobs
+ self.trees = trees
+ self.sha = sha
+ self.file_calls = 0
+ self.head_calls = 0
+ self.file_shas: list[str] = []
+
+ def __call__(self, _method: str, _url: str, **kwargs: Any) -> _Response:
+ payload = kwargs["json"]
+ query, variables = payload["query"], payload["variables"]
+ if "defaultBranchRef" in query:
+ self.head_calls += 1
+ # A repository with no commits has no default branch, and GitHub says so with a null.
+ ref = {"target": {"oid": self.sha}} if self.sha is not None else None
+ return _Response(200, {"data": {"repository": {"defaultBranchRef": ref}}})
+ self.file_calls += 1
+ field: dict[str, Any] = {}
+ for name, expression in variables.items():
+ if name in ("owner", "name"):
+ continue
+ sha, path = expression.split(":", 1)
+ self.file_shas.append(sha)
+ body = self.blobs.get(path)
+ if path in self.trees:
+ field[f"f{name[1:]}"] = {} if "text" in query else {"__typename": "Tree"}
+ elif body is None:
+ field[f"f{name[1:]}"] = None
+ else:
+ field[f"f{name[1:]}"] = {"text": body} if "text" in query else {"__typename": "Blob"}
+ return _Response(200, {"data": {"repository": field}})
+
+
+class _ScriptedGitHub:
+ """Answers a files query with the scripted status codes in order, recording each token used."""
+
+ def __init__(self, statuses: list[int]) -> None:
+ self._statuses = statuses
+ self.tokens: list[str] = []
+
+ def __call__(self, _method: str, _url: str, **kwargs: Any) -> _Response:
+ self.tokens.append(kwargs["headers"]["Authorization"])
+ status = self._statuses[len(self.tokens) - 1]
+ if status != 200:
+ return _Response(status, {"message": "Bad credentials"})
+ return _Response(200, {"data": {"repository": {"f0": {"text": _ROOT_OWNERS}}}})
+
+
+def _fetcher() -> GitHubFilesFetcher:
+ return GitHubFilesFetcher.from_token("t0ken", installation_id="42", priority=Priority.BATCH)
+
+
+class TestGitHubFilesFetcher(SimpleTestCase):
+ def test_a_batch_is_split_into_chunks_and_a_missing_file_comes_back_absent(self) -> None:
+ # GitHub answers a few hundred aliased blobs with a 502, so one batch has to be several
+ # requests, and every path has to survive the split.
+ present = [f"d{index}/owners.yaml" for index in range(_CHUNK_FILES)]
+ github = _FakeGitHub(dict.fromkeys(present, _ROOT_OWNERS))
+ with patch("posthog.ownership.github_files.github_request", side_effect=github):
+ read = _fetcher().read_files(_REPOSITORY, _SHA, [*present, "gone/owners.yaml"], monotonic() + 30)
+ assert github.file_calls == 2
+ assert read[present[0]] == _ROOT_OWNERS
+ assert read["gone/owners.yaml"] != _ROOT_OWNERS
+
+ def test_a_repository_with_no_commits_names_no_head_instead_of_failing(self) -> None:
+ # An empty repository answers with a null defaultBranchRef and no error. Failing it would
+ # take down every other repository the same run reads.
+ github = _FakeGitHub({}, sha=None)
+ with patch("posthog.ownership.github_files.github_request", side_effect=github):
+ assert _fetcher().head_commit_sha(_REPOSITORY) is None
+
+ def test_existence_is_answered_without_a_body(self) -> None:
+ # Most probed paths are candidates a batch only wants to rule out, and one of them can be a
+ # whole source file.
+ github = _FakeGitHub({"nodejs/owners.yaml": _ROOT_OWNERS}, trees=frozenset({"nodejs"}))
+ with patch("posthog.ownership.github_files.github_request", side_effect=github):
+ exists = _fetcher().files_exist(
+ _REPOSITORY, _SHA, ["nodejs/owners.yaml", "gone.yaml", "nodejs"], monotonic() + 30
+ )
+ assert exists == {"nodejs/owners.yaml": True, "gone.yaml": False, "nodejs": False}
+
+ @parameterized.expand(
+ [
+ ("server_error", lambda: _Response(502, None)),
+ ("graphql_errors", lambda: _Response(200, {"data": None, "errors": [{"message": "NOT_FOUND"}]})),
+ ("no_repository", lambda: _Response(200, {"data": {"repository": None}})),
+ # A partial answer: the repository object is there, and only the failed aliases are null.
+ (
+ "partial_errors",
+ lambda: _Response(200, {"data": {"repository": {"f0": None}}, "errors": [{"message": "TIMEOUT"}]}),
+ ),
+ ("unparseable", lambda: _Response(200, None, raw=b"<html>gateway</html>")),
+ ("not_an_object", lambda: _Response(200, [{"message": "NOT_FOUND"}])),
+ ("missing_alias", lambda: _Response(200, {"data": {"repository": {}}})),
+ # GitHub cuts a large blob's text short and still answers 200, so the prefix would parse
+ # as a complete file and cache a wrong answer for the whole TTL.
+ (
+ "truncated_blob",
+ lambda: _Response(200, {"data": {"repository": {"f0": {"text": "own", "isTruncated": True}}}}),
+ ),
+ # The per-file limit alone lets one chunk of a hundred near-limit blobs materialize a
+ # hundred megabytes, sixteen chunks at a time.
+ ("oversized_answer", lambda: _Response(200, None, raw=b"x" * (_MAX_RESPONSE_BYTES + 1))),
+ ]
+ )
+ def test_an_unreadable_answer_raises_rather_than_reading_as_absent(
+ self, _name: str, answer: Callable[[], _Response]
+ ) -> None:
+ # A repository the credential cannot see answers the same way as one that declares nothing,
+ # and reading that as "no owners" attributes the whole batch to nobody.
+ with patch("posthog.ownership.github_files.github_request", side_effect=lambda *a, **kw: answer()):
+ with self.assertRaises(OwnershipUnavailable):
+ _fetcher().read_files(_REPOSITORY, _SHA, ["owners.yaml"], monotonic() + 30)
+
+ @parameterized.expand(
+ [
+ # A credential that can be minted again retries once, so a token revoked or rotated under
+ # the batch recovers instead of failing every read that follows it.
+ ("mintable_recovers", True, [401, 200], 2, 1, False),
+ ("mintable_gives_up_on_the_second_401", True, [401, 401], 2, 1, True),
+ # A personal access token cannot be minted again, so a retry would only spend one more call.
+ ("static_fails_closed", False, [401], 1, 0, True),
+ ]
+ )
+ def test_a_401_asks_for_a_fresh_credential_once(
+ self, _name: str, mintable: bool, statuses: list[int], calls: int, refreshes: int, fails: bool
+ ) -> None:
+ refreshed: list[str] = []
+
+ def refresh() -> str:
+ refreshed.append("fresh")
+ return "fresh"
+
+ github = _ScriptedGitHub(statuses)
+ fetcher = GitHubFilesFetcher.from_token(
+ "t0ken", installation_id="42", refresh=refresh if mintable else None, priority=Priority.BATCH
+ )
+ with patch("posthog.ownership.github_files.github_request", side_effect=github):
+ if fails:
+ with self.assertRaises(OwnershipUnavailable):
+ fetcher.read_files(_REPOSITORY, _SHA, ["owners.yaml"], monotonic() + 30)
+ else:
+ read = fetcher.read_files(_REPOSITORY, _SHA, ["owners.yaml"], monotonic() + 30)
+ assert read == {"owners.yaml": _ROOT_OWNERS}
+ assert len(github.tokens) == calls
+ assert len(refreshed) == refreshes
+ if mintable:
+ assert github.tokens[-1] == "Bearer fresh"
+
+ def test_an_installation_mints_the_replacement_token(self) -> None:
+ # get_access_token keeps the stored token until it nears expiry, so it can hand back the very
+ # token the 401 refused. Only a refresh mints a new one.
+ integration = MagicMock(github_installation_id="42")
+ integration.get_access_token.side_effect = ["stale", "fresh"]
+ github = _ScriptedGitHub([401, 200])
+ with patch("posthog.ownership.github_files.github_request", side_effect=github):
+ GitHubFilesFetcher.from_integration(integration, priority=Priority.BATCH).read_files(
+ _REPOSITORY, _SHA, ["owners.yaml"], monotonic() + 30
+ )
+ integration.refresh_access_token.assert_called_once()
+ assert github.tokens == ["Bearer stale", "Bearer fresh"]
+
+ def test_a_slow_repository_gives_up_instead_of_holding_the_worker(self) -> None:
+ # A cold board asks for hundreds of files. Without a budget for the whole batch, a stalled
+ # API holds a web worker far past the per-request timeout.
+ release = Event()
+ self.addCleanup(release.set)
+
+ def stalls(*_args: Any, **_kwargs: Any) -> _Response:
+ release.wait(timeout=10)
+ return _Response(200, {"data": {"repository": {}}})
+
+ with patch("posthog.ownership.github_files.github_request", side_effect=stalls):
+ with self.assertRaises(OwnershipUnavailable):
+ _fetcher().read_files(_REPOSITORY, _SHA, ["owners.yaml"], monotonic() - 1)
+
+
+class TestAuthenticatedRepoFiles(SimpleTestCase):
+ def setUp(self) -> None:
+ cache.clear()
+
+ def _files(self) -> AuthenticatedRepoFiles:
+ return AuthenticatedRepoFiles(_REPOSITORY, _fetcher())
+
+ def test_a_burst_asks_github_for_the_head_commit_once(self) -> None:
+ github = _FakeGitHub({"owners.yaml": _ROOT_OWNERS})
+ with patch("posthog.ownership.github_files.github_request", side_effect=github):
+ assert self._files().read("owners.yaml") == _ROOT_OWNERS
+ assert self._files().read("owners.yaml") == _ROOT_OWNERS
+ assert github.head_calls == 1
+
+ def test_an_unreachable_cache_reads_from_github_instead_of_failing(self) -> None:
+ github = _FakeGitHub({"owners.yaml": _ROOT_OWNERS})
+ down = ConnectionError("redis is down")
+ with (
+ patch.object(cache, "get", side_effect=down),
+ patch.object(cache, "set", side_effect=down),
+ patch.object(cache, "get_many", side_effect=down),
+ patch.object(cache, "set_many", side_effect=down),
+ patch("posthog.ownership.github_files.github_request", side_effect=github),
+ ):
+ assert self._files().read("owners.yaml") == _ROOT_OWNERS
+
+ def test_a_partially_failed_answer_caches_no_absence(self) -> None:
+ # An errored alias comes back null, exactly like a file the commit does not hold. Caching
+ # that as an absence would hold for the whole TTL and move every path under it to an ancestor.
+ working = _FakeGitHub({"owners.yaml": _ROOT_OWNERS})
+
+ def partial(method: str, url: str, **kwargs: Any) -> _Response:
+ response = working(method, url, **kwargs)
+ if "defaultBranchRef" in kwargs["json"]["query"]:
+ return response
+ return _Response(200, {"data": {"repository": {"f0": None}}, "errors": [{"message": "TIMEOUT"}]})
+
+ with patch("posthog.ownership.github_files.github_request", side_effect=partial):
+ with self.assertRaises(OwnershipUnavailable):
+ self._files().read("owners.yaml")
+ with patch("posthog.ownership.github_files.github_request", side_effect=working):
+ assert self._files().read("owners.yaml") == _ROOT_OWNERS
+
+ def test_an_empty_repository_reads_as_absent_and_caches_no_absence(self) -> None:
+ # Every file of a repository with no commits is absent, and there is no commit to key that
+ # absence by, so caching it would hold for the whole TTL and outlive the first push.
+ github = _FakeGitHub({}, sha=None)
+ with patch("posthog.ownership.github_files.github_request", side_effect=github):
+ files = self._files()
+ assert files.read("owners.yaml") is None
+ assert files.exists_all(["owners.yaml"]) == {"owners.yaml": False}
+ assert github.file_calls == 0
+
+ github.sha, github.blobs = _SHA, {"owners.yaml": _ROOT_OWNERS}
+ with patch("posthog.ownership.github_files.github_request", side_effect=github):
+ assert self._files().read("owners.yaml") == _ROOT_OWNERS
+
+ @parameterized.expand([("cached_head", False, _SHA), ("fresh_head", True, _NEW_SHA)])
+ def test_a_fresh_head_run_reads_at_the_head_of_this_run(
+ self, _name: str, fresh_head: bool, expected_sha: str
+ ) -> None:
+ # A caller that derives a decision it never stores cannot correct a head another caller
+ # cached two minutes ago, so it has to be able to skip that entry. The entry is still
+ # written, because every other caller is happy with it.
+ github = _FakeGitHub({"owners.yaml": _ROOT_OWNERS}, sha=_NEW_SHA)
+ key = f"{_CACHE_PREFIX}:head:{_fetcher().audience}:{_REPOSITORY}"
+ cache.set(key, _SHA, 120)
+ with patch("posthog.ownership.github_files.github_request", side_effect=github):
+ files = AuthenticatedRepoFiles(_REPOSITORY, _fetcher(), fresh_head=fresh_head)
+ assert files.read("owners.yaml") == _ROOT_OWNERS
+ assert github.file_shas == [expected_sha]
+ assert cache.get(key) == expected_sha
+
+ @parameterized.expand([("present", _ROOT_OWNERS), ("absent", None)])
+ def test_a_commit_is_read_once_and_a_new_commit_is_read_again(self, _name: str, body: str | None) -> None:
+ # The cache is keyed by commit, so a merge has to be visible once the head lookup expires,
+ # and an absent file must not be refetched on every batch until then.
+ github = _FakeGitHub({"owners.yaml": body} if body is not None else {})
+ with (
+ patch("posthog.ownership.github_files._HEAD_CACHE_TTL_SECONDS", 0),
+ patch("posthog.ownership.github_files.github_request", side_effect=github),
+ ):
+ assert self._files().read("owners.yaml") == body
+ assert self._files().read("owners.yaml") == body
+ assert github.file_calls == 1
+ github.sha = "b" * 40
+ assert self._files().read("owners.yaml") == body
+ assert github.file_calls == 2
+
+
+class TestFetcherForTeam(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ cache.clear()
+
+ @parameterized.expand([("with_installation", True), ("without_installation", False)])
+ def test_a_team_reads_authenticated_only_where_its_installation_covers_the_repository(
+ self, _name: str, covered: bool
+ ) -> None:
+ # The lookup probes GitHub once per integration the team has, and a page load asks for the
+ # reader on every request, so the decision has to survive the next one.
+ integration = Integration.objects.create(
+ team=self.team,
+ kind="github",
+ integration_id="42",
+ config={"account": {"name": "PostHog"}},
+ sensitive_config={"access_token": "t0ken"},
+ )
+ with patch(
+ "posthog.ownership.github_files.GitHubIntegration.first_for_team_repository",
+ return_value=GitHubIntegration(integration) if covered else None,
+ ) as probe:
+ first = fetcher_for_team(self.team.pk, _REPOSITORY, priority=Priority.NORMAL)
+ second = fetcher_for_team(self.team.pk, _REPOSITORY, priority=Priority.NORMAL)
+ assert probe.call_count == 1
+ expected = AuthenticatedRepoFiles if covered else GitHubRepoFiles
+ assert isinstance(first, expected)
+ assert isinstance(second, expected)
+
+ @parameterized.expand(
+ [
+ ("our_budget", GitHubEgressBudgetExhausted("shed")),
+ ("githubs_limit", GitHubRateLimitError("429")),
+ ]
+ )
+ def test_a_spent_budget_degrades_to_the_anonymous_reader_without_a_cached_decision(
+ self, _name: str, error: Exception
+ ) -> None:
+ # Callers evaluate this before their own unavailable-ownership handler runs, so a raise here
+ # turns optional enrichment into a 500. The decision must not be cached either, or the
+ # anonymous reader would outlive the exhausted budget by the cache's whole window.
+ with patch(
+ "posthog.ownership.github_files.GitHubIntegration.first_for_team_repository", side_effect=error
+ ) as spent:
+ assert isinstance(fetcher_for_team(self.team.pk, _REPOSITORY, priority=Priority.NORMAL), GitHubRepoFiles)
+ assert spent.call_count == 1
+ assert cache.get(f"{_CACHE_PREFIX}:integration:{self.team.pk}:{_REPOSITORY.casefold()}") is None
diff --git a/posthog/ownership/test/test_path_ownership.py b/posthog/ownership/test/test_path_ownership.py
new file mode 100644
index 000000000000..d5154e57d8d3
--- /dev/null
+++ b/posthog/ownership/test/test_path_ownership.py
@@ -0,0 +1,159 @@
+from collections.abc import Iterator
+from dataclasses import field
+from threading import Event
+from time import monotonic
+from typing import cast
+
+from unittest.mock import patch
+
+from django.core.cache import cache
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+from requests import Response
+
+from posthog.dataclasses import frozen
+from posthog.ownership.paths import UNOWNED_TEAM, resolve_path_owners
+from posthog.ownership.repo_files import _MAX_FILE_BYTES, GitHubRepoFiles, OwnershipUnavailable, capped_text
+
+_ROOT_OWNERS = """version: 1
+owners: [team-root]
+teams:
+ team-ingestion:
+ notifications: '#alerts-ingestion'
+"""
+
+_OWNERS = {
+ "owners.yaml": _ROOT_OWNERS,
+ "nodejs/src/owners.yaml": "version: 1\nowners: [team-ingestion]\n",
+}
+
+
+@frozen(frozen=False)
+class _FakeRepoFiles:
+ owners: dict[str, str] = field(default_factory=lambda: dict(_OWNERS))
+
+ def read(self, path: str) -> str | None:
+ return self.owners.get(path)
+
+ def read_all(self, paths: list[str]) -> None:
+ pass
+
+
+class TestPathOwnership(SimpleTestCase):
+ def test_places_each_path_exactly_and_returns_the_registry(self) -> None:
+ # Exact resolution, not the suite-root search: 'src/...' is a real repo-relative path here
+ # and must not be repositioned under nodejs/ the way a reported test path is.
+ owned = resolve_path_owners(
+ "PostHog/posthog",
+ ["nodejs/src/cdp/worker.ts", "src/cdp/worker.ts"],
+ files=_FakeRepoFiles(),
+ )
+ assert owned.resolved
+ assert owned.team_by_path == {"nodejs/src/cdp/worker.ts": "team-ingestion", "src/cdp/worker.ts": "team-root"}
+ assert owned.registry["team-ingestion"].notifications == "#alerts-ingestion"
+
+ def test_an_unreadable_repository_owns_nothing_and_says_so(self) -> None:
+ no_root = _FakeRepoFiles(owners={k: v for k, v in _OWNERS.items() if k != "owners.yaml"})
+ owned = resolve_path_owners("PostHog/posthog", ["nodejs/src/cdp/worker.ts"], files=no_root)
+ assert not owned.resolved
+ assert owned.team_by_path == {"nodejs/src/cdp/worker.ts": UNOWNED_TEAM}
+ assert owned.registry == {}
+
+
+class TestGitHubRepoFiles(SimpleTestCase):
+ def setUp(self) -> None:
+ cache.clear()
+
+ @parameterized.expand([(500,), (403,)])
+ def test_an_unexpected_status_raises_rather_than_reading_as_absent(self, status: int) -> None:
+ # Reading a failure as "no such file" reattributes everything under it to an ancestor.
+ with patch(
+ "posthog.ownership.repo_files.github_request",
+ return_value=_response(status),
+ ):
+ with self.assertRaises(OwnershipUnavailable):
+ GitHubRepoFiles("PostHog/posthog").read("owners.yaml")
+
+ def test_a_missing_file_is_absent_and_fetched_once(self) -> None:
+ with patch(
+ "posthog.ownership.repo_files.github_request",
+ return_value=_response(404),
+ ) as request:
+ files = GitHubRepoFiles("PostHog/posthog")
+ assert files.read("nodejs/owners.yaml") is None
+ assert files.read("nodejs/owners.yaml") is None
+ assert GitHubRepoFiles("PostHog/posthog").read("nodejs/owners.yaml") is None
+ assert request.call_count == 1
+
+ def test_a_slow_repository_gives_up_instead_of_holding_the_worker(self) -> None:
+ # A cold board asks for hundreds of files. Without a budget for the whole resolution, a
+ # stalled raw host holds a web worker far past the per-request timeout.
+ started, release, finished = Event(), Event(), Event()
+ self.addCleanup(release.set)
+
+ def stalls(_method: str, _url: str, **_kwargs: object) -> _response:
+ started.set()
+ release.wait(timeout=10)
+ finished.set()
+ return _response(404)
+
+ files = GitHubRepoFiles("PostHog/posthog")
+
+ def at_the_deadline_once_the_fetch_runs() -> float:
+ assert started.wait(timeout=10)
+ return files._deadline
+
+ with (
+ patch("posthog.ownership.repo_files.github_request", side_effect=stalls),
+ patch(
+ "posthog.ownership.repo_files.monotonic",
+ side_effect=at_the_deadline_once_the_fetch_runs,
+ ),
+ ):
+ with self.assertRaises(OwnershipUnavailable):
+ files.read("owners.yaml")
+ assert not finished.is_set()
+
+ def test_a_body_that_arrives_after_the_deadline_is_refused(self) -> None:
+ # The per-request timeout starts again on each chunk, so the byte limit alone lets one read
+ # run for minutes. Nothing waits for the fetch after the deadline, so nothing else stops it.
+ with self.assertRaises(OwnershipUnavailable):
+ capped_text(
+ cast(Response, _response(200, body=b"owners")),
+ description="owners.yaml",
+ limit=_MAX_FILE_BYTES,
+ deadline=monotonic() - 1,
+ )
+
+ @parameterized.expand([("declared", True), ("streamed", False)])
+ def test_an_oversized_file_is_refused(self, _name: str, declare_length: bool) -> None:
+ # A connected repository controls these files, so an unbounded read would put its bytes in
+ # a worker's memory and in Redis. Content-Length can lie, so the streamed read is the ceiling.
+ oversized = b"x" * (_MAX_FILE_BYTES + 1)
+ headers = {"Content-Length": str(len(oversized))} if declare_length else {}
+ with patch(
+ "posthog.ownership.repo_files.github_request",
+ return_value=_response(200, body=oversized, headers=headers),
+ ):
+ with self.assertRaises(OwnershipUnavailable):
+ GitHubRepoFiles("PostHog/posthog").read("owners.yaml")
+
+
+class _response:
+ encoding = "utf-8"
+
+ def __init__(self, status: int, body: bytes = b"", headers: dict[str, str] | None = None) -> None:
+ self.status_code = status
+ self.headers = headers or {}
+ self._body = body
+
+ def iter_content(self, chunk_size: int) -> Iterator[bytes]:
+ for start in range(0, len(self._body), chunk_size):
+ yield self._body[start : start + chunk_size]
+
+ def __enter__(self) -> "_response":
+ return self
+
+ def __exit__(self, *args: object) -> None:
+ pass
diff --git a/products/engineering_analytics/backend/facade/api.py b/products/engineering_analytics/backend/facade/api.py
index c9fab99efde9..dfd999a7bc2c 100644
--- a/products/engineering_analytics/backend/facade/api.py
+++ b/products/engineering_analytics/backend/facade/api.py
@@ -18,7 +18,6 @@ then delegates to the read layer: source selection and access control live in th
not in the query builders below it.
"""
-from collections.abc import Sequence
from typing import TYPE_CHECKING
from posthog.models.team import Team
@@ -40,7 +39,6 @@ from products.engineering_analytics.backend.facade.contracts import (
GitHubTeamRoster,
MasterFailureGroup,
MergedPullRequest,
- PathOwnership,
PRCostSummary,
PRLifecycle,
PullRequestList,
@@ -703,9 +701,3 @@ def get_github_team_roster(*, team: Team, user_access_control: "UserAccessContro
insists on. An unsynced snapshot comes back as ``synced=False``, never an error.
"""
return logic.build_github_team_roster(team=team, user_access_control=user_access_control)
-
-
-def resolve_path_owners(repository: str, paths: Sequence[str]) -> PathOwnership:
- """Name the team that owns each repository path, from the ownership files on the repository's
- default branch. It takes no team, because nothing PostHog stores feeds the answer."""
- return logic.resolve_path_owners(repository, paths)
diff --git a/products/engineering_analytics/backend/facade/contracts.py b/products/engineering_analytics/backend/facade/contracts.py
index 1671095621d5..714dba108913 100644
--- a/products/engineering_analytics/backend/facade/contracts.py
+++ b/products/engineering_analytics/backend/facade/contracts.py
@@ -21,12 +21,10 @@ read layer maps them into these types. Reviewers and file paths are
intentionally absent until the warehouse data that backs them lands.
"""
-from collections.abc import Mapping
from dataclasses import field
from datetime import date, datetime
from enum import StrEnum
-from owners_yaml.schema import TeamEntry
from pydantic.dataclasses import dataclass
from posthog.hogql.database.models import FieldOrTable
@@ -688,9 +686,6 @@ class FlakyTestList:
# expires a quarantine, so this deadline is the product's own accountability bar.
TRUNK_QUARANTINE_TTL_DAYS = 15
-# The first-class team every unattributed test aggregates under, on every surface here.
-UNOWNED_TEAM = "unowned"
-
@dataclass(frozen=True)
class TrunkQuarantinedTest:
@@ -1600,21 +1595,6 @@ class WorkflowJobAggregate:
estimated_cost_usd: float | None
-@dataclass(frozen=True)
-class PathOwnership:
- """Which team owns each repository path, plus the repo's Slack registry from the root ``owners.yaml``.
- The registry rides along because the caller that asks who owns a path usually has to reach that
- team next, and the root file answers both questions in one read.
-
- ``resolved`` is false when the ownership files could not be read; every path is then
- ``UNOWNED_TEAM`` and the registry is empty. A caller that says so beats one that reads the blind
- answer as "nobody owns this"."""
-
- team_by_path: Mapping[str, str]
- registry: Mapping[str, TeamEntry]
- resolved: bool
-
-
class DeliveryScopeKind(StrEnum):
"""Which pull requests a delivery read covers. A scope is always exactly one author, one GitHub
team, or one pull request, so no delivery read puts people side by side (SPEC §2)."""
diff --git a/products/engineering_analytics/backend/logic/__init__.py b/products/engineering_analytics/backend/logic/__init__.py
index d3c5826ce586..8a5c1bf74e78 100644
--- a/products/engineering_analytics/backend/logic/__init__.py
+++ b/products/engineering_analytics/backend/logic/__init__.py
@@ -31,7 +31,6 @@ from products.engineering_analytics.backend.logic.dora import build_dora_overvie
from products.engineering_analytics.backend.logic.github_teams import (
build_github_team_roster as build_github_team_roster,
)
-from products.engineering_analytics.backend.logic.ownership import resolve_path_owners as resolve_path_owners
from products.engineering_analytics.backend.logic.pull_requests import (
build_author_workflow_costs as build_author_workflow_costs,
build_ci_cards as build_ci_cards,
diff --git a/products/engineering_analytics/backend/logic/ownership.py b/products/engineering_analytics/backend/logic/ownership.py
index 6bd7dd090d19..d8c2e782c838 100644
--- a/products/engineering_analytics/backend/logic/ownership.py
+++ b/products/engineering_analytics/backend/logic/ownership.py
@@ -5,180 +5,32 @@ the capture-time span stamp the flaky rollups keep (SPEC). The web container has
files are fetched and cached.
"""
-import random
-from collections.abc import Callable, Iterable, Sequence
-from concurrent.futures import ThreadPoolExecutor
-from http import HTTPStatus
-from time import monotonic
-from typing import Any, Protocol, TypeVar
+from typing import Protocol
-from django.core.cache import cache
-
-import requests
import structlog
-from owners_yaml import OwnershipSource, OwnersResolver
from owners_yaml.matcher import normalize_path
-from owners_yaml.resolver import teams_registry
-from requests.adapters import HTTPAdapter
from posthog.dataclasses import frozen
-from posthog.egress.github.transport import github_request
-from posthog.models.integration.github import _is_safe_github_repo_path
-
-from products.engineering_analytics.backend.facade.contracts import UNOWNED_TEAM, PathOwnership
+from posthog.ownership.paths import UNOWNED_TEAM, own_paths, read_root
+from posthog.ownership.repo_files import GitHubRepoFiles, OwnershipUnavailable, RepoFiles
logger = structlog.get_logger(__name__)
-_T = TypeVar("_T")
-
-# The raw host serves a public repo's files off a CDN, so these reads draw on no GitHub API rate
-# limit, and the HEAD ref follows the default branch. A private repo answers 404 to all of it, which
-# the root-file guard in _read_root catches.
-_RAW_HOST = "https://raw.githubusercontent.com"
-_REF = "HEAD"
-_EGRESS_SOURCE = "engineering_analytics_ownership"
-# Egress metrics are labeled by endpoint, so a raw file path per label would be unbounded.
-_EGRESS_ENDPOINT = "/{owner}/{repo}/{ref}/{path}"
-_TIMEOUT_SECONDS = 5.0
-_FETCH_WORKERS = 16
-# A connected repository controls these files, so an unbounded read would put its bytes in a
-# worker's memory and in Redis. An ownership file is a few KB; this repo's whole set is under 25 KB.
-_MAX_FILE_BYTES = 1024 * 1024
-# The whole resolution, not one request. A quarantine snapshot is capped at HogQL's implicit 100
-# rows, so a cold board can ask for hundreds of files; if the raw host stalls, the per-request
-# timeout alone would still let one board load hold a web worker for minutes. Past this the board
-# says ownership is unavailable, which beats hanging.
-_RESOLVE_BUDGET_SECONDS = 20.0
-
-# Ownership files change at review speed, so a stale answer stays right, and only the request that
-# finds the cache cold pays for the fetches. A batch writes every key at once, so the jitter spreads
-# their expiry over later requests instead of stranding one with the whole refetch.
-_CACHE_TTL_SECONDS = 6 * 60 * 60
-_CACHE_TTL_JITTER_SECONDS = 60 * 60
-_CACHE_PREFIX = "eng_analytics:repo_file"
-# Absence needs a cache value of its own, and no file holds this one.
-_ABSENT = "\x00absent"
-
-_ROOT_OWNERS_FILE = "owners.yaml"
-
# Directories a TypeScript suite can run from, so its tests arrive named relative to one of these.
# Keep in step with jest_root_for_suite in .github/scripts/report_test_timings.py, which stamps the
# same repositioning onto the CI spans.
_SUITE_ROOTS = ("nodejs/", "frontend/", "services/mcp/", "common/replay-shared/")
-class OwnershipUnavailable(Exception):
- """The repository's ownership files could not be read, so no attribution is trustworthy."""
-
+class ProbeableRepoFiles(RepoFiles, Protocol):
+ """A reader that also answers which paths the repository holds, in batches.
-class NoRootOwnersFile(OwnershipUnavailable):
- """The repository answers with no root owners file, which is normal for most repositories."""
-
-
-class RepoFiles(OwnershipSource, Protocol):
- """An ownership source that also answers which paths the repository holds, in batches."""
+ Placing a test needs this and resolving a path does not: a quarantined test arrives named by its
+ suite, so the repository has to say which of its candidate paths exists.
+ """
def exists_all(self, paths: list[str]) -> dict[str, bool]: ...
- def read_all(self, paths: list[str]) -> None: ...
-
-
-class GitHubRepoFiles:
- """A public repository's files over HTTPS, cached in Redis. Build one per batch: it holds the
- batch's memo and its HTTP connections."""
-
- def __init__(self, repository: str) -> None:
- self.repository = repository
- # Raw cache values, so ``_ABSENT`` rather than None for a file the repository does not hold.
- # The resolver reads each file again after the batch fetched it, and Redis is a network hop too.
- self._bodies: dict[str, str] = {}
- self._session = requests.Session()
- # requests pools 10 connections by default and discards the overflow, so a smaller pool than
- # the worker count makes most of the batch pay a fresh TLS handshake.
- self._session.mount(_RAW_HOST, HTTPAdapter(pool_connections=_FETCH_WORKERS, pool_maxsize=_FETCH_WORKERS))
- self._deadline = monotonic() + _RESOLVE_BUDGET_SECONDS
-
- def read(self, path: str) -> str | None:
- if path not in self._bodies:
- self.read_all([path])
- return None if self._bodies[path] == _ABSENT else self._bodies[path]
-
- def read_all(self, paths: list[str]) -> None:
- """Take every file the batch needs before it reads any, so one Redis round trip and one
- concurrent fetch cover them all."""
- self._bodies.update(self._batch("text", [p for p in paths if p not in self._bodies], self._get))
-
- def exists_all(self, paths: list[str]) -> dict[str, bool]:
- return self._batch("exists", paths, self._head)
-
- def _batch(self, kind: str, paths: Iterable[str], fetch: Callable[[str], _T]) -> dict[str, _T]:
- todo = list(dict.fromkeys(paths))
- if not todo:
- return {}
- by_key = {self._key(kind, path): path for path in todo}
- known = {by_key[key]: value for key, value in cache.get_many(list(by_key)).items()}
- fetched = _fetch_all(fetch, [path for path in todo if path not in known], self._deadline)
- if fetched:
- cache.set_many({self._key(kind, path): value for path, value in fetched.items()}, _ttl())
- known.update(fetched)
- return known
-
- def _key(self, kind: str, path: str) -> str:
- return f"{_CACHE_PREFIX}:{kind}:{self.repository}:{_REF}:{path}"
-
- def _get(self, path: str) -> str:
- """The file's text, or ``_ABSENT`` when the repository has no such file."""
- with self._response("GET", path, stream=True) as response:
- if response.status_code == HTTPStatus.NOT_FOUND:
- return _ABSENT
- return self._capped_text(response, path)
-
- def _head(self, path: str) -> bool:
- with self._response("HEAD", path) as response:
- return response.status_code != HTTPStatus.NOT_FOUND
-
- def _response(self, method: str, path: str, **kwargs: Any) -> requests.Response:
- """Any status but 200 or 404 raises rather than reading as absent, because a missing
- ownership file silently reattributes everything under it to an ancestor."""
- if not _is_safe_github_repo_path(self.repository):
- # Source config is team-writable, so a crafted value must not steer the URL.
- raise OwnershipUnavailable(f"unsafe repository path: {self.repository!r}")
- url = f"{_RAW_HOST}/{self.repository}/{_REF}/{path}"
- try:
- response = github_request(
- method,
- url,
- source=_EGRESS_SOURCE,
- endpoint=_EGRESS_ENDPOINT,
- timeout=_TIMEOUT_SECONDS,
- session=self._session,
- **kwargs,
- )
- except Exception as e:
- raise OwnershipUnavailable(f"could not read {path} from {self.repository}: {e}") from e
- if response.status_code not in (HTTPStatus.OK, HTTPStatus.NOT_FOUND):
- raise OwnershipUnavailable(f"{self.repository} answered {response.status_code} for {path}")
- return response
-
- def _capped_text(self, response: requests.Response, path: str) -> str:
- too_large = f"{path} in {self.repository} exceeds the {_MAX_FILE_BYTES}-byte limit"
- # Content-Length can be absent or wrong, so the streamed read below is the actual ceiling.
- declared = response.headers.get("Content-Length")
- if declared is not None and declared.isdigit() and int(declared) > _MAX_FILE_BYTES:
- raise OwnershipUnavailable(too_large)
- body = bytearray()
- for chunk in response.iter_content(chunk_size=8192):
- # The request timeout starts again on every chunk received, so a host that sends the body
- # slowly enough holds this read for as long as the byte limit allows. _fetch_all stops
- # waiting for a fetch at the deadline, so the fetch stops at the first chunk after it,
- # which the request timeout puts within _TIMEOUT_SECONDS of the deadline.
- if monotonic() > self._deadline:
- raise OwnershipUnavailable(f"reading {path} from {self.repository} passed the resolution budget")
- body.extend(chunk)
- if len(body) > _MAX_FILE_BYTES:
- raise OwnershipUnavailable(too_large)
- return body.decode(response.encoding or "utf-8", errors="replace")
-
@frozen
class QuarantinedTestFile:
@@ -207,97 +59,10 @@ class RepoOwnershipResult:
resolved: bool
-def resolve_test_ownership(
- repository: str, tests: list[QuarantinedTestFile], files: RepoFiles | None = None
-) -> RepoOwnershipResult:
- """Place every test in the repository and name the team that owns it."""
- reader = files if files is not None else GitHubRepoFiles(repository)
- try:
- return RepoOwnershipResult(tests=_place(repository, reader, tests), resolved=True)
- except OwnershipUnavailable:
- # One unreadable file makes every later answer suspect too, so the batch fails together
- # rather than attributing part of it.
- logger.exception("repo_ownership_unavailable", repository=repository)
- return RepoOwnershipResult(tests=[UNPLACED] * len(tests), resolved=False)
-
-
-def resolve_path_owners(repository: str, paths: Sequence[str], files: RepoFiles | None = None) -> PathOwnership:
- """Name the team that owns each repository path, and return the repo's Slack registry. Paths must
- be repo-relative: unlike reported test paths, they get no candidate-path search."""
- reader = files if files is not None else GitHubRepoFiles(repository)
- try:
- return _own_paths(reader, _read_root(repository, reader), list(dict.fromkeys(paths)))
- except NoRootOwnersFile:
- # Most repositories declare no owners.yaml, so this is no error for a caller to act on.
- logger.info("repo_path_ownership_no_root_file", repository=repository)
- return PathOwnership(team_by_path=dict.fromkeys(paths, UNOWNED_TEAM), registry={}, resolved=False)
- except OwnershipUnavailable:
- logger.exception("repo_path_ownership_unavailable", repository=repository)
- return PathOwnership(team_by_path=dict.fromkeys(paths, UNOWNED_TEAM), registry={}, resolved=False)
-
-
-def _read_root(repository: str, files: RepoFiles) -> str:
- root = files.read(_ROOT_OWNERS_FILE)
- if root is None:
- raise NoRootOwnersFile(f"{repository} has no root {_ROOT_OWNERS_FILE}")
- return root
-
-
-def _own_paths(files: RepoFiles, root: str, paths: list[str]) -> PathOwnership:
- resolver = OwnersResolver(source=files)
- files.read_all(resolver.ownership_file_paths(paths))
- owners = resolver.map(paths)
- return PathOwnership(
- team_by_path={path: _team(owners[path].owners) for path in paths},
- registry=teams_registry(root),
- resolved=True,
- )
-
-
-def _place(repository: str, files: RepoFiles, tests: list[QuarantinedTestFile]) -> list[PlacedTest]:
- # Every repo this runs against declares one, so its absence proves the reader is blind
- # (a private or renamed repo answers 404 to everything), not that nobody owns anything.
- root = _read_root(repository, files)
- candidates = [_candidate_paths(test) for test in tests]
- present = files.exists_all([path for group in candidates for path in group])
- placed = [next((path for path in group if present[path]), None) for group in candidates]
- owned = _own_paths(files, root, [path for path in placed if path])
- return [
- PlacedTest(
- # A Rust crate is placed by its manifest, which is not the test's file.
- path="" if path is None or test.crate else path,
- owner_team=owned.team_by_path[path] if path else UNOWNED_TEAM,
- )
- for test, path in zip(tests, placed, strict=True)
- ]
-
-
-def _ttl() -> int:
- return _CACHE_TTL_SECONDS + random.randint(0, _CACHE_TTL_JITTER_SECONDS)
-
-
-def _team(owners: list[str] | None) -> str:
- """An '@handle' owner is a person, and every surface downstream keys on a team slug."""
- return next((owner for owner in owners or [] if not owner.startswith("@")), UNOWNED_TEAM)
-
-
-def _fetch_all(fetch: Callable[[str], _T], paths: Iterable[str], deadline: float) -> dict[str, _T]:
- """Fetch every distinct path concurrently, within what is left of the batch's budget. The one
- place this module waits on the network."""
- todo = list(dict.fromkeys(paths))
- if not todo:
- return {}
- pool = ThreadPoolExecutor(max_workers=min(_FETCH_WORKERS, len(todo)))
- try:
- futures = {path: pool.submit(fetch, path) for path in todo}
- return {path: future.result(max(deadline - monotonic(), 0)) for path, future in futures.items()}
- except TimeoutError as e:
- raise OwnershipUnavailable(f"ownership took longer than {_RESOLVE_BUDGET_SECONDS}s") from e
- finally:
- # Not a `with` block: its exit waits for every running fetch, which holds the request thread
- # past the deadline. A lost batch drops the queued fetches and leaves the running ones to
- # stop at the same deadline on their own, which the read in _capped_text enforces.
- pool.shutdown(wait=False, cancel_futures=True)
+def _strip_relative_prefix(path: str) -> str:
+ while path.startswith("../"):
+ path = path.partition("/")[2]
+ return path
def _candidate_paths(test: QuarantinedTestFile) -> list[str]:
@@ -321,7 +86,33 @@ def _candidate_paths(test: QuarantinedTestFile) -> list[str]:
return [reported, *(f"{root}{reported}" for root in _SUITE_ROOTS)]
-def _strip_relative_prefix(path: str) -> str:
- while path.startswith("../"):
- path = path.partition("/")[2]
- return path
+def _place(repository: str, files: ProbeableRepoFiles, tests: list[QuarantinedTestFile]) -> list[PlacedTest]:
+ # Every repo this runs against declares one, so its absence proves the reader is blind
+ # (a private or renamed repo answers 404 to everything), not that nobody owns anything.
+ root = read_root(repository, files)
+ candidates = [_candidate_paths(test) for test in tests]
+ present = files.exists_all([path for group in candidates for path in group])
+ placed = [next((path for path in group if present[path]), None) for group in candidates]
+ owned = own_paths(files, root, [path for path in placed if path])
+ return [
+ PlacedTest(
+ # A Rust crate is placed by its manifest, which is not the test's file.
+ path="" if path is None or test.crate else path,
+ owner_team=owned.team_by_path[path] if path else UNOWNED_TEAM,
+ )
+ for test, path in zip(tests, placed, strict=True)
+ ]
+
+
+def resolve_test_ownership(
+ repository: str, tests: list[QuarantinedTestFile], files: ProbeableRepoFiles | None = None
+) -> RepoOwnershipResult:
+ """Place every test in the repository and name the team that owns it."""
+ reader = files if files is not None else GitHubRepoFiles(repository)
+ try:
+ return RepoOwnershipResult(tests=_place(repository, reader, tests), resolved=True)
+ except OwnershipUnavailable:
+ # One unreadable file makes every later answer suspect too, so the batch fails together
+ # rather than attributing part of it.
+ logger.exception("repo_ownership_unavailable", repository=repository)
+ return RepoOwnershipResult(tests=[UNPLACED] * len(tests), resolved=False)
diff --git a/products/engineering_analytics/backend/logic/ownership_files.py b/products/engineering_analytics/backend/logic/ownership_files.py
new file mode 100644
index 000000000000..f5e1fc5b23e3
--- /dev/null
+++ b/products/engineering_analytics/backend/logic/ownership_files.py
@@ -0,0 +1,52 @@
+"""Where the credential for reading a repository's ownership files comes from.
+
+Engineering analytics reports on a repository the team already connected as a warehouse source, so
+that source holds a credential for it. Using it is what lets a private repository resolve at all.
+The credential comes from the one source the read is already scoped to, never from a walk over the
+team's other sources: a source the caller may not access can list the same repository, and reading
+with its credential would hand the caller data the per-source warehouse RBAC denies them. A read
+that has no selected source, or whose source holds no usable credential, falls back to the team's
+GitHub integration, and then to the anonymous public reader.
+"""
+
+from posthog.egress.limiter.policies import Priority
+from posthog.models.integration import GitHubIntegration, Integration
+from posthog.models.team import Team
+from posthog.ownership.github_files import EGRESS_SOURCE, AuthenticatedRepoFiles, GitHubFilesFetcher, fetcher_for_team
+
+from products.warehouse_sources.backend.facade import api as warehouse_sources
+from products.warehouse_sources.backend.facade.contracts import GitHubSourceCredential
+
+from .ownership import ProbeableRepoFiles
+
+
+def _fetcher_for_credential(
+ team_id: int, credential: GitHubSourceCredential, *, priority: Priority
+) -> GitHubFilesFetcher | None:
+ if credential.personal_access_token:
+ # The token is the customer's own, on the customer's own GitHub budget, so it names no
+ # installation for the egress limiter to gate on.
+ return GitHubFilesFetcher.from_token(credential.personal_access_token, priority=priority)
+ if credential.integration_id is None:
+ return None
+ integration = Integration.objects.filter(team_id=team_id, id=credential.integration_id, kind="github").first()
+ if integration is None:
+ return None
+ github = GitHubIntegration(integration, source=EGRESS_SOURCE, priority=priority)
+ return GitHubFilesFetcher.from_integration(github, priority=priority)
+
+
+def repo_files(team: Team, repository: str, *, source_id: str, priority: Priority) -> ProbeableRepoFiles:
+ """The reader for this repository's ownership files, authenticated where the team allows it.
+
+ ``source_id`` is the source the caller resolved this repository from (see
+ ``CuratedGitHubSource.source_id``), and the only source a credential may come from here. Pass an
+ empty string for a read that has no selected source; it falls back like a source with no
+ credential does.
+ """
+ credential = warehouse_sources.github_source_credential(team_id=team.pk, source_id=source_id) if source_id else None
+ if credential is not None:
+ fetcher = _fetcher_for_credential(team.pk, credential, priority=priority)
+ if fetcher is not None:
+ return AuthenticatedRepoFiles(repository, fetcher)
+ return fetcher_for_team(team.pk, repository, priority=priority)
diff --git a/products/engineering_analytics/backend/logic/queries/_curated.py b/products/engineering_analytics/backend/logic/queries/_curated.py
index d6bed58c77ce..5cbab5c1a242 100644
--- a/products/engineering_analytics/backend/logic/queries/_curated.py
+++ b/products/engineering_analytics/backend/logic/queries/_curated.py
@@ -179,6 +179,15 @@ class CuratedGitHubSource:
"""The selected source's ``owner/name`` identity for reads outside the warehouse."""
return self._tables.repository
+ @property
+ def source_id(self) -> str:
+ """The selected source, which the resolver already filtered by the caller's access.
+
+ A read outside the warehouse that needs a GitHub credential takes it from this source, so
+ it never reads with a credential of a source the caller is not allowed to use.
+ """
+ return self._tables.source_id
+
@classmethod
def for_team(
cls,
diff --git a/products/engineering_analytics/backend/logic/queries/_test_spans.py b/products/engineering_analytics/backend/logic/queries/_test_spans.py
index 5087320c27ae..5818fb24dd6c 100644
--- a/products/engineering_analytics/backend/logic/queries/_test_spans.py
+++ b/products/engineering_analytics/backend/logic/queries/_test_spans.py
@@ -30,8 +30,8 @@ from posthog.hogql import ast
from posthog.clickhouse.workload import Workload
from posthog.dataclasses import frozen
+from posthog.ownership.paths import UNOWNED_TEAM
-from products.engineering_analytics.backend.facade.contracts import UNOWNED_TEAM
from products.engineering_analytics.backend.logic.merge_queue import source_pr_string_expr
from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource
from products.engineering_analytics.backend.logic.queries._workflow_filters import job_created_floor_constant
diff --git a/products/engineering_analytics/backend/logic/queries/delivery_comparison.py b/products/engineering_analytics/backend/logic/queries/delivery_comparison.py
index c0abc0e32cad..ec308be6740b 100644
--- a/products/engineering_analytics/backend/logic/queries/delivery_comparison.py
+++ b/products/engineering_analytics/backend/logic/queries/delivery_comparison.py
@@ -10,8 +10,9 @@ from datetime import UTC, datetime, timedelta
from posthog.hogql import ast
+from posthog.ownership.paths import UNOWNED_TEAM
+
from products.engineering_analytics.backend.facade.contracts import (
- UNOWNED_TEAM,
DeliveryComparison,
DeliveryScopeKind,
ReadyToMergeMedians,
diff --git a/products/engineering_analytics/backend/logic/queries/trunk_quarantine.py b/products/engineering_analytics/backend/logic/queries/trunk_quarantine.py
index 243bd930c5c0..96de594352a2 100644
--- a/products/engineering_analytics/backend/logic/queries/trunk_quarantine.py
+++ b/products/engineering_analytics/backend/logic/queries/trunk_quarantine.py
@@ -8,12 +8,15 @@ under ``'unowned'``.
from datetime import UTC, datetime, timedelta
+from posthog.egress.limiter.policies import Priority
+
from products.engineering_analytics.backend.facade.contracts import (
TrunkQuarantineDebt,
TrunkQuarantinedTest,
TrunkQuarantineTeamDebt,
)
from products.engineering_analytics.backend.logic.ownership import QuarantinedTestFile, resolve_test_ownership
+from products.engineering_analytics.backend.logic.ownership_files import repo_files
from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource
# Oldest first, so a repo past the cap keeps the debt that has aged past its TTL.
@@ -90,7 +93,12 @@ def query_trunk_quarantine_debt(
(runner, nodeid, QuarantinedTestFile(source_path=source_path, crate=crate), status, setting, case_id, at)
for runner, nodeid, source_path, crate, status, setting, case_id, at in rows
]
- owned_by_test = resolve_test_ownership(curated.repository, [row[2] for row in parsed])
+ owned_by_test = resolve_test_ownership(
+ curated.repository,
+ [row[2] for row in parsed],
+ # A person is waiting on the board, so the reads run on the interactive lane.
+ files=repo_files(curated.team, curated.repository, source_id=curated.source_id, priority=Priority.NORMAL),
+ )
tests: list[TrunkQuarantinedTest] = []
for (runner, nodeid, _file, status, quarantine_setting, test_case_id, quarantined_at), owned in zip(
parsed, owned_by_test.tests, strict=True
diff --git a/products/engineering_analytics/backend/logic/sources.py b/products/engineering_analytics/backend/logic/sources.py
index 45ea52230f40..f9129afdfe1a 100644
--- a/products/engineering_analytics/backend/logic/sources.py
+++ b/products/engineering_analytics/backend/logic/sources.py
@@ -115,6 +115,10 @@ class GitHubTables:
issue_events_team_requests: bool = False
# Used to scope cross-store reads such as CI traces to the selected source's repository.
repository: str = ""
+ # The source these tables came from, already filtered by the caller's per-source warehouse RBAC.
+ # A read outside the warehouse that needs the repository's credential takes it from this source
+ # alone, so it can never reach a credential of a source the caller may not use.
+ source_id: str = ""
def resolve_github_tables(
@@ -187,6 +191,7 @@ def resolve_github_tables(
reviews=tables.get(REVIEWS_SCHEMA),
issue_events_team_requests=candidate.tables.issue_events_team_requests,
repository=candidate.repository,
+ source_id=candidate.source_id,
)
if source_id is not None:
raise GitHubSourceNotConnectedError(_NO_SELECTED_SOURCE)
@@ -381,6 +386,7 @@ class _RepoCandidate(NamedTuple):
# a bare row has no repo to attribute it to); the parsed ``owner/repo`` for a qualified repo.
repository: str
tables: _RepoTables
+ source_id: str
def _repo_candidates(*, team: Team, sources: QuerySet[ExternalDataSource]) -> Iterator[_RepoCandidate]:
@@ -410,7 +416,7 @@ def _repo_candidates(*, team: Team, sources: QuerySet[ExternalDataSource]) -> It
by_repo = _synced_tables_by_repo(team=team, source=source)
for repo_key in sorted(by_repo, key=order_key):
repository = display if repo_key == legacy_key else repo_key
- yield _RepoCandidate(repository=repository, tables=by_repo[repo_key])
+ yield _RepoCandidate(repository=repository, tables=by_repo[repo_key], source_id=str(source.id))
def _github_sources(team: Team, user_access_control: "UserAccessControl | None" = None) -> QuerySet[ExternalDataSource]:
diff --git a/products/engineering_analytics/backend/tests/test_logic_sources.py b/products/engineering_analytics/backend/tests/test_logic_sources.py
index 962fa4086690..73d98e65c2e5 100644
--- a/products/engineering_analytics/backend/tests/test_logic_sources.py
+++ b/products/engineering_analytics/backend/tests/test_logic_sources.py
@@ -68,10 +68,12 @@ class TestResolveGitHubTables(BaseTest):
_BOTH_SYNCED = [(PULL_REQUESTS_SCHEMA, True, True), (WORKFLOW_RUNS_SCHEMA, True, True)]
def test_resolves_non_default_prefix_tables(self) -> None:
- self._connect(prefix="myprefix", schemas=self._BOTH_SYNCED)
+ source = self._connect(prefix="myprefix", schemas=self._BOTH_SYNCED)
tables = resolve_github_tables(team=self.team)
assert tables == GitHubTables(
- pull_requests="myprefixgithub_pull_requests", workflow_runs="myprefixgithub_workflow_runs"
+ pull_requests="myprefixgithub_pull_requests",
+ workflow_runs="myprefixgithub_workflow_runs",
+ source_id=str(source.id),
)
@parameterized.expand([("with_team_requests", ["event", "requested_team"], True), ("without", ["event"], False)])
@@ -164,10 +166,12 @@ class TestResolveGitHubTables(BaseTest):
def test_skips_incomplete_source_for_a_complete_one(self) -> None:
# The oldest source is missing an endpoint; resolution falls through to the complete one.
self._connect(prefix="incomplete", schemas=[(PULL_REQUESTS_SCHEMA, True, True)])
- self._connect(prefix="complete", schemas=self._BOTH_SYNCED)
+ complete = self._connect(prefix="complete", schemas=self._BOTH_SYNCED)
tables = resolve_github_tables(team=self.team)
assert tables == GitHubTables(
- pull_requests="completegithub_pull_requests", workflow_runs="completegithub_workflow_runs"
+ pull_requests="completegithub_pull_requests",
+ workflow_runs="completegithub_workflow_runs",
+ source_id=str(complete.id),
)
def test_ignores_soft_deleted_source(self) -> None:
@@ -181,7 +185,9 @@ class TestResolveGitHubTables(BaseTest):
newer = self._connect(prefix="newer", schemas=self._BOTH_SYNCED)
tables = resolve_github_tables(team=self.team, source_id=str(newer.id))
assert tables == GitHubTables(
- pull_requests="newergithub_pull_requests", workflow_runs="newergithub_workflow_runs"
+ pull_requests="newergithub_pull_requests",
+ workflow_runs="newergithub_workflow_runs",
+ source_id=str(newer.id),
)
def test_unknown_source_id_raises(self) -> None:
@@ -337,7 +343,7 @@ class TestMultiRepoGitHubResolution(BaseTest):
def test_new_source_single_qualified_repo_resolves(self) -> None:
# A source created via the multi-repo `repositories` field has no legacy `repository`, so its
# one repo is qualified from day one. Bare-name matching would 400 this — the onboarding break.
- self._multi_repo_source(
+ source = self._multi_repo_source(
prefix="fresh",
repos={"PostHog/posthog": [(PULL_REQUESTS_SCHEMA, True), (WORKFLOW_RUNS_SCHEMA, True)]},
)
@@ -346,6 +352,7 @@ class TestMultiRepoGitHubResolution(BaseTest):
pull_requests="freshgithub_posthog_posthog_pull_requests",
workflow_runs="freshgithub_posthog_posthog_workflow_runs",
repository="posthog/posthog",
+ source_id=str(source.id),
)
@parameterized.expand(
diff --git a/products/engineering_analytics/backend/tests/test_ownership.py b/products/engineering_analytics/backend/tests/test_ownership.py
index 4d07921900ec..a08a244e0782 100644
--- a/products/engineering_analytics/backend/tests/test_ownership.py
+++ b/products/engineering_analytics/backend/tests/test_ownership.py
@@ -1,26 +1,17 @@
-from collections.abc import Iterator
from dataclasses import field
-from threading import Event
-from time import monotonic
-from unittest.mock import patch
-
-from django.core.cache import cache
from django.test import SimpleTestCase
from parameterized import parameterized
from posthog.dataclasses import frozen
+from posthog.ownership.paths import UNOWNED_TEAM
+from posthog.ownership.repo_files import OwnershipUnavailable
-from products.engineering_analytics.backend.facade.contracts import UNOWNED_TEAM
from products.engineering_analytics.backend.logic.ownership import (
- _MAX_FILE_BYTES,
UNPLACED,
- GitHubRepoFiles,
- OwnershipUnavailable,
PlacedTest,
QuarantinedTestFile,
- resolve_path_owners,
resolve_test_ownership,
)
@@ -130,129 +121,3 @@ class TestRepoOwnership(SimpleTestCase):
def test_a_resolved_batch_says_so(self) -> None:
assert resolve_test_ownership("PostHog/posthog", [], files=_FakeRepoFiles()).resolved
-
-
-class TestPathOwnership(SimpleTestCase):
- def test_places_each_path_exactly_and_returns_the_registry(self) -> None:
- # Exact resolution, not the suite-root search: 'src/...' is a real repo-relative path here
- # and must not be repositioned under nodejs/ the way a reported test path is.
- owned = resolve_path_owners(
- "PostHog/posthog",
- ["nodejs/src/cdp/worker.ts", "src/cdp/worker.ts"],
- files=_FakeRepoFiles(),
- )
- assert owned.resolved
- assert owned.team_by_path == {"nodejs/src/cdp/worker.ts": "team-ingestion", "src/cdp/worker.ts": "team-root"}
- assert owned.registry["team-ingestion"].notifications == "#alerts-ingestion"
-
- def test_an_unreadable_repository_owns_nothing_and_says_so(self) -> None:
- no_root = _FakeRepoFiles(owners={k: v for k, v in _OWNERS.items() if k != "owners.yaml"})
- owned = resolve_path_owners("PostHog/posthog", ["nodejs/src/cdp/worker.ts"], files=no_root)
- assert not owned.resolved
- assert owned.team_by_path == {"nodejs/src/cdp/worker.ts": UNOWNED_TEAM}
- assert owned.registry == {}
-
-
-class TestGitHubRepoFiles(SimpleTestCase):
- def setUp(self) -> None:
- cache.clear()
-
- @parameterized.expand([(500,), (403,)])
- def test_an_unexpected_status_raises_rather_than_reading_as_absent(self, status: int) -> None:
- # Reading a failure as "no such file" reattributes everything under it to an ancestor.
- with patch(
- "products.engineering_analytics.backend.logic.ownership.github_request",
- return_value=_response(status),
- ):
- with self.assertRaises(OwnershipUnavailable):
- GitHubRepoFiles("PostHog/posthog").read("owners.yaml")
-
- def test_a_missing_file_is_absent_and_fetched_once(self) -> None:
- with patch(
- "products.engineering_analytics.backend.logic.ownership.github_request",
- return_value=_response(404),
- ) as request:
- files = GitHubRepoFiles("PostHog/posthog")
- assert files.read("nodejs/owners.yaml") is None
- assert files.read("nodejs/owners.yaml") is None
- assert GitHubRepoFiles("PostHog/posthog").read("nodejs/owners.yaml") is None
- assert request.call_count == 1
-
- def test_a_slow_repository_gives_up_instead_of_holding_the_worker(self) -> None:
- # A cold board asks for hundreds of files. Without a budget for the whole resolution, a
- # stalled raw host holds a web worker far past the per-request timeout.
- started, release, finished = Event(), Event(), Event()
- self.addCleanup(release.set)
-
- def stalls(_method: str, _url: str, **_kwargs: object) -> _response:
- started.set()
- release.wait(timeout=10)
- finished.set()
- return _response(404)
-
- files = GitHubRepoFiles("PostHog/posthog")
-
- def at_the_deadline_once_the_fetch_runs() -> float:
- assert started.wait(timeout=10)
- return files._deadline
-
- with (
- patch("products.engineering_analytics.backend.logic.ownership.github_request", side_effect=stalls),
- patch(
- "products.engineering_analytics.backend.logic.ownership.monotonic",
- side_effect=at_the_deadline_once_the_fetch_runs,
- ),
- ):
- with self.assertRaises(OwnershipUnavailable):
- files.read("owners.yaml")
- assert not finished.is_set()
-
- def test_a_file_that_arrives_too_slowly_is_refused(self) -> None:
- # The per-request timeout starts again on each chunk, so the byte limit alone lets one read
- # run for minutes. Nothing waits for the fetch after the deadline, so nothing else stops it.
- files = GitHubRepoFiles("PostHog/posthog")
- response = _response(200)
-
- def expires_mid_body(chunk_size: int) -> Iterator[bytes]:
- yield b"x" * chunk_size
- files._deadline = monotonic() - 1
- yield b"x" * chunk_size
-
- with (
- patch("products.engineering_analytics.backend.logic.ownership.github_request", return_value=response),
- patch.object(response, "iter_content", expires_mid_body),
- ):
- with self.assertRaises(OwnershipUnavailable):
- files.read("owners.yaml")
-
- @parameterized.expand([("declared", True), ("streamed", False)])
- def test_an_oversized_file_is_refused(self, _name: str, declare_length: bool) -> None:
- # A connected repository controls these files, so an unbounded read would put its bytes in
- # a worker's memory and in Redis. Content-Length can lie, so the streamed read is the ceiling.
- oversized = b"x" * (_MAX_FILE_BYTES + 1)
- headers = {"Content-Length": str(len(oversized))} if declare_length else {}
- with patch(
- "products.engineering_analytics.backend.logic.ownership.github_request",
- return_value=_response(200, body=oversized, headers=headers),
- ):
- with self.assertRaises(OwnershipUnavailable):
- GitHubRepoFiles("PostHog/posthog").read("owners.yaml")
-
-
-class _response:
- encoding = "utf-8"
-
- def __init__(self, status: int, body: bytes = b"", headers: dict[str, str] | None = None) -> None:
- self.status_code = status
- self.headers = headers or {}
- self._body = body
-
- def iter_content(self, chunk_size: int) -> Iterator[bytes]:
- for start in range(0, len(self._body), chunk_size):
- yield self._body[start : start + chunk_size]
-
- def __enter__(self) -> "_response":
- return self
-
- def __exit__(self, *args: object) -> None:
- pass
diff --git a/products/engineering_analytics/backend/tests/test_ownership_files.py b/products/engineering_analytics/backend/tests/test_ownership_files.py
new file mode 100644
index 000000000000..374b36c23a38
--- /dev/null
+++ b/products/engineering_analytics/backend/tests/test_ownership_files.py
@@ -0,0 +1,74 @@
+from posthog.test.base import BaseTest
+from unittest.mock import patch
+
+from django.core.cache import cache
+
+from parameterized import parameterized
+
+from posthog.egress.limiter.policies import Priority
+from posthog.models.integration import Integration
+from posthog.ownership.github_files import AuthenticatedRepoFiles, GitHubFilesFetcher
+from posthog.ownership.repo_files import GitHubRepoFiles
+
+from products.engineering_analytics.backend.logic.ownership_files import repo_files
+from products.warehouse_sources.backend.facade.contracts import GitHubSourceCredential
+
+_REPOSITORY = "PostHog/posthog"
+_CREDENTIAL = "products.warehouse_sources.backend.facade.api.github_source_credential"
+
+
+class TestOwnershipFiles(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ # The team's covering integration is cached per repository, so one test's fallback would
+ # otherwise answer the next one's lookup.
+ cache.clear()
+
+ def _integration(self) -> Integration:
+ return Integration.objects.create(
+ team=self.team,
+ kind="github",
+ integration_id="42",
+ config={"account": {"name": "PostHog"}},
+ sensitive_config={"access_token": "t0ken"},
+ )
+
+ def test_the_selected_sources_token_is_what_reads_the_repository(self) -> None:
+ # A connected source is the only credential engineering analytics has for a private
+ # repository, and the read must use the token of the source it was scoped to.
+ with (
+ patch(_CREDENTIAL, return_value=GitHubSourceCredential(personal_access_token="selected")) as credential,
+ patch.object(GitHubFilesFetcher, "from_token", side_effect=GitHubFilesFetcher.from_token) as built,
+ ):
+ files = repo_files(self.team, _REPOSITORY, source_id="src", priority=Priority.BATCH)
+ credential.assert_called_once_with(team_id=self.team.pk, source_id="src")
+ built.assert_called_once_with("selected", priority=Priority.BATCH)
+ assert isinstance(files, AuthenticatedRepoFiles)
+
+ @parameterized.expand([("a_connected_integration", True), ("an_integration_row_that_is_gone", False)])
+ def test_an_oauth_source_reads_as_its_github_integration(self, _name: str, connected: bool) -> None:
+ # The source names an integration row rather than holding a token, so a row that was
+ # disconnected since the sync was configured has to fall back rather than fail the board.
+ integration_id = self._integration().pk if connected else 0
+ with (
+ patch(_CREDENTIAL, return_value=GitHubSourceCredential(integration_id=integration_id)),
+ patch("posthog.ownership.github_files.GitHubIntegration.first_for_team_repository", return_value=None),
+ ):
+ files = repo_files(self.team, _REPOSITORY, source_id="src", priority=Priority.BATCH)
+ assert isinstance(files, AuthenticatedRepoFiles if connected else GitHubRepoFiles)
+
+ @parameterized.expand([("no_selected_source", "", 0), ("a_source_with_no_credential", "src", 1)])
+ def test_a_read_with_no_credential_falls_back_to_the_team_integration(
+ self, _name: str, source_id: str, lookups: int
+ ) -> None:
+ with (
+ patch(_CREDENTIAL, return_value=None) as credential,
+ patch(
+ "posthog.ownership.github_files.GitHubIntegration.first_for_team_repository", return_value=None
+ ) as team_lookup,
+ ):
+ files = repo_files(self.team, _REPOSITORY, source_id=source_id, priority=Priority.BATCH)
+ # An empty source_id names no source, so it must not cost a source lookup either.
+ assert credential.call_count == lookups
+ team_lookup.assert_called_once()
+ assert isinstance(files, GitHubRepoFiles)
diff --git a/products/engineering_analytics/backend/tests/test_quarantine.py b/products/engineering_analytics/backend/tests/test_quarantine.py
index 6823f896f42d..59a5b7c61782 100644
--- a/products/engineering_analytics/backend/tests/test_quarantine.py
+++ b/products/engineering_analytics/backend/tests/test_quarantine.py
@@ -780,6 +780,8 @@ class TestQuarantineRequestValidation(SimpleTestCase):
class _StubCurated:
def __init__(self, rows: list[tuple[Any, ...]]) -> None:
self.repository = "PostHog/posthog"
+ self.team = None
+ self.source_id = ""
self._rows = rows
self.sql = ""
@@ -817,10 +819,13 @@ class TestTrunkQuarantineDebtTruncation(TestCase):
def test_rollup_never_counts_more_tests_than_it_returns(self, _name: str, row_count: int, truncated: bool) -> None:
curated = _StubCurated(self._rows(row_count))
- def place(_repository: str, tests: list[Any]) -> RepoOwnershipResult:
+ def place(_repository: str, tests: list[Any], **_kwargs: Any) -> RepoOwnershipResult:
return RepoOwnershipResult(tests=[PlacedTest(path="p", owner_team="team-a")] * len(tests), resolved=True)
- with mock.patch(f"{_TRUNK_QUARANTINE}.resolve_test_ownership", side_effect=place):
+ with (
+ mock.patch(f"{_TRUNK_QUARANTINE}.resolve_test_ownership", side_effect=place),
+ mock.patch(f"{_TRUNK_QUARANTINE}.repo_files"),
+ ):
debt = query_trunk_quarantine_debt(
curated=curated, # type: ignore[arg-type]
ttl_days=30,
diff --git a/products/signals/ARCHITECTURE.md b/products/signals/ARCHITECTURE.md
index 7d6e6e9749da..6fce543c2f1f 100644
--- a/products/signals/ARCHITECTURE.md
+++ b/products/signals/ARCHITECTURE.md
@@ -1327,7 +1327,7 @@ Under the `signals-pr-dri-assignee` flag, the candidates are, most responsible f
1. **The person who chose the work.** A claim a person made, or one their agent made for them, since an agent claim records the person it ran as. A task claim does not count: an auto-started report is claimed by its own implementation task, and that task runs as the report's top suggested reviewer, so it names a commit-history guess rather than a decision.
2. **Somebody who asked to be assigned** through `SignalUserAutonomyConfig.github_assign_on_pull_request`. Where several did, the one who owns the changed code wins, else the highest-ranked suggested reviewer among them.
-3. **A member of the team that owns the changed files**, when the repository declares ownership in `owners.yaml` (`backend/pr_owning_team.py`). The members follow in random order. A member the report suggests gets no priority, because commit history would otherwise give one prolific committer every pull request. The engineering analytics facade (`resolve_path_owners`) resolves the team. GitHub teams are the canonical team identity, so the members come from GitHub's team members API, which needs the organization members read permission on the GitHub app.
+3. **A member of the team that owns the changed files**, when the repository declares ownership in `owners.yaml` (`backend/pr_owning_team.py`). The members follow in random order. A member the report suggests gets no priority, because commit history would otherwise give one prolific committer every pull request. The core ownership module (`posthog.ownership.paths.resolve_path_owners`) resolves the team. GitHub teams are the canonical team identity, so the members come from GitHub's team members API, which needs the organization members read permission on the GitHub app.
4. **The suggested reviewers in rank order**, when no ownership source names a team.
A candidate from rungs 1, 2 and 4 must be an organization member with a connected GitHub account. A member of the owning team needs only GitHub team membership, because that membership is the ownership, and does not need a PostHog account. Each candidate is checked with GitHub's read-only assignee check first, because the add-assignees call drops a login without push access instead of failing. A candidate GitHub cannot assign moves the walk to the next one, for up to four checks, and a failed check stops it. A report with no candidate at all gets no DRI.
@@ -1339,7 +1339,7 @@ Without the flag the older rule stands: every suggested reviewer who opted in is
> [!WARNING]
> Keep the `signals-pr-dri-assignee` flag on the PostHog organization only until a team-level off switch exists in the inbox settings. Assigning people on a customer's GitHub is that team's decision, and today a team cannot turn the rule off: removing `owners.yaml` only changes who gets picked.
-The ownership lookup reads `owners.yaml` only, and only for a public repository, because the engineering analytics lookup reads files anonymously. A repository with only CODEOWNERS, or a private repository, falls back to the suggested reviewers. The planned `owners_yaml` resolver adapter covers both: CODEOWNERS as a second format behind the same resolver interface, and files read through the GitHub app.
+The ownership lookup reads the files through `posthog.ownership`, with the GitHub integration the team already connected, so a private repository resolves wherever that installation covers it. A repository no installation covers is still read anonymously, which answers for a public repository only. The lookup reads `owners.yaml` and nothing else, so a repository declaring ownership in CODEOWNERS alone falls back to the suggested reviewers. CODEOWNERS as a second format behind the same resolver interface is still open.
**Fleet steering in the task description** (`load_report_steering` in `backend/report_steering.py`).
diff --git a/products/signals/backend/pr_owning_team.py b/products/signals/backend/pr_owning_team.py
index d6f1991d0c59..5b7005019dca 100644
--- a/products/signals/backend/pr_owning_team.py
+++ b/products/signals/backend/pr_owning_team.py
@@ -14,11 +14,11 @@ from collections import Counter
import structlog
from posthog.dataclasses import frozen
+from posthog.egress.limiter.policies import Priority
from posthog.models.github_integration_base import PullRequestRef
from posthog.models.integration import GitHubIntegration
-
-from products.engineering_analytics.backend.facade.api import resolve_path_owners
-from products.engineering_analytics.backend.facade.contracts import UNOWNED_TEAM
+from posthog.ownership.github_files import AuthenticatedRepoFiles, GitHubFilesFetcher
+from posthog.ownership.paths import UNOWNED_TEAM, resolve_path_owners
logger = structlog.get_logger(__name__)
@@ -53,7 +53,14 @@ class OwningTeamResolver:
if not files["paths"]:
return None
- ownership = resolve_path_owners(self.parsed.repository, files["paths"])
+ # The resolver already holds the team's installation, so the ownership files come from it
+ # rather than from the anonymous public reader, which lets a private repository resolve too.
+ # Report generation is background work, so it sheds before anything a person waits on.
+ owners_files = AuthenticatedRepoFiles(
+ self.parsed.repository,
+ GitHubFilesFetcher.from_integration(self.github, priority=Priority.BATCH),
+ )
+ ownership = resolve_path_owners(self.parsed.repository, files["paths"], files=owners_files)
if not ownership.resolved:
return None
counts = Counter(team for team in ownership.team_by_path.values() if team != UNOWNED_TEAM)
diff --git a/products/signals/backend/report_generation/ownership_reviewers.py b/products/signals/backend/report_generation/ownership_reviewers.py
index 6221752a9b30..e4b8a3fe5468 100644
--- a/products/signals/backend/report_generation/ownership_reviewers.py
+++ b/products/signals/backend/report_generation/ownership_reviewers.py
@@ -8,11 +8,12 @@ from django.db.models.functions import Lower
from owners_yaml.matcher import compile_pattern, normalize_path
+from posthog.egress.limiter.policies import Priority
from posthog.models.integration import GitHubIntegration
from posthog.models.team.team import Team
+from posthog.ownership.github_files import AuthenticatedRepoFiles, GitHubFilesFetcher
+from posthog.ownership.paths import UNOWNED_TEAM, resolve_path_owners
-from products.engineering_analytics.backend.facade.api import resolve_path_owners
-from products.engineering_analytics.backend.facade.contracts import UNOWNED_TEAM
from products.signals.backend.report_generation.resolve_reviewers import (
bounded_reviewer_reason,
resolve_org_github_login_to_users,
@@ -76,7 +77,10 @@ def suggest_repository_owners(
if github is None:
return []
codeowners = _codeowners_for_paths(github, repository, paths)
- ownership = resolve_path_owners(repository, paths)
+ owners_files = AuthenticatedRepoFiles(
+ repository, GitHubFilesFetcher.from_integration(github, priority=Priority.BATCH)
+ )
+ ownership = resolve_path_owners(repository, paths, files=owners_files)
except Exception:
logger.exception("Could not resolve repository owners for %s", repository)
return []
diff --git a/products/signals/backend/test/test_ownership_reviewers.py b/products/signals/backend/test/test_ownership_reviewers.py
index 198f299fde36..8275120fcc2c 100644
--- a/products/signals/backend/test/test_ownership_reviewers.py
+++ b/products/signals/backend/test/test_ownership_reviewers.py
@@ -5,8 +5,8 @@ from unittest.mock import MagicMock, patch
from posthog.models import User
from posthog.models.organization import OrganizationMembership
+from posthog.ownership.paths import PathOwnership
-from products.engineering_analytics.backend.facade.contracts import PathOwnership
from products.signals.backend.artefact_attribution import ArtefactAttribution
from products.signals.backend.artefact_schemas import SignalFinding, SuggestedReviewers
from products.signals.backend.models import SignalReport, SignalReportArtefact
diff --git a/products/signals/backend/test/test_reviewer_pr_assignment.py b/products/signals/backend/test/test_reviewer_pr_assignment.py
index 80fe3a111213..7550c95febfb 100644
--- a/products/signals/backend/test/test_reviewer_pr_assignment.py
+++ b/products/signals/backend/test/test_reviewer_pr_assignment.py
@@ -7,8 +7,8 @@ from social_django.models import UserSocialAuth
from posthog.models import Organization, Team, User
from posthog.models.organization import OrganizationMembership
+from posthog.ownership.paths import UNOWNED_TEAM, PathOwnership
-from products.engineering_analytics.backend.facade.contracts import UNOWNED_TEAM, PathOwnership
from products.signals.backend.artefact_attribution import ArtefactAttribution
from products.signals.backend.models import (
SignalReport,
diff --git a/products/stamphog/backend/logic/channel_resolution.py b/products/stamphog/backend/logic/channel_resolution.py
index 9aa9c9b2edf1..4d6353f28055 100644
--- a/products/stamphog/backend/logic/channel_resolution.py
+++ b/products/stamphog/backend/logic/channel_resolution.py
@@ -36,7 +36,9 @@ from owners_yaml.resolver import Purpose, TeamChannel, team_channel, teams_regis
from owners_yaml.schema import Producer, TeamEntry
from posthog.dataclasses import frozen
+from posthog.egress.limiter.policies import Priority
from posthog.models.integration import Integration
+from posthog.ownership.github_files import AuthenticatedRepoFiles, GitHubFilesFetcher
from posthog.team_notifications.slack import SlackChannel, fetch_channel_map, find_channel
from ..facade.enums import ChannelResolutionSource
@@ -139,7 +141,26 @@ class _RepoRouting:
declared_channel: str | None
-def _read_repo_routing(repo_config: StamphogRepoConfig) -> _RepoRouting:
+def _fetcher_for_installation(installation_id: str) -> GitHubFilesFetcher:
+ """One fetcher per installation, not per repository.
+
+ It holds a token and a connection pool, and a team's repositories usually sit under one
+ installation, so building one per repository mints a token and a pool to read a single file.
+ """
+ try:
+ client = StamphogGitHubClient(installation_id)
+ return GitHubFilesFetcher.from_token(
+ client.installation_token(),
+ installation_id=installation_id,
+ refresh=client.refresh_installation_token,
+ # The daily run is background work, so it sheds before anything a person waits on.
+ priority=Priority.BATCH,
+ )
+ except Exception as e:
+ raise RoutingUnavailable(f"could not authenticate installation {installation_id}: {e}") from e
+
+
+def _read_repo_routing(repo_config: StamphogRepoConfig, fetcher: GitHubFilesFetcher) -> _RepoRouting:
"""One repo's routing config: its root registry, and the digest channel it declared.
Both reads answer to one failure contract. A transient fetch failure for either file raises
@@ -148,9 +169,10 @@ def _read_repo_routing(repo_config: StamphogRepoConfig) -> _RepoRouting:
owners.yaml inherits one, and a repo declaring no channel has no repo audience to route.
"""
try:
- raw = StamphogGitHubClient(repo_config.installation_id).get_default_branch_file(
- repo_config.repository, _OWNERS_FILE_PATH
- )
+ # Routing is derived every run and never stored, so a head SHA another read cached up to
+ # two minutes ago could route a merged owners.yaml change to yesterday's channel.
+ files = AuthenticatedRepoFiles(repo_config.repository, fetcher, fresh_head=True)
+ raw = files.read(_OWNERS_FILE_PATH)
digest_config = load_repo_digest_config(repo_config) if repo_config.digest_enabled else None
except Exception as e:
raise RoutingUnavailable(f"could not read routing config for {repo_config.repository}: {e}") from e
@@ -173,8 +195,13 @@ def build_routing_context(team_id: int) -> RoutingContext | None:
registry_by_repo: dict[str, dict[str, TeamEntry]] = {}
declared_repo_channel: dict[str, str] = {}
+ fetcher_by_installation: dict[str, GitHubFilesFetcher] = {}
for repo_config in _candidate_repo_configs(team_id):
- routing = _read_repo_routing(repo_config)
+ fetcher = fetcher_by_installation.get(repo_config.installation_id)
+ if fetcher is None:
+ fetcher = _fetcher_for_installation(repo_config.installation_id)
+ fetcher_by_installation[repo_config.installation_id] = fetcher
+ routing = _read_repo_routing(repo_config, fetcher)
registry_by_repo[repo_config.repository] = routing.registry
if routing.declared_channel is not None:
declared_repo_channel[repo_config.repository] = routing.declared_channel
diff --git a/products/stamphog/backend/logic/github_client.py b/products/stamphog/backend/logic/github_client.py
index 937a851966c0..9db17e9484a1 100644
--- a/products/stamphog/backend/logic/github_client.py
+++ b/products/stamphog/backend/logic/github_client.py
@@ -409,6 +409,18 @@ class StamphogGitHubClient:
cache.set(cache_key, {"token": token, "expires_at": expires_epoch}, timeout=ttl)
return token
+ def installation_token(self) -> str:
+ """A valid installation token, for a shared reader that talks to GitHub on its own.
+
+ The ownership file reader takes a bare token rather than a client, so one GraphQL read
+ serves every product instead of each one growing its own fetch.
+ """
+ return self._get_installation_token()
+
+ def refresh_installation_token(self) -> str:
+ """A freshly minted installation token, for a shared reader that met a 401 with the last one."""
+ return self._get_installation_token(force_refresh=True)
+
# --- Core request helper ---
def _request(
diff --git a/products/stamphog/backend/tests/conftest.py b/products/stamphog/backend/tests/conftest.py
index e8542ffae12a..41803c74bd2d 100644
--- a/products/stamphog/backend/tests/conftest.py
+++ b/products/stamphog/backend/tests/conftest.py
@@ -6,6 +6,7 @@ from typing import Any
import pytest
from unittest.mock import MagicMock, patch
+from django.core.cache import cache
from django.test import Client, override_settings
from cryptography.hazmat.primitives import serialization
@@ -178,6 +179,10 @@ def stamphog_chain() -> Iterator[StamphogChain]:
``on_commit`` fires inline (the test's outer transaction never really commits). Everything else
runs as production code.
"""
+ # The chain caches GitHub reads (installation tokens, the ownership reader's head commit and
+ # blobs), and those entries outlive one test, so a test would answer with the files of the one
+ # before it.
+ cache.clear()
recorder = fakes.GitHubRecorder()
# review-guidance.md is a required trusted policy file — run_review_in_sandbox fails closed without
# it — so seed it for the whole chain; individual tests still set/override policy.yml as they need.
@@ -207,6 +212,9 @@ def stamphog_chain() -> Iterator[StamphogChain]:
stack.enter_context(
patch("products.stamphog.backend.logic.github_client.github_request", recorder.github_request)
)
+ # Routing reads the repo's owners.yaml through the shared ownership reader, which talks to
+ # GitHub itself rather than through the stamphog client.
+ stack.enter_context(patch("posthog.ownership.github_files.github_request", recorder.github_request))
stack.enter_context(
patch(
"products.stamphog.backend.logic.github_client.remember_observed_core_limit",
diff --git a/products/stamphog/backend/tests/fakes.py b/products/stamphog/backend/tests/fakes.py
index cb71b930a89d..c08208768e8b 100644
--- a/products/stamphog/backend/tests/fakes.py
+++ b/products/stamphog/backend/tests/fakes.py
@@ -120,12 +120,24 @@ class FakeResponse:
self._json = json_data
self.text = text if text else ("" if json_data is None else "<json>")
self.headers = headers or {}
+ self.encoding = "utf-8"
def json(self) -> Any:
if self._json is None:
raise ValueError("no json")
return self._json
+ def iter_content(self, chunk_size: int = 8192) -> Iterable[bytes]:
+ raw = (json.dumps(self._json) if self._json is not None else self.text).encode()
+ for start in range(0, len(raw), chunk_size):
+ yield raw[start : start + chunk_size]
+
+ def __enter__(self) -> FakeResponse:
+ return self
+
+ def __exit__(self, *_exc: object) -> None:
+ return None
+
class GitHubRecorder:
"""Scriptable GitHub API fake. Configure reads, then read ``github_writes`` after a run."""
@@ -164,6 +176,9 @@ class GitHubRecorder:
# Per-repository overrides for the same paths, for cases where two connected repos must
# answer differently (one carries a root owners.yaml, another does not).
self.repo_files: dict[tuple[str, str], str] = {}
+ # Repositories with no commits at all. GitHub answers their head lookup with a null
+ # defaultBranchRef, which is what a freshly created connected repo looks like.
+ self.empty_repositories: set[str] = set()
self.github_writes: list[dict[str, Any]] = []
self._next_id = 90000
@@ -267,13 +282,23 @@ class GitHubRecorder:
def _graphql(self, body: dict) -> FakeResponse:
query = str(body.get("query") or "")
variables = body.get("variables") or {}
- # GraphQL callers share /graphql: get_pr_review_threads, get_user_team_slugs, and the
- # minimizeComment mutation after a dismissal. Route by the query's shape.
+ # GraphQL callers share /graphql: get_pr_review_threads, get_user_team_slugs, the minimizeComment
+ # mutation after a dismissal, and the shared ownership file reader. Route by the query's shape.
if "minimizeComment" in query:
self.github_writes.append({"kind": "minimize_review", "node_id": variables.get("id"), "query": query})
return FakeResponse(
200, json_data={"data": {"minimizeComment": {"minimizedComment": {"isMinimized": True}}}}
)
+ if "defaultBranchRef" in query:
+ if f"{variables.get('owner', '')}/{variables.get('name', '')}" in self.empty_repositories:
+ return FakeResponse(200, json_data={"data": {"repository": {"defaultBranchRef": None}}})
+ # The ownership reader caches blobs per commit, and the cache outlives one test. A commit
+ # derived from the scripted files keeps each test reading its own files.
+ scripted = repr(sorted(self.policy_files.items()) + sorted(self.repo_files.items()))
+ oid = hashlib.sha256(scripted.encode()).hexdigest()
+ return FakeResponse(200, json_data={"data": {"repository": {"defaultBranchRef": {"target": {"oid": oid}}}}})
+ if "object(expression:" in query:
+ return self._ownership_blobs(f"{variables.get('owner', '')}/{variables.get('name', '')}", query, variables)
if "reviewThreads" in query:
repo = f"{variables.get('owner', '')}/{variables.get('name', '')}"
number = int(variables.get("pr") or 0)
@@ -293,6 +318,21 @@ class GitHubRecorder:
teams_data = {"data": {"organization": {"teams": {"nodes": [{"slug": s} for s in slugs]}}}}
return FakeResponse(200, json_data=teams_data)
+ def _ownership_blobs(self, repo: str, query: str, variables: dict) -> FakeResponse:
+ """The aliased blob lookups the shared ownership reader sends, served from the same files the
+ contents API answers with. Each variable holds a ``<commit>:<path>`` expression."""
+ field: dict[str, Any] = {}
+ for name, expression in variables.items():
+ if name in ("owner", "name"):
+ continue
+ path = str(expression).split(":", 1)[1]
+ content = self.repo_files.get((repo, path), self.policy_files.get(path))
+ if content is None:
+ field[f"f{name[1:]}"] = None
+ else:
+ field[f"f{name[1:]}"] = {"text": content} if "text" in query else {"__typename": "Blob"}
+ return FakeResponse(200, json_data={"data": {"repository": field}})
+
def _record_write(self, kind: str, repo: str, number: int, body: dict | None) -> FakeResponse:
new_id = self._alloc_id()
self.github_writes.append({"kind": kind, "repo": repo, "number": number, "body": body or {}, "id": new_id})
diff --git a/products/stamphog/backend/tests/test_integration.py b/products/stamphog/backend/tests/test_integration.py
index 3b935848e98e..8285c63cd5db 100644
--- a/products/stamphog/backend/tests/test_integration.py
+++ b/products/stamphog/backend/tests/test_integration.py
@@ -1841,6 +1841,33 @@ def test_registry_of_one_connected_repo_routes_an_audience_from_a_repo_without_o
assert (run.slack_channel_id, run.resolution_source) == ("C-STANDUP", ChannelResolutionSource.OWNERS_CONTACT)
[email protected]_db(databases=PRODUCT_DATABASES)
+def test_a_repository_with_no_commits_does_not_block_the_teams_other_digests(
+ team, stamphog_chain: StamphogChain
+) -> None:
+ # A repository with no commits has no default branch, so its head lookup answers with a null.
+ # Treating that as an unreadable routing file took the whole team's run down, which meant one
+ # freshly connected repo silenced every other repo's morning digest.
+ _repo_config(team.id, repository="acme/charts")
+ _repo_config(team.id, repository="acme/widgets")
+ Integration.objects.create(
+ team_id=team.id, kind="slack", config={"authed_user": {"id": "U1"}}, sensitive_config={"access_token": "x"}
+ )
+ stamphog_chain.recorder.empty_repositories.add("acme/charts")
+ stamphog_chain.recorder.repo_files[("acme/widgets", "owners.yaml")] = _STANDUP_REGISTRY
+ _merged_pr_with_audience(
+ team.id,
+ StamphogRepoConfig.objects.for_team(team.id).get(repository="acme/widgets"),
+ number=101,
+ audience_key="team-devex",
+ )
+ fakes.FakeSlackIntegration.reset(channels=_DEVEX_WORKSPACE)
+
+ send_daily_digests()
+
+ assert DigestRun.objects.for_team(team.id).get(audience_key="team-devex").slack_channel_id == "C-STANDUP"
+
+
@pytest.mark.parametrize(
"audience_repository,expected_channel",
[("acme/aardvark", "C-STANDUP"), ("acme/widgets", "C-DEVEX")],
diff --git a/products/visual_review/backend/logic/debt_digest.py b/products/visual_review/backend/logic/debt_digest.py
index edbac7879aa8..244318a4fcbf 100644
--- a/products/visual_review/backend/logic/debt_digest.py
+++ b/products/visual_review/backend/logic/debt_digest.py
@@ -53,8 +53,11 @@ from owners_yaml.schema import Producer, TeamEntry
from posthog.comment.formatting import escape_slack_mrkdwn
from posthog.dataclasses import frozen
+from posthog.egress.limiter.policies import Priority
from posthog.models.integration import Integration, SlackIntegration
from posthog.models.user import User
+from posthog.ownership.github_files import fetcher_for_team
+from posthog.ownership.paths import UNOWNED_TEAM, PathOwnership, resolve_path_owners
from posthog.team_notifications.slack import (
MAX_BLOCKS,
MAX_BUTTON_URL_CHARS,
@@ -77,9 +80,6 @@ from posthog.team_notifications.slack import (
)
from posthog.utils import human_list, pluralize
-from products.engineering_analytics.backend.facade.api import resolve_path_owners
-from products.engineering_analytics.backend.facade.contracts import UNOWNED_TEAM, PathOwnership
-
from ..facade.contracts import FLAKINESS_EXPIRY_SOON_DAYS, TOLERATION_PILEUP_WINDOW_DAYS
from ..facade.enums import RunType
from ..models import QuarantinedIdentifier, Repo, Run
@@ -856,7 +856,13 @@ def send_debt_digest(repo: Repo, mode: str) -> list[str]:
logger.info("visual_review.debt_digest_nothing_owed", repo_id=str(repo.id), team_id=repo.team_id)
return []
- ownership = resolve_path_owners(repo.repo_full_name, paths_to_resolve(debt))
+ ownership = resolve_path_owners(
+ repo.repo_full_name,
+ paths_to_resolve(debt),
+ # The digest is scheduled work that nobody waits on, so it sheds first when the
+ # installation's GitHub budget runs hot and sends the same items next week.
+ files=fetcher_for_team(repo.team_id, repo.repo_full_name, priority=Priority.BATCH),
+ )
if not ownership.resolved:
# A blind answer names no team and carries no registry, so every item would read as
# unowned and be dropped. Say so instead, and send the same items next week.
diff --git a/products/visual_review/backend/logic/owners.py b/products/visual_review/backend/logic/owners.py
index 4aa41ac52122..1a3ffc72c231 100644
--- a/products/visual_review/backend/logic/owners.py
+++ b/products/visual_review/backend/logic/owners.py
@@ -4,8 +4,9 @@ from collections.abc import Iterable, Mapping
import structlog
-from products.engineering_analytics.backend.facade.api import resolve_path_owners
-from products.engineering_analytics.backend.facade.contracts import UNOWNED_TEAM
+from posthog.egress.limiter.policies import Priority
+from posthog.ownership.github_files import fetcher_for_team
+from posthog.ownership.paths import UNOWNED_TEAM, resolve_path_owners
from ..facade.enums import RunType
from ..models import Repo, Run
@@ -50,7 +51,12 @@ def owner_teams(
logger.warning("visual_review.owner_teams_too_many_paths", repo_id=str(repo.id), paths=len(paths))
return {}
- ownership = resolve_path_owners(repo.repo_full_name, paths)
+ ownership = resolve_path_owners(
+ repo.repo_full_name,
+ paths,
+ # A person is waiting on the snapshot list, so the reads run on the interactive lane.
+ files=fetcher_for_team(repo.team_id, repo.repo_full_name, priority=Priority.NORMAL),
+ )
if not ownership.resolved:
logger.info("visual_review.owner_teams_unresolved", repo_id=str(repo.id))
return {}
diff --git a/products/visual_review/backend/tests/logic/test_debt_digest.py b/products/visual_review/backend/tests/logic/test_debt_digest.py
index e25210027275..3fad3a11b75c 100644
--- a/products/visual_review/backend/tests/logic/test_debt_digest.py
+++ b/products/visual_review/backend/tests/logic/test_debt_digest.py
@@ -11,6 +11,7 @@ from django.utils import timezone
from owners_yaml.schema import TeamEntry
from posthog.models.team.team import Team
+from posthog.ownership.paths import UNOWNED_TEAM, PathOwnership
from posthog.team_notifications.slack import (
MAX_BLOCKS,
MAX_SECTION_CHARS,
@@ -19,7 +20,6 @@ from posthog.team_notifications.slack import (
SlackPostRefused,
)
-from products.engineering_analytics.backend.facade.contracts import UNOWNED_TEAM, PathOwnership
from products.visual_review.backend.facade.contracts import (
FLAKINESS_EXPIRY_SOON_DAYS,
TOLERATION_PILEUP_WINDOW_DAYS,
diff --git a/products/visual_review/backend/tests/logic/test_owners.py b/products/visual_review/backend/tests/logic/test_owners.py
index a0d1fcdcd95b..1b8b5395c496 100644
--- a/products/visual_review/backend/tests/logic/test_owners.py
+++ b/products/visual_review/backend/tests/logic/test_owners.py
@@ -1,7 +1,8 @@
import pytest
from unittest.mock import MagicMock, patch
-from products.engineering_analytics.backend.facade.contracts import UNOWNED_TEAM, PathOwnership
+from posthog.ownership.paths import UNOWNED_TEAM, PathOwnership
+
from products.visual_review.backend.logic import owners, story_index
from products.visual_review.backend.logic.run_queries import SnapshotKey
@@ -37,11 +38,16 @@ class TestOwnerTeams:
ownership = PathOwnership(
team_by_path={"frontend/src/scenes/Button.stories.tsx": "team-replay"}, registry={}, resolved=resolved
)
+ repo = MagicMock(repo_full_name="org/repo", team_id=7)
with (
patch("products.visual_review.backend.logic.story_index.latest_story_index", return_value=_INDEX),
patch("products.visual_review.backend.logic.owners.resolve_path_owners", return_value=ownership),
+ # The reader reaches the team's integration and the cache, which this test has neither of.
+ patch("products.visual_review.backend.logic.owners.fetcher_for_team") as reader,
patch.object(owners, "_MAX_OWNED_PATHS", max_paths),
):
- result = owners.owner_teams(MagicMock(repo_full_name="org/repo"), [_BUTTON, _CARD, _GONE, _PLAYWRIGHT], {})
+ result = owners.owner_teams(repo, [_BUTTON, _CARD, _GONE, _PLAYWRIGHT], {})
assert result == expected
+ if max_paths > 1:
+ assert reader.call_args.args == (7, "org/repo")
diff --git a/products/warehouse_sources/backend/facade/api.py b/products/warehouse_sources/backend/facade/api.py
index f5ffb408fe9a..b7683c9144ed 100644
--- a/products/warehouse_sources/backend/facade/api.py
+++ b/products/warehouse_sources/backend/facade/api.py
@@ -117,6 +117,7 @@ __all__ = [
# weight off the ``django.setup()`` import path — only the namespaced-resource registry loads them.
_LAZY = {
"github_repositories_for_job_inputs": "github_warehouse_repos",
+ "github_source_credential": "github_warehouse_repos",
"reconcile_github_repositories": "github_warehouse_repos",
}
diff --git a/products/warehouse_sources/backend/facade/contracts.py b/products/warehouse_sources/backend/facade/contracts.py
index b621afaa0b0d..dae771557d40 100644
--- a/products/warehouse_sources/backend/facade/contracts.py
+++ b/products/warehouse_sources/backend/facade/contracts.py
@@ -16,6 +16,7 @@ demand map). The HogQL system-table model classes cross the boundary as objects
``facade/hogql.py``, and temporal/source wiring via ``facade/temporal.py`` — not here.
"""
+from dataclasses import field
from datetime import datetime, time, timedelta
from uuid import UUID
@@ -267,3 +268,16 @@ class DataWarehouseCredential:
id: UUID
team_id: int
created_at: datetime
+
+
+@dataclass(frozen=True)
+class GitHubSourceCredential:
+ """How a GitHub source authenticates to the repositories it syncs.
+
+ Exactly one field is set. This is the one contract that carries a secret, because a consumer
+ that has to read the same repository the source reads cannot do it without the token. ``repr``
+ omits the token so it cannot reach a log line or a traceback frame.
+ """
+
+ integration_id: int | None = None
+ personal_access_token: str | None = field(default=None, repr=False)
diff --git a/products/warehouse_sources/backend/github_warehouse_repos.py b/products/warehouse_sources/backend/github_warehouse_repos.py
index 7276efbac188..7e727b1a2a36 100644
--- a/products/warehouse_sources/backend/github_warehouse_repos.py
+++ b/products/warehouse_sources/backend/github_warehouse_repos.py
@@ -17,6 +17,8 @@ activity self-heals missing rows, and hook drift is surfaced by the webhook stat
from typing import Any, cast
+from django.core.exceptions import ValidationError
+
import structlog
from posthog.exceptions_capture import capture_exception
@@ -24,17 +26,59 @@ from posthog.models import Team
from products.cdp.backend.models.hog_functions.hog_function import HogFunction
from products.data_warehouse.backend.facade.api import get_webhook_url
+from products.warehouse_sources.backend.facade.contracts import GitHubSourceCredential
from products.warehouse_sources.backend.facade.models import (
ExternalDataSchema,
ExternalDataSource,
sync_old_schemas_with_new_schemas,
)
-from products.warehouse_sources.backend.facade.source_management import GithubSource, SourceRegistry
+from products.warehouse_sources.backend.facade.source_management import GithubSource, GithubSourceConfig, SourceRegistry
from products.warehouse_sources.backend.facade.types import ExternalDataSourceType
logger = structlog.get_logger(__name__)
+def github_source_credential(*, team_id: int, source_id: str) -> GitHubSourceCredential | None:
+ """How the team's GitHub source at ``source_id`` authenticates, for a consumer that has to read
+ the same repositories the source syncs.
+
+ The caller names one source, and the team filter keeps a stale or crafted id from reaching
+ another team's source. None covers every case that yields nothing to read with: no such source,
+ a deleted one, a source of another type, a config that does not parse, and a half-configured
+ auth method. A consumer that has no credential falls back on its own, so one answer for all of
+ them keeps that branch out of the consumer.
+ """
+ try:
+ source = (
+ ExternalDataSource.objects.filter(team_id=team_id, id=source_id, source_type=ExternalDataSourceType.GITHUB)
+ .exclude(deleted=True)
+ .first()
+ )
+ except (ValidationError, ValueError):
+ # The id travels from a resolve the caller made, so a value that is no UUID is a normal
+ # answer of "no such source" rather than a failure.
+ return None
+ if source is None:
+ return None
+ # ``job_inputs`` is an ``EncryptedJSONField`` that can hold any JSON value, and a half-written
+ # source is a normal state, so an unreadable config is no reason to fail the consumer.
+ if not isinstance(source.job_inputs, dict):
+ return None
+ try:
+ config = GithubSourceConfig.from_dict(source.job_inputs)
+ except Exception:
+ logger.warning("github_source_credential_config_unreadable", source_id=str(source.pk))
+ return None
+ auth = config.auth_method
+ if auth.selection == "pat":
+ if not auth.personal_access_token:
+ return None
+ return GitHubSourceCredential(personal_access_token=auth.personal_access_token)
+ if auth.github_integration_id is None:
+ return None
+ return GitHubSourceCredential(integration_id=auth.github_integration_id)
+
+
def github_repositories_for_job_inputs(job_inputs: dict[str, Any] | None) -> list[str]:
"""The effective repo list for stored GitHub job_inputs; [] when unparseable or unset."""
source = cast(GithubSource, SourceRegistry.get_source(ExternalDataSourceType.GITHUB))
diff --git a/products/warehouse_sources/backend/tests/test_facade.py b/products/warehouse_sources/backend/tests/test_facade.py
index a577a8baf5c1..915d55352dfc 100644
--- a/products/warehouse_sources/backend/tests/test_facade.py
+++ b/products/warehouse_sources/backend/tests/test_facade.py
@@ -15,6 +15,7 @@ from products.access_control.backend.facade.user_access_control import AccessCon
from products.access_control.backend.models.access_control import AccessControl
from products.data_warehouse.backend.facade.models import ExternalDataSourceRevenueAnalyticsConfig
from products.warehouse_sources.backend.facade import api, contracts, hogql, hooks, sources, temporal
+from products.warehouse_sources.backend.facade.types import ExternalDataSourceType
from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
@@ -333,3 +334,66 @@ def test_wiring_reexports_resolve() -> None:
assert temporal.ACTIVITIES is not None and temporal.WORKFLOWS is not None
assert isinstance(sources.CHARGE_RESOURCE_NAME, str)
assert sources.NamingConvention is not None
+
+
+_PAT_INPUTS = {"auth_method": {"selection": "pat", "personal_access_token": "t0ken"}}
+
+
+class TestGitHubSourceCredential(BaseTest):
+ def _source(self, job_inputs: dict, **overrides) -> ExternalDataSource:
+ return ExternalDataSource.objects.create(
+ team_id=overrides.pop("team_id", self.team.pk),
+ source_id=str(uuid.uuid4()),
+ connection_id=str(uuid.uuid4()),
+ status="Completed",
+ source_type=overrides.pop("source_type", ExternalDataSourceType.GITHUB),
+ job_inputs=job_inputs,
+ **overrides,
+ )
+
+ @parameterized.expand(
+ [
+ ("a_personal_access_token", _PAT_INPUTS, contracts.GitHubSourceCredential(personal_access_token="t0ken")),
+ ("a_pat_selection_with_no_token", {"auth_method": {"selection": "pat"}}, None),
+ (
+ "an_oauth_integration",
+ {"auth_method": {"selection": "oauth", "github_integration_id": 7}},
+ contracts.GitHubSourceCredential(integration_id=7),
+ ),
+ ("an_oauth_selection_with_no_integration", {"auth_method": {"selection": "oauth"}}, None),
+ ("a_config_that_does_not_parse", {"auth_method": "oauth"}, None),
+ ]
+ )
+ def test_the_auth_method_decides_the_credential(
+ self, _name: str, job_inputs: dict, expected: contracts.GitHubSourceCredential | None
+ ) -> None:
+ # A half-configured source is a normal state, and the consumer falls back on no credential,
+ # so every unusable auth method has to answer None rather than raise.
+ source = self._source(job_inputs)
+
+ assert api.github_source_credential(team_id=self.team.pk, source_id=str(source.id)) == expected
+
+ @parameterized.expand(
+ [
+ ("a_deleted_source", {"deleted": True}),
+ ("a_source_of_another_type", {"source_type": "Stripe"}),
+ ]
+ )
+ def test_a_source_that_syncs_no_github_repository_yields_no_credential(self, _name: str, overrides: dict) -> None:
+ source = self._source(_PAT_INPUTS, **overrides)
+
+ assert api.github_source_credential(team_id=self.team.pk, source_id=str(source.id)) is None
+
+ def test_another_teams_source_yields_no_credential(self) -> None:
+ # The id travels from a resolve the caller made, so a stale or crafted value must not hand
+ # a team the credential of a source it cannot see.
+ other_team = Team.objects.create(organization=self.organization, name="other")
+ source = self._source(_PAT_INPUTS)
+
+ assert api.github_source_credential(team_id=other_team.pk, source_id=str(source.id)) is None
+
+ @parameterized.expand([("an_id_that_is_gone", str(uuid.uuid4())), ("an_id_that_is_no_uuid", "not-a-uuid")])
+ def test_an_id_that_names_no_source_yields_no_credential(self, _name: str, source_id: str) -> None:
+ self._source(_PAT_INPUTS)
+
+ assert api.github_source_credential(team_id=self.team.pk, source_id=source_id) is None
diff --git a/tach.toml b/tach.toml
index 356d178e67a8..61b3a2dbbb3d 100644
--- a/tach.toml
+++ b/tach.toml
@@ -834,7 +834,7 @@ depends_on = [
"products.cdp",
"products.conversations",
"products.dashboards",
- # Facade-only: the DRI pick on a self-driving pull request asks which team owns each of its files.
+ # Facade-only: reviewer suggestions read the GitHub team roster to route work at a team slug.
"products.engineering_analytics",
# Facade-only (enforced by data_catalog's [[interfaces]] block): the scout harness gates
# its catalog-first prompt rule on the data catalog flag.
@@ -1053,7 +1053,6 @@ layer = "modules"
path = "products.visual_review"
depends_on = [
"posthog",
- "products.engineering_analytics",
]
layer = "modules"
diff --git a/uv.lock b/uv.lock
index 89a3d47f04cd..571b7c354a91 100644
--- a/uv.lock
+++ b/uv.lock
@@ -5272,7 +5272,7 @@ wheels = [
[[package]]
name = "owners-yaml"
-version = "0.2.0"
+version = "0.2.1"
source = { editable = "packages/owners-yaml" }
dependencies = [
{ name = "click" },