sediment-api 0.7.1__tar.gz → 0.8.0__tar.gz

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 (78) hide show
  1. {sediment_api-0.7.1 → sediment_api-0.8.0}/PKG-INFO +5 -5
  2. {sediment_api-0.7.1 → sediment_api-0.8.0}/pyproject.toml +5 -5
  3. {sediment_api-0.7.1 → sediment_api-0.8.0}/sediment_api/__init__.py +1 -1
  4. {sediment_api-0.7.1 → sediment_api-0.8.0}/sediment_api/reports/compute_report.py +23 -3
  5. {sediment_api-0.7.1 → sediment_api-0.8.0}/sediment_api/routers/forge.py +44 -4
  6. {sediment_api-0.7.1 → sediment_api-0.8.0}/sediment_api/routers/otlp.py +6 -1
  7. {sediment_api-0.7.1 → sediment_api-0.8.0}/sediment_api/routers/v1.py +7 -34
  8. {sediment_api-0.7.1 → sediment_api-0.8.0}/tests/test_compute_report_cli.py +74 -1
  9. {sediment_api-0.7.1 → sediment_api-0.8.0}/tests/test_push_mirror.py +167 -4
  10. {sediment_api-0.7.1 → sediment_api-0.8.0}/tests/test_v1.py +1 -1
  11. {sediment_api-0.7.1 → sediment_api-0.8.0}/.gitignore +0 -0
  12. {sediment_api-0.7.1 → sediment_api-0.8.0}/LICENSE +0 -0
  13. {sediment_api-0.7.1 → sediment_api-0.8.0}/sediment_api/config.py +0 -0
  14. {sediment_api-0.7.1 → sediment_api-0.8.0}/sediment_api/database.py +0 -0
  15. {sediment_api-0.7.1 → sediment_api-0.8.0}/sediment_api/deps.py +0 -0
  16. {sediment_api-0.7.1 → sediment_api-0.8.0}/sediment_api/ingest_envelopes.py +0 -0
  17. {sediment_api-0.7.1 → sediment_api-0.8.0}/sediment_api/main.py +0 -0
  18. {sediment_api-0.7.1 → sediment_api-0.8.0}/sediment_api/mirror_gc.py +0 -0
  19. {sediment_api-0.7.1 → sediment_api-0.8.0}/sediment_api/reports/__init__.py +0 -0
  20. {sediment_api-0.7.1 → sediment_api-0.8.0}/sediment_api/reports/abandonment_report.py +0 -0
  21. {sediment_api-0.7.1 → sediment_api-0.8.0}/sediment_api/reports/attribution_share_report.py +0 -0
  22. {sediment_api-0.7.1 → sediment_api-0.8.0}/sediment_api/reports/dataset_diagnostics.py +0 -0
  23. {sediment_api-0.7.1 → sediment_api-0.8.0}/sediment_api/reports/label_confidence_inspection.py +0 -0
  24. {sediment_api-0.7.1 → sediment_api-0.8.0}/sediment_api/reports/lifecycle_report.py +0 -0
  25. {sediment_api-0.7.1 → sediment_api-0.8.0}/sediment_api/reports/merge_retention_report.py +0 -0
  26. {sediment_api-0.7.1 → sediment_api-0.8.0}/sediment_api/reports/model_report.py +0 -0
  27. {sediment_api-0.7.1 → sediment_api-0.8.0}/sediment_api/reports/precision_report.py +0 -0
  28. {sediment_api-0.7.1 → sediment_api-0.8.0}/sediment_api/reports/recovery_yield_report.py +0 -0
  29. {sediment_api-0.7.1 → sediment_api-0.8.0}/sediment_api/routers/__init__.py +0 -0
  30. {sediment_api-0.7.1 → sediment_api-0.8.0}/sediment_api/routers/ci_vendor.py +0 -0
  31. {sediment_api-0.7.1 → sediment_api-0.8.0}/sediment_api/routers/compute.py +0 -0
  32. {sediment_api-0.7.1 → sediment_api-0.8.0}/sediment_api/routers/gateway.py +0 -0
  33. {sediment_api-0.7.1 → sediment_api-0.8.0}/sediment_api/routers/query.py +0 -0
  34. {sediment_api-0.7.1 → sediment_api-0.8.0}/sediment_api/routers/reports.py +0 -0
  35. {sediment_api-0.7.1 → sediment_api-0.8.0}/sediment_api/services/__init__.py +0 -0
  36. {sediment_api-0.7.1 → sediment_api-0.8.0}/sediment_api/services/operational_reports.py +0 -0
  37. {sediment_api-0.7.1 → sediment_api-0.8.0}/sediment_api/worker.py +0 -0
  38. {sediment_api-0.7.1 → sediment_api-0.8.0}/sediment_api/workers.py +0 -0
  39. {sediment_api-0.7.1 → sediment_api-0.8.0}/tests/conftest.py +0 -0
  40. {sediment_api-0.7.1 → sediment_api-0.8.0}/tests/test_attribution_share_report.py +0 -0
  41. {sediment_api-0.7.1 → sediment_api-0.8.0}/tests/test_baseline_gap_repro.py +0 -0
  42. {sediment_api-0.7.1 → sediment_api-0.8.0}/tests/test_bug_repro_offset.py +0 -0
  43. {sediment_api-0.7.1 → sediment_api-0.8.0}/tests/test_capture_record_isolation.py +0 -0
  44. {sediment_api-0.7.1 → sediment_api-0.8.0}/tests/test_ci_vendor.py +0 -0
  45. {sediment_api-0.7.1 → sediment_api-0.8.0}/tests/test_compute_ingest.py +0 -0
  46. {sediment_api-0.7.1 → sediment_api-0.8.0}/tests/test_config.py +0 -0
  47. {sediment_api-0.7.1 → sediment_api-0.8.0}/tests/test_context_discovery_authority.py +0 -0
  48. {sediment_api-0.7.1 → sediment_api-0.8.0}/tests/test_context_discovery_query.py +0 -0
  49. {sediment_api-0.7.1 → sediment_api-0.8.0}/tests/test_context_discovery_workers.py +0 -0
  50. {sediment_api-0.7.1 → sediment_api-0.8.0}/tests/test_context_evidence_query.py +0 -0
  51. {sediment_api-0.7.1 → sediment_api-0.8.0}/tests/test_context_query.py +0 -0
  52. {sediment_api-0.7.1 → sediment_api-0.8.0}/tests/test_credential_authorities.py +0 -0
  53. {sediment_api-0.7.1 → sediment_api-0.8.0}/tests/test_database_lifecycle.py +0 -0
  54. {sediment_api-0.7.1 → sediment_api-0.8.0}/tests/test_database_outage.py +0 -0
  55. {sediment_api-0.7.1 → sediment_api-0.8.0}/tests/test_database_role_startup.py +0 -0
  56. {sediment_api-0.7.1 → sediment_api-0.8.0}/tests/test_dataset_diagnostics_report.py +0 -0
  57. {sediment_api-0.7.1 → sediment_api-0.8.0}/tests/test_e2e_smoke.py +0 -0
  58. {sediment_api-0.7.1 → sediment_api-0.8.0}/tests/test_evidence_query.py +0 -0
  59. {sediment_api-0.7.1 → sediment_api-0.8.0}/tests/test_evidence_worker_imports.py +0 -0
  60. {sediment_api-0.7.1 → sediment_api-0.8.0}/tests/test_evidence_workers.py +0 -0
  61. {sediment_api-0.7.1 → sediment_api-0.8.0}/tests/test_gateway_capture_receipt.py +0 -0
  62. {sediment_api-0.7.1 → sediment_api-0.8.0}/tests/test_gateway_identity.py +0 -0
  63. {sediment_api-0.7.1 → sediment_api-0.8.0}/tests/test_ingest_envelopes.py +0 -0
  64. {sediment_api-0.7.1 → sediment_api-0.8.0}/tests/test_lifecycle_report_cli.py +0 -0
  65. {sediment_api-0.7.1 → sediment_api-0.8.0}/tests/test_merge_retention_cli.py +0 -0
  66. {sediment_api-0.7.1 → sediment_api-0.8.0}/tests/test_one_shot_database.py +0 -0
  67. {sediment_api-0.7.1 → sediment_api-0.8.0}/tests/test_operational_reports.py +0 -0
  68. {sediment_api-0.7.1 → sediment_api-0.8.0}/tests/test_operational_reports_service.py +0 -0
  69. {sediment_api-0.7.1 → sediment_api-0.8.0}/tests/test_postgres_gateway_tracer.py +0 -0
  70. {sediment_api-0.7.1 → sediment_api-0.8.0}/tests/test_query.py +0 -0
  71. {sediment_api-0.7.1 → sediment_api-0.8.0}/tests/test_report_attachment_scope.py +0 -0
  72. {sediment_api-0.7.1 → sediment_api-0.8.0}/tests/test_report_routes.py +0 -0
  73. {sediment_api-0.7.1 → sediment_api-0.8.0}/tests/test_repository_identity_ingest.py +0 -0
  74. {sediment_api-0.7.1 → sediment_api-0.8.0}/tests/test_repository_identity_model_service.py +0 -0
  75. {sediment_api-0.7.1 → sediment_api-0.8.0}/tests/test_repository_identity_queries.py +0 -0
  76. {sediment_api-0.7.1 → sediment_api-0.8.0}/tests/test_retrieval_authority.py +0 -0
  77. {sediment_api-0.7.1 → sediment_api-0.8.0}/tests/test_worker_processes.py +0 -0
  78. {sediment_api-0.7.1 → sediment_api-0.8.0}/tests/test_worker_routes.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: sediment-api
3
- Version: 0.7.1
3
+ Version: 0.8.0
4
4
  Summary: Sediment ingest API: facts in through three doors
5
5
  Project-URL: Source, https://github.com/sediment-ai/sediment
6
6
  Project-URL: Documentation, https://github.com/sediment-ai/sediment/tree/main/docs
@@ -13,8 +13,8 @@ Requires-Dist: anyio>=4.16.0
13
13
  Requires-Dist: fastapi>=0.142.2
14
14
  Requires-Dist: httpx>=0.27
15
15
  Requires-Dist: pydantic-settings>=2.16.2
16
- Requires-Dist: sediment-capture==0.7.1
17
- Requires-Dist: sediment-core==0.7.1
18
- Requires-Dist: sediment-derive==0.7.1
19
- Requires-Dist: sediment-export==0.7.1
16
+ Requires-Dist: sediment-capture==0.8.0
17
+ Requires-Dist: sediment-core==0.8.0
18
+ Requires-Dist: sediment-derive==0.8.0
19
+ Requires-Dist: sediment-export==0.8.0
20
20
  Requires-Dist: uvicorn>=0.54.0
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "sediment-api"
3
- version = "0.7.1"
3
+ version = "0.8.0"
4
4
  description = "Sediment ingest API: facts in through three doors"
5
5
  requires-python = ">=3.12"
6
6
  license = "AGPL-3.0-or-later"
@@ -12,10 +12,10 @@ dependencies = [
12
12
  "httpx>=0.27",
13
13
  "uvicorn>=0.54.0",
14
14
  "pydantic-settings>=2.16.2",
15
- "sediment-core==0.7.1",
16
- "sediment-capture==0.7.1",
17
- "sediment-derive==0.7.1",
18
- "sediment-export==0.7.1",
15
+ "sediment-core==0.8.0",
16
+ "sediment-capture==0.8.0",
17
+ "sediment-derive==0.8.0",
18
+ "sediment-export==0.8.0",
19
19
  ]
20
20
 
21
21
  [project.urls]
@@ -3,4 +3,4 @@
3
3
 
4
4
  # Single source for the API version string — FastAPI's ``app.version``
5
5
  # (reported by /health) and GET /v1/me both read it, so the two cannot drift.
6
- __version__ = "0.7.1"
6
+ __version__ = "0.8.0"
@@ -2,6 +2,7 @@
2
2
  """Compute report: Session completion time by final Compute allocation.
3
3
 
4
4
  sediment report compute --org acme-corp
5
+ sediment report compute --org acme-corp --since-days 30
5
6
  sediment report compute --org acme-corp --json
6
7
  sediment report compute --org acme-corp --rows-out sessions.jsonl
7
8
  """
@@ -12,12 +13,14 @@ import argparse
12
13
  import json
13
14
  import os
14
15
  import sys
16
+ from datetime import UTC, datetime
15
17
 
16
18
  from sediment_core import normalize_org_id
17
19
  from sediment_derive import ComputeArm
18
20
  from sediment_export import (
19
21
  ComputeReport,
20
22
  DurationDistribution,
23
+ OperationalReportScope,
21
24
  compute_report_to_json,
22
25
  compute_timings_to_export_rows,
23
26
  generate_compute_report_result,
@@ -60,7 +63,9 @@ def _difference(name: str, difference: MedianDifference) -> str:
60
63
  )
61
64
 
62
65
 
63
- def _print_table(report: ComputeReport) -> None:
66
+ def _print_table(report: ComputeReport, *, org_id: str, since_days: int | None) -> None:
67
+ window = f"last {since_days} day(s)" if since_days else "all history"
68
+ print(f"org: {org_id} window: {window}")
64
69
  print(f"Sessions with a Compute allocation: {report.sessions_with_allocation}")
65
70
  print(f"timed Sessions: {report.timed_sessions}")
66
71
  skipped = ", ".join(f"{key}={value}" for key, value in report.skipped.items())
@@ -103,6 +108,13 @@ def build_parser() -> argparse.ArgumentParser:
103
108
  required=not os.environ.get("SEDIMENT_ORG_ID"),
104
109
  help="org id (default: $SEDIMENT_ORG_ID)",
105
110
  )
111
+ parser.add_argument(
112
+ "--since-days",
113
+ type=int,
114
+ default=None,
115
+ help="window Compute allocations (and their Session timings) to the last N days by "
116
+ "capture time; default: all history",
117
+ )
106
118
  parser.add_argument(
107
119
  "--json", action="store_true", help="emit JSON instead of a text report"
108
120
  )
@@ -117,19 +129,27 @@ def build_parser() -> argparse.ArgumentParser:
117
129
 
118
130
  def main(argv: list[str] | None = None) -> int:
119
131
  args = build_parser().parse_args(argv)
132
+ if args.since_days is not None and args.since_days <= 0:
133
+ print("error: --since-days must be a positive integer", file=sys.stderr)
134
+ return 2
120
135
  try:
121
136
  org_id = normalize_org_id(args.org)
122
137
  except ValueError as exc:
123
138
  print(f"error: {exc}", file=sys.stderr)
124
139
  return 2
140
+ scope = (
141
+ OperationalReportScope.trailing_days(args.since_days, as_of=datetime.now(UTC))
142
+ if args.since_days is not None
143
+ else None
144
+ )
125
145
  with one_shot_fact_store(
126
146
  args.database_url, operation="generate compute report"
127
147
  ) as store:
128
- result = generate_compute_report_result(store, org_id)
148
+ result = generate_compute_report_result(store, org_id, scope=scope)
129
149
  if args.json:
130
150
  print(json.dumps(compute_report_to_json(result.report), indent=2))
131
151
  else:
132
- _print_table(result.report)
152
+ _print_table(result.report, org_id=org_id, since_days=args.since_days)
133
153
  if args.rows_out:
134
154
  try:
135
155
  write_result = write_jsonl(
@@ -202,12 +202,12 @@ def _capture_session_commit_observations(
202
202
  return observations
203
203
 
204
204
 
205
- def _store_session_commit_observations(
205
+ def _store_session_commit_observations_per_edge(
206
206
  push: Push,
207
207
  observations: list[SessionCommitObservation],
208
208
  store: FactStore,
209
- ) -> None:
210
- """Persist collected observations after releasing the mirror lock."""
209
+ ) -> tuple[int, int]:
210
+ """Store edges one at a time after a batch failure; stop on DB outage."""
211
211
  stored_count = 0
212
212
  duplicate_count = 0
213
213
  for observation in observations:
@@ -218,7 +218,7 @@ def _store_session_commit_observations(
218
218
  "session_commit_observation_database_unavailable repo=%s",
219
219
  push.repo,
220
220
  )
221
- return
221
+ return stored_count, duplicate_count
222
222
  except Exception:
223
223
  logger.exception(
224
224
  "session_commit_observation_error repo=%s commit_sha=%s",
@@ -228,6 +228,46 @@ def _store_session_commit_observations(
228
228
  continue
229
229
  stored_count += int(stored)
230
230
  duplicate_count += int(not stored)
231
+ return stored_count, duplicate_count
232
+
233
+
234
+ def _store_session_commit_observations(
235
+ push: Push,
236
+ observations: list[SessionCommitObservation],
237
+ store: FactStore,
238
+ ) -> None:
239
+ """Persist collected observations after releasing the mirror lock."""
240
+ stored_count = 0
241
+ duplicate_count = 0
242
+ try:
243
+ stored_flags = store.store_session_commit_observations(observations)
244
+ except SQLAlchemyError:
245
+ # SQLAlchemy exception text can contain statements, parameters, and
246
+ # driver diagnostics. Fall back per edge without putting any of that
247
+ # secret-bearing context in the log (same posture as
248
+ # `_derive_push_attributions`).
249
+ logger.error(
250
+ "session_commit_observation_batch_database_unavailable "
251
+ "repo=%s; falling back per edge",
252
+ push.repo,
253
+ )
254
+ stored_count, duplicate_count = _store_session_commit_observations_per_edge(
255
+ push, observations, store
256
+ )
257
+ except Exception:
258
+ # Batch insert is one transaction. A contradictory edge rolls the
259
+ # whole delivery back; fall back per edge so a committed prefix
260
+ # still survives (same fail-soft as the pre-batch loop).
261
+ logger.exception(
262
+ "session_commit_observation_batch_error repo=%s; falling back per edge",
263
+ push.repo,
264
+ )
265
+ stored_count, duplicate_count = _store_session_commit_observations_per_edge(
266
+ push, observations, store
267
+ )
268
+ else:
269
+ stored_count = sum(stored_flags)
270
+ duplicate_count = len(stored_flags) - stored_count
231
271
  logger.info(
232
272
  "session_commit_observations_captured repo=%s stored=%d duplicates=%d",
233
273
  push.repo,
@@ -108,7 +108,12 @@ def _store_translated_facts(
108
108
  rejected: list,
109
109
  retry_linkages: list,
110
110
  ) -> tuple[int, int, int, int]:
111
- """Store one translated OTLP request outside the event loop."""
111
+ """Store one translated OTLP request outside the event loop.
112
+
113
+ Decisions stay one batched transaction. Edit observations, RejectedEdits,
114
+ and RetryLinkages each commit separately so a later storage failure can
115
+ leave a committed prefix that replay deduplicates.
116
+ """
112
117
  stored = sum(store.store_decisions(decisions))
113
118
  observations_stored = sum(
114
119
  store.store_edit_observation(observation) for observation in observations
@@ -21,7 +21,7 @@ from __future__ import annotations
21
21
  from typing import Any
22
22
 
23
23
  from fastapi import APIRouter, Depends, HTTPException
24
- from sediment_core import FactStore, FactTable, NonEmptyId
24
+ from sediment_core import FactStore, NonEmptyId
25
25
 
26
26
  from .. import __version__
27
27
  from ..config import settings
@@ -29,15 +29,6 @@ from ..deps import CredentialIdentity, get_store, verify_operator_token, verify_
29
29
 
30
30
  router = APIRouter(tags=["v1"])
31
31
 
32
- _SESSION_FACT_TABLES = (
33
- FactTable.INFERENCE_CALLS,
34
- FactTable.DEVELOPER_DECISIONS,
35
- FactTable.EDIT_OBSERVATIONS,
36
- FactTable.REJECTED_EDITS,
37
- FactTable.RETRY_LINKAGES,
38
- FactTable.COMPUTE_ALLOCATIONS,
39
- )
40
-
41
32
 
42
33
  @router.get("/me")
43
34
  def me(identity: CredentialIdentity = Depends(verify_token)) -> dict[str, Any]:
@@ -66,21 +57,9 @@ def facts(
66
57
  ("visible" = not quarantined) count. Sessions are upserted metadata,
67
58
  not quarantinable facts, so they carry a bare count with no visible
68
59
  column — the same shape ``sediment facts`` prints."""
69
- tables: dict[str, dict[str, int]] = {}
70
- for table in FactTable:
71
- tables[table.value] = {
72
- "total": store.count_facts(
73
- settings.org_id, table, include_quarantined=True
74
- ),
75
- "visible": store.count_facts(settings.org_id, table),
76
- }
77
- return {
78
- "sessions": store.count_sessions(settings.org_id),
79
- "tables": tables,
80
- # quarantine_revision is the org's provenance high-water mark (MAX
81
- # quarantine-log rowid, 0 when none) — already an int from the store.
82
- "quarantine_revision": store.quarantine_revision(settings.org_id),
83
- }
60
+ # quarantine_revision is the org's provenance high-water mark (MAX
61
+ # quarantine-log rowid, 0 when none) — already an int from the store.
62
+ return store.count_fact_inventory(settings.org_id)
84
63
 
85
64
 
86
65
  @router.get("/facts/session/{session_id}")
@@ -91,16 +70,10 @@ def session_facts(
91
70
  ) -> dict[str, Any]:
92
71
  """Fact counts for one session, so a client can verify its own writes
93
72
  without treating unrelated organization-wide totals as evidence."""
94
- tables = {
95
- table.value: {
96
- "total": store.count_session_facts(
97
- settings.org_id, table, session_id, include_quarantined=True
98
- ),
99
- "visible": store.count_session_facts(settings.org_id, table, session_id),
100
- }
101
- for table in _SESSION_FACT_TABLES
73
+ return {
74
+ "session_id": session_id,
75
+ "tables": store.count_session_fact_inventory(settings.org_id, session_id),
102
76
  }
103
- return {"session_id": session_id, "tables": tables}
104
77
 
105
78
 
106
79
  @router.get("/facts/session/{session_id}/inference-calls")
@@ -17,7 +17,7 @@ from sediment_core import (
17
17
  T0 = datetime(2026, 10, 1, 12, 0, tzinfo=UTC)
18
18
 
19
19
 
20
- def _seed(store) -> None:
20
+ def _seed(store, *, captured_at: datetime | None = None) -> None:
21
21
  for index, (cpu, work_s) in enumerate(
22
22
  [(2000, 60), (2000, 70), (2000, 80), (8000, 20), (8000, 30), (8000, 40)]
23
23
  ):
@@ -30,6 +30,7 @@ def _seed(store) -> None:
30
30
  cpu_millicores=cpu,
31
31
  memory_bytes=None,
32
32
  occurred_at=T0 - timedelta(minutes=1),
33
+ captured_at=captured_at or T0,
33
34
  )
34
35
  )
35
36
  for call, end_s in enumerate((5, 10 + work_s)):
@@ -52,6 +53,7 @@ def _seed(store) -> None:
52
53
  allocation_source=ComputeAllocationSource.AGENT_REQUEST,
53
54
  cpu_millicores=16000,
54
55
  occurred_at=T0,
56
+ captured_at=captured_at or T0,
55
57
  )
56
58
  )
57
59
 
@@ -64,6 +66,7 @@ def test_compute_report_table_names_arms_comparisons_and_skips(
64
66
  assert cli.main(["--org", "acme", "--database-url", postgres_database_url]) == 0
65
67
 
66
68
  output = capsys.readouterr().out
69
+ assert "org: acme window: all history" in output
67
70
  assert "Sessions with a Compute allocation: 7" in output
68
71
  assert "timed Sessions: 6" in output
69
72
  assert "no_inference_calls=1" in output
@@ -110,3 +113,73 @@ def test_compute_report_json_and_rows_out(
110
113
  rows = [json.loads(line) for line in destination.read_text().splitlines()]
111
114
  assert [row["session_id"] for row in rows] == [f"session-{i}" for i in range(6)]
112
115
  assert rows[0]["elapsed_ms"] == 70_000
116
+
117
+
118
+ def test_compute_report_since_days_windows_and_rejects_non_positive(
119
+ postgres_store, postgres_database_url, monkeypatch, capsys
120
+ ) -> None:
121
+ _seed(postgres_store, captured_at=T0)
122
+ assert (
123
+ cli.main(
124
+ [
125
+ "--org",
126
+ "acme",
127
+ "--database-url",
128
+ postgres_database_url,
129
+ "--since-days",
130
+ "0",
131
+ ]
132
+ )
133
+ == 2
134
+ )
135
+ assert "positive integer" in capsys.readouterr().err
136
+
137
+ class FrozenDatetime(datetime):
138
+ @classmethod
139
+ def now(cls, tz=None):
140
+ return empty_now if tz is None else empty_now.astimezone(tz)
141
+
142
+ empty_now = T0 + timedelta(days=30)
143
+ monkeypatch.setattr(cli, "datetime", FrozenDatetime)
144
+ assert (
145
+ cli.main(
146
+ [
147
+ "--org",
148
+ "acme",
149
+ "--database-url",
150
+ postgres_database_url,
151
+ "--since-days",
152
+ "7",
153
+ ]
154
+ )
155
+ == 0
156
+ )
157
+ output = capsys.readouterr().out
158
+ assert "org: acme window: last 7 day(s)" in output
159
+ assert "Sessions with a Compute allocation: 0" in output
160
+ assert "arms: no data" in output
161
+
162
+ class InsideDatetime(datetime):
163
+ @classmethod
164
+ def now(cls, tz=None):
165
+ return inside_now if tz is None else inside_now.astimezone(tz)
166
+
167
+ inside_now = T0 + timedelta(days=3)
168
+ monkeypatch.setattr(cli, "datetime", InsideDatetime)
169
+ assert (
170
+ cli.main(
171
+ [
172
+ "--org",
173
+ "acme",
174
+ "--database-url",
175
+ postgres_database_url,
176
+ "--since-days",
177
+ "7",
178
+ "--json",
179
+ ]
180
+ )
181
+ == 0
182
+ )
183
+ report = json.loads(capsys.readouterr().out)
184
+ assert report["sessions_with_allocation"] == 7
185
+ assert report["timed_sessions"] == 6
@@ -33,6 +33,7 @@ from sediment_core import (
33
33
  InferenceCall,
34
34
  InferenceMessage,
35
35
  Push,
36
+ SessionCommitObservation,
36
37
  TextPart,
37
38
  )
38
39
  from sediment_derive import MirrorManager
@@ -638,15 +639,15 @@ def test_blocked_observation_store_does_not_hold_the_mirror_lock(
638
639
  store_entered = threading.Event()
639
640
  allow_store = threading.Event()
640
641
  snapshot_acquired = threading.Event()
641
- original_store = postgres_store.store_session_commit_observation
642
+ original_store = postgres_store.store_session_commit_observations
642
643
 
643
- def store_observation(observation):
644
+ def store_observations(observations):
644
645
  store_entered.set()
645
646
  assert allow_store.wait(timeout=5)
646
- return original_store(observation)
647
+ return original_store(observations)
647
648
 
648
649
  monkeypatch.setattr(
649
- postgres_store, "store_session_commit_observation", store_observation
650
+ postgres_store, "store_session_commit_observations", store_observations
650
651
  )
651
652
  refresh_thread = threading.Thread(
652
653
  target=forge._refresh_mirror, args=(push, postgres_store)
@@ -668,6 +669,168 @@ def test_blocked_observation_store_does_not_hold_the_mirror_lock(
668
669
  snapshot_thread.join(timeout=5)
669
670
 
670
671
 
672
+ def test_batch_observation_integrity_error_keeps_committed_prefix(
673
+ postgres_store, postgres_engine, caplog
674
+ ) -> None:
675
+ """A row-level IntegrityError in the batch path must not drop good edges.
676
+
677
+ ``store_session_commit_observations`` commits one transaction; on failure
678
+ forge falls back per edge so earlier observations still land — the same
679
+ fail-soft the pre-batch loop provided.
680
+ """
681
+ push = Push(
682
+ push_id="prefix-push",
683
+ org_id=settings.org_id,
684
+ provider=ForgeProvider.GITHUB,
685
+ repo=REPO,
686
+ clone_url="https://example.test/acme/backend.git",
687
+ ref="refs/heads/main",
688
+ before_sha="0" * 40,
689
+ after_sha="a" * 40,
690
+ )
691
+ postgres_store.store_push(push)
692
+ good = SessionCommitObservation(
693
+ observation_id="prefix-good",
694
+ org_id=settings.org_id,
695
+ repo=REPO,
696
+ commit_sha="a" * 40,
697
+ session_id="session-good",
698
+ source_push_id=push.push_id,
699
+ captured_at=datetime(2026, 8, 22, 12, 0, tzinfo=UTC),
700
+ )
701
+ blocked = SessionCommitObservation(
702
+ observation_id="prefix-blocked",
703
+ org_id=settings.org_id,
704
+ repo=REPO,
705
+ commit_sha="b" * 40,
706
+ session_id="session-blocked",
707
+ source_push_id=push.push_id,
708
+ captured_at=datetime(2026, 8, 22, 12, 1, tzinfo=UTC),
709
+ )
710
+ with postgres_engine.begin() as connection:
711
+ connection.exec_driver_sql(
712
+ "ALTER TABLE session_commit_observations "
713
+ "ADD CONSTRAINT reject_blocked_session "
714
+ "CHECK (session_id <> 'session-blocked')"
715
+ )
716
+ caplog.set_level(logging.ERROR, logger="sediment.api.forge")
717
+ try:
718
+ forge._store_session_commit_observations(push, [good, blocked], postgres_store)
719
+ finally:
720
+ with postgres_engine.begin() as connection:
721
+ connection.exec_driver_sql(
722
+ "ALTER TABLE session_commit_observations "
723
+ "DROP CONSTRAINT reject_blocked_session"
724
+ )
725
+
726
+ stored = postgres_store.read_session_commit_observations(settings.org_id)
727
+ assert [row.observation_id for row in stored] == ["prefix-good"]
728
+ assert any(
729
+ "session_commit_observation_batch_database_unavailable" in record.message
730
+ for record in caplog.records
731
+ )
732
+ assert "session_blocked" not in caplog.text
733
+ assert "DETAIL" not in caplog.text
734
+
735
+
736
+ def test_batch_observation_sqlalchemy_error_does_not_log_driver_diagnostics(
737
+ postgres_store, monkeypatch, caplog
738
+ ) -> None:
739
+ push = Push(
740
+ push_id="diag-push",
741
+ org_id=settings.org_id,
742
+ provider=ForgeProvider.GITHUB,
743
+ repo=REPO,
744
+ clone_url="https://example.test/acme/backend.git",
745
+ ref="refs/heads/main",
746
+ before_sha="0" * 40,
747
+ after_sha="a" * 40,
748
+ )
749
+ postgres_store.store_push(push)
750
+ observation = SessionCommitObservation(
751
+ observation_id="diag-obs",
752
+ org_id=settings.org_id,
753
+ repo=REPO,
754
+ commit_sha="a" * 40,
755
+ session_id="session-diag",
756
+ source_push_id=push.push_id,
757
+ captured_at=datetime(2026, 8, 22, 12, 0, tzinfo=UTC),
758
+ )
759
+ sentinel = "sentinel-driver-diagnostic"
760
+ statement = "INSERT INTO session_commit_observations VALUES (:secret)"
761
+ params = {"secret": sentinel}
762
+ original_batch = postgres_store.store_session_commit_observations
763
+ calls = {"count": 0}
764
+
765
+ def fail_batch_once(observations):
766
+ calls["count"] += 1
767
+ if calls["count"] == 1:
768
+ raise OperationalError(statement, params, Exception(f"DETAIL: {sentinel}"))
769
+ return original_batch(observations)
770
+
771
+ monkeypatch.setattr(
772
+ postgres_store, "store_session_commit_observations", fail_batch_once
773
+ )
774
+ with caplog.at_level(logging.ERROR, logger="sediment.api.forge"):
775
+ forge._store_session_commit_observations(push, [observation], postgres_store)
776
+
777
+ assert "session_commit_observation_batch_database_unavailable" in caplog.text
778
+ assert "falling back per edge" in caplog.text
779
+ assert sentinel not in caplog.text
780
+ assert statement not in caplog.text
781
+ assert "DETAIL" not in caplog.text
782
+ assert "OperationalError" not in caplog.text
783
+ stored = postgres_store.read_session_commit_observations(settings.org_id)
784
+ assert [row.observation_id for row in stored] == ["diag-obs"]
785
+
786
+
787
+ def test_batch_observation_identity_conflict_keeps_sibling_edges(
788
+ postgres_store, caplog
789
+ ) -> None:
790
+ push = Push(
791
+ push_id="conflict-push",
792
+ org_id=settings.org_id,
793
+ provider=ForgeProvider.GITHUB,
794
+ repo=REPO,
795
+ clone_url="https://example.test/acme/backend.git",
796
+ ref="refs/heads/main",
797
+ before_sha="0" * 40,
798
+ after_sha="a" * 40,
799
+ repository_provider=ForgeProvider.GITHUB,
800
+ repository_host="github.com",
801
+ repository_id="12345",
802
+ )
803
+ postgres_store.store_push(push)
804
+ good = SessionCommitObservation(
805
+ observation_id="conflict-good",
806
+ org_id=settings.org_id,
807
+ repo=REPO,
808
+ repository_provider=ForgeProvider.GITHUB,
809
+ repository_host="github.com",
810
+ repository_id="12345",
811
+ commit_sha="a" * 40,
812
+ session_id="session-good",
813
+ source_push_id=push.push_id,
814
+ captured_at=datetime(2026, 8, 22, 12, 0, tzinfo=UTC),
815
+ )
816
+ bad = SessionCommitObservation(
817
+ observation_id="conflict-bad",
818
+ org_id=settings.org_id,
819
+ repo=REPO,
820
+ repository_provider=ForgeProvider.GITHUB,
821
+ repository_host="github.com",
822
+ repository_id="99999",
823
+ commit_sha="b" * 40,
824
+ session_id="session-bad",
825
+ source_push_id=push.push_id,
826
+ captured_at=datetime(2026, 8, 22, 12, 1, tzinfo=UTC),
827
+ )
828
+ caplog.set_level(logging.ERROR, logger="sediment.api.forge")
829
+ forge._store_session_commit_observations(push, [good, bad], postgres_store)
830
+ stored = postgres_store.read_session_commit_observations(settings.org_id)
831
+ assert [row.observation_id for row in stored] == ["conflict-good"]
832
+
833
+
671
834
  @pytest.mark.parametrize("identified", [False, True])
672
835
  def test_push_pokes_attribution_derivation_and_logs_counts(
673
836
  client: TestClient, tmp_path: Path, monkeypatch, caplog, identified
@@ -101,7 +101,7 @@ def test_me_happy_path(client: TestClient) -> None:
101
101
  assert resp.status_code == 200
102
102
  assert resp.json() == {
103
103
  "org_id": ORG,
104
- "version": "0.7.1",
104
+ "version": "0.8.0",
105
105
  "authority": "operator",
106
106
  "client_id": "operator",
107
107
  }
File without changes
File without changes