Skip to content

Fix/etl memory and weight validation v2#2383

Merged
andrew-bierman merged 8 commits into
mainfrom
fix/etl-memory-and-weight-validation-v2
May 7, 2026
Merged

Fix/etl memory and weight validation v2#2383
andrew-bierman merged 8 commits into
mainfrom
fix/etl-memory-and-weight-validation-v2

Conversation

@andrew-bierman
Copy link
Copy Markdown
Collaborator

@andrew-bierman andrew-bierman commented May 7, 2026

Description

Closes #

Type of change

  • 🐛 Bug fix
  • ✨ New feature
  • ♻️ Refactor / code improvement
  • 📝 Documentation update
  • 🔧 CI / configuration change
  • ⬆️ Dependency update
  • 🗄️ Database migration

Area(s) affected

  • Mobile app (apps/expo)
  • API / Backend (packages/api)
  • Landing page (apps/landing)
  • Guides site (apps/guides)
  • CI / CD (.github/)

Testing

  • Added / updated unit tests
  • Manually tested on iOS
  • Manually tested on Android
  • Manually tested on Web
  • API endpoints verified (e.g. curl or Postman)

Screenshots / recordings

Pre-merge checklist

  • bun format && bun lint passes with no errors
  • bun check-types passes with no errors
  • No new secrets or credentials are committed
  • Database migration included (if schema changed)
  • Feature flag added (if this is a new feature)
  • PR title follows conventional commits (feat:, fix:, chore:, etc.)

…files

Replace end-of-stream single flush with per-BATCH_SIZE flushes during the
CSV parse loop. Valid and invalid item batches are written to DB every 100
rows, arrays are cleared, and totalProcessed is updated incrementally so
progress is visible on long-running jobs. Remaining rows are flushed after
the loop as before.

Fixes evo (174K rows) and gearx (166K rows) jobs stuck in 'running' forever.
Clothing and footwear brands (kuhl, obozfootwear, prana) routinely omit
weight data, causing 0% ingest rates. Weight is important for comparisons
but it is better to ingest items without it than to reject them entirely.
Items missing weight are stored as-is and simply excluded from weight views.

Weight and weightUnit remain nullable at the DB layer (no schema change).
The ON CONFLICT DO UPDATE SET clause was using COALESCE(table.field, excluded.field)
which means existing non-null values could never be corrected by a fresh scrape.
Changed to excluded.field directly so re-scraping always wins, allowing price,
weight, availability, and other fields to be corrected when the source data changes.

Exception: created_at retains COALESCE so the original creation timestamp is
preserved across upserts.
…state

Manually runnable script that fails any ETL job that has been in 'running'
status for more than 30 minutes. Addresses jobs left stuck when the Worker
crashes mid-stream (e.g. OOM) without reaching the error handler.
Protect against scrapers returning weight=0 or weight<0 overwriting
valid existing weight data. Weight and weight_unit now only update when
the incoming value is a positive number; otherwise the stored value is
preserved. All other fields continue to accept the fresh scraped value
so stale data can still be corrected by re-scraping.
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 7, 2026

Warning

Rate limit exceeded

@andrew-bierman has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 17 minutes and 8 seconds before requesting another review.

To continue reviewing without waiting, purchase usage credits in the billing tab.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 2f4f8a8c-548b-4f5d-88e3-f2256cc31add

📥 Commits

Reviewing files that changed from the base of the PR and between 9cbd0c6 and 4007975.

📒 Files selected for processing (7)
  • apps/expo/app/(app)/current-pack/[id].tsx
  • apps/expo/app/(app)/recent-packs.tsx
  • packages/api/scripts/reset-stuck-etl-jobs.sql
  • packages/api/src/services/catalogService.ts
  • packages/api/src/services/etl/CatalogItemValidator.ts
  • packages/api/src/services/etl/processCatalogEtl.ts
  • tsconfig.json

Warning

.coderabbit.yaml has a parsing error

The CodeRabbit configuration file in this repository has a parsing error and default settings were used instead. Please fix the error(s) in the configuration file. You can initialize chat with CodeRabbit to get help with the configuration file.

💥 Parsing errors (1)
Validation error: String must contain at most 250 character(s) at "tone_instructions"
⚙️ Configuration instructions
  • Please see the configuration documentation for more information.
  • You can also validate your configuration using the online YAML validator.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/etl-memory-and-weight-validation-v2

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@github-actions github-actions Bot added the api label May 7, 2026
@github-actions
Copy link
Copy Markdown
Contributor

github-actions Bot commented May 7, 2026

Coverage Report for Expo Unit Tests Coverage (./apps/expo)

Status Category Percentage Covered / Total
🔵 Lines 81.65% 534 / 654
🔵 Statements 81.65% (🎯 75%) 534 / 654
🔵 Functions 92.98% 53 / 57
🔵 Branches 90.13% 201 / 223
File CoverageNo changed files found.
Generated in workflow #1083 for commit 4007975 by the Vitest Coverage Report Action

@github-actions
Copy link
Copy Markdown
Contributor

github-actions Bot commented May 7, 2026

Coverage Report for API Unit Tests Coverage (./packages/api)

Status Category Percentage Covered / Total
🔵 Lines 75.74% 609 / 804
🔵 Statements 75.74% (🎯 65%) 609 / 804
🔵 Functions 95.91% 47 / 49
🔵 Branches 88.23% 270 / 306
File CoverageNo changed files found.
Generated in workflow #1083 for commit 4007975 by the Vitest Coverage Report Action

@github-actions github-actions Bot added the mobile label May 7, 2026
@andrew-bierman andrew-bierman marked this pull request as ready for review May 7, 2026 18:06
Copilot AI review requested due to automatic review settings May 7, 2026 18:06
@andrew-bierman andrew-bierman merged commit c1f2b9a into main May 7, 2026
9 checks passed
@andrew-bierman andrew-bierman deleted the fix/etl-memory-and-weight-validation-v2 branch May 7, 2026 18:12
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR aims to improve catalog ETL robustness (memory usage + weight handling) and adjust downstream catalog upsert behavior to better handle missing/invalid weight data.

Changes:

  • Flush ETL valid/invalid batches to the DB during streaming to reduce worker memory pressure.
  • Make catalog ETL validation treat weight / weightUnit as optional and adjust upsert conflict behavior (notably around weight fields).
  • Misc: add a SQL script to fail “stuck” ETL jobs; adjust Expo UI callsites to compile by casting t to any; tweak root TS config.

Reviewed changes

Copilot reviewed 6 out of 7 changed files in this pull request and generated 6 comments.

Show a summary per file
File Description
tsconfig.json Adjusts TS compiler options (removes baseUrl, changes ignoreDeprecations).
packages/api/src/services/etl/processCatalogEtl.ts Streams CSV rows and flushes valid/invalid batches periodically to avoid OOM.
packages/api/src/services/etl/CatalogItemValidator.ts Changes ETL validation to no longer require weight / weightUnit.
packages/api/src/services/catalogService.ts Modifies catalog item upsert conflict-update behavior, including special handling for weight fields.
packages/api/scripts/reset-stuck-etl-jobs.sql Adds a manual script to mark long-running ETL jobs as failed.
apps/expo/app/(app)/recent-packs.tsx Casts t to any when calling getRelativeTime.
apps/expo/app/(app)/current-pack/[id].tsx Casts t to any when calling getRelativeTime.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +111 to +141
// Flush valid batch to DB every BATCH_SIZE rows to avoid Worker OOM on large files
if (validItemsBatch.length >= BATCH_SIZE) {
await processValidItemsBatch({ jobId, items: [...validItemsBatch], env });
await db
.update(etlJobs)
.set({ totalProcessed: sql`COALESCE(${etlJobs.totalProcessed}, 0) + ${BATCH_SIZE}` })
.where(eq(etlJobs.id, jobId));
validItemsBatch.length = 0;
}
// Flush invalid batch to DB every BATCH_SIZE rows
if (invalidItemsBatch.length >= BATCH_SIZE) {
await processLogsBatch({ jobId, logs: [...invalidItemsBatch], env });
await db
.update(etlJobs)
.set({ totalProcessed: sql`COALESCE(${etlJobs.totalProcessed}, 0) + ${BATCH_SIZE}` })
.where(eq(etlJobs.id, jobId));
invalidItemsBatch.length = 0;
}
}

console.log(`🔍 [TRACE] Streaming complete - processing batches`);
console.log(`🔍 [TRACE] Streaming complete - processing remaining batches`);

const itemsProcessed = validItemsBatch.length + invalidItemsBatch.length;
// Flush remaining items after the stream ends
const remainingItems = validItemsBatch.length + invalidItemsBatch.length;

await db
.update(etlJobs)
.set({ totalProcessed: sql`COALESCE(${etlJobs.totalProcessed}, 0) + ${itemsProcessed}` })
.where(eq(etlJobs.id, jobId));
if (remainingItems > 0) {
await db
.update(etlJobs)
.set({ totalProcessed: sql`COALESCE(${etlJobs.totalProcessed}, 0) + ${remainingItems}` })
.where(eq(etlJobs.id, jobId));
}
acc[col.name] =
sql`CASE WHEN excluded.${sql.identifier('weight')} IS NOT NULL AND excluded.${sql.identifier('weight')} > 0 THEN excluded.${sql.identifier('weight_unit')} ELSE COALESCE(${catalogItems.weightUnit}, excluded.${sql.identifier('weight_unit')}) END`;
} else {
acc[col.name] = sql`excluded.${sql.identifier(col.name)}`;
Comment on lines +352 to +356
sql`CASE WHEN excluded.${sql.identifier('weight')} IS NOT NULL AND excluded.${sql.identifier('weight')} > 0 THEN excluded.${sql.identifier('weight')} ELSE COALESCE(${catalogItems.weight}, excluded.${sql.identifier('weight')}) END`;
} else if (col.name === 'weight_unit') {
// weight_unit stays in sync with weight validity
acc[col.name] =
sql`CASE WHEN excluded.${sql.identifier('weight')} IS NOT NULL AND excluded.${sql.identifier('weight')} > 0 THEN excluded.${sql.identifier('weight_unit')} ELSE COALESCE(${catalogItems.weightUnit}, excluded.${sql.identifier('weight_unit')}) END`;
Comment on lines 36 to 49
@@ -45,7 +45,7 @@ function RecentPackCard({ pack }: { pack: Pack }) {
</View>
<Text variant="caption1" className="text-muted-foreground">
{t('packs.lastUpdated', {
time: getRelativeTime(pack.localUpdatedAt ?? pack.updatedAt, t),
time: getRelativeTime(pack.localUpdatedAt ?? pack.updatedAt, t as any),
})}
Comment on lines 156 to 159
<Text variant="subhead" className="mt-1 text-muted-foreground">
{t('packs.lastUpdated', {
time: getRelativeTime(pack.localUpdatedAt ?? pack.updatedAt, t),
time: getRelativeTime(pack.localUpdatedAt ?? pack.updatedAt, t as any),
})}
Comment on lines 34 to +36
// Additional validations
// Note: weight and weightUnit are intentionally not required — clothing/footwear brands often
// omit weight data. Items without weight are ingested but won't appear in weight comparisons.
andrew-bierman added a commit that referenced this pull request May 14, 2026
…lidation-v2

Fix/etl memory and weight validation v2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants