Coverage for json_safety.py: 100%

68 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-22 12:55 +0000

1"""Shared JSON-safety helpers (V5.4.7, development/Problems.md #120). 

2 

3Three failure modes kept biting every JSON producer in this repo 

4independently: 

5 

61. **Non-finite floats** — `json.dumps` happily emits bare `NaN`/`Infinity` 

7 (Python-tolerant, but PostgreSQL JSONB rejects them and browser 

8 `JSON.parse` throws), so one poisoned event wedged the whole Redis → 

9 Postgres pipeline (Problems.md #120) and a NaN state value broke the 

10 webui's response parsing. 

112. **numpy scalar types** — `np.float64`/`np.int64` raise `TypeError` under 

12 `json.dumps`, silently dropping events whose payloads came straight from 

13 pandas. 

143. **Non-atomic writes** — truncate-then-`write_text` leaves a torn file 

15 whenever a reader races the writer or the writer dies mid-write; every 

16 reader of these files (`monitoring/api_server.py`, both workers) then 

17 either 500s or reads half a document. 

18 

19One module, three pure functions, stdlib-only (plus numpy when present), 

20so any layer can import it without cycles: the producers sanitize before 

21dumps, the writers go through `atomic_write_json`, and the lenient reader 

22degrades to None instead of raising. 

23""" 

24 

25from __future__ import annotations 

26 

27import json 

28import math 

29import os 

30import tempfile 

31from pathlib import Path 

32from typing import TYPE_CHECKING 

33 

34if TYPE_CHECKING: 

35 from typing import Any 

36 

37 

38def _is_numpy_number(value) -> bool: 

39 """True for np.integer/np.floating without importing numpy at module 

40 load (kept optional on purpose - this module must import everywhere).""" 

41 type_name = type(value).__module__ 

42 if type_name != "numpy": 

43 return False 

44 return hasattr(value, "item") 

45 

46 

47def sanitize_json_finite(value: Any) -> Any: 

48 """Recursively converts a structure into something `json.dumps(..., 

49 allow_nan=False)` can always serialize: 

50 

51 - non-finite floats (NaN / +/-inf) -> None ("value unavailable", 

52 the repo-wide degrade convention) 

53 - numpy integer/float scalars -> plain int/float (via .item()) 

54 - dict keys are passed through unchanged (they must already be strings) 

55 

56 Tuples/lists/dicts are rebuilt; everything else returns unchanged.""" 

57 if isinstance(value, float): 

58 return value if math.isfinite(value) else None 

59 if isinstance(value, (bool, int, str)) or value is None: 

60 return value 

61 if _is_numpy_number(value): 

62 as_python = value.item() 

63 if isinstance(as_python, float) and not math.isfinite(as_python): 

64 return None 

65 return as_python 

66 if isinstance(value, dict): 

67 return {key: sanitize_json_finite(item) for key, item in value.items()} 

68 if isinstance(value, (list, tuple)): 

69 return [sanitize_json_finite(item) for item in value] 

70 return value 

71 

72 

73def dumps_json_safe(payload: Any) -> str: 

74 """sanitize + dumps with allow_nan=False - the single serialization 

75 path shared by the Redis producers and the status-file writers, so a 

76 non-finite value can never reach Postgres JSONB or the webui again.""" 

77 return json.dumps(sanitize_json_finite(payload), allow_nan=False) 

78 

79 

80def atomic_write_json(path: Path, payload: Any, *, indent: int | None = None) -> None: 

81 """Writes payload to path via a same-directory temp file + os.replace. 

82 

83 os.replace is atomic within a filesystem, so a concurrent reader sees 

84 either the complete old file or the complete new file - never a torn 

85 one - and a writer crash mid-write leaves the previous generation 

86 intact. The temp file is cleaned up on failure.""" 

87 path = Path(path) 

88 path.parent.mkdir(parents=True, exist_ok=True) 

89 text = json.dumps(sanitize_json_finite(payload), allow_nan=False, indent=indent) 

90 fd, tmp_name = tempfile.mkstemp(dir=str(path.parent), prefix=f".{path.name}.", suffix=".tmp") 

91 try: 

92 with os.fdopen(fd, "w", encoding="utf-8") as handle: 

93 handle.write(text) 

94 handle.flush() 

95 os.fsync(handle.fileno()) 

96 os.replace(tmp_name, path) 

97 except Exception: 

98 try: 

99 os.unlink(tmp_name) 

100 except OSError: 

101 pass 

102 raise 

103 

104 

105def atomic_write_text(path: Path, text: str) -> None: 

106 """atomic_write_json's twin for plain-text content (CSV caches etc.) - 

107 same same-directory temp file + os.replace contract.""" 

108 path = Path(path) 

109 path.parent.mkdir(parents=True, exist_ok=True) 

110 fd, tmp_name = tempfile.mkstemp(dir=str(path.parent), prefix=f".{path.name}.", suffix=".tmp") 

111 try: 

112 with os.fdopen(fd, "w", encoding="utf-8") as handle: 

113 handle.write(text) 

114 handle.flush() 

115 os.fsync(handle.fileno()) 

116 os.replace(tmp_name, path) 

117 except Exception: 

118 try: 

119 os.unlink(tmp_name) 

120 except OSError: 

121 pass 

122 raise 

123 

124 

125def load_json_lenient(path: Path) -> Any: 

126 """Reads and parses path, returning None on ANY failure (missing, 

127 unreadable, mid-write torn, malformed). Every caller treats None as 

128 'not available right now' and degrades - the monitoring readers' 

129 documented contract, now actually true while a writer is mid-replace.""" 

130 try: 

131 with Path(path).open("r", encoding="utf-8") as handle: 

132 return json.load(handle) 

133 except Exception: 

134 return None