Verily Study Watch ingestion logs can be too large to load into memory. Implement an online grep-style function that scans an iterable of log lines, selects lines matching a regular expression, and returns surrounding context while merging overlapping match regions.
Implement grep_context(lines, pattern, before, after), where lines is an iterable of strings, pattern is a valid Python regular expression, and before and after are nonnegative integers. Return a list of match blocks. Each block is a list of [line_number, line] pairs, using one-based line numbers. Include up to before preceding lines and up to after following lines for every matching line. A line must appear at most once in a block. Merge blocks whose context ranges overlap or touch.
The function must process lines in one forward pass. Do not convert the input iterable to a list or assume it supports random access. The implementation may buffer only the context needed to decide whether a later match extends the current block.
def grep_context(lines, pattern, before, after):