Subtraction and simplicity scratchpad · NVIDIA/hyperflare-inference #603

Raw Markdown for agents: https://autobot.eidonix.com/p/0e6dfd73-299a-4544-8411-71494f42e55d.md

#1 [high] Suggestion 1: RevisionLookupError struct + downcast is boilerplate for a message nothing reads via source()

Lens: Subtraction/Simplicity.

Changed code, flare/src/hub.rs:3398-3419 (new type):

#[derive(Debug)]
struct RevisionLookupError {
    repository: String,
    revision: String,
    source: Box<dyn std::error::Error>,
}

impl std::fmt::Display for RevisionLookupError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            formatter,
            "cannot resolve {}@{}: {}",
            self.repository, self.revision, self.source
        )
    }
}

impl std::error::Error for RevisionLookupError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        Some(self.source.as_ref())
    }
}

and flare/src/hub.rs:3427-3441:

    let info = resolve_revision(api, repo, progress).map_err(|source| {
        if matches!(
            source.downcast_ref::<ApiError>(),
            Some(ApiError::RequestError(error))
                if matches!(error.as_ref(), ureq::Error::StatusCode(404))
        ) {
            Box::new(RevisionLookupError {
                repository: repo.url(),
                revision: repo.revision().to_owned(),
                source,
            })
        } else {
            source
        }
    })?;

Evidence that the struct's only purpose (the Error::source cause chain) is unused:

Replacement (deletes the whole struct + two impls, ~22 lines, and the nested matches! guard):

    let info = resolve_revision(api, repo, progress).map_err(|error| {
        if matches!(
            error.downcast_ref::<ApiError>(),
            Some(ApiError::RequestError(error))
                if matches!(error.as_ref(), ureq::Error::StatusCode(404))
        ) {
            format!("cannot resolve {}@{}: {error}", repo.url(), repo.revision()).into()
        } else {
            error
        }
    })?;

(Box<dyn Error>: From<String>, and {error} still embeds the original ApiError, so "retains HTTP 404 without assigning a cause" is preserved.)

Module convention is exactly this one-liner form: flare/src/hub.rs:2280 map_err(|error| format!("cannot check {}@{revision} for updates: {error}; …", origin.repository)), :2658 map_err(|error| format!("core file is unavailable: {name}: {error}")), :3069-ish result.map_err(|error| error.to_string().into()) (:3057). AGENTS.md:188-190 rejects "unsupported abstractions … without a concrete requirement"; a private typed error whose source() is never read is that.

#4 [high] Research summary

Subtraction/Simplicity review of PR #603 (+41/−1, flare/src/hub.rs only). The diff is small and well-tested, but it introduces a private error type and the first ApiError downcast in flare to produce a message string that nothing in the codebase reads as a typed error — while the same file already has both a one-line format!(...).into() idiom for this exact message shape and a named-predicate idiom for ApiError/ureq status checks. Three suggestions, all citing the changed lines:

  1. Delete RevisionLookupError (flare/src/hub.rs:3398-3419) and collapse the map_err closure (:3427-3441). The type's only added value over a formatted string is Error::source(), and nobody walks the chain: the crate alias is Box<dyn std::error::Error> (:29), the CLI prints Display (flare-cli/src/main.rs:64), and Orbit flattens to String (flare-cli/src/orbit/controller.rs:2533-2536, :2545). No .chain() or Error::source walk exists in flare/ or flare-cli/. Replace with format!("cannot resolve {}@{}: {error}", repo.url(), repo.revision()).into(), exactly the pattern at :2280, :2658, :3057. Saves ~22 lines of boilerplate + two hand-written impls and keeps the semantics (Display still embeds the original ApiError, so HTTP 404 is retained and no cause assigned).

  2. Name the "is this a Hub 404" predicate instead of a third inline copy. The same nested match now appears at :2142, :3383 and :3431; transient_hub_error (:5460-5471) is the established idiom for exactly this kind of ApiError predicate. A one-line hub_not_found(&ApiError) -> bool used at all three sites removes the nested matches! guard and keeps the retry decision and the diagnostic decision from drifting apart.

  3. Placement (lower priority): the context is duplicated across the two callers of one function — new wrap at :3427 and hand-written twin at :2279-2280. Producing the context inside resolve_revision (:3374-3396) would cover both callers and need no downcast at all, because the retry match at :3381 still holds a concrete ApiError; the type information is only lost at the result => result? arm on :3392. Also noted: RevisionClient::revision (:2130-2151) still surfaces bare 404s and is used by the update check, so the diagnostic gap narrows rather than closes; and the new operator-visible text has no matching clause in docs/cli-design.md:920-929 (AGENTS.md treats error text as specification).

No dead code, no flags/config knobs, no speculative generality beyond item 1; the test change (:8620-8622) is minimal and proportional.

#5 [high] Report verdict: diff focused but hand-rolls an error type; 3 ranked simplifications

Lens: Subtraction/Simplicity & Conventions. Verdict summary for the final report (details in entries 1-3, all citations there).

Overall: the diff is small (+41/−1, flare/src/hub.rs only), focused, has no dead code, no flags/config knobs, no new dependencies, no fallback branches added, and the test change (flare/src/hub.rs:8620-8622) is minimal and proportional. It is NOT already lean in one respect: it hand-rolls a 22-line private error type plus two impl blocks and an ApiError downcast (flare/src/hub.rs:3398-3419, :3427-3441) to produce a Display string that no consumer reads as a typed error, where the same file's dominant pattern is a one-line format!(...).into() (:2280, :2658, :3057).

Three suggestions, ranked:

  1. [high, entry 1] Delete RevisionLookupError entirely; replace the map_err closure body's Box::new(RevisionLookupError{..}) with format!("cannot resolve {}@{}: {error}", repo.url(), repo.revision()).into(). Evidence source() is unused: alias Box<dyn Error> at :29; CLI prints Display only (flare-cli/src/main.rs:64); Orbit flattens (flare-cli/src/orbit/controller.rs:2533-2536, :2545); no chain walk in flare/ or flare-cli/.
  2. [medium, entry 2] Third inline copy of the 404 walk (:2142, :3383, :3431); existing named-predicate precedent transient_hub_error (:5460-5471). Add hub_not_found(&ApiError) -> bool and use at all three.
  3. [medium, entry 3] Placement: context duplicated at the two callers of resolve_revision — new wrap :3427 vs pre-existing hand-written twin :2279-2280. Inside resolve_revision (:3374-3396) the 404 arm at :3381 still has a concrete ApiError, so no downcast would be needed. Note the update-check path RevisionClient::revision (:2130-2151, swallowed at :2171, used by check_core_updates at flare-cli/src/cache_commands.rs:272) is still bare 404, and the new message has no docs clause at docs/cli-design.md:920-929 (AGENTS.md:52-58 treats error text as specification).

Strictly-not-duplicating-correctness note: I did not raise the -tp1 alias naming (message reports the originally requested @gb10 after the alias retry 404s) as a bug — that is the Correctness lens's ground; under this lens it is simply a consequence of where the wrap sits (item 3).

#2 [medium] Suggestion 2: third copy of the 404-walk over ApiError/ureq; a helper already exists by precedent (transient_hub_error)

Lens: Duplication / existing abstraction.

Instance A (pre-existing), flare/src/hub.rs:2141-2146:

        let body = match get(revision) {
            Err(ureq::Error::StatusCode(404)) if tp1_revision_alias(revision) => {
                get(&format!("{revision}-tp1"))?
            }
            result => result?,
        };

Instance B, flare/src/hub.rs:3381-3393 (resolve_revision):

    let info = match with_transient_retry(|| api.repo(repo.clone()).info()) {
        Err(ApiError::RequestError(error))
            if matches!(error.as_ref(), ureq::Error::StatusCode(404))
                && tp1_revision_alias(revision) =>

Instance C (added by this PR), flare/src/hub.rs:3428-3432:

        if matches!(
            source.downcast_ref::<ApiError>(),
            Some(ApiError::RequestError(error))
                if matches!(error.as_ref(), ureq::Error::StatusCode(404))
        ) {

The repo already establishes the named-predicate idiom for exactly this, flare/src/hub.rs:5457-5471:

/// Errors from Hub resolution or file identity that may succeed when retried.
/// Authentication, missing repositories, missing files, and malformed responses
/// are permanent and are never retried, so the signed binding is unchanged.
fn transient_hub_error(error: &ApiError) -> bool {
    let ApiError::RequestError(request) = error else {
        return false;
    };
    match request.as_ref() {
        ureq::Error::Timeout(_)
        | ureq::Error::Io(_)
        | ureq::Error::HostNotFound
        | ureq::Error::ConnectionFailed => true,
        ureq::Error::StatusCode(status) => matches!(status, 408 | 429 | 500..=599),
        _ => false,
    }
}

Suggestion: add one sibling predicate next to :3460-3472 (or to :5460) and use it at all three sites:

/// Whether a Hub request failed because the reference does not exist.
fn hub_not_found(error: &ApiError) -> bool {
    matches!(error, ApiError::RequestError(request) if matches!(request.as_ref(), ureq::Error::StatusCode(404)))
}

Then B becomes Err(error) if hub_not_found(&error) && tp1_revision_alias(revision), and C becomes if error.downcast_ref::<ApiError>().is_some_and(hub_not_found). Removes the nested matches! guard and the drift risk between the retry decision and the diagnostic decision (they must stay on the same status).

#3 [medium] Suggestion 3: placement in the second of two callers, and no docs clause for new operator text

Lens: Subtraction (placement/duplication), lower priority than entries 1-2.

The same repo@revision context now exists twice in one file, for two callers of the same function:

    let info = resolve_revision(&api, &repo, None)
        .map_err(|error| format!("cannot check {}@{revision} for updates: {error}; the local version is unchanged (use --offline to skip the check)", origin.repository))?;

So the file has two divergent messages for one failure. If the context were produced inside resolve_revision (flare/src/hub.rs:3374-3396), it would cover both callers and, decisively, no downcast would be needed: inside resolve_revision the error is still a concrete ApiError at the match on :3381 — the type information is only lost when the arm at :3392 result => result? boxes it. A 404 arm there can therefore return the formatted message directly, deleting the entire downcast_ref::<ApiError> guard at :3428-3432. If that were done, :2280's duplicated {}@{revision} becomes removable (its unique content is "cannot check … for updates: …; the local version is unchanged (use --offline to skip the check)").

Also not reached by the wrap: RevisionClient::revision (flare/src/hub.rs:2130-2151) still returns a bare ureq::Error::StatusCode(404); scan_revisions swallows it at :2171 (let Ok(remote) = self.revision(&key.0, &key.1) else { continue; };) and the update check check_core_updates (flare-cli/src/cache_commands.rs:272) uses that path. Not a defect of this diff, but the "operator cannot tell which reference" gap the PR cites only narrows for download/acquire/run and Orbit agent downloads — worth stating, not fixing here.

Convention note (low): the operator-visible text is undocumented; docs/cli-design.md:920-929 specifies the -tp1 retry behavior and what Flare records, with no mention of the message. AGENTS.md:52-58 treats error text as specification and routes unresolved defects to docs/TODO.txt (which is what #489's reviewer asked for and this PR does not do). A one-clause addition at docs/cli-design.md:924-926 would keep docs and message aligned.