Skip to content

Commit 50ec858

Browse files
pelikhanCopilot
andauthored
Route simple skip-if queries through GraphQL/REST to spare the search API (#80479)
* Route simple skip-if queries through GraphQL/REST to reduce search API pressure Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> * Document the efficient skip-if query subset in agent instructions and schema Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> * Use backend-neutral skip-if log and dedupe REST pagination counts Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> * Add fuzz tests for the skip-if query parser Adds a shared invariant harness (JS), a seeded property test (vitest), and a Go FuzzSkipIfQueryParser driver registered in make fuzz and CI. Fuzzing found that partially quoted values (label:"a b"c) were accepted with literal quotes; these now fall back to the search API. Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --------- Co-authored-by: pelikhan <4175913+pelikhan@users.noreply.github.com> Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
1 parent 3decbd6 commit 50ec858

14 files changed

Lines changed: 954 additions & 14 deletions

‎.changeset/skip-if-query-api-routing.md‎

Lines changed: 5 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎.github/aw/syntax-core.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,11 @@ The YAML frontmatter supports these fields:
5757

5858
- Query is automatically scoped to the current repository (use `scope: none` for cross-repo queries)
5959
- Use to gate workflows on preconditions (e.g., only run if open PRs exist)
60+
- **Efficient skip-if queries**: prefer the subset evaluated via GraphQL/REST instead of the rate-limited search API (30 req/min):
61+
- Allowed: `is:`/`type:`/`state:` (`issue`, `pr`, `open`, `closed`, `merged`), `label:` (one or more, AND), `author:`, `assignee:`, `mentions:` (plain logins), `sort:`
62+
- Must stay scoped to one repository (default scope; not `scope: none`)
63+
- Falls back to search: free text, `in:title`/`in:body`, negation (`-label:`), comma label lists (`label:a,b`), `org:`, `@me`, other qualifiers
64+
- Prefer a marker label (`is:issue is:open label:my-workflow`) over title/body text matching when designing dedup gates
6065
- **`skip-if-check-failing:`** - Skip workflow execution when CI checks are failing on the triggering ref (boolean or object)
6166
- Boolean format: `skip-if-check-failing: true` (skip if any check is failing or pending)
6267
- Object format with filtering:

‎.github/workflows/cgo.yml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1867,6 +1867,7 @@ jobs:
18671867
tests: >-
18681868
FuzzExpressionParser:./pkg/workflow/
18691869
FuzzBashCommandParserModel:./pkg/workflow/
1870+
FuzzSkipIfQueryParser:./pkg/workflow/
18701871
FuzzMentionsFiltering:./pkg/workflow/
18711872
FuzzSanitizeOutput:./pkg/workflow/
18721873
FuzzSanitizeIncomingText:./pkg/workflow/

‎Makefile‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -275,6 +275,7 @@ fuzz:
275275
go test -fuzz=FuzzParseFrontmatter -fuzztime=30s ./pkg/parser/
276276
go test -fuzz=FuzzExpressionParser -fuzztime=30s ./pkg/workflow/
277277
go test -run='^$$' -fuzz=FuzzBashCommandParserModel -fuzztime=30s ./pkg/workflow/
278+
go test -run='^$$' -fuzz=FuzzSkipIfQueryParser -fuzztime=30s ./pkg/workflow/
278279

279280
# Run security regression tests
280281
.PHONY: test-security

‎actions/setup/js/check_skip_if_helpers.cjs‎

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
const { getErrorMessage } = require("./error_helpers.cjs");
55
const { ERR_API, ERR_CONFIG } = require("./error_codes.cjs");
66
const { writeDenialSummary } = require("./pre_activation_summary.cjs");
7+
const { countSearchMatches } = require("./skip_if_query.cjs");
78

89
/**
910
* Builds the GitHub search query, optionally scoping it to the current repository.
@@ -74,14 +75,9 @@ async function runSkipQueryGate(options) {
7475
const searchQuery = buildSearchQuery(skipQuery, skipScope);
7576

7677
try {
77-
const {
78-
data: { total_count: totalCount },
79-
} = await github.rest.search.issuesAndPullRequests({
80-
q: searchQuery,
81-
per_page: 1,
82-
});
78+
const { totalCount, exact, backend } = await countSearchMatches(searchQuery, threshold);
8379

84-
core.info(`Search found ${totalCount} matching items`);
80+
core.info(`Query matched ${exact ? "" : "at least "}${totalCount} items (via ${backend} API)`);
8581

8682
if (shouldSkip(totalCount, threshold)) {
8783
core.warning(warningMessage(totalCount, threshold));

‎actions/setup/js/check_skip_if_no_match.test.cjs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -217,7 +217,7 @@ describe("check_skip_if_no_match", () => {
217217
expect(mockCore.infos).toContain("Checking skip-if-no-match query: is:open is:issue label:enhancement");
218218
expect(mockCore.infos).toContain("Minimum matches threshold: 5");
219219
expect(mockCore.infos).toContain("Scoped query: is:open is:issue label:enhancement repo:test-owner/test-repo");
220-
expect(mockCore.infos).toContain("Search found 8 matching items");
220+
expect(mockCore.infos).toContain("Query matched 8 items (via search API)");
221221
});
222222

223223
it("should use raw query when GH_AW_SKIP_SCOPE is 'none'", async () => {
Lines changed: 204 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,204 @@
1+
// @ts-check
2+
/**
3+
* Fuzz harness for the skip-if search query parser in skip_if_query.cjs.
4+
*
5+
* Checks parser and backend-selection invariants for arbitrary queries:
6+
* - parsing never throws and is deterministic
7+
* - accepted queries are fully structured (single repo, valid enums, no OR label lists)
8+
* - unsupported queries route only to search; supported ones always keep search as fallback
9+
* - GraphQL is offered only when it is exact (<= 1 label, user filters only on issues)
10+
* - acceptance is invariant to token order, extra whitespace, and sort: qualifiers
11+
* - appending free text or a negated qualifier always forces the search API
12+
* - pressure ordering is always a permutation of the capable backends
13+
*
14+
* Used by vitest and by Go's fuzzing framework when run as main module via stdin.
15+
*/
16+
17+
const { tokenizeSearchQuery, parseSearchQuery, getCapableBackends, orderBackendsByPressure } = require("./skip_if_query.cjs");
18+
const { getErrorMessage } = require("./error_helpers.cjs");
19+
20+
const TYPES = [null, "issue", "pr"];
21+
const STATES = [null, "open", "closed", "merged"];
22+
const LOGIN_PATTERN = /^[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?$/;
23+
24+
/**
25+
* Rate-limit scenarios exercised for every query.
26+
* @type {(Record<string, { limit: number, remaining: number }> | null)[]}
27+
*/
28+
const RESOURCE_SCENARIOS = [
29+
null,
30+
{},
31+
{ graphql: { limit: 5000, remaining: 5000 }, core: { limit: 5000, remaining: 5000 }, search: { limit: 30, remaining: 30 } },
32+
{ graphql: { limit: 5000, remaining: 10 }, core: { limit: 5000, remaining: 4000 }, search: { limit: 30, remaining: 30 } },
33+
{ graphql: { limit: 5000, remaining: 0 }, core: { limit: 5000, remaining: 0 }, search: { limit: 30, remaining: 1 } },
34+
{ graphql: { limit: 0, remaining: 0 }, core: { limit: 5000, remaining: 499 }, search: { limit: 30, remaining: 0 } },
35+
];
36+
37+
/**
38+
* Normalizes a parse result for comparisons that must ignore token order and casing.
39+
* @param {ReturnType<typeof parseSearchQuery>} result
40+
* @returns {string}
41+
*/
42+
function normalize(result) {
43+
if (!result.ok) return "unsupported";
44+
const q = result.query;
45+
const lower = (/** @type {string | null} */ v) => (v === null ? null : v.toLowerCase());
46+
return JSON.stringify({
47+
type: q.type,
48+
state: q.state,
49+
labels: [...q.labels].sort(),
50+
repo: q.repo && `${q.repo.owner}/${q.repo.repo}`.toLowerCase(),
51+
author: lower(q.author),
52+
assignee: lower(q.assignee),
53+
mentions: lower(q.mentions),
54+
});
55+
}
56+
57+
/**
58+
* Returns all invariant violations for a query. Never throws.
59+
* @param {string} query
60+
* @returns {string[]}
61+
*/
62+
function checkSkipIfQueryInvariants(query) {
63+
/** @type {string[]} */
64+
const violations = [];
65+
try {
66+
const result = parseSearchQuery(query);
67+
if (JSON.stringify(parseSearchQuery(query)) !== JSON.stringify(result)) violations.push("parse is not deterministic");
68+
69+
const backends = getCapableBackends(result);
70+
if (!result.ok) {
71+
if (typeof result.reason !== "string" || !result.reason) violations.push("rejection has no reason");
72+
if (JSON.stringify(backends) !== '["search"]') violations.push(`unsupported query offered ${backends.join(",")}`);
73+
} else {
74+
const q = result.query;
75+
if (!q.repo || !q.repo.owner || !q.repo.repo) violations.push("accepted query without repository");
76+
if (!TYPES.includes(q.type)) violations.push(`invalid type ${q.type}`);
77+
if (!STATES.includes(q.state)) violations.push(`invalid state ${q.state}`);
78+
if (q.state === "merged" && q.type !== "pr") violations.push("merged state without pr type");
79+
if (q.labels.some(l => !l || l.includes(","))) violations.push("empty or OR label accepted");
80+
if ([...q.labels, q.author, q.assignee, q.mentions, q.repo?.owner, q.repo?.repo].some(v => v?.includes('"'))) violations.push("value with stray quote accepted");
81+
if (new Set(q.labels).size !== q.labels.length) violations.push("duplicate labels");
82+
for (const login of [q.author, q.assignee, q.mentions]) {
83+
if (login !== null && !LOGIN_PATTERN.test(login)) violations.push(`invalid login ${login}`);
84+
}
85+
86+
if (backends[backends.length - 1] !== "search") violations.push("search is not the final fallback");
87+
if (!backends.includes("rest")) violations.push("REST not offered for supported query");
88+
const graphqlExact = q.labels.length <= 1 && (q.type === "issue" || !(q.author || q.assignee || q.mentions));
89+
if (backends.includes("graphql") !== graphqlExact) violations.push(`graphql offered=${backends.includes("graphql")} exact=${graphqlExact}`);
90+
91+
for (const suffix of [" zzfreetext", " -label:x", ' "quoted text"', " in:title"]) {
92+
if (parseSearchQuery(query + suffix).ok) violations.push(`suffix ${JSON.stringify(suffix)} did not force search`);
93+
}
94+
}
95+
96+
for (const resources of RESOURCE_SCENARIOS) {
97+
const ordered = orderBackendsByPressure(backends, resources);
98+
if (ordered.length !== backends.length || [...ordered].sort().join() !== [...backends].sort().join()) {
99+
violations.push(`pressure ordering ${ordered.join(",")} is not a permutation of ${backends.join(",")}`);
100+
}
101+
}
102+
103+
const tokens = tokenizeSearchQuery(query);
104+
if (tokens === null) {
105+
if (result.ok) violations.push("accepted query with unbalanced quotes");
106+
} else {
107+
const expected = normalize(result);
108+
const variants = {
109+
reordered: [...tokens].reverse().join(" "),
110+
"extra whitespace": ` \t${tokens.join(" \n\t ")} `,
111+
"sort qualifier": [...tokens, "sort:updated-desc"].join(" "),
112+
};
113+
for (const [name, variant] of Object.entries(variants)) {
114+
if (normalize(parseSearchQuery(variant)) !== expected) violations.push(`${name} variant changed result`);
115+
}
116+
}
117+
} catch (err) {
118+
violations.push(`threw: ${getErrorMessage(err)}`);
119+
}
120+
return violations;
121+
}
122+
123+
const FRAGMENTS = [
124+
"is:issue",
125+
"is:pr",
126+
"is:pull-request",
127+
"IS:Open",
128+
"is:open",
129+
"is:closed",
130+
"is:merged",
131+
"is:draft",
132+
"type:issue",
133+
"type:pr",
134+
"state:open",
135+
"state:closed",
136+
"state:merged",
137+
"label:bug",
138+
"label:Bug",
139+
'label:"needs triage"',
140+
"label:a,b",
141+
'label:""',
142+
"label:",
143+
"-label:bug",
144+
"repo:octo/demo",
145+
"repo:Octo/Demo",
146+
"repo:octo/other",
147+
"repo:bad",
148+
"author:octocat",
149+
"author:app/bot",
150+
"assignee:@me",
151+
"assignee:octocat",
152+
"mentions:hubot",
153+
"sort:created-desc",
154+
"org:octo",
155+
"in:title",
156+
"no:assignee",
157+
'"[daily-report]"',
158+
"free",
159+
'"unterminated',
160+
":",
161+
"-",
162+
];
163+
164+
/**
165+
* Builds a query from a byte choice stream and a free-form payload.
166+
* @param {number[]} bytes
167+
* @param {string} payload
168+
* @returns {string}
169+
*/
170+
function buildModelQuery(bytes, payload) {
171+
const parts = [];
172+
for (const b of bytes.slice(0, 64)) {
173+
const pick = b % (FRAGMENTS.length + 4);
174+
if (pick < FRAGMENTS.length) parts.push(FRAGMENTS[pick]);
175+
else if (pick === FRAGMENTS.length) parts.push(`label:${payload}`);
176+
else if (pick === FRAGMENTS.length + 1) parts.push(`author:${payload}`);
177+
else if (pick === FRAGMENTS.length + 2) parts.push(`repo:${payload}`);
178+
else parts.push(payload);
179+
}
180+
return parts.join((bytes[0] ?? 0) % 3 === 0 ? " \t " : " ");
181+
}
182+
183+
// Read input from stdin for Go-driven fuzzing
184+
if (require.main === module) {
185+
let input = "";
186+
process.stdin.on("data", chunk => {
187+
input += chunk;
188+
});
189+
process.stdin.on("end", () => {
190+
try {
191+
// Expected JSON: { query?: string, bytes?: number[], payload?: string }
192+
const { query, bytes, payload } = JSON.parse(input);
193+
const text = Array.isArray(bytes) ? buildModelQuery(bytes, payload ?? "") : (query ?? "");
194+
const violations = checkSkipIfQueryInvariants(text);
195+
process.stdout.write(JSON.stringify({ ok: violations.length === 0, query: text, violations }));
196+
process.exit(0);
197+
} catch (err) {
198+
process.stdout.write(JSON.stringify({ ok: false, violations: [getErrorMessage(err)] }));
199+
process.exit(1);
200+
}
201+
});
202+
}
203+
204+
module.exports = { checkSkipIfQueryInvariants, buildModelQuery, FRAGMENTS };
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
// @ts-check
2+
/**
3+
* Property-based fuzz tests for the skip-if search query parser.
4+
* Invariants live in fuzz_skip_if_query_harness.cjs and are shared with the Go fuzzer
5+
* (pkg/workflow/skip_if_query_fuzz_test.go).
6+
*/
7+
import { describe, it, expect } from "vitest";
8+
9+
const { checkSkipIfQueryInvariants, buildModelQuery, FRAGMENTS } = require("./fuzz_skip_if_query_harness.cjs");
10+
const { parseSearchQuery } = require("./skip_if_query.cjs");
11+
12+
/**
13+
* Deterministic mulberry32 PRNG so failures are reproducible.
14+
* @param {number} seed
15+
*/
16+
function prng(seed) {
17+
return () => {
18+
seed = (seed + 0x6d2b79f5) | 0;
19+
let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
20+
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
21+
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
22+
};
23+
}
24+
25+
const PAYLOADS = ["", "x", "octo/demo", "a,b", '"', '"quoted"', "-neg", "with space", "日本語", "\u00a0", "a:b", "@me", "Bug"];
26+
27+
describe("fuzz_skip_if_query - seed corpus", () => {
28+
it.each([
29+
"is:issue is:open label:bug repo:octo/demo",
30+
'is:pr is:merged label:"needs triage" repo:octo/demo sort:created-desc',
31+
"label:a label:b assignee:octocat repo:octo/demo",
32+
'is:issue in:title "[daily-report]" repo:octo/demo',
33+
'label:"a b"c repo:octo/demo',
34+
'label:a"b c" repo:octo/demo',
35+
"repo:octo/demo repo:Octo/Demo author:A author:a",
36+
"is:issue is:merged repo:octo/demo",
37+
"",
38+
'"',
39+
"\t\n ",
40+
])("holds invariants for %j", query => {
41+
expect(checkSkipIfQueryInvariants(query)).toEqual([]);
42+
});
43+
44+
it("rejects values with partial quoting so they fall back to search", () => {
45+
expect(parseSearchQuery('label:"a b"c repo:octo/demo').ok).toBe(false);
46+
expect(parseSearchQuery('label:a"b c" repo:octo/demo').ok).toBe(false);
47+
});
48+
});
49+
50+
describe("fuzz_skip_if_query - generated queries", () => {
51+
it("holds invariants for grammar-generated queries", () => {
52+
const rand = prng(0x5eed);
53+
let accepted = 0;
54+
for (let i = 0; i < 3000; i++) {
55+
const bytes = Array.from({ length: 1 + Math.floor(rand() * 8) }, () => Math.floor(rand() * 256));
56+
const payload = PAYLOADS[Math.floor(rand() * PAYLOADS.length)];
57+
// Most generated queries need a repo qualifier to exercise the accepted path.
58+
const query = `${buildModelQuery(bytes, payload)}${rand() < 0.7 ? " repo:octo/demo" : ""}`;
59+
const violations = checkSkipIfQueryInvariants(query);
60+
if (violations.length) throw new Error(`invariants failed for ${JSON.stringify(query)}: ${violations.join("; ")}`);
61+
if (parseSearchQuery(query).ok) accepted++;
62+
}
63+
// Guard against a generator that only produces rejected queries.
64+
expect(accepted).toBeGreaterThan(100);
65+
});
66+
67+
it("holds invariants for random character soup", () => {
68+
const rand = prng(42);
69+
const alphabet = 'abc:/-," \t@isrepolabe';
70+
for (let i = 0; i < 2000; i++) {
71+
const length = Math.floor(rand() * 40);
72+
const query = Array.from({ length }, () => alphabet[Math.floor(rand() * alphabet.length)]).join("");
73+
const violations = checkSkipIfQueryInvariants(query);
74+
if (violations.length) throw new Error(`invariants failed for ${JSON.stringify(query)}: ${violations.join("; ")}`);
75+
}
76+
});
77+
78+
it("covers every fragment in the generator vocabulary", () => {
79+
for (const fragment of FRAGMENTS) {
80+
expect(checkSkipIfQueryInvariants(`${fragment} repo:octo/demo`)).toEqual([]);
81+
}
82+
});
83+
});

0 commit comments

Comments
 (0)