#!/bin/sh
#
# Copyright (C) 2003 - 2026 Qore Technologies, s.r.o.
#
# Seed a standalone qcc object group with one shared-parse batch compile.
#
# This is also the builder for any strongly connected component that spans more
# than one source: its members are mutually dependent, so they have no valid
# relative order and must share one parse.  The batch writes every member of
# every component in the group, which is why it holds the GROUP lock rather than
# a component lock, and why it publishes every component's generation record
# when it completes.  `qore-qo-incremental` delegates here with
# QORE_QCC_FORCE_BATCH=1 when a multi-member component is stale.

set -eu

if [ "$#" -ne 4 ]; then
    echo "usage: $0 CONTEXT BOOTSTRAP_STAMP BATCH_SCRIPT SOURCE_ORDER_HELPER" >&2
    exit 2
fi

context=$1
bootstrap_stamp=$2
batch_script=$3
source_order_tool=$4
lock_path="${bootstrap_stamp}.lock"
# The helpers are installed side by side, so the group lock helper is found beside
# this one rather than threaded through every caller's argument list.
lock_tool=${QORE_QCC_LOCK_HELPER:-$(dirname "$0")/qore-qo-lock}
outputs_file=
# The ordering token's state before this run advanced it, and whether the run
# reached its publication.
#
# Currency treats a member whose stamp is older than the ordering token as
# belonging to a previous bootstrap, so advancing the token marks the WHOLE group
# stale until a publication touches every member stamp again.  A parse that fails
# -- a syntax error in one source, the common case while editing -- publishes
# nothing and touches no member stamp, so leaving the token advanced converted a
# one-component rebuild into a whole-group one: the next build found every member
# older than the token, and the build after that recompiled all of them.  A failed
# parse must leave the tree exactly as it found it.
saved_stamp=
stamp_existed=false
token_committed=false
# When this group last published a whole-group generation.
#
# The bootstrap stamp cannot say that.  It is also the build tool's ordering
# token, so it is touched by runs of this helper that publish nothing: CMake's
# Makefile generator duplicates this recipe into every independent target that
# depends on the stamp, and with a parallel build the copy that loses the race to
# the group lock finds the tree the winner published current and touches the stamp
# so no member stays older than its dependencies.  That touch is invisible to the
# build, but it moved the marker the frozen dependency graph is compared against,
# and it can land after the coordinator's last freeze -- which then names a
# publication the group no longer reports, and every later build discards an edge
# set that is still exact.
#
# This file is advanced only by a shared parse -- the one operation that rewrites
# every depfile in the group -- and never by a run that compiles nothing.
publication_marker="${bootstrap_stamp}.publication"
# One shared parse over PART of the group: the plan file names the components to
# compile and publish, one `KEY<TAB>SOURCE<TAB>OUTPUT` row per member.
#
# The group lock covers it exactly as it covers a whole-group parse -- the parse
# writes members the caller did not ask for only in the sense that a component
# spans several -- but nothing else about the group changes: the ordering token
# is not advanced, no whole-group publication is dated, and the components that
# were not compiled keep the generation they had.
subset_plan=${QORE_QCC_SUBSET_PLAN:-}
subset_script=${QORE_QCC_SUBSET_SCRIPT:-}
subset_keys=
subset_convex_keys=
subset_convex_plan=
subset_preloads=
subset_preload_dir=
# When set, names a file this script fills with the keys of the stale components it left for the
# caller's next pass; see run_subset_parse().
subset_deferred_file=${QORE_QCC_SUBSET_DEFERRED:-}
current_stamps=
currency_file=
member_stamps=
# Set by qore-qo-incremental when the group holds a component that spans several
# sources. It does NOT skip the currency check -- doing so made every member of
# one component force its own redundant batch -- it only says that a batch
# failure is fatal, because such a component has no per-source fallback.
require_batch=${QORE_QCC_REQUIRE_BATCH:-0}
# A group coordinator has already completed the source-generation currency
# pass. The first lock owner may proceed directly; a process that had to wait
# must recheck because the preceding owner may have completed the same build.
force_batch=${QORE_QCC_FORCE_BATCH:-0}
lock_waited=false
# Whether this run may answer a partly stale group by handing the stale set to
# the group coordinator instead of parsing the group.
#
# It may only do so for the CMake bootstrap recipe, which is scheduled BEFORE
# the coordinator: for that caller the hand-off is the whole point, because the
# coordinator is a separate process that runs next and decides how to rebuild
# the set it was given.
#
# Every other caller reached here by asking for the group's own parse and reads
# a successful exit as proof that it ran.  There is no coordinator downstream of
# them to receive a hand-off -- one of them IS the coordinator -- so answering
# them with one returns success having compiled nothing:
#
#   * qore-qo-incremental-plan escalates to the group's parse from the rebuild
#     CLOSURE, then verifies.  Handed its own stale set back, it finds the
#     components it asked to have parsed still stale and fails the build with
#     "shared-parse incremental build left stale components" -- a hard failure
#     naming no source, on a tree that builds on the next attempt.
#   * qore-qo-incremental reaches the group's parse for a component that spans
#     several sources, which has no standalone builder at all.  Handed its own
#     stale set back, that recipe exits 0 without compiling or publishing
#     anything, and the object it was asked for is silently not built.
#
# The two callers reach the re-check by different routes -- the coordinator only
# when it waited for the group lock, the object recipe on every run -- but the
# answer is the same for both: a caller that asked for the group's parse gets
# it.  Note that this does not skip the re-check, only its hand-off outcome: a
# follower that finds the group CURRENT still adopts the tree the holder it
# waited behind published, which is what keeps concurrent callers to one parse.
if [ "$force_batch" = 1 ] || [ "$require_batch" = 1 ]; then
    handoff_available=false
else
    handoff_available=true
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
}

#! Removes PATH, tolerating a remover that got there first.
#  The caller wants a state -- PATH gone -- rather than the act of removing it,
#  and it can race another builder that decided the same thing.  `rm -f` alone
#  does not express that: it swallows a path that was already missing when it
#  looked, but busybox reports an ENOENT unlink that follows a successful lstat
#  and exits non-zero, so the caller that loses the race by microseconds fails --
#  and under `set -e` that ends the build.  GNU coreutils ignores the same errno,
#  which is why this shape only ever fails on musl/busybox hosts.  A removal that
#  fails for any other reason is still an error and is still reported.
#
#  The lock paths this used to serve are gone: an fcntl lock is released by the
#  kernel, so nothing reclaims one and nothing unlinks one.  What is left is the
#  ordering token, which a run that published nothing must put back.
remove_raced_path() {
    if rm -f "$1" 2>/dev/null; then
        return 0
    fi
    if [ ! -e "$1" ] && [ ! -L "$1" ]; then
        return 0
    fi
    # Still there, so this was not the race: repeat the removal without
    # suppressing it, and let the utility say why it cannot be done.
    rm -f "$1"
}

#! Undoes this run's advance of the ordering token when it published nothing.
#  Publication is all-or-nothing -- the batch touches no member stamp and writes
#  no generation record until every object has been emitted -- so a run that did
#  not reach it has changed nothing the token needs to dominate.
restore_ordering_token() {
    if [ "$token_committed" = true ] || [ -z "$saved_stamp" ]; then
        return 0
    fi
    if [ "$stamp_existed" = true ]; then
        touch -r "$saved_stamp" "$bootstrap_stamp" 2>/dev/null || true
    else
        remove_raced_path "$bootstrap_stamp"
    fi
}

#! Records the ordering token's state so a run that publishes nothing can undo it.
save_ordering_token() {
    if [ -n "$saved_stamp" ]; then
        return 0
    fi
    saved_stamp="${bootstrap_stamp}.pre.$$"
    if [ -f "$bootstrap_stamp" ]; then
        stamp_existed=true
        # -p for the modification time: that timestamp IS the saved state.
        cp -p "$bootstrap_stamp" "$saved_stamp"
    else
        stamp_existed=false
        : > "$saved_stamp"
    fi
}

#! Keeps this run's advance of the ordering token: it published or adopted a tree.
commit_ordering_token() {
    token_committed=true
}

cleanup() {
    restore_ordering_token
    if [ -n "$saved_stamp" ]; then
        rm -f "$saved_stamp"
    fi
    if [ -n "$subset_keys" ]; then
        rm -f "$subset_keys"
    fi
    if [ -n "${subset_convex_keys:-}" ]; then
        rm -f "$subset_convex_keys"
    fi
    if [ -n "${subset_convex_plan:-}" ]; then
        rm -f "$subset_convex_plan"
    fi
    if [ -n "${currency_file:-}" ]; then
        rm -f "$currency_file"
    fi
    if [ -n "${current_stamps:-}" ]; then
        rm -f "$current_stamps"
    fi
    if [ -n "${member_stamps:-}" ]; then
        rm -f "$member_stamps"
    fi
    if [ -n "${subset_preloads:-}" ]; then
        rm -f "$subset_preloads"
    fi
    if [ -n "${subset_preload_dir:-}" ]; then
        rm -rf "$subset_preload_dir"
    fi
    if [ -n "$outputs_file" ]; then
        rm -f "$outputs_file"
    fi
    # The group lock is not removed here, or anywhere: it is an fcntl lock held by
    # the process that re-executed this script, and the kernel drops it when that
    # process exits.  Unlinking the path while another builder holds a lock on the
    # inode would let the next waiter create a new one and enter the critical
    # section alongside the holder.
}
trap cleanup EXIT
trap 'exit 1' HUP INT TERM

if [ ! -f "$context" ]; then
    echo "$0: missing qcc context: $context" >&2
    exit 1
fi
if [ ! -f "$batch_script" ]; then
    echo "$0: missing qcc batch script: $batch_script" >&2
    exit 1
fi
if [ ! -x "$source_order_tool" ]; then
    echo "$0: missing qcc source-order helper: $source_order_tool" >&2
    exit 1
fi

mkdir -p "$(dirname "$bootstrap_stamp")"

# Enter the group's critical section by re-executing this script under an
# exclusive fcntl lock, rather than by publishing a hard link and polling for it.
#
# The poll was not just slow.  A hard link outlives the process that made it, so a
# waiter had to decide whether an existing lock was abandoned -- read the owner pid
# out of the record, ask whether it was alive, compare-and-remove if it was not,
# and recognise the lock shapes older versions of this helper published -- and that
# reclaim could not be made exclusive, so two waiters removing one abandoned lock
# had to be defined as normal operation.  An fcntl lock is owned by the kernel and
# released when its holder exits however it exits, so none of that state exists.
#
# The lock is held by the process that execs this one, for exactly as long as this
# script runs.  Everything above this point is argument checking that is safe to do
# twice; everything below it is the critical section, which is what the lock was
# always taken for.  QORE_QO_LOCK_WAITED is the helper's result and may already be
# present from an outer lock, so only the private re-exec marker proves this group
# lock is held.
if [ "${QORE_QCC_LOCKED_BATCH:-}" != 1 ]; then
    if [ ! -f "$lock_tool" ]; then
        echo "$0: missing qcc lock helper: $lock_tool" >&2
        exit 1
    fi
    # 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_LOCKED_BATCH=1 \
            exec "$QORE_QCC_QORE_EXECUTABLE" "$lock_tool" "$lock_path" "$0" "$@"
    fi
    QORE_QCC_LOCKED_BATCH=1 \
        exec "$lock_tool" "$lock_path" "$0" "$@"
fi

# A follower that waited for the lock must re-check what it came to do: the holder
# it waited behind may have published exactly that.  The helper reports contention
# from a non-blocking attempt made before it blocked, so this is observed rather
# than inferred from how long the wait took.
if [ "$QORE_QO_LOCK_WAITED" = 1 ]; then
    lock_waited=true
fi

outputs_file=$(mktemp "${TMPDIR:-/tmp}/qore-qo-batch-outputs.XXXXXX")
sed -n 's/^output=//p' "$context" > "$outputs_file"

#! Dates a whole-group generation change, superseding every frozen edge set.
#  Called once before the shared parse -- a parse that fails part way through has
#  still rewritten depfiles, so a graph frozen before it must not survive either --
#  and once after the publication, so that the coordinator's next freeze records
#  the date the published tree actually carries.
date_generation_change() {
    touch "$publication_marker"
}

#! Dates a tree this run adopted rather than compiled, if nothing else has.
#  Adoption rewrites no depfile, so it must never supersede a frozen edge set.
#  Creating the marker when it is missing only gives a tree published before this
#  helper knew to date it a date that later freezes can be compared against; until
#  then no snapshot can be applied at all.
adopt_generation() {
    if [ ! -f "$publication_marker" ]; then
        touch "$publication_marker"
    fi
}

#! Writes the group's member success stamps, one path per line, once.
member_stamp_list() {
    if [ -n "$member_stamps" ]; then
        return 0
    fi
    member_stamps=$(mktemp "${TMPDIR:-/tmp}/qore-qo-batch-stamps.XXXXXX")
    awk 'NF { print $0 ".stamp" }' "$outputs_file" > "$member_stamps"
}

#! Dates every member success stamp.
#  One pass and one touch: a group with hundreds of members would otherwise
#  spend more time forking than the currency scan it is answering took, and
#  every fork widens the interval in which the group is half dated.
touch_member_stamps() {
    member_stamp_list
    # Never hand xargs an empty list: GNU xargs runs the command anyway, and
    # `touch` with no operand is an error that `set -e` turns into a failed
    # build.  BSD xargs does not, and only one of the two has -r.
    if [ -s "$member_stamps" ]; then
        tr '\n' '\0' < "$member_stamps" | xargs -0 touch
    fi
}

#! Adopts a tree this run found current: every member first, the token last.
#  Currency treats a member whose stamp is older than the ordering token as
#  belonging to a previous bootstrap, so a run that advances the token BEFORE it
#  dates the member stamps publishes an interval -- the whole sweep wide -- in
#  which every member it has not reached yet reads as stale to anything looking
#  at the group.  That is the same encoding the hand-off uses deliberately, so a
#  reader cannot tell the two apart: it sees a partly stale group and acts on it.
#
#  The readers are not hypothetical, and neither is the cost.  CMake's Makefile
#  generator duplicates this recipe into every independent target that depends on
#  the stamp, so a copy of it adopts the tree while the group coordinator is
#  verifying a whole-group parse it has just completed -- and the coordinator
#  then reports components stale that its own parse left current and fails the
#  build, naming no source and no line, on a tree that builds on the next
#  attempt.
#
#  Doing it the other way round removes the interval rather than narrowing it: at
#  no point in an adopt is any member of the group older than the token.  The
#  token is dated from the first stamp the sweep touched, which is the earliest
#  of them, and that is all this touch was ever for -- the token has to be newer
#  than the prerequisites that made the build tool run the recipe, not newer than
#  the tree it is adopting.
adopt_member_stamps() {
    touch_member_stamps
    if [ -s "$member_stamps" ]; then
        touch -r "$(head -n 1 "$member_stamps")" "$bootstrap_stamp"
    else
        touch "$bootstrap_stamp"
    fi
}

#! Compiles the components the plan names, in one parse, and publishes them.
#  Everything the parse does not compile is preloaded from the object directory
#  as sibling `.qo` declarations, which is what makes a partial parse cost what
#  the partial parse is worth rather than what the group is worth.
run_subset_parse() {
    subset_keys=$(mktemp "${TMPDIR:-/tmp}/qore-qo-subset-keys.XXXXXX")
    awk -F '\t' 'NF && $1 != "" { print $1 }' "$subset_plan" | sort -u > "$subset_keys"
    if [ ! -s "$subset_keys" ]; then
        echo "$0: subset plan names no component: $subset_plan" >&2
        return 1
    fi
    # A follower that waited for the lock may find the components it was asked
    # for already published by the holder; the whole-group parse re-checks the
    # same way.
    if [ "$lock_waited" = true ]; then
        if run_source_order --scc-current-set "$context" "$subset_keys"; then
            return 0
        fi
    fi

    # Only the part of the stale set that one parse can compile consistently.  A
    # preloaded `.qo` is what its source compiled to against the previous generation
    # of everything it depends on, so a stale component that preloads an object
    # compiled against ANOTHER stale component in the same parse gets that
    # component's previous declarations back, shadowing the ones the parse makes
    # ("INVALID-MEMBER: 'type' is not a registered member of class ...").  Such a
    # component is left stale and compiled by the next pass, once what it preloads
    # has been rebuilt against the new declarations.
    subset_convex_keys=$(mktemp "${TMPDIR:-/tmp}/qore-qo-subset-convex.XXXXXX")
    if run_source_order --scc-convex-set "$context" "$subset_keys" > "$subset_convex_keys"; then
        :
    else
        return $?
    fi
    if [ ! -s "$subset_convex_keys" ]; then
        echo "$0: no part of the subset plan can be compiled in one parse: $subset_plan" >&2
        return 1
    fi
    if [ -n "$subset_deferred_file" ]; then
        # sorted like the keys file, which is what comm needs
        sort -u "$subset_convex_keys" | comm -23 "$subset_keys" - > "$subset_deferred_file"
    fi
    subset_deferred_count=$(sort -u "$subset_convex_keys" | comm -23 "$subset_keys" - | wc -l | tr -d ' ')
    if [ "$subset_deferred_count" -gt 0 ]; then
        echo "$0: leaving $subset_deferred_count stale component(s) for the next pass: each would preload" \
            "an object compiled against another component this parse recompiles"
        subset_convex_plan=$(mktemp "${TMPDIR:-/tmp}/qore-qo-subset-plan.XXXXXX")
        awk -F '\t' 'NR == FNR { keep[$1] = 1; next } keep[$1]' \
            "$subset_convex_keys" "$subset_plan" > "$subset_convex_plan"
        subset_plan=$subset_convex_plan
        sort -u "$subset_convex_keys" > "$subset_keys"
    fi

    subset_count=$(awk -F '\t' 'NF && $2 != ""' "$subset_plan" | wc -l | tr -d ' ')
    group_count=$(awk 'NF' "$outputs_file" | wc -l | tr -d ' ')
    echo "$0: compiling $subset_count of $group_count sources in one shared parse"

    # What the parse resolves against: the transitive predecessors of the
    # components it compiles, and nothing else.
    #
    # Not the whole object directory.  A `.qo` carries every declaration it was
    # compiled against, including ones made in OTHER sources, so preloading a
    # CONSUMER of a source this parse compiles brings that source's own
    # declarations back -- and the parse can then no longer make them ("enum 'X'
    # conflicts with existing namespace 'X'").  The per-file path has always
    # staged its preloads this way; a parse of several sources needs the union.
    subset_preloads=$(mktemp "${TMPDIR:-/tmp}/qore-qo-subset-preloads.XXXXXX")
    if ! run_source_order --scc-preload-set "$context" "$subset_keys" \
            > "$subset_preloads"; then
        subset_preload_rc=$?
        rm -f "$subset_preloads"
        subset_preloads=
        return $subset_preload_rc
    fi
    subset_preload_dir=$(mktemp -d "$(dirname "$bootstrap_stamp")/../.qcc-preload.subset.XXXXXX")
    while IFS= read -r preload_qo; do
        [ -n "$preload_qo" ] || continue
        [ -f "$preload_qo" ] || continue
        preload_name=$(basename "$preload_qo")
        [ -e "$subset_preload_dir/$preload_name" ] && continue
        # A hard link, as the per-file path does: one coherent artifact
        # generation for the duration of this parse, immune to a concurrent
        # provider's atomic replacement.
        ln "$preload_qo" "$subset_preload_dir/$preload_name"
        if [ -f "$preload_qo.compile-contract.stamp" ]; then
            ln -s "$preload_qo.compile-contract.stamp" \
                "$subset_preload_dir/$preload_name.compile-contract.stamp"
        fi
        if [ -f "$preload_qo.idx.json" ]; then
            ln "$preload_qo.idx.json" "$subset_preload_dir/$preload_name.idx.json"
        fi
    done < "$subset_preloads"
    rm -f "$subset_preloads"
    subset_preloads=

    tab=$(printf '\t')
    set -- "$subset_preload_dir"
    while IFS="$tab" read -r subset_key subset_source subset_output; do
        [ -n "$subset_source" ] || continue
        set -- "$@" "$subset_source"
    done < "$subset_plan"
    if [ "$#" -eq 0 ]; then
        echo "$0: subset plan names no source: $subset_plan" >&2
        return 1
    fi
    if ! sh "$subset_script" "$@"; then
        return 1
    fi
    # The parse rewrote every member it was given, so their stamps and their
    # components' generation records are committed together -- the same rule the
    # whole-group parse follows, applied to the part that was compiled.
    while IFS="$tab" read -r subset_key subset_source subset_output; do
        [ -n "$subset_output" ] || continue
        touch "$subset_output.stamp"
    done < "$subset_plan"
    # The status matters to the caller: a graph transition means "re-plan", while
    # anything else means the parse did not publish what it compiled.
    # `$?` after a completed `if` is the compound's status, not the condition's,
    # so the publish status has to be captured in the else branch.
    if run_source_order --scc-publish-set "$context" "$subset_keys"; then
        return 0
    else
        return $?
    fi
}

if [ -n "$subset_plan" ]; then
    if [ ! -f "$subset_plan" ]; then
        echo "$0: missing subset plan: $subset_plan" >&2
        exit 1
    fi
    if [ -z "$subset_script" ] || [ ! -f "$subset_script" ]; then
        echo "$0: missing subset compile script: ${subset_script:-<unset>}" >&2
        exit 1
    fi
    run_subset_parse
    exit $?
fi

# Currency is a property of every component's published generation, not of a
# per-file sidecar sweep: the whole point of the generation record is that one
# token comparison covers a component's entire transitive source closure.  A
# follower that waited on the lock re-evaluates it here, so a stale marker can
# never hide a crashed or incomplete bootstrap.
#
# The currency helper also owns the group-context generation transition, which a
# `[ "$context" -nt "$bootstrap_stamp" ]` test used to decide here.  Do not move
# that comparison back into the shell: POSIX only requires test(1) to compare
# st_mtime, so busybox ash -- /bin/sh on Alpine -- compares whole seconds, while
# dash and bash compare the nanosecond fields.  Both timestamps are produced by
# this build and are usually less than a second apart, so on busybox the
# transition was invisible whenever the machine was fast enough to publish both
# inside one second, and Make then ran the standalone qcc rule once for every
# source in the group.  The helper compares the same timestamps at full
# resolution on every platform.
current=false
partial=false
if [ "$force_batch" != 1 ] || [ "$lock_waited" = true ]; then
    currency_file=$(mktemp "${TMPDIR:-/tmp}/qore-qo-bootstrap-currency.XXXXXX")
    if [ -f "$bootstrap_stamp" ]; then
        run_source_order --scc-stale --rebuild-closure --all-members \
            --batch-stamp "$bootstrap_stamp" "$context" > "$currency_file"
    else
        run_source_order --scc-stale --rebuild-closure --all-members "$context" \
            > "$currency_file"
    fi
    group_components=$(awk -F '\t' '$1 == "rebuild-closure" { print $3; exit }' \
        "$currency_file")
    case "$group_components" in
        ''|*[!0-9]*)
            group_components=0
            ;;
    esac
    stale_components=$(awk -F '\t' '$1 != "rebuild-closure" && !seen[$2]++ { n++ }
        END { print n + 0 }' "$currency_file")
    if [ "$stale_components" -eq 0 ]; then
        current=true
    elif [ "$handoff_available" = true ] && [ "$group_components" -gt 0 ] \
            && [ "$stale_components" -lt "$group_components" ]; then
        partial=true
    fi
fi

if [ "$current" = true ] && [ -f "$bootstrap_stamp" ]; then
    # The custom command can be rerun because an orchestration helper changed
    # even though the published object generation is still current.  Acknowledge
    # that dependency generation once for the whole group; otherwise every
    # member stamp remains older than the helper and Make launches the
    # standalone wrapper for every source.
    adopt_generation
    adopt_member_stamps
    rm -f "$currency_file"
    exit 0
fi

if [ "$partial" = true ]; then
    # Part of the group is stale, and the group coordinator that runs right after
    # this recipe is what decides how to rebuild it: one shared parse over the
    # stale set, standalone compiles, or -- when the stale set really is the
    # group -- the whole-group parse below.  Reaching for that parse from here
    # instead, which is what this recipe used to do for ANY staleness, meant a
    # module timestamp or a handful of stale components reparsed every source in
    # the group before the coordinator was ever consulted.
    #
    # The ordering token need not already exist: a tree published before this
    # helper dated its parses has none, and creating it here is what lets the
    # hand-over be expressed at all.
    #
    # The stale set is handed on in the vocabulary the whole build already
    # speaks: every member that is NOT stale gets a stamp newer than the ordering
    # token, and every member that is keeps the older one.  That is exactly what
    # currency means by "belongs to a previous bootstrap", so the coordinator,
    # the object recipes and the build tool all see the same set -- including the
    # components this pass found stale only because a build input from OUTSIDE
    # the group moved, which the coordinator's own source-content scan cannot
    # see.
    touch "$bootstrap_stamp"
    adopt_generation
    # One pass over both lists, and one touch: a group with hundreds of members
    # would otherwise spend more time forking than the currency scan took.
    current_stamps=$(mktemp "${TMPDIR:-/tmp}/qore-qo-bootstrap-current.XXXXXX")
    awk -F '\t' 'NR == FNR {
            if ($1 != "rebuild-closure" && $5 != "") {
                stale[$5] = 1
            }
            next
        }
        NF && !($0 in stale) { print $0 ".stamp" }' "$currency_file" "$outputs_file" \
        > "$current_stamps"
    # Never hand xargs an empty list: GNU xargs runs the command anyway, and
    # `touch` with no operand is an error that `set -e` turns into a failed
    # build.  BSD xargs does not, and only one of the two has -r.
    if [ -s "$current_stamps" ]; then
        tr '\n' '\0' < "$current_stamps" | xargs -0 touch
    fi
    rm -f "$current_stamps" "$currency_file"
    commit_ordering_token
    exit 0
fi
if [ -n "${currency_file:-}" ]; then
    rm -f "$currency_file"
fi

if [ "$current" = true ]; then
    # Adopt an already-current tree whose marker was missing, without rewriting
    # any object or contract content.
    #
    # Ahead of the ordering token below, not behind it: an adopt has nothing to
    # mark stale, and advancing the token first would make the whole group read
    # as stale for the length of the sweep.  See adopt_member_stamps().
    adopt_generation
    adopt_member_stamps
    exit 0
fi

# The marker has to precede every member success stamp: a member whose stamp is
# older than the marker is treated as belonging to a previous bootstrap.  Record
# what it was first: from here the run either publishes the whole group or must
# put the marker back, because everything below it is now stale by that rule.
save_ordering_token
touch "$bootstrap_stamp"

# One shared parse for the whole group. This message is emitted exactly once per
# batch that actually runs, which is what makes "a component was built as one
# unit" observable: several members of one component can each ask for the build,
# but only the lock holder compiles, and the rest find the generation current.
echo "$0: compiling the group in one shared parse"
date_generation_change

# One rebuild, never a convergence loop.  A batch can report that its inputs
# moved only because an agent outside the build rewrote a source while qcc was
# reading it; the members of this group cannot move it, because this lock covers
# all of them.
# `$?` after a NEGATED condition is the negation's status, not the command's, so
# the batch status has to be captured in the else branch.
if sh "$batch_script"; then
    batch_rc=0
else
    batch_rc=$?
fi
if [ "$batch_rc" -eq 75 ]; then
    echo "$0: qcc batch inputs moved during compilation; rebuilding the group once"
    if sh "$batch_script"; then
        batch_rc=0
    else
        batch_rc=$?
    fi
    if [ "$batch_rc" -eq 75 ]; then
        echo "$0: qcc batch inputs moved during the group rebuild; the sources are" \
            "being changed by something other than this build" >&2
        exit 1
    fi
fi
if [ "$batch_rc" -ne 0 ]; then
    if [ "$require_batch" = 1 ]; then
        # A multi-member component has no per-source fallback: its members are
        # mutually dependent, so failing to share one parse is a hard failure
        # rather than something the per-file path could finish.
        echo "$0: batch compile failed and this group has a component that spans" \
            "several sources; there is no per-source fallback" >&2
        exit "$batch_rc"
    fi
    echo "$0: batch bootstrap failed; falling back to per-source compilation" >&2
    # The EXIT handler puts the ordering token back, so the per-source path finds
    # exactly the components that were stale before this attempt.  Leaving the
    # token advanced instead -- which is what this did while the token was also
    # the publication marker -- made every member of the group look like it
    # belonged to a previous bootstrap, so the fallback rebuilt all of them.
    exit 0
fi

# Batch parsing has no preloaded source objects, so it inherits no parse
# defines from siblings.  Clear this per-source input before later delta builds.
while IFS= read -r output; do
    [ -n "$output" ] || continue
    : > "$output.source-parse-defines"
done < "$outputs_file"
touch_member_stamps

# The batch rewrote every member of every component, so every generation record
# is committed together.  A partial sweep would leave some component claiming a
# generation the group no longer has.
run_source_order --scc-publish-all "$context"

# Every depfile in the group has been rewritten and every component record
# committed, so the date the freeze after this run reads is this one.
date_generation_change
commit_ordering_token
