forked from bazelbuild/bazel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SequencedSkyframeExecutorTest.java
2563 lines (2375 loc) · 108 KB
/
SequencedSkyframeExecutorTest.java
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
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2020 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.skyframe;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
import static com.google.devtools.build.lib.actions.util.ActionCacheTestHelper.AMNESIAC_CACHE;
import static com.google.devtools.build.lib.actions.util.ActionsTestUtil.NULL_ACTION_OWNER;
import static com.google.devtools.build.lib.testutil.MoreAsserts.assertEventCount;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.fail;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicates;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import com.google.common.hash.HashCode;
import com.google.common.testing.GcFinalization;
import com.google.common.util.concurrent.Uninterruptibles;
import com.google.devtools.build.lib.actions.AbstractAction;
import com.google.devtools.build.lib.actions.Action;
import com.google.devtools.build.lib.actions.ActionAnalysisMetadata;
import com.google.devtools.build.lib.actions.ActionCacheChecker;
import com.google.devtools.build.lib.actions.ActionExecutionContext;
import com.google.devtools.build.lib.actions.ActionExecutionException;
import com.google.devtools.build.lib.actions.ActionExecutionStatusReporter;
import com.google.devtools.build.lib.actions.ActionInputPrefetcher;
import com.google.devtools.build.lib.actions.ActionKeyContext;
import com.google.devtools.build.lib.actions.ActionLookupData;
import com.google.devtools.build.lib.actions.ActionLookupKey;
import com.google.devtools.build.lib.actions.ActionLookupValue;
import com.google.devtools.build.lib.actions.ActionOwner;
import com.google.devtools.build.lib.actions.ActionResult;
import com.google.devtools.build.lib.actions.ActionTemplate;
import com.google.devtools.build.lib.actions.Actions;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.actions.Artifact.DerivedArtifact;
import com.google.devtools.build.lib.actions.Artifact.SpecialArtifact;
import com.google.devtools.build.lib.actions.Artifact.TreeFileArtifact;
import com.google.devtools.build.lib.actions.ArtifactOwner;
import com.google.devtools.build.lib.actions.ArtifactRoot;
import com.google.devtools.build.lib.actions.ArtifactRoot.RootType;
import com.google.devtools.build.lib.actions.BasicActionLookupValue;
import com.google.devtools.build.lib.actions.BuildFailedException;
import com.google.devtools.build.lib.actions.FileArtifactValue;
import com.google.devtools.build.lib.actions.FileStateValue;
import com.google.devtools.build.lib.actions.MiddlemanType;
import com.google.devtools.build.lib.actions.MutableActionGraph.ActionConflictException;
import com.google.devtools.build.lib.actions.ResourceManager;
import com.google.devtools.build.lib.actions.util.ActionsTestUtil;
import com.google.devtools.build.lib.actions.util.DummyExecutor;
import com.google.devtools.build.lib.actions.util.InjectedActionLookupKey;
import com.google.devtools.build.lib.actions.util.TestAction;
import com.google.devtools.build.lib.actions.util.TestAction.DummyAction;
import com.google.devtools.build.lib.analysis.AnalysisOptions;
import com.google.devtools.build.lib.analysis.BlazeDirectories;
import com.google.devtools.build.lib.analysis.ConfiguredTarget;
import com.google.devtools.build.lib.analysis.OutputGroupInfo;
import com.google.devtools.build.lib.analysis.TopLevelArtifactContext;
import com.google.devtools.build.lib.analysis.config.CoreOptions;
import com.google.devtools.build.lib.analysis.util.AnalysisMock;
import com.google.devtools.build.lib.analysis.util.BuildViewTestCase;
import com.google.devtools.build.lib.bugreport.BugReporter;
import com.google.devtools.build.lib.buildtool.BuildRequestOptions;
import com.google.devtools.build.lib.buildtool.SkyframeBuilder;
import com.google.devtools.build.lib.clock.BlazeClock;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.cmdline.PackageIdentifier;
import com.google.devtools.build.lib.collect.nestedset.NestedSet;
import com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder;
import com.google.devtools.build.lib.collect.nestedset.Order;
import com.google.devtools.build.lib.events.Event;
import com.google.devtools.build.lib.events.EventCollector;
import com.google.devtools.build.lib.events.EventKind;
import com.google.devtools.build.lib.events.ExtendedEventHandler;
import com.google.devtools.build.lib.events.ExtendedEventHandler.Postable;
import com.google.devtools.build.lib.events.NullEventHandler;
import com.google.devtools.build.lib.events.Reporter;
import com.google.devtools.build.lib.packages.NoSuchPackageException;
import com.google.devtools.build.lib.packages.Package;
import com.google.devtools.build.lib.packages.Target;
import com.google.devtools.build.lib.packages.semantics.BuildLanguageOptions;
import com.google.devtools.build.lib.pkgcache.LoadedPackageProvider;
import com.google.devtools.build.lib.pkgcache.PackageManager;
import com.google.devtools.build.lib.pkgcache.PackageOptions;
import com.google.devtools.build.lib.query2.common.QueryTransitivePackagePreloader;
import com.google.devtools.build.lib.runtime.KeepGoingOption;
import com.google.devtools.build.lib.server.FailureDetails.Crash;
import com.google.devtools.build.lib.server.FailureDetails.FailureDetail;
import com.google.devtools.build.lib.server.FailureDetails.Spawn;
import com.google.devtools.build.lib.server.FailureDetails.Spawn.Code;
import com.google.devtools.build.lib.skyframe.DirtinessCheckerUtils.BasicFilesystemDirtinessChecker;
import com.google.devtools.build.lib.skyframe.SkyframeActionExecutor.ActionCompletedReceiver;
import com.google.devtools.build.lib.skyframe.SkyframeActionExecutor.ProgressSupplier;
import com.google.devtools.build.lib.skyframe.TopLevelStatusEvents.TopLevelTargetBuiltEvent;
import com.google.devtools.build.lib.skyframe.serialization.DeserializationContext;
import com.google.devtools.build.lib.skyframe.serialization.ObjectCodec;
import com.google.devtools.build.lib.skyframe.serialization.SerializationContext;
import com.google.devtools.build.lib.skyframe.serialization.autocodec.AutoCodec;
import com.google.devtools.build.lib.testutil.MoreAsserts;
import com.google.devtools.build.lib.testutil.TestUtils;
import com.google.devtools.build.lib.util.AbruptExitException;
import com.google.devtools.build.lib.util.CrashFailureDetails;
import com.google.devtools.build.lib.util.DetailedExitCode;
import com.google.devtools.build.lib.util.Fingerprint;
import com.google.devtools.build.lib.util.io.TimestampGranularityMonitor;
import com.google.devtools.build.lib.vfs.FileSystemUtils;
import com.google.devtools.build.lib.vfs.ModifiedFileSet;
import com.google.devtools.build.lib.vfs.Path;
import com.google.devtools.build.lib.vfs.PathFragment;
import com.google.devtools.build.lib.vfs.Root;
import com.google.devtools.build.lib.vfs.RootedPath;
import com.google.devtools.build.lib.vfs.Symlinks;
import com.google.devtools.build.lib.vfs.SyscallCache;
import com.google.devtools.build.skyframe.DeterministicHelper;
import com.google.devtools.build.skyframe.Differencer.Diff;
import com.google.devtools.build.skyframe.EvaluationContext;
import com.google.devtools.build.skyframe.EvaluationResult;
import com.google.devtools.build.skyframe.GraphTester;
import com.google.devtools.build.skyframe.NotifyingHelper;
import com.google.devtools.build.skyframe.NotifyingHelper.EventType;
import com.google.devtools.build.skyframe.SkyFunction;
import com.google.devtools.build.skyframe.SkyFunctionName;
import com.google.devtools.build.skyframe.SkyKey;
import com.google.devtools.build.skyframe.SkyValue;
import com.google.devtools.build.skyframe.TrackingAwaiter;
import com.google.devtools.build.skyframe.ValueWithMetadata;
import com.google.devtools.common.options.OptionsParser;
import com.google.devtools.common.options.OptionsProvider;
import com.google.protobuf.CodedInputStream;
import com.google.protobuf.CodedOutputStream;
import com.google.testing.junit.testparameterinjector.TestParameter;
import com.google.testing.junit.testparameterinjector.TestParameterInjector;
import java.io.IOException;
import java.io.Serializable;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.regex.Pattern;
import javax.annotation.Nullable;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
/** Tests for {@link SequencedSkyframeExecutor}. */
@RunWith(TestParameterInjector.class)
public final class SequencedSkyframeExecutorTest extends BuildViewTestCase {
private static final DetailedExitCode USER_DETAILED_EXIT_CODE =
DetailedExitCode.of(
FailureDetail.newBuilder()
.setSpawn(Spawn.newBuilder().setCode(Code.NON_ZERO_EXIT))
.build());
private static final DetailedExitCode INFRA_DETAILED_EXIT_CODE =
DetailedExitCode.of(
FailureDetail.newBuilder()
.setCrash(Crash.newBuilder().setCode(Crash.Code.CRASH_UNKNOWN))
.build());
private final OptionsParser options =
OptionsParser.builder()
.optionsClasses(
AnalysisOptions.class,
BuildLanguageOptions.class,
BuildRequestOptions.class,
CoreOptions.class,
KeepGoingOption.class,
PackageOptions.class)
.build();
private final Map<SkyFunctionName, SkyFunction> extraSkyFunctions = new HashMap<>();
private QueryTransitivePackagePreloader visitor;
@Before
public void createVisitorAndParseOptions() throws Exception {
visitor = skyframeExecutor.getQueryTransitivePackagePreloader();
options.parse("--jobs=20");
}
@Override
protected AnalysisMock getAnalysisMock() {
AnalysisMock delegate = super.getAnalysisMock();
return new AnalysisMock.Delegate(delegate) {
@Override
public ImmutableMap<SkyFunctionName, SkyFunction> getSkyFunctions(
BlazeDirectories directories) {
return ImmutableMap.<SkyFunctionName, SkyFunction>builder()
.putAll(delegate.getSkyFunctions(directories))
.putAll(extraSkyFunctions)
.buildOrThrow();
}
};
}
private static class TopLevelTargetBuiltEventCollector {
private final Set<TopLevelTargetBuiltEvent> collectedEvents = new HashSet<>();
@Subscribe
void collect(TopLevelTargetBuiltEvent e) {
collectedEvents.add(e);
}
private ImmutableSet<TopLevelTargetBuiltEvent> getCollectedEvents() {
return ImmutableSet.copyOf(collectedEvents);
}
}
@Test
public void testChangeFile() throws Exception {
analysisMock.pySupport().setup(mockToolsConfig);
skyframeExecutor.invalidateFilesUnderPathForTesting(
reporter, ModifiedFileSet.EVERYTHING_MODIFIED, Root.fromPath(rootDirectory));
String pathString = rootDirectory + "/python/hello/BUILD";
scratch.file(pathString, "py_binary(name = 'hello', srcs = ['hello.py'])");
// A dummy file that is never changed.
scratch.file(rootDirectory + "/misc/BUILD", "sh_binary(name = 'misc', srcs = ['hello.sh'])");
sync("//python/hello:hello", "//misc:misc");
// No changes yet.
assertThat(dirtyValues()).isEmpty();
// Make a change.
scratch.overwriteFile(pathString, "py_binary(name = 'hello', srcs = ['something_else.py'])");
assertThat(dirtyValues())
.containsExactly(
FileStateValue.key(
RootedPath.toRootedPath(
Root.fromPath(rootDirectory), PathFragment.create("python/hello/BUILD"))));
// The method will continue returning the value until we invalidate it and re-evaluate.
assertThat(dirtyValues()).hasSize(1);
skyframeExecutor.invalidateFilesUnderPathForTesting(
reporter,
ModifiedFileSet.builder().modify(PathFragment.create("python/hello/BUILD")).build(),
Root.fromPath(rootDirectory));
sync("//python/hello:hello");
assertThat(dirtyValues()).isEmpty();
}
// Regression for b/13328517. clearAnalysisCache() method is call when --discard_analysis_cache
// is used. This saves about 10% of the memory during execution.
@Test
public void testClearAnalysisCache() throws Exception {
skyframeExecutor.setEventBus(new EventBus());
scratch.file(rootDirectory + "/discard/BUILD",
"genrule(name='x', srcs=['input'], outs=['out'], cmd='false')");
scratch.file(rootDirectory + "/discard/input", "foo");
ConfiguredTarget ct =
skyframeExecutor.getConfiguredTargetForTesting(
reporter, Label.parseCanonical("@//discard:x"), getTargetConfiguration());
assertThat(ct).isNotNull();
WeakReference<ConfiguredTarget> ref = new WeakReference<>(ct);
ct = null;
// Allow all values to be cleared by passing in empty set of top-level values, since we're not
// actually building.
skyframeExecutor.clearAnalysisCache(ImmutableSet.of(), ImmutableSet.of());
GcFinalization.awaitClear(ref);
}
@Test
public void testChangeDirectory() throws Exception {
analysisMock.pySupport().setup(mockToolsConfig);
skyframeExecutor.invalidateFilesUnderPathForTesting(
reporter, ModifiedFileSet.EVERYTHING_MODIFIED, Root.fromPath(rootDirectory));
scratch.file("python/hello/BUILD",
"py_binary(name = 'hello', srcs = ['hello.py'], data = glob(['*.txt']))");
scratch.file("python/hello/foo.txt", "foo");
// A dummy directory that is not changed.
scratch.file(
"misc/BUILD",
"py_binary(name = 'misc', srcs = ['other.py'], data = glob(['*.txt'], allow_empty ="
+ " True))");
sync("//python/hello:hello", "//misc:misc");
// No changes yet.
assertThat(dirtyValues()).isEmpty();
// Make a change.
scratch.file("python/hello/bar.txt", "bar");
assertThat(dirtyValues())
.containsExactly(
DirectoryListingStateValue.key(
RootedPath.toRootedPath(
Root.fromPath(rootDirectory), PathFragment.create("python/hello"))));
// The method will continue returning the value until we invalidate it and re-evaluate.
assertThat(dirtyValues()).hasSize(1);
skyframeExecutor.invalidateFilesUnderPathForTesting(
reporter,
ModifiedFileSet.builder().modify(PathFragment.create("python/hello/bar.txt")).build(),
Root.fromPath(rootDirectory));
sync("//python/hello:hello");
assertThat(dirtyValues()).isEmpty();
}
@Test
public void sync_onlyExternalFileChanged_reportsAffectedFile() throws Exception {
Root externalRoot = Root.fromPath(scratch.dir("/external"));
RootedPath file = RootedPath.toRootedPath(externalRoot, scratch.file("/external/file"));
initializeSkyframeExecutor(
/*doPackageLoadingChecks=*/ true, ImmutableList.of(nothingChangedDiffAwarenessFactory()));
skyframeExecutor
.injectable()
.inject(file, FileStateValue.create(file, SyscallCache.NO_CACHE, /*tsgm=*/ null));
skyframeExecutor.externalFilesHelper.getAndNoteFileType(file);
// Initial sync to establish the baseline DiffAwareness.View.
skyframeExecutor.handleDiffsForTesting(NullEventHandler.INSTANCE);
scratch.overwriteFile("/external/file", "new content");
syncSkyframeExecutor();
Diff diff = getRecordedDiff();
assertThat(diff.changedKeysWithNewValues()).containsKey(file);
}
@Test
public void sync_nothingChangedWithExternalFile_reportsNoExternalKeysInDiff() throws Exception {
Root externalRoot = Root.fromPath(scratch.dir("/external"));
RootedPath file = RootedPath.toRootedPath(externalRoot, scratch.file("/external/file"));
initializeSkyframeExecutor(
/*doPackageLoadingChecks=*/ true, ImmutableList.of(nothingChangedDiffAwarenessFactory()));
skyframeExecutor
.injectable()
.inject(file, FileStateValue.create(file, SyscallCache.NO_CACHE, /*tsgm=*/ null));
skyframeExecutor.externalFilesHelper.getAndNoteFileType(file);
// Initial sync to establish the baseline DiffAwareness.View.
skyframeExecutor.handleDiffsForTesting(NullEventHandler.INSTANCE);
syncSkyframeExecutor();
Diff diff = getRecordedDiff();
assertThat(diff.changedKeysWithoutNewValues()).doesNotContain(file);
assertThat(diff.changedKeysWithNewValues()).doesNotContainKey(file);
}
@Test
public void sync_onlyExternalListingChanged_reportsAffectedListing() throws Exception {
Root externalRoot = Root.fromPath(scratch.dir("/external"));
RootedPath dir = RootedPath.toRootedPath(externalRoot, scratch.dir("/external/foo"));
DirectoryListingStateValue value =
DirectoryListingStateValue.create(dir.asPath().readdir(Symlinks.NOFOLLOW));
DirectoryListingStateValue.Key dirListingKey = DirectoryListingStateValue.key(dir);
initializeSkyframeExecutor(
/*doPackageLoadingChecks=*/ true, ImmutableList.of(nothingChangedDiffAwarenessFactory()));
skyframeExecutor
.injectable()
.inject(
ImmutableMap.of(
dir,
FileStateValue.create(dir, SyscallCache.NO_CACHE, /*tsgm=*/ null),
dirListingKey,
value));
skyframeExecutor.externalFilesHelper.getAndNoteFileType(dir);
// Initial sync to establish the baseline DiffAwareness.View.
skyframeExecutor.handleDiffsForTesting(NullEventHandler.INSTANCE);
scratch.file("/external/foo/new_file");
syncSkyframeExecutor();
Diff diff = getRecordedDiff();
assertThat(diff.changedKeysWithoutNewValues()).containsNoneOf(dir, dirListingKey);
assertThat(diff.changedKeysWithNewValues()).doesNotContainKey(dir);
assertThat(diff.changedKeysWithNewValues()).containsKey(dirListingKey);
}
@Test
public void sync_nothingChangedWithExternalListing_reportsNoExternalKeysInDiff()
throws Exception {
Root externalRoot = Root.fromPath(scratch.dir("/external"));
RootedPath dir = RootedPath.toRootedPath(externalRoot, scratch.dir("/external/foo"));
DirectoryListingStateValue value =
DirectoryListingStateValue.create(dir.asPath().readdir(Symlinks.NOFOLLOW));
DirectoryListingStateValue.Key dirListingKey = DirectoryListingStateValue.key(dir);
initializeSkyframeExecutor(
/*doPackageLoadingChecks=*/ true, ImmutableList.of(nothingChangedDiffAwarenessFactory()));
skyframeExecutor
.injectable()
.inject(
ImmutableMap.of(
dir,
FileStateValue.create(dir, SyscallCache.NO_CACHE, /*tsgm=*/ null),
dirListingKey,
value));
skyframeExecutor.externalFilesHelper.getAndNoteFileType(dir);
// Initial sync to establish the baseline DiffAwareness.View.
skyframeExecutor.handleDiffsForTesting(NullEventHandler.INSTANCE);
syncSkyframeExecutor();
Diff diff = getRecordedDiff();
assertThat(diff.changedKeysWithoutNewValues()).containsNoneOf(dir, dirListingKey);
assertThat(diff.changedKeysWithNewValues()).doesNotContainKey(dir);
assertThat(diff.changedKeysWithNewValues()).doesNotContainKey(dirListingKey);
}
private static DiffAwareness.Factory nothingChangedDiffAwarenessFactory() {
return pathEntry ->
new DiffAwareness() {
@Override
public View getCurrentView(OptionsProvider options) {
return new View() {};
}
@Override
public ModifiedFileSet getDiff(View oldView, View newView) {
return ModifiedFileSet.NOTHING_MODIFIED;
}
@Override
public String name() {
return null;
}
@Override
public void close() {}
};
}
private Diff getRecordedDiff() {
return skyframeExecutor
.getDifferencerForTesting()
.getDiff(/*fromGraph=*/ null, ignored -> false, ignored -> false);
}
@Test
public void testSetDeletedPackages() throws Exception {
ExtendedEventHandler eventHandler = NullEventHandler.INSTANCE;
scratch.file("foo/bar/BUILD", "cc_library(name = 'bar', hdrs = ['bar.h'])");
scratch.file("foo/baz/BUILD", "cc_library(name = 'baz', hdrs = ['baz.h'])");
assertThat(
skyframeExecutor
.getPackageManager()
.isPackage(eventHandler, PackageIdentifier.createInMainRepo("foo/bar")))
.isTrue();
assertThat(
skyframeExecutor
.getPackageManager()
.getBuildFileForPackage(PackageIdentifier.createInMainRepo("foo/bar")))
.isNotNull();
assertThat(
skyframeExecutor
.getPackageManager()
.isPackage(eventHandler, PackageIdentifier.createInMainRepo("foo/baz")))
.isTrue();
assertThat(
skyframeExecutor
.getPackageManager()
.getBuildFileForPackage(PackageIdentifier.createInMainRepo("foo/baz")))
.isNotNull();
assertThat(
skyframeExecutor
.getPackageManager()
.isPackage(eventHandler, PackageIdentifier.createInMainRepo("not/a/package")))
.isFalse();
assertThat(
skyframeExecutor
.getPackageManager()
.getBuildFileForPackage(PackageIdentifier.createInMainRepo("not/a/package")))
.isNull();
skyframeExecutor.getPackageManager().getPackage(
eventHandler, PackageIdentifier.createInMainRepo("foo/bar"));
skyframeExecutor.getPackageManager().getPackage(
eventHandler, PackageIdentifier.createInMainRepo("foo/baz"));
assertThrows(
"non-existent package was incorrectly thought to exist",
NoSuchPackageException.class,
() ->
skyframeExecutor
.getPackageManager()
.getPackage(eventHandler, PackageIdentifier.createInMainRepo("not/a/package")));
ImmutableSet<PackageIdentifier> deletedPackages = ImmutableSet.of(
PackageIdentifier.createInMainRepo("foo/bar"));
skyframeExecutor.setDeletedPackages(deletedPackages);
assertThat(
skyframeExecutor
.getPackageManager()
.isPackage(eventHandler, PackageIdentifier.createInMainRepo("foo/bar")))
.isFalse();
assertThat(
skyframeExecutor
.getPackageManager()
.getBuildFileForPackage(PackageIdentifier.createInMainRepo("foo/bar")))
.isNull();
assertThrows(
"deleted package was incorrectly thought to exist",
NoSuchPackageException.class,
() ->
skyframeExecutor
.getPackageManager()
.getPackage(eventHandler, PackageIdentifier.createInMainRepo("foo/bar")));
assertThat(
skyframeExecutor
.getPackageManager()
.isPackage(eventHandler, PackageIdentifier.createInMainRepo("foo/baz")))
.isTrue();
}
// Directly tests that PackageFunction adds a dependency on the PackageLookupValue for
// (potential) subpackages. This is tested indirectly in several places (e.g.
// LabelVisitorTest#testSubpackageBoundaryAdd and
// PackageDeletionTest#testUnsuccessfulBuildAfterDeletion) but those tests are also indirectly
// testing the behavior of TargetFunction when the target has a '/'.
@Test
public void testDependencyOnPotentialSubpackages() throws Exception {
ExtendedEventHandler eventHandler = NullEventHandler.INSTANCE;
scratch.file("x/BUILD",
"sh_library(name = 'x', deps = ['//x:y/z'])",
"sh_library(name = 'y/z')");
Package pkgBefore = skyframeExecutor.getPackageManager().getPackage(
eventHandler, PackageIdentifier.createInMainRepo("x"));
assertThat(pkgBefore.containsErrors()).isFalse();
scratch.file("x/y/BUILD",
"sh_library(name = 'z')");
ModifiedFileSet modifiedFiles = ModifiedFileSet.builder()
.modify(PathFragment.create("x"))
.modify(PathFragment.create("x/y"))
.modify(PathFragment.create("x/y/BUILD"))
.build();
skyframeExecutor.invalidateFilesUnderPathForTesting(
reporter, modifiedFiles, Root.fromPath(rootDirectory));
// The package lookup for "x" should now fail because it's invalid.
reporter.removeHandler(failFastHandler); // expect errors
assertThat(
skyframeExecutor
.getPackageManager()
.getPackage(eventHandler, PackageIdentifier.createInMainRepo("x"))
.containsErrors())
.isTrue();
scratch.deleteFile("x/y/BUILD");
skyframeExecutor.invalidateFilesUnderPathForTesting(
reporter, modifiedFiles, Root.fromPath(rootDirectory));
// The package lookup for "x" should now succeed again.
reporter.addHandler(failFastHandler); // no longer expect errors
Package pkgAfter = skyframeExecutor.getPackageManager().getPackage(
eventHandler, PackageIdentifier.createInMainRepo("x"));
assertThat(pkgAfter).isNotSameInstanceAs(pkgBefore);
}
@Test
public void testSkyframePackageManagerGetBuildFileForPackage() throws Exception {
PackageManager skyframePackageManager = skyframeExecutor.getPackageManager();
scratch.file("nobuildfile/foo.txt");
scratch.file("deletedpackage/BUILD");
skyframeExecutor.setDeletedPackages(ImmutableList.of(
PackageIdentifier.createInMainRepo("deletedpackage")));
scratch.file("invalidpackagename.42/BUILD");
Path everythingGoodBuildFilePath = scratch.file("everythinggood/BUILD");
assertThat(
skyframePackageManager.getBuildFileForPackage(
PackageIdentifier.createInMainRepo("nobuildfile")))
.isNull();
assertThat(
skyframePackageManager.getBuildFileForPackage(
PackageIdentifier.createInMainRepo("deletedpackage")))
.isNull();
assertThat(
skyframePackageManager.getBuildFileForPackage(
PackageIdentifier.createInMainRepo("everythinggood")))
.isEqualTo(everythingGoodBuildFilePath);
}
/**
* Indirect regression test for b/12543229: "The Skyframe error propagation model is
* problematic".
*/
@Test
public void testPackageFunctionHandlesExceptionFromDependencies() throws Exception {
reporter.removeHandler(failFastHandler);
Path badDirPath = scratch.dir("bad/dir");
// This will cause an IOException when trying to compute the glob, which is required to load
// the package.
badDirPath.setReadable(false);
scratch.file("bad/BUILD",
"filegroup(name='fg', srcs=glob(['**']))");
assertThrows(
NoSuchPackageException.class,
() ->
skyframeExecutor
.getPackageManager()
.getPackage(reporter, PackageIdentifier.createInMainRepo("bad")));
}
private ImmutableList<SkyKey> dirtyValues() throws InterruptedException {
Diff diff =
new FilesystemValueChecker(
new TimestampGranularityMonitor(BlazeClock.instance()),
SyscallCache.NO_CACHE,
/* numThreads= */ 20)
.getDirtyKeys(
skyframeExecutor.getEvaluator().getValues(), new BasicFilesystemDirtinessChecker());
return ImmutableList.<SkyKey>builder()
.addAll(diff.changedKeysWithoutNewValues())
.addAll(diff.changedKeysWithNewValues().keySet())
.build();
}
private void sync(String... labelStrings) throws Exception {
Set<Label> labels = new HashSet<>();
for (String labelString : labelStrings) {
labels.add(Label.parseCanonical(labelString));
}
visitor.preloadTransitiveTargets(
reporter, labels, /*keepGoing=*/ false, /*parallelThreads=*/ 200, /*callerForError=*/ null);
}
@Test
public void testInterruptLoadedTarget() throws Exception {
analysisMock.pySupport().setup(mockToolsConfig);
scratch.file(
"python/hello/BUILD",
"py_binary(name = 'hello', srcs = ['hello.py'], data = glob(['*.txt'], allow_empty ="
+ " True))");
Thread.currentThread().interrupt();
LoadedPackageProvider packageProvider =
new LoadedPackageProvider(skyframeExecutor.getPackageManager(), reporter);
assertThrows(
InterruptedException.class,
() ->
packageProvider.getLoadedTarget(Label.parseAbsoluteUnchecked("//python/hello:hello")));
Target target = packageProvider.getLoadedTarget(
Label.parseAbsoluteUnchecked("//python/hello:hello"));
assertThat(target).isNotNull();
}
/**
* Generating the same output from two targets is ok if we build them on successive builds
* and invalidate the first target before we build the second target. This test is basically
* copied here from {@code AnalysisCachingTest} because here we can control the number of Skyframe
* update calls that we make. This prevents an intermediate update call from clearing the action
* and hiding the bug.
*/
@Test
public void testNoActionConflictWithInvalidatedTarget() throws Exception {
scratch.file(
"conflict/BUILD",
"cc_library(name='x', srcs=['foo.cc'])",
"cc_binary(name='_objs/x/foo.o', srcs=['bar.cc'])");
ConfiguredTargetAndData conflict =
skyframeExecutor.getConfiguredTargetAndDataForTesting(
reporter, Label.parseCanonical("@//conflict:x"), getTargetConfiguration());
assertThat(conflict).isNotNull();
ArtifactRoot root =
getTargetConfiguration()
.getBinDirectory(conflict.getConfiguredTarget().getLabel().getRepository());
Action oldAction =
getGeneratingAction(
getDerivedArtifact(
PathFragment.create("conflict/_objs/x/foo.o"),
root,
ConfiguredTargetKey.fromConfiguredTarget(conflict.getConfiguredTarget())));
assertThat(oldAction.getOwner().getLabel().toString()).isEqualTo("//conflict:x");
skyframeExecutor.handleAnalysisInvalidatingChange();
ConfiguredTargetAndData objsConflict =
skyframeExecutor.getConfiguredTargetAndDataForTesting(
reporter, Label.parseCanonical("@//conflict:_objs/x/foo.o"), getTargetConfiguration());
assertThat(objsConflict).isNotNull();
Action newAction =
getGeneratingAction(
getDerivedArtifact(
PathFragment.create("conflict/_objs/x/foo.o"),
root,
ConfiguredTargetKey.fromConfiguredTarget(objsConflict.getConfiguredTarget())));
assertThat(newAction.getOwner().getLabel().toString()).isEqualTo("//conflict:_objs/x/foo.o");
}
@Test
public void testGetPackageUsesListener() throws Exception {
scratch.file("pkg/BUILD", "thisisanerror");
EventCollector customEventCollector = new EventCollector(EventKind.ERRORS);
Package pkg = skyframeExecutor.getPackageManager().getPackage(
new Reporter(new EventBus(), customEventCollector),
PackageIdentifier.createInMainRepo("pkg"));
assertThat(pkg.containsErrors()).isTrue();
MoreAsserts.assertContainsEvent(customEventCollector, "name 'thisisanerror' is not defined");
}
/** Dummy action that does not create its lone output file. */
private static class MissingOutputAction extends DummyAction {
MissingOutputAction(NestedSet<Artifact> inputs, Artifact output, MiddlemanType type) {
super(inputs, output, type);
}
@Override
public ActionResult execute(ActionExecutionContext actionExecutionContext)
throws ActionExecutionException, InterruptedException {
ActionResult actionResult = super.execute(actionExecutionContext);
try {
getPrimaryOutput().getPath().deleteTree();
} catch (IOException e) {
throw new AssertionError(e);
}
return actionResult;
}
}
private static final ActionCacheChecker NULL_CHECKER =
new ActionCacheChecker(
AMNESIAC_CACHE,
new ActionsTestUtil.FakeArtifactResolverBase(),
new ActionKeyContext(),
Predicates.alwaysTrue(),
/*cacheConfig=*/ null);
private static final ProgressSupplier EMPTY_PROGRESS_SUPPLIER = new ProgressSupplier() {
@Override
public String getProgressString() {
return "";
}
};
private static final ActionCompletedReceiver EMPTY_COMPLETION_RECEIVER =
new ActionCompletedReceiver() {
@Override
public void actionCompleted(ActionLookupData actionLookupData) {}
@Override
public void noteActionEvaluationStarted(ActionLookupData actionLookupData, Action action) {}
};
private <T extends SkyValue> EvaluationResult<T> evaluate(Iterable<? extends SkyKey> roots)
throws InterruptedException {
EvaluationContext evaluationContext =
EvaluationContext.newBuilder()
.setKeepGoing(false)
.setNumThreads(SequencedSkyframeExecutor.DEFAULT_THREAD_COUNT)
.setEventHandler(reporter)
.build();
return skyframeExecutor.getEvaluator().evaluate(roots, evaluationContext);
}
/**
* Make sure that if a shared action fails to create an output file, the other action doesn't
* complain about it too.
*/
@Test
public void testSharedActionsNoOutputs() throws Exception {
Path root = getExecRoot();
PathFragment execPath = PathFragment.create("out").getRelative("missing");
// We create two "configured targets" and two copies of the same artifact, each generated by
// an action from its respective configured target.
ActionLookupKey lc1 = new InjectedActionLookupKey("lc1");
Artifact output1 =
DerivedArtifact.create(
ArtifactRoot.asDerivedRoot(root, RootType.Output, "out"), execPath, lc1);
Action action1 =
new MissingOutputAction(
NestedSetBuilder.emptySet(Order.STABLE_ORDER), output1, MiddlemanType.NORMAL);
ActionLookupValue ctValue1 = createActionLookupValue(action1, lc1);
ActionLookupKey lc2 = new InjectedActionLookupKey("lc2");
Artifact output2 =
DerivedArtifact.create(
ArtifactRoot.asDerivedRoot(root, RootType.Output, "out"), execPath, lc2);
Action action2 =
new MissingOutputAction(
NestedSetBuilder.emptySet(Order.STABLE_ORDER), output2, MiddlemanType.NORMAL);
ActionLookupValue ctValue2 = createActionLookupValue(action2, lc2);
// Inject the "configured targets" into the graph.
skyframeExecutor
.getDifferencerForTesting()
.inject(ImmutableMap.of(lc1, ctValue1, lc2, ctValue2));
// Do a null build, so that the skyframe executor initializes the action executor properly.
skyframeExecutor.setActionOutputRoot(getOutputPath());
skyframeExecutor.setActionExecutionProgressReportingObjects(EMPTY_PROGRESS_SUPPLIER,
EMPTY_COMPLETION_RECEIVER, ActionExecutionStatusReporter.create(reporter));
skyframeExecutor.buildArtifacts(
reporter,
ResourceManager.instanceForTestingOnly(),
new DummyExecutor(fileSystem, rootDirectory),
ImmutableSet.of(),
ImmutableSet.of(),
ImmutableSet.of(),
ImmutableSet.of(),
ImmutableSet.of(),
options,
NULL_CHECKER,
null,
null);
reporter.removeHandler(failFastHandler); // Expect errors.
skyframeExecutor.prepareBuildingForTestingOnly(
reporter, new DummyExecutor(fileSystem, rootDirectory), options, NULL_CHECKER);
EvaluationResult<FileArtifactValue> result = evaluate(ImmutableList.of(output1, output2));
assertWithMessage(result.toString()).that(result.keyNames()).isEmpty();
assertThat(result.hasError()).isTrue();
MoreAsserts.assertContainsEvent(eventCollector,
"output '" + output1.prettyPrint() + "' was not created");
MoreAsserts.assertContainsEvent(eventCollector, "not all outputs were created or valid");
assertEventCount(2, eventCollector);
}
/** Shared actions can race and both check the action cache and try to execute. */
@Test
public void testSharedActionsRacing() throws Exception {
Path root = getExecRoot();
PathFragment execPath = PathFragment.create("out").getRelative("file");
Path sourcePath = rootDirectory.getRelative("foo/src");
sourcePath.getParentDirectory().createDirectoryAndParents();
FileSystemUtils.createEmptyFile(sourcePath);
// We create two "configured targets" and two copies of the same artifact, each generated by
// an action from its respective configured target. Both actions will consume the input file
// "out/input" so we can synchronize their execution.
ActionLookupKey inputKey = new InjectedActionLookupKey("input");
Artifact input =
DerivedArtifact.create(
ArtifactRoot.asDerivedRoot(root, RootType.Output, "out"),
PathFragment.create("out").getRelative("input"),
inputKey);
Action baseAction =
new DummyAction(NestedSetBuilder.emptySet(Order.STABLE_ORDER), input, MiddlemanType.NORMAL);
ActionLookupValue ctBase = createActionLookupValue(baseAction, inputKey);
ActionLookupKey lc1 = new InjectedActionLookupKey("lc1");
Artifact output1 =
DerivedArtifact.create(
ArtifactRoot.asDerivedRoot(root, RootType.Output, "out"), execPath, lc1);
Action action1 =
new DummyAction(
NestedSetBuilder.create(Order.STABLE_ORDER, input), output1, MiddlemanType.NORMAL);
ActionLookupValue ctValue1 = createActionLookupValue(action1, lc1);
ActionLookupKey lc2 = new InjectedActionLookupKey("lc2");
Artifact output2 =
DerivedArtifact.create(
ArtifactRoot.asDerivedRoot(root, RootType.Output, "out"), execPath, lc2);
Action action2 =
new DummyAction(
NestedSetBuilder.create(Order.STABLE_ORDER, input), output2, MiddlemanType.NORMAL);
ActionLookupValue ctValue2 = createActionLookupValue(action2, lc2);
// Stall both actions during the "checking inputs" phase so that neither will enter
// SkyframeActionExecutor before both have asked SkyframeActionExecutor if another shared action
// is running. This way, both actions will check the action cache beforehand and try to update
// the action cache post-build.
final CountDownLatch inputsRequested = new CountDownLatch(2);
skyframeExecutor.configureActionExecutor(/* fileCache= */ null, ActionInputPrefetcher.NONE);
skyframeExecutor
.getEvaluator()
.injectGraphTransformerForTesting(
NotifyingHelper.makeNotifyingTransformer(
(key, type, order, context) -> {
if (type == EventType.GET_VALUE_WITH_METADATA
&& key.functionName().equals(Artifact.ARTIFACT)
&& input.equals(key)) {
inputsRequested.countDown();
try {
assertThat(
inputsRequested.await(
TestUtils.WAIT_TIMEOUT_SECONDS, TimeUnit.SECONDS))
.isTrue();
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
}
}));
// Inject the "configured targets" and artifact into the graph.
skyframeExecutor
.getDifferencerForTesting()
.inject(ImmutableMap.of(lc1, ctValue1, lc2, ctValue2, inputKey, ctBase));
// Do a null build, so that the skyframe executor initializes the action executor properly.
skyframeExecutor.setActionOutputRoot(getOutputPath());
skyframeExecutor.setActionExecutionProgressReportingObjects(EMPTY_PROGRESS_SUPPLIER,
EMPTY_COMPLETION_RECEIVER, ActionExecutionStatusReporter.create(reporter));
skyframeExecutor.buildArtifacts(
reporter,
ResourceManager.instanceForTestingOnly(),
new DummyExecutor(fileSystem, rootDirectory),
ImmutableSet.of(),
ImmutableSet.of(),
ImmutableSet.of(),
ImmutableSet.of(),
ImmutableSet.of(),
options,
NULL_CHECKER,
null,
null);
skyframeExecutor.prepareBuildingForTestingOnly(
reporter, new DummyExecutor(fileSystem, rootDirectory), options, NULL_CHECKER);
EvaluationResult<FileArtifactValue> result =
evaluate(Artifact.keys(ImmutableList.of(output1, output2)));
assertThat(result.hasError()).isFalse();
TrackingAwaiter.INSTANCE.assertNoErrors();
}
/**
* Tests a subtle situation when three shared actions race and are interrupted. Action A starts
* executing. Actions B and C start executing. Action B notices action A is already executing and
* sets completionFuture. It then exits, returning control to
* AbstractParallelEvaluator$Evaluate#run code. The build is interrupted. When B's code tries to
* register the future with AbstractQueueVisitor, the future is canceled (or if the interrupt
* races with B registering the future, shortly thereafter). Action C then starts running. It too
* notices Action A is already executing. The future's state should be consistent. A cannot finish
* until C runs, since otherwise C would see that A was done.
*/
@Test
public void testThreeSharedActionsRacing() throws Exception {
Path root = getExecRoot();
PathFragment out = PathFragment.create("out");
PathFragment execPath = out.getRelative("file");
// We create three "configured targets" and three copies of the same artifact, each generated by
// an action from its respective configured target. The actions wouldn't actually do the same
// thing if they executed, but they look the same to our execution engine.
ActionLookupKey lcA = new InjectedActionLookupKey("lcA");
Artifact outputA =
DerivedArtifact.create(
ArtifactRoot.asDerivedRoot(root, RootType.Output, "out"), execPath, lcA);
CountDownLatch actionAStartedSoOthersCanProceed = new CountDownLatch(1);
CountDownLatch actionCFinishedSoACanFinish = new CountDownLatch(1);
Action actionA =
new TestAction(
(Serializable & Callable<Void>)
() -> {
actionAStartedSoOthersCanProceed.countDown();
try {
Thread.sleep(TestUtils.WAIT_TIMEOUT_MILLISECONDS);
} catch (InterruptedException e) {
TrackingAwaiter.INSTANCE.awaitLatchAndTrackExceptions(
actionCFinishedSoACanFinish, "third didn't finish");
throw e;
}
throw new IllegalStateException("Should have been interrupted");
},
NestedSetBuilder.emptySet(Order.STABLE_ORDER),
ImmutableSet.of(outputA));
ActionLookupValue ctA = createActionLookupValue(actionA, lcA);
// Shared actions: they look the same from the point of view of Blaze data.
ActionLookupKey lcB = new InjectedActionLookupKey("lcB");
Artifact outputB =
DerivedArtifact.create(
ArtifactRoot.asDerivedRoot(root, RootType.Output, "out"), execPath, lcB);
Action actionB =
new DummyAction(
NestedSetBuilder.emptySet(Order.STABLE_ORDER), outputB, MiddlemanType.NORMAL);
ActionLookupValue ctB = createActionLookupValue(actionB, lcB);
ActionLookupKey lcC = new InjectedActionLookupKey("lcC");
Artifact outputC =
DerivedArtifact.create(
ArtifactRoot.asDerivedRoot(root, RootType.Output, "out"), execPath, lcC);
Action actionC =
new DummyAction(
NestedSetBuilder.emptySet(Order.STABLE_ORDER), outputC, MiddlemanType.NORMAL);
ActionLookupValue ctC = createActionLookupValue(actionC, lcC);
// Both shared actions wait for A to start executing. We do that by stalling their dep requests
// on their configured targets. We then let B proceed. Once B finishes its SkyFunction run, it
// interrupts the main thread. C just waits until it has been interrupted, and then another
// little bit, to give B time to attempt to add the future and try to cancel it. It not waiting
// long enough can lead to a flaky pass.
Thread mainThread = Thread.currentThread();
CountDownLatch cStarted = new CountDownLatch(1);