Files
aji/docs/rfcs/0037-borrow-diagnostic-related-locations.md
T

15 KiB

RFC 0037: Related locations for borrow diagnostics

Status: Proposed
Scope: Diagnostic metadata for E2101, E2104 and E4302; AIR format 0 and .aji 0.1
Language version: 0.1
Supersedes: —

Implementation and spec integration are prepared together for owner adoption (P6-7/DD-018). Formal status remains Proposed; this does not record acceptance. The specification is authoritative for the prepared implementation, while this RFC retains its rationale and bounded scope.

Motivation

E2101/E2104 identify a conflicting live borrow with conflicts_with, but expose only the current operation's source position. E4302 identifies the outstanding task without showing its spawn. An agent must search lowered AIR or reconstruct provenance to find the earlier construct.

The existing verifier already selects the conflicting borrow or loan. Reporting its location improves machine repairability and auditability without introducing a lifetime inference or choosing a repair. This is the bounded part of C5 in the design review and assessment.

Scope is deliberately limited to related positions using existing file/line/column conventions. Computing a safe enclosing block, exact edit ranges, ancestry trees, or every possible conflict is separate work.

Precise invariant

For a fixed input, the verifier MUST make the same acceptance/rejection decision and select the same primary diagnostic as before this extension. Related metadata MUST refer to the already selected conflicting value or outstanding task and to a real definition/spawn location. Metadata MUST NOT add a borrow, end a borrow, change a loan, broaden effects or authority, or alter runtime behavior.

An earlier position denotes a syntactic origin, not a claim that it ran before the primary operation in every schedule or that enclosing/deleting it would repair the program.

Normative rule changes

Integrated in spec 10 §2, “Related locations”:

A diagnostic MAY include related_locations, an ordered array of non-binding factual context records. Each record MUST contain role and value. The identity in value uses the existing diagnostic value naming convention. A located record MUST contain file, line and col, using the primary location's conventions. Additional fields MUST NOT change an existing field's meaning.

E2101 and E2104 diagnostics that identify conflicts_with MUST include one related record with role conflicting_borrow and that value's definition position. E4302 diagnostics that identify task MUST include one related record with role task_spawn and the spawn origin of that outstanding task. The record's value MUST equal the corresponding conflicts_with or task field, respectively. Other forms of these codes MUST NOT invent a conflicting value or task.

The related record MUST describe the same conflict selected for the primary diagnostic. Implementations MUST NOT enumerate other conflicts as part of this extension. The primary position, existing structured fields, error code, diagnostic ordering and duplicate suppression MUST retain their existing meaning and selection behavior.

Integrated in spec 15 §10, “Related source positions”:

For a diagnostic from lowered AIR, each related AIR position MUST be mapped independently through the lowering source map, including the source file recorded for imported or specialized code. If mapped, file, line and col MUST denote that source construct, and air_line/air_col MUST retain its AIR position, as for the primary diagnostic.

If no related source mapping exists, the related record MUST omit file, line and col as a group, retain its factual role, value and air_line/air_col, and MUST NOT substitute a guessed source position. This rule does not change the existing primary-position fallback.

For direct AIR input, related records use the input AIR file and definition/spawn position, without source-mapping metadata. The new array is omitted when there is no identified related context. An unmapped source record still identifies a known AIR origin; it is not a located source record.

The first release adds exactly one related record for each covered diagnostic form. Stable role names are conflicting_borrow and task_spawn; future roles require a specified extension. Object key order is role, value, then file, line, col when available, then air_line, air_col for lowered AIR. Existing envelope fields keep their serialization order; related_locations is appended at the end. Values are source/SSA identities, not user-facing name inference.

Verifier implications

No new abstract borrow state, acceptance rule or transfer function is introduced. For E2101/E2104, use the ValueInfo.span for the selected conflicts_with definition, never its root merely because the root is easier to find. For a caller receiving a borrow-returning call, this is the caller's view definition; the callee's from declaration is not substituted.

For E4302, record the creating task.spawn position as diagnostic provenance on a loan. Carry it through the existing task-handle transitions, including the returned handle on the cancelled edge of task.join_cancel. Looking up that returned handle's definition would report the cancellation arm instead of the spawn and is insufficient. The loan's current task identity remains the existing task field; the related position identifies its creation, even if the SSA handle name changed.

Metadata is available only after the same SSA/type prerequisites as today. It does not participate in liveness, overlap, join-state equality or rejection. Source-map failure affects only availability of a related source position.

Implementation uses constant-sized provenance per existing loan and constant-time definition lookup per diagnostic; asymptotic borrow-verification complexity is unchanged. Serialization adds at most one record per covered diagnostic. No recursive ancestry walk, additional whole-program pass or filesystem read is required.

Interpreter / runtime implications

None. Accepted programs have identical run records, memory behavior, task scheduling, weak-memory choices, traps and fuel accounting. Rejected programs are never executed. Diagnostic output is deterministic for the same input and source maps; related metadata consumes no Aji runtime fuel.

AIR changes

No syntax, instruction, operand/result type, ownership/memory/concurrency effect, capability requirement, trap or verifier transfer changes. AIR format 0 retains its frozen meaning. Diagnostic envelope metadata is not an AIR semantic feature and needs no module feature declaration.

Valid example

module related.valid
fn main() -> u64 effects [] {
    var data: [u64; 1] = [1u64];
    { ref view = data; assert(view[0] == 1u64); }
    data[0] = 2u64;
    return data[0];
}

The borrow ends before the write. The program remains accepted and returns 2; no diagnostic or related record is emitted. The verifier is not instructed to construct this block as a repair.

Rejected example

module related.rejected
fn main() -> u64 effects [] {
    var data: [u64; 1] = [1u64];
    ref view = data;
    data[0] = 2u64;
    return view[0];
}

This remains E2101: the write conflicts with the live shared view. The primary diagnostic retains the write position, while the related position maps the selected view definition to the borrow construct. Illustrative additional field (the value name and exact column come from actual lowering):

{"related_locations":[{"role":"conflicting_borrow","value":"%data_4","file":"rejected.aji","line":4,"col":5,"air_line":13,"air_col":5}]}

For E2104, the rejected region-reset fixture must report the existing selected borrow's definition. For E4302, ending a lent borrow must retain the borrow-end primary position and add the outstanding task's spawn; cancelled join must retain that spawn through handle replacement. These examples add facts, not new rejection rules.

Diagnostics impact

No new codes or kinds. E2101, E2104 and E4302 receive the additive array in the identified forms. Existing borrow, conflicts_with, task, primary location and AIR position fields remain intact. Related objects must be typed structured data in src/diag.zig, not JSON embedded in a string field or text parsed from message.

Consumers must tolerate optional metadata and an unmapped related source record. The CLI's JSON Lines, exit codes and stdout/stderr contract remain unchanged. No edits or repair_candidates are generated by this RFC.

Spec integration

The prepared change integrates the rules into:

  • spec 10 §2: envelope, roles, conditions, identity and serialization contract;
  • spec 15 §10: independent related-position source mapping and fallback;
  • spec 08 §11 and spec 03 §20: reference the E2101/E2104 diagnostic metadata without changing borrow rules;
  • spec 04 §34: reference E4302 spawn metadata and cancelled-handle provenance;
  • reference/error-codes.md: annotate existing codes with a reference to the metadata contract;
  • Quick Reference: one short note on using related_locations for the relevant errors.

Spec 10 §2 and spec 15 §10 already enter the AIR and source bundles respectively. Keep the necessary schema text there rather than adding the RFC rationale or repeated examples to every bundle page.

The integration condenses the schema and code-to-role mapping into a few table rows plus the required source-map/determinism invariants. Rationale, implementation discussion and test matrices remain here or in tests rather than expanding normative prose with them.

Compatibility and migration

Accepted/rejected sets, rejection codes, runtime outcomes and source/AIR ratio stay unchanged. No AIR format or language-version increment is required because no construct's meaning changes. Diagnostics gain optional fields; consumers comparing exact JSON bytes or maintaining diagnostic goldens need updates. Existing clients ignoring unknown fields continue to operate.

Preserve current first-conflict selection and source diagnostic deduplication. Do not merge related records from discarded duplicate diagnostics: that would silently introduce conflict enumeration and change the proposed bounded scope.

Agent complexity impact

  • New concepts: one optional factual related-location record with two stable roles; no new programming-language concept.
  • New verifier state: diagnostic provenance on existing loans; no new abstract semantic state.
  • Syntax/instructions: none; .aji syntax and lowering semantics are unchanged.
  • Interactions: reborrows, borrow returns, region result parameters, cancelled task handles, imported source, generic specializations and existing diagnostic deduplication.
  • Repairability: avoids searching for the selected earlier construct; does not promise a unique repair or lower total cost without measurement.
  • Existing primitives: sufficient for the programs and verifier; the current JSON envelope lacks structured related positions.
  • New diagnostics: no codes; an additive metadata field on three existing codes.
  • Bundle budget: measured integration after DD-017 (cl100k): AIR 46,937 → 47,328 (+391); Quick 8,807 → 8,859 (+52), other source 65,799 → 66,195 (+396), full source 74,606 → 75,054 (+448, +0.60%). Necessary schema/source-map rules enter the bundles, not this RFC. Other tokenizer totals and unchanged std size are recorded in docs/agent/README.md.

This is a diagnostic extension, not a semantic feature with a new source syntax. It still lands through spec, diagnostic API, verifier provenance, source mapping, Quick Reference and AIR/source CLI tests together; interpreter behavior must remain unchanged.

Validation plan

Before calling this RFC implemented:

  1. Verify positive and negative examples in AIR and through the source pipeline: ending a borrow before access/reset remains accepted; keeping it live retains E2101/E2104; joining before ending remains accepted; ending before join retains E4302. Source lowering normally prevents explicit early borrow.end; where no ordinary source spelling exposes E4302, a mapped lowered-AIR pipeline fixture must cover its source metadata without adding source syntax or relaxing lifetime rules.
  2. Assert related role, identity and exact file/line/column for all three codes, including shared/exclusive reborrows, split views, region allocations, call-returned views and parameter definitions.
  3. Test E4302 on ordinary and cancelled join paths so the spawn position survives task-handle replacement. Retain existing deterministic/randomized scheduler coverage for accepted task counterparts; extra metadata must not influence scheduling or loans.
  4. Test imports, generic specialization and cases where the earlier and primary positions map to different source files. Preserve current code/location deduplication and deterministic record ordering.
  5. Test an intentionally absent related source mapping: no fabricated file/line/column, AIR coordinates retained. Cover direct AIR input and exact JSON serialization separately.
  6. Compare accepted run records before/after, conformance rejection codes and diagnostic counts. Run unit tests, conformance, targeted CLI checks and bundle measurements; do not use M/C to choose the schema or scope.

Alternatives considered

  • SSA names only: current behavior; reliable identities but costly source reconstruction.
  • Human notes only: loses the machine-readable contract.
  • Every ancestor/conflict: adds output and provenance complexity; not needed to locate today's selected conflict.
  • Suggested enclosing block or exact repair: requires additional correctness analysis or a semantic choice; deferred.
  • Task handle definition for E4302: fails to identify spawn after a cancelled join returns another handle; use carried spawn provenance.
  • A new error code: the violated rule is unchanged; unnecessary compatibility cost.

Unresolved questions

No semantic decision is delegated to implementation. The owner must decide adoption. End ranges, original user-facing names, multiple conflicts and block-enclosure suggestions are explicitly outside scope and need a separate proposal if desired.

Draft validation

Both .aji code blocks were extracted and checked against the baseline compiler: the valid example returns 2 with fuel 1,000; the negative example rejects with E2101. Its selected %data_4 definition is AIR line 13, mapping to source line 4, column 5. The JSON addition above now matches the implemented metadata contract. The examples also have source/AIR conformance counterparts under related_locations and related_borrow_*. Validation results for the prepared implementation are recorded under P6-7; formal adoption remains the owner's decision.