diffscore 0.1.0__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 (38) hide show
  1. diffscore/__init__.py +3 -0
  2. diffscore/api.py +729 -0
  3. diffscore/calibration.py +374 -0
  4. diffscore/cli.py +867 -0
  5. diffscore/config.py +88 -0
  6. diffscore/db/__init__.py +27 -0
  7. diffscore/db/base.py +25 -0
  8. diffscore/db/migrate.py +61 -0
  9. diffscore/db/models.py +257 -0
  10. diffscore/db/session.py +37 -0
  11. diffscore/diffing.py +292 -0
  12. diffscore/graders.py +281 -0
  13. diffscore/jobs.py +161 -0
  14. diffscore/judge.py +355 -0
  15. diffscore/labeling.py +167 -0
  16. diffscore/llm.py +120 -0
  17. diffscore/migrations/README +1 -0
  18. diffscore/migrations/env.py +84 -0
  19. diffscore/migrations/script.py.mako +28 -0
  20. diffscore/migrations/versions/2026_11_30-03d94780829e_run_error_and_cache_latency.py +34 -0
  21. diffscore/migrations/versions/2026_11_30-8c8961902e49_run_spend.py +34 -0
  22. diffscore/migrations/versions/2026_11_30-da2445f19a6c_initial_schema.py +280 -0
  23. diffscore/migrations/versions/2026_12_01-053ee29c31c6_run_case_keys.py +55 -0
  24. diffscore/migrations/versions/2026_12_01-9dc97334c9d9_judge_calibration.py +69 -0
  25. diffscore/migrations/versions/2026_12_01-a85ad738bd12_run_provider_keys.py +32 -0
  26. diffscore/queries.py +165 -0
  27. diffscore/runner.py +393 -0
  28. diffscore/secrets.py +130 -0
  29. diffscore/stats.py +83 -0
  30. diffscore/suite.py +329 -0
  31. diffscore/templates/env.example +14 -0
  32. diffscore/templates/example-prompt.md +14 -0
  33. diffscore/templates/example.yaml +75 -0
  34. diffscore-0.1.0.dist-info/METADATA +351 -0
  35. diffscore-0.1.0.dist-info/RECORD +38 -0
  36. diffscore-0.1.0.dist-info/WHEEL +4 -0
  37. diffscore-0.1.0.dist-info/entry_points.txt +2 -0
  38. diffscore-0.1.0.dist-info/licenses/LICENSE +21 -0
diffscore/config.py ADDED
@@ -0,0 +1,88 @@
1
+ """Settings, read from the environment and an optional `.env` file.
2
+
3
+ Every variable from the spec lives here so there is one place to look. Secrets
4
+ are `SecretStr` so they never show up in a repr, a traceback or a log line.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ from functools import lru_cache
11
+
12
+ from pydantic import SecretStr
13
+ from pydantic_settings import BaseSettings, SettingsConfigDict
14
+
15
+ # Provider keys LiteLLM reads straight from the process environment.
16
+ _PROVIDER_ENV = {
17
+ "openrouter_api_key": "OPENROUTER_API_KEY",
18
+ "gemini_api_key": "GEMINI_API_KEY",
19
+ "groq_api_key": "GROQ_API_KEY",
20
+ "openai_api_key": "OPENAI_API_KEY",
21
+ "anthropic_api_key": "ANTHROPIC_API_KEY",
22
+ }
23
+
24
+
25
+ class Settings(BaseSettings):
26
+ model_config = SettingsConfigDict(env_file=".env", extra="ignore")
27
+
28
+ # Core
29
+ # A local SQLite file by default, so `pip install diffscore` works with no setup.
30
+ # Postgres for the hosted API: postgresql+psycopg://user:pass@host:5432/db
31
+ database_url: str = "sqlite:///.diffscore/diffscore.db"
32
+ redis_url: str = "redis://localhost:6379/0"
33
+ secret_key: SecretStr | None = None
34
+ fernet_key: SecretStr | None = None
35
+ api_key: SecretStr | None = None
36
+
37
+ # Model providers
38
+ openrouter_api_key: SecretStr | None = None
39
+ gemini_api_key: SecretStr | None = None
40
+ groq_api_key: SecretStr | None = None
41
+ openai_api_key: SecretStr | None = None
42
+ anthropic_api_key: SecretStr | None = None
43
+ ollama_base_url: str = "http://localhost:11434"
44
+ default_model: str = "gemini/gemini-3.5-flash-lite"
45
+ # Must differ from the model under test: models grade their own outputs generously.
46
+ # Default fits Gemini's free tier (gemini-3.6-flash allows only 20 requests a day);
47
+ # a stronger judge such as groq/llama-3.3-70b-versatile is worth a free Groq key.
48
+ judge_model: str = "gemini/gemini-3.1-flash-lite"
49
+ judge_rpm: float | None = None # judge calls per minute when the judge has its own limit
50
+
51
+ # Guardrails
52
+ max_tokens_per_run: int = 500_000
53
+ max_cases_anonymous: int = 25
54
+ model_rpm: float | None = None # pace model calls; Gemini's free tier allows 15/min
55
+
56
+ # API and queue (Phase 5)
57
+ queue_sync: bool = False # run jobs inline in the API process (dev and tests)
58
+ cors_origins: str = "http://localhost:3000,https://diffscore.space"
59
+ public_projects: str = "sample,playground" # readable without API_KEY
60
+ samples_dir: str = "examples" # curated suites anyone may run
61
+ anon_runs_per_hour: int = 10 # per client IP
62
+ trust_proxy: bool = False # use X-Forwarded-For (behind Caddy/Fly)
63
+
64
+ # Ops
65
+ sentry_dsn: SecretStr | None = None
66
+ public_base_url: str = "https://diffscore.space"
67
+
68
+ def public_project_set(self) -> set[str]:
69
+ return {p.strip() for p in self.public_projects.split(",") if p.strip()}
70
+
71
+ def cors_origin_list(self) -> list[str]:
72
+ return [o.strip() for o in self.cors_origins.split(",") if o.strip()]
73
+
74
+ def export_provider_keys(self) -> None:
75
+ """Make keys from `.env` visible to LiteLLM, which reads `os.environ`.
76
+
77
+ Keys already set in the real environment win over `.env`.
78
+ """
79
+ for field, env_name in _PROVIDER_ENV.items():
80
+ value: SecretStr | None = getattr(self, field)
81
+ if value is not None and value.get_secret_value() and env_name not in os.environ:
82
+ os.environ[env_name] = value.get_secret_value()
83
+ os.environ.setdefault("OLLAMA_API_BASE", self.ollama_base_url)
84
+
85
+
86
+ @lru_cache
87
+ def get_settings() -> Settings:
88
+ return Settings()
@@ -0,0 +1,27 @@
1
+ from diffscore.db.base import Base
2
+ from diffscore.db.models import (
3
+ Cache,
4
+ Case,
5
+ Grade,
6
+ HumanLabel,
7
+ JudgeCalibration,
8
+ Project,
9
+ PromptVersion,
10
+ Result,
11
+ Run,
12
+ Suite,
13
+ )
14
+
15
+ __all__ = [
16
+ "Base",
17
+ "Cache",
18
+ "Case",
19
+ "Grade",
20
+ "HumanLabel",
21
+ "JudgeCalibration",
22
+ "Project",
23
+ "PromptVersion",
24
+ "Result",
25
+ "Run",
26
+ "Suite",
27
+ ]
diffscore/db/base.py ADDED
@@ -0,0 +1,25 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any, ClassVar
4
+
5
+ from sqlalchemy import JSON, MetaData
6
+ from sqlalchemy.dialects.postgresql import JSONB
7
+ from sqlalchemy.orm import DeclarativeBase
8
+
9
+ # Stable constraint names, so Alembic migrations are deterministic and
10
+ # constraints can be dropped by name later.
11
+ NAMING_CONVENTION = {
12
+ "ix": "ix_%(column_0_label)s",
13
+ "uq": "uq_%(table_name)s_%(column_0_N_name)s",
14
+ "ck": "ck_%(table_name)s_%(constraint_name)s",
15
+ "fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
16
+ "pk": "pk_%(table_name)s",
17
+ }
18
+
19
+ # JSONB on Postgres, plain JSON elsewhere — lets tests run on in-memory SQLite.
20
+ JSONType = JSON().with_variant(JSONB(), "postgresql")
21
+
22
+
23
+ class Base(DeclarativeBase):
24
+ metadata = MetaData(naming_convention=NAMING_CONVENTION)
25
+ type_annotation_map: ClassVar[dict[Any, Any]] = {dict[str, Any]: JSONType, list[Any]: JSONType}
@@ -0,0 +1,61 @@
1
+ """Schema management for both backends.
2
+
3
+ - **SQLite** (the default for `pip install` users): the schema creates itself
4
+ on first use and upgrades itself after a new release. Nobody should have to
5
+ run a migration command to try a CLI.
6
+ - **Postgres** (the hosted API and anyone who sets DATABASE_URL): migrations run
7
+ only when asked, with `diffscore migrate`, because a shared database
8
+ shouldn't change shape just because someone ran a command against it.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from pathlib import Path
14
+
15
+ from alembic import command
16
+ from alembic.config import Config
17
+ from alembic.runtime.migration import MigrationContext
18
+ from alembic.script import ScriptDirectory
19
+ from sqlalchemy import Engine, inspect
20
+
21
+ from diffscore.db.base import Base
22
+
23
+ MIGRATIONS = Path(__file__).resolve().parent.parent / "migrations"
24
+
25
+
26
+ def alembic_config(url: str) -> Config:
27
+ cfg = Config()
28
+ cfg.set_main_option("script_location", str(MIGRATIONS))
29
+ cfg.attributes["url"] = url
30
+ return cfg
31
+
32
+
33
+ def head_revision() -> str | None:
34
+ return ScriptDirectory(str(MIGRATIONS)).get_current_head()
35
+
36
+
37
+ def current_revision(engine: Engine) -> str | None:
38
+ with engine.connect() as conn:
39
+ return MigrationContext.configure(conn).get_current_revision()
40
+
41
+
42
+ def upgrade(url: str) -> None:
43
+ command.upgrade(alembic_config(url), "head")
44
+
45
+
46
+ def ensure_sqlite_schema(engine: Engine) -> None:
47
+ """Create a fresh SQLite database at the latest schema, or bring an old one up to it.
48
+
49
+ A brand-new file gets `create_all` plus a stamp: the historical Postgres
50
+ migrations aren't replayed on SQLite. Later releases upgrade it in batch mode.
51
+ """
52
+ url = engine.url.render_as_string(hide_password=False)
53
+ tables = set(inspect(engine).get_table_names())
54
+ if "alembic_version" not in tables:
55
+ if tables - {"alembic_version"}:
56
+ return # tables from something else; don't touch them
57
+ Base.metadata.create_all(engine)
58
+ command.stamp(alembic_config(url), "head")
59
+ return
60
+ if current_revision(engine) != head_revision():
61
+ upgrade(url)
diffscore/db/models.py ADDED
@@ -0,0 +1,257 @@
1
+ """The nine tables from the build spec.
2
+
3
+ The rule the whole schema serves: generation (`result`) and grading (`grade`)
4
+ are separate rows, so stored outputs can be re-graded without paying for
5
+ another model call. `prompt_version` and `run` are immutable snapshots, so a
6
+ diff between two runs is a join, not a recomputation.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from datetime import datetime
12
+ from decimal import Decimal
13
+ from typing import Any
14
+
15
+ from sqlalchemy import (
16
+ CheckConstraint,
17
+ DateTime,
18
+ Float,
19
+ ForeignKey,
20
+ Integer,
21
+ LargeBinary,
22
+ Numeric,
23
+ String,
24
+ Text,
25
+ UniqueConstraint,
26
+ func,
27
+ )
28
+ from sqlalchemy.orm import Mapped, mapped_column, relationship
29
+
30
+ from diffscore.db.base import Base
31
+
32
+ VERDICTS = ("pass", "fail")
33
+ RUN_STATUSES = ("pending", "running", "completed", "failed", "cancelled")
34
+
35
+
36
+ def _in(column: str, values: tuple[str, ...]) -> str:
37
+ quoted = ", ".join(f"'{v}'" for v in values)
38
+ return f"{column} IN ({quoted})"
39
+
40
+
41
+ class _Timestamped:
42
+ created_at: Mapped[datetime] = mapped_column(
43
+ DateTime(timezone=True), server_default=func.now(), nullable=False
44
+ )
45
+
46
+
47
+ class Project(_Timestamped, Base):
48
+ """A user's app under test. Owns provider keys and the default model."""
49
+
50
+ __tablename__ = "project"
51
+
52
+ id: Mapped[int] = mapped_column(primary_key=True)
53
+ name: Mapped[str] = mapped_column(String(200), unique=True)
54
+ default_model: Mapped[str | None] = mapped_column(String(200))
55
+ # Fernet ciphertext of a JSON {provider: key} map. Never returned by the API.
56
+ provider_keys_encrypted: Mapped[bytes | None] = mapped_column(LargeBinary)
57
+
58
+ prompt_versions: Mapped[list[PromptVersion]] = relationship(back_populates="project")
59
+ suites: Mapped[list[Suite]] = relationship(back_populates="project")
60
+
61
+
62
+ class PromptVersion(_Timestamped, Base):
63
+ """Prompt template text and params. Immutable — a change is a new row."""
64
+
65
+ __tablename__ = "prompt_version"
66
+ __table_args__ = (UniqueConstraint("project_id", "content_hash"),)
67
+
68
+ id: Mapped[int] = mapped_column(primary_key=True)
69
+ project_id: Mapped[int] = mapped_column(ForeignKey("project.id", ondelete="CASCADE"))
70
+ template: Mapped[str] = mapped_column(Text)
71
+ params: Mapped[dict[str, Any]] = mapped_column(default=dict)
72
+ content_hash: Mapped[str] = mapped_column(String(64)) # sha256 hex of template + params
73
+ label: Mapped[str | None] = mapped_column(String(200))
74
+
75
+ project: Mapped[Project] = relationship(back_populates="prompt_versions")
76
+
77
+
78
+ class Suite(_Timestamped, Base):
79
+ """A named set of cases. Points at the run new runs are diffed against."""
80
+
81
+ __tablename__ = "suite"
82
+ __table_args__ = (UniqueConstraint("project_id", "name"),)
83
+
84
+ id: Mapped[int] = mapped_column(primary_key=True)
85
+ project_id: Mapped[int] = mapped_column(ForeignKey("project.id", ondelete="CASCADE"))
86
+ name: Mapped[str] = mapped_column(String(200))
87
+ # suite -> run -> suite is a cycle; use_alter adds this FK after both tables exist.
88
+ baseline_run_id: Mapped[int | None] = mapped_column(
89
+ ForeignKey("run.id", ondelete="SET NULL", use_alter=True)
90
+ )
91
+
92
+ project: Mapped[Project] = relationship(back_populates="suites")
93
+ cases: Mapped[list[Case]] = relationship(back_populates="suite")
94
+ runs: Mapped[list[Run]] = relationship(back_populates="suite", foreign_keys="Run.suite_id")
95
+
96
+
97
+ class Case(_Timestamped, Base):
98
+ """One test input, an optional reference output, and per-case graders.
99
+
100
+ `key` is the stable id from the suite file. Runs are diffed by joining on it.
101
+ """
102
+
103
+ __tablename__ = "case"
104
+ __table_args__ = (UniqueConstraint("suite_id", "key"),)
105
+
106
+ id: Mapped[int] = mapped_column(primary_key=True)
107
+ suite_id: Mapped[int] = mapped_column(ForeignKey("suite.id", ondelete="CASCADE"))
108
+ key: Mapped[str] = mapped_column(String(200))
109
+ input: Mapped[dict[str, Any]] = mapped_column()
110
+ reference_output: Mapped[str | None] = mapped_column(Text)
111
+ graders: Mapped[list[Any]] = mapped_column(default=list)
112
+
113
+ suite: Mapped[Suite] = relationship(back_populates="cases")
114
+
115
+
116
+ class Run(_Timestamped, Base):
117
+ """One execution of suite x prompt_version x model. The unit you diff."""
118
+
119
+ __tablename__ = "run"
120
+ __table_args__ = (CheckConstraint(_in("status", RUN_STATUSES), name="status"),)
121
+
122
+ id: Mapped[int] = mapped_column(primary_key=True)
123
+ suite_id: Mapped[int] = mapped_column(ForeignKey("suite.id", ondelete="CASCADE"), index=True)
124
+ prompt_version_id: Mapped[int] = mapped_column(ForeignKey("prompt_version.id"))
125
+ model: Mapped[str] = mapped_column(String(200))
126
+ params: Mapped[dict[str, Any]] = mapped_column(default=dict)
127
+ status: Mapped[str] = mapped_column(String(20), default="pending")
128
+ error: Mapped[str | None] = mapped_column(Text) # why a run stopped early
129
+ # The case ids in this run, in order: the suite as it was when the run started.
130
+ case_keys: Mapped[list[Any]] = mapped_column(default=list)
131
+ # A visitor's own provider keys for this run only (Fernet ciphertext); wiped
132
+ # when the run finishes. Never returned by the API.
133
+ provider_keys_encrypted: Mapped[bytes | None] = mapped_column(LargeBinary)
134
+ # Everything this run paid for: answers and judge calls, cache hits excluded.
135
+ tokens_spent: Mapped[int | None] = mapped_column(Integer)
136
+ cost_spent: Mapped[Decimal | None] = mapped_column(Numeric(12, 6))
137
+ finished_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
138
+
139
+ suite: Mapped[Suite] = relationship(back_populates="runs", foreign_keys=[suite_id])
140
+ prompt_version: Mapped[PromptVersion] = relationship()
141
+ results: Mapped[list[Result]] = relationship(back_populates="run")
142
+
143
+
144
+ class Result(_Timestamped, Base):
145
+ """Raw model output for one case in one run. No score here — that's the point."""
146
+
147
+ __tablename__ = "result"
148
+ __table_args__ = (UniqueConstraint("run_id", "case_id"),)
149
+
150
+ id: Mapped[int] = mapped_column(primary_key=True)
151
+ run_id: Mapped[int] = mapped_column(ForeignKey("run.id", ondelete="CASCADE"))
152
+ case_id: Mapped[int] = mapped_column(ForeignKey("case.id", ondelete="CASCADE"))
153
+ output: Mapped[str | None] = mapped_column(Text)
154
+ error: Mapped[str | None] = mapped_column(Text)
155
+ input_tokens: Mapped[int | None] = mapped_column(Integer)
156
+ output_tokens: Mapped[int | None] = mapped_column(Integer)
157
+ latency_ms: Mapped[int | None] = mapped_column(Integer)
158
+ cost_usd: Mapped[Decimal | None] = mapped_column(Numeric(12, 6))
159
+ cache_hit: Mapped[bool] = mapped_column(default=False)
160
+
161
+ run: Mapped[Run] = relationship(back_populates="results")
162
+ case: Mapped[Case] = relationship()
163
+ grades: Mapped[list[Grade]] = relationship(back_populates="result")
164
+ human_labels: Mapped[list[HumanLabel]] = relationship(back_populates="result")
165
+
166
+
167
+ class Grade(_Timestamped, Base):
168
+ """One grader's verdict on one result. Many per result; re-runnable.
169
+
170
+ Carrying `grader_version` is what lets you show a score moving because the
171
+ rubric changed, not just because the prompt did. `details` holds judge
172
+ output such as `failed_criterion` and `evidence`.
173
+ """
174
+
175
+ __tablename__ = "grade"
176
+ __table_args__ = (
177
+ CheckConstraint(_in("verdict", VERDICTS), name="verdict"),
178
+ CheckConstraint("score >= 0 AND score <= 1", name="score_range"),
179
+ )
180
+
181
+ id: Mapped[int] = mapped_column(primary_key=True)
182
+ result_id: Mapped[int] = mapped_column(ForeignKey("result.id", ondelete="CASCADE"), index=True)
183
+ grader_name: Mapped[str] = mapped_column(String(100))
184
+ grader_version: Mapped[str] = mapped_column(String(50))
185
+ score: Mapped[float] = mapped_column(Float)
186
+ verdict: Mapped[str] = mapped_column(String(10))
187
+ reason: Mapped[str | None] = mapped_column(Text)
188
+ details: Mapped[dict[str, Any]] = mapped_column(default=dict)
189
+
190
+ result: Mapped[Result] = relationship(back_populates="grades")
191
+
192
+
193
+ class HumanLabel(_Timestamped, Base):
194
+ """Your own pass/fail on a result — the gold set the judge is measured against.
195
+
196
+ `grader_name` scopes the label to one grader's criterion for per-grader
197
+ kappa; NULL means an overall verdict on the output.
198
+ """
199
+
200
+ __tablename__ = "human_label"
201
+ __table_args__ = (
202
+ CheckConstraint(_in("verdict", VERDICTS), name="verdict"),
203
+ UniqueConstraint("result_id", "grader_name", postgresql_nulls_not_distinct=True),
204
+ )
205
+
206
+ id: Mapped[int] = mapped_column(primary_key=True)
207
+ result_id: Mapped[int] = mapped_column(ForeignKey("result.id", ondelete="CASCADE"))
208
+ grader_name: Mapped[str | None] = mapped_column(String(100))
209
+ verdict: Mapped[str] = mapped_column(String(10))
210
+ note: Mapped[str | None] = mapped_column(Text)
211
+
212
+ result: Mapped[Result] = relationship(back_populates="human_labels")
213
+
214
+
215
+ class Cache(_Timestamped, Base):
216
+ """sha256(prompt + input + model + params) -> output. Makes reruns free."""
217
+
218
+ __tablename__ = "cache"
219
+
220
+ key: Mapped[str] = mapped_column(String(64), primary_key=True)
221
+ model: Mapped[str] = mapped_column(String(200))
222
+ output: Mapped[str] = mapped_column(Text)
223
+ input_tokens: Mapped[int | None] = mapped_column(Integer)
224
+ output_tokens: Mapped[int | None] = mapped_column(Integer)
225
+ # The original call's latency, so latency graders give the same verdict on a rerun.
226
+ latency_ms: Mapped[int | None] = mapped_column(Integer)
227
+ cost_usd: Mapped[Decimal | None] = mapped_column(Numeric(12, 6))
228
+ hit_count: Mapped[int] = mapped_column(Integer, default=0)
229
+
230
+
231
+ class JudgeCalibration(_Timestamped, Base):
232
+ """One `diffscore calibrate` result: how far a judge agreed with your labels.
233
+
234
+ Kept so every screen can show a judge's kappa beside its verdicts, and so
235
+ you can see kappa move as the rubric is rewritten (grader_version).
236
+ """
237
+
238
+ __tablename__ = "judge_calibration"
239
+
240
+ id: Mapped[int] = mapped_column(primary_key=True)
241
+ suite_id: Mapped[int] = mapped_column(ForeignKey("suite.id", ondelete="CASCADE"), index=True)
242
+ grader_name: Mapped[str] = mapped_column(String(100))
243
+ grader_version: Mapped[str] = mapped_column(String(50))
244
+ judge_model: Mapped[str] = mapped_column(String(200))
245
+ labels: Mapped[int] = mapped_column(Integer)
246
+ kappa: Mapped[float | None] = mapped_column(Float)
247
+ agreement: Mapped[float] = mapped_column(Float)
248
+ judge_pass_human_fail: Mapped[int] = mapped_column(Integer)
249
+ judge_fail_human_pass: Mapped[int] = mapped_column(Integer)
250
+ verbosity_r: Mapped[float | None] = mapped_column(Float)
251
+ self_preference_ok: Mapped[bool] = mapped_column()
252
+ position_pairs: Mapped[int | None] = mapped_column(Integer)
253
+ position_consistent: Mapped[int | None] = mapped_column(Integer)
254
+ variance_cases: Mapped[int | None] = mapped_column(Integer)
255
+ variance_flipped: Mapped[int | None] = mapped_column(Integer)
256
+ evidence_found: Mapped[int] = mapped_column(Integer)
257
+ evidence_total: Mapped[int] = mapped_column(Integer)
@@ -0,0 +1,37 @@
1
+ from __future__ import annotations
2
+
3
+ from functools import lru_cache
4
+ from pathlib import Path
5
+ from typing import Any
6
+
7
+ from sqlalchemy import Engine, create_engine, event
8
+ from sqlalchemy.engine import make_url
9
+ from sqlalchemy.orm import Session, sessionmaker
10
+
11
+ from diffscore.config import get_settings
12
+
13
+
14
+ @lru_cache
15
+ def get_engine() -> Engine:
16
+ url = make_url(get_settings().database_url)
17
+ if url.get_backend_name() != "sqlite":
18
+ return create_engine(url, pool_pre_ping=True)
19
+
20
+ # SQLite: the zero-setup default. Make the folder, turn on foreign keys,
21
+ # and create or upgrade the schema so `diffscore run` just works.
22
+ if url.database and url.database != ":memory:":
23
+ Path(url.database).expanduser().parent.mkdir(parents=True, exist_ok=True)
24
+ engine = create_engine(url, connect_args={"check_same_thread": False})
25
+
26
+ @event.listens_for(engine, "connect")
27
+ def _foreign_keys(dbapi_conn: Any, _record: Any) -> None:
28
+ dbapi_conn.execute("PRAGMA foreign_keys=ON")
29
+
30
+ from diffscore.db.migrate import ensure_sqlite_schema
31
+
32
+ ensure_sqlite_schema(engine)
33
+ return engine
34
+
35
+
36
+ def make_session() -> Session:
37
+ return sessionmaker(bind=get_engine(), expire_on_commit=False)()