Walkthrough

AI-assisted coding round in a provided codebase

Meta-style rounds (and their Microsoft, OpenAI, Apple and Fireworks cousins): fix a bug, build a feature and make it faster in a repo you've never seen, with an AI assistant you direct, check and sometimes overrule.

Researched

Coding Both tracks Senior + Staff 60 min AI-assisted codingDebugging
On this page

The prompt

If you only remember one thing, say this in the first minute: “Before I ask the assistant anything, I’ll read the code and run the tests. For each phase I’ll say what I think is wrong, write a test that fails for that reason, and only then ask the assistant to draft the change, in pieces small enough to check in seconds. I’ll read every line before it goes in and run the whole suite after every paste. For the speed phase I’ll measure before and after, on every kind of input. The assistant does the typing; the diagnosis, the tests and the decisions are mine.”

The rest of this page explains each part of that answer, using one practice codebase from start to finish.

What the round looks like

You get about an hour, a codebase of several files that you have never seen, a test suite, and an AI assistant. The work comes in phases. First you run the tests and explain a failure, or fix a reported bug. Then you build a missing piece, often while the inputs get harder. Last, you handle edge cases and scale, sometimes with a benchmark to beat. You are graded on how you solve the problem, not on how cleverly you phrase requests to the assistant.

What makes this different from a normal coding round

A normal coding round gives you an empty editor and one self-contained problem. You type every line, and the interviewer watches how you think about the algorithm. Nothing in the room writes code except you.

This round changes three things, and a good answer is built around them:

  1. The code is not yours. It is a small real project with several files, existing tests and existing bugs. Reading it quickly and forming a correct theory of what it does is most of the work. This is the skill of a good reviewer, not of a fast typist.
  2. A second typist is in the room, and it is sometimes confidently wrong. The assistant is a chat tool backed by a large language model (LLM): a program trained on huge amounts of text and code that writes a plausible reply to whatever you type. It can produce a 40-line function in seconds. It can also invent a helper function that does not exist, or offer a fix that passes the visible test and leaves the bug. So the skill being tested shifts from “can you write it” to “can you tell whether what was written is right”.
  3. You hold two conversations at once. One is with the assistant, the other with the interviewer. If you go quiet while you read generated code, the interviewer can’t see your judgment, and judgment is what they grade.

The best-documented version is Meta’s: about 60 minutes in CoderPad (a shared online editor) on a multi-file project, with three phases (bug, feature, optimize), a model you choose, and an assistant that only chats (Hello Interviewsecondary · 16 Feb 2026, dglearning (Substack)secondary · 17 Apr 2026).

Words you need first

  • Prompt: the instruction you type to the assistant. A good prompt carries your diagnosis and your limits (“only change this function, show only the changed lines”), not just the error message.
  • Chat-only assistant: it answers in a side panel and cannot edit your files. You copy its code into the editor yourself, so every paste is a moment where you choose what goes in. Meta’s round is reported to work this way.
  • Coding agent: an assistant that can also edit files and run commands on its own. You meet these at work and in the neighbouring drive-an-agent family.
  • Inline completion: grey suggested text that appears as you type, which you accept with a key press. GitHub Copilot in VS Code works this way. It is reported for Microsoft’s version of the round.
  • Invented helper: a call to a function that sounds right but doesn’t exist in the codebase. Models do this because they predict likely-looking code; when they can’t see the repo, a plausible name is the likely guess. Interviewers notice whether you catch it.

Where this round is reported

Meta’s round went live around October 2025 (a Blind E4 candidate wrote it “was introduced around October 1” (as of · Blind)), after 404 Media reported the plan from internal posts (404 Medianews · 29 Jul 2025). (E4, L5 and E7 are company level names used in the reports below; at Meta, E7 is Senior Staff.)

r2a-004 Meta 2026 Senior

AI-enabled round: a small multi-file Python codebase with tests and bugs. Run the tests, explain why one fails, and implement a missing core function as inputs widen from letters to numbers to mixed. An LLM is available; the candidate reports it invented helper functions that did not exist in the codebase.

AI-assisted coding rounds AI-assisted codingDebugging Medium confidence

Staff signal The signal is verification: run tests file by file, catch the hallucinated helper, and explain why the first approach (a bitmask) collided once digits appeared.

r2b-002 Microsoft Mar 2026

AI-assisted coding round (Microsoft CoreAI): solve a coding problem in VS Code with GitHub Copilot while sharing your screen. A commenter says difficulty matches the standard rounds, with a slightly higher bar because you have help.

AI-assisted coding rounds AI-assisted coding Low confidence

Staff signal Commenter's advice: state your approach out loud first, review every suggestion before accepting it, and explain why a wrong Copilot suggestion is wrong before fixing it.

Sources

The other questions in this family test the same skill in a different wrapper:

CompanyReported shapeSource
MetaBug, feature, edge cases and scale in one repo; a maze where the assistant kept answering wrong; a card game; friend recommendations over test suites up to about 100k users and 1.5M pairs; debug, naive solution, benchmark, optimizeHello Interviewsecondary · 16 Feb 2026 PracHubfirst-hand · 19 Sep 2026 Yuan Meng (personal blog)first-hand
Microsoft CoreAI”an IDE connected to an AI coding assistant” (pre-interview Blind post); search previews say VS Code with GitHub Copilot while sharing your screenBlindfirst-hand Blindfirst-hand
OpenAIAn AI-enabled live-coding screen with an easy, multi-step “delivery rate” problem and complexity questions (one forward-deployed engineer account); separately, a beta “agentic coding” onsite on a large codebase that not every candidate getsAcedfirst-hand · 2026 interviewing.iosecondary · 2026
ApplePseudocode for a sensor-data algorithm, then Claude implements it and you explain and test it (snippet only)Interview Querysnippet only
Fireworks AIMutual-friend recommendations that exclude current friends, then a bounded score in [0, 1]PracHubfirst-hand · 13 Sep 2026

Two neighbours look similar but live elsewhere. LinkedIn’s LRU, TTL and thread-safety round is in the cache coding family. Building a product-shaped feature by directing an agent is the drive-an-agent family.

Policies differ by company and by round, so ask the recruiter. Anthropic says live interviews are “all you” with no AI unless it says otherwise (Anthropic candidate guidance (as of · Anthropic)). Amazon’s interview rule is no generative-AI tools (“GenAI”) “unless explicitly permitted” (ITPronews · 14 Mar 2025), while its own careers page says the redesigned software-engineer (SDE) online assessment includes an interactive AI assistant (Amazonofficial). Google’s Gemini “code comprehension” round is a plan reported by Business Insider for H2 2026, for junior and mid-level candidates on select US teams, not Senior or Staff (reported plan (as of · Storyboard18 · The Outpost (automated summary of Entrepreneur and Digit, relaying Business Insider))).

What is being tested

In one sentence: the same things as a normal coding round, plus whether you can tell good generated code from bad. Here is what candidates and prep sites report, followed by my reading.

The usual four signals, not prompting. Hello Interview reports that Meta scores problem solving, code quality, verification and communication, and that the round “isn’t about prompt engineering”. An internal source it quotes puts the bar as “Should use AI, but need to show you understand the code” (Hello Interviewsecondary · 16 Feb 2026). interviewing.io relays Meta materials calling AI use optional with “no bearing on the outcome”, and its author disputes that in practice (interviewing.iosecondary · 2026).

Partnering, not authorship. A named machine-learning engineer who went through Meta’s round wrote that the interviewer “cared more about how well I partnered with AI to achieve the goal” than about who typed the code (Yuan Meng (personal blog)first-hand).

Catching wrong output. A rejected Meta L5 candidate reports that the model invented helper functions that did not exist in the codebase, and that a bitmask approach (one bit per letter in an integer) collided once digits joined letters (Aced (formerly Exponent)first-hand · 2026). An E7 candidate gave up on a model that kept answering a maze problem wrong and wrote the code himself (Hello Interviewsecondary · 16 Feb 2026). Canva, which runs its own AI-assisted round, wrote that “The most successful candidates didn’t just prompt AI and accept whatever it generated” (Canva Engineeringofficial · 11 Jun 2025).

Calibration in both directions. Using the assistant too little is also marked down. After a rejection in two AI rounds, a Meta candidate’s recruiter said “less manual work, more on AI” (PracHubfirst-hand · Jul 2026). A Microsoft commenter called the round “similar difficulty to their standard coding rounds” with “a slightly higher bar since you have help”, and advised “Review every suggestion before accepting” (Blindfirst-hand).

Two conversations at once. Meta candidates told Hello Interview that “keeping the dialogue going with the interviewer was the hardest part” (Hello Interviewsecondary · 16 Feb 2026). Finishing still counts: a January 2026 candidate solved 3 of a 4-part question and was rejected (Blindfirst-hand · 15 Jan 2026), and a LinkedIn candidate finished 2 of 4 after spending most of the time fixing the AI’s mistakes (PracHubfirst-hand · Aug 2026).

My reading. The round grades what a good reviewer does under time pressure. You form a theory from the code. You prove it with a test that fails for the reason you stated. You hand off typing you can check quickly. You refuse anything you can’t explain. The assistant changes how fast code appears, not who answers for it.

Say it like this: “I’ll use the assistant for anything I can check faster than I can type. The diagnosis and the test cases stay with me.”

Clarify and scope

Ask about the round before the problem, in the first two minutes:

  1. Tools. Which models, and can the assistant edit files or only chat? A chat-only assistant makes copy-paste the bottleneck, so you ask for small pieces.
  2. Tests. Can I run the suite as often as I like? Is there a larger hidden or tiered suite for the scale phase? (Meta candidates describe three suites of growing size, PracHubfirst-hand · 19 Sep 2026.)
  3. Done. For the bug phase, is “done” the test passing, or the root cause explained? May I add tests?
  4. Narration. Think aloud while I prompt, or summarize after each step?

The practice codebase used on this page

To make the rest concrete, this page follows one practice repo through all three phases: this site’s Build Your Own Kafka-lite lab, a small Kafka-like log broker written in Go. A log broker is a server that stores messages by appending them to files, and lets readers fetch them by position. Five terms carry the whole example:

  • Topic and partition: a topic is a named stream of messages, such as orders. It is split into numbered partitions, each its own log, so the load can be spread out. The practice repo mostly uses partition 0.
  • Offset: a message’s position number in the log: 0, 1, 2 and so on. A reader asks for “messages from offset 40”.
  • Segment: the log is split across files. Each segment is a .log file holding records back to back, plus a small .index file that helps find a record without reading from the start.
  • Consumer group: a named set of readers (say, billing) that share one saved position per topic and partition, so a restarted reader carries on where the group stopped. Saving that position is called committing an offset.
  • Torn record: a record that was only partly written when the process died. The first phase is about this.

With that picture, the questions about the problem make sense:

  • Crash model. Can a process die mid-write? (Yes: that is the bug.) Is fsync on every write expected? (fsync forces the operating system to put the data on disk now, which is safe but slow.) Or is batched fsync accepted?
  • Semantics. Is “at least once” delivery fine for consumers, meaning a message may arrive twice after a crash but is never lost? Can a group commit a lower offset than before?
  • Scale. Will readers mostly read many small messages from the start of the log, or jump to single offsets? The optimization depends on which.

Out of scope unless asked: replication, multiple brokers, partition assignment inside a group.

Plan before code

The system in one picture

Producer
   │  POST /produce  (topic "orders", payload)
   ▼
HTTP server (cmd/server/main.go)
   │
   ▼
DiskBroker (pkg/broker/broker.go)
   │  append the record; every 4th record also gets an index entry
   ▼
<dataDir>/orders/0/                           one directory per topic and partition
   00000000000000000000.log    records back to back:
                               [offset: 8 bytes][length: 4 bytes][payload: length bytes] ...
   00000000000000000000.index  one 8-byte entry per 4 records:
                               [record number in segment: 4 bytes][byte position in .log: 4 bytes]
   │
   ▼
Consumer
   GET /consume?offset=N  → find the index entry at or before N, then read forward to N
   POST /groups/{id}/commit → appends a JSON record to the "__consumer_offsets" topic

Producer and HTTP server. Clients send messages over plain HTTP. The server is a thin wrapper; all the logic is in the broker package.

DiskBroker. It appends each message as a record of a 12-byte header (8 bytes of offset, 4 bytes of payload length) followed by the payload. Every fourth record, it also writes an index entry. When a segment reaches maxSegmentBytes (64 MB), it starts a new segment file, which is called rotation.

The .log and .index files. Because the index only covers every fourth record, it is called a sparse index. To read offset N, the broker finds the nearest index entry at or before N, jumps to that byte position, and reads forward at most three records.

Consumer groups. A commit is stored as a JSON message in a special topic, __consumer_offsets. That is the same trick real Kafka uses: positions are just more messages in a log.

The repo, as you would map it out loud in the first five minutes:

labs/kafka-lite/
  pkg/broker/broker.go        v0 in-memory log, v1 segmented disk log + sparse index, v2 consumer groups
  pkg/broker/broker_test.go   14 tests, all passing
  cmd/server/main.go          HTTP: /produce, /consume, /groups/{id}/join|heartbeat|commit|offset
  bench_test.go               produce, consume, index-lookup and commit benchmarks

It has no external dependencies, so go test ./... works from a fresh clone. Everything below was run in a scratch copy on 2026-10-12 with Go 1.26.9 on an Apple M1 Ultra. The lab itself is unchanged. The bugs were not planted: they are in the code as committed.

Read the tests as claims, not proof

A test’s name says what someone meant to check. Its body says what is actually checked. All 14 tests pass, and three of them promise more than they check:

  • TestDiskBroker_SegmentRotation writes 500 records of 24 bytes (about 12 KB) against a 64 MB segment size. It never rotates, so the path that reads across several segments has no test.
  • TestConsumerGroup_ResumeAfterRestart only checks that __consumer_offsets has records after a restart. Its own comment says rebuilding offsets “is left as an extension”, while the package comment says commits survive restarts.
  • TestDiskBroker_Durability closes the broker cleanly. Nothing simulates a crash.

Say this out loud. It tells the interviewer where you think the bugs are before any AI is involved: “All tests pass, but nothing simulates a crash, nothing restarts a consumer group and checks its position, and nothing actually rotates a segment. That’s where I’d look first.”

Decide who does what

WorkWhoWhy
Reading the code, naming the root causeyougraded as problem solving; the model has not seen the failure
The test that reproduces the bugyou decide the cases, AI draftsit must fail for the stated reason
The fixyou choose the approach, AI draftsthe approach is the algorithm; the typing is not
Test scaffolding, benchmark harnessAIquick to check, slow to type
Reviewing every line before it landsyou”show you understand the code” is the reported bar
Choosing between optimizationsyou, from measurementsa suggestion is not evidence

This is the same order practitioners describe for agent work generally: plans, then tests, then code review (Simon Willison, 2025-10-07); specify, plan, break into tasks, implement, and review small changes (GitHub, 2025-09-02).

A clock for the hour

This is a suggested budget, not a reported one. It keeps any single phase from eating the round.

MinuteStepWhat to say in the interview
0–5Map the repo, run the tests, read the three over-promising tests”Nothing simulates a crash, so I’ll start there.”
5–25Phase 1: reproduce the torn-record bug, explain it, fix it”This test fails for the reason I stated; now I’ll ask for the fix.”
25–42Phase 2: tests for offset replay, then the implementation”These five cases are the spec. The assistant can draft against them.”
42–57Phase 3: profile, two options, measure both”I’ll keep whichever wins on both read shapes.”
57–60Summarize what is fixed and what isn’t”Here’s what I chose not to fix today, and why.”

Solution in stages

The code below was written for this page and run in the scratch copy. It is not a transcript of a model’s output. The prompts are what you would type.

Phase 1: the bug (after a crash, a consumer gets garbage)

The report. “After the broker crashed and restarted, one consumer got a corrupted message, and messages produced after the restart never arrived.”

Picture the crash first. A crash in the middle of a write leaves the end of the active .log file looking like this:

... [rec-8: header | payload] [rec-9: header | pay]   ← file ends here; "load" was never written

On restart, the broker must notice that rec-9 is incomplete, throw those bytes away, and append the next record right after rec-8. If it doesn’t, the next record is written after the half-record, and every reader that reaches that point reads garbage.

Reproduce it yourself. You can simulate a crash by cutting bytes off the end of the file. The test checks counts, offsets and payloads, at several cut points, because a crash can land in the payload or in the 12-byte header:

// rec-9 is 17 bytes: 8 (offset) + 4 (length) + 5 (payload).
for _, cut := range []int64{1, 3, 9, 15, 20} { // payload, payload, header, header, into rec-8
	// produce rec-0..rec-9, Close, os.Truncate(logPath, size-cut), reopen ...
	// want: LogLength == complete records; next Produce gets the next offset;
	// Consume(0, 100) returns exactly rec-0.. plus "after-crash", payloads intact.
}

On the original code all five cases fail:

cut_1_bytes:  LogLength after reopen = 10, want 9 complete records
cut_3_bytes:  LogLength after reopen = 10, want 9 complete records
cut_9_bytes:  offset 9: got (9, ""), want (9, "after-crash")
cut_15_bytes: consumed 9 messages, want 10
cut_20_bytes: LogLength after reopen = 9, want 8 complete records

Read the failure lines before going on. Each one is a different symptom of the same cause, and the third one (got (9, "")) is what a torn header looks like.

Explain it before prompting. (EOF below means end of file.) On startup, countMessagesInLog walks the log with f.Seek(payloadLen, io.SeekCurrent), which means “skip ahead by the payload length”. Seeking past the end of a file is not an error in Go: the io.Seeker docs say seeking to any positive offset “may be allowed”, with later I/O “implementation-dependent”. So a record whose payload was cut short still counts as complete. The broker then sets the next offset one too high and appends after the torn bytes, and the reader misparses everything that follows.

Say it like this: “Recovery counts the half-written record as whole, because seeking past the end of the file doesn’t fail in Go. So we append after garbage.”

The trap in the first fix. The obvious fix, and the one an assistant is likely to offer, is to count only records whose payload fits in the file. It makes the LogLength check pass. Run the full test and it still fails in all five cases, with payloads like "re\x00\x00\x00": the torn bytes are still in the file, and the next record lands after them. A test that checked only the count would have passed. This is why the test compares payloads.

The prompt, once you know the fix:

In pkg/broker/broker.go, recovery counts a torn last record as complete because Seek past EOF
succeeds. Replace countMessagesInLog with scanLog(f *os.File, base int64) (count int, validBytes int64)
that uses ReadAt for the 12-byte header, stops at a short header, a payload past EOF, or an offset
field != base+count. Add repairTail(seg) that truncates the active segment's .log to validBytes and
its .index to whole 8-byte entries whose position < validBytes. Call it in partition.open before
the last segment is reopened for append. No exported API changes. Show only changed functions.

The prompt carries three things: the diagnosis, the rule the fix must keep (only ever append right after a complete record), and a limit on the output so the reply is short enough to review.

func scanLog(f *os.File, base int64) (count int, validBytes int64) {
	st, err := f.Stat()
	if err != nil {
		return 0, 0
	}
	size := st.Size()
	var hdr [12]byte
	for {
		if _, err := f.ReadAt(hdr[:], validBytes); err != nil {
			return count, validBytes // EOF inside a header
		}
		if int64(binary.BigEndian.Uint64(hdr[0:8])) != base+int64(count) {
			return count, validBytes // not the record we expect (zeros, garbage)
		}
		next := validBytes + 12 + int64(binary.BigEndian.Uint32(hdr[8:12]))
		if next > size {
			return count, validBytes // payload cut short
		}
		validBytes = next
		count++
	}
}

func repairTail(seg *segmentInfo) error {
	if err := os.Truncate(seg.logPath, seg.logSize); err != nil {
		return err
	}
	idx, err := os.ReadFile(seg.indexPath)
	if err != nil {
		return err
	}
	keep := 0
	for i := 0; i+8 <= len(idx); i += 8 {
		if int64(binary.BigEndian.Uint32(idx[i+4:i+8])) >= seg.logSize {
			break
		}
		keep = i + 8
	}
	return os.Truncate(seg.indexPath, int64(keep))
}

scanLog reads each header with ReadAt, which, unlike Seek, does report when the file ends early. It stops at the first record that is short, or whose offset field isn’t the next expected number. repairTail then cuts the file back to the last complete record. openSegment now sets seg.msgCount, seg.logSize = scanLog(logF, base), so the next append starts where the last complete record ends.

Review points to say out loud:

  • The index can also be torn. A half-written 8-byte entry would shift every later entry, so it is cut too.
  • The offset-field check rejects a tail of zero bytes, which would otherwise parse as a valid empty record at offset 0.
  • The files in the original are not gofmt-clean, so keep formatting out of this diff, or the reviewer can’t see the fix.
CheckOriginalCount-only fixFull fix
torn-tail test, 5 cut points5 fail5 fail (corrupt payloads)5 pass
full suite, go vet, -race -count=3passpasspass

Phase 2: the feature (consumer-group offsets survive a restart)

The spec, in your words. “CommitOffset appends a JSON record to __consumer_offsets, but FetchOffset reads an in-memory map that a restarted broker starts empty. So every group restarts from offset 0 and reprocesses everything, and a commit after the restart fails with group "billing" not found.” Both were reproduced on the original code.

In plain terms: the broker writes down every saved position, but never reads the notes back after a restart. The feature is to replay those notes when the broker starts.

Write the tests first, with the edge cases you decided on:

  • the last commit for a (group, topic, partition) wins, including a commit that rewinds;
  • groups and partitions are independent; an unknown group still returns 0;
  • a group can commit after the restart without re-joining;
  • an unparsable record in __consumer_offsets is skipped, and the commits around it survive;
  • a fresh data directory starts without creating __consumer_offsets just to read it.

On the original code they fail like this:

FetchOffset(billing, orders, 0) after restart = 0, want 4
FetchOffset(search, orders, 0) after restart = 0, want 5
commit after restart: group "billing" not found; call JoinGroup first
orders/0 = 0, want 3      (corrupt-record test)

Delegate the implementation with those constraints:

Add (b *DiskBroker) loadCommittedOffsets() error, called from NewDiskBroker. If
<dataDir>/__consumer_offsets/0 doesn't exist, return nil. Otherwise read partition 0 with
b.Consume in batches of 1024 from offset 0, json.Unmarshal each payload into a typed
offsetRecord{Group, Topic, Partition, Offset}, skip records that fail or have an empty group,
create missing groups with empty member maps, set offsets[partitionKey(...)] (last wins).
Use the same struct in CommitOffset. Only use functions that exist in broker.go.

The last line is there because invented helpers are a reported failure in this round (Aced (formerly Exponent)first-hand · 2026). If the draft calls something like b.readAll(topic), search for it before you read further.

func (b *DiskBroker) loadCommittedOffsets() error {
	if _, err := os.Stat(filepath.Join(b.dataDir, offsetsTopic, "0")); os.IsNotExist(err) {
		return nil
	}
	for next := int64(0); ; {
		msgs, err := b.Consume(offsetsTopic, 0, next, 1024)
		if err != nil {
			return err
		}
		if len(msgs) == 0 {
			return nil
		}
		for _, m := range msgs {
			var rec offsetRecord
			if err := json.Unmarshal(m.Payload, &rec); err != nil || rec.Group == "" {
				continue // corrupt or foreign record: skip it, keep the rest
			}
			g, ok := b.groups[rec.Group]
			if !ok {
				g = &consumerGroup{groupID: rec.Group, members: map[string]time.Time{},
					offsets: map[string]int64{}, broker: b}
				b.groups[rec.Group] = g
			}
			g.offsets[partitionKey(rec.Topic, rec.Partition)] = rec.Offset
		}
		next = msgs[len(msgs)-1].Offset + 1
	}
}

Review points.

  • It changes b.groups without holding groupsMu, the lock that normally protects it. That is safe only because it runs inside NewDiskBroker, before anyone else holds the broker. Write that in a comment.
  • Records written by the original map-based code still decode. (A raw record in the old key order was replayed to the right offset.)
  • Phase 1 protects this code. A torn last commit record is cut on open, instead of poisoning the next commit.

Say what it costs. Replay reads every commit ever written. In the scratch copy, startup took about 30 ms with 10,001 records and about 320 ms with 110,001 (three runs each, before phase 3), so roughly 3 µs per record. The log never shrinks, so startup time keeps growing with the number of commits. Kafka’s answer is log compaction: keeping only the latest record for each key. A toy answer is a periodic snapshot. Name it and move on.

Phase 3: optimize (reads)

Measure first, then profile. A profile records where a program spends its time, function by function. The repo has benchmarks for both read shapes: 100 messages of 256 bytes from offset 0 (BenchmarkDiskBrokerConsume) and one message at a scattered offset (BenchmarkIndexLookup). A CPU profile of each shows almost all time in syscalls (requests to the operating system):

  • about 71% of the consume benchmark is in read, because every record costs three unbuffered reads;
  • about 69% of the lookup benchmark is in open, because every call opens the index file and the log file again.

Say it like this: “The time isn’t in our logic; it’s in asking the operating system for tiny reads and reopening files. So the fix is fewer system calls, not a smarter algorithm.”

Ask for two options, then measure both.

  • Option A wraps the log file in a 64 KiB bufio.Reader: read a big chunk once, then serve small reads from memory.
  • Option B keeps the sparse index in memory (it is 8 bytes per 4 messages), keeps one read-only file handle per segment, reads through a 16 KiB buffer over an io.NewSectionReader bounded by logSize, and skips payloads before the target offset without allocating them.

Both pass the full suite with -race.

Before trusting either, close the coverage gap from the plan. Make maxSegmentBytes a package variable with a test-only setter, and add a test that writes 500 records into 1 KiB segments (12 segments), reads 60 messages from eight start offsets including segment boundaries, restarts, and reads again. It passed on the original code and on both options. Now the multi-segment path, which both options touch, has a test.

Results, 8 interleaved runs of each version, compared with benchstat (a Go tool that compares benchmark runs and reports whether a difference is real; load average 4 to 7, so treat the middle digits as noise):

BenchmarkAfter phases 1–2A: buffered readsB: in-memory index + kept handle
Consume 100 × 256 B, time/op227 µs68.5 µs (−70%)15.3 µs (−93%)
Single-offset lookup, time/op42.4 µs48.9 µs (+15%)3.5 µs (−92%)
Lookup, bytes allocated/op892 B65 KiB16 KiB

Option A is the trap worth noticing. It fixes one benchmark and makes the other worse, because a 64 KiB buffer is allocated and filled to read about 150 bytes. Measuring only the benchmark you were asked about would have shipped a regression. Option B wins both. Its cost is memory proportional to the index (about 2 bytes per message) and one open file per segment, which matters with thousands of segments.

Verification

PhaseBeforeAfterCommand
1 bugtorn-tail test fails 5 of 5 cases; count-only fix still fails 5 of 55 of 5 passgo test ./pkg/broker -run TornTail -v
2 featuregroup offsets 0 after restart; commit after restart errors3 replay tests pass; old-format record replays`go test ./pkg/broker -run ‘Offsets
coverage gaprotation never exercised12-segment read and restart test passes on every version-run RealRotations
3 optimize227 µs consume, 42.4 µs lookup15.3 µs, 3.5 µs`go test -bench ‘Consume
allfull suite, go vet, -race -count=3 passgo vet ./... && go test -race ./...

The table is the evidence. The habits behind it matter more, because they carry to any repo:

  • Make the test fail first, for the reason you stated, and read the failure line. got (9, "") is the torn header; a timeout or a panic would be a different bug.
  • Check payloads, not just counts. The count-only fix passed every count assertion.
  • Treat a test name as a claim. Three tests here promise more than they check.
  • Run the suite after every pasted change. With a chat-only assistant, every paste is a chance to break something unrelated.
  • Benchmark every read shape you touch, with repeats. One shape got 15% slower under option A.
  • Narrate in three beats per step: what you believe, what you will ask the AI for, and what result would prove you wrong.

Complexity and performance

Complexity questions in this round are about the code as it now stands, including what the assistant added. For the practice repo:

  • Recovery (scanLog): O(records in the segment), once per segment at startup, one ReadAt per record. Startup over many large sealed segments is the next cost; real brokers trust sealed segments and scan only the active one.
  • Read: a binary search over I in-memory index entries, O(log I), then a forward scan of at most indexInterval (4) records to the target, then O(k) for k messages. Under the original code each call also paid two file opens and O(log I) seek-and-read syscalls.
  • Replay: O(total commits ever made), about 3 µs per record in the scratch run, growing without bound.
  • Memory: the in-memory index is 8 bytes per 4 messages, plus one file handle per segment.

The replay cost is the one that bites in production, because it grows with uptime. With an assumed 100 consumers committing once a second, one day of commits adds about 26 seconds to startup. That is the case for compaction.

The arithmetic behind the numbers (for a Staff-level follow-up)
Startup replay time grows with commits
t_replay ≈ c × consumers × commits_per_second × uptime_seconds
c
replay cost per record, about 3 µs in the scratch run (320 ms ÷ 110,001 records)
consumers × commits_per_second
commit rate into __consumer_offsets (assumed)
uptime_seconds
time since the log was last compacted or snapshotted
Worked example

Assume 100 consumers committing once a second for one day: 100 × 86,400 = 8.64M records × 3 µs ≈ 26 s of startup. That is the case for compaction.

  • Index memory: one 8-byte entry per 4 messages is 8 ÷ 4 = 2 bytes per message. A million messages need about 2 MB of index in memory.
  • Why option A regressed on lookups: filling a 64 KiB buffer to read a record of about 150 bytes moves roughly 65,536 ÷ 150 ≈ 440 times more data than needed, and the benchmark shows the 65 KiB allocated per lookup.

Small-team version

At a company of 50 to 500 people this round is not interview theatre. One engineer and a coding agent inherit code nobody remembers writing, and the job is the same loop: read before prompting, reproduce with a test, let the agent draft, review in small diffs, measure before optimizing.

Buy

  • The assistant. Buy a coding-agent seat; nobody builds this. A heavy day of agent use costs about $3.68, or about $150 a month at an assumed 40 sessions. That is about 1% of a loaded engineer’s monthly cost, so the agent pays for itself if it saves about 1% of that engineer’s time. The real cost is review time, which the next section is about. (Providers charge per token, a chunk of text of roughly ¾ of a word. Input the provider has seen recently can be billed as cached input, at a tenth of the price. The working is in the box below.)
  • CI. Hosted CI that runs the suite, go vet or linters, and -race on every change is the gate that makes agent output reviewable.
The arithmetic behind the numbers (for a Staff-level follow-up)
  • Prices: Claude Sonnet 5 at the list prices fetched 2026-10-11: $2 per million input tokens, $0.20 per million cached input tokens, $10 per million output tokens.
  • One heavy session (assumed): 3M input tokens, 80% of them cached, plus 0.2M output tokens: 0.6 × $2 + 2.4 × $0.20 + 0.2 × $10 = $1.20 + $0.48 + $2.00 = $3.68.
  • A month (assumed 40 sessions): 40 × $3.68 = $147, about $150.
  • The engineer: an assumed loaded cost of about $194K a year (the US Bureau of Labor Statistics median developer wage ÷ an assumed 0.70 wage share), or about $16,200 a month. 1% of that is about $162, a little more than the agent’s monthly cost.

Build (the habits, as team rules)

  • A plan before code. For anything bigger than a one-line fix, the agent writes a short plan and a person approves it. Practitioner accounts of two-person teams describe exactly this: approve plans, check the agent’s work “at the lowest value stage”, and let tests drive iteration (Every, 2025-06-11).
  • A failing test first, written or approved by a person. The agent can draft it; a person decides the cases. The torn-tail test above is the model: it checks the outcome a user would see, not an internal count.
  • Small diffs. One concern per change, with formatting in a separate change. Review time, not generation, is where the time goes: a summary of Faros AI’s 2025 data reported PR review time up 91% and PR size up 154% on high-adoption teams (Augment Code summary; Faros AI).
  • Turn each agent mistake into a rule or a test. Mitchell Hashimoto describes adding an AGENTS.md rule (a file of standing instructions the agent reads at the start of every session) or a tool each time an agent errs (2026-02-05).
  • Search for siblings. Any bug that is a pattern (a header set after WriteHeader, a Seek past EOF) gets a repo-wide search, not a one-line fix.

Skip

  • Unreviewed agent merges for code that touches storage, money, auth or customer data. The few public accounts of “no human review” setups that we found describe internal tools, or well-funded teams with held-out scenario tests.
  • Optimizing without a benchmark, and keeping changes the benchmark can’t show.

What you still own

The diagnosis, the test cases, the decision about what not to fix today (replay cost, path traversal through topic names, the untested rotation path), and the release. Interview loops at small companies lean the same way: PostHog’s handbook describes a pairing session debugging existing code for product engineers (PostHog), and a recruiting vendor’s playbook recommends a short-lived repo with a broken agent pipeline and an AI assistant allowed (Dover, updated 2026-08-24; a vendor, so treat it as one view).

Revisit when

  • Review becomes the bottleneck (PRs wait longer than they take to write): shrink diffs further, add an agent-run first review, or move checking into held-out scenario tests.
  • The team grows past the point where one person knows the codebase: invest in the harness (AGENTS.md, scripted test runs, fixtures) so agents and new hires get the same context.
  • A change ships an incident: add the missing test and the rule, and tighten sign-off for that area rather than loosening review.

Senior vs Staff

AI-assisted round in a provided codebase

Senior

  • Finishes all three phases, each with a failing-then-passing test or a benchmark as evidence.
  • Names the root cause (Seek past EOF) before prompting, and catches that the count-only fix still corrupts payloads.
  • Writes narrow prompts with constraints and an output limit, and reviews every line before pasting.
  • Measures both read shapes, not only the one asked about.
  • Keeps the interviewer informed in short beats.

Staff

  • Reads the tests as claims and finds the three that promise more than they check, before touching code.
  • Makes the untested rotation path testable before trusting an optimization on it.
  • States the cost of each change (replay grows with commits; one file handle per segment) and what would change the answer.
  • Lists sibling and out-of-scope risks (torn index, path traversal through topic names, no compaction) and decides which to fix now.
  • Keeps each phase small enough that phase 3 doesn’t rewrite phase 1.

Level calibration for Meta is unclear. interviewing.io and DG Learning say E7 and above get a single AI-assisted coding round; Hello Interview says one classic and one AI round up to E7/M2. Neither cites Meta (interviewing.iosecondary, dglearning (Substack)secondary · 17 Apr 2026, Hello Interviewsecondary · 16 Feb 2026). E7 at Meta is Senior Staff. If the first reading is right, this round carries the whole coding signal at that level.

Follow-ups

(Reported, Meta) The assistant uses a helper function that doesn't exist. What do you do?

Say so, search the repo for it, and restate your prompt to use only functions you name or paste. A Meta L5 candidate who hit this ignored the invented helpers and ran the tests one file at a time to keep the output readable (Aced (formerly Exponent)first-hand · 2026). Spotting it out loud is a point in your favour; pasting it is not.

(Reported, Meta) The assistant keeps giving wrong answers. Do you keep prompting?

No. Two wrong answers in a row means the model lacks something you know: the failing test, a constraint, the data shape. Give it that once. If it still fails, write the code yourself and say why. An E7 candidate did exactly that on a maze problem (Hello Interviewsecondary · 16 Feb 2026).

(Reported, Meta) Now scale it: the large test suite times out.

Profile before guessing, as in phase 3. One Meta candidate’s advice was to keep each AI request to a few minutes of work, cap every run with a timeout, and validate on small samples before the large suite (PracHubfirst-hand · 19 Sep 2026). Then pick the algorithmic change the profile points to.

(Reported, OpenAI) What are the time and memory complexity of your solution?

The forward-deployed engineer account reports complexity questions after the multi-step problem (Acedfirst-hand · 2026). Answer for the code as written, including what the assistant added: an extra sort, a copied slice or a map rebuilt per call is yours now. For the practice repo: reads are O(log I + k) with the in-memory index, replay is O(commits ever made).

(Not reported; a natural next push) The broker crashes during repairTail itself. Is recovery still safe?

Yes, because the repair is idempotent: truncating to the same valid length twice is the same as once, and the index cut depends only on the log length. What isn’t covered: a crash between writing a record and writing its index entry leaves a missing entry, which only slows lookups. A real log adds a checksum per record so it can also reject a full-length record with corrupted bytes.

(Not reported; a natural next push) A client sends topic=../../etc to /consume. What happens?

getOrCreatePartition joins the topic name into a path and creates directories even on a read, so a GET can create directories outside the data directory. This is called path traversal. Validate topic names against an allow-list pattern, and stop creating partitions on read. Find it by searching for filepath.Join with request input.

Common mistakes

  • Prompting before reading. Pasting the failure into the chat and the answer back into the editor, round after round, never forms a theory. Diagnose first; a guide to Cursor’s loop calls this pattern “the fastest rejection in the building” (techinterview.orgsecondary · 2026).
  • Accepting the first fix because the visible assertion passes. The count-only fix passed the count and still corrupted payloads.
  • Trusting test names. SegmentRotation never rotates.
  • Under-using the assistant at companies that expect it. Hand-typing boilerplate reads as poor tool judgment (PracHubfirst-hand · Jul 2026).
  • Pasting code you can’t explain. The reported bar is understanding the code (Hello Interviewsecondary · 16 Feb 2026).
  • Optimizing the benchmark you were given and regressing another one. Option A did exactly that.
  • Spending the round on review. The LinkedIn candidate finished 2 of 4 parts (PracHubfirst-hand · Aug 2026). Ask for smaller pieces so each review takes seconds.
  • Going quiet while reading AI output. The interviewer can’t grade judgment they can’t hear; use the three-beat narration.

Prove it with a lab

Build Your Own Kafka-liteProves itProof labgo

Run the three phases above in your own copy, timed at 60 minutes, with whichever assistant your target company allows. Start by reading the three over-promising tests, write the torn-tail test before any prompt, and stop after each phase to say what proved it.

Second drill. Its sliding-window concurrency test fails intermittently: about 5% to 37% of 500 plain runs and 55 to 97 of 100 with -race (Go 1.26.9, M1 Ultra, 2026-10-11, depending on load), and -race reports no data race, because it is a check-then-act logic race. As committed it also needs go mod tidy.

Tests pass, though one concurrency test fails intermittently (about 5% to 37% of runs, depending on load).

Third, untimed drill. TestDelayedMessageNotVisibleBeforeDelay panics: DelayedSendMessage converts its delay with int(delay.Seconds()), so 500 ms becomes 0 and the message is visible at once, and the test then indexes an empty slice. Explain both failures before prompting.

Partial: the code is real, but its tests don't pass yet (the delayed-message test panics, as of 2026-10-11).

The rate-limiter drill teaches a lesson the broker doesn’t. Go’s race detector (-race) finds two goroutines touching the same memory without a lock. A check-then-act race is different: the program checks a condition (“is there room for one more request?”) and acts on it (“count the request”) in two separate steps, and another goroutine gets in between. Each step can be perfectly safe on its own, so the detector stays silent and only reasoning about the code finds it. A fix that locks each step separately still leaves the gap; the check and the act must happen under one lock.

Do one drill with no AI at all. Classic and no-AI rounds haven’t gone away (Anthropicofficial · 10 Jul 2025), and that run tells you what you can do unaided.

Questions in this family

11 reported questions share this underlying problem. 11 have an answer card. Each one links to its own page with sources and confidence.

Sources