#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 7;
int indeg[maxn];
vector<int> g[maxn];
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>>
    q;
int main() {
  int T;
  cin >> T;
  while (T--) {
    int n;
    cin >> n;
    while (!q.empty()) q.pop();
    for (int i = 1; i <= n; i++) g[i].clear();
    for (int i = 1; i <= n; i++) {
      cin >> indeg[i];
      if (!indeg[i]) q.push(make_pair(1, i));
      for (int j = 1; j <= indeg[i]; j++) {
        int k;
        cin >> k;
        g[k].push_back(i);
      }
    }
    int cnt = 0, ans = -1;
    while (!q.empty()) {
      auto tp = q.top();
      ans = tp.first;
      q.pop();
      cnt++;
      for (int i : g[tp.second]) {
        indeg[i]--;
        if (!indeg[i]) {
          if (i > tp.second)
            q.push(make_pair(ans, i));
          else
            q.push(make_pair(ans + 1, i));
        }
      }
    }
    if (cnt != n) ans = -1;
    cout << ans << "\n";
  }
}
