internal/worker: call ReInsertLatestVersion

After processing a module, call ReInsertLatestVersion.

Skip the call if this is the cooked latest version of an alternative
path. The same check is made inside ReInsertLatestVersion, but using
the module_version_states table, and the module being processed has
not yet been inserted into that table.

For golang/go#44710

Change-Id: Icd0d0c0045ccadf3e97d32c63146262a3b442577
Reviewed-on: https://go-review.googlesource.com/c/pkgsite/+/303649
Trust: Jonathan Amsterdam <jba@google.com>
Run-TryBot: Jonathan Amsterdam <jba@google.com>
Reviewed-by: Julie Qiu <julie@golang.org>
TryBot-Result: kokoro <noreply+kokoro@google.com>
diff --git a/internal/postgres/insert_module.go b/internal/postgres/insert_module.go
index add7573..e5ea8c4 100644
--- a/internal/postgres/insert_module.go
+++ b/internal/postgres/insert_module.go
@@ -648,6 +648,10 @@
 		if err != nil {
 			return err
 		}
+		if lmv == nil {
+			log.Debugf(ctx, "ReInsertLatestVersion(%q): no latest-version info", modulePath)
+			return nil
+		}
 		if lmv.GoodVersion == "" {
 			// TODO(golang/go#44710): once we are confident that
 			// latest_module_versions is accurate and up to date, we can assume
@@ -694,7 +698,7 @@
 		}
 		// We only need the readme for the module.
 		readme, err := getModuleReadme(ctx, tx, modulePath, lmv.GoodVersion)
-		if err != nil {
+		if err != nil && !errors.Is(err, derrors.NotFound) {
 			return err
 		}
 
diff --git a/internal/worker/fetch.go b/internal/worker/fetch.go
index 6b38571..5035dda 100644
--- a/internal/worker/fetch.go
+++ b/internal/worker/fetch.go
@@ -110,6 +110,21 @@
 		return ft.Status, ft.ResolvedVersion, ft.Error
 	}
 
+	// Check if the latest good version of the module is not the one in search_documents,
+	// and insert it there and in imports_unique if so.
+	// Do not bother if this is an alternative module path.
+	if ft.Status != derrors.ToStatus(derrors.AlternativeModule) || lmv == nil || lmv.CookedVersion != ft.ResolvedVersion {
+		if err := f.DB.ReInsertLatestVersion(ctx, modulePath); err != nil {
+			log.Error(ctx, err)
+			if ft.Status != http.StatusInternalServerError {
+				ft.Error = err
+				ft.Status = http.StatusInternalServerError
+			}
+			// Do not return an error here, because we want to insert into
+			// module_version_states below.
+		}
+	}
+
 	// Update the module_version_states table with the new status of
 	// module@version. This must happen last, because if it succeeds with a
 	// code < 500 but a later action fails, we will never retry the later