merge: integrate Bloomberg generation reliability

This commit is contained in:
2026-11-24 09:42:48 +01:00
11 changed files with 641 additions and 73 deletions

View File

@ -3,7 +3,7 @@ package ai
import (
"bytes"
"context"
"fmt"
"errors"
"os/exec"
"strings"
)
@ -28,17 +28,11 @@ func (p *claudeCodeProvider) Summarize(ctx context.Context, prompt string, _ Gen
cmd.Stderr = &stderr
err := cmd.Run()
fmt.Printf("[claudecode] stdout len=%d stderr=%q err=%v\n", stdout.Len(), stderr.String(), err)
if err != nil {
msg := strings.TrimSpace(stderr.String())
if msg == "" {
msg = strings.TrimSpace(stdout.String())
if ctx.Err() != nil {
return "", ctx.Err()
}
if msg == "" {
msg = err.Error()
}
return "", fmt.Errorf("claude cli: %s", msg)
return "", errors.New("claude cli: execution failed")
}
return strings.TrimSpace(stdout.String()), nil
}

View File

@ -0,0 +1,136 @@
package ai
import (
"bytes"
"context"
"encoding/json"
"errors"
"github.com/tradarr/backend/internal/generation"
"github.com/tradarr/backend/internal/models"
"github.com/tradarr/backend/internal/scraper"
"io"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
type reliabilityRepo struct{ saved []generation.GenerationRecord }
func (r *reliabilityRepo) LoadUserInput(context.Context, string) (generation.UserInput, error) {
key := models.SourceYahooFinance
return generation.UserInput{Language: "fr", RankingMode: "title", GlobalLimit: 1, Assets: []models.UserAsset{{Name: "Fixture Company"}}, Sources: []models.Source{{ID: "s", SourceKey: &key, Enabled: true, ArticleLimit: 1}}}, nil
}
func (r *reliabilityRepo) SaveGeneration(ctx context.Context, _ string, record generation.GenerationRecord) error {
if ctx.Err() != nil {
return ctx.Err()
}
r.saved = append(r.saved, record)
return nil
}
type reliabilityFeed struct{}
func (reliabilityFeed) Name() string { return "fixture" }
func (reliabilityFeed) Scrape(context.Context, []string) ([]scraper.Article, error) {
return []scraper.Article{{Title: "Fixture Company"}}, nil
}
type reliabilityDecider struct{}
func (reliabilityDecider) DecideMentions(context.Context, string, string, []models.UserAsset, []generation.Candidate) ([]generation.Candidate, error) {
return nil, errors.New("unexpected ranking for exact mention")
}
func TestTicket35HTTPProviderFailureReachesSafeGenerationOutcome(t *testing.T) {
for _, kind := range []string{"timeout", "canceled", "provider"} {
t.Run(kind, func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
provider := newOllama("http://PRIVATE_URL.invalid", "fixture")
provider.client = &http.Client{Transport: ticket31Transport(func(*http.Request) (*http.Response, error) {
if kind == "timeout" {
return nil, &url.Error{URL: "http://PRIVATE_URL.invalid", Err: context.DeadlineExceeded}
}
if kind == "canceled" {
cancel()
return nil, context.Canceled
}
return &http.Response{StatusCode: 503, Body: io.NopCloser(strings.NewReader("PRIVATE_BODY PRIVATE_SECRET")), Header: make(http.Header)}, nil
})}
repo := &reliabilityRepo{}
uc := generation.NewUseCase(generation.Dependencies{Repository: repo, Decider: reliabilityDecider{}, Summarizer: generationSummarizer{provider: provider}, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: reliabilityFeed{}}})
r, err := uc.Generate(ctx, "fixture")
want := map[string]string{"timeout": "summary_timeout", "canceled": "summary_canceled", "provider": "summary_failed"}[kind]
if err != nil || r.Outcome.FailureCode != want || r.Summary != nil || len(repo.saved) != 1 {
t.Fatalf("code=%s err=%v", r.Outcome.FailureCode, err)
}
encoded, _ := json.Marshal(repo.saved)
if bytes.Contains(encoded, []byte("PRIVATE")) {
t.Fatal("raw provider error persisted")
}
})
}
}
func TestTicket35RealAdapterKeepsFiveMinuteBudgetAcrossMentionPasses(t *testing.T) {
ranker, _ := NewLayaHTTPRanker(LayaHTTPConfig{BaseURL: "http://fixture.invalid"})
ctx, cancel := ranker.WithSelectionBudget(context.Background())
defer cancel()
deadline, _ := ctx.Deadline()
calls := 0
ranker.client = &http.Client{Transport: ticket31Transport(func(req *http.Request) (*http.Response, error) {
calls++
actual, ok := req.Context().Deadline()
if !ok || !actual.Equal(deadline) || time.Until(actual) < 4*time.Minute+59*time.Second || time.Until(actual) > 5*time.Minute {
t.Fatal("shared default deadline changed")
}
var payload struct{ Questions map[string]any }
_ = json.NewDecoder(req.Body).Decode(&payload)
key := ""
for k := range payload.Questions {
key = k
}
raw := `{"results":[{"answers":{"` + key + `":{"type":"noul","noul":0.1,"answer_confidence":0.99}},"usage":{"truncated":false}}]}`
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(raw)), Header: make(http.Header)}, nil
})}
for _, pass := range []string{generation.MentionDirect, generation.MentionIndirect} {
got, err := ranker.DecideMentions(ctx, "title", pass, nil, []generation.Candidate{{ID: "fixture"}})
if err != nil || len(got) != 0 {
t.Fatal(err)
}
}
if calls != 2 {
t.Fatal(calls)
}
}
func TestTicket35ClaudeCLIErrorDoesNotExposeStdoutStderrOrRawError(t *testing.T) {
directory := t.TempDir()
binary := filepath.Join(directory, "claude")
if err := os.WriteFile(binary, []byte("#!/bin/sh\nprintf 'PRIVATE_STDOUT'\nprintf 'PRIVATE_STDERR' >&2\nexit 1\n"), 0700); err != nil {
t.Fatal(err)
}
t.Setenv("PATH", directory+string(os.PathListSeparator)+os.Getenv("PATH"))
reader, writer, err := os.Pipe()
if err != nil {
t.Fatal(err)
}
old := os.Stdout
os.Stdout = writer
t.Cleanup(func() { os.Stdout = old; reader.Close(); writer.Close() })
_, providerErr := newClaudeCode("fixture").Summarize(context.Background(), "PRIVATE_PROMPT", GenOptions{})
writer.Close()
os.Stdout = old
output, _ := io.ReadAll(reader)
if providerErr == nil || strings.Contains(providerErr.Error(), "PRIVATE") || bytes.Contains(output, []byte("PRIVATE")) {
t.Fatal("raw CLI diagnostics escaped")
}
canceled, cancel := context.WithCancel(context.Background())
cancel()
_, providerErr = newClaudeCode("fixture").Summarize(canceled, "fixture", GenOptions{})
if !errors.Is(providerErr, context.Canceled) {
t.Fatal("CLI cancellation identity lost")
}
}

View File

@ -3,6 +3,7 @@ package generation
import (
"context"
"crypto/rand"
"errors"
"fmt"
"strings"
"time"
@ -135,7 +136,15 @@ func (u *useCase) Generate(ctx context.Context, userID string) (Result, error) {
result.Summary.ModelName = &resolved.Model
}
}
if err := u.Repository.SaveGeneration(ctx, userID, result); err != nil {
saveCtx := ctx
// Terminal metadata must survive a canceled provider/worker context.
// Preserve the job identity for the existing atomic finalization path.
if status == "failed" && ctx.Err() != nil {
var cancel context.CancelFunc
saveCtx, cancel = context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second)
defer cancel()
}
if err := u.Repository.SaveGeneration(saveCtx, userID, result); err != nil {
return Result{}, fmt.Errorf("save generation: %w", err)
}
return result, nil
@ -232,7 +241,10 @@ func (u *useCase) Generate(ctx context.Context, userID string) (Result, error) {
return finish("no_results", "", "")
}
content, err := resolved.Summarizer.Summarize(ctx, input.Language, input.Assets, selected)
if err != nil || strings.TrimSpace(content) == "" {
if err != nil || ctx.Err() != nil {
return finish("failed", summaryFailureCode(ctx, err), "")
}
if strings.TrimSpace(content) == "" {
return finish("failed", "summary_failed", "")
}
if partial {
@ -240,3 +252,17 @@ func (u *useCase) Generate(ctx context.Context, userID string) (Result, error) {
}
return finish("succeeded", "", content)
}
func summaryFailureCode(ctx context.Context, err error) string {
if errors.Is(ctx.Err(), context.DeadlineExceeded) || errors.Is(err, context.DeadlineExceeded) {
return "summary_timeout"
}
if errors.Is(ctx.Err(), context.Canceled) || errors.Is(err, context.Canceled) {
return "summary_canceled"
}
var timeout interface{ Timeout() bool }
if errors.As(err, &timeout) && timeout.Timeout() {
return "summary_timeout"
}
return "summary_failed"
}

View File

@ -0,0 +1,172 @@
package generation
import (
"context"
"encoding/json"
"errors"
"fmt"
"github.com/tradarr/backend/internal/models"
"github.com/tradarr/backend/internal/scraper"
"github.com/tradarr/backend/internal/scraper/bloomberg"
"io"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"time"
)
func TestTicket35SummaryFailureDistinguishesTimeoutCancellationAndProvider(t *testing.T) {
for _, tc := range []struct {
name string
err error
code string
}{
{"timeout", fmt.Errorf("PRIVATE_BODY: %w", context.DeadlineExceeded), "summary_timeout"},
{"cancel", fmt.Errorf("PRIVATE_BODY: %w", context.Canceled), "summary_canceled"},
{"http timeout", &url.Error{URL: "https://PRIVATE_URL.invalid", Err: context.DeadlineExceeded}, "summary_timeout"},
{"provider", errors.New("PRIVATE_BODY timeout https://PRIVATE_URL.invalid"), "summary_failed"},
} {
t.Run(tc.name, func(t *testing.T) {
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title", GlobalLimit: 1, Assets: []models.UserAsset{{Name: "Fixture Company"}}, Sources: []models.Source{{ID: "s", SourceKey: testSourceKey(models.SourceYahooFinance), Enabled: true, ArticleLimit: 1}}}}, saved: map[string][]GenerationRecord{}}
sum := &contractSummarizer{err: tc.err}
r, err := NewUseCase(Dependencies{Repository: repo, Decider: &allYesMention{}, Summarizer: sum, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: &contractScraper{articles: []scraper.Article{{Title: "Fixture Company"}}}}}).Generate(context.Background(), "u")
if err != nil || r.Summary != nil || r.Outcome.Status != "failed" || r.Outcome.FailureCode != tc.code {
t.Fatalf("status=%s code=%s err=%v", r.Outcome.Status, r.Outcome.FailureCode, err)
}
encoded, _ := json.Marshal(repo.saved)
if strings.Contains(string(encoded), "PRIVATE") || strings.Contains(string(encoded), "https://") {
t.Fatal("raw provider error persisted")
}
})
}
}
type cancelSummary struct{ cancel context.CancelFunc }
func (s cancelSummary) Summarize(context.Context, string, []models.UserAsset, []Candidate) (string, error) {
s.cancel()
return "", fmt.Errorf("PRIVATE_PROVIDER_ERROR: %w", context.Canceled)
}
type terminalRepo struct {
*contractRepository
expectedJob string
checked bool
}
func (r *terminalRepo) SaveGeneration(ctx context.Context, user string, record GenerationRecord) error {
if ctx.Err() != nil {
return ctx.Err()
}
if models.GenerationJobID(ctx) != r.expectedJob {
return errors.New("job identity lost")
}
deadline, ok := ctx.Deadline()
if !ok || time.Until(deadline) > 10*time.Second {
return errors.New("terminal persistence is not bounded")
}
r.checked = true
return r.contractRepository.SaveGeneration(ctx, user, record)
}
func TestTicket35CanceledSummaryStillPersistsSafeTerminalOutcome(t *testing.T) {
base := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title", GlobalLimit: 1, Assets: []models.UserAsset{{Name: "Fixture Company"}}, Sources: []models.Source{{ID: "s", SourceKey: testSourceKey(models.SourceYahooFinance), Enabled: true, ArticleLimit: 1}}}}, saved: map[string][]GenerationRecord{}}
repo := &terminalRepo{contractRepository: base, expectedJob: "fixture-job"}
ctx, cancel := context.WithCancel(models.WithGenerationJob(context.Background(), repo.expectedJob))
defer cancel()
r, err := NewUseCase(Dependencies{Repository: repo, Decider: &allYesMention{}, Summarizer: cancelSummary{cancel}, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: &contractScraper{articles: []scraper.Article{{Title: "Fixture Company"}}}}}).Generate(ctx, "u")
if err != nil || !repo.checked || r.Summary != nil || r.Outcome.FailureCode != "summary_canceled" || len(base.saved["u"]) != 1 {
t.Fatal(r.Outcome, err)
}
}
type budgetMention struct {
contexts []context.Context
budgetCalls int
failIndirect bool
}
func (b *budgetMention) WithSelectionBudget(ctx context.Context) (context.Context, context.CancelFunc) {
b.budgetCalls++
return context.WithTimeout(ctx, 5*time.Minute)
}
func (b *budgetMention) DecideMentions(ctx context.Context, _, pass string, _ []models.UserAsset, candidates []Candidate) ([]Candidate, error) {
b.contexts = append(b.contexts, ctx)
if pass == MentionIndirect {
if b.failIndirect {
return nil, context.DeadlineExceeded
}
return candidates, nil
}
return nil, nil
}
func TestTicket35ThreePassBudgetIsSharedAndFailureDropsAllSelection(t *testing.T) {
articles := []scraper.Article{{Title: "Fixture Company"}}
for i := 0; i < 65; i++ {
articles = append(articles, scraper.Article{Title: fmt.Sprintf("unmatched %d", i)})
}
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title", GlobalLimit: 100, Assets: []models.UserAsset{{Name: "Fixture Company"}}, Sources: []models.Source{{ID: "s", SourceKey: testSourceKey(models.SourceYahooFinance), Enabled: true, ArticleLimit: 100}}}}, saved: map[string][]GenerationRecord{}}
gate := &budgetMention{failIndirect: true}
sum := &contractSummarizer{}
r, err := NewUseCase(Dependencies{Repository: repo, Decider: gate, Summarizer: sum, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: &contractScraper{articles: articles}}}).Generate(context.Background(), "u")
if err != nil || r.Summary != nil || r.Outcome.FailureCode != "ranking_failed" || len(sum.articles) != 0 || gate.budgetCalls != 1 || len(gate.contexts) != 3 {
t.Fatal(r.Outcome, err)
}
first, _ := gate.contexts[0].Deadline()
for _, ctx := range gate.contexts {
deadline, ok := ctx.Deadline()
if !ok || !deadline.Equal(first) || time.Until(deadline) < 4*time.Minute+59*time.Second || time.Until(deadline) > 5*time.Minute {
t.Fatal("ranking deadline reset/reduced")
}
}
}
type bloombergFixtureFeed struct{ client *bloomberg.Bloomberg }
func (b bloombergFixtureFeed) Name() string { return "bloomberg" }
func (b bloombergFixtureFeed) Scrape(ctx context.Context, symbols []string) ([]scraper.Article, error) {
return b.client.ScrapeWithCredentials(ctx, "fixture", "fixture", symbols)
}
func TestTicket35BloombergMissingContentProducesHonestGenerationFallback(t *testing.T) {
requests := 0
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requests++
if r.URL.Path != "/bloomberg/scrape" {
t.Error("unexpected scraper path")
}
w.Header().Set("Content-Type", "application/json")
io.WriteString(w, `{"articles":[{"title":"Fixture Company","url":"https://fixture.invalid/article","published_at":null}]}`)
}))
defer server.Close()
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title_content", GlobalLimit: 1, Assets: []models.UserAsset{{Name: "Fixture Company"}}, Sources: []models.Source{{ID: "s", SourceKey: testSourceKey(models.SourceBloomberg), Enabled: true, ArticleLimit: 1}}}}, saved: map[string][]GenerationRecord{}}
summary := &contractSummarizer{}
r, err := NewUseCase(Dependencies{Repository: repo, Decider: &allYesMention{}, Summarizer: summary, Scrapers: map[string]scraper.Scraper{models.SourceBloomberg: bloombergFixtureFeed{bloomberg.New(server.URL)}}}).Generate(context.Background(), "u")
if err != nil || r.Summary == nil || requests != 1 || r.Outcome.ContentFallbacks != 1 || r.Outcome.SourceStats[0].ContentFallbacks != 1 || len(summary.articles) != 1 || summary.articles[0][0].Article.Content != "" || summary.articles[0][0].Article.PublishedAt != nil {
t.Fatal("inaccurate Bloomberg content availability", r.Outcome, err)
}
}
type liveContextSummary struct{ called bool }
func (s *liveContextSummary) Summarize(ctx context.Context, _ string, _ []models.UserAsset, _ []Candidate) (string, error) {
s.called = true
if ctx.Err() != nil {
return "", ctx.Err()
}
return "fixture synthesis", nil
}
func TestTicket35SummaryDoesNotInheritCanceledSelectionBudget(t *testing.T) {
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title", GlobalLimit: 1, Assets: []models.UserAsset{{Name: "Fixture Company"}}, Sources: []models.Source{{ID: "s", SourceKey: testSourceKey(models.SourceYahooFinance), Enabled: true, ArticleLimit: 1}}}}, saved: map[string][]GenerationRecord{}}
gate := &budgetMention{}
sum := &liveContextSummary{}
r, err := NewUseCase(Dependencies{Repository: repo, Decider: gate, Summarizer: sum, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: &contractScraper{articles: []scraper.Article{{Title: "unmatched"}}}}}).Generate(context.Background(), "u")
if err != nil || r.Summary == nil || !sum.called || gate.budgetCalls != 1 || len(gate.contexts) != 2 {
t.Fatal(r.Outcome, err)
}
for _, ctx := range gate.contexts {
if ctx.Err() != context.Canceled {
t.Fatal("selection context was not released")
}
}
}

View File

@ -4,6 +4,7 @@ import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
@ -50,27 +51,30 @@ func (b *Bloomberg) ScrapeWithCredentials(ctx context.Context, username, passwor
payload, _ := json.Marshal(scraperRequest{Username: username, Password: password})
req, err := http.NewRequestWithContext(ctx, http.MethodPost, b.scraperURL+"/bloomberg/scrape", bytes.NewReader(payload))
if err != nil {
return nil, err
return nil, errors.New("bloomberg: request construction failed")
}
req.Header.Set("Content-Type", "application/json")
resp, err := b.client.Do(req)
if err != nil {
return nil, fmt.Errorf("scraper service unreachable: %w", err)
return nil, scraperFailure(ctx, err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("scraper service HTTP %d: %s", resp.StatusCode, body)
return nil, fmt.Errorf("bloomberg: scraper HTTP %d", resp.StatusCode)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, scraperFailure(ctx, err)
}
var result scraperResponse
if err := json.Unmarshal(body, &result); err != nil {
return nil, fmt.Errorf("parse scraper response: %w", err)
return nil, errors.New("bloomberg: invalid response")
}
if result.Error != "" {
return nil, fmt.Errorf("bloomberg: %s", result.Error)
return nil, errors.New("bloomberg: scraper failure")
}
var articles []scraper.Article
@ -90,7 +94,6 @@ func (b *Bloomberg) ScrapeWithCredentials(ctx context.Context, username, passwor
syms := scraper.DetectSymbols(title, symbols)
articles = append(articles, scraper.Article{
Title: title,
Content: title,
URL: url,
PublishedAt: date,
Symbols: syms,
@ -99,3 +102,18 @@ func (b *Bloomberg) ScrapeWithCredentials(ctx context.Context, username, passwor
fmt.Printf("bloomberg: %d articles fetched\n", len(articles))
return articles, nil
}
// Preserve only typed timeout/cancellation identity, never the raw transport error.
func scraperFailure(ctx context.Context, err error) error {
if errors.Is(ctx.Err(), context.DeadlineExceeded) || errors.Is(err, context.DeadlineExceeded) {
return fmt.Errorf("bloomberg: timeout: %w", context.DeadlineExceeded)
}
if errors.Is(ctx.Err(), context.Canceled) || errors.Is(err, context.Canceled) {
return fmt.Errorf("bloomberg: canceled: %w", context.Canceled)
}
var timeout interface{ Timeout() bool }
if errors.As(err, &timeout) && timeout.Timeout() {
return fmt.Errorf("bloomberg: timeout: %w", context.DeadlineExceeded)
}
return errors.New("bloomberg: transport failure")
}

View File

@ -0,0 +1,58 @@
package bloomberg
import (
"context"
"errors"
"io"
"net/http"
"net/url"
"strings"
"testing"
)
func TestTicket35AbsentContentIsEmptyAndScraperErrorsAreSanitized(t *testing.T) {
cases := []struct {
name, body string
status int
err error
want string
}{
{name: "success", status: 200, body: `{"articles":[{"title":"fixture title","url":"https://fixture.invalid/article"}]}`},
{name: "http", status: 503, body: "PRIVATE_BODY https://private.invalid", want: "HTTP 503"},
{name: "service", status: 200, body: `{"error":"PRIVATE_BODY https://private.invalid"}`, want: "scraper failure"},
{name: "transport", err: &url.Error{Op: "POST", URL: "https://PRIVATE_URL.invalid", Err: errors.New("PRIVATE_BODY")}, want: "transport failure"},
{name: "timeout", err: &url.Error{Op: "POST", URL: "https://PRIVATE_URL.invalid", Err: context.DeadlineExceeded}, want: "timeout"},
{name: "canceled", err: &url.Error{Op: "POST", URL: "https://PRIVATE_URL.invalid", Err: context.Canceled}, want: "canceled"},
{name: "json", status: 200, body: `{"PRIVATE_BODY":`, want: "invalid response"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
b := New("http://PRIVATE_URL.invalid")
b.client = &http.Client{Transport: dateTransport(func(*http.Request) (*http.Response, error) {
if tc.err != nil {
return nil, tc.err
}
return &http.Response{StatusCode: tc.status, Body: io.NopCloser(strings.NewReader(tc.body)), Header: make(http.Header)}, nil
})}
articles, err := b.ScrapeWithCredentials(context.Background(), "PRIVATE_USER", "PRIVATE_SECRET", nil)
if tc.want == "" {
if err != nil || len(articles) != 1 || articles[0].Content != "" || articles[0].PublishedAt != nil {
t.Fatal("invented content/date", err)
}
return
}
if err == nil || !strings.Contains(err.Error(), tc.want) || articles != nil {
t.Fatalf("unexpected result: %v", err)
}
if strings.Contains(err.Error(), "PRIVATE") || strings.Contains(err.Error(), "http://") || strings.Contains(err.Error(), "https://") {
t.Fatal("raw scraper error leaked")
}
if tc.name == "timeout" && !errors.Is(err, context.DeadlineExceeded) {
t.Fatal("timeout identity lost")
}
if tc.name == "canceled" && !errors.Is(err, context.Canceled) {
t.Fatal("cancellation identity lost")
}
})
}
}

View File

@ -85,9 +85,23 @@ Seuls la synthèse et les bilans agrégés existants sont persistés. Aucun arti
### Date de publication Bloomberg
Le service Node conserve ses mécanismes Byparr/Puppeteer et son extraction de liens/titres. Après collecte, il lit les métadonnées des pages d’articles via le même mécanisme pour remplir `published_at`. La priorité est `meta[name="iso-8601-publish-date"]`, puis `time[datetime]`, puis `datePublished` d’un objet JSON-LD de type Article/NewsArticle/ReportageNewsArticle (tableaux et `@graph` inclus). Seules des dates ISO complètes avec fuseau explicite et calendrier valide sont retenues ; une erreur d’accès, absence ou métadonnée invalide laisse `null`. Les nouvelles lectures de pages pour les dates ne journalisent ni URL, ni HTML, ni texte. Elles sont limitées aux URLs HTTPS d’articles Bloomberg, sans credentials ni port non standard ; les autres liens gardent une date nulle sans être visités.
Le ticket #35 supprime la revisite séquentielle des URLs d’articles ajoutée pour les dates. Le service Node conserve ses pages, mécanismes Byparr/Puppeteer, déduplication et filtres de liens/titres existants. Il ne charge **aucune page supplémentaire pour une date** : sept sections Byparr, ou login puis trois sections Puppeteer, comme auparavant.
L’adaptateur Go propage cette date après validation RFC3339 et n’utilise plus `time.Now()` comme date de publication. Un ancien service Node sans ce champ reste compatible, avec date nulle. Cette hydratation ajoute des lectures de pages et peut augmenter le temps de collecte ; aucune source réelle n’a été appelée pour la vérifier. Main a confirmé après inspection que les trois fichiers attachés exposent tous ces trois marqueurs : `meta[name="iso-8601-publish-date"]`, `time[datetime]` et `datePublished` JSON-LD. Les tests représentent ce contrat par trois snippets synthétiques contenant chacun les trois clés, plus les cas de fallback entre métadonnées invalides, sans reprendre le contenu ni l’identité des pages.
`published_at` est extrait uniquement du **HTML déjà chargé et associable à l’article** : métadonnées d’une page si son URL est précisément celle de l’article, `time[datetime]`/meta dans son lien ou un bloc `<article>` ne contenant qu’une seule identité de story, ou `datePublished` JSON-LD Article/NewsArticle dont `url`/`mainEntityOfPage` correspond exactement à cet article. Une date générale de section et les dates de blocs ambigus ne sont jamais distribuées aux liens. Les marqueurs confirmés dans les trois pages inspectées restent supportés : `meta[name="iso-8601-publish-date"]`, `time[datetime]`, `datePublished`. Les dates ISO complètes doivent avoir un fuseau et un calendrier valides. Un doublon observé sur une section déjà chargée peut compléter une date précédemment nulle, sans modifier l’ordre des articles.
Si le HTML chargé ne fournit pas de métadonnée associable, la date reste `null`, sans réseau de fallback. Cela peut réduire la couverture des dates par rapport à une visite de chaque article ; la règle source-level du ticket #34 conserve alors l’ordre reçu de la source, y compris dans un lot mixte. Les fixtures sont des snippets synthétiques d’attributs, non des articles ou pages identifiantes. Aucun coût ni disponibilité de source réelle n’a été mesuré.
Le DTO Node existant ne fournit pas de contenu d’article. L’adaptateur Go laisse donc `Article.Content` **vide**, au lieu d’y recopier le titre. Il ne remplace jamais une date absente par `time.Now()`. En mode titre+contenu, l’absence de contenu suit le diagnostic agrégé existant `content_fallback=title_only` ; aucun contenu complet n’est prétendu disponible. Les limites d’ingestion/parsing, les pools N et la sélection en trois passes ne sont pas étendus.
Les erreurs de transport, timeout, réponse HTTP, JSON et service du scraper sont rendues sous des catégories fixes, avec statut HTTP numérique quand disponible, sans URL, corps ni message brut. Les logs Node ne contiennent plus d’URL, titre de page, corps d’erreur ou détails de login. Une erreur exposée par la route reste générique. Les annulations/timeouts Go conservent uniquement leur identité typée standard, jamais le message du transport.
### Échecs de synthèse et budgets
`LAYA_TIMEOUT` garde son défaut **5m**, son override opérateur et sa borne 10m. Le contexte est partagé entre la sélection déterministe et tous les appels/lots directs et indirects, pas recréé par lot. Un échec invalide toute la sélection, y compris les acceptations antérieures ; aucune synthèse partielle ni fallback. La fin de ce contexte de sélection n’annule pas le contexte parent destiné à la synthèse.
Après sélection, le résultat d’échec utilise `summary_timeout` pour une échéance/timeout typé du fournisseur, `summary_canceled` pour une annulation typée, et `summary_failed` pour une autre erreur fournisseur ou une réponse vide. Aucun diagnostic brut n’est persisté dans le bilan ni ajouté aux logs. Claude CLI ne journalise plus stdout/stderr lors d’un échec et conserve l’identité d’une annulation/échéance de son contexte.
Si le contexte parent est lui-même expiré/annulé, seule l’écriture du **bilan terminal d’échec** dispose d’un contexte séparé borné à 10s, conservant l’identité du job pour la finalisation atomique existante. Cette écriture ne prolonge ni le travail fournisseur ni le classement et ne sauvegarde aucune synthèse partielle. Les autres erreurs de stockage restent traitées par le mécanisme existant des jobs.
### Diagnostics agrégés du classement

View File

@ -1,4 +1,4 @@
const { withPublicationDates } = require('./publication-date')
const { withDatesFromLoadedHtml } = require('./publication-date')
const express = require('express')
const cheerio = require('cheerio')
const puppeteer = require('puppeteer-extra')
@ -21,21 +21,24 @@ async function byparrRequest(body) {
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
if (!resp.ok) throw new Error(`byparr HTTP ${resp.status}: ${await resp.text()}`)
if (!resp.ok) {
try { await resp.body?.cancel() } catch { /* Release without reading/logging the body. */ }
throw new Error(`byparr HTTP ${resp.status}`)
}
return resp.json()
}
async function byparrFetch(url, quiet = false) {
if (!quiet) console.log('[byparr] GET', url)
if (!quiet) console.log('[byparr] section request')
const data = await byparrRequest({ cmd: 'request.get', url, maxTimeout: 60000 })
const html = data.solution?.response
if (!html) throw new Error(`byparr returned no HTML for ${url}`)
if (!html) throw new Error('byparr returned no HTML')
return { html }
}
// ---------- Article parsing ----------
function parseArticlesFromHtml(html) {
function parseArticlesFromHtml(html, loadedURL) {
const $ = cheerio.load(html)
const results = []
const seen = new Set()
@ -56,7 +59,7 @@ function parseArticlesFromHtml(html) {
results.push({ title, url: clean })
})
return results
return withDatesFromLoadedHtml(results, html, loadedURL, $)
}
// ---------- Bloomberg scraping via Byparr ----------
@ -81,20 +84,23 @@ async function scrapeBloombergViaByparr(username, password) {
for (const url of byparrPages) {
try {
const { html } = await byparrFetch(url)
const items = parseArticlesFromHtml(html)
const items = parseArticlesFromHtml(html, url)
for (const item of items) {
if (!seen.has(item.url)) {
seen.add(item.url)
articles.push(item)
} else if (item.published_at) {
const existing = articles.find(article => article.url === item.url)
if (existing && !existing.published_at) existing.published_at = item.published_at
}
}
console.log('[bloomberg]', url, '->', items.length, 'articles')
console.log('[bloomberg] section articles:', items.length)
} catch (e) {
console.error('[bloomberg] error on', url, ':', e.message)
console.error('[bloomberg] section unavailable')
}
}
return withPublicationDates(articles, async url => (await byparrFetch(url, true)).html)
return articles
}
// ---------- Bloomberg scraping via Puppeteer (fallback, may be blocked) ----------
@ -161,8 +167,8 @@ async function scrapeBloombergViaPuppeteer(username, password) {
type: i.type, name: i.name, id: i.id, placeholder: i.placeholder, visible: i.offsetParent !== null
}))
)
console.log('[bloomberg] inputs on login page:', JSON.stringify(pageInputs))
console.log('[bloomberg] page title:', await page.title())
console.log('[bloomberg] login input count:', pageInputs.length)
const emailOk = await tryType(page, [
'#email-form-input',
@ -194,7 +200,7 @@ async function scrapeBloombergViaPuppeteer(username, password) {
} catch {
await new Promise(r => setTimeout(r, 3000))
}
console.log('[bloomberg] after email submit, url:', page.url())
console.log('[bloomberg] email step completed')
const pwdOk = await tryType(page, [
'input[type="password"]',
@ -211,10 +217,9 @@ async function scrapeBloombergViaPuppeteer(username, password) {
])
const currentURL = page.url()
console.log('[bloomberg] after login, url:', currentURL)
console.log('[bloomberg] login navigation completed')
if (currentURL.includes('/account/signin')) {
const bodyText = await page.evaluate(() => document.body.innerText.slice(0, 500))
throw new Error(`login did not redirect — page content: ${bodyText}`)
throw new Error('login did not redirect')
}
const targetPages = [
@ -228,29 +233,29 @@ async function scrapeBloombergViaPuppeteer(username, password) {
for (const url of targetPages) {
try {
console.log('[bloomberg] scraping', url)
console.log('[bloomberg] loading section')
await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 30000 })
await page.waitForSelector('a[data-component="story-link"]', { timeout: 15000 }).catch(() => {})
const html = await page.content()
const items = parseArticlesFromHtml(html)
const items = parseArticlesFromHtml(html, url)
for (const item of items) {
if (!seen.has(item.url)) {
seen.add(item.url)
articles.push(item)
} else if (item.published_at) {
const existing = articles.find(article => article.url === item.url)
if (existing && !existing.published_at) existing.published_at = item.published_at
}
}
console.log('[bloomberg]', url, '->', items.length, 'articles')
console.log('[bloomberg] section articles:', items.length)
} catch (e) {
console.error('[bloomberg] error on', url, ':', e.message)
console.error('[bloomberg] section unavailable')
}
}
return await withPublicationDates(articles, async url => {
await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 30000 })
return page.content()
})
return articles
} finally {
if (browser) await browser.close()
}
@ -279,8 +284,8 @@ app.post('/bloomberg/scrape', async (req, res) => {
console.log('[bloomberg] total:', articles.length, 'articles')
res.json({ articles })
} catch (e) {
console.error('[bloomberg] scrape error:', e.message)
res.status(500).json({ error: e.message })
console.error('[bloomberg] scrape unavailable')
res.status(500).json({ error: 'scrape unavailable' })
}
})

View File

@ -58,14 +58,60 @@ function isArticleURL(value) {
} catch { return false }
}
async function withPublicationDates(articles, loadHtml) {
const result = []
for (const article of articles) {
let published_at = null
try { if (isArticleURL(article.url)) published_at = extractPublicationDate(await loadHtml(article.url)) } catch { /* Date stays unknown. */ }
result.push({ ...article, published_at })
// Only associate metadata with an article identified in this already-loaded
// document. Section-level publication dates must never be copied onto its links.
function withDatesFromLoadedHtml(articles, html, loadedURL, parsed) {
const $ = parsed || cheerio.load(html)
const dates = new Map()
function key(value) {
try {
if (typeof value !== 'string' || !value.trim()) return null
const url = new URL(value, loadedURL)
url.search = ''
url.hash = ''
return isArticleURL(url.href) ? url.href : null
} catch { return null }
}
return result
const wanted = new Set(articles.map(article => key(article.url)).filter(Boolean))
const pageKey = key(loadedURL)
if (pageKey && wanted.has(pageKey)) {
const date = extractPublicationDate(html)
if (date) dates.set(pageKey, date)
}
for (const anchor of $('a[data-component="story-link"]').toArray()) {
const articleKey = key($(anchor).attr('href'))
if (!articleKey || !wanted.has(articleKey) || dates.has(articleKey)) continue
let scope = $(anchor)
const card = scope.closest('article')
if (card.length) {
const links = new Set(card.find('a[data-component="story-link"]').toArray()
.map(link => key($(link).attr('href'))).filter(Boolean))
if (links.size === 1 && links.has(articleKey)) scope = card
}
for (const [selector, attribute] of [['meta[name="iso-8601-publish-date"]', 'content'], ['time[datetime]', 'datetime']]) {
for (const element of scope.find(selector).toArray()) {
const date = reliableISO($(element).attr(attribute))
if (date) { dates.set(articleKey, date); break }
}
if (dates.has(articleKey)) break
}
}
let visited = 0
function collect(node, depth = 0) {
if (!node || typeof node !== 'object' || depth > 32 || ++visited > 2000) return
const types = Array.isArray(node['@type']) ? node['@type'] : [node['@type']]
if (types.some(type => ['Article', 'NewsArticle', 'ReportageNewsArticle'].includes(type))) {
const identity = node.url || node.mainEntityOfPage
const articleKey = key(typeof identity === 'string' ? identity : identity?.['@id'])
const date = reliableISO(node.datePublished)
if (articleKey && wanted.has(articleKey) && !dates.has(articleKey) && date) dates.set(articleKey, date)
}
for (const child of Object.values(node)) collect(child, depth + 1)
}
for (const script of $('script[type="application/ld+json"]').toArray()) {
try { collect(JSON.parse($(script).text())) } catch { /* Unknown date, no raw metadata logging. */ }
}
return articles.map(article => ({ ...article, published_at: dates.get(key(article.url)) || null }))
}
module.exports = { extractPublicationDate, withPublicationDates }
module.exports = { extractPublicationDate, withDatesFromLoadedHtml }

View File

@ -1,6 +1,6 @@
const { test } = require('node:test')
const assert = require('node:assert/strict')
const { extractPublicationDate, withPublicationDates } = require('../publication-date')
const { extractPublicationDate, withDatesFromLoadedHtml } = require('../publication-date')
test('minimal metadata fixtures preserve genuine dates with explicit zones', () => {
assert.equal(extractPublicationDate('<meta name="iso-8601-publish-date" content="2026-01-02T03:04:05Z">'), '2026-01-02T03:04:05.000Z')
@ -12,27 +12,30 @@ test('invalid or missing metadata never manufactures a collection date', () => {
assert.equal(extractPublicationDate(html), null)
}
})
test('metadata priority and failed hydration retain order and nullable dates', async () => {
test('already-loaded section metadata is associated per article, never by page date', () => {
const a = { title: 'fixture-a', url: 'https://www.bloomberg.com/news/articles/fixture-a' }
const b = { title: 'fixture-b', url: 'https://www.bloomberg.com/news/articles/fixture-b' }
const seen = []
const result = await withPublicationDates([a, b], async url => {
seen.push(url)
if (url === b.url) throw new Error('fixture only')
return '<meta name="iso-8601-publish-date" content="2026-01-02T03:04:05Z"><time datetime="2026-01-03T00:00:00Z"></time>'
})
assert.deepEqual(seen, [a.url, b.url])
assert.equal(result[0].published_at, '2026-01-02T03:04:05.000Z')
assert.equal(result[1].published_at, null)
const c = { title: 'fixture-c', url: 'https://www.bloomberg.com/news/articles/fixture-c' }
const html = '<meta name="iso-8601-publish-date" content="2026-12-31T00:00:00Z">' +
'<article><a data-component="story-link" href="/news/articles/fixture-a"></a><time datetime="2026-01-02T03:04:05Z"></time></article>' +
'<script type="application/ld+json">{"@type":"NewsArticle","url":"https://www.bloomberg.com/news/articles/fixture-b","datePublished":"2026-02-03T04:05:06Z"}</script>'
const result = withDatesFromLoadedHtml([a, b, c], html, 'https://www.bloomberg.com/markets/stocks')
assert.deepEqual(result.map(article => article.url), [a.url, b.url, c.url])
assert.deepEqual(result.map(article => article.published_at), ['2026-01-02T03:04:05.000Z', '2026-02-03T04:05:06.000Z', null])
assert.equal(a.published_at, undefined)
})
test('date hydration never fetches unrelated hosts or non-article URLs', async () => {
let calls = 0
const urls = ['http://127.0.0.1/news/articles/x', 'https://other.invalid/news/articles/x', 'https://www.bloomberg.com@other.invalid/news/articles/x', 'https://www.bloomberg.com:8443/news/articles/x', 'https://www.bloomberg.com/markets']
const result = await withPublicationDates(urls.map(url => ({ url })), async () => { calls++; return '' })
assert.equal(calls, 0)
assert.ok(result.every(item => item.published_at === null))
test('ambiguous cards, invalid metadata and unrelated URLs remain date-null', () => {
const urls = ['https://www.bloomberg.com/news/articles/a', 'https://www.bloomberg.com/news/articles/b', 'http://127.0.0.1/news/articles/x', 'https://other.invalid/news/articles/x']
const html = '<article><a data-component="story-link" href="/news/articles/a"></a><a data-component="story-link" href="/news/articles/b"></a><time datetime="2026-01-02T03:04:05Z"></time></article>' +
'<script type="application/ld+json">{"@type":"NewsArticle","url":"http://127.0.0.1/news/articles/x","datePublished":"2026-01-02T03:04:05Z"}</script>'
const result = withDatesFromLoadedHtml(urls.map(url => ({ url })), html, 'https://www.bloomberg.com/markets')
assert.ok(result.every(article => article.published_at === null))
})
test('page-level publication metadata applies only to the already-loaded article', () => {
const urls = ['https://www.bloomberg.com/news/articles/a', 'https://www.bloomberg.com/news/articles/b']
const result = withDatesFromLoadedHtml(urls.map(url => ({ url })), '<meta name="iso-8601-publish-date" content="2026-01-02T03:04:05Z">', urls[0])
assert.equal(result[0].published_at, '2026-01-02T03:04:05.000Z')
assert.equal(result[1].published_at, null)
})
test('the three observed page shapes expose all publication metadata keys', () => {

View File

@ -0,0 +1,96 @@
const { test } = require('node:test')
const assert = require('node:assert/strict')
const fs = require('node:fs')
const vm = require('node:vm')
const { createRequire } = require('node:module')
const path = require('node:path')
const dated = '<article><a data-component="story-link" href="/news/articles/fixture-a"><div data-testid="headline"><span>Synthetic fixture headline</span></div></a><time datetime="2026-01-02T03:04:05Z"></time></article>'
const undated = dated.replace('<time datetime="2026-01-02T03:04:05Z"></time>', '')
// Exercise actual collection/route code with fake transports, browser and timers.
// No server, browser process or source network request is started.
async function runFixture ({ byparr = true, httpError = false, launchError = false } = {}) {
const route = {}
const calls = []
const navigations = []
const logs = []
let bodyReads = 0
let contents = 0
let result
let status = 200
let closed = false
const app = { use () {}, get () {}, post (name, handler) { route[name] = handler }, listen () {} }
const express = () => app
express.json = () => () => {}
const index = path.resolve(__dirname, '../index.js')
const localRequire = createRequire(index)
const page = {
async setViewport () {}, async evaluateOnNewDocument () {},
async goto (url) { navigations.push(url) },
async evaluate () { return true }, async waitForSelector () {}, async type () {},
async waitForFunction () {}, async waitForNavigation () {}, async $ () { return null },
keyboard: { async press () {} },
url () { return 'https://www.bloomberg.com/markets' },
async content () { return contents++ === 0 ? undated : dated }
}
const browser = { async newPage () { return page }, async close () { closed = true } }
vm.runInNewContext(fs.readFileSync(index, 'utf8'), {
require (name) {
if (name === 'express') return express
if (name === 'puppeteer-extra') return {
use () {},
async launch () {
if (launchError) throw new Error('PRIVATE_BODY https://PRIVATE_URL.invalid')
return browser
}
}
if (name === 'puppeteer-extra-plugin-stealth') return () => ({})
return localRequire(name)
},
process: { env: { BYPARR_URL: byparr ? 'http://fixture.invalid' : '' } },
setTimeout (callback) { queueMicrotask(callback) },
console: { log (...args) { logs.push(args.join(' ')) }, error (...args) { logs.push(args.join(' ')) } },
async fetch (_url, options) {
const requested = JSON.parse(options.body).url
calls.push(requested)
return {
ok: !httpError, status: httpError ? 503 : 200,
async text () { bodyReads++; return 'PRIVATE_BODY https://PRIVATE_URL.invalid' },
async json () { return { solution: { response: calls.length === 1 ? undated : dated } } }
}
}
})
await route['/bloomberg/scrape']({ body: { username: 'PRIVATE_USER', password: 'PRIVATE_SECRET' } }, {
json (body) { result = body }, status (code) { status = code; return this }
})
return { result, status, calls, navigations, logs, bodyReads, closed }
}
test('Byparr loads only seven existing sections and enriches a repeated link in place', async () => {
const { result, calls, logs } = await runFixture()
assert.equal(calls.length, 7)
assert.ok(calls.every(url => !url.includes('/news/articles/')))
assert.equal(result.articles.length, 1)
assert.equal(result.articles[0].published_at, '2026-01-02T03:04:05.000Z')
assert.ok(logs.every(line => !line.includes('http') && !line.includes('Synthetic fixture headline')))
})
test('Puppeteer loads only login and three existing sections, no article revisits', async () => {
const { result, navigations, calls, closed, logs } = await runFixture({ byparr: false })
assert.equal(navigations.length, 4)
assert.ok(navigations.every(url => !url.includes('/news/articles/')))
assert.equal(calls.length, 0)
assert.equal(result.articles.length, 1)
assert.equal(result.articles[0].published_at, '2026-01-02T03:04:05.000Z')
assert.equal(closed, true)
assert.ok(logs.every(line => !line.includes('http') && !line.includes('PRIVATE')))
})
test('scraper failures never expose response bodies, URLs or credentials', async () => {
const http = await runFixture({ httpError: true })
assert.equal(http.bodyReads, 0)
assert.ok(http.logs.every(line => !line.includes('http') && !line.includes('PRIVATE')))
const browser = await runFixture({ byparr: false, launchError: true })
assert.equal(browser.status, 500)
assert.equal(browser.result.error, 'scrape unavailable')
assert.ok(browser.logs.every(line => !line.includes('http') && !line.includes('PRIVATE')))
})