Skip to content

Improve warning line/column accuracy and error messages - #31

Merged
rockneurotiko merged 7 commits into
mainfrom
improve-warning-lines-and-messages
Apr 27, 2026
Merged

rockneurotiko merged 7 commits into
mainfrom
improve-warning-lines-and-messages

Conversation

@rockneurotiko

@rockneurotiko rockneurotiko commented Apr 25, 2026 •

Copy link
Copy Markdown
Owner

Fixed:

  • Warning line and column numbers are now accurate for all macro variants (~GQL sigil, gql heredoc, gql inline string, gql_from_file). Previously, line numbers were off by one due to a spurious +1 in the offset calculation.
  • Single-line gql("...") string arguments now correctly map errors to the call site line.
  • gql_from_file errors now report lines relative to the external file rather than the call site.
  • Runtime validation no longer double-formats error messages.

Improved:

  • Validation errors originating in external fragments (via fragments: option) now include context with the fragment name and line, and point to the ...FragmentName spread in the query rather than the sigil line.
  • 'expected value of type X, found a variable' messages are now enriched with the variable name and declared type, e.g. 'found variable $traveller_guid of type String!'
  • Added THIRD_PARTY_LICENSES.md for apollo-compiler (MIT/Apache-2.0).

Added 18 new tests covering all of the above.

Summary by CodeRabbit

  • Bug Fixes

    • More accurate error/warning locations for inline, single-line, and external-file queries
    • Runtime validation no longer double-formats messages
    • Fragment validation errors now reference the fragment spread and include surrounding context
    • Type-mismatch diagnostics enriched with variable name and declared type
  • Documentation

    • Added third-party licenses and clarified license notice for the parsing/validation dependency
  • Tests

    • New diagnostics tests covering line/column accuracy and message enrichment
  • Chores

    • Included third-party licenses in packaged files

Fixed:
- Warning line and column numbers are now accurate for all macro
  variants (~GQL sigil, gql heredoc, gql inline string, gql_from_file).
  Previously, line numbers were off by one due to a spurious +1 in
  the offset calculation.
- Single-line gql("...") string arguments now correctly map errors
  to the call site line.
- gql_from_file errors now report lines relative to the external file
  rather than the call site.
- Runtime validation no longer double-formats error messages.

Improved:
- Validation errors originating in external fragments (via fragments:
  option) now include context with the fragment name and line, and
  point to the ...FragmentName spread in the query rather than the
  sigil line.
- 'expected value of type X, found a variable' messages are now
  enriched with the variable name and declared type, e.g.
  'found variable `$traveller_guid` of type `String!`'
- Added THIRD_PARTY_LICENSES.md for apollo-compiler (MIT/Apache-2.0).

Added 18 new tests covering all of the above.
@coderabbitai

coderabbitai Bot commented Apr 25, 2026 •

Copy link
Copy Markdown

Warning

Rate limit exceeded

@rockneurotiko has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 28 minutes and 31 seconds before requesting another review.

To keep reviews running without waiting, you can enable usage-based add-on for your organization. This allows additional reviews beyond the hourly cap. Account admins can enable it under billing.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 8a86a695-69be-4432-9e22-9e4bfe8d70b5

📥 Commits

Reviewing files that changed from the base of the PR and between 3fcf333 and c8d69a7.

📒 Files selected for processing (3)
  • lib/graphql_query.ex
  • lib/graphql_query/parser.ex
  • lib/graphql_query/validator.ex
📝 Walkthrough

Walkthrough

Adjusts GraphQL diagnostic/reporting: maps inline and external-file validation locations correctly, attributes errors to fragment spreads, enriches Apollo type-mismatch messages with variable name/type, centralizes validation diagnostic emission, updates logger runtime formatting, adds third‑party license doc, and extends tests for these behaviors.

Changes

Cohort / File(s) Summary
Documentation & Packaging
CHANGELOG.md, README.md, THIRD_PARTY_LICENSES.md, mix.exs
Adds third‑party license manifest and README notice for apollo-compiler; documents diagnostic fixes/improvements; includes THIRD_PARTY_LICENSES.md in packaged files.
Entrypoints & Logging
lib/graphql_query.ex, lib/graphql_query/logger.ex
Adjusts gql_from_file/2 and single-line gql/2 caller metadata to produce correct file- or sigil-relative locations; logger runtime branch no longer double-formats messages.
Document Utilities
lib/graphql_query/document.ex
Adds filter_used_fragments_for/2 wrapper exposing fragment filtering for a document.
Parsing & Message Enrichment
lib/graphql_query/parser.ex
Adds build_line_map/1, resolve_error_source/2, find_spread_line/2, and enrich_error_message/2; changes warn-line baseline computation to use file-relative line.
Validation Centralization
lib/graphql_query/validator.ex
Adds emit_validation_diagnostics/6 (internal) to centralize diagnostic formatting, line-map use, fragment adjustments, and message enrichment.
Tests
test/graphql_query_test.exs
Adds extensive tests for diagnostic line/column correctness across sigils, inline/heredoc/call-site cases, external .graphql files, fragment spread mapping, runtime logging format, and enrich_error_message/2.
CI
.github/workflows/ci.yml
Makes dialyzer cache save conditional on the dialyzer step outcome to avoid saving when skipped.

Sequence Diagram(s)

sequenceDiagram
  participant Caller
  participant Document
  participant Parser
  participant Validator as "apollo-compiler"
  participant Logger

  Caller->>Document: assemble document (+ fragments)
  Document->>Parser: build_line_map(document)
  Caller->>Validator: validate(combined_query)
  Validator-->>Parser: diagnostics (absolute lines)
  Parser->>Parser: resolve_error_source(diagnostic.line, line_map)
  Parser->>Parser: enrich_error_message(diagnostic, query_text)
  Parser->>Logger: emit formatted_message, location
  Logger-->>Caller: log warning/error
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Poem

🐰 I hopped through lines both near and far,
Found spreads and vars and set each pointer right.
Errors point where fragments and sigils are,
Types sing their names so mismatches lose their fright.
A tiny thump—diagnostics now take flight.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 77.78% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main changes: improved warning line/column accuracy and enriched error messages across all macros, runtime validation, and external fragments.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
✨ Simplify code
  • Create PR with simplified code
  • Commit simplified code in branch improve-warning-lines-and-messages

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

🧹 Nitpick comments (6)
lib/graphql_query.ex (2)

467-470: caller.line - 1 can underflow at line 1.

For a single-line gql("...") invocation on source line 1, inline_meta becomes [line: 0]. With the line-offset machinery (where the parser's reported line 1 is added to this base), a GraphQL error then surfaces at file line 1, which is correct. However, if other code paths interpret line: 0 as "unknown" (the gql_from_file path uses line: 0 deliberately), this could create ambiguity. In practice, top-of-file gql("…") calls are rare, but worth being aware of — a max(caller.line - 1, 0) is already implicitly fine, but consider a brief comment clarifying that line 0 here means "base offset, parser line 1 maps to file line 1".

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/graphql_query.ex` around lines 467 - 470, The code sets inline_meta =
[line: caller.line - 1] which can produce line: 0 for calls on source line 1 and
may be ambiguous; change this to use a non-negative base like inline_meta =
[line: max(caller.line - 1, 0)] (or equivalent) and add a short comment in the
same area (near warn_location and inline_meta) clarifying that line: 0 is the
base offset meaning “parser line 1 maps to file line 1” to avoid confusion with
other paths that use line: 0 to denote unknown.

1207-1213: Spread-not-found fallback uses line: 0 — confirm downstream rendering.

When Parser.find_spread_line/2 returns nil (e.g., the failing fragment is referenced transitively via another fragment, not directly spread in the query), this falls back to spread_line = 0, then format_error adds the caller's base line offset. The resulting reported line will be caller_line + 0, which is typically just the sigil/macro line — acceptable as a fallback, but the column: 0 may render as :0 in some IDE/CI parsers. Consider using loc.column (preserving the original column) or 1 for the fallback when the spread isn't found, so downstream tools that strip zero-columns still get a sensible cursor.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/graphql_query.ex` around lines 1207 - 1213, The fallback when
Parser.find_spread_line(line_map, name) returns nil currently sets spread_line =
0 and column = 0 which can render as :0 downstream; update the logic in this
block so that when find_spread_line/2 returns nil you keep a sensible column
(use the original loc.column or 1) and only fall back the line to 0 if
necessary, i.e. construct adjusted_loc from %{loc | line: spread_line || 0,
column: loc.column || 1} (refer to Parser.find_spread_line/2, spread_line,
adjusted_loc, and the code path that produces adjusted_error) so downstream
format_error consumers get a valid non-zero column.
THIRD_PARTY_LICENSES.md (1)

19-19: Specify a language on the fenced code block.

markdownlint (MD040) flags this fence as missing a language. Use text (or similar) to satisfy the linter and improve rendering hints.

📝 Proposed fix
-```
+```text
 Copyright 2021 Apollo Graph, Inc.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@THIRD_PARTY_LICENSES.md` at line 19, The fenced code block in
THIRD_PARTY_LICENSES.md is missing a language tag (MD040); update the opening
fence for the license block (the triple backticks) to include a language
identifier such as text (e.g., change ``` to ```text) so the markdown linter
stops flagging it and rendering hints improve.
test/graphql_query_test.exs (1)

2734-2766: Line-mapping math: double-check the comment for query Q2.

The heredoc starts at source line 5 (the ~GQL"""). Inside the heredoc:

  • line 1 → { → source line 6 ✓
  • line 7 → query Q2(...) → source line 12 ✓

The math holds, but the inline comment says "line 7 of GQL + sigil at line 5". Strictly, line 1 of the heredoc content maps to source line 6 (i.e., sigil_line + 1), not sigil_line + 0. The comments would be slightly clearer if they mentioned the offset is sigil_line + content_line. Minor doc nit only — assertions are correct.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@test/graphql_query_test.exs` around lines 2734 - 2766, Update the inline
comment explaining the line-mapping for the heredoc in the test "~GQL with
multiple errors on different lines reports correct lines": clarify that the
heredoc content line N maps to source line sigil_line + N (e.g., content line 1
→ sigil_line + 1), and change the phrase "line 7 of GQL + sigil at line 5" to
explicitly state "content line 7 → sigil_line (5) + 7 = source line 12" so the
offset rule (sigil_line + content_line) is unambiguous; leave the assertions
(assert logs =~ ...) unchanged.
lib/graphql_query/document.ex (1)

283-287: Naming nit: _public suffix combined with @doc false is contradictory.

The _public suffix suggests an external API while @doc false hides it from documentation. Consider either dropping the suffix (e.g., filter_used_fragments_for/2) or making it part of the public, documented API. This is purely a style suggestion.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/graphql_query/document.ex` around lines 283 - 287, Rename the function
filter_used_fragments_public/2 to a clearer internal name (e.g.,
filter_used_fragments_for/2 or filter_used_fragments/2) to remove the misleading
_public suffix; update the `@spec` annotation and the function head (def
filter_used_fragments_for(document, fragments) do ...) and replace all internal
callers that reference filter_used_fragments_public to the new name, keeping
`@doc` false if this remains internal; ensure the alias to the helper
filter_used_fragments/2 (the existing internal helper) is preserved and run
tests to verify no references to the old symbol remain.
lib/graphql_query/parser.ex (1)

115-123: Minor: avoid acc ++ [item] in the reduce.

Appending to a list inside a reduce is O(n²). Prepend and reverse, or accumulate the offset only and rebuild at the end. With realistic fragment counts the difference is negligible, but the idiom is easy to fix and matches the rest of the codebase’s style.

♻️ Proposed refactor
-    {segments, _} =
-      Enum.reduce(used_fragments, {initial, query_lines}, fn fragment, {acc, offset} ->
+    {segments_rev, _} =
+      Enum.reduce(used_fragments, {[], query_lines}, fn fragment, {acc, offset} ->
         frag_text = Kernel.to_string(fragment)
         frag_lines = count_lines(frag_text)
         start = offset + 1
         finish = offset + frag_lines
         name = fragment.name || "unnamed"
-        {acc ++ [{{:fragment, name}, start, finish}], finish}
+        {[{{:fragment, name}, start, finish} | acc], finish}
       end)
+
+    segments = initial ++ Enum.reverse(segments_rev)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/graphql_query/parser.ex` around lines 115 - 123, The reduce is building
segments with acc ++ [item] causing O(n²); change Enum.reduce over
used_fragments to prepend each new fragment entry into the accumulator (e.g.,
add {{:fragment, name}, start, finish} to the head of acc) while still tracking
offset, then after the reduce reverse the accumulated list to produce segments;
update references to the accumulator tuple in the reducer (currently {acc,
offset}) and keep using fragment.name and count_lines(fragment_text) as before
so behavior is unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@CHANGELOG.md`:
- Line 14: The Markdown example uses backslash-escaped backticks
(`\`$traveller_guid\``) which CommonMark will render with literal backslashes;
replace this with a proper code-fenced example or a longer backtick fence so the
variable `$traveller_guid` and types `ID!` / `String!` render correctly; update
the line that currently reads the enriched error example (the text containing
expected value of type ID!, found variable `$traveller_guid` of type `String!`)
to be presented inside a fenced code block (or use triple backticks / longer
fence) so no backslashes are needed and the inline code appears as intended.

In `@lib/graphql_query.ex`:
- Around line 1161-1163: The inline conditional used to build line_map in
print_warnings (function print_warnings/4) is exceeding formatter line length;
change the single-line `if document, do: ..., else: ...` into a multi-line
if/else block (or assign with a case/cond) so it fits formatting rules, and
apply the same change to print_typed_warnings (print_typed_warnings/3) where the
identical inline conditional appears; then run `mix format` locally and commit
the formatted file so CI passes.

In `@lib/graphql_query/parser.ex`:
- Around line 216-221: The with-block beginning at the
Regex.run(`@found_variable_pattern`, message) branch is not formatted per mix
format; reformat the clause that calls extract_variable_at(query_text, loc.line,
loc.column) and find_variable_type(query_text, var_name) so the chained pattern
matches and bindings are wrapped across lines as the project formatter expects
(or simply run mix format to fix it). Locate the
Regex.run/@found_variable_pattern branch and the with that references
extract_variable_at and find_variable_type and apply mix format (or adjust line
breaks) so CI's mix format check passes.
- Around line 166-182: The find_spread_lines function is currently capturing the
inline-fragment keyword "on" due to the regex ~r/\.\.\.\s*(\w+)/ which causes
"on" to be inserted into the spreads map and can block later real fragment names
via Map.put_new; update the matching logic to exclude the "on" keyword (e.g. use
a regex with a negative lookahead like ~r/\.\.\.\s*(?!on\b)(\w+)/ or filter out
matches where the captured name == "on" before calling Map.put_new) so only real
fragment spread names are added to the map.

In `@test/graphql_query_test.exs`:
- Line 2731: The failing lines are long assertion messages that violate mix
format line-length; run `mix format` (or reformat the file) and wrap the long
assertion messages so they break across lines; specifically update the
assertions around the variable occurrences check (the `occurrences` assert) and
the several `assert enriched.message == "expected value of type ID, found
variable ..."` assertions so the message strings and arguments are split into
multiple concatenated or heredoc-safe lines; target the assertions in
test/graphql_query_test.exs referencing `occurrences` and `enriched.message` and
commit the formatted file.

---

Nitpick comments:
In `@lib/graphql_query.ex`:
- Around line 467-470: The code sets inline_meta = [line: caller.line - 1] which
can produce line: 0 for calls on source line 1 and may be ambiguous; change this
to use a non-negative base like inline_meta = [line: max(caller.line - 1, 0)]
(or equivalent) and add a short comment in the same area (near warn_location and
inline_meta) clarifying that line: 0 is the base offset meaning “parser line 1
maps to file line 1” to avoid confusion with other paths that use line: 0 to
denote unknown.
- Around line 1207-1213: The fallback when Parser.find_spread_line(line_map,
name) returns nil currently sets spread_line = 0 and column = 0 which can render
as :0 downstream; update the logic in this block so that when find_spread_line/2
returns nil you keep a sensible column (use the original loc.column or 1) and
only fall back the line to 0 if necessary, i.e. construct adjusted_loc from
%{loc | line: spread_line || 0, column: loc.column || 1} (refer to
Parser.find_spread_line/2, spread_line, adjusted_loc, and the code path that
produces adjusted_error) so downstream format_error consumers get a valid
non-zero column.

In `@lib/graphql_query/document.ex`:
- Around line 283-287: Rename the function filter_used_fragments_public/2 to a
clearer internal name (e.g., filter_used_fragments_for/2 or
filter_used_fragments/2) to remove the misleading _public suffix; update the
`@spec` annotation and the function head (def filter_used_fragments_for(document,
fragments) do ...) and replace all internal callers that reference
filter_used_fragments_public to the new name, keeping `@doc` false if this remains
internal; ensure the alias to the helper filter_used_fragments/2 (the existing
internal helper) is preserved and run tests to verify no references to the old
symbol remain.

In `@lib/graphql_query/parser.ex`:
- Around line 115-123: The reduce is building segments with acc ++ [item]
causing O(n²); change Enum.reduce over used_fragments to prepend each new
fragment entry into the accumulator (e.g., add {{:fragment, name}, start,
finish} to the head of acc) while still tracking offset, then after the reduce
reverse the accumulated list to produce segments; update references to the
accumulator tuple in the reducer (currently {acc, offset}) and keep using
fragment.name and count_lines(fragment_text) as before so behavior is unchanged.

In `@test/graphql_query_test.exs`:
- Around line 2734-2766: Update the inline comment explaining the line-mapping
for the heredoc in the test "~GQL with multiple errors on different lines
reports correct lines": clarify that the heredoc content line N maps to source
line sigil_line + N (e.g., content line 1 → sigil_line + 1), and change the
phrase "line 7 of GQL + sigil at line 5" to explicitly state "content line 7 →
sigil_line (5) + 7 = source line 12" so the offset rule (sigil_line +
content_line) is unambiguous; leave the assertions (assert logs =~ ...)
unchanged.

In `@THIRD_PARTY_LICENSES.md`:
- Line 19: The fenced code block in THIRD_PARTY_LICENSES.md is missing a
language tag (MD040); update the opening fence for the license block (the triple
backticks) to include a language identifier such as text (e.g., change ``` to
```text) so the markdown linter stops flagging it and rendering hints improve.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 88f17c87-a350-48a6-852b-bc9f74040a4a

📥 Commits

Reviewing files that changed from the base of the PR and between d75e51e and 29e10ef.

📒 Files selected for processing (9)
  • CHANGELOG.md
  • README.md
  • THIRD_PARTY_LICENSES.md
  • lib/graphql_query.ex
  • lib/graphql_query/document.ex
  • lib/graphql_query/logger.ex
  • lib/graphql_query/parser.ex
  • mix.exs
  • test/graphql_query_test.exs

Comment thread CHANGELOG.md Resolved
Comment thread lib/graphql_query.ex Resolved
Comment thread lib/graphql_query.ex Resolved
Comment thread lib/graphql_query/parser.ex Resolved
Comment thread lib/graphql_query/parser.ex Resolved
Comment thread test/graphql_query_test.exs Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (5)
lib/graphql_query.ex (2)

468-470: caller.line - 1 can produce a negative base line in pathological cases.

For a top-of-file inline gql("...") call (caller.line == 1) inline_meta becomes [line: 0], which is what error_location/2 expects (warn_line + error.line with error.line = 1 → file line 1). However, if caller.line is ever 0 in some test/macro composition path, you'd report at line -1. In practice caller.line should always be ≥ 1, so this is mostly a defensive concern — max(caller.line - 1, 0) would make the intent explicit and avoid surprises in tooling.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/graphql_query.ex` around lines 468 - 470, The current use of caller.line
- 1 when building inline_meta can produce negative line numbers in pathological
cases; change the computation in the inline_meta assignment (where inline_meta =
[line: caller.line - 1]) to clamp the result at 0 (e.g., use a max-like
operation) so the base line passed into error_location/2 and used with warn_line
never becomes negative; update the inline_meta creation near the inline gql
handling to use the clamped value (referencing inline_meta, caller.line, and
error_location/2).

1090-1132: Code duplication between runtime warnings and errors paths.

The two branches of the with block (lines 1086–1112 for {:ok, warnings} and 1118–1131 for {:error, errors}) duplicate the line_map/query_text setup, the enrich → adjust → format → append → log pipeline, and the iteration. The same pattern is also re-implemented at compile time in print_warnings/4 and print_typed_warnings/3 (lines 1161–1199). Consider extracting a shared helper (e.g. emit_validation_diagnostics(query, items, warn_location, source, item_to_error_fun)) so the four call sites stay in sync as the pipeline evolves.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/graphql_query.ex` around lines 1090 - 1132, Both runtime branches
duplicate the same prepare→enrich→adjust→format→append→log pipeline
(build_line_map, Document.format_query_with_fragments,
Parser.enrich_error_message, maybe_adjust_for_fragment, Parser.format_error,
append_fragment_context, Logger.warning), and the same logic is repeated in
print_warnings/4 and print_typed_warnings/3; extract a single helper (suggest
name emit_validation_diagnostics/5) that accepts the query, the list of items
(warnings or errors), warn_location, source/type flag, and a mapping function
that converts an item into a ValidationError, then replace the duplicated blocks
in the {:ok, warnings} and {:error, errors} branches and the two print_*
functions to call this helper so parsing/formatting/logging logic is centralized
and kept in sync.
lib/graphql_query/parser.ex (2)

261-271: find_variable_type/2 returns the first $name: match across operations.

A query with multiple operations declaring the same variable name with different types (query A($id: ID!) {...} query B($id: String!) {...}) will always resolve to the first declaration via Regex.run/2, which can mislead the enriched message when the offending operation is the second one. Scoping the search to the operation containing loc.line (or returning all candidates and disambiguating by location) would be more robust. Low priority since this is an unusual schema shape.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/graphql_query/parser.ex` around lines 261 - 271, find_variable_type/2
currently uses Regex.run to return the first "$name: type" across the whole
query_text causing incorrect type resolution when multiple operations declare
the same variable; update find_variable_type/2 to either (a) restrict the regex
search to the operation block that contains the error location (use the provided
loc.line or operation span parsed earlier) so it only matches declarations in
that operation, or (b) return all matches (e.g., with Regex.scan) and
disambiguate by comparing each match's position in query_text to the error's
location, ensuring you reference and update the logic around
find_variable_type/2 to accept or access the error loc to pick the correct
variable declaration.

168-185: Spread tracking only records the first line per fragment name.

Map.put_new/3 at line 182 keeps the earliest line a given ...FragmentName appears on. If the same fragment is spread multiple times in the query and the validation error is associated with a later spread, the user is pointed at the first occurrence instead. Consider tracking a list of lines per fragment (and choosing the closest one to the error in maybe_adjust_for_fragment), or at minimum documenting this behavior in the moduledoc.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/graphql_query/parser.ex` around lines 168 - 185,
find_spread_lines/collect_spread_names currently uses Map.put_new (in
collect_spread_names) so only the first spread line per fragment name is
recorded; change the accumulator to map fragment name -> list of line numbers
and record every occurrence (e.g., in collect_spread_names replace
Map.put_new(inner_acc, name, line_num) with Map.update(inner_acc, name,
[line_num], fn existing -> [line_num | existing] end) or equivalent so every
spread line is stored), then update maybe_adjust_for_fragment to choose the most
relevant line from that list (e.g., closest to the error) or sort/uniq the lists
as needed; alternatively, if you prefer the simpler route, add moduledoc noting
the current first-occurrence behavior.
CHANGELOG.md (1)

16-18: Add a language identifier to the fenced code block.

markdownlint (MD040) flagged this fenced block. Use text (or another appropriate identifier) so it renders consistently and passes lint.

📝 Proposed fix
-  ```
+  ```text
   expected value of type ID!, found variable `$guid` of type `String!`
</details>

<details>
<summary>🤖 Prompt for AI Agents</summary>

Verify each finding against the current code and only fix it if needed.

In @CHANGELOG.md around lines 16 - 18, Add a language identifier to the fenced
code block containing the text "expected value of type ID!, found variable
$guid of type String!" so it satisfies markdownlint MD040; update the
triple-backtick opener to include a language token such as text (e.g., ```text)
for that specific fenced block in CHANGELOG.md so it renders consistently.


</details>

</blockquote></details>

</blockquote></details>

<details>
<summary>🤖 Prompt for all review comments with AI agents</summary>

Verify each finding against the current code and only fix it if needed.

Inline comments:
In @lib/graphql_query.ex:

  • Around line 1212-1213: The current fallback sets spread_line =
    Parser.find_spread_line(line_map, name) || 0 and then builds adjusted_loc =
    %{loc | line: spread_line, column: 0}, which forces line: 0 when no spread is
    found and collapses the diagnostic onto the sigil/heredoc; instead, detect the
    "no spread" case (Parser.find_spread_line returns nil/false) and preserve the
    original loc (do not overwrite loc.line/column) while still attaching frag_ctx
    so append_fragment_context/2 can add the in-fragment context; update the code
    around spread_line/adjusted_loc to only rewrite loc when a valid spread_line
    exists and otherwise pass through the original loc to error_location/2 so the
    user sees the fragment line plus the appended fragment context.

Nitpick comments:
In @CHANGELOG.md:

  • Around line 16-18: Add a language identifier to the fenced code block
    containing the text "expected value of type ID!, found variable $guid of type
    String!" so it satisfies markdownlint MD040; update the triple-backtick opener
    to include a language token such as text (e.g., ```text) for that specific
    fenced block in CHANGELOG.md so it renders consistently.

In @lib/graphql_query.ex:

  • Around line 468-470: The current use of caller.line - 1 when building
    inline_meta can produce negative line numbers in pathological cases; change the
    computation in the inline_meta assignment (where inline_meta = [line:
    caller.line - 1]) to clamp the result at 0 (e.g., use a max-like operation) so
    the base line passed into error_location/2 and used with warn_line never becomes
    negative; update the inline_meta creation near the inline gql handling to use
    the clamped value (referencing inline_meta, caller.line, and error_location/2).
  • Around line 1090-1132: Both runtime branches duplicate the same
    prepare→enrich→adjust→format→append→log pipeline (build_line_map,
    Document.format_query_with_fragments, Parser.enrich_error_message,
    maybe_adjust_for_fragment, Parser.format_error, append_fragment_context,
    Logger.warning), and the same logic is repeated in print_warnings/4 and
    print_typed_warnings/3; extract a single helper (suggest name
    emit_validation_diagnostics/5) that accepts the query, the list of items
    (warnings or errors), warn_location, source/type flag, and a mapping function
    that converts an item into a ValidationError, then replace the duplicated blocks
    in the {:ok, warnings} and {:error, errors} branches and the two print_*
    functions to call this helper so parsing/formatting/logging logic is centralized
    and kept in sync.

In @lib/graphql_query/parser.ex:

  • Around line 261-271: find_variable_type/2 currently uses Regex.run to return
    the first "$name: type" across the whole query_text causing incorrect type
    resolution when multiple operations declare the same variable; update
    find_variable_type/2 to either (a) restrict the regex search to the operation
    block that contains the error location (use the provided loc.line or operation
    span parsed earlier) so it only matches declarations in that operation, or (b)
    return all matches (e.g., with Regex.scan) and disambiguate by comparing each
    match's position in query_text to the error's location, ensuring you reference
    and update the logic around find_variable_type/2 to accept or access the error
    loc to pick the correct variable declaration.
  • Around line 168-185: find_spread_lines/collect_spread_names currently uses
    Map.put_new (in collect_spread_names) so only the first spread line per fragment
    name is recorded; change the accumulator to map fragment name -> list of line
    numbers and record every occurrence (e.g., in collect_spread_names replace
    Map.put_new(inner_acc, name, line_num) with Map.update(inner_acc, name,
    [line_num], fn existing -> [line_num | existing] end) or equivalent so every
    spread line is stored), then update maybe_adjust_for_fragment to choose the most
    relevant line from that list (e.g., closest to the error) or sort/uniq the lists
    as needed; alternatively, if you prefer the simpler route, add moduledoc noting
    the current first-occurrence behavior.

</details>

<details>
<summary>🪄 Autofix (Beta)</summary>

Fix all unresolved CodeRabbit comments on this PR:

- [ ] <!-- {"checkboxId": "4b0d0e0a-96d7-4f10-b296-3a18ea78f0b9"} --> Push a commit to this branch (recommended)
- [ ] <!-- {"checkboxId": "ff5b1114-7d8c-49e6-8ac1-43f82af23a33"} --> Create a new PR with the fixes

</details>

---

<details>
<summary>ℹ️ Review info</summary>

<details>
<summary>⚙️ Run configuration</summary>

**Configuration used**: Organization UI

**Review profile**: CHILL

**Plan**: Pro

**Run ID**: `0a8cc6d0-6acd-46da-b11a-42392592e631`

</details>

<details>
<summary>📥 Commits</summary>

Reviewing files that changed from the base of the PR and between 29e10efb34f21e59941098a1a6ed2f057a903428 and 9f31e67ec5524cc2ccb99767593c0ce0bcb2ea68.

</details>

<details>
<summary>📒 Files selected for processing (7)</summary>

* `.github/workflows/ci.yml`
* `CHANGELOG.md`
* `THIRD_PARTY_LICENSES.md`
* `lib/graphql_query.ex`
* `lib/graphql_query/document.ex`
* `lib/graphql_query/parser.ex`
* `test/graphql_query_test.exs`

</details>

<details>
<summary>✅ Files skipped from review due to trivial changes (1)</summary>

* THIRD_PARTY_LICENSES.md

</details>

</details>

<!-- This is an auto-generated comment by CodeRabbit for review status -->

Comment thread lib/graphql_query.ex Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
lib/graphql_query/validator.ex (1)

168-183: Centralized diagnostic emission looks good.

The helper cleanly composes line-map building, message enrichment, fragment-context adjustment, and formatting, matching the existing call sites in lib/graphql_query.ex. One small nit: alias GraphqlQuery.Parser could be lifted to the module level alongside the existing alias GraphqlQuery.{...} block (or merged into it) for consistency, since the Parser alias is now used unconditionally on every call. Not blocking.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/graphql_query/validator.ex` around lines 168 - 183, Move the local alias
for Parser out of the function and into the module-level aliases to match the
existing GraphqlQuery.{...} alias block: remove the line "alias
GraphqlQuery.Parser" from emit_validation_diagnostics and add Parser to the
module alias list so that functions like emit_validation_diagnostics,
Parser.build_line_map, Parser.enrich_error_message and Parser.format_error use
the module-level alias consistently.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@lib/graphql_query/validator.ex`:
- Around line 168-183: Move the local alias for Parser out of the function and
into the module-level aliases to match the existing GraphqlQuery.{...} alias
block: remove the line "alias GraphqlQuery.Parser" from
emit_validation_diagnostics and add Parser to the module alias list so that
functions like emit_validation_diagnostics, Parser.build_line_map,
Parser.enrich_error_message and Parser.format_error use the module-level alias
consistently.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 58434279-4539-4c10-8408-3bdccbe07662

📥 Commits

Reviewing files that changed from the base of the PR and between 9f31e67 and 3fcf333.

📒 Files selected for processing (4)
  • CHANGELOG.md
  • lib/graphql_query.ex
  • lib/graphql_query/parser.ex
  • lib/graphql_query/validator.ex
🚧 Files skipped from review as they are similar to previous changes (2)
  • CHANGELOG.md
  • lib/graphql_query/parser.ex

@rockneurotiko
rockneurotiko merged commit 4481586 into main Apr 27, 2026
6 checks passed
@rockneurotiko
rockneurotiko deleted the improve-warning-lines-and-messages branch April 27, 2026 09:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant