Leakage-Free Trailing Seven-Day Feature Counts for Each Label Event

Last updated: November 29, 2026

Quick Overview

For a churn or click model, you have label events (user_id, label_ts) and an activity log (user_id, event_ts, event_type). For each label row, compute the number of events of each type in the 7 days strictly before label_ts, without a full user-level cross join.

Meta
Data Manipulation (SQL/Python)
Machine Learning Engineer
Meta
November 29, 2026
Machine Learning Engineer
Onsite
Data Manipulation (SQL/Python)
Hard

0

0

0 solved


For a churn or click model, you have label events (user_id, label_ts) and an activity log (user_id, event_ts, event_type). For each label row, compute the number of events of each type in the 7 days strictly before label_ts, without a full user-level cross join.

Meta ML engineers build training data where features must reflect only what was known at prediction time. This onsite question tests point-in-time correctness (strict inequalities, no future events) and an efficient pandas implementation, since a merge on user_id then filter explodes for heavy users with millions of events.

What the Interviewer Expects
  • State the window precisely as [label_ts - 7d, label_ts)
  • Explain why merge-then-filter is quadratic per user
  • Use cumulative counts plus two as-of lookups to get window counts in O(n log n)
  • Use allow_exact_matches=False to exclude events at label_ts
  • Preserve the original label rows and order
Key Topics to Cover
point-in-time correctness
merge_asof
cumulative counts
data leakage
feature engineering
How to Approach This
  1. Clarify the schema and expected output format before writing queries.
  2. Use CTEs (WITH clauses) to break complex queries into readable steps.
  3. Consider window functions (ROW_NUMBER, RANK, LAG, LEAD) for ranking and sequential analysis.
  4. Watch for NULLs, duplicates, and edge cases in JOINs and GROUP BY.
  5. For pandas, prefer vectorized operations over row-by-row iteration.
Possible Follow-up Questions
  • How would you add a trailing 7-day sum of watch time instead of a count?
  • How do you make sure the online feature pipeline computes exactly the same window?
  • How would you handle events that arrive late in the log?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice SQL Problems
Sample Answer
Clarify the Data

A user can have several label rows. Event types are a small known set (for example 'like', 'comment', 'share'). An event exactly at label_ts is excluded, since in production the prediction is made b...

Approach

Count of events in [lo, hi) equals C(< hi) minus C(< lo), where C is the cumulative count of a user's events. Sort events by time and give each a running count per (user, type). For each label, `merge...


Submit Your Answer
Markdown supported