#!/bin/sh
#
# Copyright (C) 2003 - 2026 Qore Technologies, s.r.o.
#
# Incremental driver for one AOT `.qo` artifact.
#
# Invoked by the build as the recipe for OUTPUT (a `.qo`), but the unit of work
# is not OUTPUT: it is the strongly connected component of the required-edge
# graph that OUTPUT belongs to.  A required edge that closes a cycle cannot be
# expressed as a build edge, so the members of a cyclic component have no valid
# relative order and must be compiled and published as one generation under one
# lock.  `qore-qo-source-order --scc-*` computes that decomposition and the
# generation identity; this script is the builder for it.
#
# A component is current when its published generation record names the token
# that its current sources hash to.  Because the token is a Merkle digest over
# the component's whole transitive source closure, that single comparison
# answers the question for every member at once -- which is what per-file
# freshness could not do.
#
# Publication is a compare-and-swap: the token is computed before the compile
# and re-checked when the record is written.  If the sources moved underneath,
# nothing is published and the whole component is rebuilt exactly once.  There
# is no per-file retry loop, and a normal build performs no rebuild at all.
#
# A singleton component keeps the fast path: one `qcc -c -L <preload>` compile
# of one source against the frozen outputs of its predecessor components.  A
# multi-member component needs one shared parse across its members, so it is
# delegated to the group batch bootstrap, which holds the group lock and
# republishes every component's generation record.

set -eu

# Preserve qcc crash artifacts for AOT/linker debugging when the host core
# pattern permits it.
ulimit -c unlimited 2>/dev/null || true

if [ "$#" -lt 3 ]; then
    echo "usage: $0 OUTPUT SOURCE SINGLE_SCRIPT [PRELOAD_QO ...]" >&2
    exit 2
fi

canonical_path() {
    path=$1
    dir=$(dirname "$path")
    base=$(basename "$path")
    if [ -d "$dir" ]; then
        printf '%s/%s\n' "$(CDPATH= cd "$dir" && pwd -P)" "$base"
    else
        printf '%s\n' "$path"
    fi
}

output=$(canonical_path "$1")
source=$(canonical_path "$2")
single_script=$(canonical_path "$3")
shift 3
this_script=$(canonical_path "$0")
qo_dir=$(dirname "$output")
idxfile="$output.idx.json"
script_dir=$(CDPATH= cd "$(dirname "$(canonical_path "$this_script")")" && pwd -P)
single_script_dir=$(CDPATH= cd "$(dirname "$single_script")" && pwd -P)
context_file="$single_script_dir/.qcc-context"
if [ ! -f "$context_file" ] && [ -f "$qo_dir/.qcc-context" ]; then
    context_file="$qo_dir/.qcc-context"
fi
source_order_tool="${QORE_QCC_SOURCE_ORDER_HELPER:-$script_dir/qore-qo-source-order}"
source_parse_define_tool="${QORE_QCC_SOURCE_PARSE_DEFINE_HELPER:-$script_dir/qore-qo-source-parse-defines}"
batch_bootstrap_tool="${QORE_QCC_BATCH_BOOTSTRAP_HELPER:-$script_dir/qore-qo-batch-bootstrap}"
batch_bootstrap_stamp=${QORE_QCC_BATCH_BOOTSTRAP_STAMP:-}
# The script that parses PART of a group in one go, preloading the rest.  A
# component that spans several sources needs a shared parse, but it does not need
# the group's: only its own members are mutually dependent.
subset_script=${QORE_QCC_SUBSET_SCRIPT:-}
batch_script="$single_script_dir/qcc-batch.sh"

# The component this recipe actually builds, resolved once.
#
# `component_key` is the only durable name for it.  A component index is a
# function of the graph -- the decomposition is numbered by lowest member node,
# so one required edge appearing or disappearing renumbers every component above
# it -- and the build's own depfiles contribute required edges.  An index
# resolved in one process and used in the next can therefore name a different
# component, which is how a compile ends up publishing against the wrong
# generation or, worse, compiling against another component's preload.  The key
# is a digest of the member output set, so it either names the same members or
# does not resolve at all.
component_index=
component_key=
component_selector=
component_size=0
component_lock=
component_lock_hint=${QORE_QCC_COMPONENT_LOCK:-}
# The helpers are installed side by side, so the lock helper is found beside this
# one rather than threaded through every caller's argument list.
lock_tool=${QORE_QCC_LOCK_HELPER:-$(dirname "$this_script")/qore-qo-lock}
planned_stale=${QORE_QCC_PLANNED_STALE:-0}

# True when the group coordinator ran ahead of this recipe.
#
# The coordinator is then the group's scheduler and this recipe is a verifier of
# the same predicate: it must ask the currency question with the coordinator's
# rule, not a stricter one.  Answering it differently is what let the
# coordinator find a group current while every object recipe behind it found
# its own component stale -- and then compile, concurrently, the fan-out the
# coordinator exists to replace.  Build inputs from outside the group are the
# build tool's business; the coordinator's plan target takes them as
# dependencies, so it is reached whenever one of them moves.
coordinator_scheduled=${QORE_QCC_PREREQUISITES_ORDERED:-0}
currency_scope=
if [ "$coordinator_scheduled" = 1 ]; then
    currency_scope=--source-deps-only
fi

run_source_order() {
    if [ -n "${QORE_QCC_QORE_EXECUTABLE:-}" ] \
            && [ -x "$QORE_QCC_QORE_EXECUTABLE" ]; then
        "$QORE_QCC_QORE_EXECUTABLE" "$source_order_tool" "$@"
    else
        "$source_order_tool" "$@"
    fi
}

have_source_order() {
    [ -x "$source_order_tool" ] && [ -f "$context_file" ]
}

#! Resolves the component that publishes OUTPUT from the current graph.
resolve_component_from_graph() {
    if ! have_source_order; then
        return 1
    fi
    component_line=$(run_source_order --scc-for "$context_file" "$output") || return 1
    component_index=$(printf '%s' "$component_line" | cut -f1)
    component_key=$(printf '%s' "$component_line" | cut -f2)
    component_size=$(printf '%s' "$component_line" | cut -f3)
    case "$component_size" in
        ''|*[!0-9]*)
            echo "$0: cannot read component size for $output: $component_line" >&2
            return 1
            ;;
    esac
    if [ -z "$component_index" ] || [ -z "$component_key" ]; then
        return 1
    fi
    component_selector=$component_key
    return 0
}

#! Resolves the component that publishes OUTPUT.
#  Failure is not fatal: a context-less invocation (or a helper that predates
#  the component surface) falls back to treating OUTPUT as its own unit, which
#  is what a singleton component is anyway.
resolve_component() {
    if [ -n "${QORE_QCC_COMPONENT_INDEX:-}" ] \
            && [ -n "${QORE_QCC_COMPONENT_KEY:-}" ] \
            && [ -n "${QORE_QCC_COMPONENT_SIZE:-}" ]; then
        case "$QORE_QCC_COMPONENT_INDEX:$QORE_QCC_COMPONENT_SIZE" in
            *[!0-9:]*|:|*:)
                echo "$0: invalid planned component identity:" \
                    "$QORE_QCC_COMPONENT_INDEX $QORE_QCC_COMPONENT_SIZE" >&2
                return 1
                ;;
        esac
        component_index=$QORE_QCC_COMPONENT_INDEX
        component_key=$QORE_QCC_COMPONENT_KEY
        component_size=$QORE_QCC_COMPONENT_SIZE
        component_selector=$component_key
        return 0
    fi
    resolve_component_from_graph
}

#! Re-resolves component identity after the dependency graph transitioned.
#  Everything the planner passed describes the superseded decomposition, so it
#  is discarded rather than mixed with the identity read from the current graph.
resolve_component_live() {
    component_lock_hint=
    component_lock=
    resolve_component_from_graph
}

#! The identity of the component's member sources, before anything is compiled.
#  Deliberately NOT the full generation token: a compile rewrites its own depfile,
#  which contributes required edges, which decide the component's predecessors.
#  Comparing full tokens across a compile would report "inputs moved" on every
#  build that changes a depfile.
component_source_token() {
    run_source_order --scc-source-token "$context_file" "$component_selector"
}

cleanup_stage_dir() {
    stage_dir=${1:-}
    if [ -n "$stage_dir" ] && [ -d "$stage_dir" ]; then
        rm -rf "$stage_dir"
    fi
}

prepare_preload_dir() {
    preload_dir=$1
    preload_file=$2

    target_name=$(basename "$output")
    mkdir -p "$preload_dir"
    while IFS= read -r preload_qo; do
        [ -n "$preload_qo" ] || continue
        [ -f "$preload_qo" ] || continue
        preload_name=$(basename "$preload_qo")
        [ "$preload_name" = "$target_name" ] && continue
        [ -e "$preload_dir/$preload_name" ] && continue
        # Freeze one coherent artifact generation for this qcc process.  A
        # symlink would follow a concurrent provider's atomic replacement and
        # could expose different generations while qcc restores metadata and
        # executable bodies from the same logical preload.
        ln "$preload_qo" "$preload_dir/$preload_name"
        if [ -f "$preload_qo.compile-contract.stamp" ]; then
            # qcc canonicalizes this path into the generated depfile, so keep
            # it linked to the live sidecar.
            ln -s "$preload_qo.compile-contract.stamp" \
                "$preload_dir/$preload_name.compile-contract.stamp"
        fi
        if [ -f "$preload_qo.idx.json" ]; then
            ln "$preload_qo.idx.json" \
                "$preload_dir/$preload_name.idx.json"
        fi
    done < "$preload_file"
}

collect_source_parse_defines() {
    define_file=$1
    preload_file=$2
    define_tmp=$(mktemp "$define_file.tmp.XXXXXX")

    if [ ! -x "$source_parse_define_tool" ]; then
        echo "$0: missing source parse define helper: $source_parse_define_tool" >&2
        rm -f "$define_tmp"
        return 1
    fi
    if [ -n "${QORE_QCC_QORE_EXECUTABLE:-}" ] \
            && [ -x "$QORE_QCC_QORE_EXECUTABLE" ]; then
        if ! "$QORE_QCC_QORE_EXECUTABLE" --exec-mode=ast \
                "$source_parse_define_tool" "$output" "$preload_file" \
                > "$define_tmp"; then
            rm -f "$define_tmp"
            return 1
        fi
    else
        if ! "$source_parse_define_tool" "$output" "$preload_file" \
                > "$define_tmp"; then
            rm -f "$define_tmp"
            return 1
        fi
    fi
    if [ -f "$define_file" ] && cmp -s "$define_file" "$define_tmp"; then
        rm -f "$define_tmp"
    else
        mv "$define_tmp" "$define_file"
    fi
}

#! Outputs of every member of every transitive predecessor component.
#  The component's own members are excluded by construction: it compiles them
#  together, so a sibling `.qo` would be the generation this build replaces.
select_preload_outputs() {
    resolved_file=$1
    compile_plan_file=$2
    shift 2
    requested_file=$(mktemp "${TMPDIR:-/tmp}/qore-qo-requested.XXXXXX")
    : > "$resolved_file"

    if [ -n "$compile_plan_file" ]; then
        awk -F '\t' '$1 == "preload" { print substr($0, index($0, "\t") + 1) }' \
            "$compile_plan_file" > "$requested_file"
    elif have_source_order && [ -n "$component_selector" ]; then
        if ! run_source_order --scc-preload "$context_file" "$component_selector" \
                > "$requested_file"; then
            rm -f "$requested_file"
            return 1
        fi
    else
        for preload_qo in "$@"; do
            printf '%s\n' "$preload_qo" >> "$requested_file"
        done
    fi

    while IFS= read -r preload_qo; do
        [ -n "$preload_qo" ] || continue
        [ "$preload_qo" = "$output" ] && continue
        if [ -f "$preload_qo" ]; then
            printf '%s\n' "$preload_qo" >> "$resolved_file"
        fi
    done < "$requested_file"
    rm -f "$requested_file"
}

select_manifest_inputs() {
    resolved_file=$1
    compile_plan_file=$2
    requested_file=$(mktemp "${TMPDIR:-/tmp}/qore-qo-direct.XXXXXX")
    : > "$resolved_file"

    if [ -n "$compile_plan_file" ]; then
        awk -F '\t' '$1 == "direct" { print substr($0, index($0, "\t") + 1) }' \
            "$compile_plan_file" > "$requested_file"
    elif have_source_order; then
        if ! run_source_order --direct "$context_file" "$output" > "$requested_file"; then
            rm -f "$requested_file"
            return 1
        fi
    else
        : > "$requested_file"
    fi

    while IFS= read -r preload_qo; do
        [ -n "$preload_qo" ] || continue
        [ "$preload_qo" = "$output" ] && continue
        if [ -f "$preload_qo.compile-contract.stamp" ]; then
            printf '%s\n' "$preload_qo.compile-contract.stamp" \
                >> "$resolved_file"
        elif [ -f "$preload_qo" ]; then
            printf '%s\n' "$preload_qo" >> "$resolved_file"
        fi
    done < "$requested_file"
    rm -f "$requested_file"
}

#! Compiles the one member of a singleton component.
#  Returns 0 on success, 75 when qcc reports that its inputs moved under it, and
#  1 on a real compile failure.  A 75 is never retried here: the caller decides,
#  once, whether to rebuild the whole component.
compile_single_member() {
    selected_preload_file=$1
    manifest_input_file=$2
    single_log=
    single_preload=
    extra_define_file=

    if [ ! -f "$single_script" ]; then
        echo "$0: missing single compile script: $single_script" >&2
        return 1
    fi

    # Recompile only this source against the frozen predecessor preload.
    # qcc-single.sh writes OUTPUT, OUTPUT.d, OUTPUT.idx.json, status JSON, the
    # source manifest, and success/content stamps. qcc itself decides whether
    # the manifest is current and can skip before Qore initialization when
    # nothing affecting the output changed.
    extra_define_file=$output.source-parse-defines
    single_log=$(mktemp "${TMPDIR:-/tmp}/qore-qo-single.XXXXXX")
    single_preload=$(mktemp -d "$qo_dir/.qcc-preload.$(basename "$output").XXXXXX")

    if ! prepare_preload_dir "$single_preload" "$selected_preload_file" \
            >> "$single_log" 2>&1 \
            || ! collect_source_parse_defines "$extra_define_file" \
                "$selected_preload_file" >> "$single_log" 2>&1; then
        cat "$single_log" >&2
        rm -f "$single_log"
        cleanup_stage_dir "$single_preload"
        return 1
    fi

    # `$?` after a NEGATED condition is the negation's status, not the command's,
    # so the compile status has to be captured in the else branch.
    if QORE_QCC_SOURCE_PARSE_DEFINE_FILE=$extra_define_file \
            QORE_QCC_SOURCE_MANIFEST_INPUT_FILE=$manifest_input_file \
            QORUS_QO_SOURCE_PARSE_DEFINE_FILE=$extra_define_file \
            QORUS_QO_SOURCE_MANIFEST_INPUT_FILE=$manifest_input_file \
            sh "$single_script" "$source" "$output" "$single_preload" \
                >> "$single_log" 2>&1; then
        rc=0
    else
        rc=$?
    fi
    cleanup_stage_dir "$single_preload"
    if [ "$rc" -ne 0 ]; then
        # A retryable attempt reports an error only because its snapshot is no
        # longer publishable; that diagnostic is superseded by the rebuild the
        # caller performs, so it is not preserved in a successful build log.
        if [ "$rc" -eq 75 ]; then
            rm -f "$single_log"
        else
            cat "$single_log" >&2
            rm -f "$single_log"
        fi
        return "$rc"
    fi

    cat "$single_log"
    rm -f "$single_log"
    if [ ! -f "$idxfile" ]; then
        echo "$0: single compile succeeded but did not create $idxfile" >&2
        return 1
    fi
    return 0
}

#! Runs a graph query, scoping currency the way this invocation is entitled to.
#  `$currency_scope` is empty unless the group coordinator scheduled this
#  recipe, and an empty word must not reach the helper as an argument.
run_scoped_source_order() {
    if [ -n "$currency_scope" ]; then
        run_source_order "$currency_scope" "$@"
    else
        run_source_order "$@"
    fi
}

component_is_current() {
    if ! have_source_order || [ -z "$component_selector" ]; then
        return 1
    fi
    if [ -n "$batch_bootstrap_stamp" ]; then
        run_scoped_source_order --scc-current --batch-stamp "$batch_bootstrap_stamp" \
            "$context_file" "$component_selector"
    else
        run_scoped_source_order --scc-current "$context_file" "$component_selector"
    fi
}

#! Writes one coherent locked snapshot for a singleton compile.
prepare_component_compile_plan() {
    compile_plan_file=$1
    if [ -n "$batch_bootstrap_stamp" ]; then
        run_scoped_source_order --scc-compile-plan \
            --batch-stamp "$batch_bootstrap_stamp" \
            "$context_file" "$component_selector" > "$compile_plan_file"
    else
        run_scoped_source_order --scc-compile-plan \
            "$context_file" "$component_selector" > "$compile_plan_file"
    fi
}

#! Commits the compiled component, refusing to publish against a moved input.
#  \a 1 is the member-source token the compile was planned from and \a 2 the
#  dependency-graph generation its preload was selected from; an empty graph
#  generation means the caller had no plan to compare against, which is the
#  context-less fallback rather than a permissive publish.
publish_component() {
    if [ -n "$2" ]; then
        run_source_order --scc-publish --expect "$1" --expect-graph "$2" \
            "$context_file" "$component_selector"
    else
        run_source_order --scc-publish --expect "$1" \
            "$context_file" "$component_selector"
    fi
}

accept_current_component() {
    if ! component_is_current; then
        return 1
    fi
    # The custom command can be newer than its output only because a source or
    # ordering prerequisite changed. Record that this generation was validated
    # against the newer input without rewriting object or contract content.
    # Recursive prerequisite probes must remain observational.
    if [ "${QORE_QCC_PREREQUISITES_READY:-0}" != 1 ]; then
        touch "$output.stamp"
    fi
    return 0
}

#! Builds the component, with its generation lock already held by the caller.
#  One lock covers every member, so no sibling can publish a new compile contract
#  while this compile runs -- the condition the retry loop existed to absorb.
#  Prints the compile outcome; the caller escalates on 75.
#
#  The lock itself is not taken here.  It is an fcntl lock held by the qore-qo-lock
#  process that executed this script, for exactly as long as this script runs, so
#  this body has no acquire loop, no owner record, no liveness check and no
#  reclaim: the kernel releases the lock when its holder exits, however it exits.
#  What used to be here was a hard link plus a one-second poll, and every piece of
#  the machinery around it existed only because a hard link outlives its owner.
run_locked_component() (
    selected_preload_file=
    manifest_input_file=
    compile_plan_file=
    expected_graph=

    cleanup_locked_component() {
        if [ -n "$selected_preload_file" ]; then
            rm -f "$selected_preload_file"
        fi
        if [ -n "$manifest_input_file" ]; then
            rm -f "$manifest_input_file"
        fi
        if [ -n "$compile_plan_file" ]; then
            rm -f "$compile_plan_file"
        fi
    }
    trap cleanup_locked_component EXIT
    trap 'exit 1' HUP INT TERM


    # Another waiter may have published this exact component while this process
    # was blocked.  Resolve currency, the compare-and-swap source token, the
    # transitive preload, and direct manifest inputs from one graph snapshot.
    # Starting the source-order helper separately for each answer makes a large
    # group rescan every member depfile several times for one tiny rebuild.
    if have_source_order && [ -n "$component_selector" ]; then
        compile_plan_file=$(mktemp "${TMPDIR:-/tmp}/qore-qo-compile-plan.XXXXXX")
        # The plan fails with 76 when the component key no longer names a
        # component, which is a graph transition rather than a bad argument, so
        # its status is propagated instead of being flattened to a generic
        # failure the caller cannot act on.
        if prepare_component_compile_plan "$compile_plan_file"; then
            plan_rc=0
        else
            plan_rc=$?
        fi
        if [ "$plan_rc" -ne 0 ]; then
            exit "$plan_rc"
        fi
        plan_current=$(awk -F '\t' '$1 == "current" { print $2; exit }' \
            "$compile_plan_file")
        case "$plan_current" in
            1)
                exit 0
                ;;
            0)
                expected_sources=$(awk -F '\t' \
                    '$1 == "source-token" { print $2; exit }' \
                    "$compile_plan_file")
                if [ -z "$expected_sources" ]; then
                    echo "$0: compile plan omitted the source token for $output" >&2
                    exit 1
                fi
                # The graph the preload below was selected from.  Publication
                # refuses to commit against any other one, so an artifact
                # compiled against a superseded preload cannot be published as
                # if it had been planned against the graph that replaced it.
                expected_graph=$(awk -F '\t' \
                    '$1 == "graph-generation" { print $2; exit }' \
                    "$compile_plan_file")
                ;;
            *)
                echo "$0: invalid compile plan for $output" >&2
                exit 1
                ;;
        esac
    else
        if accept_current_component; then
            exit 0
        fi
        # The member sources this compile is about to read. Publication is
        # refused if they move away from this snapshot.
        expected_sources=$(component_source_token) || exit 1
    fi

    selected_preload_file=$(mktemp "${TMPDIR:-/tmp}/qore-qo-selected.XXXXXX")
    if ! select_preload_outputs "$selected_preload_file" \
            "$compile_plan_file" "$@"; then
        exit 1
    fi

    manifest_input_file=$(mktemp "${TMPDIR:-/tmp}/qore-qo-manifest.XXXXXX")
    if ! select_manifest_inputs "$manifest_input_file" "$compile_plan_file"; then
        exit 1
    fi

    if compile_single_member "$selected_preload_file" "$manifest_input_file"; then
        compile_rc=0
    else
        compile_rc=$?
    fi
    if [ "$compile_rc" -ne 0 ]; then
        exit "$compile_rc"
    fi

    if ! have_source_order || [ -z "$component_selector" ]; then
        exit 0
    fi
    if publish_component "$expected_sources" "$expected_graph" >&2; then
        publish_rc=0
    else
        publish_rc=$?
    fi
    exit "$publish_rc"
)

#! True when this group is configured with a shared parse.
#  CMake configures the batch script, the batch bootstrap stamp and the plan
#  target together, and only for a group with more than one source, so this also
#  answers whether the group has a coordinator at all.
have_group_batch() {
    [ -n "$batch_bootstrap_stamp" ] && [ -f "$batch_script" ] \
        && [ -x "$batch_bootstrap_tool" ]
}

#! Runs the group's shared parse, which writes and publishes every component.
#  The batch takes the GROUP lock rather than a component lock, because it is the
#  only builder that writes members it was not asked for.  Several callers can
#  ask for it at once: only the lock holder compiles, and the rest find the
#  generation current and return.
run_group_batch() {
    if ! have_group_batch; then
        echo "$0: the group has no batch compile script, so its shared parse" \
            "cannot be started; component $component_key cannot be published as" \
            "part of a coherent generation" >&2
        return 1
    fi
    # No frozen graph: the batch compiles every member of every component under
    # the group lock, so nothing can be reading a decomposition it invalidates,
    # and it must publish against the graph its own compiles produce.
    QORE_QCC_GRAPH_SNAPSHOT= \
    QORE_QCC_REQUIRE_BATCH=1 \
        QORE_QCC_QORE_EXECUTABLE="${QORE_QCC_QORE_EXECUTABLE:-}" \
        "$batch_bootstrap_tool" "$context_file" "$batch_bootstrap_stamp" \
            "$batch_script" "$source_order_tool"
}

#! Rebuilds this component's members through one shared parse over just them.
#  Its members are mutually dependent, so they have no valid internal order and
#  no standalone builder; every other member of the group is current as far as
#  this recipe is concerned and is preloaded rather than recompiled.  Falls back
#  to the whole-group parse when the group was configured without a subset script.
run_component_parse() {
    if ! have_group_batch; then
        echo "$0: the group has no batch compile script, so its shared parse" \
            "cannot be started; component $component_key cannot be published as" \
            "part of a coherent generation" >&2
        return 1
    fi
    # See qore-qo-incremental-plan for what selects this and what it costs.
    if [ "${QORE_QCC_SUBSET_PARSE:-0}" != 1 ] || [ -z "$subset_script" ] \
            || [ ! -f "$subset_script" ] || [ -z "$component_selector" ]; then
        run_group_batch
        return $?
    fi
    component_members=$(mktemp "${TMPDIR:-/tmp}/qore-qo-component-members.XXXXXX")
    component_plan=$(mktemp "${TMPDIR:-/tmp}/qore-qo-component-plan.XXXXXX")
    if ! run_scoped_source_order --scc-members "$context_file" \
            "$component_selector" > "$component_members"; then
        rm -f "$component_members" "$component_plan"
        return 1
    fi
    awk -F '\t' -v key="$component_key" 'NF >= 2 { print key "\t" $1 "\t" $2 }' \
        "$component_members" > "$component_plan"
    rm -f "$component_members"
    QORE_QCC_GRAPH_SNAPSHOT= \
    QORE_QCC_SUBSET_PLAN="$component_plan" \
    QORE_QCC_SUBSET_SCRIPT="$subset_script" \
        QORE_QCC_QORE_EXECUTABLE="${QORE_QCC_QORE_EXECUTABLE:-}" \
        "$batch_bootstrap_tool" "$context_file" "$batch_bootstrap_stamp" \
            "$batch_script" "$source_order_tool"
    component_parse_rc=$?
    rm -f "$component_plan"
    if [ "$component_parse_rc" -eq 0 ]; then
        return 0
    fi
    # See qore-qo-incremental-plan: a parse of part of a group resolves what it
    # did not compile from `.qo` shells, and a shell can carry a declaration the
    # parse itself makes.  The group's own parse has no shells.
    echo "$0: the shared parse of component $component_key failed; falling back" \
        "to the group's own parse" >&2
    run_group_batch
}

#! Rebuilds every member of every component in the group through one shared parse.
#  A component with more than one member has no valid internal order, so its
#  members cannot be compiled separately against each other.  The group batch is
#  the existing mechanism that parses many sources at once.
build_group_batch() {
    # A group coordinator schedules every stale multi-member component into the
    # shared parse before the object recipes it plans for, so reaching here
    # behind one used to be treated as a contradiction and reported as a build
    # failure.  It is not one.  The claim an object recipe carries says the group
    # HAS a coordinator, not that the coordinator has already run: whether it is
    # reached first depends on how the consuming project asks for the objects,
    # and a project that depends on the object stamps as files rather than on the
    # group's order targets reaches the recipes first.  The plan can also have
    # been left behind entirely -- its stamp lives beside the build scripts while
    # the generations it describes live beside the objects, so removing the object
    # directory leaves the stamp asserting a currency that no longer exists.
    #
    # Either way this component spans several sources, which means it has no
    # valid internal order and no standalone builder at all.  The shared parse is
    # the only thing that can compile it, and refusing to start it only turned a
    # schedule this recipe cannot control into a failed build.
    if [ "$coordinator_scheduled" = 1 ]; then
        echo "$0: component $component_key spans $component_size sources and is" \
            "stale although the group has a coordinator; starting a shared parse" \
            "of its members from here, because a component spanning several" \
            "sources has no standalone builder"
        # Everything the claim authorises -- the narrowed currency rule, the
        # skipped prerequisite pass -- is only sound while the plan holds for this
        # component, and it does not.
        coordinator_scheduled=0
        currency_scope=
    else
        echo "$0: component $component_key spans $component_size sources;" \
            "delegating to a shared parse of its members"
    fi
    run_component_parse
}

#! Brings every transitive predecessor component current, in dependency order.
#  One member per component is enough: the component is the unit of work, so
#  building any member brings all of them current.
build_prerequisites() {
    # `$coordinator_scheduled`, not the environment variable it was read from:
    # the claim it carries can be abandoned during this run, and the environment
    # still says otherwise.
    if [ "${QORE_QCC_PREREQUISITES_READY:-0}" = 1 ] \
            || [ "$coordinator_scheduled" = 1 ] \
            || ! have_source_order \
            || [ -z "$component_selector" ]; then
        return 0
    fi

    prerequisite_map=$(mktemp "${TMPDIR:-/tmp}/qore-qo-prerequisites.XXXXXX")
    if ! run_source_order --scc-prerequisites "$context_file" "$component_selector" \
            > "$prerequisite_map"; then
        rm -f "$prerequisite_map"
        return 1
    fi

    tab=$(printf '\t')
    rc=0
    while IFS="$tab" read -r prerequisite_index prerequisite_key; do
        [ -n "$prerequisite_key" ] || continue
        # The key, not the index: each member lookup is a separate process, and
        # a prerequisite compiled by an earlier iteration rewrites its depfile,
        # which can renumber every component the remaining iterations name.
        member_line=$(run_source_order --scc-members "$context_file" \
            "$prerequisite_key" | head -1) || { rc=1; break; }
        prerequisite_source=$(printf '%s' "$member_line" | cut -f1)
        prerequisite_output=$(printf '%s' "$member_line" | cut -f2)
        [ -n "$prerequisite_source" ] || continue
        [ -n "$prerequisite_output" ] || continue
        if ! QORE_QCC_PREREQUISITES_READY=1 \
                QORE_QCC_PREREQUISITES_ORDERED="$coordinator_scheduled" \
                QORE_QCC_BATCH_BOOTSTRAP_STAMP="$batch_bootstrap_stamp" \
                "$this_script" "$prerequisite_output" "$prerequisite_source" \
                    "$single_script"; then
            echo "$0: cannot bring prerequisite component $prerequisite_key current" \
                "for $component_key" >&2
            rc=1
            break
        fi
    done < "$prerequisite_map"
    rm -f "$prerequisite_map"
    return "$rc"
}

#! The lock covering every member of the component this recipe publishes.
#  Resolving it is itself a graph query, so it can report a transition (76) just
#  as the compile plan and the publication can; that status is propagated rather
#  than flattened, because the caller's response to it is to re-resolve.
resolve_component_lock() {
    component_lock="$output.lock"
    if [ -n "$component_lock_hint" ]; then
        component_lock=$component_lock_hint
        return 0
    fi
    if ! have_source_order || [ -z "$component_selector" ]; then
        return 0
    fi
    if resolved_lock=$(run_source_order --scc-lock "$context_file" \
            "$component_selector"); then
        component_lock=$resolved_lock
        return 0
    else
        return $?
    fi
}

#! Runs one locked attempt at building the component, and returns its status.
#  The lock has to be held by a process that lives for the whole critical section,
#  and a POSIX shell cannot hold an fcntl lock, so this re-executes the script
#  under qore-qo-lock rather than taking a lock and continuing.  The re-execution
#  is given the identity this process resolved -- not the one the planner passed,
#  which a graph transition may already have superseded -- so the locked run
#  resolves exactly the same component without querying the graph again.
#
#  Its argument vector is this recipe's own, unchanged, which is what makes the
#  round trip faithful: OUTPUT, SOURCE, SINGLE_SCRIPT and the preload objects.
with_component_lock() {
    if [ ! -f "$lock_tool" ]; then
        echo "$0: missing qcc lock helper: $lock_tool" >&2
        return 1
    fi
    mkdir -p "$(dirname "$component_lock")"
    # Named the same way the source-order helper is: a build that is testing a
    # qore it has not installed must not reach a different one through the
    # helper's shebang.
    if [ -n "${QORE_QCC_QORE_EXECUTABLE:-}" ] \
            && [ -x "$QORE_QCC_QORE_EXECUTABLE" ]; then
        QORE_QCC_COMPONENT_INDEX="$component_index" \
        QORE_QCC_COMPONENT_KEY="$component_key" \
        QORE_QCC_COMPONENT_SIZE="$component_size" \
        QORE_QCC_COMPONENT_LOCK="$component_lock" \
        QORE_QCC_LOCKED_COMPONENT=1 \
            "$QORE_QCC_QORE_EXECUTABLE" "$lock_tool" "$component_lock" \
            "$this_script" "$output" "$source" "$single_script" "$@"
        return $?
    fi
    QORE_QCC_COMPONENT_INDEX="$component_index" \
    QORE_QCC_COMPONENT_KEY="$component_key" \
    QORE_QCC_COMPONENT_SIZE="$component_size" \
    QORE_QCC_COMPONENT_LOCK="$component_lock" \
    QORE_QCC_LOCKED_COMPONENT=1 \
        "$lock_tool" "$component_lock" "$this_script" \
        "$output" "$source" "$single_script" "$@"
}

#! Makes the component current, rebuilding the whole component at most once more.
#  The single rebuild is not a convergence loop.  It answers one of exactly two
#  conditions, which are deliberately reported apart because they have nothing in
#  common but their timing:
#
#    75  an agent outside the build mutated a member source while qcc was
#        reading it, which no amount of analysis can order;
#    76  the build's own dependency graph moved between planning and
#        publication, so the compile may have used a preload the current graph
#        would not have chosen.  Identity is re-resolved from the current graph
#        before the retry, because everything resolved from the superseded one
#        -- key, size, lock -- may now name a different unit of work.
#
#  Neither is retried more than once: a second occurrence means the input is
#  changing faster than the build can read it, and repeating the compile would
#  only make correctness depend on winning a race.
build_component() {
    attempt=1
    while :; do
        if [ "$component_size" -gt 1 ]; then
            build_group_batch
            return $?
        fi
        if resolve_component_lock; then
            rc=0
        else
            rc=$?
        fi
        if [ "$rc" -eq 0 ]; then
            # `$?` after a completed `if` is the status of the compound command,
            # which is 0 whenever an unmatched condition ran no branch -- so the
            # build status has to be captured in an else branch, never read back
            # after the `if` that tested it.
            if with_component_lock "$@"; then
                rc=0
            else
                rc=$?
            fi
            if [ "$rc" -eq 0 ]; then
                return 0
            fi
        fi
        if [ "$rc" -ne 75 ] && [ "$rc" -ne 76 ]; then
            return "$rc"
        fi
        if [ "$attempt" -ge 2 ]; then
            if [ "$rc" -eq 75 ]; then
                echo "$0: inputs of component $component_key moved during its" \
                    "rebuild; the sources are being changed by something other" \
                    "than this build" >&2
            else
                echo "$0: the dependency graph moved again while component" \
                    "$component_key was rebuilt; the build's own depfiles are not" \
                    "stable for the duration of a compile" >&2
            fi
            return 1
        fi
        if [ "$rc" -eq 75 ]; then
            echo "$0: inputs of component $component_key moved during compilation;" \
                "rebuilding the component once"
        else
            echo "$0: the dependency graph changed while component $component_key" \
                "was compiled; re-resolving its identity and rebuilding it once"
            # The loop head re-checks the member count and re-resolves the lock
            # from whatever this reports, so a component that gained members in
            # the transition is handed to the shared parse rather than compiled
            # as a singleton it no longer is.
            resolve_component_live || return 1
        fi
        attempt=$((attempt + 1))
    done
}

run_main() {
    resolve_component || true

    # The group coordinator has already performed one group-wide currency pass
    # and ordered every stale component.  Repeating the unlocked current and
    # prerequisite queries here reloads the same graph without adding a
    # correctness check; the locked compile plan below still handles a builder
    # that won the race and published this component first.
    if [ "$planned_stale" = 1 ] && [ -n "$component_selector" ]; then
        build_component "$@"
        exit $?
    fi

    if accept_current_component; then
        exit 0
    fi

    if ! build_prerequisites; then
        exit 1
    fi

    # A predecessor can become current without changing its compile contract.
    # Recheck after the ordered handoff so dependents avoid preload setup and
    # qcc startup when their executable assumptions remain valid.
    if accept_current_component; then
        exit 0
    fi

    build_component "$@"
}

# The locked half of one build attempt, re-executed by with_component_lock() under
# the component's lock.  It runs exactly one attempt and returns its status; the
# retry that answers a 75 or a 76 belongs to the unlocked caller, which has to
# re-resolve the component's identity before trying again.
if [ "${QORE_QCC_LOCKED_COMPONENT:-}" = 1 ]; then
    resolve_component || true
    run_locked_component "$@"
    exit $?
fi

run_main "$@"
