synth-ai 0.2.8.dev2__py3-none-any.whl → 0.4.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (740) hide show
  1. synth_ai/__init__.py +44 -24
  2. synth_ai/__main__.py +30 -3
  3. synth_ai/cli/__init__.py +103 -48
  4. synth_ai/cli/__main__.py +42 -0
  5. synth_ai/cli/_internal/__init__.py +5 -0
  6. synth_ai/cli/_internal/modal_wrapper.py +31 -0
  7. synth_ai/cli/_internal/storage.py +20 -0
  8. synth_ai/cli/_internal/typer_patch.py +47 -0
  9. synth_ai/cli/_internal/validate_task_app.py +29 -0
  10. synth_ai/cli/agents/__init__.py +17 -0
  11. synth_ai/cli/agents/claude.py +77 -0
  12. synth_ai/cli/agents/codex.py +265 -0
  13. synth_ai/cli/agents/opencode.py +253 -0
  14. synth_ai/cli/commands/__init__.py +18 -0
  15. synth_ai/cli/commands/artifacts/__init__.py +13 -0
  16. synth_ai/cli/commands/artifacts/client.py +119 -0
  17. synth_ai/cli/commands/artifacts/config.py +57 -0
  18. synth_ai/cli/commands/artifacts/core.py +24 -0
  19. synth_ai/cli/commands/artifacts/download.py +188 -0
  20. synth_ai/cli/commands/artifacts/export.py +186 -0
  21. synth_ai/cli/commands/artifacts/list.py +156 -0
  22. synth_ai/cli/commands/artifacts/parsing.py +250 -0
  23. synth_ai/cli/commands/artifacts/show.py +336 -0
  24. synth_ai/cli/commands/demo/__init__.py +3 -0
  25. synth_ai/cli/commands/demo/core.py +153 -0
  26. synth_ai/cli/commands/eval/__init__.py +10 -0
  27. synth_ai/cli/commands/eval/config.py +338 -0
  28. synth_ai/cli/commands/eval/core.py +256 -0
  29. synth_ai/cli/commands/eval/runner.py +704 -0
  30. synth_ai/cli/commands/eval/validation.py +60 -0
  31. synth_ai/cli/commands/filter/__init__.py +12 -0
  32. synth_ai/cli/commands/filter/core.py +424 -0
  33. synth_ai/cli/commands/filter/errors.py +55 -0
  34. synth_ai/cli/commands/filter/validation.py +77 -0
  35. synth_ai/cli/commands/help/__init__.py +185 -0
  36. synth_ai/cli/commands/help/core.py +72 -0
  37. synth_ai/cli/commands/scan/__init__.py +19 -0
  38. synth_ai/cli/commands/scan/cloudflare_scanner.py +403 -0
  39. synth_ai/cli/commands/scan/core.py +344 -0
  40. synth_ai/cli/commands/scan/health_checker.py +242 -0
  41. synth_ai/cli/commands/scan/local_scanner.py +278 -0
  42. synth_ai/cli/commands/scan/models.py +83 -0
  43. synth_ai/cli/commands/smoke/__init__.py +7 -0
  44. synth_ai/cli/commands/smoke/core.py +1428 -0
  45. synth_ai/cli/commands/status/__init__.py +3 -0
  46. synth_ai/cli/commands/status/client.py +91 -0
  47. synth_ai/cli/commands/status/config.py +12 -0
  48. synth_ai/cli/commands/status/errors.py +11 -0
  49. synth_ai/cli/commands/status/subcommands/__init__.py +3 -0
  50. synth_ai/cli/commands/status/subcommands/config.py +13 -0
  51. synth_ai/cli/commands/status/subcommands/files.py +34 -0
  52. synth_ai/cli/commands/status/subcommands/jobs.py +51 -0
  53. synth_ai/cli/commands/status/subcommands/models.py +35 -0
  54. synth_ai/cli/commands/status/subcommands/runs.py +34 -0
  55. synth_ai/cli/commands/status/subcommands/session.py +77 -0
  56. synth_ai/cli/commands/status/subcommands/summary.py +39 -0
  57. synth_ai/cli/commands/status/subcommands/utils.py +41 -0
  58. synth_ai/cli/commands/status/utils.py +23 -0
  59. synth_ai/cli/commands/train/__init__.py +53 -0
  60. synth_ai/cli/commands/train/core.py +22 -0
  61. synth_ai/cli/commands/train/errors.py +117 -0
  62. synth_ai/cli/commands/train/judge_schemas.py +201 -0
  63. synth_ai/cli/commands/train/judge_validation.py +305 -0
  64. synth_ai/cli/commands/train/prompt_learning_validation.py +633 -0
  65. synth_ai/cli/commands/train/validation.py +392 -0
  66. synth_ai/cli/demo_apps/__init__.py +10 -0
  67. synth_ai/cli/demo_apps/core/__init__.py +28 -0
  68. synth_ai/{demos → cli/demo_apps}/core/cli.py +783 -441
  69. synth_ai/cli/demo_apps/crafter/__init__.py +1 -0
  70. synth_ai/cli/demo_apps/crafter/crafter_fft_4b.toml +55 -0
  71. synth_ai/cli/demo_apps/crafter/grpo_crafter_task_app.py +186 -0
  72. synth_ai/cli/demo_apps/crafter/rl_from_base_qwen4b.toml +74 -0
  73. synth_ai/cli/demo_apps/demo_registry.py +176 -0
  74. synth_ai/cli/demo_apps/demo_task_apps/__init__.py +7 -0
  75. synth_ai/{demos → cli/demo_apps}/demo_task_apps/core.py +75 -37
  76. synth_ai/cli/demo_apps/demo_task_apps/crafter/__init__.py +1 -0
  77. synth_ai/cli/demo_apps/demo_task_apps/crafter/configs/crafter_fft_4b.toml +53 -0
  78. synth_ai/cli/demo_apps/demo_task_apps/crafter/configs/rl_from_base_qwen4b.toml +73 -0
  79. synth_ai/cli/demo_apps/demo_task_apps/crafter/grpo_crafter_task_app.py +185 -0
  80. synth_ai/{demos → cli/demo_apps}/demo_task_apps/math/_common.py +1 -2
  81. synth_ai/{demos → cli/demo_apps}/demo_task_apps/math/app.py +2 -1
  82. synth_ai/cli/demo_apps/demo_task_apps/math/config.toml +73 -0
  83. synth_ai/{demos → cli/demo_apps}/demo_task_apps/math/deploy_modal.py +3 -6
  84. synth_ai/cli/demo_apps/demo_task_apps/math/modal_task_app.py +738 -0
  85. synth_ai/cli/demo_apps/demo_task_apps/math/task_app_entry.py +39 -0
  86. synth_ai/cli/demo_apps/math/__init__.py +1 -0
  87. synth_ai/cli/demo_apps/math/_common.py +16 -0
  88. synth_ai/cli/demo_apps/math/app.py +38 -0
  89. synth_ai/cli/demo_apps/math/config.toml +75 -0
  90. synth_ai/cli/demo_apps/math/deploy_modal.py +54 -0
  91. synth_ai/cli/demo_apps/math/modal_task_app.py +698 -0
  92. synth_ai/cli/demo_apps/math/task_app_entry.py +53 -0
  93. synth_ai/cli/demo_apps/mipro/main.py +271 -0
  94. synth_ai/cli/demo_apps/mipro/task_app.py +922 -0
  95. synth_ai/cli/demo_apps/mipro/train_cfg.toml +92 -0
  96. synth_ai/cli/demos/__init__.py +12 -0
  97. synth_ai/cli/demos/demo.py +32 -0
  98. synth_ai/cli/demos/rl_demo.py +254 -0
  99. synth_ai/cli/deploy.py +216 -0
  100. synth_ai/cli/infra/__init__.py +14 -0
  101. synth_ai/cli/{balance.py → infra/balance.py} +16 -4
  102. synth_ai/cli/infra/mcp.py +35 -0
  103. synth_ai/cli/infra/modal_app.py +36 -0
  104. synth_ai/cli/infra/setup.py +69 -0
  105. synth_ai/cli/infra/status.py +16 -0
  106. synth_ai/cli/infra/turso.py +77 -0
  107. synth_ai/cli/lib/__init__.py +10 -0
  108. synth_ai/cli/lib/agents.py +76 -0
  109. synth_ai/cli/lib/apps/modal_app.py +101 -0
  110. synth_ai/cli/lib/apps/task_app.py +642 -0
  111. synth_ai/cli/lib/bin.py +39 -0
  112. synth_ai/cli/lib/env.py +375 -0
  113. synth_ai/cli/lib/errors.py +85 -0
  114. synth_ai/cli/lib/modal.py +315 -0
  115. synth_ai/cli/lib/plotting.py +126 -0
  116. synth_ai/cli/lib/prompt_args.py +39 -0
  117. synth_ai/cli/lib/prompts.py +284 -0
  118. synth_ai/cli/lib/sqld.py +122 -0
  119. synth_ai/cli/lib/task_app_discovery.py +884 -0
  120. synth_ai/cli/lib/task_app_env.py +295 -0
  121. synth_ai/cli/lib/train_cfgs.py +300 -0
  122. synth_ai/cli/lib/tunnel_records.py +207 -0
  123. synth_ai/cli/local/__init__.py +14 -0
  124. synth_ai/cli/local/experiment_queue/__init__.py +72 -0
  125. synth_ai/cli/local/experiment_queue/api_schemas.py +221 -0
  126. synth_ai/cli/local/experiment_queue/celery_app.py +208 -0
  127. synth_ai/cli/local/experiment_queue/config.py +128 -0
  128. synth_ai/cli/local/experiment_queue/config_utils.py +272 -0
  129. synth_ai/cli/local/experiment_queue/database.py +175 -0
  130. synth_ai/cli/local/experiment_queue/dispatcher.py +119 -0
  131. synth_ai/cli/local/experiment_queue/models.py +231 -0
  132. synth_ai/cli/local/experiment_queue/progress_info.py +160 -0
  133. synth_ai/cli/local/experiment_queue/results.py +373 -0
  134. synth_ai/cli/local/experiment_queue/schemas.py +131 -0
  135. synth_ai/cli/local/experiment_queue/service.py +344 -0
  136. synth_ai/cli/local/experiment_queue/status.py +372 -0
  137. synth_ai/cli/local/experiment_queue/status_tracker.py +360 -0
  138. synth_ai/cli/local/experiment_queue/tasks.py +1984 -0
  139. synth_ai/cli/local/experiment_queue/trace_storage.py +65 -0
  140. synth_ai/cli/local/experiment_queue/validation.py +157 -0
  141. synth_ai/cli/local/session/__init__.py +92 -0
  142. synth_ai/cli/local/session/client.py +383 -0
  143. synth_ai/cli/local/session/constants.py +63 -0
  144. synth_ai/cli/local/session/exceptions.py +105 -0
  145. synth_ai/cli/local/session/manager.py +139 -0
  146. synth_ai/cli/local/session/models.py +89 -0
  147. synth_ai/cli/local/session/query.py +110 -0
  148. synth_ai/cli/root.py +150 -108
  149. synth_ai/cli/task_apps/__init__.py +37 -0
  150. synth_ai/cli/task_apps/commands.py +3145 -0
  151. synth_ai/cli/task_apps/deploy.py +7 -0
  152. synth_ai/cli/task_apps/list.py +26 -0
  153. synth_ai/cli/task_apps/main.py +36 -0
  154. synth_ai/cli/task_apps/modal_serve.py +11 -0
  155. synth_ai/cli/task_apps/serve.py +11 -0
  156. synth_ai/cli/training/__init__.py +8 -0
  157. synth_ai/cli/training/train.py +5 -0
  158. synth_ai/cli/training/train_cfg.py +34 -0
  159. synth_ai/cli/{watch.py → training/watch.py} +13 -18
  160. synth_ai/cli/turso.py +52 -0
  161. synth_ai/cli/utils/__init__.py +8 -0
  162. synth_ai/cli/utils/experiments.py +235 -0
  163. synth_ai/cli/utils/queue.py +504 -0
  164. synth_ai/cli/{recent.py → utils/recent.py} +13 -7
  165. synth_ai/cli/{traces.py → utils/traces.py} +9 -5
  166. synth_ai/contracts/__init__.py +67 -0
  167. synth_ai/core/__init__.py +100 -0
  168. synth_ai/core/_utils/__init__.py +54 -0
  169. synth_ai/core/_utils/base_url.py +10 -0
  170. synth_ai/core/_utils/http.py +10 -0
  171. synth_ai/core/_utils/prompts.py +14 -0
  172. synth_ai/core/_utils/task_app_state.py +12 -0
  173. synth_ai/core/_utils/user_config.py +10 -0
  174. synth_ai/core/apps/common.py +116 -0
  175. synth_ai/core/auth.py +95 -0
  176. synth_ai/core/cfgs.py +240 -0
  177. synth_ai/core/config/__init__.py +16 -0
  178. synth_ai/core/config/base.py +168 -0
  179. synth_ai/core/config/resolver.py +89 -0
  180. synth_ai/core/env.py +231 -0
  181. synth_ai/core/errors.py +126 -0
  182. synth_ai/core/http.py +230 -0
  183. synth_ai/core/integrations/__init__.py +11 -0
  184. synth_ai/core/integrations/cloudflare.py +1710 -0
  185. synth_ai/core/integrations/mcp/__init__.py +6 -0
  186. synth_ai/core/integrations/mcp/__main__.py +8 -0
  187. synth_ai/core/integrations/mcp/claude.py +36 -0
  188. synth_ai/core/integrations/mcp/main.py +254 -0
  189. synth_ai/core/integrations/mcp/setup.py +100 -0
  190. synth_ai/core/integrations/modal.py +277 -0
  191. synth_ai/core/json.py +72 -0
  192. synth_ai/core/log_filter.py +99 -0
  193. synth_ai/core/logging.py +82 -0
  194. synth_ai/core/paths.py +107 -0
  195. synth_ai/core/pricing.py +109 -0
  196. synth_ai/core/process.py +233 -0
  197. synth_ai/core/ssl.py +25 -0
  198. synth_ai/core/storage/__init__.py +71 -0
  199. synth_ai/core/task_app_state.py +318 -0
  200. synth_ai/core/telemetry.py +282 -0
  201. synth_ai/{tracing_v3 → core/tracing_v3}/__init__.py +5 -1
  202. synth_ai/{tracing_v3 → core/tracing_v3}/abstractions.py +21 -4
  203. synth_ai/core/tracing_v3/config.py +229 -0
  204. synth_ai/core/tracing_v3/constants.py +21 -0
  205. synth_ai/{tracing_v3 → core/tracing_v3}/db_config.py +42 -29
  206. synth_ai/{tracing_v3 → core/tracing_v3}/decorators.py +80 -45
  207. synth_ai/{tracing_v3 → core/tracing_v3}/examples/basic_usage.py +15 -9
  208. synth_ai/{tracing_v3 → core/tracing_v3}/hooks.py +6 -4
  209. synth_ai/{tracing_v3 → core/tracing_v3}/llm_call_record_helpers.py +161 -61
  210. synth_ai/{tracing_v3 → core/tracing_v3}/migration_helper.py +1 -2
  211. synth_ai/{tracing_v3 → core/tracing_v3}/replica_sync.py +12 -7
  212. synth_ai/core/tracing_v3/serialization.py +130 -0
  213. synth_ai/{tracing_v3 → core/tracing_v3}/session_tracer.py +88 -21
  214. synth_ai/{tracing_v3 → core/tracing_v3}/storage/base.py +99 -12
  215. synth_ai/core/tracing_v3/storage/config.py +109 -0
  216. synth_ai/{tracing_v3 → core/tracing_v3}/storage/factory.py +11 -9
  217. synth_ai/{tracing_v3 → core/tracing_v3}/storage/utils.py +15 -11
  218. synth_ai/core/tracing_v3/trace_utils.py +326 -0
  219. synth_ai/core/tracing_v3/turso/__init__.py +12 -0
  220. synth_ai/core/tracing_v3/turso/daemon.py +278 -0
  221. synth_ai/{tracing_v3 → core/tracing_v3}/turso/models.py +7 -3
  222. synth_ai/core/tracing_v3/turso/native_manager.py +1385 -0
  223. synth_ai/{tracing_v3 → core/tracing_v3}/utils.py +5 -4
  224. synth_ai/core/urls.py +18 -0
  225. synth_ai/core/user_config.py +137 -0
  226. synth_ai/core/uvicorn.py +222 -0
  227. synth_ai/data/__init__.py +83 -0
  228. synth_ai/data/enums.py +123 -0
  229. synth_ai/data/rewards.py +152 -0
  230. synth_ai/data/traces.py +35 -0
  231. synth_ai/products/__init__.py +6 -0
  232. synth_ai/products/graph_evolve/__init__.py +46 -0
  233. synth_ai/products/graph_evolve/client.py +226 -0
  234. synth_ai/products/graph_evolve/config.py +591 -0
  235. synth_ai/products/graph_evolve/converters/__init__.py +42 -0
  236. synth_ai/products/graph_evolve/converters/openai_sft.py +484 -0
  237. synth_ai/products/graph_evolve/examples/hotpotqa/config.toml +109 -0
  238. synth_ai/products/graph_evolve/run.py +222 -0
  239. synth_ai/products/graph_gepa/__init__.py +23 -0
  240. synth_ai/products/graph_gepa/converters/__init__.py +19 -0
  241. synth_ai/products/graph_gepa/converters/openai_sft.py +29 -0
  242. synth_ai/sdk/__init__.py +123 -0
  243. synth_ai/sdk/api/__init__.py +1 -0
  244. synth_ai/sdk/api/models/supported.py +514 -0
  245. synth_ai/sdk/api/research_agent/__init__.py +296 -0
  246. synth_ai/sdk/api/train/__init__.py +85 -0
  247. synth_ai/sdk/api/train/builders.py +895 -0
  248. synth_ai/sdk/api/train/cli.py +2199 -0
  249. synth_ai/sdk/api/train/config_finder.py +267 -0
  250. synth_ai/sdk/api/train/configs/__init__.py +65 -0
  251. synth_ai/sdk/api/train/configs/prompt_learning.py +1706 -0
  252. synth_ai/sdk/api/train/configs/rl.py +187 -0
  253. synth_ai/sdk/api/train/configs/sft.py +99 -0
  254. synth_ai/sdk/api/train/configs/shared.py +81 -0
  255. synth_ai/sdk/api/train/context_learning.py +312 -0
  256. synth_ai/sdk/api/train/env_resolver.py +418 -0
  257. synth_ai/sdk/api/train/graph_validators.py +216 -0
  258. synth_ai/sdk/api/train/graphgen.py +984 -0
  259. synth_ai/sdk/api/train/graphgen_models.py +823 -0
  260. synth_ai/sdk/api/train/graphgen_validators.py +109 -0
  261. synth_ai/sdk/api/train/local_api.py +10 -0
  262. synth_ai/sdk/api/train/pollers.py +124 -0
  263. synth_ai/sdk/api/train/progress/__init__.py +97 -0
  264. synth_ai/sdk/api/train/progress/dataclasses.py +569 -0
  265. synth_ai/sdk/api/train/progress/events.py +326 -0
  266. synth_ai/sdk/api/train/progress/results.py +428 -0
  267. synth_ai/sdk/api/train/progress/tracker.py +641 -0
  268. synth_ai/sdk/api/train/prompt_learning.py +469 -0
  269. synth_ai/sdk/api/train/rl.py +441 -0
  270. synth_ai/sdk/api/train/sft.py +396 -0
  271. synth_ai/sdk/api/train/summary.py +522 -0
  272. synth_ai/sdk/api/train/supported_algos.py +147 -0
  273. synth_ai/sdk/api/train/task_app.py +351 -0
  274. synth_ai/sdk/api/train/utils.py +279 -0
  275. synth_ai/sdk/api/train/validators.py +2424 -0
  276. synth_ai/sdk/graphs/__init__.py +15 -0
  277. synth_ai/sdk/graphs/completions.py +570 -0
  278. synth_ai/{inference → sdk/inference}/__init__.py +0 -1
  279. synth_ai/sdk/inference/client.py +128 -0
  280. synth_ai/sdk/jobs/__init__.py +16 -0
  281. synth_ai/sdk/jobs/client.py +371 -0
  282. synth_ai/sdk/judging/__init__.py +14 -0
  283. synth_ai/sdk/judging/base.py +24 -0
  284. synth_ai/sdk/judging/client.py +40 -0
  285. synth_ai/sdk/judging/schemas.py +222 -0
  286. synth_ai/sdk/judging/types.py +42 -0
  287. synth_ai/sdk/learning/__init__.py +99 -0
  288. synth_ai/sdk/learning/algorithms.py +14 -0
  289. synth_ai/{learning → sdk/learning}/client.py +121 -30
  290. synth_ai/sdk/learning/config.py +5 -0
  291. synth_ai/{learning → sdk/learning}/constants.py +0 -2
  292. synth_ai/sdk/learning/context_learning_client.py +531 -0
  293. synth_ai/sdk/learning/context_learning_types.py +292 -0
  294. synth_ai/sdk/learning/ft_client.py +7 -0
  295. synth_ai/{learning → sdk/learning}/health.py +15 -9
  296. synth_ai/{learning → sdk/learning}/jobs.py +44 -47
  297. synth_ai/sdk/learning/prompt_extraction.py +334 -0
  298. synth_ai/sdk/learning/prompt_learning_client.py +455 -0
  299. synth_ai/sdk/learning/prompt_learning_types.py +186 -0
  300. synth_ai/{rl → sdk/learning/rl}/__init__.py +13 -8
  301. synth_ai/{learning/rl_client.py → sdk/learning/rl/client.py} +89 -77
  302. synth_ai/sdk/learning/rl/config.py +31 -0
  303. synth_ai/{rl → sdk/learning/rl}/contracts.py +5 -14
  304. synth_ai/{rl → sdk/learning/rl}/env_keys.py +45 -16
  305. synth_ai/sdk/learning/rl/secrets.py +13 -0
  306. synth_ai/sdk/learning/rl_client.py +5 -0
  307. synth_ai/sdk/learning/sft/__init__.py +29 -0
  308. synth_ai/sdk/learning/sft/client.py +95 -0
  309. synth_ai/sdk/learning/sft/config.py +270 -0
  310. synth_ai/sdk/learning/sft/data.py +698 -0
  311. synth_ai/sdk/learning/sse.py +57 -0
  312. synth_ai/sdk/learning/validators.py +52 -0
  313. synth_ai/sdk/localapi/__init__.py +40 -0
  314. synth_ai/sdk/localapi/apps/__init__.py +28 -0
  315. synth_ai/sdk/localapi/client.py +10 -0
  316. synth_ai/sdk/localapi/contracts.py +10 -0
  317. synth_ai/sdk/localapi/helpers.py +519 -0
  318. synth_ai/sdk/localapi/rollouts.py +87 -0
  319. synth_ai/sdk/localapi/server.py +29 -0
  320. synth_ai/sdk/localapi/template.py +70 -0
  321. synth_ai/sdk/streaming/__init__.py +35 -0
  322. synth_ai/sdk/streaming/config.py +94 -0
  323. synth_ai/sdk/streaming/handlers.py +1997 -0
  324. synth_ai/sdk/streaming/streamer.py +713 -0
  325. synth_ai/sdk/streaming/types.py +112 -0
  326. synth_ai/sdk/task/__init__.py +164 -0
  327. synth_ai/sdk/task/apps/__init__.py +169 -0
  328. synth_ai/sdk/task/auth.py +165 -0
  329. synth_ai/sdk/task/client.py +175 -0
  330. synth_ai/sdk/task/config.py +257 -0
  331. synth_ai/sdk/task/contracts.py +219 -0
  332. synth_ai/sdk/task/datasets.py +108 -0
  333. synth_ai/sdk/task/errors.py +50 -0
  334. synth_ai/sdk/task/health.py +34 -0
  335. synth_ai/sdk/task/in_process.py +1190 -0
  336. synth_ai/sdk/task/in_process_runner.py +314 -0
  337. synth_ai/sdk/task/inference_api.py +299 -0
  338. synth_ai/sdk/task/json.py +111 -0
  339. synth_ai/sdk/task/proxy.py +287 -0
  340. synth_ai/sdk/task/rubrics/__init__.py +55 -0
  341. synth_ai/sdk/task/rubrics/loaders.py +156 -0
  342. synth_ai/sdk/task/rubrics/models.py +57 -0
  343. synth_ai/sdk/task/rubrics/scoring.py +116 -0
  344. synth_ai/sdk/task/rubrics/strict.py +149 -0
  345. synth_ai/sdk/task/rubrics.py +219 -0
  346. synth_ai/sdk/task/server.py +631 -0
  347. synth_ai/sdk/task/trace_correlation_helpers.py +539 -0
  348. synth_ai/sdk/task/tracing_utils.py +95 -0
  349. synth_ai/sdk/task/validators.py +441 -0
  350. synth_ai/sdk/task/vendors.py +59 -0
  351. synth_ai/sdk/training/__init__.py +102 -0
  352. synth_ai/sdk/tunnels/__init__.py +83 -0
  353. synth_ai/sdk/tunnels/cleanup.py +83 -0
  354. synth_ai/sdk/tunnels/ports.py +120 -0
  355. synth_ai/utils/__init__.py +213 -0
  356. synth_ai-0.4.3.dist-info/METADATA +262 -0
  357. synth_ai-0.4.3.dist-info/RECORD +370 -0
  358. {synth_ai-0.2.8.dev2.dist-info → synth_ai-0.4.3.dist-info}/entry_points.txt +0 -1
  359. synth_ai/cli/calc.py +0 -69
  360. synth_ai/cli/demo.py +0 -144
  361. synth_ai/cli/legacy_root_backup.py +0 -470
  362. synth_ai/cli/man.py +0 -106
  363. synth_ai/cli/rl_demo.py +0 -202
  364. synth_ai/cli/status.py +0 -133
  365. synth_ai/config/base_url.py +0 -107
  366. synth_ai/core/experiment.py +0 -15
  367. synth_ai/core/system.py +0 -15
  368. synth_ai/demos/core/__init__.py +0 -1
  369. synth_ai/demos/demo_task_apps/__init__.py +0 -1
  370. synth_ai/demos/demo_task_apps/math/config.toml +0 -129
  371. synth_ai/demos/demo_task_apps/math/deploy_task_app.sh +0 -22
  372. synth_ai/demos/demo_task_apps/math/modal_task_app.py +0 -415
  373. synth_ai/environments/__init__.py +0 -31
  374. synth_ai/environments/environment/__init__.py +0 -1
  375. synth_ai/environments/environment/artifacts/__init__.py +0 -1
  376. synth_ai/environments/environment/artifacts/base.py +0 -52
  377. synth_ai/environments/environment/core.py +0 -67
  378. synth_ai/environments/environment/db/__init__.py +0 -1
  379. synth_ai/environments/environment/db/sqlite.py +0 -45
  380. synth_ai/environments/environment/registry.py +0 -233
  381. synth_ai/environments/environment/resources/sqlite.py +0 -45
  382. synth_ai/environments/environment/results.py +0 -1
  383. synth_ai/environments/environment/rewards/__init__.py +0 -1
  384. synth_ai/environments/environment/rewards/core.py +0 -29
  385. synth_ai/environments/environment/shared_engine.py +0 -26
  386. synth_ai/environments/environment/tools/__init__.py +0 -200
  387. synth_ai/environments/examples/__init__.py +0 -1
  388. synth_ai/environments/examples/bandit/__init__.py +0 -33
  389. synth_ai/environments/examples/bandit/engine.py +0 -294
  390. synth_ai/environments/examples/bandit/environment.py +0 -194
  391. synth_ai/environments/examples/bandit/taskset.py +0 -200
  392. synth_ai/environments/examples/crafter_classic/__init__.py +0 -8
  393. synth_ai/environments/examples/crafter_classic/agent_demos/analyze_semantic_words_markdown.py +0 -250
  394. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_comprehensive_evaluation.py +0 -59
  395. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_evaluation_browser.py +0 -152
  396. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_evaluation_config.toml +0 -24
  397. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_evaluation_framework.py +0 -1194
  398. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_modal_ft/crafter_synth_config.toml +0 -56
  399. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_modal_ft/filter_config_modal.toml +0 -32
  400. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_modal_ft/filter_traces_sft_turso.py +0 -738
  401. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_modal_ft/kick_off_ft_modal.py +0 -384
  402. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_modal_ft/old/analyze_action_results.py +0 -53
  403. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_modal_ft/old/analyze_agent_actions.py +0 -178
  404. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_modal_ft/old/analyze_latest_run.py +0 -222
  405. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_modal_ft/old/analyze_lm_traces.py +0 -183
  406. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_modal_ft/old/analyze_no_rewards.py +0 -210
  407. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_modal_ft/old/analyze_trace_issue.py +0 -206
  408. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_modal_ft/old/check_db_schema.py +0 -49
  409. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_modal_ft/old/check_latest_results.py +0 -64
  410. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_modal_ft/old/debug_agent_responses.py +0 -88
  411. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_modal_ft/old/quick_trace_check.py +0 -77
  412. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_openai_ft/compare_experiments.py +0 -324
  413. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_openai_ft/filter_traces_sft_turso.py +0 -580
  414. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_openai_ft/kick_off_ft_oai.py +0 -362
  415. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_openai_ft/multi_model_config.toml +0 -49
  416. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_openai_ft/old/analyze_enhanced_hooks.py +0 -332
  417. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_openai_ft/old/analyze_hook_events.py +0 -97
  418. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_openai_ft/old/analyze_hook_results.py +0 -217
  419. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_openai_ft/old/check_hook_storage.py +0 -87
  420. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_openai_ft/old/check_seeds.py +0 -88
  421. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_openai_ft/old/compare_seed_performance.py +0 -195
  422. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_openai_ft/old/custom_eval_pipelines.py +0 -400
  423. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_openai_ft/old/plot_hook_frequency.py +0 -195
  424. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_openai_ft/old/seed_analysis_summary.py +0 -56
  425. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_openai_ft/run_rollouts_for_models_and_compare_v3.py +0 -858
  426. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_quick_evaluation.py +0 -52
  427. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_react_agent.py +0 -874
  428. synth_ai/environments/examples/crafter_classic/agent_demos/crafter_trace_evaluation.py +0 -1412
  429. synth_ai/environments/examples/crafter_classic/agent_demos/example_v3_usage.py +0 -216
  430. synth_ai/environments/examples/crafter_classic/agent_demos/old/compare_traces.py +0 -296
  431. synth_ai/environments/examples/crafter_classic/agent_demos/old/crafter_comprehensive_evaluation.py +0 -58
  432. synth_ai/environments/examples/crafter_classic/agent_demos/old/crafter_env_serialization.py +0 -464
  433. synth_ai/environments/examples/crafter_classic/agent_demos/old/crafter_evaluation_browser.py +0 -152
  434. synth_ai/environments/examples/crafter_classic/agent_demos/old/crafter_quick_evaluation.py +0 -51
  435. synth_ai/environments/examples/crafter_classic/agent_demos/old/crafter_trace_evaluation.py +0 -1412
  436. synth_ai/environments/examples/crafter_classic/agent_demos/old/debug_player_loss.py +0 -112
  437. synth_ai/environments/examples/crafter_classic/agent_demos/old/diagnose_service.py +0 -203
  438. synth_ai/environments/examples/crafter_classic/agent_demos/old/diagnose_slowness.py +0 -305
  439. synth_ai/environments/examples/crafter_classic/agent_demos/old/eval_by_difficulty.py +0 -126
  440. synth_ai/environments/examples/crafter_classic/agent_demos/old/eval_example.py +0 -94
  441. synth_ai/environments/examples/crafter_classic/agent_demos/old/explore_saved_states.py +0 -142
  442. synth_ai/environments/examples/crafter_classic/agent_demos/old/filter_traces_sft.py +0 -26
  443. synth_ai/environments/examples/crafter_classic/agent_demos/old/filter_traces_sft_OLD.py +0 -984
  444. synth_ai/environments/examples/crafter_classic/agent_demos/old/generate_ft_data_gemini.py +0 -724
  445. synth_ai/environments/examples/crafter_classic/agent_demos/old/generate_ft_data_modal.py +0 -386
  446. synth_ai/environments/examples/crafter_classic/agent_demos/old/generate_ft_metadata.py +0 -205
  447. synth_ai/environments/examples/crafter_classic/agent_demos/old/kick_off_ft_gemini.py +0 -150
  448. synth_ai/environments/examples/crafter_classic/agent_demos/old/kick_off_ft_modal.py +0 -283
  449. synth_ai/environments/examples/crafter_classic/agent_demos/old/prepare_vertex_ft.py +0 -280
  450. synth_ai/environments/examples/crafter_classic/agent_demos/old/profile_env_slowness.py +0 -456
  451. synth_ai/environments/examples/crafter_classic/agent_demos/old/replicate_issue.py +0 -166
  452. synth_ai/environments/examples/crafter_classic/agent_demos/old/run_and_eval.py +0 -102
  453. synth_ai/environments/examples/crafter_classic/agent_demos/old/run_comparison.py +0 -128
  454. synth_ai/environments/examples/crafter_classic/agent_demos/old/run_qwen_rollouts.py +0 -655
  455. synth_ai/environments/examples/crafter_classic/agent_demos/old/trace_eval_OLD.py +0 -202
  456. synth_ai/environments/examples/crafter_classic/agent_demos/old/validate_openai_format.py +0 -166
  457. synth_ai/environments/examples/crafter_classic/config_logging.py +0 -111
  458. synth_ai/environments/examples/crafter_classic/debug_translation.py +0 -0
  459. synth_ai/environments/examples/crafter_classic/engine.py +0 -579
  460. synth_ai/environments/examples/crafter_classic/engine_deterministic_patch.py +0 -64
  461. synth_ai/environments/examples/crafter_classic/engine_helpers/action_map.py +0 -6
  462. synth_ai/environments/examples/crafter_classic/engine_helpers/serialization.py +0 -75
  463. synth_ai/environments/examples/crafter_classic/engine_serialization_patch_v3.py +0 -267
  464. synth_ai/environments/examples/crafter_classic/environment.py +0 -404
  465. synth_ai/environments/examples/crafter_classic/taskset.py +0 -233
  466. synth_ai/environments/examples/crafter_classic/trace_hooks_v3.py +0 -228
  467. synth_ai/environments/examples/crafter_classic/world_config_patch_simple.py +0 -299
  468. synth_ai/environments/examples/crafter_custom/__init__.py +0 -4
  469. synth_ai/environments/examples/crafter_custom/agent_demos/__init__.py +0 -1
  470. synth_ai/environments/examples/crafter_custom/agent_demos/trace_eval.py +0 -202
  471. synth_ai/environments/examples/crafter_custom/crafter/__init__.py +0 -7
  472. synth_ai/environments/examples/crafter_custom/crafter/config.py +0 -182
  473. synth_ai/environments/examples/crafter_custom/crafter/constants.py +0 -8
  474. synth_ai/environments/examples/crafter_custom/crafter/engine.py +0 -269
  475. synth_ai/environments/examples/crafter_custom/crafter/env.py +0 -262
  476. synth_ai/environments/examples/crafter_custom/crafter/objects.py +0 -417
  477. synth_ai/environments/examples/crafter_custom/crafter/recorder.py +0 -187
  478. synth_ai/environments/examples/crafter_custom/crafter/worldgen.py +0 -118
  479. synth_ai/environments/examples/crafter_custom/dataset_builder.py +0 -373
  480. synth_ai/environments/examples/crafter_custom/environment.py +0 -312
  481. synth_ai/environments/examples/crafter_custom/old/analyze_diamond_issue.py +0 -159
  482. synth_ai/environments/examples/crafter_custom/old/analyze_diamond_spawning.py +0 -158
  483. synth_ai/environments/examples/crafter_custom/old/compare_worlds.py +0 -71
  484. synth_ai/environments/examples/crafter_custom/old/dataset_stats.py +0 -105
  485. synth_ai/environments/examples/crafter_custom/old/diamond_spawning_summary.py +0 -119
  486. synth_ai/environments/examples/crafter_custom/old/example_dataset_usage.py +0 -52
  487. synth_ai/environments/examples/crafter_custom/run_dataset.py +0 -305
  488. synth_ai/environments/examples/enron/art_helpers/email_search_tools.py +0 -156
  489. synth_ai/environments/examples/enron/art_helpers/local_email_db.py +0 -281
  490. synth_ai/environments/examples/enron/art_helpers/types_enron.py +0 -25
  491. synth_ai/environments/examples/enron/engine.py +0 -295
  492. synth_ai/environments/examples/enron/environment.py +0 -166
  493. synth_ai/environments/examples/enron/taskset.py +0 -112
  494. synth_ai/environments/examples/enron/units/keyword_stats.py +0 -112
  495. synth_ai/environments/examples/minigrid/__init__.py +0 -48
  496. synth_ai/environments/examples/minigrid/agent_demos/minigrid_evaluation_framework.py +0 -1188
  497. synth_ai/environments/examples/minigrid/agent_demos/minigrid_quick_evaluation.py +0 -48
  498. synth_ai/environments/examples/minigrid/agent_demos/minigrid_react_agent.py +0 -562
  499. synth_ai/environments/examples/minigrid/agent_demos/minigrid_trace_evaluation.py +0 -221
  500. synth_ai/environments/examples/minigrid/engine.py +0 -589
  501. synth_ai/environments/examples/minigrid/environment.py +0 -274
  502. synth_ai/environments/examples/minigrid/environment_mapping.py +0 -242
  503. synth_ai/environments/examples/minigrid/puzzle_loader.py +0 -417
  504. synth_ai/environments/examples/minigrid/taskset.py +0 -583
  505. synth_ai/environments/examples/nethack/__init__.py +0 -7
  506. synth_ai/environments/examples/nethack/achievements.py +0 -337
  507. synth_ai/environments/examples/nethack/agent_demos/nethack_evaluation_framework.py +0 -981
  508. synth_ai/environments/examples/nethack/agent_demos/nethack_quick_evaluation.py +0 -74
  509. synth_ai/environments/examples/nethack/agent_demos/nethack_react_agent.py +0 -831
  510. synth_ai/environments/examples/nethack/engine.py +0 -739
  511. synth_ai/environments/examples/nethack/environment.py +0 -256
  512. synth_ai/environments/examples/nethack/helpers/__init__.py +0 -41
  513. synth_ai/environments/examples/nethack/helpers/action_mapping.py +0 -301
  514. synth_ai/environments/examples/nethack/helpers/nle_wrapper.py +0 -402
  515. synth_ai/environments/examples/nethack/helpers/observation_utils.py +0 -433
  516. synth_ai/environments/examples/nethack/helpers/recording_wrapper.py +0 -200
  517. synth_ai/environments/examples/nethack/helpers/trajectory_recorder.py +0 -269
  518. synth_ai/environments/examples/nethack/helpers/visualization/replay_viewer.py +0 -308
  519. synth_ai/environments/examples/nethack/helpers/visualization/visualizer.py +0 -431
  520. synth_ai/environments/examples/nethack/taskset.py +0 -323
  521. synth_ai/environments/examples/red/__init__.py +0 -7
  522. synth_ai/environments/examples/red/agent_demos/__init__.py +0 -1
  523. synth_ai/environments/examples/red/config_logging.py +0 -110
  524. synth_ai/environments/examples/red/engine.py +0 -694
  525. synth_ai/environments/examples/red/engine_helpers/__init__.py +0 -1
  526. synth_ai/environments/examples/red/engine_helpers/memory_map.py +0 -28
  527. synth_ai/environments/examples/red/engine_helpers/reward_components.py +0 -276
  528. synth_ai/environments/examples/red/engine_helpers/reward_library/__init__.py +0 -142
  529. synth_ai/environments/examples/red/engine_helpers/reward_library/adaptive_rewards.py +0 -57
  530. synth_ai/environments/examples/red/engine_helpers/reward_library/battle_rewards.py +0 -284
  531. synth_ai/environments/examples/red/engine_helpers/reward_library/composite_rewards.py +0 -150
  532. synth_ai/environments/examples/red/engine_helpers/reward_library/economy_rewards.py +0 -138
  533. synth_ai/environments/examples/red/engine_helpers/reward_library/efficiency_rewards.py +0 -57
  534. synth_ai/environments/examples/red/engine_helpers/reward_library/exploration_rewards.py +0 -331
  535. synth_ai/environments/examples/red/engine_helpers/reward_library/novelty_rewards.py +0 -121
  536. synth_ai/environments/examples/red/engine_helpers/reward_library/pallet_town_rewards.py +0 -559
  537. synth_ai/environments/examples/red/engine_helpers/reward_library/pokemon_rewards.py +0 -313
  538. synth_ai/environments/examples/red/engine_helpers/reward_library/social_rewards.py +0 -148
  539. synth_ai/environments/examples/red/engine_helpers/reward_library/story_rewards.py +0 -247
  540. synth_ai/environments/examples/red/engine_helpers/screen_analysis.py +0 -368
  541. synth_ai/environments/examples/red/engine_helpers/state_extraction.py +0 -140
  542. synth_ai/environments/examples/red/environment.py +0 -238
  543. synth_ai/environments/examples/red/taskset.py +0 -79
  544. synth_ai/environments/examples/red/units/__init__.py +0 -1
  545. synth_ai/environments/examples/sokoban/__init__.py +0 -1
  546. synth_ai/environments/examples/sokoban/agent_demos/sokoban_full_eval.py +0 -899
  547. synth_ai/environments/examples/sokoban/engine.py +0 -678
  548. synth_ai/environments/examples/sokoban/engine_helpers/__init__.py +0 -1
  549. synth_ai/environments/examples/sokoban/engine_helpers/room_utils.py +0 -657
  550. synth_ai/environments/examples/sokoban/engine_helpers/vendored/__init__.py +0 -18
  551. synth_ai/environments/examples/sokoban/engine_helpers/vendored/envs/__init__.py +0 -3
  552. synth_ai/environments/examples/sokoban/engine_helpers/vendored/envs/boxoban_env.py +0 -131
  553. synth_ai/environments/examples/sokoban/engine_helpers/vendored/envs/render_utils.py +0 -370
  554. synth_ai/environments/examples/sokoban/engine_helpers/vendored/envs/room_utils.py +0 -332
  555. synth_ai/environments/examples/sokoban/engine_helpers/vendored/envs/sokoban_env.py +0 -306
  556. synth_ai/environments/examples/sokoban/engine_helpers/vendored/envs/sokoban_env_fixed_targets.py +0 -67
  557. synth_ai/environments/examples/sokoban/engine_helpers/vendored/envs/sokoban_env_pull.py +0 -115
  558. synth_ai/environments/examples/sokoban/engine_helpers/vendored/envs/sokoban_env_two_player.py +0 -123
  559. synth_ai/environments/examples/sokoban/engine_helpers/vendored/envs/sokoban_env_variations.py +0 -394
  560. synth_ai/environments/examples/sokoban/environment.py +0 -229
  561. synth_ai/environments/examples/sokoban/generate_verified_puzzles.py +0 -440
  562. synth_ai/environments/examples/sokoban/puzzle_loader.py +0 -312
  563. synth_ai/environments/examples/sokoban/taskset.py +0 -428
  564. synth_ai/environments/examples/sokoban/units/astar_common.py +0 -95
  565. synth_ai/environments/examples/tictactoe/__init__.py +0 -1
  566. synth_ai/environments/examples/tictactoe/engine.py +0 -368
  567. synth_ai/environments/examples/tictactoe/environment.py +0 -240
  568. synth_ai/environments/examples/tictactoe/taskset.py +0 -215
  569. synth_ai/environments/examples/verilog/__init__.py +0 -10
  570. synth_ai/environments/examples/verilog/engine.py +0 -329
  571. synth_ai/environments/examples/verilog/environment.py +0 -350
  572. synth_ai/environments/examples/verilog/taskset.py +0 -420
  573. synth_ai/environments/examples/wordle/__init__.py +0 -29
  574. synth_ai/environments/examples/wordle/engine.py +0 -398
  575. synth_ai/environments/examples/wordle/environment.py +0 -159
  576. synth_ai/environments/examples/wordle/helpers/generate_instances_wordfreq.py +0 -75
  577. synth_ai/environments/examples/wordle/taskset.py +0 -230
  578. synth_ai/environments/reproducibility/core.py +0 -42
  579. synth_ai/environments/reproducibility/helpers.py +0 -0
  580. synth_ai/environments/reproducibility/tree.py +0 -364
  581. synth_ai/environments/service/app.py +0 -98
  582. synth_ai/environments/service/core_routes.py +0 -1020
  583. synth_ai/environments/service/external_registry.py +0 -56
  584. synth_ai/environments/service/registry.py +0 -9
  585. synth_ai/environments/stateful/__init__.py +0 -1
  586. synth_ai/environments/stateful/core.py +0 -163
  587. synth_ai/environments/stateful/engine.py +0 -21
  588. synth_ai/environments/stateful/state.py +0 -7
  589. synth_ai/environments/tasks/api.py +0 -19
  590. synth_ai/environments/tasks/core.py +0 -80
  591. synth_ai/environments/tasks/filters.py +0 -41
  592. synth_ai/environments/tasks/utils.py +0 -91
  593. synth_ai/environments/v0_observability/history.py +0 -3
  594. synth_ai/environments/v0_observability/log.py +0 -2
  595. synth_ai/evals/base.py +0 -15
  596. synth_ai/experimental/synth_oss.py +0 -446
  597. synth_ai/handshake.py +0 -63
  598. synth_ai/http.py +0 -26
  599. synth_ai/http_client.py +0 -104
  600. synth_ai/inference/client.py +0 -20
  601. synth_ai/install_sqld.sh +0 -40
  602. synth_ai/jobs/client.py +0 -246
  603. synth_ai/learning/__init__.py +0 -24
  604. synth_ai/learning/config.py +0 -43
  605. synth_ai/learning/filtering.py +0 -0
  606. synth_ai/learning/ft_client.py +0 -59
  607. synth_ai/learning/offline/dpo.py +0 -0
  608. synth_ai/learning/offline/providers.py +0 -7
  609. synth_ai/learning/offline/sft.py +0 -0
  610. synth_ai/learning/offline/shared.py +0 -0
  611. synth_ai/learning/online/grpo.py +0 -0
  612. synth_ai/learning/online/irft.py +0 -0
  613. synth_ai/learning/prompts/banking77_injection_eval.py +0 -168
  614. synth_ai/learning/prompts/gepa.py +0 -0
  615. synth_ai/learning/prompts/hello_world_in_context_injection_ex.py +0 -213
  616. synth_ai/learning/prompts/mipro.py +0 -289
  617. synth_ai/learning/prompts/random_search.py +0 -246
  618. synth_ai/learning/prompts/run_mipro_banking77.py +0 -172
  619. synth_ai/learning/prompts/run_random_search_banking77.py +0 -324
  620. synth_ai/learning/sse.py +0 -58
  621. synth_ai/learning/validators.py +0 -48
  622. synth_ai/lm/__init__.py +0 -51
  623. synth_ai/lm/caching/constants.py +0 -6
  624. synth_ai/lm/caching/dbs.py +0 -0
  625. synth_ai/lm/caching/ephemeral.py +0 -102
  626. synth_ai/lm/caching/handler.py +0 -137
  627. synth_ai/lm/caching/initialize.py +0 -11
  628. synth_ai/lm/caching/persistent.py +0 -114
  629. synth_ai/lm/config.py +0 -110
  630. synth_ai/lm/constants.py +0 -32
  631. synth_ai/lm/core/__init__.py +0 -8
  632. synth_ai/lm/core/all.py +0 -73
  633. synth_ai/lm/core/exceptions.py +0 -7
  634. synth_ai/lm/core/main.py +0 -319
  635. synth_ai/lm/core/main_v3.py +0 -594
  636. synth_ai/lm/core/synth_models.py +0 -48
  637. synth_ai/lm/core/vendor_clients.py +0 -188
  638. synth_ai/lm/cost/__init__.py +0 -0
  639. synth_ai/lm/cost/monitor.py +0 -1
  640. synth_ai/lm/cost/statefulness.py +0 -1
  641. synth_ai/lm/injection.py +0 -80
  642. synth_ai/lm/overrides.py +0 -206
  643. synth_ai/lm/provider_support/__init__.py +0 -8
  644. synth_ai/lm/provider_support/anthropic.py +0 -972
  645. synth_ai/lm/provider_support/openai.py +0 -1139
  646. synth_ai/lm/provider_support/suppress_logging.py +0 -31
  647. synth_ai/lm/structured_outputs/__init__.py +0 -0
  648. synth_ai/lm/structured_outputs/handler.py +0 -440
  649. synth_ai/lm/structured_outputs/inject.py +0 -297
  650. synth_ai/lm/structured_outputs/rehabilitate.py +0 -185
  651. synth_ai/lm/tools/__init__.py +0 -3
  652. synth_ai/lm/tools/base.py +0 -172
  653. synth_ai/lm/unified_interface.py +0 -202
  654. synth_ai/lm/vendors/__init__.py +0 -0
  655. synth_ai/lm/vendors/base.py +0 -81
  656. synth_ai/lm/vendors/core/__init__.py +0 -0
  657. synth_ai/lm/vendors/core/anthropic_api.py +0 -387
  658. synth_ai/lm/vendors/core/gemini_api.py +0 -292
  659. synth_ai/lm/vendors/core/mistral_api.py +0 -322
  660. synth_ai/lm/vendors/core/openai_api.py +0 -225
  661. synth_ai/lm/vendors/core/synth_dev_api.py +0 -0
  662. synth_ai/lm/vendors/local/__init__.py +0 -0
  663. synth_ai/lm/vendors/local/ollama.py +0 -0
  664. synth_ai/lm/vendors/openai_standard.py +0 -780
  665. synth_ai/lm/vendors/openai_standard_responses.py +0 -256
  666. synth_ai/lm/vendors/retries.py +0 -22
  667. synth_ai/lm/vendors/supported/__init__.py +0 -0
  668. synth_ai/lm/vendors/supported/custom_endpoint.py +0 -417
  669. synth_ai/lm/vendors/supported/deepseek.py +0 -69
  670. synth_ai/lm/vendors/supported/grok.py +0 -75
  671. synth_ai/lm/vendors/supported/groq.py +0 -16
  672. synth_ai/lm/vendors/supported/ollama.py +0 -15
  673. synth_ai/lm/vendors/supported/openrouter.py +0 -74
  674. synth_ai/lm/vendors/supported/together.py +0 -11
  675. synth_ai/lm/vendors/synth_client.py +0 -808
  676. synth_ai/lm/warmup.py +0 -186
  677. synth_ai/rl/secrets.py +0 -19
  678. synth_ai/scripts/verify_rewards.py +0 -100
  679. synth_ai/task/__init__.py +0 -10
  680. synth_ai/task/contracts.py +0 -120
  681. synth_ai/task/health.py +0 -28
  682. synth_ai/task/validators.py +0 -12
  683. synth_ai/tracing/__init__.py +0 -30
  684. synth_ai/tracing_v1/__init__.py +0 -33
  685. synth_ai/tracing_v3/config.py +0 -84
  686. synth_ai/tracing_v3/storage/config.py +0 -62
  687. synth_ai/tracing_v3/turso/__init__.py +0 -25
  688. synth_ai/tracing_v3/turso/daemon.py +0 -144
  689. synth_ai/tracing_v3/turso/manager.py +0 -760
  690. synth_ai/v0/tracing/__init__.py +0 -0
  691. synth_ai/v0/tracing/abstractions.py +0 -224
  692. synth_ai/v0/tracing/base_client.py +0 -91
  693. synth_ai/v0/tracing/client_manager.py +0 -131
  694. synth_ai/v0/tracing/config.py +0 -142
  695. synth_ai/v0/tracing/context.py +0 -146
  696. synth_ai/v0/tracing/decorators.py +0 -682
  697. synth_ai/v0/tracing/events/__init__.py +0 -0
  698. synth_ai/v0/tracing/events/manage.py +0 -147
  699. synth_ai/v0/tracing/events/scope.py +0 -86
  700. synth_ai/v0/tracing/events/store.py +0 -228
  701. synth_ai/v0/tracing/immediate_client.py +0 -151
  702. synth_ai/v0/tracing/local.py +0 -18
  703. synth_ai/v0/tracing/log_client_base.py +0 -73
  704. synth_ai/v0/tracing/retry_queue.py +0 -186
  705. synth_ai/v0/tracing/trackers.py +0 -515
  706. synth_ai/v0/tracing/upload.py +0 -512
  707. synth_ai/v0/tracing/utils.py +0 -9
  708. synth_ai/v0/tracing_v1/__init__.py +0 -16
  709. synth_ai/v0/tracing_v1/abstractions.py +0 -224
  710. synth_ai/v0/tracing_v1/base_client.py +0 -91
  711. synth_ai/v0/tracing_v1/client_manager.py +0 -131
  712. synth_ai/v0/tracing_v1/config.py +0 -142
  713. synth_ai/v0/tracing_v1/context.py +0 -146
  714. synth_ai/v0/tracing_v1/decorators.py +0 -703
  715. synth_ai/v0/tracing_v1/events/__init__.py +0 -0
  716. synth_ai/v0/tracing_v1/events/manage.py +0 -147
  717. synth_ai/v0/tracing_v1/events/scope.py +0 -86
  718. synth_ai/v0/tracing_v1/events/store.py +0 -228
  719. synth_ai/v0/tracing_v1/immediate_client.py +0 -151
  720. synth_ai/v0/tracing_v1/local.py +0 -18
  721. synth_ai/v0/tracing_v1/log_client_base.py +0 -73
  722. synth_ai/v0/tracing_v1/retry_queue.py +0 -186
  723. synth_ai/v0/tracing_v1/trackers.py +0 -515
  724. synth_ai/v0/tracing_v1/upload.py +0 -527
  725. synth_ai/v0/tracing_v1/utils.py +0 -9
  726. synth_ai/zyk/__init__.py +0 -30
  727. synth_ai-0.2.8.dev2.dist-info/METADATA +0 -129
  728. synth_ai-0.2.8.dev2.dist-info/RECORD +0 -420
  729. /synth_ai/{demos → cli/demo_apps}/demo_task_apps/math/__init__.py +0 -0
  730. /synth_ai/{lm/caching → core/apps}/__init__.py +0 -0
  731. /synth_ai/{tracing_v3 → core/tracing_v3}/lm_call_record_abstractions.py +0 -0
  732. /synth_ai/{tracing_v3 → core/tracing_v3}/storage/__init__.py +0 -0
  733. /synth_ai/{tracing_v3 → core/tracing_v3}/storage/exceptions.py +0 -0
  734. /synth_ai/{tracing_v3 → core/tracing_v3}/storage/types.py +0 -0
  735. /synth_ai/{compound/cais.py → py.typed} +0 -0
  736. /synth_ai/{learning → sdk/learning}/core.py +0 -0
  737. /synth_ai/{learning → sdk/learning}/gateway.py +0 -0
  738. {synth_ai-0.2.8.dev2.dist-info → synth_ai-0.4.3.dist-info}/WHEEL +0 -0
  739. {synth_ai-0.2.8.dev2.dist-info → synth_ai-0.4.3.dist-info}/licenses/LICENSE +0 -0
  740. {synth_ai-0.2.8.dev2.dist-info → synth_ai-0.4.3.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,1385 @@
1
+ """LibSQL-native trace manager prototype.
2
+
3
+ This module provides the Turso/libsql-backed trace storage implementation. It
4
+ mirrors the public surface area of the historical SQLAlchemy manager while
5
+ executing all operations directly via libsql.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import asyncio
11
+ import json
12
+ import logging
13
+ import re
14
+ from collections.abc import Callable
15
+ from dataclasses import asdict, dataclass
16
+ from datetime import UTC, datetime
17
+ from pathlib import Path
18
+ from typing import TYPE_CHECKING, Any, cast
19
+ from urllib.parse import parse_qsl, urlencode, urlparse, urlunparse
20
+
21
+ import httpx
22
+ import libsql
23
+ from sqlalchemy.engine import make_url
24
+
25
+ from ..abstractions import (
26
+ EnvironmentEvent,
27
+ LMCAISEvent,
28
+ RuntimeEvent,
29
+ SessionMessageContent,
30
+ SessionTrace,
31
+ )
32
+ from ..config import CONFIG
33
+ from ..storage.base import TraceStorage
34
+ from .models import analytics_views
35
+
36
+ if TYPE_CHECKING:
37
+ from sqlite3 import Connection as LibsqlConnection
38
+ else: # pragma: no cover - runtime fallback for typing only
39
+ LibsqlConnection = Any # type: ignore[assignment]
40
+
41
+ _LIBSQL_CONNECT_ATTR = getattr(libsql, "connect", None)
42
+ if _LIBSQL_CONNECT_ATTR is None: # pragma: no cover - defensive guard
43
+ raise RuntimeError("libsql.connect is required for NativeLibsqlTraceManager")
44
+ _libsql_connect: Callable[..., LibsqlConnection] = cast(
45
+ Callable[..., LibsqlConnection],
46
+ _LIBSQL_CONNECT_ATTR,
47
+ )
48
+
49
+ try: # pragma: no cover - exercised only when pandas present
50
+ import pandas as pd # type: ignore
51
+ except Exception: # pragma: no cover
52
+ pd = None # type: ignore[assignment]
53
+
54
+ logger = logging.getLogger(__name__)
55
+
56
+
57
+ @dataclass(slots=True)
58
+ class _ConnectionTarget:
59
+ """Resolved connection target for libsql."""
60
+
61
+ database: str
62
+ sync_url: str | None = None
63
+ auth_token: str | None = None
64
+
65
+
66
+ def _strip_auth_component(url: str) -> tuple[str, str | None]:
67
+ """Remove auth_token query parameter from URL, returning the token separately."""
68
+ parsed = urlparse(url)
69
+ if not parsed.query:
70
+ return url, None
71
+
72
+ params = dict(parse_qsl(parsed.query, keep_blank_values=True))
73
+ token = params.pop("auth_token", None)
74
+ query = urlencode(params, doseq=True)
75
+ sanitised = urlunparse(parsed._replace(query=query))
76
+ return sanitised, token
77
+
78
+
79
+ def _resolve_connection_target(db_url: str | None, auth_token: str | None) -> _ConnectionTarget:
80
+ """Normalise the configured database URL."""
81
+ url = db_url or CONFIG.db_url
82
+ sanitised, token_from_url = _strip_auth_component(url)
83
+ effective_token = auth_token or token_from_url or CONFIG.auth_token
84
+
85
+ # SQLAlchemy-compatible libsql scheme (`sqlite+libsql://<endpoint or path>`)
86
+ if sanitised.startswith("sqlite+libsql://"):
87
+ raise RuntimeError("sqlite+libsql scheme is no longer supported; use libsql://")
88
+
89
+ # Plain SQLite files: file://, /absolute/path, or relative path
90
+ # libsql.connect() handles these without sync_url or auth_token
91
+ if sanitised.startswith("file://") or sanitised.startswith("/") or "://" not in sanitised:
92
+ # Strip file:// prefix if present, libsql.connect handles both formats
93
+ db_path = sanitised.replace("file://", "") if sanitised.startswith("file://") else sanitised
94
+ return _ConnectionTarget(database=db_path, sync_url=None, auth_token=None)
95
+
96
+ # Native libsql URLs (`libsql://...`).
97
+ if sanitised.startswith("libsql://"):
98
+ return _ConnectionTarget(database=sanitised, sync_url=sanitised, auth_token=effective_token)
99
+
100
+ # Fallback to SQLAlchemy URL parsing for anything else we missed.
101
+ try:
102
+ parsed = make_url(sanitised)
103
+ driver = parsed.drivername.lower()
104
+ if driver.startswith("sqlite"):
105
+ database = parsed.database or ""
106
+ if database and database not in {":memory:", ":memory"}:
107
+ # Absolute paths are passed through; relative paths are resolved to cwd
108
+ if database.startswith("/"):
109
+ db_path = database
110
+ else:
111
+ db_path = str(Path(database).expanduser().resolve())
112
+ elif database in {":memory:", ":memory"}:
113
+ db_path = ":memory:"
114
+ else:
115
+ raise RuntimeError("SQLite URL missing database path.")
116
+ return _ConnectionTarget(database=db_path, sync_url=None, auth_token=None)
117
+ if driver.startswith("libsql"):
118
+ database = parsed.render_as_string(hide_password=False)
119
+ return _ConnectionTarget(database=database, sync_url=database, auth_token=effective_token)
120
+ except Exception: # pragma: no cover - defensive guardrail
121
+ logger.debug("Unable to parse db_url via SQLAlchemy", exc_info=True)
122
+
123
+ # Python libsql client uses HTTP API for http:// URLs, not Hrana WebSocket
124
+ # For local sqld with http:// URL, we need to ensure it points to the HTTP API port
125
+ # sqld uses two ports: Hrana WebSocket (e.g. 8080) and HTTP API (e.g. 8081)
126
+ # libsql.connect() with http:// uses HTTP API, so URL should point to HTTP API port
127
+ if sanitised.startswith(("http://", "https://", "libsql://")):
128
+ return _ConnectionTarget(database=sanitised, sync_url=sanitised, auth_token=effective_token)
129
+ raise RuntimeError(f"Unsupported tracing database URL: {sanitised}")
130
+
131
+
132
+ def _json_dumps(value: Any) -> str | None:
133
+ """Serialise Python objects as JSON compatible with the existing schema."""
134
+
135
+ def _default(obj: Any):
136
+ if isinstance(obj, datetime):
137
+ return obj.isoformat()
138
+ return str(obj)
139
+
140
+ if value is None:
141
+ return None
142
+ return json.dumps(value, separators=(",", ":"), default=_default)
143
+
144
+
145
+ def _maybe_datetime(value: Any) -> Any:
146
+ if value is None or isinstance(value, datetime):
147
+ return value
148
+ if isinstance(value, str):
149
+ try:
150
+ return datetime.fromisoformat(value)
151
+ except ValueError:
152
+ pass
153
+ return value
154
+
155
+
156
+ def _load_json(value: Any) -> Any:
157
+ if value is None or isinstance(value, dict | list):
158
+ return value or {}
159
+ if isinstance(value, str):
160
+ try:
161
+ return json.loads(value)
162
+ except (TypeError, ValueError):
163
+ return {}
164
+ return value
165
+
166
+
167
+ _TABLE_DEFINITIONS: tuple[str, ...] = (
168
+ """
169
+ CREATE TABLE IF NOT EXISTS experiments (
170
+ experiment_id VARCHAR PRIMARY KEY,
171
+ name VARCHAR NOT NULL,
172
+ description TEXT,
173
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
174
+ updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
175
+ configuration TEXT,
176
+ metadata TEXT
177
+ )
178
+ """,
179
+ """
180
+ CREATE TABLE IF NOT EXISTS systems (
181
+ system_id VARCHAR PRIMARY KEY,
182
+ name VARCHAR NOT NULL,
183
+ system_type VARCHAR,
184
+ description TEXT,
185
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
186
+ metadata TEXT
187
+ )
188
+ """,
189
+ """
190
+ CREATE TABLE IF NOT EXISTS system_versions (
191
+ version_id VARCHAR PRIMARY KEY,
192
+ system_id VARCHAR NOT NULL,
193
+ version_number VARCHAR NOT NULL,
194
+ commit_hash VARCHAR,
195
+ created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
196
+ configuration TEXT,
197
+ metadata TEXT,
198
+ FOREIGN KEY(system_id) REFERENCES systems(system_id),
199
+ UNIQUE(system_id, version_number)
200
+ )
201
+ """,
202
+ """
203
+ CREATE TABLE IF NOT EXISTS experimental_systems (
204
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
205
+ experiment_id VARCHAR NOT NULL,
206
+ system_id VARCHAR NOT NULL,
207
+ version_id VARCHAR NOT NULL,
208
+ FOREIGN KEY(experiment_id) REFERENCES experiments(experiment_id),
209
+ FOREIGN KEY(system_id) REFERENCES systems(system_id),
210
+ FOREIGN KEY(version_id) REFERENCES system_versions(version_id)
211
+ )
212
+ """,
213
+ """
214
+ CREATE TABLE IF NOT EXISTS session_traces (
215
+ session_id VARCHAR PRIMARY KEY,
216
+ created_at DATETIME NOT NULL,
217
+ num_timesteps INTEGER NOT NULL,
218
+ num_events INTEGER NOT NULL,
219
+ num_messages INTEGER NOT NULL,
220
+ metadata TEXT,
221
+ experiment_id VARCHAR,
222
+ embedding VECTOR,
223
+ FOREIGN KEY(experiment_id) REFERENCES experiments(experiment_id)
224
+ )
225
+ """,
226
+ """
227
+ CREATE TABLE IF NOT EXISTS session_timesteps (
228
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
229
+ session_id VARCHAR NOT NULL,
230
+ step_id VARCHAR NOT NULL,
231
+ step_index INTEGER NOT NULL,
232
+ turn_number INTEGER,
233
+ started_at DATETIME,
234
+ completed_at DATETIME,
235
+ num_events INTEGER,
236
+ num_messages INTEGER,
237
+ step_metadata TEXT,
238
+ UNIQUE(session_id, step_id),
239
+ FOREIGN KEY(session_id) REFERENCES session_traces(session_id)
240
+ )
241
+ """,
242
+ """
243
+ CREATE TABLE IF NOT EXISTS events (
244
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
245
+ session_id VARCHAR NOT NULL,
246
+ timestep_id INTEGER,
247
+ event_type VARCHAR NOT NULL,
248
+ system_instance_id VARCHAR,
249
+ event_time FLOAT,
250
+ message_time INTEGER,
251
+ created_at DATETIME,
252
+ model_name VARCHAR,
253
+ provider VARCHAR,
254
+ input_tokens INTEGER,
255
+ output_tokens INTEGER,
256
+ total_tokens INTEGER,
257
+ cost_usd INTEGER,
258
+ latency_ms INTEGER,
259
+ span_id VARCHAR,
260
+ trace_id VARCHAR,
261
+ call_records TEXT,
262
+ reward FLOAT,
263
+ terminated BOOLEAN,
264
+ truncated BOOLEAN,
265
+ system_state_before TEXT,
266
+ system_state_after TEXT,
267
+ metadata TEXT,
268
+ event_metadata TEXT,
269
+ embedding VECTOR,
270
+ CHECK (event_type IN ('cais', 'environment', 'runtime')),
271
+ FOREIGN KEY(session_id) REFERENCES session_traces(session_id),
272
+ FOREIGN KEY(timestep_id) REFERENCES session_timesteps(id)
273
+ )
274
+ """,
275
+ """
276
+ CREATE TABLE IF NOT EXISTS messages (
277
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
278
+ session_id VARCHAR NOT NULL,
279
+ timestep_id INTEGER,
280
+ message_type VARCHAR NOT NULL,
281
+ content TEXT NOT NULL,
282
+ timestamp DATETIME,
283
+ event_time FLOAT,
284
+ message_time INTEGER,
285
+ metadata TEXT,
286
+ embedding VECTOR,
287
+ CHECK (message_type IN ('user', 'assistant', 'system', 'tool_use', 'tool_result')),
288
+ FOREIGN KEY(session_id) REFERENCES session_traces(session_id),
289
+ FOREIGN KEY(timestep_id) REFERENCES session_timesteps(id)
290
+ )
291
+ """,
292
+ """
293
+ CREATE TABLE IF NOT EXISTS outcome_rewards (
294
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
295
+ session_id VARCHAR NOT NULL,
296
+ total_reward FLOAT NOT NULL,
297
+ achievements_count INTEGER NOT NULL,
298
+ total_steps INTEGER NOT NULL,
299
+ created_at DATETIME NOT NULL,
300
+ reward_metadata TEXT,
301
+ annotation TEXT,
302
+ FOREIGN KEY(session_id) REFERENCES session_traces(session_id)
303
+ )
304
+ """,
305
+ """
306
+ CREATE TABLE IF NOT EXISTS event_rewards (
307
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
308
+ event_id INTEGER NOT NULL,
309
+ session_id VARCHAR NOT NULL,
310
+ message_id INTEGER,
311
+ turn_number INTEGER,
312
+ reward_value FLOAT NOT NULL,
313
+ reward_type VARCHAR,
314
+ "key" VARCHAR,
315
+ annotation TEXT,
316
+ source VARCHAR,
317
+ created_at DATETIME NOT NULL,
318
+ FOREIGN KEY(event_id) REFERENCES events(id),
319
+ FOREIGN KEY(session_id) REFERENCES session_traces(session_id),
320
+ FOREIGN KEY(message_id) REFERENCES messages(id)
321
+ )
322
+ """
323
+ )
324
+
325
+
326
+ _INDEX_DEFINITIONS: tuple[str, ...] = (
327
+ "CREATE INDEX IF NOT EXISTS idx_session_created ON session_traces (created_at)",
328
+ "CREATE INDEX IF NOT EXISTS idx_session_experiment ON session_traces (experiment_id)",
329
+ "CREATE INDEX IF NOT EXISTS idx_timestep_session_step ON session_timesteps (session_id, step_id)",
330
+ "CREATE INDEX IF NOT EXISTS idx_timestep_turn ON session_timesteps (turn_number)",
331
+ "CREATE INDEX IF NOT EXISTS idx_event_session_step ON events (session_id, timestep_id)",
332
+ "CREATE INDEX IF NOT EXISTS idx_event_type ON events (event_type)",
333
+ "CREATE INDEX IF NOT EXISTS idx_event_created ON events (created_at)",
334
+ "CREATE INDEX IF NOT EXISTS idx_event_model ON events (model_name)",
335
+ "CREATE INDEX IF NOT EXISTS idx_event_trace ON events (trace_id)",
336
+ "CREATE INDEX IF NOT EXISTS idx_message_session_step ON messages (session_id, timestep_id)",
337
+ "CREATE INDEX IF NOT EXISTS idx_message_type ON messages (message_type)",
338
+ "CREATE INDEX IF NOT EXISTS idx_message_timestamp ON messages (timestamp)",
339
+ "CREATE INDEX IF NOT EXISTS idx_experiment_created ON experiments (created_at)",
340
+ "CREATE INDEX IF NOT EXISTS idx_experiment_name ON experiments (name)",
341
+ "CREATE INDEX IF NOT EXISTS idx_system_name ON systems (name)",
342
+ "CREATE INDEX IF NOT EXISTS idx_system_type ON systems (system_type)",
343
+ "CREATE UNIQUE INDEX IF NOT EXISTS uq_system_version ON system_versions (system_id, version_number)",
344
+ "CREATE INDEX IF NOT EXISTS idx_version_system ON system_versions (system_id)",
345
+ "CREATE INDEX IF NOT EXISTS idx_version_created ON system_versions (created_at)",
346
+ "CREATE UNIQUE INDEX IF NOT EXISTS uq_experiment_system ON experimental_systems (experiment_id, system_id)",
347
+ "CREATE INDEX IF NOT EXISTS idx_experimental_system ON experimental_systems (experiment_id, system_id)",
348
+ "CREATE INDEX IF NOT EXISTS idx_outcome_rewards_session ON outcome_rewards (session_id)",
349
+ "CREATE INDEX IF NOT EXISTS idx_outcome_rewards_total ON outcome_rewards (total_reward)",
350
+ "CREATE INDEX IF NOT EXISTS idx_event_rewards_session ON event_rewards (session_id)",
351
+ "CREATE INDEX IF NOT EXISTS idx_event_rewards_event ON event_rewards (event_id)",
352
+ "CREATE INDEX IF NOT EXISTS idx_event_rewards_type ON event_rewards (reward_type)",
353
+ 'CREATE INDEX IF NOT EXISTS idx_event_rewards_key ON event_rewards ("key")',
354
+ )
355
+
356
+
357
+ class NativeLibsqlTraceManager(TraceStorage):
358
+ """Libsql-backed trace manager."""
359
+
360
+ def __init__(
361
+ self,
362
+ db_url: str | None = None,
363
+ *,
364
+ auth_token: str | None = None,
365
+ ):
366
+ self._config_auth_token = auth_token
367
+ self._target = _resolve_connection_target(db_url, auth_token)
368
+ self._conn: LibsqlConnection | None = None
369
+ self._conn_lock = asyncio.Lock()
370
+ self._op_lock = asyncio.Lock()
371
+ self._initialized = False
372
+
373
+ def _open_connection(self) -> LibsqlConnection:
374
+ """Open a libsql connection for the resolved target."""
375
+ kwargs: dict[str, Any] = {}
376
+ if self._target.sync_url and self._target.sync_url.startswith("libsql://"):
377
+ kwargs["sync_url"] = self._target.sync_url
378
+ if self._target.auth_token:
379
+ kwargs["auth_token"] = self._target.auth_token
380
+ # Disable automatic background sync; ReplicaSync drives this explicitly.
381
+ kwargs.setdefault("sync_interval", 0)
382
+ logger.debug("Opening libsql connection to %s", self._target.database)
383
+ return _libsql_connect(self._target.database, **kwargs)
384
+
385
+ async def initialize(self):
386
+ """Initialise the backend."""
387
+ async with self._conn_lock:
388
+ if self._initialized:
389
+ return
390
+
391
+ # Fast-fail preflight: if using remote endpoint or local sqld, check health
392
+ # Skip health check for plain SQLite files (sync_url is None)
393
+ if self._target.sync_url:
394
+ try:
395
+ parsed = urlparse(self._target.database or "")
396
+ # Check for local sqld: http://, https://, or libsql://
397
+ if parsed.scheme in ("http", "https", "libsql"):
398
+ host_port = parsed.netloc or ""
399
+ host = (host_port.split(":", 1)[0] or "").strip().lower()
400
+ if host in {"127.0.0.1", "localhost"} and host_port:
401
+ # For http:// URLs, the port should already be the HTTP API port
402
+ # For libsql:// URLs, we need to calculate health check port
403
+ if ":" in host_port:
404
+ port = int(host_port.split(":", 1)[1])
405
+ if parsed.scheme == "libsql":
406
+ # libsql:// uses Hrana port, health check is on HTTP API port (Hrana + 1)
407
+ health_url = f"http://{host}:{port + 1}/health"
408
+ else:
409
+ # http:// already points to HTTP API port
410
+ health_url = f"http://{host}:{port}/health"
411
+ else:
412
+ health_url = f"http://{host_port}/health"
413
+ try:
414
+ async with httpx.AsyncClient(timeout=httpx.Timeout(1.0)) as client:
415
+ resp = await client.get(health_url)
416
+ if resp.status_code != 200:
417
+ raise RuntimeError(
418
+ f"Tracing backend unhealthy at {health_url} (status={resp.status_code})"
419
+ )
420
+ except Exception as exc: # pragma: no cover - network env dependent
421
+ raise RuntimeError(
422
+ f"Tracing backend not reachable at {health_url}. "
423
+ f"Start sqld with both ports: sqld --db-path <path> --hrana-listen-addr {host}:HRANA_PORT --http-listen-addr {host}:HTTP_PORT "
424
+ f"or disable tracing (TASKAPP_TRACING_ENABLED=0)."
425
+ ) from exc
426
+ except Exception:
427
+ # Propagate any preflight failure to abort early
428
+ raise
429
+
430
+ # Establish a libsql connection for future native operations.
431
+ self._conn = self._open_connection()
432
+ self._ensure_schema()
433
+ self._initialized = True
434
+
435
+ async def close(self):
436
+ """Close the libsql connection."""
437
+ async with self._conn_lock:
438
+ if self._conn:
439
+ logger.debug("Closing libsql connection to %s", self._target.database)
440
+ self._conn.close()
441
+ self._conn = None
442
+ self._initialized = False
443
+
444
+ # ------------------------------------------------------------------
445
+ # Delegated operations (to be swapped with native libsql versions).
446
+ # ------------------------------------------------------------------
447
+
448
+ async def insert_session_trace(self, trace: SessionTrace) -> str:
449
+ await self.initialize()
450
+
451
+ import logging as _logging
452
+ _logger = _logging.getLogger(__name__)
453
+ _logger.info(f"[TRACE_DEBUG] insert_session_trace START: session_id={trace.session_id}, {len(trace.markov_blanket_message_history)} messages")
454
+
455
+ session_exists = await self._session_exists(trace.session_id)
456
+ _logger.info(f"[TRACE_DEBUG] Session exists: {session_exists}")
457
+
458
+ step_id_map: dict[str, int] = {}
459
+
460
+ if session_exists:
461
+ _logger.warning(f"[TRACE_DEBUG] Session {trace.session_id} already exists, skipping events/timesteps, only updating messages!")
462
+ # Don't return early - we need to save messages!
463
+ # Just update metadata
464
+ async with self._op_lock:
465
+ conn = self._conn
466
+ assert conn is not None
467
+ conn.execute(
468
+ "UPDATE session_traces SET metadata = ? WHERE session_id = ?",
469
+ (_json_dumps(trace.metadata or {}), trace.session_id),
470
+ )
471
+ conn.commit()
472
+ # Skip events and timesteps to ensure idempotency
473
+ else:
474
+ created_at = trace.created_at or datetime.now(UTC)
475
+
476
+ async with self._op_lock:
477
+ conn = self._conn
478
+ assert conn is not None
479
+ conn.execute(
480
+ """
481
+ INSERT INTO session_traces (
482
+ session_id,
483
+ created_at,
484
+ num_timesteps,
485
+ num_events,
486
+ num_messages,
487
+ metadata
488
+ )
489
+ VALUES (?, ?, 0, 0, 0, ?)
490
+ """,
491
+ (
492
+ trace.session_id,
493
+ created_at.isoformat(),
494
+ _json_dumps(trace.metadata or {}),
495
+ ),
496
+ )
497
+ conn.commit()
498
+ _logger.info("[TRACE_DEBUG] Session row inserted")
499
+
500
+ # Only insert timesteps and events if this is a new session
501
+ for step in trace.session_time_steps:
502
+ step_db_id = await self.ensure_timestep(
503
+ trace.session_id,
504
+ step_id=step.step_id,
505
+ step_index=step.step_index,
506
+ turn_number=step.turn_number,
507
+ started_at=step.timestamp,
508
+ completed_at=step.completed_at,
509
+ metadata=step.step_metadata or {},
510
+ )
511
+ step_id_map[step.step_id] = step_db_id
512
+
513
+ for event in trace.event_history:
514
+ step_ref = None
515
+ metadata = event.metadata or {}
516
+ if isinstance(metadata, dict):
517
+ step_ref = metadata.get("step_id")
518
+ timestep_db_id = step_id_map.get(step_ref) if step_ref else None
519
+ await self.insert_event_row(
520
+ trace.session_id,
521
+ timestep_db_id=timestep_db_id,
522
+ event=event,
523
+ metadata_override=event.metadata or {},
524
+ )
525
+
526
+ import logging as _logging
527
+ _logger = _logging.getLogger(__name__)
528
+ _logger.info(f"[TRACE_DEBUG] insert_session_trace: saving {len(trace.markov_blanket_message_history)} messages (session_exists={session_exists})")
529
+
530
+ # Only insert messages if this is a new session (for idempotency)
531
+ if not session_exists:
532
+ for idx, msg in enumerate(trace.markov_blanket_message_history):
533
+ metadata = dict(getattr(msg, "metadata", {}) or {})
534
+ step_ref = metadata.get("step_id")
535
+ content_value = msg.content
536
+ if isinstance(msg.content, SessionMessageContent):
537
+ if msg.content.json_payload:
538
+ metadata.setdefault("json_payload", msg.content.json_payload)
539
+ content_value = msg.content.json_payload
540
+ else:
541
+ content_value = msg.content.as_text()
542
+ if msg.content.text:
543
+ metadata.setdefault("text", msg.content.text)
544
+ elif not isinstance(content_value, str):
545
+ try:
546
+ content_value = json.dumps(content_value, ensure_ascii=False)
547
+ except (TypeError, ValueError):
548
+ content_value = str(content_value)
549
+
550
+ _logger.info(f"[TRACE_DEBUG] Message {idx+1}: type={msg.message_type}, content_len={len(str(content_value))}")
551
+
552
+ try:
553
+ await self.insert_message_row(
554
+ trace.session_id,
555
+ timestep_db_id=step_id_map.get(step_ref) if step_ref else None,
556
+ message_type=msg.message_type,
557
+ content=content_value,
558
+ event_time=msg.time_record.event_time,
559
+ message_time=msg.time_record.message_time,
560
+ metadata=metadata,
561
+ )
562
+ _logger.info(f"[TRACE_DEBUG] Message {idx+1}: saved successfully")
563
+ except Exception as exc:
564
+ _logger.error(f"[TRACE_DEBUG] Message {idx+1}: FAILED TO SAVE: {exc}", exc_info=True)
565
+ raise
566
+ else:
567
+ _logger.info("[TRACE_DEBUG] Skipping message insertion for existing session (idempotency)")
568
+
569
+ async with self._op_lock:
570
+ conn = self._conn
571
+ assert conn is not None
572
+ conn.execute(
573
+ "UPDATE session_traces SET num_timesteps = ?, num_events = ?, num_messages = ?, metadata = ? WHERE session_id = ?",
574
+ (
575
+ len(trace.session_time_steps),
576
+ len(trace.event_history),
577
+ len(trace.markov_blanket_message_history),
578
+ _json_dumps(trace.metadata or {}),
579
+ trace.session_id,
580
+ ),
581
+ )
582
+ conn.commit()
583
+
584
+ return trace.session_id
585
+
586
+ async def get_session_trace(self, session_id: str) -> dict[str, Any] | None:
587
+ await self.initialize()
588
+
589
+ async with self._op_lock:
590
+ conn = self._conn
591
+ assert conn is not None
592
+
593
+ session_cursor = conn.execute(
594
+ """
595
+ SELECT session_id,
596
+ created_at,
597
+ num_timesteps,
598
+ num_events,
599
+ num_messages,
600
+ metadata
601
+ FROM session_traces
602
+ WHERE session_id = ?
603
+ """,
604
+ (session_id,),
605
+ )
606
+ session_row = session_cursor.fetchone()
607
+ session_cursor.close()
608
+
609
+ if not session_row:
610
+ return None
611
+
612
+ session_columns = ["session_id", "created_at", "num_timesteps", "num_events", "num_messages", "metadata"]
613
+ session_data = dict(zip(session_columns, session_row, strict=True))
614
+
615
+ timestep_cursor = conn.execute(
616
+ """
617
+ SELECT step_id,
618
+ step_index,
619
+ turn_number,
620
+ started_at,
621
+ completed_at,
622
+ step_metadata
623
+ FROM session_timesteps
624
+ WHERE session_id = ?
625
+ ORDER BY step_index ASC
626
+ """,
627
+ (session_id,),
628
+ )
629
+ timestep_rows = timestep_cursor.fetchall()
630
+ timestep_cursor.close()
631
+
632
+ return {
633
+ "session_id": session_data["session_id"],
634
+ "created_at": _maybe_datetime(session_data["created_at"]),
635
+ "num_timesteps": session_data["num_timesteps"],
636
+ "num_events": session_data["num_events"],
637
+ "num_messages": session_data["num_messages"],
638
+ "metadata": _load_json(session_data["metadata"]),
639
+ "timesteps": [
640
+ {
641
+ "step_id": row[0],
642
+ "step_index": row[1],
643
+ "turn_number": row[2],
644
+ "started_at": _maybe_datetime(row[3]),
645
+ "completed_at": _maybe_datetime(row[4]),
646
+ "metadata": _load_json(row[5]),
647
+ }
648
+ for row in timestep_rows
649
+ ],
650
+ }
651
+
652
+ async def _session_exists(self, session_id: str) -> bool:
653
+ await self.initialize()
654
+ async with self._op_lock:
655
+ conn = self._conn
656
+ assert conn is not None
657
+ cursor = conn.execute(
658
+ "SELECT 1 FROM session_traces WHERE session_id = ?", (session_id,)
659
+ )
660
+ row = cursor.fetchone()
661
+ cursor.close()
662
+ return row is not None
663
+
664
+ @staticmethod
665
+ def _normalise_params(params: dict[str, Any] | None) -> dict[str, Any]:
666
+ if not params:
667
+ return {}
668
+ normalised: dict[str, Any] = {}
669
+ for key, value in params.items():
670
+ if isinstance(value, datetime):
671
+ normalised[key] = value.isoformat()
672
+ else:
673
+ normalised[key] = value
674
+ return normalised
675
+
676
+ @staticmethod
677
+ def _prepare_query_params(query: str, params: dict[str, Any] | list[Any] | tuple[Any, ...]) -> tuple[str, tuple[Any, ...]]:
678
+ if isinstance(params, dict):
679
+ keys: list[str] = []
680
+
681
+ def _replace(match: re.Match[str]) -> str:
682
+ key = match.group(1)
683
+ keys.append(key)
684
+ return "?"
685
+
686
+ new_query = re.sub(r":([a-zA-Z_][a-zA-Z0-9_]*)", _replace, query)
687
+ if not keys:
688
+ raise ValueError("No named parameters found in query for provided mapping")
689
+ values = tuple(params[key] for key in keys)
690
+ return new_query, values
691
+ if isinstance(params, list | tuple):
692
+ return query, tuple(params)
693
+ raise TypeError("Unsupported parameter type for query execution")
694
+
695
+ def _ensure_schema(self) -> None:
696
+ if not self._conn:
697
+ raise RuntimeError("Connection not initialised")
698
+
699
+ for ddl in _TABLE_DEFINITIONS:
700
+ self._conn.execute(ddl)
701
+ self._apply_schema_migrations()
702
+ for ddl in _INDEX_DEFINITIONS:
703
+ self._conn.execute(ddl)
704
+ for view_sql in analytics_views.values():
705
+ self._conn.execute(view_sql)
706
+ self._conn.commit()
707
+
708
+ def _apply_schema_migrations(self) -> None:
709
+ """Apply forward-compatible schema changes for existing databases."""
710
+ self._migrate_outcome_rewards()
711
+
712
+ @staticmethod
713
+ def _col_value(row: Any, *, index: int, key: str) -> Any:
714
+ try:
715
+ return row[key] # type: ignore[index]
716
+ except Exception:
717
+ return row[index]
718
+
719
+ def _migrate_outcome_rewards(self) -> None:
720
+ conn = self._conn
721
+ if conn is None: # pragma: no cover - defensive guard
722
+ raise RuntimeError("Connection not initialised")
723
+
724
+ cursor = conn.execute("PRAGMA table_info(outcome_rewards)")
725
+ rows = cursor.fetchall()
726
+ cursor.close()
727
+ if not rows:
728
+ return
729
+
730
+ columns: dict[str, str] = {}
731
+ for row in rows:
732
+ name = str(self._col_value(row, index=1, key="name"))
733
+ col_type = self._col_value(row, index=2, key="type")
734
+ columns[name] = (str(col_type) if col_type is not None else "").strip().upper()
735
+
736
+ total_reward_type = columns.get("total_reward", "")
737
+ has_annotation = "annotation" in columns
738
+
739
+ # If the DB was created with total_reward INTEGER, rebuild the table to
740
+ # update the declared type and add the annotation column in one step.
741
+ if total_reward_type == "INTEGER":
742
+ conn.execute("BEGIN")
743
+ try:
744
+ conn.execute("ALTER TABLE outcome_rewards RENAME TO outcome_rewards_old")
745
+ conn.execute(
746
+ """
747
+ CREATE TABLE outcome_rewards (
748
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
749
+ session_id VARCHAR NOT NULL,
750
+ total_reward FLOAT NOT NULL,
751
+ achievements_count INTEGER NOT NULL,
752
+ total_steps INTEGER NOT NULL,
753
+ created_at DATETIME NOT NULL,
754
+ reward_metadata TEXT,
755
+ annotation TEXT,
756
+ FOREIGN KEY(session_id) REFERENCES session_traces(session_id)
757
+ )
758
+ """
759
+ )
760
+ conn.execute(
761
+ """
762
+ INSERT INTO outcome_rewards (
763
+ id,
764
+ session_id,
765
+ total_reward,
766
+ achievements_count,
767
+ total_steps,
768
+ created_at,
769
+ reward_metadata,
770
+ annotation
771
+ )
772
+ SELECT
773
+ id,
774
+ session_id,
775
+ CAST(total_reward AS FLOAT),
776
+ achievements_count,
777
+ total_steps,
778
+ created_at,
779
+ reward_metadata,
780
+ NULL
781
+ FROM outcome_rewards_old
782
+ """
783
+ )
784
+ conn.execute("DROP TABLE outcome_rewards_old")
785
+ conn.execute("COMMIT")
786
+ except Exception:
787
+ conn.execute("ROLLBACK")
788
+ raise
789
+ return
790
+
791
+ # Otherwise, add annotation column if missing.
792
+ if not has_annotation:
793
+ conn.execute("ALTER TABLE outcome_rewards ADD COLUMN annotation TEXT")
794
+
795
+ async def query_traces(self, query: str, params: dict[str, Any] | None = None) -> Any:
796
+ await self.initialize()
797
+
798
+ async with self._op_lock:
799
+ conn = self._conn
800
+ assert conn is not None
801
+ normalised = self._normalise_params(params)
802
+ if normalised:
803
+ prepared_query, prepared_params = self._prepare_query_params(query, normalised)
804
+ cursor = conn.execute(prepared_query, prepared_params)
805
+ else:
806
+ cursor = conn.execute(query)
807
+ try:
808
+ description = cursor.description or []
809
+ columns = [col[0] for col in description]
810
+ rows = cursor.fetchall()
811
+ finally:
812
+ cursor.close()
813
+
814
+ if not rows:
815
+ if pd is not None:
816
+ return pd.DataFrame(columns=list(columns)) # type: ignore[arg-type]
817
+ return []
818
+
819
+ records = [dict(zip(columns, row, strict=True)) for row in rows]
820
+ if pd is not None:
821
+ return pd.DataFrame(records)
822
+ return records
823
+
824
+ async def get_model_usage(
825
+ self,
826
+ start_date=None,
827
+ end_date=None,
828
+ model_name=None,
829
+ ) -> Any:
830
+ query = """
831
+ SELECT * FROM model_usage_stats
832
+ WHERE 1=1
833
+ """
834
+ params: dict[str, Any] = {}
835
+ if start_date:
836
+ params["start_date"] = start_date
837
+ query += " AND last_used >= :start_date"
838
+ if end_date:
839
+ params["end_date"] = end_date
840
+ query += " AND first_used <= :end_date"
841
+ if model_name:
842
+ params["model_name"] = model_name
843
+ query += " AND model_name = :model_name"
844
+ query += " ORDER BY usage_count DESC"
845
+ return await self.query_traces(query, params)
846
+
847
+ async def delete_session(self, session_id: str) -> bool:
848
+ await self.initialize()
849
+
850
+ async with self._op_lock:
851
+ conn = self._conn
852
+ assert conn is not None
853
+
854
+ cursor = conn.execute(
855
+ "SELECT 1 FROM session_traces WHERE session_id = ?", (session_id,)
856
+ )
857
+ exists = cursor.fetchone() is not None
858
+ cursor.close()
859
+ if not exists:
860
+ return False
861
+
862
+ conn.execute("DELETE FROM event_rewards WHERE session_id = ?", (session_id,))
863
+ conn.execute("DELETE FROM outcome_rewards WHERE session_id = ?", (session_id,))
864
+ conn.execute("DELETE FROM messages WHERE session_id = ?", (session_id,))
865
+ conn.execute("DELETE FROM events WHERE session_id = ?", (session_id,))
866
+ conn.execute("DELETE FROM session_timesteps WHERE session_id = ?", (session_id,))
867
+ conn.execute("DELETE FROM session_traces WHERE session_id = ?", (session_id,))
868
+ conn.commit()
869
+ return True
870
+
871
+ # Experiment helpers -------------------------------------------------
872
+ async def create_experiment(
873
+ self,
874
+ experiment_id: str,
875
+ name: str,
876
+ description: str | None = None,
877
+ configuration: dict[str, Any] | None = None,
878
+ ) -> str:
879
+ await self.initialize()
880
+
881
+ async with self._op_lock:
882
+ conn = self._conn
883
+ assert conn is not None
884
+ conn.execute(
885
+ """
886
+ INSERT INTO experiments (experiment_id, name, description, configuration)
887
+ VALUES (?, ?, ?, ?)
888
+ ON CONFLICT(experiment_id) DO UPDATE SET
889
+ name = excluded.name,
890
+ description = excluded.description,
891
+ configuration = excluded.configuration
892
+ """,
893
+ (
894
+ experiment_id,
895
+ name,
896
+ description,
897
+ _json_dumps(configuration or {}),
898
+ ),
899
+ )
900
+ conn.commit()
901
+ return experiment_id
902
+
903
+ async def link_session_to_experiment(self, session_id: str, experiment_id: str):
904
+ await self.initialize()
905
+
906
+ async with self._op_lock:
907
+ conn = self._conn
908
+ assert conn is not None
909
+ conn.execute(
910
+ "UPDATE session_traces SET experiment_id = ? WHERE session_id = ?",
911
+ (experiment_id, session_id),
912
+ )
913
+ conn.commit()
914
+
915
+ async def get_sessions_by_experiment(
916
+ self, experiment_id: str, limit: int | None = None
917
+ ) -> list[dict[str, Any]]:
918
+ await self.initialize()
919
+
920
+ sql = """
921
+ SELECT session_id,
922
+ created_at,
923
+ num_timesteps,
924
+ num_events,
925
+ num_messages,
926
+ metadata
927
+ FROM session_traces
928
+ WHERE experiment_id = ?
929
+ ORDER BY created_at DESC
930
+ """
931
+ params: list[Any] = [experiment_id]
932
+ if limit is not None:
933
+ sql += " LIMIT ?"
934
+ params.append(limit)
935
+
936
+ async with self._op_lock:
937
+ conn = self._conn
938
+ assert conn is not None
939
+ cursor = conn.execute(sql, params)
940
+ rows = cursor.fetchall()
941
+ cursor.close()
942
+
943
+ return [
944
+ {
945
+ "session_id": row[0],
946
+ "created_at": _maybe_datetime(row[1]),
947
+ "num_timesteps": row[2],
948
+ "num_events": row[3],
949
+ "num_messages": row[4],
950
+ "metadata": _load_json(row[5]),
951
+ }
952
+ for row in rows
953
+ ]
954
+
955
+ async def batch_insert_sessions(
956
+ self, traces: list[SessionTrace], batch_size: int | None = None
957
+ ) -> list[str]:
958
+ batch_size = batch_size or CONFIG.batch_size
959
+ inserted: list[str] = []
960
+
961
+ for i in range(0, len(traces), batch_size):
962
+ chunk = traces[i : i + batch_size]
963
+ for trace in chunk:
964
+ session_id = await self.insert_session_trace(trace)
965
+ inserted.append(session_id)
966
+ return inserted
967
+
968
+ # Incremental helpers -----------------------------------------------
969
+ async def ensure_session(
970
+ self,
971
+ session_id: str,
972
+ *,
973
+ created_at=None,
974
+ metadata=None,
975
+ ) -> None:
976
+ await self.initialize()
977
+
978
+ created_at_val = (created_at or datetime.now(UTC)).isoformat()
979
+ metadata_json = _json_dumps(metadata or {})
980
+
981
+ async with self._op_lock:
982
+ conn = self._conn
983
+
984
+ assert conn is not None
985
+ conn.execute(
986
+ """
987
+ INSERT INTO session_traces (
988
+ session_id, created_at, num_timesteps, num_events, num_messages, metadata
989
+ )
990
+ VALUES (?, ?, 0, 0, 0, ?)
991
+ ON CONFLICT(session_id) DO NOTHING
992
+ """,
993
+ (session_id, created_at_val, metadata_json),
994
+ )
995
+ conn.commit()
996
+
997
+ async def ensure_timestep(
998
+ self,
999
+ session_id: str,
1000
+ *,
1001
+ step_id: str,
1002
+ step_index: int,
1003
+ turn_number: int | None = None,
1004
+ started_at=None,
1005
+ completed_at=None,
1006
+ metadata=None,
1007
+ ) -> int:
1008
+ await self.initialize()
1009
+
1010
+ started_at_val = (started_at or datetime.now(UTC)).isoformat()
1011
+ completed_at_val = completed_at.isoformat() if completed_at else None
1012
+ metadata_json = _json_dumps(metadata or {})
1013
+
1014
+ async with self._op_lock:
1015
+ conn = self._conn
1016
+
1017
+ assert conn is not None
1018
+ cur = conn.execute(
1019
+ """
1020
+ SELECT id FROM session_timesteps
1021
+ WHERE session_id = ? AND step_id = ?
1022
+ """,
1023
+ (session_id, step_id),
1024
+ )
1025
+ row = cur.fetchone()
1026
+ if row:
1027
+ return int(row[0])
1028
+
1029
+ cur = conn.execute(
1030
+ """
1031
+ INSERT INTO session_timesteps (
1032
+ session_id,
1033
+ step_id,
1034
+ step_index,
1035
+ turn_number,
1036
+ started_at,
1037
+ completed_at,
1038
+ num_events,
1039
+ num_messages,
1040
+ step_metadata
1041
+ )
1042
+ VALUES (?, ?, ?, ?, ?, ?, 0, 0, ?)
1043
+ """,
1044
+ (
1045
+ session_id,
1046
+ step_id,
1047
+ step_index,
1048
+ turn_number,
1049
+ started_at_val,
1050
+ completed_at_val,
1051
+ metadata_json,
1052
+ ),
1053
+ )
1054
+ timestep_id = int(cur.lastrowid or 0)
1055
+ conn.execute(
1056
+ """
1057
+ UPDATE session_traces
1058
+ SET num_timesteps = num_timesteps + 1
1059
+ WHERE session_id = ?
1060
+ """,
1061
+ (session_id,),
1062
+ )
1063
+ conn.commit()
1064
+ return timestep_id
1065
+
1066
+ async def insert_event_row(
1067
+ self,
1068
+ session_id: str,
1069
+ *,
1070
+ timestep_db_id: int | None,
1071
+ event: Any,
1072
+ metadata_override: dict[str, Any] | None = None,
1073
+ ) -> int:
1074
+ await self.initialize()
1075
+
1076
+ if not isinstance(event, EnvironmentEvent | LMCAISEvent | RuntimeEvent):
1077
+ raise TypeError(f"Unsupported event type for native manager: {type(event)!r}")
1078
+
1079
+ metadata_json = metadata_override or event.metadata or {}
1080
+ event_extra_metadata = getattr(event, "event_metadata", None)
1081
+ system_state_before = getattr(event, "system_state_before", None)
1082
+ system_state_after = getattr(event, "system_state_after", None)
1083
+
1084
+ payload: dict[str, Any] = {
1085
+ "session_id": session_id,
1086
+ "timestep_id": timestep_db_id,
1087
+ "system_instance_id": event.system_instance_id,
1088
+ "event_time": event.time_record.event_time,
1089
+ "message_time": event.time_record.message_time,
1090
+ "metadata": metadata_json,
1091
+ "event_metadata": event_extra_metadata,
1092
+ "system_state_before": system_state_before,
1093
+ "system_state_after": system_state_after,
1094
+ }
1095
+
1096
+ if isinstance(event, LMCAISEvent):
1097
+ call_records = None
1098
+ if getattr(event, "call_records", None):
1099
+ # Handle both dataclass instances and dicts (from deserialization)
1100
+ call_records = [
1101
+ asdict(record) if not isinstance(record, dict) else record
1102
+ for record in event.call_records
1103
+ ]
1104
+ payload.update(
1105
+ {
1106
+ "event_type": "cais",
1107
+ "model_name": event.model_name,
1108
+ "provider": event.provider,
1109
+ "input_tokens": event.input_tokens,
1110
+ "output_tokens": event.output_tokens,
1111
+ "total_tokens": event.total_tokens,
1112
+ "cost_usd": int(event.cost_usd * 100) if event.cost_usd is not None else None,
1113
+ "latency_ms": event.latency_ms,
1114
+ "span_id": event.span_id,
1115
+ "trace_id": event.trace_id,
1116
+ "call_records": call_records,
1117
+ }
1118
+ )
1119
+ elif isinstance(event, EnvironmentEvent):
1120
+ payload.update(
1121
+ {
1122
+ "event_type": "environment",
1123
+ "reward": event.reward,
1124
+ "terminated": event.terminated,
1125
+ "truncated": event.truncated,
1126
+ }
1127
+ )
1128
+ elif isinstance(event, RuntimeEvent):
1129
+ payload.update(
1130
+ {
1131
+ "event_type": "runtime",
1132
+ "metadata": {**(event.metadata or {}), "actions": event.actions},
1133
+ }
1134
+ )
1135
+
1136
+ async with self._op_lock:
1137
+ conn = self._conn
1138
+
1139
+ assert conn is not None
1140
+ cur = conn.execute(
1141
+ """
1142
+ INSERT INTO events (
1143
+ session_id,
1144
+ timestep_id,
1145
+ event_type,
1146
+ system_instance_id,
1147
+ event_time,
1148
+ message_time,
1149
+ model_name,
1150
+ provider,
1151
+ input_tokens,
1152
+ output_tokens,
1153
+ total_tokens,
1154
+ cost_usd,
1155
+ latency_ms,
1156
+ span_id,
1157
+ trace_id,
1158
+ call_records,
1159
+ reward,
1160
+ terminated,
1161
+ truncated,
1162
+ system_state_before,
1163
+ system_state_after,
1164
+ metadata,
1165
+ event_metadata
1166
+ )
1167
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
1168
+ """,
1169
+ (
1170
+ payload["session_id"],
1171
+ payload["timestep_id"],
1172
+ payload.get("event_type"),
1173
+ payload["system_instance_id"],
1174
+ payload["event_time"],
1175
+ payload["message_time"],
1176
+ payload.get("model_name"),
1177
+ payload.get("provider"),
1178
+ payload.get("input_tokens"),
1179
+ payload.get("output_tokens"),
1180
+ payload.get("total_tokens"),
1181
+ payload.get("cost_usd"),
1182
+ payload.get("latency_ms"),
1183
+ payload.get("span_id"),
1184
+ payload.get("trace_id"),
1185
+ _json_dumps(payload.get("call_records")),
1186
+ payload.get("reward"),
1187
+ payload.get("terminated"),
1188
+ payload.get("truncated"),
1189
+ _json_dumps(payload.get("system_state_before")),
1190
+ _json_dumps(payload.get("system_state_after")),
1191
+ _json_dumps(payload.get("metadata")),
1192
+ _json_dumps(payload.get("event_metadata")),
1193
+ ),
1194
+ )
1195
+ event_id = int(cur.lastrowid or 0)
1196
+ conn.execute(
1197
+ """
1198
+ UPDATE session_traces
1199
+ SET num_events = num_events + 1
1200
+ WHERE session_id = ?
1201
+ """,
1202
+ (session_id,),
1203
+ )
1204
+ if timestep_db_id is not None:
1205
+ conn.execute(
1206
+ """
1207
+ UPDATE session_timesteps
1208
+ SET num_events = num_events + 1
1209
+ WHERE id = ?
1210
+ """,
1211
+ (timestep_db_id,),
1212
+ )
1213
+ conn.commit()
1214
+ return event_id
1215
+
1216
+ async def insert_message_row(
1217
+ self,
1218
+ session_id: str,
1219
+ *,
1220
+ timestep_db_id: int | None,
1221
+ message_type: str,
1222
+ content: Any,
1223
+ event_time: float | None = None,
1224
+ message_time: int | None = None,
1225
+ metadata: dict[str, Any] | None = None,
1226
+ ) -> int:
1227
+ await self.initialize()
1228
+
1229
+ metadata_payload = dict(metadata or {})
1230
+ if isinstance(content, SessionMessageContent):
1231
+ if content.json_payload:
1232
+ metadata_payload.setdefault("json_payload", content.json_payload)
1233
+ content_value = content.json_payload
1234
+ else:
1235
+ content_value = content.as_text()
1236
+ if content.text:
1237
+ metadata_payload.setdefault("text", content.text)
1238
+ else:
1239
+ content_value = content
1240
+ if not isinstance(content_value, str):
1241
+ try:
1242
+ content_value = json.dumps(content_value, ensure_ascii=False)
1243
+ except (TypeError, ValueError):
1244
+ content_value = str(content_value)
1245
+
1246
+ async with self._op_lock:
1247
+ conn = self._conn
1248
+
1249
+ assert conn is not None
1250
+ cur = conn.execute(
1251
+ """
1252
+ INSERT INTO messages (
1253
+ session_id,
1254
+ timestep_id,
1255
+ message_type,
1256
+ content,
1257
+ event_time,
1258
+ message_time,
1259
+ metadata
1260
+ )
1261
+ VALUES (?, ?, ?, ?, ?, ?, ?)
1262
+ """,
1263
+ (
1264
+ session_id,
1265
+ timestep_db_id,
1266
+ message_type,
1267
+ content_value,
1268
+ event_time,
1269
+ message_time,
1270
+ _json_dumps(metadata_payload),
1271
+ ),
1272
+ )
1273
+ message_id = int(cur.lastrowid or 0)
1274
+ conn.execute(
1275
+ """
1276
+ UPDATE session_traces
1277
+ SET num_messages = num_messages + 1
1278
+ WHERE session_id = ?
1279
+ """,
1280
+ (session_id,),
1281
+ )
1282
+ if timestep_db_id is not None:
1283
+ conn.execute(
1284
+ """
1285
+ UPDATE session_timesteps
1286
+ SET num_messages = num_messages + 1
1287
+ WHERE id = ?
1288
+ """,
1289
+ (timestep_db_id,),
1290
+ )
1291
+ conn.commit()
1292
+ return message_id
1293
+
1294
+ async def insert_outcome_reward(
1295
+ self,
1296
+ session_id: str,
1297
+ *,
1298
+ total_reward: float,
1299
+ achievements_count: int,
1300
+ total_steps: int,
1301
+ reward_metadata: dict | None = None,
1302
+ annotation: dict[str, Any] | None = None,
1303
+ ) -> int:
1304
+ await self.initialize()
1305
+
1306
+ async with self._op_lock:
1307
+ conn = self._conn
1308
+
1309
+ assert conn is not None
1310
+ cur = conn.execute(
1311
+ """
1312
+ INSERT INTO outcome_rewards (
1313
+ session_id,
1314
+ total_reward,
1315
+ achievements_count,
1316
+ total_steps,
1317
+ created_at,
1318
+ reward_metadata,
1319
+ annotation
1320
+ )
1321
+ VALUES (?, ?, ?, ?, ?, ?, ?)
1322
+ """,
1323
+ (
1324
+ session_id,
1325
+ total_reward,
1326
+ achievements_count,
1327
+ total_steps,
1328
+ datetime.now(UTC).isoformat(),
1329
+ _json_dumps(reward_metadata),
1330
+ _json_dumps(annotation),
1331
+ ),
1332
+ )
1333
+ conn.commit()
1334
+ return int(cur.lastrowid or 0)
1335
+
1336
+ async def insert_event_reward(
1337
+ self,
1338
+ session_id: str,
1339
+ *,
1340
+ event_id: int,
1341
+ message_id: int | None = None,
1342
+ turn_number: int | None = None,
1343
+ reward_value: float = 0.0,
1344
+ reward_type: str | None = None,
1345
+ key: str | None = None,
1346
+ annotation: dict[str, Any] | None = None,
1347
+ source: str | None = None,
1348
+ ) -> int:
1349
+ await self.initialize()
1350
+
1351
+ async with self._op_lock:
1352
+ conn = self._conn
1353
+
1354
+ assert conn is not None
1355
+ cur = conn.execute(
1356
+ """
1357
+ INSERT INTO event_rewards (
1358
+ event_id,
1359
+ session_id,
1360
+ message_id,
1361
+ turn_number,
1362
+ reward_value,
1363
+ reward_type,
1364
+ key,
1365
+ annotation,
1366
+ source,
1367
+ created_at
1368
+ )
1369
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
1370
+ """,
1371
+ (
1372
+ event_id,
1373
+ session_id,
1374
+ message_id,
1375
+ turn_number,
1376
+ reward_value,
1377
+ reward_type,
1378
+ key,
1379
+ _json_dumps(annotation),
1380
+ source,
1381
+ datetime.now(UTC).isoformat(),
1382
+ ),
1383
+ )
1384
+ conn.commit()
1385
+ return int(cur.lastrowid or 0)