diff --git a/crates/analysis-prompt/src/lib.rs b/crates/analysis-prompt/src/lib.rs
index 5dbfe27..d5a7d67 100644
--- a/crates/analysis-prompt/src/lib.rs
+++ b/crates/analysis-prompt/src/lib.rs
@@ -462,8 +462,8 @@ fn question_system(language: &str) -> String {
if language == "hu" {
let mut text = format!(
"Tapasztalt, empatikus, lélektani szemléletű asztrológus vagy a Sorsfonalak alkalmazásban. Az olvasó már \
-megkapta a részletes elemzését (születési képletelemzést vagy éves előrejelzést), és most kérdez róla. Válaszolj a \
-kérdésére.
+megkapta a részletes elemzését (születési képletelemzést, kapcsolati elemzést vagy éves előrejelzést), és most kérdez \
+róla. Válaszolj a kérdésére.
Szabályok:
- A válasz a megadott képletadatokon és az elemzésen alapuljon. Ne találj ki pozíciót, fényszöget, házat vagy dátumot, \
@@ -471,8 +471,10 @@ amely nincs az adatok között. Ha a kérdésre az adatok alapján nem lehet fel
amit a képlet erről mutat.
- Maradj összhangban az elemzéssel. Ha a kérdés olyan részletre vonatkozik, amelyet az elemzés nem tárgyalt, a \
képletadatokból egészítsd ki.
-- Közvetlenül a kérdezőhöz szólj, tegező formában. Ha a kérdés két ember kapcsolatáról szól, csak abból beszélj, amit \
-az adatok mutatnak.
+- Közvetlenül a kérdezőhöz szólj, tegező formában. Kapcsolati elemzésnél (két képlet összevetése) a kérdező az egyik \
+fél: ha a kérdésből nem derül ki, melyik, beszélj kettejükhöz („ti”, „kettőtök”). A feleket az adatokban Person 1 és \
+Person 2 jelöli, a szövegben „az első fél” és „a második fél”. Ne feltételezd a nemüket és a kapcsolat jellegét, és \
+csak abból beszélj, amit az adatok mutatnak.
- Hangnem: meleg, őszinte, megerősítő és konkrét. Ne légy fatalista: ne jósolj betegséget, halált, balesetet, \
terhességet vagy biztos eseményeket, és ne adj orvosi, jogi vagy pénzügyi tanácsot. Ha ilyet kérdeznek, kedvesen \
tereld a választ arra, amit az asztrológia valóban mutat: hajlamokra, időszakokra, lehetőségekre.
@@ -490,7 +492,8 @@ használhatsz.
}
format!(
"You are an experienced, warm and psychologically minded astrologer in the Sorsfonalak app. The reader has \
-received their detailed analysis (a natal chart interpretation or a yearly forecast) and now asks a question about it. \
+received their detailed analysis (a natal chart interpretation, a relationship analysis or a yearly forecast) and now \
+asks a question about it. \
Answer it.
Write in {lang}.
@@ -499,7 +502,9 @@ Rules:
- Base the answer on the chart data and the analysis given. Never invent positions, aspects, houses or dates that are \
not listed. If the data cannot answer the question, say so honestly and describe what the chart does show about it.
- Stay consistent with the analysis; fill in details it did not cover from the chart data.
-- Speak to the reader directly, in the informal second person.
+- Speak to the reader directly, in the informal second person. On a relationship analysis the reader is one of the \
+two people (Person 1 and Person 2 in the data); when it is unclear which, speak to both. Do not assume their genders \
+or the type of relationship.
- Tone: warm, honest, empowering and concrete. Not fatalistic: no predictions of illness, death, accidents, pregnancy \
or certain events, and no medical, legal or financial advice; if asked, turn gently to what astrology does show \
(tendencies, periods, opportunities).
diff --git a/crates/db/migrations/0020_generation_errors.sql b/crates/db/migrations/0020_generation_errors.sql
new file mode 100644
index 0000000..9bc463f
--- /dev/null
+++ b/crates/db/migrations/0020_generation_errors.sql
@@ -0,0 +1,26 @@
+-- Every failed attempt of an analysis, an answer or a prompt test run, for the
+-- admin error log. No foreign keys: the log outlives deleted items. Kept for
+-- 90 days (worker cleanup).
+CREATE TABLE generation_errors (
+ id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ source text NOT NULL CHECK (source IN ('analysis', 'question', 'preview')),
+ item_id uuid NOT NULL,
+ kind text NOT NULL,
+ model text NOT NULL,
+ attempt integer NOT NULL,
+ -- What happened next: tried again, the default model took over, or gave up.
+ outcome text NOT NULL CHECK (outcome IN ('retry', 'fallback', 'failed')),
+ error text NOT NULL,
+ seconds integer
+);
+
+CREATE INDEX generation_errors_created_idx ON generation_errors (created_at DESC);
+CREATE INDEX generation_errors_item_idx ON generation_errors (item_id);
+
+-- When the current text was asked for (a regeneration or an admin restart
+-- sets it again): the waiting page counts from here.
+ALTER TABLE analyses ADD COLUMN requested_at timestamptz NOT NULL DEFAULT now();
+UPDATE analyses SET requested_at = created_at;
+ALTER TABLE questions ADD COLUMN requested_at timestamptz NOT NULL DEFAULT now();
+UPDATE questions SET requested_at = created_at;
diff --git a/docs/kerdesek.md b/docs/kerdesek.md
index 0535459..1125856 100644
--- a/docs/kerdesek.md
+++ b/docs/kerdesek.md
@@ -1,13 +1,14 @@
# Kérdések az elemzésekről
-A kész részletes képletelemzés és éves előrejelzés alatt a felhasználó kérdezhet róla („Kérdezz az elemzésedről”). Minden kérdés egy `question` egységet használ; minden csomagban 3 jár, és külön is vehető (+5 kérdés, 1 000 Ft). Admin ingyen kérdez.
+A kész részletes képletelemzés, kapcsolati elemzés és éves előrejelzés alatt a felhasználó kérdezhet róla („Kérdezz az elemzésedről”). Minden kérdés egy `question` egységet használ; minden csomagban 3 jár, és külön is vehető (+5 kérdés, 1 000 Ft). Admin ingyen kérdez.
## Hogyan készül a válasz
- **Modell:** a Modellek oldalon külön beállítható kérdés-válasz modell (alapból Opus 5.5). Ha a választott modell hibára fut, az alapmodell válaszol (tartalék).
-- **Amit a modell kap:** a képlet tömör adatsorát (előrejelzésnél az év adatait is), magát az elemzést, az ugyanerre az elemzésre feltett korábbi legfeljebb 6 kérdést a válasszal, és az új kérdést. Születési dátum, hely, idő és név nem megy ki.
+- **Amit a modell kap:** a képlet tömör adatsorát (kapcsolati elemzésnél mindkét képletet és az összevetést, előrejelzésnél az év adatait is), magát az elemzést, az ugyanerre az elemzésre feltett korábbi legfeljebb 6 kérdést a válasszal, és az új kérdést. Születési dátum, hely, idő és név nem megy ki.
- **Prompt:** az admin felületen szerkeszthető (Promptok → Kérdés-válasz). A szóhatár (`QUESTION_MAX_WORDS` = 250) a felhasználói üzenetben is benne van, így a prompt átírásától sem vész el. A kérdés legfeljebb 600 karakter.
- **Szabályok:** csak a képletből és az elemzésből válaszol, nem jósol betegséget, halált, balesetet, terhességet vagy biztos eseményt, nem ad orvosi, jogi, pénzügyi tanácsot; a nem asztrológiai kérdést udvariasan elhárítja; a kérdésben lévő utasításokat nem követi.
+- **Kapcsolati elemzés:** az összevetés mindkét tagja kérdezhet (a saját kérdéseiből), és mindketten látják a kérdéseket és a válaszokat.
- **Egyszerre egy:** amíg egy kérdésre készül a válasz, újabb nem tehető fel ugyanarra az elemzésre (így a válaszok egymásra épülnek).
- **Hiba:** a worker újrapróbálja, mint az elemzéseket; végleges hibánál a kérdést visszaadja (egyszer).
- **Újragenerálás:** admin a válasz melletti ↻ gombbal újraírathatja (díjmentesen).
diff --git a/services/backend/README.md b/services/backend/README.md
index 0205dd6..14f6651 100644
--- a/services/backend/README.md
+++ b/services/backend/README.md
@@ -127,6 +127,8 @@ Hibák formátuma: `{"error": {"code", "message"}}`. A születési adatok hibái
- **Fizetős rész:** a részletes elemzés darabra megy. A képletelemzés egy `natal`, a szinasztria-elemzés egy `synastry` egységet von le (`credit_ledger.unit`). Az egységek csomagvásárlásból (Stripe, később) vagy admin jóváírásból jönnek. Havi ingyenes keret nincs.
- **Modell:** három beállítás az admin felületen, az OpenRouter listájából (`model_settings` tábla): az elemzések és az éves előrejelzés (képlet-, kapcsolati elemzés, előrejelzés) közös modellje, a kérdés-válasz modellje és a rövid összefoglalóé. Ha nincs beállítva, az `ANALYSIS_MODEL` / `SUMMARY_MODEL` (alapból mindkettő Opus 5.5, a 2026-11-es összevetés legjobbja, lásd `services/worker/README.md`). Csak kötött JSON-választ adó modell választható. A kliens nem választ modellt, és a modell neve felhasználónak sehol nem jelenik meg.
- **Tartalék:** ha a választott modell kétszer hibára fut (végleges hibánál egyszer), a worker az alapmodellel próbálja tovább (`fallback_model`, `on_fallback`); csak ha az is elbukik, jár vissza az egység. A Modellek oldal mutatja, hány szövegnél kellett az elmúlt 30 napban.
+- **Hibanapló:** a worker minden sikertelen próbálkozást a `generation_errors` táblába ír (mi, melyik modell, hányadik kísérlet, mi lett: újrapróbálás, tartalék vagy végleges hiba, mennyi ideig tartott); az admin Hibanapló oldala mutatja (`GET /v1/admin/errors?source=&outcome=`), 90 napig őrizzük. A felhasználó a várakozó oldalon látja, ha az előző próbálkozás nem sikerült és újrapróbáljuk; a számláló a kérés idejétől (`requested_at`) mér.
+- **Futó generálások:** a Modellek oldalon látszik minden készülő és sorban álló elemzés és válasz, a modelljével és azzal, amivel most indulna; újraindításkor a jelenlegi beállítással indul újra (`GET /v1/admin/jobs`, `POST /v1/admin/jobs/restart`). Minden kísérlet `started_at` értéke a „jegye”: az újraindítás törli, így a workerben még futó régi kísérlet nem írhatja felül az újat, és a worker 10 másodpercen belül eldobja.
- **Újragenerálás:** admin minden elemzést egyenként újraírathat (`POST /v1/admin/analyses/{id}/regenerate`): ugyanaz a sor (az azonosító és a megosztások maradnak), a jelenlegi prompttal és modellel, egységlevonás nélkül.
- **Újraszámolás:** számítási változás után a `backend recalculate` parancs minden mentett képletet, összevetést és előrejelzést újraszámol, majd minden elemzést újra sorba állít (egységlevonás nélkül).
- **Kérés:** a `POST .../analyses` (`{language?}`) létrehoz egy `pending` elemzést, és levon egy egységet; a szöveget a worker írja meg, általában 1–2 perc alatt. A kliens a `GET /v1/analyses/{id}` végponton kérdezi le az állapotát. Ha nincs egység, 402 `insufficient_credits` a válasz (`unit`, `balance` részletekkel). Hiba esetén a worker visszaadja az egységet.
diff --git a/services/backend/src/routes/analyses.rs b/services/backend/src/routes/analyses.rs
index 7eb205f..cb8cf7e 100644
--- a/services/backend/src/routes/analyses.rs
+++ b/services/backend/src/routes/analyses.rs
@@ -49,11 +49,16 @@ pub struct AnalysisRow {
pub credits_charged: i32,
pub created_at: OffsetDateTime,
pub completed_at: Option,
+ /// Attempts so far; above 1 the page says it is being tried again.
+ pub attempts: i32,
+ pub next_attempt_at: OffsetDateTime,
+ /// When the current text was asked for (set again by a regeneration).
+ pub requested_at: OffsetDateTime,
}
const ANALYSIS_COLUMNS: &str = "id, kind, chart_id, synastry_id, forecast_id, language, prompt_version, status, \
content, error, \
- credits_charged, created_at, completed_at";
+ credits_charged, created_at, completed_at, attempts, next_attempt_at, requested_at";
impl AnalysisRow {
pub fn view(&self) -> Value {
@@ -71,6 +76,9 @@ impl AnalysisRow {
"credits_charged": self.credits_charged,
"created_at": rfc3339(self.created_at),
"completed_at": rfc3339_opt(self.completed_at),
+ "attempts": self.attempts,
+ "next_attempt_at": rfc3339(self.next_attempt_at),
+ "requested_at": rfc3339(self.requested_at),
})
}
}
@@ -146,7 +154,7 @@ async fn request(
/// The cache key and the prompt version of a new analysis. The cache key leaves
/// out the admin-edited prompt revision, so a chart keeps its analysis when the
/// prompt changes; copying from another chart needs the same revision.
-async fn versions(
+pub(super) async fn versions(
state: &AppState,
kind: &str,
hash: &str,
@@ -359,6 +367,17 @@ pub async fn request_for_forecast(
request(&state, &auth, Target::Forecast { forecast_id: forecast.id, hash: forecast.forecast_hash }, req).await
}
+/// The hash of what the analysis is about (chart, comparison or forecast),
+/// part of its cache key; `None` when that was deleted.
+pub(super) async fn target_hash(db: &PgPool, row: &AnalysisRow) -> Result
) : (
-
+ <>
+
+ {summary && (
+
+ )}
+ >
)}
>
)}
diff --git a/services/frontend/src/components/DetailedAnalysis.tsx b/services/frontend/src/components/DetailedAnalysis.tsx
index c1f5535..716f007 100644
--- a/services/frontend/src/components/DetailedAnalysis.tsx
+++ b/services/frontend/src/components/DetailedAnalysis.tsx
@@ -11,6 +11,7 @@ import { AnalysisLoading } from "./AnalysisLoading";
import { AnalysisQuestions } from "./AnalysisQuestions";
import { PackageChooser } from "./PackageCards";
import { RegenerateButton } from "./RegenerateButton";
+import { RetryNotice } from "./RetryNotice";
import { AnalysisView } from "./AnalysisView";
const POLL_MS = 5000;
@@ -99,7 +100,7 @@ export function DetailedAnalysis({
canPay: boolean;
/** Shown above a finished analysis (e.g. who is the first and the second person). */
note?: string;
- /** Questions left; given where questions can be asked (natal analysis, forecast). */
+ /** Questions left; given where questions can be asked. */
questionsLeft?: number;
}) {
const [analysis, setAnalysis] = useState(initial);
@@ -155,13 +156,13 @@ export function DetailedAnalysis({
)}
{note &&
- Az előző kérés nem sikerült{isAdmin ? "" : ", az elemzést visszaadtuk a keretedbe"}. Próbáld újra.
-
+
+
+ Az elemzés többszöri próbálkozás után sem készült el.
+ {isAdmin || analysis.credits_charged === 0
+ ? " Próbáld újra."
+ : " A felhasznált egységet visszaadtuk, így ingyen újra kérheted."}
+
+ {isAdmin && analysis.error &&
Hiba: {analysis.error}
}
+
)}
{error && (
diff --git a/services/frontend/src/components/RetryNotice.tsx b/services/frontend/src/components/RetryNotice.tsx
new file mode 100644
index 0000000..2298544
--- /dev/null
+++ b/services/frontend/src/components/RetryNotice.tsx
@@ -0,0 +1,28 @@
+/**
+ * Shown while a text is being written again after a failed attempt: it is
+ * retried on its own, nothing to do. Admins also see the error.
+ */
+export function RetryNotice({
+ status,
+ error,
+ nextAttemptAt,
+ isAdmin = false,
+}: {
+ status: string;
+ error?: string | null;
+ nextAttemptAt?: string;
+ isAdmin?: boolean;
+}) {
+ if (!error || (status !== "pending" && status !== "running")) return null;
+ const wait = nextAttemptAt ? Math.round((Date.parse(nextAttemptAt) - Date.now()) / 60_000) : 0;
+ return (
+
+
+ Az előző próbálkozás nem sikerült, ezért automatikusan újrapróbáljuk. Nem kell újra kérned, és nem kerül
+ többe.
+ {status === "pending" && wait >= 1 ? ` A következő próbálkozás kb. ${wait} perc múlva indul.` : ""}
+
+ {isAdmin &&
Hiba: {error}
}
+
+ );
+}
diff --git a/services/frontend/src/lib/types.ts b/services/frontend/src/lib/types.ts
index 3fddfa3..c775533 100644
--- a/services/frontend/src/lib/types.ts
+++ b/services/frontend/src/lib/types.ts
@@ -77,6 +77,9 @@ export interface Question {
credits_charged: number;
created_at: string;
completed_at: string | null;
+ attempts?: number;
+ next_attempt_at?: string;
+ requested_at?: string;
}
export interface PublicConfig {
@@ -232,6 +235,26 @@ export interface Analysis {
credits_charged: number;
created_at: string;
completed_at: string | null;
+ /** Attempts so far, and when the next one starts (while it is retried). */
+ attempts?: number;
+ next_attempt_at?: string;
+ /** When the current text was asked for: the waiting page counts from here. */
+ requested_at?: string;
+}
+
+/** Admin: one failed attempt in the error log. */
+export interface GenerationError {
+ id: number;
+ created_at: string;
+ source: "analysis" | "question" | "preview";
+ item_id: string;
+ kind: string;
+ model: string;
+ attempt: number;
+ outcome: "retry" | "fallback" | "failed";
+ error: string;
+ seconds: number | null;
+ user: string | null;
}
export interface AdminUser {
@@ -266,6 +289,25 @@ export interface ModelFunction {
finished_30d: number;
}
+/** Admin: an analysis or answer being written or waiting in the queue. */
+export interface AdminJob {
+ id: string;
+ type: "analysis" | "question";
+ kind: "summary" | "natal" | "synastry" | "forecast" | "question";
+ status: "pending" | "running";
+ /** The model of the current attempt. */
+ model: string;
+ on_fallback: boolean;
+ /** What a restart would use now. */
+ next_model: string;
+ next_fallback: string | null;
+ attempts: number;
+ started_at: string | null;
+ created_at: string;
+ next_attempt_at: string;
+ error: string | null;
+}
+
/** A model OpenRouter offers; prices in USD per million tokens. */
export interface CatalogModel {
id: string;
diff --git a/services/worker/src/analysis/mod.rs b/services/worker/src/analysis/mod.rs
index a22bded..170e1ff 100644
--- a/services/worker/src/analysis/mod.rs
+++ b/services/worker/src/analysis/mod.rs
@@ -47,6 +47,9 @@ pub struct Job {
/// The default model, when the chosen one is another (see the module docs).
pub fallback_model: Option,
pub on_fallback: bool,
+ /// When this attempt started; also its token: an admin restart clears it,
+ /// so a superseded attempt neither writes its result nor keeps running.
+ pub started_at: time::OffsetDateTime,
}
impl Job {
@@ -125,7 +128,7 @@ impl Analyzer {
WHERE id = (SELECT id FROM analyses WHERE status = 'pending' AND next_attempt_at <= now() \
ORDER BY next_attempt_at LIMIT 1 FOR UPDATE SKIP LOCKED) \
RETURNING id, kind, chart_id, synastry_id, forecast_id, language, model, prompt_version, attempts, \
- fallback_model, on_fallback",
+ fallback_model, on_fallback, started_at",
)
.fetch_optional(&self.db)
.await?;
@@ -250,6 +253,8 @@ impl Analyzer {
.await
}
Err(e) => {
+ self.log_error("preview", job.id, &job.kind, &job.model, 1, "failed", e.message(), started.elapsed())
+ .await;
sqlx::query(
"UPDATE prompt_previews SET status = 'failed', error = $2, completed_at = now() \
WHERE id = $1 AND status = 'running'",
@@ -273,12 +278,21 @@ impl Analyzer {
/// Writes one claimed analysis and records the outcome.
pub async fn handle(&self, job: Job) {
let started = Instant::now();
- let result = match self.prompt_for(&job).await {
- Ok(prompt) => self.llm.complete(job.active_model(), &prompt).await.map(|mut c| {
- prompt::polish(&job.language, &mut c.content);
- c
- }),
- Err(e) => Err(e),
+ let work = async {
+ match self.prompt_for(&job).await {
+ Ok(prompt) => self.llm.complete(job.active_model(), &prompt).await.map(|mut c| {
+ prompt::polish(&job.language, &mut c.content);
+ c
+ }),
+ Err(e) => Err(e),
+ }
+ };
+ let result = tokio::select! {
+ result = work => result,
+ () = self.superseded("analyses", job.id, job.started_at) => {
+ tracing::info!(id = %job.id, "analysis restarted by an admin; this attempt is dropped");
+ return;
+ }
};
if let Err(e) = self.finish(&job, result, started.elapsed()).await {
tracing::error!(id = %job.id, error = %e, "saving the analysis result failed");
@@ -292,7 +306,7 @@ impl Analyzer {
sqlx::query(
"UPDATE analyses SET status = 'done', content = $2, model_used = $3, input_tokens = $4, \
output_tokens = $5, cost_usd = $6, error = NULL, completed_at = now() \
- WHERE id = $1 AND status = 'running'",
+ WHERE id = $1 AND status = 'running' AND started_at = $7",
)
.bind(job.id)
.bind(&c.content)
@@ -300,6 +314,7 @@ impl Analyzer {
.bind(c.input_tokens)
.bind(c.output_tokens)
.bind(c.cost_usd)
+ .bind(job.started_at)
.execute(&self.db)
.await?;
tracing::info!(
@@ -309,15 +324,34 @@ impl Analyzer {
}
Err(e) => {
let can_fall_back = !job.on_fallback && job.fallback_model.is_some();
- match next_step(&e, job.attempts, self.max_attempts, can_fall_back) {
+ let next = next_step(&e, job.attempts, self.max_attempts, can_fall_back);
+ let outcome = match next {
+ Next::Retry(_) => "retry",
+ Next::Fallback => "fallback",
+ Next::Fail => "failed",
+ };
+ self.log_error(
+ "analysis",
+ job.id,
+ &job.kind,
+ job.active_model(),
+ job.attempts,
+ outcome,
+ e.message(),
+ took,
+ )
+ .await;
+ match next {
Next::Retry(wait) => {
sqlx::query(
"UPDATE analyses SET status = 'pending', error = $2, \
- next_attempt_at = now() + make_interval(secs => $3) WHERE id = $1 AND status = 'running'",
+ next_attempt_at = now() + make_interval(secs => $3) \
+ WHERE id = $1 AND status = 'running' AND started_at = $4",
)
.bind(job.id)
.bind(e.message())
.bind(wait.as_secs_f64())
+ .bind(job.started_at)
.execute(&self.db)
.await?;
tracing::warn!(id = %job.id, attempts = job.attempts, retry_in_secs = wait.as_secs(), error = %e.message(), "analysis will be retried");
@@ -325,10 +359,11 @@ impl Analyzer {
Next::Fallback => {
sqlx::query(
"UPDATE analyses SET status = 'pending', error = $2, on_fallback = true, attempts = 0, \
- next_attempt_at = now() WHERE id = $1 AND status = 'running'",
+ next_attempt_at = now() WHERE id = $1 AND status = 'running' AND started_at = $3",
)
.bind(job.id)
.bind(e.message())
+ .bind(job.started_at)
.execute(&self.db)
.await?;
tracing::warn!(
@@ -337,7 +372,7 @@ impl Analyzer {
);
}
Next::Fail => {
- self.fail(job.id, e.message()).await?;
+ self.fail(job.id, job.started_at, e.message()).await?;
tracing::error!(id = %job.id, attempts = job.attempts, error = %e.message(), "analysis failed");
}
}
@@ -347,14 +382,15 @@ impl Analyzer {
}
/// Marks the analysis failed and gives its unit back (once).
- async fn fail(&self, id: Uuid, message: &str) -> Result<(), sqlx::Error> {
+ async fn fail(&self, id: Uuid, started_at: time::OffsetDateTime, message: &str) -> Result<(), sqlx::Error> {
let mut tx = self.db.begin().await?;
let row: Option<(Option, i32, String)> = sqlx::query_as(
"UPDATE analyses SET status = 'failed', error = $2, completed_at = now() \
- WHERE id = $1 AND status = 'running' RETURNING requested_by, credits_charged, kind",
+ WHERE id = $1 AND status = 'running' AND started_at = $3 RETURNING requested_by, credits_charged, kind",
)
.bind(id)
.bind(message)
+ .bind(started_at)
.fetch_optional(&mut *tx)
.await?;
if let Some((Some(user), units, kind)) = row
@@ -407,6 +443,53 @@ impl Analyzer {
Ok(result.rows_affected())
}
+ /// Records a failed attempt in the admin error log (a failure here is only logged).
+ #[allow(clippy::too_many_arguments)]
+ pub(crate) async fn log_error(
+ &self,
+ source: &str,
+ item_id: Uuid,
+ kind: &str,
+ model: &str,
+ attempt: i32,
+ outcome: &str,
+ error: &str,
+ took: Duration,
+ ) {
+ let result = sqlx::query(
+ "INSERT INTO generation_errors (source, item_id, kind, model, attempt, outcome, error, seconds) \
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)",
+ )
+ .bind(source)
+ .bind(item_id)
+ .bind(kind)
+ .bind(model)
+ .bind(attempt)
+ .bind(outcome)
+ .bind(error.chars().take(2000).collect::())
+ .bind(i32::try_from(took.as_secs()).unwrap_or(i32::MAX))
+ .execute(&self.db)
+ .await;
+ if let Err(e) = result {
+ tracing::error!(error = %e, "writing the error log");
+ }
+ }
+
+ /// Resolves when this attempt is no longer the current one (an admin
+ /// restarted it); checked every 10 seconds, never on a database error.
+ async fn superseded(&self, table: &str, id: Uuid, started_at: time::OffsetDateTime) {
+ let query = format!("SELECT status = 'running' AND started_at = $2 FROM {table} WHERE id = $1");
+ loop {
+ tokio::time::sleep(Duration::from_secs(10)).await;
+ match sqlx::query_scalar::<_, Option>(&query).bind(id).bind(started_at).fetch_optional(&self.db).await
+ {
+ Ok(Some(Some(true))) => {}
+ Ok(_) => return,
+ Err(_) => {}
+ }
+ }
+ }
+
/// On shutdown: analyses still being written go back to `pending` at once.
async fn release_running(&self) {
let ids: Vec = self.running.lock().unwrap().drain().collect();
diff --git a/services/worker/src/analysis/questions.rs b/services/worker/src/analysis/questions.rs
index ea6623c..2ea8af0 100644
--- a/services/worker/src/analysis/questions.rs
+++ b/services/worker/src/analysis/questions.rs
@@ -27,6 +27,8 @@ pub struct QuestionJob {
pub created_at: time::OffsetDateTime,
pub fallback_model: Option,
pub on_fallback: bool,
+ /// The token of this attempt (see `Job::started_at`).
+ pub started_at: time::OffsetDateTime,
}
impl Analyzer {
@@ -37,7 +39,7 @@ impl Analyzer {
WHERE id = (SELECT id FROM questions WHERE status = 'pending' AND next_attempt_at <= now() \
ORDER BY next_attempt_at LIMIT 1 FOR UPDATE SKIP LOCKED) \
RETURNING id, analysis_id, question, language, model, prompt_version, attempts, created_at, \
- fallback_model, on_fallback",
+ fallback_model, on_fallback, started_at",
)
.fetch_optional(&self.db)
.await?;
@@ -49,8 +51,9 @@ impl Analyzer {
async fn question_prompt(&self, job: &QuestionJob) -> Result {
let db_err = |e: sqlx::Error| LlmError::Transient(format!("database: {e}"));
- let (kind, chart_id, forecast_id, content): (String, Option, Option, Option) =
- sqlx::query_as("SELECT kind, chart_id, forecast_id, content FROM analyses WHERE id = $1")
+ type Row = (String, Option, Option, Option, Option);
+ let (kind, chart_id, synastry_id, forecast_id, content): Row =
+ sqlx::query_as("SELECT kind, chart_id, synastry_id, forecast_id, content FROM analyses WHERE id = $1")
.bind(job.analysis_id)
.fetch_optional(&self.db)
.await
@@ -60,6 +63,7 @@ impl Analyzer {
let content = content.ok_or_else(|| LlmError::Permanent("the analysis has no text".into()))?;
let chart_text = match kind {
Kind::Forecast => self.forecast_text(forecast_id).await?,
+ Kind::Synastry => self.synastry_text(synastry_id).await?,
_ => self.natal_text(chart_id).await?,
};
let analysis = prompt::to_markdown(kind, &job.language, &content);
@@ -91,15 +95,24 @@ impl Analyzer {
/// Answers one claimed question and records the outcome.
pub async fn handle_question(&self, job: QuestionJob) {
let started = Instant::now();
- let result = match self.question_prompt(&job).await {
- Ok(p) => {
- let model = active_model(&job.model, job.fallback_model.as_deref(), job.on_fallback);
- self.llm.complete(model, &p).await.map(|mut c| {
- prompt::polish(&job.language, &mut c.content);
- c
- })
+ let work = async {
+ match self.question_prompt(&job).await {
+ Ok(p) => {
+ let model = active_model(&job.model, job.fallback_model.as_deref(), job.on_fallback);
+ self.llm.complete(model, &p).await.map(|mut c| {
+ prompt::polish(&job.language, &mut c.content);
+ c
+ })
+ }
+ Err(e) => Err(e),
+ }
+ };
+ let result = tokio::select! {
+ result = work => result,
+ () = self.superseded("questions", job.id, job.started_at) => {
+ tracing::info!(id = %job.id, "answer restarted by an admin; this attempt is dropped");
+ return;
}
- Err(e) => Err(e),
};
if let Err(e) = self.finish_question(&job, result, started.elapsed()).await {
tracing::error!(id = %job.id, error = %e, "saving the answer failed");
@@ -119,7 +132,7 @@ impl Analyzer {
sqlx::query(
"UPDATE questions SET status = 'done', answer = $2, model_used = $3, input_tokens = $4, \
output_tokens = $5, cost_usd = $6, error = NULL, completed_at = now() \
- WHERE id = $1 AND status = 'running'",
+ WHERE id = $1 AND status = 'running' AND started_at = $7",
)
.bind(job.id)
.bind(&answer)
@@ -127,6 +140,7 @@ impl Analyzer {
.bind(c.input_tokens)
.bind(c.output_tokens)
.bind(c.cost_usd)
+ .bind(job.started_at)
.execute(&self.db)
.await?;
tracing::info!(
@@ -136,15 +150,25 @@ impl Analyzer {
}
Err(e) => {
let can_fall_back = !job.on_fallback && job.fallback_model.is_some();
- match next_step(&e, job.attempts, self.max_attempts, can_fall_back) {
+ let next = next_step(&e, job.attempts, self.max_attempts, can_fall_back);
+ let outcome = match next {
+ Next::Retry(_) => "retry",
+ Next::Fallback => "fallback",
+ Next::Fail => "failed",
+ };
+ let model = active_model(&job.model, job.fallback_model.as_deref(), job.on_fallback);
+ self.log_error("question", job.id, "question", model, job.attempts, outcome, e.message(), took).await;
+ match next {
Next::Retry(wait) => {
sqlx::query(
"UPDATE questions SET status = 'pending', error = $2, \
- next_attempt_at = now() + make_interval(secs => $3) WHERE id = $1 AND status = 'running'",
+ next_attempt_at = now() + make_interval(secs => $3) \
+ WHERE id = $1 AND status = 'running' AND started_at = $4",
)
.bind(job.id)
.bind(e.message())
.bind(wait.as_secs_f64())
+ .bind(job.started_at)
.execute(&self.db)
.await?;
tracing::warn!(id = %job.id, attempts = job.attempts, error = %e.message(), "answer will be retried");
@@ -152,10 +176,11 @@ impl Analyzer {
Next::Fallback => {
sqlx::query(
"UPDATE questions SET status = 'pending', error = $2, on_fallback = true, attempts = 0, \
- next_attempt_at = now() WHERE id = $1 AND status = 'running'",
+ next_attempt_at = now() WHERE id = $1 AND status = 'running' AND started_at = $3",
)
.bind(job.id)
.bind(e.message())
+ .bind(job.started_at)
.execute(&self.db)
.await?;
tracing::warn!(
@@ -164,7 +189,7 @@ impl Analyzer {
);
}
Next::Fail => {
- self.fail_question(job.id, e.message()).await?;
+ self.fail_question(job.id, job.started_at, e.message()).await?;
tracing::error!(id = %job.id, attempts = job.attempts, error = %e.message(), "answer failed");
}
}
@@ -174,14 +199,20 @@ impl Analyzer {
}
/// Marks the question failed and gives its unit back (once).
- async fn fail_question(&self, id: Uuid, message: &str) -> Result<(), sqlx::Error> {
+ async fn fail_question(
+ &self,
+ id: Uuid,
+ started_at: time::OffsetDateTime,
+ message: &str,
+ ) -> Result<(), sqlx::Error> {
let mut tx = self.db.begin().await?;
let row: Option<(Option, i32)> = sqlx::query_as(
"UPDATE questions SET status = 'failed', error = $2, completed_at = now() \
- WHERE id = $1 AND status = 'running' RETURNING asked_by, credits_charged",
+ WHERE id = $1 AND status = 'running' AND started_at = $3 RETURNING asked_by, credits_charged",
)
.bind(id)
.bind(message)
+ .bind(started_at)
.fetch_optional(&mut *tx)
.await?;
if let Some((Some(user), units)) = row
diff --git a/services/worker/src/cleanup.rs b/services/worker/src/cleanup.rs
index 76d4e9a..fc8e3e0 100644
--- a/services/worker/src/cleanup.rs
+++ b/services/worker/src/cleanup.rs
@@ -8,7 +8,7 @@ use tokio::sync::watch;
const INTERVAL: Duration = Duration::from_secs(3600);
/// (what, statement) pairs; each returns the number of deleted rows.
-const STATEMENTS: [(&str, &str); 6] = [
+const STATEMENTS: [(&str, &str); 7] = [
("sessions", "DELETE FROM sessions WHERE expires_at < now()"),
("auth_tokens", "DELETE FROM auth_tokens WHERE expires_at < now()"),
// Sent e-mails contain links with tokens; keep them a week for support.
@@ -26,6 +26,7 @@ const STATEMENTS: [(&str, &str); 6] = [
OR (accepted_at IS NOT NULL AND accepted_by IS NULL)",
),
("prompt_previews", "DELETE FROM prompt_previews WHERE created_at < now() - interval '30 days'"),
+ ("generation_errors", "DELETE FROM generation_errors WHERE created_at < now() - interval '90 days'"),
];
pub async fn run_once(db: &PgPool) -> Result, sqlx::Error> {
diff --git a/services/worker/src/tests.rs b/services/worker/src/tests.rs
index bf4c9c4..2079009 100644
--- a/services/worker/src/tests.rs
+++ b/services/worker/src/tests.rs
@@ -212,7 +212,8 @@ async fn cleanup_removes_only_expired_data(db: PgPool) {
("emails", 1),
("invites", 0),
("invitations", 0),
- ("prompt_previews", 0)
+ ("prompt_previews", 0),
+ ("generation_errors", 0)
]
);
let (left,): (Vec,) =
@@ -533,6 +534,18 @@ mod analyses {
let (status, attempts, ..) = row(&db, id).await;
assert_eq!((status.as_str(), attempts), ("failed", 3));
assert_eq!(refunds(&db, s.user).await, vec![1]);
+ // every failed attempt is in the admin error log
+ let log: Vec<(String, i32, String, String)> = sqlx::query_as(
+ "SELECT source, attempt, outcome, model FROM generation_errors WHERE item_id = $1 ORDER BY id",
+ )
+ .bind(id)
+ .fetch_all(&db)
+ .await
+ .unwrap();
+ let expected = |attempt: i32, outcome: &str| {
+ ("analysis".to_string(), attempt, outcome.to_string(), "test/model".to_string())
+ };
+ assert_eq!(log, vec![expected(1, "retry"), expected(2, "retry"), expected(3, "failed")]);
}
#[sqlx::test(migrator = "db::MIGRATOR")]
@@ -780,5 +793,90 @@ mod analyses {
let models: Vec =
fake.requests.lock().unwrap().iter().map(|b| b["model"].as_str().unwrap().to_string()).collect();
assert_eq!(models, ["cheap/model", "cheap/model", "test/model"]);
+ let outcomes: Vec<(String, String)> =
+ sqlx::query_as("SELECT outcome, model FROM generation_errors WHERE item_id = $1 ORDER BY id")
+ .bind(id)
+ .fetch_all(&db)
+ .await
+ .unwrap();
+ assert_eq!(
+ outcomes,
+ [("retry".to_string(), "cheap/model".to_string()), ("fallback".to_string(), "cheap/model".to_string())]
+ );
+ }
+
+ #[sqlx::test(migrator = "db::MIGRATOR")]
+ async fn a_restarted_attempt_does_not_write_its_result(db: PgPool) {
+ let s = setup(&db).await;
+ let id = request_analysis(&db, &s).await;
+ let (_, url) = fake_openrouter(vec![reply(&content(Kind::Natal))]).await;
+ let a = analyzer(&db, &url);
+ let job = a.claim().await.unwrap().expect("a job");
+ // an admin restarts it while the worker is still writing it
+ sqlx::query("UPDATE analyses SET status = 'pending', started_at = NULL, attempts = 0 WHERE id = $1")
+ .bind(id)
+ .execute(&db)
+ .await
+ .unwrap();
+ a.handle(job).await;
+ let (status, content): (String, Option) =
+ sqlx::query_as("SELECT status, content FROM analyses WHERE id = $1").bind(id).fetch_one(&db).await.unwrap();
+ assert_eq!((status.as_str(), content), ("pending", None));
+ // the new attempt writes it
+ assert!(run_once(&a).await);
+ let status: String =
+ sqlx::query_scalar("SELECT status FROM analyses WHERE id = $1").bind(id).fetch_one(&db).await.unwrap();
+ assert_eq!(status, "done");
+ }
+
+ #[sqlx::test(migrator = "db::MIGRATOR")]
+ async fn answers_a_question_about_a_relationship_with_both_charts(db: PgPool) {
+ let s = setup(&db).await;
+ let response = fixture("synastry-response.json");
+ let (chart2, synastry, analysis) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());
+ sqlx::query(
+ "INSERT INTO charts (id, owner_id, label, is_primary, kind, birth_data, result, chart_hash) \
+ VALUES ($1, $2, 'Partner', false, 'person', '{}', $3, 'hash2')",
+ )
+ .bind(chart2)
+ .bind(s.user)
+ .bind(&response["person2"])
+ .execute(&db)
+ .await
+ .unwrap();
+ sqlx::query(
+ "INSERT INTO synastries (id, owner_id, chart1_id, chart2_id, result, synastry_hash) \
+ VALUES ($1, $2, $3, $4, $5, 'sh')",
+ )
+ .bind(synastry)
+ .bind(s.user)
+ .bind(s.chart)
+ .bind(chart2)
+ .bind(&response)
+ .execute(&db)
+ .await
+ .unwrap();
+ sqlx::query(
+ "INSERT INTO analyses (id, kind, synastry_id, requested_by, language, model, prompt_version, cache_key, \
+ status, content) VALUES ($1, 'synastry', $2, $3, 'hu', 'test/model', 'v1', 'k', 'done', $4)",
+ )
+ .bind(analysis)
+ .bind(synastry)
+ .bind(s.user)
+ .bind(content(Kind::Synastry))
+ .execute(&db)
+ .await
+ .unwrap();
+ let id = ask(&db, analysis, s.user, "Mire figyeljünk egy vitában?", "pending", None).await;
+ let (fake, url) = fake_openrouter(vec![reply(&json!({"answer": "Arra, hogy..."}))]).await;
+ let a = analyzer(&db, &url);
+ assert!(answer_once(&a).await);
+ let status: String =
+ sqlx::query_scalar("SELECT status FROM questions WHERE id = $1").bind(id).fetch_one(&db).await.unwrap();
+ assert_eq!(status, "done");
+ let requests = fake.requests.lock().unwrap();
+ let user = requests[0]["messages"][1]["content"].as_str().unwrap();
+ assert!(user.starts_with("Képletadatok:\n\nSYNASTRY") && user.contains("Person 2"), "both charts");
+ assert!(!user.contains("Szeged") && !user.contains("Pécs"));
}
}