#include <bits/stdc++.h>
using namespace std;
const long long N1 = 1e9 + 7, N2 = 998244353;
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0), cout.tie(0);
  int t;
  cin >> t;
  while (t--) {
    int n, ans, cnt = 0;
    cin >> n;
    int k[n + 1];
    vector<vector<int>> a(n + 1);
    for (int i = 1; i <= n; i++) {
      cin >> k[i];
      for (int j = 0; j < k[i]; j++) {
        int v;
        cin >> v;
        a[v].push_back(i);
      }
    }
    priority_queue<pair<int, int>, vector<pair<int, int>>,
                   greater<pair<int, int>>>
        pq;
    for (int i = 1; i <= n; i++) {
      if (k[i] == 0) pq.push({1, i});
    }
    while (!pq.empty()) {
      cnt++;
      pair<int, int> now = pq.top();
      pq.pop();
      for (int j = 0; j < a[now.second].size(); j++) {
        k[a[now.second][j]]--;
        if (k[a[now.second][j]] == 0)
          pq.push(
              {(now.second > a[now.second][j]) + now.first, a[now.second][j]});
      }
      ans = now.first;
    }
    cout << (cnt == n ? ans : -1) << "\n";
  }
  return 0;
}
