@@ -128,11 +128,37 @@ async def get_state(state_yaml: str) -> StateDict:
128128 state_yaml
129129 ): # noqa: PTH113 - isfile is fine and simpler in this case.
130130 return _get_defaults (StateDict ) # type: ignore
131- async with aiofiles .open (state_yaml , mode = "r" ) as yaml_file :
132- LOG .debug ("Loading state from yaml" )
133- content = await yaml_file .read ()
134- state_yaml_payload : StateDict = yaml .safe_load (content )
135- return state_yaml_payload
131+
132+ try :
133+ async with aiofiles .open (state_yaml , mode = "r" ) as yaml_file :
134+ LOG .debug ("Loading state from yaml" )
135+ content = await yaml_file .read ()
136+ state_yaml_payload : StateDict = yaml .safe_load (content )
137+
138+ # Handle corrupted/empty YAML files
139+ if state_yaml_payload is None :
140+ LOG .warning (
141+ "State file %s is corrupted or empty, reinitializing with defaults" ,
142+ state_yaml ,
143+ )
144+ defaults = _get_defaults (StateDict ) # type: ignore
145+ async with aiofiles .open (state_yaml , mode = "w" ) as yaml_file_write :
146+ content = yaml .dump (defaults )
147+ await yaml_file_write .write (content )
148+ return defaults
149+
150+ return state_yaml_payload
151+ except yaml .YAMLError as e :
152+ LOG .error (
153+ "Failed to parse state file %s: %s. Reinitializing with defaults." ,
154+ state_yaml ,
155+ e ,
156+ )
157+ defaults = _get_defaults (StateDict ) # type: ignore
158+ async with aiofiles .open (state_yaml , mode = "w" ) as yaml_file_write :
159+ content = yaml .dump (defaults )
160+ await yaml_file_write .write (content )
161+ return defaults
136162
137163
138164async def set_state (
0 commit comments