onetaskgraph-github-projects 0.17.5

A onetaskgraph source over GitHub Projects.
Documentation
//! Every document this source sends, held below GitHub's per-query node limit.
//!
//! No network, no credential and no schema: the count is arithmetic over the document's
//! own text, so this runs in the ordinary check on a pull request from a fork.
//!
//! The number is `nodeCount`, the most nodes **one query may return**, which GitHub checks
//! per query and refuses a document above before executing it. It is not `cost`, the
//! rate-limit points a call spends against an hourly allowance: that is the sibling file
//! `tests/point_cost.rs`, which pins every document's price rather than holding one under a
//! limit, there being no per-call point limit to hold it under.

use onetaskgraph_github_projects::{NODE_COUNT_LIMIT, graphql, worst_case_node_count};

/// What this source's own text says about `document`, or the failure it is.
///
/// One place the verdict is spelled, so the inventory sweep below and the discrimination
/// case beneath it are the same check over different documents rather than two checks
/// that could come to differ. The message names the document and the count it computed,
/// because a reader who has just added a connection needs to know which document grew and
/// by how much — the limit alone says neither.
fn over_limit(doing: &str, document: &str) -> Option<String> {
    let count = worst_case_node_count(document)
        .unwrap_or_else(|error| panic!("the document for {doing} could not be counted: {error}"));
    (count >= NODE_COUNT_LIMIT).then(|| {
        format!(
            "the document for {doing} may return {count} nodes, at or above GitHub's limit \
             of {NODE_COUNT_LIMIT}; next: give one of its connections a smaller page size, \
             or stop selecting it"
        )
    })
}

/// Every document, from the inventory rather than from a list written out here.
///
/// Reading [`graphql::DOCUMENTS`] is what makes this cover a document nobody thought
/// about: `documents_are_all_inventoried` already fails when a `pub const` there is left
/// out of that list, so a connection added later to a shared fragment is counted here
/// without this test being edited to know about it.
#[test]
fn every_document_this_source_sends_stays_under_githubs_node_limit() {
    let refused = graphql::DOCUMENTS
        .iter()
        .filter_map(|(document, doing)| over_limit(doing, document))
        .collect::<Vec<_>>();
    assert!(refused.is_empty(), "{}", refused.join("\n"));
}

/// The three documents that share the board-issue fragment, with the headroom each has.
///
/// The sweep above says only that nothing crossed. This says where each of them sits, so a
/// change that quadruples a count while staying under the limit is visible as a number
/// moving rather than as a test still passing. The figures are recomputed here from the
/// production text, never restated from the documentation.
///
/// The recovery read is pinned beside them although it reaches one issue rather than a
/// page of them: it is the document that walks an issue's board memberships at the full
/// page size, so it is where the cost of making a missed membership recoverable sits, and
/// a change to that trade shows up here as this number moving.
#[test]
fn the_documents_that_reach_an_issue_under_a_page_are_the_ones_with_least_headroom() {
    let count = |document: &str| worst_case_node_count(document).expect("a countable document");
    assert_eq!(count(graphql::SEARCH_ISSUES), 20_400);
    // The search's count, plus a page of `$nestedFirst` blockers under each of its hundred
    // issues: what lets a project's tasks answer their own forward edges.
    // And the project issue itself, with its own page of blockers: what lets the read of the
    // project that follows its tasks' be answered by this one.
    // Paged at `MEMBER_PAGE_SIZE` rather than a hundred, so twenty-three sub-issues carry it.
    // llmlint: ignore[tests_hold_no_nonfunctional_thresholds] This figure is not a threshold but the instrument this test exists to be, as its own documentation says: the worst-case count recomputed from the production text, pinned so a change to a document is a number a reviewer sees move. This change moved it deliberately, and `session-cost.md` says why.
    assert_eq!(count(graphql::SUB_ISSUES), 6_095);
    assert_eq!(count(graphql::BOARD), 10_150);
    assert_eq!(count(graphql::ISSUE_BOARD_ITEMS), 5_100);
    // One issue with its board half, the field definitions of the boards it sits on and the
    // far ends of its `blockedBy`: what a write of it needs, read with it.
    assert_eq!(count(graphql::ISSUE), 456);
    // The item and its first page of comments, and a batch of those, one per alias.
    assert_eq!(count(graphql::ISSUE_DETAIL), 303);
    assert_eq!(
        count(graphql::ISSUE_DETAILS),
        303 * onetaskgraph_github_projects::DETAIL_BATCH as u64
    );
    assert_eq!(count(graphql::ISSUE_DEPENDENCIES), 200);
    // A task's comments hang off one issue rather than off a page of them, so nothing
    // multiplies through the read and its whole count is the page GitHub is asked for.
    assert_eq!(count(graphql::ISSUE_COMMENTS), 100);
    assert_eq!(count(graphql::COMMENT_ISSUE), 0);
    assert_eq!(count(graphql::REPOSITORY), 0);
    // The batched search at the largest round a find sends — every one of its twenty search
    // slots and five origin slots asking a whole page of a hundred — and no connection under a
    // row: a slot's count is its page, never its page times what each row carries.
    assert_eq!(
        count(graphql::SEARCH_BATCH),
        u64::from(onetaskgraph_github_projects::MAX_PAGE_SIZE)
            * (onetaskgraph_github_projects::SEARCH_BATCH
                + onetaskgraph_github_projects::SEARCH_BATCH_ORIGINS) as u64
    );
}

/// Every connection — a field paged by `first` or `last` — that one row of a batched search's
/// slots selects, by the path it is at, or the fragment spread that could hide one.
///
/// GitHub prices a connection under a page once per row asked, so a search slot selecting one
/// costs a round more with every row it asks; the batched search reads which issues match and
/// nothing beneath them, and this is what says so of the document as written.
fn connections_under_a_row(document: &str) -> Vec<String> {
    use graphql_parser::query::{Definition, OperationDefinition, Selection};
    fn walk(selections: &[Selection<'_, String>], path: &str, found: &mut Vec<String>) {
        for selection in selections {
            match selection {
                Selection::Field(field) => {
                    let here = format!("{path}/{}", field.name);
                    if field
                        .arguments
                        .iter()
                        .any(|(name, _)| name == "first" || name == "last")
                    {
                        found.push(here.clone());
                    }
                    walk(&field.selection_set.items, &here, found);
                }
                Selection::InlineFragment(fragment) => {
                    walk(&fragment.selection_set.items, path, found);
                }
                Selection::FragmentSpread(spread) => {
                    found.push(format!("{path}/...{}", spread.fragment_name));
                }
            }
        }
    }
    /// The selections one row of `field`'s connection holds: its `nodes`, however deep the
    /// connection sits under the slot's root field.
    fn rows<'a>(
        selections: &'a [Selection<'a, String>],
        found: &mut Vec<&'a [Selection<'a, String>]>,
    ) {
        for selection in selections {
            match selection {
                Selection::Field(field) if field.name == "nodes" => {
                    found.push(&field.selection_set.items);
                }
                Selection::Field(field) => rows(&field.selection_set.items, found),
                Selection::InlineFragment(fragment) => rows(&fragment.selection_set.items, found),
                Selection::FragmentSpread(_) => {}
            }
        }
    }
    let parsed = graphql_parser::parse_query::<String>(document).expect("a document");
    let mut found = Vec::new();
    for definition in &parsed.definitions {
        let Definition::Operation(OperationDefinition::Query(query)) = definition else {
            continue;
        };
        for selection in &query.selection_set.items {
            let Selection::Field(slot) = selection else {
                continue;
            };
            let Some(alias) = &slot.alias else {
                continue;
            };
            let mut held = Vec::new();
            rows(&slot.selection_set.items, &mut held);
            assert!(!held.is_empty(), "the slot {alias} reads no rows");
            for row in held {
                walk(row, alias, &mut found);
            }
        }
    }
    found
}

/// The batched search's slots read which issues match — each row's scalar fields alone — and
/// select no connection GitHub prices per row asked: not a hit's `labels`, not its
/// `projectItems` and their `fieldValues`, not any other.
#[test]
fn a_batched_search_slot_selects_no_connection_priced_per_row() {
    assert_eq!(
        connections_under_a_row(graphql::SEARCH_BATCH),
        Vec::<String>::new()
    );
}

/// The check above names a connection a search slot's row selects again — through the shared
/// issue fragment or written out — which is what makes it evidence rather than a pass over any
/// document at all.
#[test]
fn the_row_check_names_a_connection_a_search_slot_selects_again() {
    let fragment = graphql::SEARCH_BATCH.replacen(
        "nodes{__typename ... on Issue{id number",
        "nodes{__typename ...BoardIssue ... on Issue{id number",
        1,
    ) + " fragment BoardIssue on Issue{id}";
    assert_eq!(connections_under_a_row(&fragment), ["s0/...BoardIssue"]);
    let labels = graphql::SEARCH_BATCH.replacen(
        "repository{nameWithOwner}}}}",
        "repository{nameWithOwner} labels(first:50){nodes{id}}}}}",
        1,
    );
    assert_eq!(connections_under_a_row(&labels), ["s0/labels"]);
    let field_values = graphql::SEARCH_BATCH.replacen(
        "content{__typename ... on Issue{id}}",
        "content{__typename ... on Issue{id}} fieldValues(first:50){nodes{__typename}}",
        1,
    );
    assert_eq!(connections_under_a_row(&field_values), ["o0/fieldValues"]);
}

/// The board-issue fragment as it stood before the innermost label connection came out.
///
/// Kept verbatim rather than described: this is the document GitHub refused with *"by the
/// time this query traverses to the labels connection, it is requesting up to 2,500,000
/// possible nodes which exceeds the maximum limit of 500,000"*, and it is what makes the
/// check above evidence rather than an assertion nobody has watched fail.
///
/// **GitHub's figures were for this text under a `BOARD_ITEMS_PAGE_SIZE` of ten**, where
/// the innermost path alone is the 2,500,000 it quoted and the whole document 2,556,100.
/// The check counts it under the page sizes this source binds *today*, which is what makes
/// it a drive of the real verdict rather than of a second calculation, so the numbers
/// below are that same text at a membership page of three: 750,000 down the innermost path
/// and 770,400 over the whole document. Both properties GitHub's message demonstrates
/// survive the smaller page — the document is refused, and the count is the sum rather than
/// the deepest path.
const SEARCH_ISSUES_BEFORE_THE_FIX: &str = r#"query($search:String!,$type:SearchType!,$first:Int!,$after:String,$nestedFirst:Int!,$boardItems:Int!,$duplicates:Boolean!){
      search(query:$search,type:$type,first:$first,after:$after){
        pageInfo{hasNextPage endCursor}
        nodes{__typename ...BoardIssue}
      }
    } fragment BoardIssue on Issue{__typename id title body url createdAt updatedAt state stateReason(enableDuplicate:$duplicates) repository{nameWithOwner} parent{id} subIssuesSummary{total}
      labels(first:$nestedFirst){nodes{id name color}pageInfo{hasNextPage}}
      projectItems(first:$boardItems){nodes{id project{number}
        fieldValues(first:$nestedFirst){nodes{
          ... on ProjectV2ItemFieldSingleSelectValue{name field{
            ... on ProjectV2SingleSelectField{id name options{id name}}
          }}
          ... on ProjectV2ItemFieldTextValue{text field{... on ProjectV2Field{id name}}}
          ... on ProjectV2ItemFieldLabelValue{labels(first:$nestedFirst){nodes{id name color}pageInfo{hasNextPage}}}
        }pageInfo{hasNextPage}}}pageInfo{hasNextPage}}}"#;

/// The check refuses an over-limit document, naming it and the count it computed.
///
/// Without this the sweep above could pass over any tree at all — including one where the
/// calculation had been wired up to return zero.
#[test]
fn the_check_reports_a_failure_naming_an_over_limit_document_and_its_count() {
    let refusal = over_limit(
        "searching this board's issues before the fix",
        SEARCH_ISSUES_BEFORE_THE_FIX,
    )
    .expect("the pre-fix document is over the limit");
    assert!(
        refusal.contains("searching this board's issues before the fix"),
        "{refusal}"
    );
    assert!(refusal.contains("770400"), "{refusal}");
    assert!(refusal.contains("500000"), "{refusal}");
}

/// The sum across sibling paths, not the deepest path alone.
///
/// GitHub's message quotes the innermost path on its own — 2,500,000 at the membership
/// page of ten it was refused under, 750,000 at the three this source binds now — and a
/// check that computed only that would be a different check from the one GitHub runs. This
/// pins the pre-fix document at the sum of every path, which is the figure the published
/// rules produce and the one the limit is applied to.
#[test]
fn the_count_sums_sibling_paths_rather_than_taking_the_deepest_one() {
    assert_eq!(
        worst_case_node_count(SEARCH_ISSUES_BEFORE_THE_FIX).expect("a countable document"),
        770_400
    );
}

/// Every document a source opted in to assignees sends — each read spelled with the people of
/// every issue it reaches — stays under the same limit, with the most people GitHub assigns
/// one issue on every one.
#[test]
fn every_document_an_opted_in_source_sends_stays_under_githubs_node_limit() {
    let over: Vec<String> = graphql::DOCUMENTS
        .iter()
        .filter_map(|(document, doing)| {
            let spelled = graphql::with_assignees(document)?;
            let mut sizes = onetaskgraph_github_projects::largest_page_sizes();
            sizes.insert("assigneeFirst".to_owned(), 10);
            let count = onetaskgraph_github_projects::node_count(&spelled, &sizes)
                .unwrap_or_else(|error| panic!("{doing} with assignees: {error}"));
            (count >= NODE_COUNT_LIMIT).then(|| format!("{doing}: {count} nodes"))
        })
        .collect();
    assert!(over.is_empty(), "{}", over.join("\n"));
}