Debian Codegraph @

tests/i/run_modes/test_simulation.py

raw
1 # THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE.
2 # Copyright (C) NIWA & British Crown (Met Office) & Contributors.
3 #
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16
17 """Test the workings of simulation mode"""
18
19 import logging
20 from pathlib import Path
21 import pytest
22 from pytest import param
23
24 from cylc.flow import commands
25 from cylc.flow.cycling.iso8601 import ISO8601Point
26 from cylc.flow.run_modes import RunMode
27 from cylc.flow.run_modes.simulation import sim_time_check
28
29
30 async def test_started_trigger(flow, reftest, scheduler):
31 """Does the started task output trigger downstream tasks
32 in sim mode?
33
34 Long standing Bug discovered in Skip Mode work.
35 https://github.com/cylc/cylc-flow/pull/6039#issuecomment-2321147445
36 """
37 schd = scheduler(
38 flow(
39 {
40 'scheduler': {
41 'events': {
42 'stall timeout': 'PT0S',
43 'abort on stall timeout': True,
44 }
45 },
46 'scheduling': {'graph': {'R1': 'a:started => b'}},
47 }
48 ),
49 paused_start=False,
50 )
51 assert await reftest(schd) == {
52 ('1/a', None),
53 ('1/b', ('1/a',))
54 }
55
56
57 @pytest.fixture
58 def monkeytime(monkeypatch):
59 """Convenience function monkeypatching time."""
60 def _inner(time_: int):
61 monkeypatch.setattr('cylc.flow.task_job_mgr.time', lambda: time_)
62 monkeypatch.setattr(
63 'cylc.flow.run_modes.simulation.time', lambda: time_)
64 return _inner
65
66
67 @pytest.fixture
68 def run_simjob(monkeytime):
69 """Run a simulated job to completion.
70
71 Returns the output status.
72 """
73 def _run_simjob(schd, point, task):
74 itask = schd.pool.get_task(point, task)
75 itask.state.is_queued = False
76 monkeytime(0)
77 schd.task_job_mgr.submit_nonlive_task_jobs([itask], RunMode.SIMULATION)
78 monkeytime(itask.mode_settings.timeout + 1)
79
80 # Run Time Check
81 assert sim_time_check(
82 schd.task_events_mgr, [itask],
83 schd.workflow_db_mgr
84 ) is True
85
86 # Capture result process queue.
87 return itask
88 return _run_simjob
89
90
91 @pytest.fixture(scope='module')
92 async def sim_time_check_setup(
93 mod_flow, mod_scheduler, mod_start, mod_one_conf,
94 ):
95 schd = mod_scheduler(mod_flow({
96 'scheduler': {'cycle point format': '%Y'},
97 'scheduling': {
98 'initial cycle point': '1066',
99 'graph': {
100 'R1': 'one & fail_all & fast_forward',
101 'P1Y': 'fail_once & fail_all_submits'
102 }
103 },
104 'runtime': {
105 'one': {},
106 'fail_all': {
107 'simulation': {
108 'fail cycle points': 'all',
109 'fail try 1 only': False
110 },
111 'outputs': {'foo': 'bar'}
112 },
113 # This task ought not be finished quickly, but for the speed up
114 'fast_forward': {
115 'execution time limit': 'PT1M',
116 'simulation': {'speedup factor': 2}
117 },
118 'fail_once': {
119 'simulation': {
120 'fail cycle points': '1066, 1068',
121 }
122 },
123 'fail_all_submits': {
124 'simulation': {
125 'fail cycle points': '1066',
126 'fail try 1 only': False,
127 }
128 }
129 }
130 }))
131 async with mod_start(schd):
132 itasks = schd.pool.get_tasks()
133 [schd.task_job_mgr._set_retry_timers(i) for i in itasks]
134 yield schd, itasks
135
136
137 def test_false_if_not_running(
138 sim_time_check_setup, monkeypatch
139 ):
140 schd, itasks = sim_time_check_setup
141
142 itasks = [i for i in itasks if i.state.status != 'running']
143
144 # False if task status not running:
145 assert sim_time_check(schd.task_events_mgr, itasks, '') is False
146
147
148 @pytest.mark.parametrize(
149 'itask, point, results',
150 (
151 # Task fails this CP, first submit.
152 param(
153 'fail_once', '1066', (True, False, False),
154 id='only-fail-on-submit-1'),
155 # Task succeeds this CP, all submits.
156 param(
157 'fail_once', '1067', (False, False, False),
158 id='do-not-fail-this-cp'),
159 # Task fails this CP, first submit.
160 param(
161 'fail_once', '1068', (True, False, False),
162 id='and-another-cp'),
163 # Task fails this CP, all submits.
164 param(
165 'fail_all_submits', '1066', (True, True, True),
166 id='fail-all-submits'),
167 # Task succeeds this CP, all submits.
168 param(
169 'fail_all_submits', '1067', (False, False, False),
170 id='fail-no-submits'),
171 )
172 )
173 def test_fail_once(sim_time_check_setup, itask, point, results, monkeypatch):
174 """A task with a fail cycle point only fails
175 at that cycle point, and then only on the first submission.
176 """
177 schd, _ = sim_time_check_setup
178
179 itask = schd.pool.get_task(
180 ISO8601Point(point), itask)
181
182 for i, result in enumerate(results):
183 itask.try_timers['execution-retry'].num = i
184 schd.task_job_mgr.submit_nonlive_task_jobs([itask], RunMode.SIMULATION)
185 assert itask.mode_settings.sim_task_fails is result
186
187
188 def test_task_finishes(sim_time_check_setup, monkeytime, caplog):
189 """...and an appropriate message sent.
190
191 Checks that failed and bar are output if a task is set to fail.
192
193 Does NOT check every possible cause of an outcome - this is done
194 in unit tests.
195 """
196 schd, _ = sim_time_check_setup
197 monkeytime(0)
198
199 # Setup a task to fail, submit it.
200 fail_all_1066 = schd.pool.get_task(ISO8601Point('1066'), 'fail_all')
201 fail_all_1066.state.status = 'running'
202 fail_all_1066.state.is_queued = False
203 schd.task_job_mgr.submit_nonlive_task_jobs(
204 [fail_all_1066], RunMode.SIMULATION
205 )
206
207 # For the purpose of the test delete the started time set by
208 # submit_nonlive_task_jobs.
209 fail_all_1066.summary['started_time'] = 0
210
211 # Before simulation time is up:
212 assert sim_time_check(schd.task_events_mgr, [fail_all_1066], '') is False
213
214 # Time's up...
215 monkeytime(12)
216
217 # After simulation time is up it Fails and records custom outputs:
218 assert sim_time_check(schd.task_events_mgr, [fail_all_1066], '') is True
219 outputs = fail_all_1066.state.outputs
220 assert outputs.is_message_complete('succeeded') is False
221 assert outputs.is_message_complete('bar') is True
222 assert outputs.is_message_complete('failed') is True
223
224
225 def test_task_sped_up(sim_time_check_setup, monkeytime):
226 """Task will speed up by a factor set in config."""
227
228 schd, _ = sim_time_check_setup
229 fast_forward_1066 = schd.pool.get_task(
230 ISO8601Point('1066'), 'fast_forward')
231
232 # Run the job submission method:
233 monkeytime(0)
234 schd.task_job_mgr.submit_nonlive_task_jobs(
235 [fast_forward_1066], RunMode.SIMULATION
236 )
237 fast_forward_1066.state.is_queued = False
238
239 result = sim_time_check(schd.task_events_mgr, [fast_forward_1066], '')
240 assert result is False
241 monkeytime(29)
242 result = sim_time_check(schd.task_events_mgr, [fast_forward_1066], '')
243 assert result is False
244 monkeytime(31)
245 result = sim_time_check(schd.task_events_mgr, [fast_forward_1066], '')
246 assert result is True
247
248
249 async def test_settings_restart(monkeytime, flow, scheduler, start):
250 """Check that simulation mode settings are correctly restored
251 upon restart.
252
253 In the case of start time this is collected from the database
254 from task_jobs.start_time.
255
256 tasks:
257 one: Runs straighforwardly.
258 two: Test case where database is missing started_time
259 because it was upgraded from an earlier version of Cylc.
260 """
261 id_ = flow({
262 'scheduler': {'cycle point format': '%Y'},
263 'scheduling': {
264 'initial cycle point': '1066',
265 'graph': {
266 'R1': 'one & two'
267 }
268 },
269 'runtime': {
270 'root': {
271 'execution time limit': 'PT1M',
272 'execution retry delays': 'P0Y',
273 'simulation': {
274 'speedup factor': 1,
275 'fail cycle points': 'all',
276 'fail try 1 only': True,
277 }
278 },
279 }
280 })
281 schd = scheduler(id_)
282 # Start the workflow:
283 async with start(schd):
284 og_timeouts = {}
285 for itask in schd.pool.get_tasks():
286 schd.task_job_mgr.submit_nonlive_task_jobs(
287 [itask], RunMode.SIMULATION
288 )
289
290 og_timeouts[itask.identity] = itask.mode_settings.timeout
291
292 # Mock wallclock < sim end timeout
293 monkeytime(itask.mode_settings.timeout - 1)
294 assert sim_time_check(
295 schd.task_events_mgr, [itask], schd.workflow_db_mgr
296 ) is False
297
298 # Stop and restart the scheduler:
299 schd = scheduler(id_)
300 async with start(schd):
301 for itask in schd.pool.get_tasks():
302 # Check that we haven't got mode settings back:
303 assert itask.mode_settings is None
304
305 if itask.identity == '1066/two':
306 # Delete the database entry for `two`: Ensure that
307 # we don't break sim mode on upgrade to this version of Cylc.
308 schd.workflow_db_mgr.pri_dao.connect().execute(
309 'UPDATE task_jobs'
310 '\n SET time_submit = NULL'
311 '\n WHERE (name == \'two\')'
312 )
313 schd.workflow_db_mgr.process_queued_ops()
314 monkeytime(42)
315 else:
316 monkeytime(og_timeouts[itask.identity] - 1)
317
318 assert sim_time_check(
319 schd.task_events_mgr, [itask], schd.workflow_db_mgr
320 ) is False
321
322 # Check that the itask.mode_settings is now re-created
323
324 assert itask.mode_settings.simulated_run_length == 60.0
325 assert itask.mode_settings.sim_task_fails is True
326
327
328 async def test_settings_reload(
329 flow, scheduler, start, run_simjob
330 ):
331 """Check that simulation mode settings are changed for future
332 pseudo jobs on reload.
333
334 """
335 id_ = flow({
336 'scheduler': {'cycle point format': '%Y'},
337 'scheduling': {
338 'initial cycle point': '1066',
339 'graph': {'R1': 'one'}
340 },
341 'runtime': {
342 'one': {
343 'execution time limit': 'PT1M',
344 'execution retry delays': 'P0Y',
345 'simulation': {
346 'speedup factor': 1,
347 'fail cycle points': 'all',
348 'fail try 1 only': False,
349 }
350 },
351 }
352 })
353 schd = scheduler(id_)
354 async with start(schd):
355 # Submit first psuedo-job and "run" to failure:
356 one_1066 = schd.pool.get_task(ISO8601Point('1066'), 'one')
357
358 itask = run_simjob(schd, one_1066.point, 'one')
359 assert itask.state.outputs.is_message_complete('failed') is False
360
361 # Modify config as if reinstall had taken place:
362 conf_file = Path(schd.workflow_run_dir) / 'flow.cylc'
363 conf_file.write_text(
364 conf_file.read_text().replace('False', 'True'))
365
366 # Reload Workflow:
367 await commands.run_cmd(commands.reload_workflow(schd))
368
369 # Submit second psuedo-job and "run" to success:
370 itask = run_simjob(schd, one_1066.point, 'one')
371 assert itask.state.outputs.is_message_complete('succeeded') is True
372
373
374 async def test_settings_broadcast(
375 flow, scheduler, start, monkeytime, log_filter
376 ):
377 """Assert that broadcasting a change in the settings for a task
378 affects subsequent psuedo-submissions.
379 """
380 id_ = flow({
381 'scheduler': {'cycle point format': '%Y'},
382 'scheduling': {
383 'initial cycle point': '1066',
384 'graph': {'R1': 'one'}
385 },
386 'runtime': {
387 'one': {
388 'execution time limit': 'PT1S',
389 'execution retry delays': '2*PT5S',
390 'simulation': {
391 'speedup factor': 1,
392 'fail cycle points': '1066',
393 'fail try 1 only': False
394 }
395 },
396 }
397 }, defaults=False)
398 schd = scheduler(id_, paused_start=False, run_mode='simulation')
399 async with start(schd) as log:
400 itask = schd.pool.get_task(ISO8601Point('1066'), 'one')
401 itask.state.is_queued = False
402
403 # Submit the first - the sim task will fail:
404 schd.task_job_mgr.submit_nonlive_task_jobs([itask], RunMode.SIMULATION)
405 assert itask.mode_settings.sim_task_fails is True
406
407 # Let task finish.
408 monkeytime(itask.mode_settings.timeout + 1)
409 assert sim_time_check(
410 schd.task_events_mgr, [itask],
411 schd.workflow_db_mgr
412 ) is True
413
414 # The mode_settings object has been cleared:
415 assert itask.mode_settings is None
416 # Change a setting using broadcast:
417 schd.broadcast_mgr.put_broadcast(
418 ['1066'], ['one'], [{
419 'simulation': {'fail cycle points': ''},
420 }])
421 # Submit again - result is different:
422 schd.task_job_mgr.submit_nonlive_task_jobs([itask], RunMode.SIMULATION)
423 assert itask.mode_settings.sim_task_fails is False
424
425 # Assert that setting run mode on a simulation mode task fails with
426 # warning:
427 good, bad = schd.broadcast_mgr.put_broadcast(
428 ['1066'], ['one'], [{
429 'run mode': 'live',
430 }])
431 assert good == []
432 assert bad == {'settings': [{'run mode': 'live'}]}
433 record = log_filter(contains='will not be actioned')[0]
434 assert record[0] == logging.WARNING
435 assert 'run mode' not in schd.broadcast_mgr.broadcasts
436
437 # Assert Clearing the broadcast works
438 schd.broadcast_mgr.clear_broadcast()
439 schd.task_job_mgr.submit_nonlive_task_jobs([itask], RunMode.SIMULATION)
440 assert itask.mode_settings.sim_task_fails is True
441
442 # Assert that list of broadcasts doesn't change if we submit
443 # Invalid fail cycle points to broadcast.
444 itask.mode_settings = None
445 schd.broadcast_mgr.put_broadcast(
446 ['1066'], ['one'], [{
447 'simulation': {'fail cycle points': 'higadfuhasgiurguj'}
448 }])
449 schd.task_job_mgr.submit_nonlive_task_jobs([itask], RunMode.SIMULATION)
450 assert (
451 'Invalid ISO 8601 date representation: higadfuhasgiurguj'
452 in log.messages[-1])
453
454 # Check that the invalid broadcast hasn't
455 # changed the itask sim mode settings:
456 assert itask.mode_settings.sim_task_fails is True
457
458 schd.broadcast_mgr.put_broadcast(
459 ['1066'], ['one'], [{
460 'simulation': {'fail cycle points': '1'}
461 }])
462 schd.task_job_mgr.submit_nonlive_task_jobs([itask], RunMode.SIMULATION)
463 assert (
464 'Invalid ISO 8601 date representation: 1'
465 in log.messages[-1])
466
467 # Broadcast tasks will reparse correctly:
468 schd.broadcast_mgr.put_broadcast(
469 ['1066'], ['one'], [{
470 'simulation': {'fail cycle points': '1945, 1977, 1066'},
471 'execution retry delays': '3*PT2S'
472 }])
473 schd.task_job_mgr.submit_nonlive_task_jobs([itask], RunMode.SIMULATION)
474 assert itask.mode_settings.sim_task_fails is True
475 assert itask.try_timers['execution-retry'].delays == [2.0, 2.0, 2.0]
476 # n.b. rtconfig should remain unchanged, lest we cancel broadcasts:
477 assert itask.tdef.rtconfig['execution retry delays'] == [5.0, 5.0]
478
479
480 async def test_db_submit_num(
481 flow, one_conf, scheduler, run, complete, db_select
482 ):
483 """Test simulation mode correctly increments the submit_num in the DB."""
484 one_conf['runtime'] = {
485 'one': {'simulation': {'default run length': 'PT0S'}}
486 }
487 schd = scheduler(flow(one_conf), paused_start=False)
488 async with run(schd):
489 await complete(schd, '1/one', timeout=10)
490 assert db_select(schd, False, 'task_states', 'submit_num', 'status') == [
491 (1, 'succeeded'),
492 ]