Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion backend/src/modules/admin/scrapers/scrapers.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ export const ScraperStatusSchema = z.object({
lastRun: z.object({
runId: z.string(),
providers: z.array(z.string()).nullable().optional(),
status: z.enum(["success", "partial", "failed", "timeout", "canceled"]),
status: z.enum(["success", "partial", "partial_success", "failed", "timeout", "canceled"]),
finishedAt: z.string().datetime(),
jobsSaved: z.number().int().nonnegative(),
jobsIndexed: z.number().int().nonnegative(),
Expand Down
33 changes: 33 additions & 0 deletions backend/tests/unit/modules/admin/scraperResult.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,36 @@ it("retains partial execution counts and accepts an empty initial history", () =
expect(result.lastRun?.status).toBe("partial");
expect(result.lastRun?.jobsIndexed).toBe(210);
});

it.each(["success", "partial", "partial_success", "failed", "timeout", "canceled"] as const)(
"preserva o status %s e os contadores retornados pelo Go",
(status) => {
const payload = {
running: false,
lastRun: {
runId: "fixture-operational-result",
providers: ["greenhouse"],
status,
finishedAt: "2026-11-12T20:00:00Z",
jobsSaved: 210,
jobsIndexed: 209,
errorType: status === "partial" ? "timeout" : "",
},
};
expect(ScraperStatusSchema.parse(payload)).toEqual(payload);
},
);

it("continua rejeitando status desconhecido no resultado da coleta", () => {
expect(ScraperStatusSchema.safeParse({
running: false,
lastRun: {
runId: "fixture-invalid-result",
status: "unknown",
finishedAt: "2026-11-12T20:00:00Z",
jobsSaved: 0,
jobsIndexed: 0,
errorType: "",
},
}).success).toBe(false);
});
36 changes: 36 additions & 0 deletions backend/tests/unit/modules/admin/scrapers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,42 @@ describe("scraperClient", () => {
vi.restoreAllMocks();
});

it.each(["partial", "partial_success"] as const)(
"preserva %s na resposta Go e permite listar o scraper",
async (status) => {
const payload = {
name: "go-scraper",
running: false,
lastRunAt: "2026-11-12T20:00:00Z",
jobsCollected: 210,
lastRun: {
runId: "fixture-partial-run",
providers: ["greenhouse"],
status,
finishedAt: "2026-11-12T20:00:00Z",
jobsSaved: 210,
jobsIndexed: 209,
errorType: "",
},
};
vi.stubGlobal("fetch", vi.fn().mockImplementation(async (input: string | URL | Request) => ({
ok: true,
status: 200,
json: async () => String(input).includes("/admin/jobs/count") ? { total: 210 } : payload,
})));

await expect(scraperClient.getStatus()).resolves.toEqual(payload);
await expect(new ScrapersService().listScrapers()).resolves.toEqual([{
name: "go-scraper",
status: "idle",
running: false,
lastRunAt: payload.lastRunAt,
jobsCollected: 210,
}]);
},
);


it("calls trigger endpoint and returns json", async () => {
vi.stubGlobal(
"fetch",
Expand Down
17 changes: 17 additions & 0 deletions docs/scraper-greenhouse-cinco-janelas.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Greenhouse em cinco janelas

Manifesto greenhouse-v2: 3339 boards preservados do v1, sem remoções ou duplicações. A redistribuição preserva a ordem anterior e divide a sequência em 668/668/668/668/667.

| Grupo | America/Sao_Paulo | Adapters |
|---|---|---:|
| greenhouse-1 | 00h–01h | 668 |
| greenhouse-2 | 06h–07h | 668 |
| greenhouse-3 | 11h–12h | 668 |
| greenhouse-4 | 17h–18h | 668 |
| greenhouse-5 | 21h–22h | 667 |

As outras 17 janelas permanecem intactas, incluindo Jooble 20h–21h. 22h–00h permanece livre. O preset usa grupos fixos; chamadas manuais e configuração customizada mantêm o seletor anterior.

SCRAPER_GREENHOUSE_WINDOW_MAX_ADAPTERS tem padrão 680 e é independente do tamanho efetivo dos grupos. Um limite menor que algum grupo impede a execução, sem truncamento.

Migração: o hash canônico é fixado sob uma chave versionada greenhouse-v2 com fencing pelo lock global. O pin imutável v1 permanece preservado. Claims de ocorrência diários mantêm as mesmas chaves e TTL de 48h: uma ocorrência já consumida não é reexecutada com a nova versão. Não se reaproveita o checkpoint rotativo manual nos grupos fixos. Em uma troca no meio do dia, a cobertura integral da nova distribuição começa no dia seguinte; não se força replay das janelas anteriores. Nenhuma chave/dado existente é apagado.
18 changes: 18 additions & 0 deletions docs/scraper-resultado-operacional.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Resultado operacional da coleta

`collection: N task(s) failed` era produzido em `pipeline.ScrapeAllSources`, depois de drenar os jobs, e propagado pelo cronjob como falha terminal. A política agora retorna `partial_success` sem erro terminal quando pelo menos `SCRAPER_MIN_SUCCESS_PERCENT` (padrão 50, intervalo 1–100) dos adapters selecionados concluíram todas as suas tarefas sem erro. O denominador inclui os não despachados. Tarefa com jobs e erro continua falhando, mas seus jobs são processados.

Erros de processamento, cancelamento, lock e deadline do ciclo continuam fatais. Timeout local do adapter é falha individual; não implica deadline do ciclo. O relatório final contém resultado técnico da coleta e resultado operacional, e é emitido depois da tentativa de liberar o lock, inclusive em falhas anteriores à coleta. `LastRun.Status` usa success/partial_success/failed; o motivo original permanece no relatório. As métricas legadas mantêm seu contrato técnico.

Contadores têm unidades distintas:

- Adapters: sucesso exige conclusão de todas as tarefas, sem qualquer erro. Falhas, timeouts e cancelamentos são categorias exclusivas, nessa prioridade: cancelamento, timeout, outros erros. Uma falha pode gerar vários diagnósticos por tarefa.
- `tasksCanceled` legado inclui tarefas com timeout. Por isso 2 timeouts podem produzir tasksCanceled=2 e cancelled=0 no resumo do provider. O relatório separa TaskTimeouts e TaskCancellations.
- `Saved()`/PersistedOperations = Inserted + Updated: operações de upsert, inclusive merges tardios de duplicatas já gravadas. PersistedDocuments conta os documentos aprovados distintos retornados pelo processamento.
- Indexed conta entradas concluídas, inclusive skips idempotentes. O buffer pode consolidar várias gravações do mesmo documento. Portanto saved=5720 e indexed=5719 não demonstram perda de índice por si só. Sem o log original não se atribui uma causa específica ao benchmark.
- IndexPending conta o buffer ainda aguardando indexação; IndexUnconfirmedInputs conta entradas de chamadas que falharam, descontando reconciliações confirmadas. Não se calcula pendência por saved-indexed. PersistencePending conta itens ainda no buffer de classificação/persistência; falhas de batches são informadas separadamente. Esses buffers não representam uma auditoria do backlog durável global.
- Received mede entradas consumidas pelo processamento antes de falha terminal; Collected mede jobs entregues pelos adapters ao coordenador, inclusive depois de uma falha de processamento.

Diagnóstico preserva o texto original, board estável, timeout, DNS e conexão tipados; códigos HTTP só são classificados com evidência explícita. Unknown continua unknown.

Validação rápida: fixtures determinísticas em pipeline e cronjob, sem chamadas à API; os testes existentes de recuperação cobrem falhas de persistência/indexação, deadline e drain.
1 change: 1 addition & 0 deletions scraper-go/cmd/server/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ func searchConfigFromRuntime(
WaitBetweenSearchesMs: req.WaitBetweenSearchesMs,
PageTimeoutMs: req.PageTimeoutMs,
MaxConcurrency: config.ResolveEffectiveConcurrency(req.MaxConcurrency, runtimeCfg.MaxConcurrency),
MinSuccessPercent: runtimeCfg.MinSuccessPercent,
ProviderMaxConcurrency: min(runtimeCfg.ProviderMaxConcurrency, config.ResolveEffectiveConcurrency(req.MaxConcurrency, runtimeCfg.MaxConcurrency)),
ProviderConcurrencyOverrides: runtimeCfg.ProviderConcurrencyOverrides,
ClassificationBatchSize: runtimeCfg.ClassificationBatchSize,
Expand Down
2 changes: 2 additions & 0 deletions scraper-go/cmd/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,8 @@ func run(adapterList []ports.JobSource, runtimeCfg config.RuntimeConfig) {

schedulerCfg.ScrapeTimeout = runtimeCfg.ScrapeTimeout
schedulerCfg.ProviderWindows = runtimeCfg.ProviderWindows
schedulerCfg.MinSuccessPercent = runtimeCfg.MinSuccessPercent
schedulerCfg.GreenhouseWindowMaxAdapters = runtimeCfg.GreenhouseWindowMaxAdapters
schedulerCfg.GreenhouseBatchSize = runtimeCfg.GreenhouseBatchSize

schedulerCfg.MaxConcurrency = runtimeCfg.MaxConcurrency
Expand Down
10 changes: 10 additions & 0 deletions scraper-go/internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ const (
)

type RuntimeConfig struct {
GreenhouseWindowMaxAdapters int
MinSuccessPercent int
ProviderWindows []ProviderWindow
GreenhouseBatchSize int
ScrapeTimeout time.Duration
Expand Down Expand Up @@ -127,6 +129,14 @@ func LoadRuntimeConfigFromLookup(lookup func(string) (string, bool)) (RuntimeCon
return RuntimeConfig{}, err
}
}
cfg.MinSuccessPercent, err = boundedPositiveIntFromLookup(lookup, "SCRAPER_MIN_SUCCESS_PERCENT", 50, 100)
if err != nil {
return RuntimeConfig{}, err
}
cfg.GreenhouseWindowMaxAdapters, err = boundedPositiveIntFromLookup(lookup, "SCRAPER_GREENHOUSE_WINDOW_MAX_ADAPTERS", 680, 1000)
if err != nil {
return RuntimeConfig{}, err
}
cfg.GreenhouseBatchSize, err = boundedPositiveIntFromLookup(lookup, "SCRAPER_GREENHOUSE_BATCH_SIZE", 1000, 1000)
if err != nil {
return RuntimeConfig{}, err
Expand Down
1 change: 1 addition & 0 deletions scraper-go/internal/config/provider_schedule.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ func ParseProviderWindowsInTimezone(value, timezone string) ([]ProviderWindow, e
"linkedin-3@linkedin=16:00-17:00", "greenhouse-4@greenhouse=17:00-18:00",
"gupy-4@gupy=18:00-19:00", "inhire-4@inhire=19:00-20:00",
"jooble-1@jooble=20:00-21:00",
"greenhouse-5@greenhouse=21:00-22:00",
}, ",")
}
if timezone == "" {
Expand Down
8 changes: 4 additions & 4 deletions scraper-go/internal/config/provider_schedule_p0_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,13 @@ import (
"github.com/stretchr/testify/require"
)

func TestProviderSchedulePresetHas21IndependentWindows(t *testing.T) {
func TestProviderSchedulePresetHas22IndependentWindows(t *testing.T) {
windows, err := ParseProviderWindows(ProviderSchedulePreset)
require.NoError(t, err)
require.Len(t, windows, 21)
require.Len(t, windows, 22)
counts := map[string]int{}
ids := map[string]bool{}
expected := []string{"greenhouse", "gupy", "inhire", "linkedin", "adzuna", "lever", "greenhouse", "gupy", "inhire", "linkedin", "themuse", "greenhouse", "gupy", "inhire", "adzuna", "lever", "linkedin", "greenhouse", "gupy", "inhire", "jooble"}
expected := []string{"greenhouse", "gupy", "inhire", "linkedin", "adzuna", "lever", "greenhouse", "gupy", "inhire", "linkedin", "themuse", "greenhouse", "gupy", "inhire", "adzuna", "lever", "linkedin", "greenhouse", "gupy", "inhire", "jooble", "greenhouse"}
for i, w := range windows {
require.Equal(t, expected[i], string(w.Provider))
require.Equal(t, i*60, w.Start)
Expand All @@ -26,7 +26,7 @@ func TestProviderSchedulePresetHas21IndependentWindows(t *testing.T) {
ids[w.WindowID()] = true
counts[string(w.Provider)]++
}
require.Equal(t, map[string]int{"greenhouse": 4, "gupy": 4, "inhire": 4, "linkedin": 3, "adzuna": 2, "lever": 2, "themuse": 1, "jooble": 1}, counts)
require.Equal(t, map[string]int{"greenhouse": 5, "gupy": 4, "inhire": 4, "linkedin": 3, "adzuna": 2, "lever": 2, "themuse": 1, "jooble": 1}, counts)
values := map[string]string{ProviderWindowsEnv: ProviderSchedulePreset}
cfg, err := LoadRuntimeConfigFromLookup(func(k string) (string, bool) { v, ok := values[k]; return v, ok })
require.NoError(t, err)
Expand Down
2 changes: 1 addition & 1 deletion scraper-go/internal/cronjob/collection_timeout_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ func TestCollectionTimeoutPersistsPartialJobsBeforeReleasingGlobalLock(t *testin
require.False(t, scheduler.IsRunning())
summary := scheduler.LastRun()
require.NotNil(t, summary)
require.Equal(t, "partial", summary.Status)
require.Equal(t, "failed", summary.Status)
require.Positive(t, summary.JobsSaved)
require.Positive(t, summary.JobsIndexed)
_, lastRunAt, jobs := scheduler.Snapshot()
Expand Down
22 changes: 19 additions & 3 deletions scraper-go/internal/cronjob/cronjob.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ import (
)

type Config struct {
GreenhouseWindowMaxAdapters int
MinSuccessPercent int
ProviderWindows []config.ProviderWindow
GreenhouseBatchSize int
Interval time.Duration
Expand Down Expand Up @@ -256,7 +258,9 @@ func (s *Scheduler) runSelectedWithLease(lease *runlock.Lease, sources []string,

func (s *Scheduler) runSelectedWindowWithLease(lease *runlock.Lease, sources []string, timeout time.Duration, window *config.ProviderWindow) (runErr error) {
var stats pipeline.ProcessStats
started := time.Now()
defer func() {
pipeline.EmitReport(lease.RunID(), sources, windowID(window), started, timeout, s.cfg.MaxConcurrency, stats, runErr)
s.recordResult(lease.RunID(), stats, runErr, sources)
metrics.FinishRun(runErr, lease.RunID())
}()
Expand Down Expand Up @@ -394,10 +398,14 @@ type RunSummary struct {
}

func (s *Scheduler) recordResult(runID string, stats pipeline.ProcessStats, err error, sources []string) {
status := metrics.Status(err)
if err != nil && stats.Saved() > 0 {
status = "partial"
status := stats.OperationalStatus
if status == "" {
status = "success"
}
if err != nil {
status = "failed"
}

now := time.Now().UTC()
s.mu.Lock()
defer s.mu.Unlock()
Expand All @@ -418,6 +426,7 @@ func (s *Scheduler) LastRun() *RunSummary {

func (s *Scheduler) searchConfig(kws []string, runID string) pipeline.SearchConfig {
return pipeline.SearchConfig{
MinSuccessPercent: s.cfg.MinSuccessPercent,
CollectionTimeout: s.cfg.ScrapeTimeout,
Store: s.jobStore,
Keywords: kws,
Expand Down Expand Up @@ -447,3 +456,10 @@ var (
ErrLockUnavailable = runlock.ErrUnavailable
ErrLockLost = runlock.ErrLost
)

func windowID(w *config.ProviderWindow) string {
if w == nil {
return ""
}
return w.WindowID()
}
18 changes: 15 additions & 3 deletions scraper-go/internal/cronjob/greenhouse_manifest.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import (
// every retained board's group; never regenerate all groups from a new sort.
// A version already pinned in Valkey is immutable, including across replicas.
//
//go:embed greenhouse_manifest_v1.json
//go:embed greenhouse_manifest_v2.json
var greenhouseManifestJSON []byte

type greenhouseManifest struct {
Expand All @@ -34,11 +34,11 @@ func parseGreenhouseManifest(data []byte) (greenhouseManifest, string, error) {
if err := json.Unmarshal(data, &m); err != nil {
return m, "", fmt.Errorf("greenhouse manifest: %w", err)
}
if !strings.HasPrefix(m.Version, "greenhouse-v") || len(m.Version) <= len("greenhouse-v") || len(m.Groups) != 4 {
if !strings.HasPrefix(m.Version, "greenhouse-v") || len(m.Version) <= len("greenhouse-v") || len(m.Groups) != 5 {
return m, "", fmt.Errorf("invalid greenhouse manifest version/groups")
}
seen := map[string]bool{}
for i := 1; i <= 4; i++ {
for i := 1; i <= 5; i++ {
group, ok := m.Groups[fmt.Sprintf("greenhouse-%d", i)]
if !ok {
return m, "", fmt.Errorf("missing greenhouse group %d", i)
Expand Down Expand Up @@ -113,6 +113,18 @@ func (s *Scheduler) greenhouseFixedBatch(ctx context.Context, lease *runlock.Lea
if err != nil {
return nil, err
}
limit := s.cfg.GreenhouseWindowMaxAdapters
if limit == 0 {
limit = 680
}
if limit < 1 {
return nil, fmt.Errorf("greenhouse window maximum must be positive")
}
for group, ids := range manifest.Groups {
if len(ids) > limit {
return nil, fmt.Errorf("greenhouse group %s has %d adapters, maximum %d", group, len(ids), limit)
}
}
batch, err := manifest.selectGroup(s.adapterList, windowID)
if err != nil {
return nil, err
Expand Down
Loading
Loading