Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,13 @@ responses trigger smaller-page attempts instead of a new retry budget. Gateway
failures at the smallest page size receive up to two additional attempts with
1–2-second and 15-second delays.

Organization team pagination uses team page sizes of 100, 50, and 25 for this
recovery, retaining the failed cursor until a page succeeds. Already emitted
teams are retained, and member pagination beyond the first 100 members continues
independently. An unrecovered team page logs a collection gap with the
organization, cursor, final page size, and emitted team count before collection
continues with the next organization.

After retries are exhausted, existing resource handlers log the failure and
continue with unaffected scopes. Already emitted records are retained, but the
affected scope may be incomplete. Resources that require all pages before
Expand Down
65 changes: 36 additions & 29 deletions src/openhound_github/resources/organization.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,9 @@
)
from openhound_github.helpers import (
_rest_api_url,
AdaptiveGraphQLPageError,
GraphQLCursorPaginator,
adaptive_graphql_paginate,
graphql_repository_batches,
graphql_client_and_path,
scim_skip_reason,
Expand Down Expand Up @@ -821,46 +823,51 @@ def users(ctx: SourceContext) -> Iterator[dict[str, Any]]:

@app.resource(name="teams", columns=Team, parallelized=True)
def teams(ctx: SourceContext):
"""Fetch teams and team member assignments from GitHub GraphQL API.
"""Fetch teams with their first page of immediate members.

Uses the Organization.teams connection with nested IMMEDIATE members to fetch
team info and member-role assignments in a single paginated query. Teams with
more than 100 members are followed up with additional member pagination queries.

Yields team records to the `teams` table and member-role records to the
`team_members` table via dlt.mark.with_table_name().

Args:
ctx (SourceContext): The shared context containing the REST client and organization name.

Yields:
Team (Team): Team record lol!.
Recover gateway failures at the same cursor with smaller team pages. The
team_members transformer handles member overflow independently.
"""

for org in ctx.organizations:
org_name = org.org_name
client, graphql_path = _graphql_client_for_org(ctx, org_name)
emitted_teams = 0
try:
paginator = GraphQLCursorPaginator(
for page_data in adaptive_graphql_paginate(
client,
graphql_path=graphql_path,
query=TEAMS_QUERY,
variables={"login": org_name, "count": 100, "after": None},
page_info_path="data.organization.teams.pageInfo",
cursor_variable="after",
cursor_field="endCursor",
has_next_field="hasNextPage",
)
data = {
"query": TEAMS_QUERY,
"variables": {"login": org_name, "count": 100, "after": None},
}
for page_data in client.paginate(
graphql_path,
method="POST",
json=data,
paginator=paginator,
data_selector="data",
resource_name="teams",
scope_name="organization",
scope_value=org_name,
log=logger,
):
teams_data = page_data[0]["organization"]["teams"]
teams_data = page_data["organization"]["teams"]
for team in teams_data["nodes"]:
emitted_teams += 1
yield {**team, "org_login": org_name}
except AdaptiveGraphQLPageError as e:
logger.error(
"Team collection gap for organization '%s': cursor=%r "
"page_size=%d emitted_teams=%d; remaining teams and their "
"dependent relationships may be incomplete: %s",
org_name,
e.cursor,
e.page_size,
emitted_teams,
e.error,
extra={
"resource": "teams",
"phase": "resource_iteration",
"org_name": org_name,
"cursor": e.cursor,
"page_size": e.page_size,
"emitted_teams": emitted_teams,
},
)
except Exception as e:
logger.error(
f"Error in resource 'teams' processing organization '{org_name}': {e}",
Expand Down
173 changes: 173 additions & 0 deletions tests/test_graphql_retry_budget.py
Original file line number Diff line number Diff line change
Expand Up @@ -420,3 +420,176 @@ def test_session_avoids_dlt_warning_and_preserves_http_errors(
target.get("https://api.github.com/example")
assert caught.value.response.status_code == status
assert len(calls) == expected_attempts


def _team_page(ids, cursor=None):
return {
"data": {
"organization": {
"teams": {
"nodes": [
{
"id": team_id,
"name": team_id,
"slug": team_id.lower(),
"members": {
"edges": [],
"pageInfo": {"hasNextPage": False, "endCursor": None},
},
}
for team_id in ids
],
"pageInfo": {
"hasNextPage": cursor is not None,
"endCursor": cursor,
},
}
}
}
}


def _team_context(client, *org_names):
from openhound_github.resources.organization import OrgContext, SourceContext

return SourceContext(
client=client,
organizations=[OrgContext(client=client, org_name=name) for name in org_names],
)


@pytest.mark.parametrize("gateway", [502, 504])
@pytest.mark.parametrize("later_page", [False, True])
def test_teams_recover_same_cursor_without_replaying_emitted_teams(
monkeypatch, gateway, later_page
):
from openhound_github.resources.organization import teams

prefix = [_team_page(["T_1"], "teams-next")] if later_page else []
client, calls = _client(
monkeypatch,
[
*prefix,
gateway,
gateway,
_team_page(["T_2"], "teams-last"),
_team_page(["T_3"]),
],
)

rows = list(teams.__wrapped__(_team_context(client, "org")))

assert [row["id"] for row in rows] == (["T_1"] if later_page else []) + [
"T_2",
"T_3",
]
assert all(row["org_login"] == "org" for row in rows)
recovery_calls = calls[len(prefix) :]
assert [call["count"] for call in recovery_calls] == [100, 50, 25, 100]
assert [call["after"] for call in recovery_calls] == [
"teams-next" if later_page else None,
] * 3 + ["teams-last"]
assert all(call["login"] == "org" for call in calls)


@pytest.mark.parametrize("later_page", [False, True])
def test_teams_exhaustion_logs_gap_retains_results_and_continues_organizations(
monkeypatch, caplog, later_page
):
from openhound_github.resources.organization import teams

prefix = [_team_page(["T_1"], "teams-next")] if later_page else []
client, calls = _client(monkeypatch, [*prefix, *([502] * 5), _team_page(["T_2"])])

rows = list(teams.__wrapped__(_team_context(client, "broken", "healthy")))

assert [(row["id"], row["org_login"]) for row in rows] == (
([("T_1", "broken")] if later_page else []) + [("T_2", "healthy")]
)
assert len(calls) == len(prefix) + 6
assert [call["count"] for call in calls[len(prefix) : -1]] == [100, 50, 25, 25, 25]
assert calls[-1] == {"login": "healthy", "count": 100, "after": None}
gap = next(
record for record in caplog.records if "Team collection gap" in record.message
)
assert gap.org_name == "broken"
assert gap.cursor == ("teams-next" if later_page else None)
assert gap.page_size == 25
assert gap.emitted_teams == int(later_page)
assert "dependent relationships may be incomplete" in gap.message


@pytest.mark.parametrize(
"failure",
[
401,
{
"data": {
"organization": {
"teams": {
"nodes": [],
"pageInfo": {
"hasNextPage": True,
"endCursor": None,
},
}
}
}
},
{"data": None, "errors": [{"message": "Access denied"}]},
],
)
def test_teams_do_not_retry_non_gateway_errors_as_smaller_pages(
monkeypatch, caplog, failure
):
from openhound_github.resources.organization import teams

client, calls = _client(monkeypatch, [failure, _team_page([])])
assert list(teams.__wrapped__(_team_context(client, "broken", "healthy"))) == []
assert len(calls) == 2
assert [call["count"] for call in calls] == [100, 100]
assert "Team collection gap" in caplog.text


def test_recovered_team_keeps_all_immediate_members_and_member_overflow(monkeypatch):
from openhound_github.models import Team
from openhound_github.resources.organization import team_members, teams

def member(index):
return {
"role": "MAINTAINER" if index == 0 else "MEMBER",
"node": {"id": f"U_{index}", "login": f"user{index}"},
}

page = _team_page(["T_1"])
page["data"]["organization"]["teams"]["nodes"][0]["members"] = {
"edges": [member(i) for i in range(100)],
"pageInfo": {"hasNextPage": True, "endCursor": "member-next"},
}
overflow = {
"data": {
"organization": {
"team": {
"members": {
"edges": [member(100)],
"pageInfo": {"hasNextPage": False, "endCursor": None},
}
}
}
}
}
client, calls = _client(monkeypatch, [502, page, overflow])
ctx = _team_context(client, "org")
team_rows = list(teams.__wrapped__(ctx))
rows = list(team_members.__wrapped__(Team.model_validate(team_rows[0]), ctx))

assert [row["id"] for row in rows] == [f"U_{i}" for i in range(101)]
assert all(row["team_id"] == "T_1" and row["org_login"] == "org" for row in rows)
assert rows[0]["role"] == "MAINTAINER"
assert rows[-1]["role"] == "MEMBER"
assert calls[-1] == {
"login": "org",
"count": 100,
"after": "member-next",
"slug": "t_1",
}