summaryrefslogtreecommitdiff
path: root/round-robin-bisect.sh
blob: 6a8dc817e5fa2026e30354b76ec19730c360aa70 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
#!/bin/bash

set -ef -o pipefail

scripts=$(dirname $0)
# shellcheck source=jenkins-helpers.sh
. $scripts/jenkins-helpers.sh

# Relative artifacts are used for generation of manifests and reproduction
# instructions.
rel_artifacts=artifacts
artifacts=$(pwd)/$rel_artifacts

fresh_dir $artifacts "$artifacts/manifests/*" "$artifacts/jenkins/*"

# Process bisect-only args
convert_args_to_variables "$@"
shift "$SHIFT_CONVERTED_ARGS"

obligatory_variables bad_url bad_branch build_script current_project
declare bad_url bad_branch build_script current_project

BUILD_URL="${BUILD_URL:-$(pwd)}"
replay_log="${replay_log-}"
reproduce_bisect="${reproduce_bisect:-false}"

# Process build args and record them in build-parameters.sh
convert_args_to_variables ^^ $reproduce_bisect %% $artifacts/manifests/build-parameters.sh "$@"
$reproduce_bisect || manifest_pop

obligatory_variables rr[ci_project] rr[ci_config]
declare -A rr

verbose="${verbose-true}"

set -u

if $verbose; then set -x; fi

mkdir -p $artifacts/jenkins
touch $artifacts/jenkins/build-name

trap print_traceback EXIT

rebase_workaround=false
rebase_workaround_opts=()

case "${rr[ci_project]}/${rr[ci_config]}:$current_project" in
    tcwg_kernel/*-next-*:linux)
	# Workaround linux-next/master rebasing on top of linux-next/stable.
	# Search for regressions against linux-mainline:master (aka linux-next:stable).
	clone_or_update_repo $current_project stable $bad_url
	# Just in case linux-next:stable has advanced between the build and bisect jobs,
	# use merge base between linux-next:stable and $bad_branch.
	bad_rev="${bad_rev-$(git_rev_parse_long $current_project $bad_branch)}"
	linux_next_stable="${linux_next_stable-$(git -C $current_project merge-base HEAD $bad_rev)}"
	cat <<EOF | manifest_out
declare -g linux_next_stable=$linux_next_stable
EOF
	echo "Rebase workaround: forcing linux baseline to $linux_next_stable"
	rebase_workaround=true
	rebase_workaround_opts+=("==rr[linux_url]" "$bad_url")
	rebase_workaround_opts+=("==rr[linux_branch]" "$linux_next_stable")
	;;
esac

# Build baseline that we are going to re-use to speed-up bisection.
# (This also confirms that infrastructure is OK.)
echo "Testing baseline (should be success)"
$build_script \
    ^^ $reproduce_bisect \
    %% $rel_artifacts/manifests/build-baseline.sh \
    @@ $rel_artifacts/manifests/build-parameters.sh \
    ==rr[mode] baseline \
    ==rr[update_baseline] push \
    ==rr[top_artifacts] "$rel_artifacts/build-baseline" \
    --verbose "$verbose" \
    "${rebase_workaround_opts[@]}"

baseline_rev="${baseline_rev-$(git -C ${current_project} rev-parse HEAD)}"
cat <<EOF | manifest_out
declare -g baseline_rev=$baseline_rev
EOF

ln -f -s "build-baseline" "$artifacts/build-$baseline_rev"
ln -f -s "build-baseline.sh" "$artifacts/manifests/build-$baseline_rev.sh"

case "${rr[ci_project]}/${rr[ci_config]}" in
    tcwg_gnu/*-check_*|tcwg_cross/*-check_*)
	(
	# Build up lists of flaky tests.  We do this by comparing
	# just-created baseline vs sumfiles in base-artifacts.
	fails=$(find $rel_artifacts/build-baseline \
		     -path "*-check_regression/fails.sum")
	xfail_short="contrib/testsuite-management/flaky/${rr[ci_config]}.xfail"
	xfail="gcc-compare-results/$xfail_short"

	if ! [ -f "$fails" ] || ! [ -f "$xfail" ]; then
	    exit
	fi

	(
	    echo
	    echo "# From $BUILD_URL:"
	    cat "$fails" | sed -e "s/^\([A-Z]\+: \)/flaky \| \1/"
	) >> "$xfail"

	git -C gcc-compare-results add "$xfail_short"
	git -C gcc-compare-results commit -m "From $BUILD_URL"
	git -C gcc-compare-results review -s
	git -C gcc-compare-results push gerrit HEAD:refs/heads/master
	) &
	res=0 && wait $! || res=$?
	# Ignore any failures in the above.
	;;
esac

mkdir -p ./bisect

# Save baseline build state, which we restore before individual bisect tests.
# This ensures that "bad" bisect tests won't affect "good" ones and vice versa.
baseline_exclude=(
    --exclude /bisect/ --exclude "/$rel_artifacts/" --exclude "/$current_project/"
)
rsync -a --del --delete-excluded "${baseline_exclude[@]}" ./ ./bisect/baseline/

cd $current_project

mkdir $artifacts/git-logs

# Make sure the sources are clean before bisecting
git reset --hard

if [ -f "$replay_log" ]; then
    cp "$replay_log" $artifacts/git-logs/bisect_replay.sh
    git bisect replay $artifacts/git-logs/bisect_replay.sh
else
    git bisect start
fi

# Hard-link BISECT_LOG inside $artifacts to guarantee its upload to jenkins.
ln -f "$(pwd)"/.git/BISECT_LOG $artifacts/git-logs/bisect_log

if ! git bisect log | grep -q "^git bisect .* $baseline_rev\$"; then
    git bisect good $baseline_rev
fi

# Bisect script.
#
# With this script we find the first commit that has regressed compared
# to baseline, but not, necessarily, the commit that caused regression in
# $bad_rev.  Consider the scenario:
# - rev_10 produced good result "2000" -- this is current baseline
# - rev_20 completely broke the build (say, result "10")
# - rev_22 fixed the build
# - rev_30 regressed the build to result "1000" -- this is the regression we
#   detected vs "2000" baseline.
#
# The script will identify rev_20 as the first failing commit, which will
# cause the baseline to be reset to rev_20 with metric "10".  When we then
# rebuild master (at rev_30) we will see a /progression/ from "10" to "1000",
# thus missing the regression of "2000" to "1000".
#
# To catch the "2000" to "1000" regression someone would need to manually
# trigger bisect between rev_22 and rev_30.
#
# We reduce the impact of the above by assigning negative values to result
# metric for builds that look very broken, and do not bisect regressions into
# the "negative" side.
cat > $artifacts/test.sh <<EOF
#!/bin/bash

set -euf -o pipefail

rev=\$(git rev-parse HEAD)

if git bisect log | grep -q "^git bisect bad \$rev\\\$"; then
  exit 1
elif git bisect log | grep -q "^git bisect skip \$rev\\\$"; then
  exit 125
elif git bisect log | grep -q "^git bisect good \$rev\\\$"; then
  exit 0
fi

cd ..

# Restore known-good baseline state.
rsync -a --del ${baseline_exclude[@]} ./bisect/baseline/ ./

$build_script \
  ^^ $reproduce_bisect \
  %% $rel_artifacts/manifests/build-\$rev.sh \
  @@ $rel_artifacts/manifests/build-parameters.sh \
  ==rr[mode] bisect \
  ==rr[${current_project}_url] "$bad_url" \
  ==rr[${current_project}_branch] \$rev \
  ==rr[top_artifacts] $rel_artifacts/build-\$rev \
  --verbose "$verbose" &
res=0 && wait \$! || res=\$?

git -C $current_project reset --hard

if [ x"\$res" != x"0" ]; then
  if [ -f $rel_artifacts/build-\$rev/trigger-build-$current_project ]; then
    exit 1
  else
    exit 125
  fi
else
  exit 0
fi
EOF
chmod +x $artifacts/test.sh

# Fetch $bad_branch/$bad_rev from $bad_url
prev_rev=$(git rev-parse HEAD)
clone_or_update_repo . "$bad_branch" "$bad_url"
bad_rev="${bad_rev-$(git_rev_parse_long . $bad_branch)}"
cat <<EOF | manifest_out
declare -g bad_rev=$bad_rev
EOF

if [ x"$baseline_rev" = x"$bad_rev" ]; then
    echo "WARNING: Detected regression with no change in sources of $current_project"
    sed -i -e "s/\$/-no_change/" $artifacts/jenkins/build-name
    trap "" EXIT
    exit 1
fi

# Confirm regression in $bad_rev vs $baseline_rev.
git checkout --detach $bad_rev
$artifacts/test.sh &
res=0 && wait $! || res=$?
# Restore revision previously checked out.  Otherwise "git bisect run"
# below will not use replay info.
git checkout --detach $prev_rev

if [ x"$res" = x"0" ]; then
    if $rebase_workaround; then
	echo "Rebase workaround: no regression between $baseline_rev and $bad_rev"
	sed -i -e "s/\$/-bad_rev-good/" $artifacts/jenkins/build-name
	project_name="${rr[ci_project]}/${rr[ci_config]}:$current_project"
	case $project_name in
	    tcwg_kernel/llvm-*-next-*:linux)
		cat > $artifacts/trigger-build-rebase <<EOF
llvm_branch=baseline
EOF
		;;
	    tcwg_kernel/gnu-*-next-*:linux)
		cat > $artifacts/trigger-build-rebase <<EOF
binutils_branch=baseline
gcc_branch=baseline
EOF
		;;
	    *) assert_with_msg "Unknown project name: $project_name" false ;;
	esac
	cat >> $artifacts/trigger-build-rebase <<EOF
linux_url=$bad_url
linux_branch=$baseline_rev
update_baseline=reset
EOF
    else
	echo "WARNING: build for bad_rev $bad_rev succeeded"
	sed -i -e "s/\$/-spurious/" $artifacts/jenkins/build-name
	# Regressions in speed benchmarking are not stable,
	# so retry with resetting baseline artifacts.
	# Retry with default parameters for other cases.
	case "${rr[ci_project]}/${rr[ci_config]}" in
	    tcwg_bmk*/gnu*-O[23]*)
		cat > $artifacts/trigger-build-reset <<EOF
binutils_branch=baseline
gcc_branch=baseline
glibc_branch=baseline
update_baseline=reset
EOF
		;;
	    tcwg_bmk*/llvm-*-O[23]*)
		cat > $artifacts/trigger-build-reset <<EOF
binutils_branch=baseline
gcc_branch=baseline
glibc_branch=baseline
llvm_branch=baseline
update_baseline=reset
EOF
		;;
	esac
    fi
    echo > $artifacts/jenkins/mail-recipients.txt
    trap "" EXIT
    exit 0
elif [ x"$res" = x"125" ]; then
    # We have confirmed a regression, but not what we have been triggered
    # to bisect.
    echo "WARNING: build for bad_rev $bad_rev showed uninteresting regression"
    sed -i -e "s/\$/-uninteresting/" $artifacts/jenkins/build-name
    echo > $artifacts/jenkins/mail-recipients.txt
    trap "" EXIT
    exit 0
fi

if ! git bisect log | grep -q "^git bisect .* $bad_rev\$"; then
    git bisect bad $bad_rev
    ln -f -s "build-$bad_rev" "$artifacts/build-bad"
    ln -f -s "build-$bad_rev.sh" "$artifacts/manifests/build-bad.sh"
fi

# Clone interesting-commits.git repo, which contains a list of SHA1s
# that might cut down bisection time.  Mostly, these are first_bad and
# last_good commits.
interesting_commits="../bisect/interesting-commits"
interesting_commits_rev=${interesting_commits_rev-linaro-local/ci/${rr[ci_project]}}
clone_or_update_repo $interesting_commits $interesting_commits_rev https://git-us.linaro.org/toolchain/ci/interesting-commits.git auto $interesting_commits_rev
interesting_commits_rev=$(git -C $interesting_commits rev-parse HEAD)
cat <<EOF | manifest_out
declare -g interesting_commits_rev=$interesting_commits_rev
EOF

# Add SHA1 commit $1 to interesting-commits and push the repo.
# If $2 is "regression" then record current configuration as having regressed
# at this commit.
# Ignore failures (since this is cache handling).
push_interesting_commit ()
{
    declare -g push_interesting_commit_result=0
    (
    set -euf -o pipefail

    local sha1="$1"
    local kind="$2"
    local -a configs

    if ! grep -q "^$sha1" $interesting_commits/$current_project; then
	echo "$sha1" >> $interesting_commits/$current_project
    fi

    if [ x"$kind" = x"regression" ]; then
	mapfile -t configs < <(grep "^$sha1" $interesting_commits/$current_project | sed -e "s/^$sha1 *//")
	configs+=("${rr[ci_project]}"/"${rr[ci_config]}")
	mapfile -t configs < <(echo "${configs[@]}" | tr ' ' '\n' | sort -u)
	sed -i -e "s#^$sha1.*\$#$sha1 ${configs[*]}#" $interesting_commits/$current_project
    fi

    git -C $interesting_commits add .
    if [ x"$(git -C $interesting_commits status --short)" = x"" ]; then
	# No file has changed.  We've been here before...
	# E.g., this is a re-occuring regression in linux-next.
	exit 125
    fi
    git -C $interesting_commits commit -m "Add $kind $sha1 from $BUILD_URL

${configs[*]}" &
    local res=0 && wait $! || res=$?

    if [ x"$res" = x"0" ]; then
	# Interesting-commits.git do not have .gitreview, so it's
	# simpler to push via gitolite.
	git_init_linaro_local_remote $interesting_commits baseline false
	git_push $interesting_commits baseline linaro-local/ci/${rr[ci_project]}
    fi
    ) &
    wait $! || push_interesting_commit_result=$?
}

# Print first_bad revision (if detected)
get_first_bad ()
{
    (
    # Allow pipefail to handle error exit codes from git bisect log and grep.
    # Note that child shell inherits settings from parent shell, so we need
    # excplicitly set "+o pipefail".
    set -euf +o pipefail

    git bisect log | tail -n1 | grep "^# first bad commit:" \
	| sed -e "s/^# first bad commit: \[\([0-9a-f]*\)\].*/\1/"
    )
}

# Print revs tested during bisect.
# $1 -- Revision kind -- good/bad/skip.
#       Print all revisions if no $1 given.
print_tested_revs ()
{
    (
    # Allow pipefail to handle error exit codes from git bisect log and grep.
    # Note that child shell inherits settings from parent shell, so we need
    # excplicitly set "+o pipefail".
    set -euf +o pipefail

    local kind="${1-[a-z]*}"
    git bisect log | grep "^git bisect $kind " | sed -e "s/^git bisect $kind //"
    )
}

# Try to reduce bisection range by testing regressions (and their parents)
# identified in other configurations.
touch $interesting_commits/$current_project
# Generate list of commits inside the bisection range.
commits_to_test=$artifacts/git-logs/commits_to_test
git bisect view --pretty=%H > $commits_to_test

# Record commits in the bisect range.  These are commits_to_test plus
# commits that have been tested.
commits_in_range=$artifacts/git-logs/commits_in_range
cp $commits_to_test $commits_in_range
print_tested_revs >> $commits_in_range

# This loop can generate lots of console noise.
set +x
while [ x"$(get_first_bad </dev/null)" = x"" ] && read -a arr; do
    (
    set -euf -o pipefail

    sha1="${arr[0]}"

    # Ignore commits outside of bisection range.
    if ! grep -q "^$sha1\$" $commits_to_test; then
	exit 0
    fi

    # Skip revisions that were already tested.  Good revisions are filtered
    # out in the above $commits_to_test check, and here we filter out
    # "bad" and "skip" revisions.
    if git bisect log | grep -q "^git bisect .* $sha1\$"; then
	exit 0
    fi

    if $verbose; then set -x; fi

    git checkout --detach $sha1
    $artifacts/test.sh &
    res=0 && wait $! || res=$?
    if [ x"$res" = x"0" ]; then
	git bisect good
    elif [ x"$res" = x"125" ]; then
	git bisect skip
    else
	git bisect bad
    fi
    git bisect view --pretty=%H > $commits_to_test
    ) </dev/null
done < <(cat $interesting_commits/$current_project)
if $verbose; then set -x; fi

if [ x"$(get_first_bad)" = x"" ]; then
    git bisect run $artifacts/test.sh &
    res=0 && wait $! || res=$?

    if [ x"$res" = x"0" ]; then
	assert_with_msg "Didn't find first bad commit!" [ x"$(get_first_bad)" != x"" ]
    fi
fi

first_bad=$(get_first_bad)
reset_rev="$first_bad"
notify_devs=true
notify_author=""
if [ x"$first_bad" != x"" ]; then
    # "git bisect run" succeeded.  Check whether this is an actual regression
    # or bisection artifact.
    last_good=""
    bad_last_good=""
    for sha1 in $(git rev-parse $first_bad^@); do
	# It seems that git-bisect assumes parent commit as "good" on
	# the basis of one of its children being "good".  Therefore we
	# can have a situation when we have parent P with children C1 and C2,
	# and child C1 has a child of its own CB.  Git-bisect tests C2 as
	# "good", and CB as "bad".  From C2 being good it assumes P as "good",
	# and it knows CB is "bad", so git-bisect returns C1 as the first bad
	# commit.
	# To simplify investigations we explicitly test parent of $first_bad.

	# Ignore commits outside of bisection range, but make an exception
	# for commits that weren't tested due to their child tested good.
	# This happens in projects that actively use merges, e.g., linux.
	if ! grep -q "^$sha1\$" $commits_in_range; then
	    child_tested_good=false
	    for tested_good in $(print_tested_revs good); do
		if git merge-base --is-ancestor $sha1 $tested_good; then
		    child_tested_good=true
		    break
		fi
	    done
	    if ! $child_tested_good; then
		continue
	    fi
	fi

	echo "Testing first_bad's parent $sha1 (hoping for success)"
	git checkout --detach "$sha1"
	$artifacts/test.sh &
	res=0 && wait $! || res=$?
	if [ x"$res" = x"0" ]; then
	    last_good=$sha1
	    break
	fi
	bad_last_good=$sha1
    done

    if [ x"$last_good" != x"" ]; then
	# We have successfully identified a bad commit with a good parent!
	# Add both $last_good and $first_bad to interesting commits.
	push_interesting_commit $last_good "last-good"
	push_interesting_commit $first_bad "regression"
	if [ x"$push_interesting_commit_result" = x"125" ]; then
	    notify_devs=false
	fi
    else
	assert_with_msg "Broken bisection range" [ x"$bad_last_good" != x"" ]
	# All parents of $first_bad tested bad, so retrigger bisection with
	# a reduced bisection range.
	cat > $artifacts/trigger-bisect <<EOF
current_project=$current_project
bad_url=$bad_url
bad_branch=$bad_last_good
EOF
	sed -i -e "s/\$/-retry-bisect/" $artifacts/jenkins/build-name
	# Don't send any emails.
	echo > $artifacts/jenkins/mail-recipients.txt
	trap "" EXIT
	exit 0
    fi
else
    # "Git bisect" didn't find the first_bad commit.
    # Possible reasons include:
    # - We have marked the regressing commit as "skip", which can happen
    #   to tcwg_bmk* projects when benchmarking infra has a problem.
    #
    # - Merge-base of $baseline_rev and $bad_rev is worse than $baseline_rev.
    #   We want to reset baseline to HEAD in this case, so that we catch most
    #   of the commits that introduced change in the result metric.
    #
    # So, to make at least some progress on narrowing down the regression ...
    # - look for the last commit that tested "good".  If it's not $baseline_rev,
    #   then we have narrowed down the bisection range somewhat.  Therefore,
    #   trigger two builds:
    #   - one to ADVANCE baseline to the last GOOD commit, and
    #   - another to expose the regression again.
    #
    # - If $baseline_rev is the only good commit, then we have got outselves
    #   to a tricky situation: we can't find the regression, and can't make
    #   a good build, which would advance the baseline.  To resolve this,
    #   trigger two builds:
    #   - one to RESET baseline to the last BAD commit, and
    #   - another to advance the baseline and expose another regression.
    #   Note that this approach correctly handles case when merge-base of
    #   $baseline_rev and $bad_rev tests "bad".

    last_good=$(print_tested_revs good | tail -n1)
    assert_with_msg "We should have at least baseline_rev as a good commit" \
		    [ x"$last_good" != x"" ]

    if [ x"$last_good" != x"$baseline_rev" ]; then
	# $reset_rev=="" due to $first_bad==""
	cat > $artifacts/trigger-build-1-advance <<EOF
${current_project}_url=$bad_url
${current_project}_branch=$last_good
EOF
	sed -i -e "s/\$/-advance-baseline/" $artifacts/jenkins/build-name
    else
	reset_rev=$(print_tested_revs bad | tail -n1)
	sed -i -e "s/\$/-reset-baseline/" $artifacts/jenkins/build-name
    fi
    # Don't send any emails.
    notify_devs=false
fi

# Bisect if officially over.
cd ..

# Create trigger-build-* files for subsequent builds.
if ! [ -f $artifacts/build-$bad_rev/trigger-build-$current_project ]; then
    # This can happen *only* when replaying bisects.
    # Otherwise $bad_rev is always tested second to $baseline_rev.
    bad_build=$(find $artifacts -path "$artifacts/build-*/trigger-build-$current_project" | tail -n1)
    assert_with_msg "No bad build during this bisect" [ x"$bad_build" != x"" ]
    mkdir -p $artifacts/build-$bad_rev
    cp $bad_build $artifacts/build-$bad_rev/trigger-build-$current_project
    sed -i -e "s/^${current_project}_branch=.*\$/${current_project}_branch=$bad_rev/" \
	$artifacts/build-$bad_rev/trigger-build-$current_project
fi

if [ x"$reset_rev" != x"" ]; then \
    if ! [ -f $artifacts/build-$reset_rev/trigger-build-$current_project ]; then
	# This is rare, but can happen that $reset_rev hasn't been tested.
	# Workaround by constructing trigger-build file from that of $bad_rev's.
	mkdir -p $artifacts/build-$reset_rev
	cp $artifacts/build-$bad_rev/trigger-build-$current_project \
	   $artifacts/build-$reset_rev/trigger-build-$current_project
	sed -i -e "s/^${current_project}_branch=$bad_rev\$/${current_project}_branch=$reset_rev/" \
	    $artifacts/build-$reset_rev/trigger-build-$current_project
    fi

    # Reset baseline to the regressed commit so that we will catch subsequent
    # regressions (worse than $bad_rev).
    cp $artifacts/build-$reset_rev/trigger-build-$current_project \
       $artifacts/trigger-build-1-reset
    echo "update_baseline=reset" >> $artifacts/trigger-build-1-reset
fi

# Trigger master build now instead of waiting for next timed SCM trigger.
cp $artifacts/build-$bad_rev/trigger-build-$current_project \
   $artifacts/trigger-build-2-default

# Save BISECT_* logs
find "$current_project" -path "$current_project/.git/BISECT_*" -print0 | xargs -0 -I@ mv @ $artifacts/git-logs/

# Remove any fail-safe email body
rm -f $artifacts/jenkins/mail-body.txt

if [ x"$first_bad" != x"" ]; then
    mkdir -p $artifacts/jenkins
    sed -i -e "s/\$/-$first_bad/" $artifacts/jenkins/build-name

    ln -f -s "build-$first_bad" "$artifacts/build-first_bad"
    ln -f -s "build-$first_bad.sh" "$artifacts/manifests/build-first_bad.sh"

    good_name="last_good"
    good_sha1="$last_good"
    bad_name="first_bad"
    bad_sha1="$first_bad"

    ln -f -s "build-$last_good" "$artifacts/build-last_good"
    ln -f -s "build-$last_good.sh" "$artifacts/manifests/build-last_good.sh"

    occurences="$(cat $current_project/$interesting_commits/$current_project | grep "^$first_bad" | sed -e "s/^$first_bad *//" | tr ' ' '\n' | sed "s#^# - #")"
    if [ "$(echo "$occurences" | wc -l)" -le 1 ]; then
	git_log_level="medium"
	notify_author=$(git -C $current_project log --pretty="%an <%ae>" -n 1 \
			    "$first_bad")
    else
	git_log_level="short"
    fi

    cat >> $artifacts/jenkins/mail-body.txt <<EOF
Successfully identified regression in *$current_project* in CI configuration ${rr[ci_project]}/${rr[ci_config]}.  So far, this commit has regressed CI configurations:
$occurences

Culprit:
<cut>
$(git -C $current_project log --pretty=$git_log_level -n 1 $first_bad)
</cut>

EOF
else
    good_name="baseline_rev"
    good_sha1="$baseline_rev"
    bad_name="bad"
    bad_sha1="$bad_rev"
    cat >> $artifacts/jenkins/mail-body.txt <<EOF
Could not identify regression in *$current_project* in CI configuration ${rr[ci_project]}/${rr[ci_config]}.  See 'Bisect log' in the links below for bisection details.

EOF
fi

if [ x"${TCWG_JIRA_TOKEN+set}" = x"set" ] && [ x"$first_bad" != x"" ]; then
    case "${rr[ci_project]}/${rr[ci_config]}:$current_project" in
	tcwg_kernel/gnu-*:linux) jira_card="GNU-681" ;;
	tcwg_kernel/gnu-*:*) jira_card="GNU-680" ;;
	tcwg_kernel/llvm-*:linux) jira_card="LLVM-647" ;;
	tcwg_kernel/llvm-*:*) jira_card="LLVM-646" ;;
	tcwg_bmk_*/gnu*-O[23]*) jira_card="GNU-689" ;;
	tcwg_bmk_*/gnu*) jira_card="GNU-686" ;;
	tcwg_bmk_*/llvm-*O[23]*) jira_card="LLVM-651" ;;
	tcwg_bmk_*/llvm-*) jira_card="LLVM-650" ;;
	tcwg_binutils/*) jira_card="GNU-692" ;;
	tcwg_cross/*) jira_card="GNU-692" ;;
	tcwg_gnu/*) jira_card="GNU-692" ;;
	# Catch-all case for when project/config IDs change, so that we
	# won't miss notifications.  Forward all that to GNU-692.
	*) jira_card="GNU-692" ;;
    esac

    if $notify_devs && [ x"$jira_card" != x"" ]; then
	cat > $artifacts/jenkins/jira-body.txt <<EOF
[$jira_card]
$(cat $artifacts/jenkins/mail-body.txt)

Details: ${BUILD_URL}artifact/$rel_artifacts/jenkins/mail-body.txt/*view*/
Even more details: ${BUILD_URL}artifact/$rel_artifacts/
EOF
	if ! [ -f $HOME/.jipdate.yml ]; then
	    cat > $HOME/.jipdate.yml <<EOF
server:
  url: https://linaro.atlassian.net
  token: #TCWG_JIRA_TOKEN#
text-editor: False
username: team-toolchain+tcwg-jira@linaro.org
EOF
	fi
	sed -i -e "s/#TCWG_JIRA_TOKEN#/$TCWG_JIRA_TOKEN/" $HOME/.jipdate.yml
	echo y | jipdate.py -f $artifacts/jenkins/jira-body.txt
    fi
fi

cat >> $artifacts/jenkins/mail-body.txt <<EOF
Results regressed to (for $bad_name == $bad_sha1)
$(cat $artifacts/build-$bad_sha1/results)

from (for $good_name == $good_sha1)
$(cat $artifacts/build-$good_sha1/results)

EOF

good_build_artifacts="Artifacts of $good_name build: ${BUILD_URL}artifact/$rel_artifacts/build-$good_sha1/"
bad_build_artifacts="Artifacts of $bad_name build: ${BUILD_URL}artifact/$rel_artifacts/build-$bad_sha1/"

# Benchmark builds have a results ID that is used to download the results
if test -f "$artifacts/build-$good_sha1/results_id"; then
  cat >> $artifacts/jenkins/mail-body.txt <<EOF
$good_build_artifacts
Results ID of $good_name: $(cat $artifacts/build-$good_sha1/results_id)
$bad_build_artifacts
Results ID of $bad_name: $(cat $artifacts/build-$bad_sha1/results_id)
EOF
# Os vs Os LTO builds have two result IDs per job
elif test -f "$artifacts/build-$good_sha1/results_id-1"; then
  cat >> $artifacts/jenkins/mail-body.txt <<EOF
$good_build_artifacts
Results IDs of $good_name:
$(cat $artifacts/build-$good_sha1/results_id-1)
$(cat $artifacts/build-$good_sha1/results_id-2)
$bad_build_artifacts
Results ID of $bad_name:
$(cat $artifacts/build-$bad_sha1/results_id-1)
$(cat $artifacts/build-$bad_sha1/results_id-2)
EOF
else
  cat >> $artifacts/jenkins/mail-body.txt <<EOF
$good_build_artifacts
$bad_build_artifacts
EOF
fi

cat >> $artifacts/jenkins/mail-body.txt <<EOF
Build top page/logs: ${BUILD_URL}

Configuration details:
$(cat $artifacts/manifests/build-baseline.sh | grep '_url]\|_branch]' | grep -v '="no_')

Reproduce builds:
<cut>
mkdir investigate-$current_project-$bad_sha1
cd investigate-$current_project-$bad_sha1

git clone https://git.linaro.org/toolchain/jenkins-scripts

mkdir -p $rel_artifacts/manifests
curl -o $rel_artifacts/manifests/build-baseline.sh ${BUILD_URL}artifact/$rel_artifacts/manifests/build-baseline.sh --fail
curl -o $rel_artifacts/manifests/build-parameters.sh ${BUILD_URL}artifact/$rel_artifacts/manifests/build-parameters.sh --fail
curl -o $rel_artifacts/test.sh ${BUILD_URL}artifact/$rel_artifacts/test.sh --fail
chmod +x $rel_artifacts/test.sh

# Reproduce the baseline build (build all pre-requisites)
$build_script @@ $rel_artifacts/manifests/build-baseline.sh

# Save baseline build state (which is then restored in $rel_artifacts/test.sh)
mkdir -p ./bisect
rsync -a --del --delete-excluded ${baseline_exclude[@]} ./ ./bisect/baseline/

cd $current_project

# Reproduce $bad_name build
git checkout --detach $bad_sha1
../$rel_artifacts/test.sh

# Reproduce $good_name build
git checkout --detach $good_sha1
../$rel_artifacts/test.sh

cd ..
</cut>

History of pending regressions and results: https://git.linaro.org/toolchain/ci/base-artifacts.git/log/?h=linaro-local/ci/${rr[ci_project]}/${rr[ci_config]}

Artifacts: ${BUILD_URL}artifact/$rel_artifacts/
Build log: ${BUILD_URL}consoleText
EOF

if [ x"$first_bad" != x"" ]; then
    cat >> $artifacts/jenkins/mail-body.txt <<EOF

Full commit (up to 1000 lines):
<cut>
$(git -C $current_project show --stat --patch $first_bad | head -n 1000)
</cut>
EOF
fi

# Set mail recipients last to preserve catch-error value from .yaml file.
# Email developers.
CI_MAIL_RECIPIENTS=("tcwg-validation@linaro.org")
case "$notify_author@${rr[ci_project]}/${rr[ci_config]}:$current_project" in
    ""@*/*:*) ;;
    *@tcwg_gnu/*-check_bootstrap*:*) ;; # We are building up list of flaky tests
    *@tcwg_cross/*-check_cross:*) ;;    # We are building up list of flaky tests
    *@tcwg_gnu/*:*)
	CI_MAIL_RECIPIENTS+=("$notify_author")
	CI_MAIL_RECIPIENTS+=("linaro-toolchain@lists.linaro.org")
	;;
    *@tcwg_cross/*:*)
	CI_MAIL_RECIPIENTS+=("$notify_author")
	CI_MAIL_RECIPIENTS+=("linaro-toolchain@lists.linaro.org")
	;;
    *@tcwg_kernel/llvm-*:linux)
	CI_MAIL_RECIPIENTS+=("$notify_author")
	CI_MAIL_RECIPIENTS+=("linaro-toolchain@lists.linaro.org")
	CI_MAIL_RECIPIENTS+=("clang-built-linux@googlegroups.com")
	CI_MAIL_RECIPIENTS+=("arnd@linaro.org")
	;;
    *@tcwg_kernel/llvm-*:llvm)
	CI_MAIL_RECIPIENTS+=("$notify_author")
	CI_MAIL_RECIPIENTS+=("linaro-toolchain@lists.linaro.org")
	CI_MAIL_RECIPIENTS+=("clang-built-linux@googlegroups.com")
	;;
    *@tcwg_bmk*/*:*)
	# Don't notify patch authors until we improve benchmarking email
	# reporting.
	#CI_MAIL_RECIPIENTS+=("$notify_author")
	CI_MAIL_RECIPIENTS+=("linaro-toolchain@lists.linaro.org")
	;;
    *@*/*:*)
	CI_MAIL_RECIPIENTS+=("linaro-toolchain@lists.linaro.org")
	;;
esac
if $notify_devs; then
    (
	IFS=","
	cat > $artifacts/jenkins/mail-recipients.txt <<EOF
${CI_MAIL_RECIPIENTS[*]}
EOF
    )
fi

trap "" EXIT