Repository navigation
feat(ingest/looker): add opt-in "View in Git" links to Explores - #21514
aviraj-gour wants to merge 17 commits into
Conversation
Add an emit_explore_git_links option to the looker source. When enabled, each Explore gets a "View in GitHub" link pinned to its header that opens the LookML file defining it. The file path comes from the explore's lookml_link, and the repository and production branch come from the Looker project API, so the recipe needs no Git settings. SSH and HTTPS remotes on github.com and gitlab.com are supported; credentials and ports are dropped from the remote before use. The link is written as an institutionalMemory patch keyed on its label, so links added in the UI are kept and a changed URL replaces the old link in place. Projects the API key cannot read, projects without a remote and unsupported hosts are reported as warnings once per project.
…lore links GitLab remotes are supported too, and the label is the key the link is matched on, so it is settled before release to avoid orphaned links.
…g on label Each Explore keeps one current ingestion-written "View in Git" link. The source reads the Explore's existing links from DataHub and treats a link as its own only when it has the label and the fixed ingestion creation stamp, so links added by hand are never changed. When the URL changes, the old link is removed and the new one added in one patch keyed on url and label; when it is unchanged nothing is written. Without a DataHub connection links are added only, and the report notes it once. Git remotes are parsed strictly: anything that is not a scheme://host/owner/repo or user@host:owner/repo remote is reported as malformed instead of being guessed into a GitHub URL.
- Rename the option to extract_explore_git_links; emit_* options in this connector filter which entities are emitted. - Leave any existing link at the same url and label alone, including one added by hand, instead of replacing it. - Stamp ingestion-written links with the SDK's ingestion actor (urn:li:corpuser:__ingestion) rather than the admin user. - URL-encode the file path when building the link. - Lowercase the host of user@host:path remotes. - Note the extra DataHub read per Explore in the docs.
Every "View in Git" link on an Explore is now managed by the option: links with that label and another URL are removed, and the current one is added if missing. The creation-stamp check is dropped, so the stamp written on links is no longer part of their identity; the label is, and must not change.
- Assert each link patch is written to its own Explore and that existing links are read for that Explore. - Cover two Explores in different projects getting their own repo URL, with one project lookup each. - Read existing links as a set of URLs, which is all the caller uses. - Say that skipped Explores keep links written by earlier runs, in the warnings and the docs.
A production branch containing '#' or '%' (e.g. hotfix#12) produced a link the browser truncated at the fragment. Encode it like the file path, keeping '/' so branches such as release/2026 stay readable.
…eal time - Parse lookml_link by its /projects/<project>/files/<path> layout, so a project or repo folder named "files" is not taken for the marker. - Stamp new Explore Git links with the current time instead of the epoch; identity is the label, so the fixed time served no purpose and showed as 1970 in the UI. - Note in the url+label link helpers that they key links differently from add_institutional_memory.
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
A failed read of an Explore's existing links raised out of the Explore loop and ended Explore ingestion and every later stage. Now nothing is written for that Explore, since its links are unknown, and the rest of ingestion carries on: - A 4xx about one Explore (e.g. 403 on a restricted entity) skips only that Explore's link. - Connection errors, timeouts, 5xx after the graph session's retries, malformed responses, 401 and 429 stop link reads and writes for the rest of the run, with one warning.
Connector Tests ResultsAll connector tests passed for commit To skip connector tests, add the Autogenerated by the connector-tests CI pipeline. |
PR SummaryOverview When enabled, the source decodes the repo-relative path from each Explore’s Supporting changes include remote/path parsers, Reviewed by Cursor Bugbot for commit 815e9dc. Bugbot is set up for automated code reviews on this repo. Configure here. |
naeemdh
left a comment
There was a problem hiding this comment.
Nice feature, and the URL-plus-label patch keys keep other links safe. One thing I'd fix before merge (error handling in the link read) and three smaller notes inline.
| return set() | ||
| try: | ||
| memory = self.ctx.graph.get_aspect(explore_urn, InstitutionalMemoryClass) | ||
| except (requests.RequestException, GraphError) as e: |
There was a problem hiding this comment.
Two issues with this handler:
get_aspectraisesGraphErrorwhen the response for this entity has no aspect payload. That's a per-entity problem, but it falls through to the run-wide branch below and sets_git_link_read_failed, so one odd Explore turns off links for the rest of the run.- Errors from
aspect_type.from_obj(...)while decoding the aspect are neitherRequestExceptionnorGraphError, so they escape the generator and fail the whole Looker source.
Could GraphError (and a broad except Exception) skip just this Explore with a warning, and keep the run-wide stop for connection errors / 5xx / 401 / 429 only?
There was a problem hiding this comment.
I checked both against a running GMS.
-
A missing aspect returns 404 in every case I tried (Explore without links, nonexistent URN, entity type without the aspect, unknown entity type), and
get_aspectturns 404 intoNone, so it doesn't raise.GraphErroronly fires on a 200 without theInstitutionalMemorykey. That key is the same for every Explore, so a 200 without it means the response itself is wrong (a proxy, a version mismatch) and every read would fail the same way. Stopping for the run is intended there. -
GMS rejects aspects missing required fields or with invalid URLs (422) and drops unknown fields on write, so what it returns decodes. A decode failure would mean a client/server model mismatch, which again hits every Explore. I'd rather not add a broad
except Exceptionfor a case that can't be per-entity.
| EXPLORE_GIT_LINK_LABEL = "View in Git" | ||
| # Reading an Explore's links failed with a bad token (401) or throttling (429): it would | ||
| # fail for every Explore, so link reads stop for the run instead of skipping one Explore. | ||
| EXPLORE_GIT_LINK_RUN_WIDE_HTTP_STATUSES = frozenset({401, 429}) |
There was a problem hiding this comment.
nit: 403 behaves run-wide in practice too. A DataHub token without dataset read privilege gets 403 on every Explore, so a big instance makes one failing read and adds one warning context per Explore. Consider adding 403 here, or stopping after a few consecutive 403s.
There was a problem hiding this comment.
The aspect GET checks READ against the specific URN (AspectResource → isAPIAuthorizedEntityUrns(..., List.of(urn))), and policy resource filters can match on the entity's URN, tag, domain, container, owner or platform instance, so a 403 can be about one Explore. Making it run-wide would let one restricted Explore turn off links for all the others. When the token is denied everywhere, the report still shows a single warning entry (contexts are a capped LossyList), and 403s aren't retried, so each read fails fast.
| self.source_config.extract_explore_git_links | ||
| and result.looker_explore | ||
| ): | ||
| yield from self._make_explore_git_link( |
There was a problem hiding this comment.
nit: this puts a blocking GMS read per Explore on the thread that drains the executor, so the parallel Explore fetches end up waiting behind serial get_aspect calls. Only the project cache needs the main thread; the get_aspect read could move into fetch_one_explore (or be batched).
There was a problem hiding this comment.
Good catch, moved it in 0897194: the get_aspect read now happens in fetch_one_explore on the worker threads and comes back in ExploreFetchResult, so reads run in parallel with the Explore fetches. The project lookup and patch building stay on the main thread, so the project cache still needs no lock. Added a test that fails if the read lands on the main thread again.
There was a problem hiding this comment.
Update: I dropped the main-thread test in 815e9dc. Which thread makes the read is a performance choice, not behaviour. The read still runs in fetch_one_explore.
| url=url, | ||
| description=EXPLORE_GIT_LINK_LABEL, | ||
| createStamp=AuditStampClass( | ||
| time=int(time.time() * 1000), actor=DEFAULT_ACTOR_URN |
There was a problem hiding this comment.
nit: without a DataHub connection, every run re-sends this add for every Explore with a fresh createStamp, so the link always looks newly created and each run writes a new institutionalMemory version per Explore. Maybe worth a note in the docs, or a stable stamp in add-only mode.
There was a problem hiding this comment.
That's the trade-off of add-only mode: without a connection we can't tell the link is already there. A fixed stamp would make the link show as created in 1970, which an earlier review flagged, so I kept the real time. The run already reports that it's add-only, and the docs say links are only added without a connection. Add-only is the fallback; recipes with the DataHub sink get the read and write nothing when the link is unchanged.
The per-Explore read of existing institutionalMemory ran on the thread that drains the Explore executor, so with a remote GMS the serial reads throttled the parallel Explore fetches. Do the read in fetch_one_explore and pass the result back; the project lookup and patch building stay on the main thread, so the project cache still needs no lock.
naeemdh
left a comment
There was a problem hiding this comment.
Nice feature: reading links on the worker threads and keying the patch on url + label works well. A few non-blocking notes inline.
| and explore_dataset_entity is not None | ||
| and looker_explore is not None | ||
| and not self._git_link_read_failed | ||
| and self._git_link_path(looker_explore) is not None |
There was a problem hiding this comment.
When an Explore stops qualifying for a link (it moves into an imported project, or lookml_link comes back empty), this check skips it completely, so the managed "View in Git" link it already has is never removed and keeps pointing at a file that no longer defines it. Could we still read the labelled links when the path is None and remove them? If that's out of scope, it would help to say in looker_post.md that existing links are kept in this case.
There was a problem hiding this comment.
Keeping the link here is deliberate. It matches how the source treats every other case where it can't tell where the file lives (project unreadable, no remote or an unsupported one): existing links are left alone. Removing it would also mean a GMS read for every Explore without a path, and a lookml_link that comes back empty once would delete the link and re-add it on the next run. Added a sentence to looker_post.md in 4b41156 saying such Explores keep their existing link.
| and e.response is not None | ||
| and 400 <= e.response.status_code < 500 | ||
| and e.response.status_code | ||
| not in EXPLORE_GIT_LINK_RUN_WIDE_HTTP_STATUSES |
There was a problem hiding this comment.
A 403 is handled as a problem with one Explore, but a token without read access to datasets gets a 403 on every Explore: one failed GMS call and one warning per Explore, and no links. Should 403 be in EXPLORE_GIT_LINK_RUN_WIDE_HTTP_STATUSES, or should we stop after a few consecutive 403s?
There was a problem hiding this comment.
Same reasoning as the earlier thread: the aspect GET checks READ against the specific URN, and policies can restrict single Explores, so a run-wide stop would drop links on Explores the token can read. Stopping after N consecutive 403s has the same problem when the first few Explores happen to be restricted. A token denied everywhere still produces one report entry (contexts are grouped under the title and capped), and 403s aren't retried, so each read fails fast.
| ) | ||
| return None | ||
| # Outage-type error: the graph session has already retried, so later reads would fail too. | ||
| self._git_link_read_failed = True |
There was a problem hiding this comment.
With max_threads > 1, every worker that passed the not self._git_link_read_failed check before this flag is set still calls GMS and adds its own "Failed to read existing Explore links" warning, so an outage can produce up to max_threads copies. test_failed_link_read_skips_links_for_the_rest_of_the_run doesn't catch this because the fixture uses max_threads=1. A lock or check-and-set around the flag and the warning would make the "only once" behaviour hold.
There was a problem hiding this comment.
Warnings with the same title and message are grouped into one report entry, so the worst case is up to max_threads extra contexts in that entry rather than separate warnings. The reads already in flight when GMS goes down would still be made with a lock around the flag, so a lock only trims those contexts. I'd leave it as is.
| # Needs at least owner/repo; never fall back to guessing a host. | ||
| if not host or "/" not in repo_path: | ||
| return None | ||
| return f"https://{host}/{repo_path}" |
There was a problem hiding this comment.
The host is copied as-is, so real GitHub/GitLab remotes on alternate hosts are rejected by GitReference as unsupported: ssh://git@ssh.github.com:443/org/repo.git (GitHub's SSH-over-443), altssh.gitlab.com, www.github.com. Could we map those to github.com and gitlab.com here?
There was a problem hiding this comment.
Done in 4b41156: ssh.github.com, www.github.com and altssh.gitlab.com now map to github.com / gitlab.com, with test cases.
| # LookML IDE link path: /projects/<project>/files/<url-encoded repo path> | ||
| LOOKML_LINK_PATH_PATTERN = re.compile(r"^/projects/[^/]+/files/(.+)$") | ||
| # SCP-style SSH remotes like git@github.com:org/repo.git | ||
| GIT_SCP_REMOTE_PATTERN = re.compile(r"^[^@/]+@([^:/]+):(.+)$") |
There was a problem hiding this comment.
Nit: git also accepts SCP remotes without a user (github.com:org/repo.git), which this pattern reports as malformed. ^(?:[^@/]+@)?([^:/]+):(.+)$ would accept them, and the owner/repo check later still applies.
There was a problem hiding this comment.
Done in 4b41156, with one change to the suggested pattern: ^(?:[^@/]+@)?([^:/@]+):([^@]+)$. With ([^:/]+):(.+), a credential remote missing its scheme (user:token@github.com/org/repo) parses with user as the host and the token in the path, and the "Unsupported Git host" warning then echoes it. Excluding @ after the optional user keeps that case malformed; GitHub and GitLab repo paths can't contain @. Added test cases for the user-less form and for the credential case.
Explore Git links now resolve SCP remotes without a user (github.com:org/repo.git) and map ssh.github.com, www.github.com and altssh.gitlab.com to their web hosts. The SCP pattern rejects "@" after the optional user, so a schemeless credential remote (user:token@github.com/org/repo) stays malformed and is never echoed in the unsupported-host warning. Document that Explores which move into an imported project or lose their LookML file keep their existing link.
naeemdh
left a comment
There was a problem hiding this comment.
Nice feature. Remote credential stripping and the (url, label) keyed patch both look good. A few comments, mostly on error handling when reading existing links: the first two (uncaught deserialize error, run-wide disable on a single GraphError) seem worth fixing before merge; the rest are nits.
| if self.ctx.graph is None: | ||
| return set() | ||
| try: | ||
| memory = self.ctx.graph.get_aspect(explore_urn, InstitutionalMemoryClass) |
There was a problem hiding this comment.
Uncaught deserialize error can abort the whole run. Only requests.RequestException and GraphError are caught here, but get_aspect also runs aspect_type.from_obj(...), which can raise other errors (Avro/ValueError-type) on a malformed stored aspect. That escapes fetch_one_explore on the worker and future.result() re-raises it in _make_explore_containers, stopping explore ingestion for every remaining Explore. Suggest catching Exception for the per-Explore path (warn, return None) so only that Explore is skipped.
There was a problem hiding this comment.
Agreed. Optional links shouldn't stop Explore ingestion. Any failed read now warns and skips only that Explore's link, the same way qlik_sense, sac and dbt handle per-entity DataHub reads. test_failed_link_read_skips_only_that_explore covers a decode error alongside a connection error, a 5xx and a 403.
There was a problem hiding this comment.
Update: in 815e9dc I cut the test to a connection error and a decode error. 5xx and 403 go through the same except, so they added nothing.
| ) | ||
| return None | ||
| # Outage-type error: the graph session has already retried, so later reads would fail too. | ||
| self._git_link_read_failed = True |
There was a problem hiding this comment.
A single bad response disables links run-wide. Any GraphError lands in this outage branch, including get_aspect's "Failed to find ... in response" for one URN whose response lacks the aspect body. That's about one Explore, not GMS health. Suggest keeping the run-wide flag for connection errors, 5xx, 401 and 429, and treating other GraphErrors as per-Explore.
There was a problem hiding this comment.
Done. The run-wide stop is removed, so a bad response now affects only its own Explore. A DataHub outage is already caught by the pipeline's connection check at start, or by the sink, so the source doesn't need its own.
| self.source_config.extract_explore_git_links | ||
| and explore_dataset_entity is not None | ||
| and looker_explore is not None | ||
| and not self._git_link_read_failed |
There was a problem hiding this comment.
Run-wide flag is racy across workers. _git_link_read_failed is read and set by parallel fetch_one_explore workers with no lock, so during an outage every in-flight worker makes its own GMS read (with the session's retries) and logs its own "Failed to read existing Explore links" warning. The unit tests use max_threads: 1, so they don't catch this. A lock or threading.Event around the check-and-set would make "skip for the rest of the run" hold. (nit)
There was a problem hiding this comment.
Gone with the previous one. There's no shared flag any more.
| and explore_dataset_entity is not None | ||
| and looker_explore is not None | ||
| and not self._git_link_read_failed | ||
| and self._git_link_path(looker_explore) is not None |
There was a problem hiding this comment.
GMS read happens before checking that a link can be built. For projects with no remote, an unreadable config or an unsupported host, each Explore still costs one GMS read per run, and the result is then discarded when _get_project_git_ref returns None. Consider resolving or checking the cached project ref first and skipping the read when it's None. (nit)
There was a problem hiding this comment.
Done in c0b34fb. fetch_one_explore now checks the project cache before reading and skips the read when the project is already known to have no usable remote. Worker threads only read the cache: project lookups and their warnings stay on the main thread, so no lock is needed. Explores fetched before their project is first looked up still read, which is at most about 2 × max_threads per project given the executor's limit on fetches in flight. Covered by test_no_link_read_once_project_is_known_unusable.
There was a problem hiding this comment.
Update: I removed test_no_link_read_once_project_is_known_unusable in 815e9dc, because it set a private attribute and only guarded an optimisation. The skip itself is unchanged.
|
|
||
| def _existing_git_link_urls(self, explore_urn: str) -> Optional[Set[str]]: | ||
| """None when the read fails: links are then left unknown, so nothing is written.""" | ||
| if self.ctx.graph is None: |
There was a problem hiding this comment.
Without a graph, every run rewrites the link. Returning an empty set means url not in existing_urls is always true, so each run sends an add keyed on (url, label). That replaces a hand-made link at the same URL and label and resets its createStamp to the ingestion actor and the current time, which the with-graph path deliberately avoids (test_hand_made_link_at_same_url_and_label_is_not_overwritten). Worth at least mentioning in the add-only info message and the docs. (nit)
There was a problem hiding this comment.
Same trade-off as round 1: without a connection we can't see the existing link, so add-only is the fallback and the run reports that once. It can replace a hand-added link with the same URL and label; the docs already say to use another label for your own links. Recipes with the DataHub sink do the read and write nothing when the link is unchanged.
| USER_STAMP = AuditStampClass(time=1700000000000, actor="urn:li:corpuser:jdoe") | ||
|
|
||
|
|
||
| def client_with(lookml_link: Optional[str], project: Optional[Project] = None) -> Any: |
There was a problem hiding this comment.
nit: metadata-ingestion/AGENTS.md says to avoid Any. Here and in fields/transport_options, aspect_type and project_response, more specific types such as mock.MagicMock, Union[Project, Exception] and Type[InstitutionalMemoryClass] would work.
There was a problem hiding this comment.
Done: MagicMock, Optional[str] / Optional[TransportOptions], Type[InstitutionalMemoryClass] and Union[Project, Exception]. Any stays only on the json.loads patch payloads in link_patches and ops.
Any error reading an Explore's existing links, including an unexpected one such as a decode failure, now warns and skips only that Explore's link instead of stopping links for the rest of the run or ending Explore ingestion. This matches how other sources handle per-entity DataHub reads; an outage is already caught by the pipeline's connection check or the sink. Also replaces Any with specific types in the Explore Git link tests.
fetch_one_explore now decides whether an Explore gets a Git link and passes the project, file path and existing links back as one ExploreGitLink, so the main thread no longer repeats the path and project checks before building the patch. Tests that leave links alone (unusable project remote, imported project, no LookML file) now start with an existing link, so they fail if a stale-link removal is sent in those cases. Adds a direct test of the url-and-label institutionalMemory patch helpers, drops a test that duplicated test_same_url_writes_nothing, and trims comments.
…mote fetch_one_explore now checks the project cache before reading an Explore's existing links and skips the read when the project is already known to have no usable Git remote, since no link is written for it anyway. Worker threads only read the cache; the main thread still does every project lookup and its warning, so no lock is needed. Explores fetched before their project is first looked up still read.
An Explore whose lookml_link is missing or unparsable got no Git link and nothing in the report. It now adds one aggregated info entry per run. Also trims the Explore Git links docs and drops comments that restated the code.
…k docs Restores the documented guarantee that an Explore keeps its existing link when its project is unusable, it moves into an imported project, or it loses its LookML file. Drops a duplicate test, two tests of implementation details, redundant parameters and a no-op mock setup; merges the URL encoding tests; checks the add-only note is absent with the flag off.
Summary
Looker Views ingested by the
lookmlsource already link to their LookML file in Git, but Explores have no way to get there: the Looker API'ssource_fileis only the file name, and thelookersource has no repository settings. This PR adds an opt-in option to thelookersource that puts a View in Git button on each Explore, pointing at the LookML file that defines it.Before / after
Before: the Explore header only links to Looker.
After (
extract_explore_git_links: true): View in Git is the header button and opens the LookML file on GitHub; View in Looker is still there under View more.How the link is built
lookml_link(/projects/<project>/files/<url-encoded path>?line=N), which carries the repo-relative path, including Explores defined in.view.lkmlfiles.git_remote_url,git_production_branch_name), once per project and cached, so the recipe needs no Git settings.scheme://host/owner/repoanduser@host:owner/reporemotes are accepted. Credentials and port are dropped, the host is lowercased, and the result goes throughGitReference, the same helper thelookmlsource uses for Views (github.com and gitlab.com). A host is never guessed./.How the link is written
institutionalMemoryentry labelledView in GitwithshowInAssetPreview: true, so it shows as a header button next to "View in Looker".View in Git. It sends one PATCH keyed by url + label that removes non-current URLs and adds the current one. Nothing is written when the link is already correct, and links with other labels are never touched.HasInstitutionalMemoryPatch:add_institutional_memory_by_url_and_labelandremove_institutional_memory_by_url_and_label.When a link can't be built
lookml_link(e.g. Looker's built-insystem__activity) or defined in an imported project are skipped.Testing
tests/unit/looker/test_looker_explore_git_links.pyrun the real source against a fake Looker client. They cover first add, unchanged run, URL change, remove-only, hand-made and other-label links, no DataHub connection, every project failure path, path and branch encoding, multiple projects, and remote parsing.Checklist
looker_post.md)🤖 Generated with Claude Code
Summary by cubic
Adds an opt-in
extract_explore_git_linksoption to thelookersource that puts a View in Git button on each Explore, linking to the LookML file that defines it. The repository and production branch come from the Explore's Looker project, so the recipe needs no Git settings.lookml_link, anchored on its/projects/<project>/files/<path>layout; the repo and branch come from the Looker project API, cached per project.github.com:org/repo.git) and alternate hosts (ssh.github.com,www.github.com,altssh.gitlab.com); malformed or unsupported remotes produce one warning per project and leave existing links unchanged.lookml_linkis reported once per run.add_institutional_memory_by_url_and_labelandremove_institutional_memory_by_url_and_labelhelpers toHasInstitutionalMemoryPatch.Written for commit 815e9dc. Summary will update on new commits.