There is a dedicated method for it `WP_Query->set_404()`. From quick search through code it can be set in `WP_Query->parse_query()` or `WP->handle_404()` (note `WP`, not `WP_Query!).

But it can (and sometimes does) get set on query externally, for example by plugin that needs to invalidate specific resource.