@@ -268,6 +268,39 @@ def __setup_files(self, append):
268268 except OSError as error :
269269 raise OSError (f"Error creating files: { error } " ) from error
270270
271+ def _append_simulation_record (self , inputs_json , outputs_json ):
272+ """Append one simulation's inputs and outputs as a paired record.
273+
274+ Writes the inputs row first, then the outputs row. If the outputs write
275+ fails, the inputs file is truncated back to its size before this call so
276+ the two files do not drift out of alignment.
277+
278+ Parameters
279+ ----------
280+ inputs_json : str
281+ Serialized inputs row, including its trailing newline.
282+ outputs_json : str
283+ Serialized outputs row, including its trailing newline.
284+ """
285+ input_path = self .input_file
286+ output_path = self .output_file
287+
288+ try :
289+ previous_input_size = os .path .getsize (input_path )
290+ except OSError :
291+ previous_input_size = 0
292+
293+ with open (input_path , "a" , encoding = "utf-8" ) as f :
294+ f .write (inputs_json )
295+
296+ try :
297+ with open (output_path , "a" , encoding = "utf-8" ) as f :
298+ f .write (outputs_json )
299+ except Exception :
300+ with open (input_path , "rb+" ) as f :
301+ f .truncate (previous_input_size )
302+ raise
303+
271304 def __run_in_serial (self ):
272305 """
273306 Runs the monte carlo simulation in serial mode.
@@ -290,10 +323,7 @@ def __run_in_serial(self):
290323 inputs_json = self .__evaluate_flight_inputs (sim_monitor .count )
291324 outputs_json = self .__evaluate_flight_outputs (flight , sim_monitor .count )
292325
293- with open (self .input_file , "a" , encoding = "utf-8" ) as f :
294- f .write (inputs_json )
295- with open (self .output_file , "a" , encoding = "utf-8" ) as f :
296- f .write (outputs_json )
326+ self ._append_simulation_record (inputs_json , outputs_json )
297327
298328 sim_monitor .print_update_status ()
299329
@@ -432,10 +462,7 @@ def __sim_producer(self, seed, sim_monitor, mutex, error_event): # pylint: disa
432462
433463 break
434464
435- with open (self .input_file , "a" , encoding = "utf-8" ) as f :
436- f .write (inputs_json )
437- with open (self .output_file , "a" , encoding = "utf-8" ) as f :
438- f .write (outputs_json )
465+ self ._append_simulation_record (inputs_json , outputs_json )
439466
440467 sim_monitor .print_update_status ()
441468 finally :
0 commit comments